@peopl-health/nexus 5.71.21 → 5.71.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/clinical/flags/escalationFlags.js +5 -0
- package/lib/clinical/services/dispatcherService.js +11 -6
- package/lib/fhir/resources/CommunicationRequest.js +1 -1
- package/lib/fhir/resources/Task.js +1 -1
- package/lib/services/escalationReviewService.js +85 -51
- package/lib/shared/dtos/DispatchedEscalation.js +1 -0
- package/package.json +1 -1
|
@@ -14,8 +14,13 @@ function feverPatientTimerLive() {
|
|
|
14
14
|
return flagOn('FEVER_PATIENT_TIMER_LIVE');
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
+
function escalationPatientTimerLive() {
|
|
18
|
+
return flagOn('ESCALATION_PATIENT_TIMER_LIVE');
|
|
19
|
+
}
|
|
20
|
+
|
|
17
21
|
module.exports = {
|
|
18
22
|
escalationAssessmentLive,
|
|
23
|
+
escalationPatientTimerLive,
|
|
19
24
|
escalationUpdateModeLive,
|
|
20
25
|
feverPatientTimerLive,
|
|
21
26
|
};
|
|
@@ -21,28 +21,31 @@ const MEDICAL_URGENCY_TO_SEVERITY = {
|
|
|
21
21
|
|
|
22
22
|
const EMERGENCY_LEVELS = new Set(['stat', 'asap']);
|
|
23
23
|
|
|
24
|
-
function pageNavigator({ severity, reason }) {
|
|
24
|
+
function pageNavigator({ severity, priority = null, reason }) {
|
|
25
25
|
return {
|
|
26
26
|
kind: 'page_navigator',
|
|
27
27
|
severity,
|
|
28
|
+
priority,
|
|
28
29
|
reason,
|
|
29
30
|
requiresAck: severity === 'critical' || severity === 'high',
|
|
30
31
|
};
|
|
31
32
|
}
|
|
32
33
|
|
|
33
|
-
function pageOncologist({ severity, reason }) {
|
|
34
|
+
function pageOncologist({ severity, priority = null, reason }) {
|
|
34
35
|
return {
|
|
35
36
|
kind: 'page_oncologist',
|
|
36
37
|
severity,
|
|
38
|
+
priority,
|
|
37
39
|
reason,
|
|
38
40
|
requiresAck: true,
|
|
39
41
|
};
|
|
40
42
|
}
|
|
41
43
|
|
|
42
|
-
function openTicket({ severity, title, reason }) {
|
|
44
|
+
function openTicket({ severity, priority = null, title, reason }) {
|
|
43
45
|
return {
|
|
44
46
|
kind: 'open_ticket',
|
|
45
47
|
severity,
|
|
48
|
+
priority,
|
|
46
49
|
title,
|
|
47
50
|
reason,
|
|
48
51
|
slaMinutes: SLA_MINUTES_BY_SEVERITY[severity] ?? null,
|
|
@@ -63,19 +66,21 @@ function planMedicalUrgent(signal) {
|
|
|
63
66
|
const level = (signal?.urgencyLevel || 'urgent').toLowerCase();
|
|
64
67
|
const indicators = Array.isArray(signal?.indicators) ? signal.indicators : [];
|
|
65
68
|
const label = signal?.category || signal?.symptom || signal?.suspectedCondition || 'medical';
|
|
69
|
+
const priority = MEDICAL_URGENCY_TO_SEVERITY[level] ? level : null;
|
|
66
70
|
if (EMERGENCY_LEVELS.has(level)) {
|
|
67
71
|
const severity = MEDICAL_URGENCY_TO_SEVERITY[level];
|
|
68
72
|
const reason = `emergency gate fired: ${indicators.join(', ') || 'unspecified'} (level=${level})`;
|
|
69
73
|
return [
|
|
70
|
-
pageOncologist({ severity, reason }),
|
|
71
|
-
pageNavigator({ severity, reason }),
|
|
72
|
-
openTicket({ severity, title: `EMERG: ${indicators.join(', ') || 'unspecified'}`, reason }),
|
|
74
|
+
pageOncologist({ severity, priority, reason }),
|
|
75
|
+
pageNavigator({ severity, priority, reason }),
|
|
76
|
+
openTicket({ severity, priority, title: `EMERG: ${indicators.join(', ') || 'unspecified'}`, reason }),
|
|
73
77
|
];
|
|
74
78
|
}
|
|
75
79
|
const severity = MEDICAL_URGENCY_TO_SEVERITY[level] || 'medium';
|
|
76
80
|
return [
|
|
77
81
|
openTicket({
|
|
78
82
|
severity,
|
|
83
|
+
priority,
|
|
79
84
|
title: `MED-${level.toUpperCase()}: ${String(label).slice(0, 60)}`,
|
|
80
85
|
reason: signal?.urgencyJustification || null,
|
|
81
86
|
}),
|
|
@@ -42,7 +42,7 @@ class CommunicationRequest {
|
|
|
42
42
|
identifier: [identifier(ESCALATION_SLUG, notify.eventId)],
|
|
43
43
|
status: NOTIFY_STATUS_TO_CR_STATUS[notify.status],
|
|
44
44
|
intent: 'plan',
|
|
45
|
-
priority: SEVERITY_TO_PRIORITY[notify.severity] || 'routine',
|
|
45
|
+
priority: notify.priority || SEVERITY_TO_PRIORITY[notify.severity] || 'routine',
|
|
46
46
|
category: [codeableConcept(notify.kind, { code: notify.kind, system: codeSystemUrl(ESCALATION_KIND_SLUG) })],
|
|
47
47
|
subject: patientReference(notify.patientId),
|
|
48
48
|
authoredOn: toIso(notify.createdAt),
|
|
@@ -32,7 +32,7 @@ class Task {
|
|
|
32
32
|
identifier: [identifier(ESCALATION_SLUG, ticket.eventId)],
|
|
33
33
|
status: TICKET_STATUS_TO_TASK_STATUS[ticket.status],
|
|
34
34
|
intent: 'order',
|
|
35
|
-
priority: SEVERITY_TO_PRIORITY[ticket.severity] || 'routine',
|
|
35
|
+
priority: ticket.priority || SEVERITY_TO_PRIORITY[ticket.severity] || 'routine',
|
|
36
36
|
code: codeableConcept(ticket.kind, { code: ticket.kind, system: codeSystemUrl(ESCALATION_KIND_SLUG) }),
|
|
37
37
|
for: patientReference(ticket.patientId),
|
|
38
38
|
authoredOn: toIso(ticket.createdAt),
|
|
@@ -32,7 +32,10 @@ const { drugsNamedIn } = require('../clinical/services/treatmentProposalService'
|
|
|
32
32
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
33
33
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
34
34
|
const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
|
|
35
|
-
const {
|
|
35
|
+
const {
|
|
36
|
+
feverPatientTimerLive: feverTimerLive,
|
|
37
|
+
escalationPatientTimerLive: escalationTimerLive,
|
|
38
|
+
} = require('../clinical/flags/escalationFlags');
|
|
36
39
|
const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
|
|
37
40
|
const { daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
|
|
38
41
|
const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
|
|
@@ -77,6 +80,9 @@ const DEFAULT_FEVER_CHEMO_WINDOW_DAYS = 42;
|
|
|
77
80
|
const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
|
|
78
81
|
const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
|
|
79
82
|
const FEVER_CATEGORY = 'febrile_neutropenia';
|
|
83
|
+
const DEFAULT_PATIENT_TIMER_MINUTES = 15;
|
|
84
|
+
const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
|
|
85
|
+
const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
|
|
80
86
|
const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
|
|
81
87
|
const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
|
|
82
88
|
const ALERT_OPERATOR = 'bot:escalationAlert';
|
|
@@ -555,7 +561,7 @@ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
|
|
|
555
561
|
const joined = await join();
|
|
556
562
|
if (joined) {
|
|
557
563
|
await scheduleDoctorAlert(joined, entry, now);
|
|
558
|
-
await
|
|
564
|
+
await armPatientTimerOnJoin(joined, entry, now);
|
|
559
565
|
if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
|
|
560
566
|
if (!DOCUMENTING_STATUSES.includes(joined.status)) {
|
|
561
567
|
logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
|
|
@@ -921,9 +927,9 @@ async function scheduleDoctorAlert(review, alarm, now) {
|
|
|
921
927
|
}
|
|
922
928
|
}
|
|
923
929
|
|
|
924
|
-
const
|
|
925
|
-
const minutes = Number(runtimeConfig.get(
|
|
926
|
-
return (Number.isFinite(minutes) && minutes > 0 ? minutes :
|
|
930
|
+
const timerMs = (key, fallback) => {
|
|
931
|
+
const minutes = Number(runtimeConfig.get(key, fallback));
|
|
932
|
+
return (Number.isFinite(minutes) && minutes > 0 ? minutes : fallback) * 60 * 1000;
|
|
927
933
|
};
|
|
928
934
|
|
|
929
935
|
const feverChemoWindowDays = () => {
|
|
@@ -946,16 +952,41 @@ async function feverTimerGap(patientCode, now) {
|
|
|
946
952
|
return days > feverChemoWindowDays() ? 'outside_chemo_window' : null;
|
|
947
953
|
}
|
|
948
954
|
|
|
949
|
-
// The timer runs from the first
|
|
950
|
-
// decision taken after it (which counts as taking the case) never moves it.
|
|
951
|
-
function
|
|
952
|
-
const
|
|
953
|
-
if (!
|
|
954
|
-
const lastMs = new Date(
|
|
955
|
+
// The timer runs from the first alert of this episode at its level, so a retried alert never restarts it
|
|
956
|
+
// and a decision taken after it (which counts as taking the case) never moves it.
|
|
957
|
+
function timerSince(review, level) {
|
|
958
|
+
const alerts = (review.doctorAlerts ?? []).filter((sent) => sent.kind === 'initial' && sent.urgencyLevel === level);
|
|
959
|
+
if (!alerts.length) return null;
|
|
960
|
+
const lastMs = new Date(alerts.at(-1).sentAt).getTime();
|
|
955
961
|
const decidedMs = Math.max(-Infinity, ...(review.decisions ?? [])
|
|
956
962
|
.map((decision) => new Date(decision.createdAt).getTime())
|
|
957
963
|
.filter((ms) => ms < lastMs));
|
|
958
|
-
return new Date(
|
|
964
|
+
return new Date(alerts.find((sent) => new Date(sent.sentAt).getTime() > decidedMs).sentAt);
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// The level whose timer is running: the highest alert sent since the last decision.
|
|
968
|
+
function timerLevelOf(review) {
|
|
969
|
+
const decidedMs = Math.max(-Infinity, ...(review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime()));
|
|
970
|
+
const alerted = (level) => (review.doctorAlerts ?? [])
|
|
971
|
+
.some((sent) => sent.kind === 'initial' && sent.urgencyLevel === level && new Date(sent.sentAt).getTime() > decidedMs);
|
|
972
|
+
return alerted('stat') ? 'stat' : 'asap';
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// An asap fever on a recent cytotoxic cycle gets the fever prompt; any other stat or asap case gets its
|
|
976
|
+
// level's prompt while that timer is live. `gap` says why the fever prompt does not apply. Without the
|
|
977
|
+
// level timers, a prompt that fires was armed as the fever prompt and fires as armed.
|
|
978
|
+
async function patientTimerOf(review, level, now, { firing = false } = {}) {
|
|
979
|
+
const levelTimer = escalationTimerLive() && Boolean(PATIENT_TIMER_PROMPT_IDS[level]);
|
|
980
|
+
const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
|
|
981
|
+
const fever = level === 'asap' && feverTimerLive() && (armedAsFever || feverAlarmsOf(review).length > 0);
|
|
982
|
+
const gap = fever && !armedAsFever ? await feverTimerGap(review.patientCode, now) : null;
|
|
983
|
+
if (fever && !gap) {
|
|
984
|
+
return { timer: { level, fever: true, promptId: FEVER_TIMER_PROMPT_ID, operator: FEVER_TIMER_OPERATOR, ms: timerMs('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES) }, gap };
|
|
985
|
+
}
|
|
986
|
+
if (levelTimer) {
|
|
987
|
+
return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: timerMs('ESCALATION_PATIENT_TIMER_MINUTES', DEFAULT_PATIENT_TIMER_MINUTES) }, gap };
|
|
988
|
+
}
|
|
989
|
+
return { timer: null, gap };
|
|
959
990
|
}
|
|
960
991
|
|
|
961
992
|
// One prompt per episode: a prompt delivered (or possibly delivered) since the episode began, or one whose
|
|
@@ -969,19 +1000,20 @@ function promptedSince(review, since, ownStart = null) {
|
|
|
969
1000
|
return delivered || (startedMs != null && startedMs >= sinceMs && startedMs !== ownStart?.getTime());
|
|
970
1001
|
}
|
|
971
1002
|
|
|
972
|
-
// An approver merely opening the review does not count: only an answer, a stat escalation
|
|
973
|
-
// thread or a staff member writing to the patient means someone took the case.
|
|
974
|
-
async function
|
|
975
|
-
// Staff acting before the
|
|
976
|
-
// take
|
|
977
|
-
const
|
|
978
|
-
const
|
|
1003
|
+
// An approver merely opening the review does not count: only an answer, a stat escalation of an asap
|
|
1004
|
+
// case, a paused thread or a staff member writing to the patient means someone took the case.
|
|
1005
|
+
async function takenReason(review, since, timer, ownStart = null) {
|
|
1006
|
+
// Staff acting before the case reached its timed level (on an earlier alarm of the same episode) did
|
|
1007
|
+
// not take it: those signals count only from the first alarm the timer is for.
|
|
1008
|
+
const atLevel = (alarm) => alarm.urgencyLevel === timer.level || appliedLevelOf(alarm) === timer.level;
|
|
1009
|
+
const first = (timer.fever ? feverAlarmsOf(review) : currentAlarms(review).filter(atLevel))[0];
|
|
1010
|
+
const from = new Date(Math.max(since.getTime(), first ? new Date(first.raisedAt).getTime() : -Infinity));
|
|
979
1011
|
const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
|
|
980
1012
|
if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) return 'review_moved_on';
|
|
981
1013
|
if (promptedSince(review, since, ownStart)) return 'already_prompted';
|
|
982
1014
|
if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
|
|
983
1015
|
const stat = (alarm) => alarm.urgencyLevel === 'stat' || alarm.appliedLevel === 'stat';
|
|
984
|
-
if (currentAlarms(review).some(stat)) return 'stat_alarm';
|
|
1016
|
+
if (timer.level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
|
|
985
1017
|
if ((review.urgencyReclassifications ?? []).some((change) => atOrAfter(change.at))) return 'reclassified';
|
|
986
1018
|
if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
|
|
987
1019
|
// A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
|
|
@@ -995,26 +1027,27 @@ async function feverTakenReason(review, since, ownStart = null) {
|
|
|
995
1027
|
return staffMessages ? 'staff_message' : null;
|
|
996
1028
|
}
|
|
997
1029
|
|
|
998
|
-
async function
|
|
1030
|
+
async function armPatientTimerOnJoin(review, alarm, now) {
|
|
999
1031
|
try {
|
|
1000
|
-
|
|
1001
|
-
if (
|
|
1002
|
-
|
|
1032
|
+
const level = appliedLevelOf(alarm);
|
|
1033
|
+
if (!escalationTimerLive() && !(feverTimerLive() && level === 'asap' && alarm.category === FEVER_CATEGORY)) return;
|
|
1034
|
+
if (!ALERTED_URGENCIES.includes(level) || alertedRankOf(review) !== URGENCY_RANK[level]) return;
|
|
1035
|
+
const since = timerSince(review, level);
|
|
1003
1036
|
if (!since || promptedSince(review, since)) return;
|
|
1004
1037
|
if (review.doctorAlertDueAt) return;
|
|
1005
|
-
const gap = await
|
|
1006
|
-
if (
|
|
1007
|
-
await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
|
|
1038
|
+
const { timer, gap } = await patientTimerOf(review, level, now);
|
|
1039
|
+
if (!timer) {
|
|
1040
|
+
if (gap) await audit(review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
|
|
1008
1041
|
return;
|
|
1009
1042
|
}
|
|
1010
1043
|
// The patient gets the full timer from when the case became eligible, not from the earlier alert.
|
|
1011
1044
|
await getEscalationReview().updateOne(
|
|
1012
1045
|
{ _id: review._id, doctorAlertDueAt: null },
|
|
1013
|
-
{ $set: { doctorAlertDueAt: new Date(now.getTime() +
|
|
1046
|
+
{ $set: { doctorAlertDueAt: new Date(now.getTime() + timer.ms), doctorAlertKind: 'patient_prompt', doctorAlertAttempts: 0 } },
|
|
1014
1047
|
BOOKKEEPING,
|
|
1015
1048
|
);
|
|
1016
1049
|
} catch (error) {
|
|
1017
|
-
logger.error('[EscalationReview] The
|
|
1050
|
+
logger.error('[EscalationReview] The patient timer was not set for a joining alarm', { escalationReviewId: String(review?._id), error: redactedError(error) });
|
|
1018
1051
|
}
|
|
1019
1052
|
}
|
|
1020
1053
|
|
|
@@ -1056,33 +1089,36 @@ async function sendPatientPrompt({ id, release, lease, now }) {
|
|
|
1056
1089
|
await audit(current, ALERT_OPERATOR, null, { action: 'patient_prompt_skipped', reason });
|
|
1057
1090
|
return null;
|
|
1058
1091
|
};
|
|
1059
|
-
if (!feverTimerLive()) return skip(review, 'flag_off');
|
|
1060
|
-
const
|
|
1061
|
-
|
|
1062
|
-
|
|
1092
|
+
if (!feverTimerLive() && !escalationTimerLive()) return skip(review, 'flag_off');
|
|
1093
|
+
const level = timerLevelOf(review);
|
|
1094
|
+
const since = timerSince(review, level);
|
|
1095
|
+
if (!since) return skip(review, `no_${level}_alert`);
|
|
1096
|
+
const { timer, gap } = await patientTimerOf(review, level, now, { firing: true });
|
|
1097
|
+
if (!timer) return skip(review, gap ?? 'flag_off');
|
|
1098
|
+
const taken = await takenReason(review, since, timer);
|
|
1063
1099
|
if (taken) return skip(review, taken);
|
|
1064
1100
|
|
|
1065
1101
|
let directive;
|
|
1066
1102
|
try {
|
|
1067
|
-
directive = String((await composePrompt({ promptId:
|
|
1103
|
+
directive = String((await composePrompt({ promptId: timer.promptId }))?.resolvedPrompt ?? '').trim();
|
|
1068
1104
|
} catch (composeError) {
|
|
1069
1105
|
// A failed read may be transient: the same slot comes back shortly, and the sweep's attempt cap
|
|
1070
1106
|
// drops it (with a ledger entry) if Airtable stays unreachable.
|
|
1071
|
-
logger.error('[EscalationReview] The
|
|
1107
|
+
logger.error('[EscalationReview] The patient prompt could not be read; trying again shortly', { escalationReviewId: String(review._id), error: redactedError(composeError) });
|
|
1072
1108
|
await release({ doctorAlertDueAt: new Date(Date.now() + ALERT_RETRY_DELAY_MS), doctorAlertKind: 'patient_prompt' });
|
|
1073
1109
|
return null;
|
|
1074
1110
|
}
|
|
1075
|
-
let error = directive ? null : `the ${
|
|
1111
|
+
let error = directive ? null : `the ${timer.promptId} prompt is empty or missing`;
|
|
1076
1112
|
let outcome = null;
|
|
1077
1113
|
let startedAt = null;
|
|
1078
1114
|
const settle = () => getEscalationReview()
|
|
1079
1115
|
.updateOne({ _id: review._id, feverPromptStartedAt: startedAt }, { $set: { feverPromptStartedAt: null } }, BOOKKEEPING);
|
|
1080
1116
|
if (error) {
|
|
1081
|
-
logger.error('[EscalationReview] The
|
|
1117
|
+
logger.error('[EscalationReview] The patient prompt has no directive; nothing was sent', { escalationReviewId: String(review._id), error });
|
|
1082
1118
|
await release();
|
|
1083
1119
|
} else {
|
|
1084
1120
|
const fresh = await loadReview(review._id);
|
|
1085
|
-
const takenNow = await
|
|
1121
|
+
const takenNow = await takenReason(fresh, since, timer);
|
|
1086
1122
|
if (takenNow) return skip(fresh, takenNow);
|
|
1087
1123
|
// The instruction runs a whole agent turn, which can outlast the sweep's lease; letting go of the
|
|
1088
1124
|
// slot first keeps a second sweep from prompting the patient twice.
|
|
@@ -1098,7 +1134,7 @@ async function sendPatientPrompt({ id, release, lease, now }) {
|
|
|
1098
1134
|
// No turn ran: the same prompt comes back shortly, under the sweep's attempt cap. A draining
|
|
1099
1135
|
// instance refused it before doing anything, so that refusal does not use up an attempt.
|
|
1100
1136
|
const rearm = async (why) => {
|
|
1101
|
-
logger.warn('[EscalationReview] The
|
|
1137
|
+
logger.warn('[EscalationReview] The patient prompt ran no turn; trying again shortly', { escalationReviewId: String(review._id), why });
|
|
1102
1138
|
const attempts = review.doctorAlertAttempts ?? 0;
|
|
1103
1139
|
await settle();
|
|
1104
1140
|
await getEscalationReview().updateOne(
|
|
@@ -1110,9 +1146,9 @@ async function sendPatientPrompt({ id, release, lease, now }) {
|
|
|
1110
1146
|
};
|
|
1111
1147
|
// The gate runs again under the chat lock, right before the turn: a patient turn queued ahead of
|
|
1112
1148
|
// this one can raise the case to stat, pause the bot or bring staff in while the prompt waits.
|
|
1113
|
-
const beforeRun = async () =>
|
|
1149
|
+
const beforeRun = async () => takenReason(await loadReview(review._id), since, timer, startedAt);
|
|
1114
1150
|
try {
|
|
1115
|
-
const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy:
|
|
1151
|
+
const result = await getMessaging().processInstruction(review.patientCode, directive, 'developer', { triggeredBy: timer.operator, beforeRun });
|
|
1116
1152
|
outcome = result?.outcome ?? null;
|
|
1117
1153
|
if (outcome === 'gated') {
|
|
1118
1154
|
await settle();
|
|
@@ -1129,10 +1165,10 @@ async function sendPatientPrompt({ id, release, lease, now }) {
|
|
|
1129
1165
|
// send happened: the same prompt comes back under the sweep's attempt cap.
|
|
1130
1166
|
return rearm(sendError instanceof DrainingError ? 'draining' : redactedError(sendError));
|
|
1131
1167
|
}
|
|
1132
|
-
if (error) logger.error('[EscalationReview] The
|
|
1168
|
+
if (error) logger.error('[EscalationReview] The patient prompt was not sent', { escalationReviewId: String(review._id), error });
|
|
1133
1169
|
}
|
|
1134
1170
|
|
|
1135
|
-
const sent = { kind: 'patient_prompt', urgencyLevel:
|
|
1171
|
+
const sent = { kind: 'patient_prompt', urgencyLevel: level, error, ...(outcome === 'threw' ? { possiblyDelivered: true } : {}), sentAt: now };
|
|
1136
1172
|
const updated = await getEscalationReview()
|
|
1137
1173
|
.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
|
|
1138
1174
|
if (startedAt) await settle();
|
|
@@ -1184,14 +1220,12 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
|
|
|
1184
1220
|
|
|
1185
1221
|
const sent = { kind, urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
|
|
1186
1222
|
const updated = await EscalationReview.findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
|
|
1187
|
-
// A
|
|
1188
|
-
//
|
|
1189
|
-
// Stat already sends the patient to the ED.
|
|
1223
|
+
// A timed case gets the patient timer even when the doctor alert failed: the doctor is retried while
|
|
1224
|
+
// there is time before the prompt and attempts left, then the patient prompt is the safety net.
|
|
1190
1225
|
const latestReview = updated ?? review;
|
|
1191
|
-
const since =
|
|
1192
|
-
const
|
|
1193
|
-
const
|
|
1194
|
-
const promptAt = feverCase && !feverGap ? since.getTime() + feverTimerMs() : null;
|
|
1226
|
+
const since = timerSince(latestReview, urgencyLevel) ?? now;
|
|
1227
|
+
const { timer, gap } = promptedSince(latestReview, since) ? {} : await patientTimerOf(latestReview, urgencyLevel, now);
|
|
1228
|
+
const promptAt = timer ? since.getTime() + timer.ms : null;
|
|
1195
1229
|
const retriesDoctor = sent.error
|
|
1196
1230
|
&& (promptAt == null || (now.getTime() + ALERT_RETRY_DELAY_MS < promptAt && (review.doctorAlertAttempts ?? 0) < MAX_ALERT_ATTEMPTS));
|
|
1197
1231
|
if (promptAt != null && !retriesDoctor) {
|
|
@@ -1218,7 +1252,7 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
|
|
|
1218
1252
|
await audit(updated ?? review, ALERT_OPERATOR, null, {
|
|
1219
1253
|
action: 'doctor_alerted', urgencyLevel, delivered: !sent.error,
|
|
1220
1254
|
});
|
|
1221
|
-
if (
|
|
1255
|
+
if (gap && !timer) await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'patient_prompt_not_armed', reason: gap });
|
|
1222
1256
|
return updated;
|
|
1223
1257
|
}
|
|
1224
1258
|
|
|
@@ -9,6 +9,7 @@ const baseFields = {
|
|
|
9
9
|
eventId: z.string(),
|
|
10
10
|
patientId: z.string(),
|
|
11
11
|
severity: z.enum(['critical', 'high', 'medium', 'low']),
|
|
12
|
+
priority: z.enum(['stat', 'asap', 'urgent', 'routine']).nullable().default(null),
|
|
12
13
|
createdAt: dateTime,
|
|
13
14
|
status: z.enum(['queued', 'sent', 'acknowledged', 'failed']).default('queued'),
|
|
14
15
|
reason: z.string().nullable().default(null),
|