@peopl-health/nexus 6.7.2 → 6.8.0-dev.21714
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/helpers/doctorReviewMessageHelper.js +7 -3
- package/lib/clinical/tools/reportMedicalEscalationTool.js +9 -17
- package/lib/models/escalationReviewModel.js +1 -0
- package/lib/services/doctorDigestService.js +52 -9
- package/lib/services/escalationReviewService.js +22 -51
- package/lib/services/reviewDeadlineService.js +0 -3
- package/lib/services/unopenedCaseService.js +9 -1
- package/lib/services/untakenAlertService.js +9 -16
- package/package.json +1 -1
|
@@ -188,6 +188,8 @@ function deadlineLabel(deadline, now, timeZone) {
|
|
|
188
188
|
return `antes del ${new Date(deadline).toLocaleDateString('es-MX', { timeZone, day: '2-digit', month: '2-digit' })} ${time}`;
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
+
const patientPromptNotice = (promptAt, timeZone) => `⏰ Si nadie lo toma, a las ${new Date(promptAt).toLocaleTimeString('es-MX', { timeZone, ...HOUR_FORMAT })} la paciente recibe los números para llamar`;
|
|
192
|
+
|
|
191
193
|
function briefSymptomOf(draft, symptom) {
|
|
192
194
|
const symptoms = Array.isArray(draft?.symptoms) ? draft.symptoms : [];
|
|
193
195
|
const wanted = oneLineOf(symptom).toLowerCase();
|
|
@@ -229,14 +231,14 @@ function briefCaseLine(identity, entry, alarmSymptom) {
|
|
|
229
231
|
}
|
|
230
232
|
|
|
231
233
|
// The four lines of the doctor's alert; each is a template variable, so none may be empty.
|
|
232
|
-
function doctorBrief({ kind, change = null, reminder = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
|
|
234
|
+
function doctorBrief({ kind, change = null, reminder = null, timer = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
|
|
233
235
|
const entry = briefSymptomOf(draft, alarmSymptom);
|
|
234
236
|
// A grave flag present asks for an assessment whoever sends the case, not only the bot's act_now.
|
|
235
237
|
const actNow = kind === 'act_now' || namedFlags(draft?.urgentPresentRedFlags).length > 0;
|
|
236
238
|
const verb = actNow ? BRIEF_VERBS.act_now : (briefDrugs(draft).length ? BRIEF_VERBS.proposal : BRIEF_VERBS.indication);
|
|
237
239
|
const mark = actNow ? '🔴' : BRIEF_MARKS[level];
|
|
238
240
|
return [
|
|
239
|
-
[reminder, [mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
|
|
241
|
+
[reminder, [mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone), timer].filter(Boolean).join(' · '),
|
|
240
242
|
briefCaseLine(identity, entry, alarmSymptom),
|
|
241
243
|
briefKeyLine(draft, entry, change === 'level' ? `Subió a ${URGENCY_LABELS[level]}` : null),
|
|
242
244
|
link,
|
|
@@ -246,7 +248,8 @@ function doctorBrief({ kind, change = null, reminder = null, level, identity, dr
|
|
|
246
248
|
const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
|
|
247
249
|
|
|
248
250
|
function doctorDigestLine({ identity, draft, alarmSymptom, deadline, now, timeZone, link }) {
|
|
249
|
-
const
|
|
251
|
+
const entry = briefSymptomOf(draft, alarmSymptom);
|
|
252
|
+
const head = [briefCaseLine(identity, entry, alarmSymptom), deadlineLabel(deadline, now, timeZone), briefKeyLine(draft, entry)].filter(Boolean).join(' · ');
|
|
250
253
|
return `${head}: ${link}`;
|
|
251
254
|
}
|
|
252
255
|
|
|
@@ -262,6 +265,7 @@ module.exports = {
|
|
|
262
265
|
doctorAlertHeadline,
|
|
263
266
|
doctorAlertOpener,
|
|
264
267
|
doctorBrief,
|
|
268
|
+
patientPromptNotice,
|
|
265
269
|
doctorDigestLine,
|
|
266
270
|
doctorDigestTitle,
|
|
267
271
|
};
|
|
@@ -8,7 +8,7 @@ const { dispatcherService } = require('../services/dispatcherService');
|
|
|
8
8
|
const { armEscalationNet } = require('../services/contingencyDispatchService');
|
|
9
9
|
const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
|
|
10
10
|
const { escalationAssessmentLive, escalationPatientTimerLive, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
|
|
11
|
-
const { ANSWER_ONLY, FEVER_CATEGORY,
|
|
11
|
+
const { ANSWER_ONLY, FEVER_CATEGORY, alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
|
|
12
12
|
const { URGENCY_RANK } = require('../../models/escalationReviewModel');
|
|
13
13
|
const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
14
14
|
const { logger } = require('../../utils/logger');
|
|
@@ -170,11 +170,10 @@ const MODE_PROPERTY = {
|
|
|
170
170
|
'description': '`new`: primer aviso de este episodio. `update`: agrega lo nuevo a la escalación que sigue abierta para este paciente, sin generar otro aviso al equipo si el nivel no sube. El nivel aplicado es el mayor entre el abierto y el que pides: uno menor no baja la escalación, queda registrado como sugerencia para el equipo. Usa `update` para sumar lo que respondió el paciente y para subir el nivel en cuanto un dato nuevo haga plausible algo más grave.',
|
|
171
171
|
};
|
|
172
172
|
|
|
173
|
-
const WHAT_CHANGED = ['new_symptom', 'higher_grade', 'new_red_flag', 'worse', 'persists_unanswered', ANSWER_ONLY
|
|
174
|
-
const HOLDABLE_CHANGES = [ANSWER_ONLY, IMPROVING];
|
|
173
|
+
const WHAT_CHANGED = ['new_symptom', 'higher_grade', 'new_red_flag', 'worse', 'persists_unanswered', ANSWER_ONLY];
|
|
175
174
|
|
|
176
175
|
const WHAT_CHANGED_PROPERTY = nullableEnum(WHAT_CHANGED);
|
|
177
|
-
WHAT_CHANGED_PROPERTY.description = 'Solo en `update`: qué trae de nuevo. `answer_only` cuando el paciente solo respondió lo que se le preguntó y su respuesta no agrega síntoma, grado, bandera roja ni empeoramiento (por ejemplo «no tengo fiebre, puedo tragar»). Si el equipo ya decidió el caso, un `answer_only` sin subir el nivel queda anotado en el caso sin volver a avisar al equipo.
|
|
176
|
+
WHAT_CHANGED_PROPERTY.description = 'Solo en `update`: qué trae de nuevo. `answer_only` cuando el paciente solo respondió lo que se le preguntó y su respuesta no agrega síntoma, grado, bandera roja ni empeoramiento (por ejemplo «no tengo fiebre, puedo tragar»). Si el equipo ya decidió el caso, un `answer_only` sin subir el nivel queda anotado en el caso sin volver a avisar al equipo. Ante cualquier duda usa el valor que corresponda o `null`: nunca `answer_only` si algo empeoró o apareció algo nuevo.';
|
|
178
177
|
|
|
179
178
|
const FEVER_RULED_OUT_PROPERTY = nullable({
|
|
180
179
|
'type': 'boolean',
|
|
@@ -186,12 +185,6 @@ const FEVER_READING_PROPERTY = nullable({
|
|
|
186
185
|
'description': 'Solo en `update`; llénalo siempre. La temperatura más reciente en °C que el paciente midió con termómetro y escribió como número en esta conversación (por ejemplo 36.4). `null` si no dio un número: «no tengo fiebre» o «me siento bien» sin lectura es `null`. Nunca la deduzcas ni la tomes de otro episodio.',
|
|
187
186
|
});
|
|
188
187
|
|
|
189
|
-
const heldReceiptOf = (review) => {
|
|
190
|
-
if (review.closedAt) return { means: 'Recorded on the case the team already closed; no new case was opened and the team was not paged. Tell the patient you noted it.', followUp: 'No check-in was armed: invite the patient to write again if it changes or worries them.' };
|
|
191
|
-
if (PRE_DECISION_STATUSES.includes(review.status)) return { means: 'Added to the case that is still with the team; the team was not paged again. Do not tell the patient the team already reviewed it.', followUp: 'The case keeps the check-in it already had; no new one was armed.' };
|
|
192
|
-
return { means: 'Recorded on the case the team already decided; the team was not paged again. Tell the patient you noted it and keep to the team\'s indication.', followUp: 'The team\'s indication for this case stands; no new check-in was armed.' };
|
|
193
|
-
};
|
|
194
|
-
|
|
195
188
|
const MODE_DESCRIPTION = '\n\n**mode:** `new` abre un aviso; `update` actualiza la escalación abierta y nunca baja su nivel. Lo que el paciente responde después de escalar va con `update`. En cada `update` llena siempre `what_changed`, `fever_reading_c` y `fever_ruled_out`: si dejas uno vacío, la alarma se trata como dato nuevo y como fiebre abierta, y el equipo vuelve a recibir el aviso. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
|
|
196
189
|
|
|
197
190
|
const CLINICAL_ASSESSMENT_PROPERTY = nullable({
|
|
@@ -340,7 +333,7 @@ async function handler(args, context = {}) {
|
|
|
340
333
|
const category = feverRuledOut && listedCategory === FEVER_CATEGORY ? 'treatment_concern' : listedCategory;
|
|
341
334
|
const categoryCoerced = rawCategory !== null && listedCategory === null;
|
|
342
335
|
const claimedChange = updateMode && WHAT_CHANGED.includes(args?.what_changed) ? args.what_changed : null;
|
|
343
|
-
const whatChanged =
|
|
336
|
+
const whatChanged = claimedChange === ANSWER_ONLY && feverReading !== null && !normalReading ? null : claimedChange;
|
|
344
337
|
const clinicalAssessment = escalationAssessmentLive() && isPlainObject(details.clinical_assessment) ? details.clinical_assessment : null;
|
|
345
338
|
const strictlyParsed = typeof rawDetails === 'string' && isPlainObject(safeParse(rawDetails, null));
|
|
346
339
|
const detailsArg = typeof rawDetails === 'string'
|
|
@@ -381,7 +374,7 @@ async function handler(args, context = {}) {
|
|
|
381
374
|
},
|
|
382
375
|
})
|
|
383
376
|
: null;
|
|
384
|
-
const heldInFollowUp =
|
|
377
|
+
const heldInFollowUp = whatChanged === ANSWER_ONLY && Boolean((review?.alarms ?? []).find((raised) => raised.alarmId === alarmId)?.isHeldInFollowUp);
|
|
385
378
|
const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
|
|
386
379
|
const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
|
|
387
380
|
const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
|
|
@@ -492,20 +485,19 @@ async function handler(args, context = {}) {
|
|
|
492
485
|
netReason = 'patient_context_missing';
|
|
493
486
|
}
|
|
494
487
|
|
|
495
|
-
const heldReceipt = heldInFollowUp ? heldReceiptOf(review) : null;
|
|
496
488
|
const data = {
|
|
497
489
|
urgency_level: urgencyLevel,
|
|
498
490
|
queued_for_team: queued,
|
|
499
491
|
safety_net_armed: netArmed,
|
|
500
492
|
safety_net_reason: netReason,
|
|
501
493
|
team_has_reviewed: false,
|
|
502
|
-
means:
|
|
503
|
-
?
|
|
494
|
+
means: heldInFollowUp
|
|
495
|
+
? 'Recorded on the case the team already decided; the team was not paged again. Tell the patient you noted it and keep to the team\'s indication.'
|
|
504
496
|
: queued
|
|
505
497
|
? 'The escalation is QUEUED for the care team. This is not confirmation that anyone has read or acted on it, and no reply has arrived. Do not tell the patient the team already reviewed it, and do not treat the topic as closed on the strength of this ack.'
|
|
506
498
|
: 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
|
|
507
|
-
follow_up:
|
|
508
|
-
...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor:
|
|
499
|
+
follow_up: heldInFollowUp ? 'The team\'s indication for this case stands; no new check-in was armed.' : followUpNote(netArmed, netReason),
|
|
500
|
+
...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
|
|
509
501
|
...(heldInFollowUp ? { held_in_follow_up: true } : {}),
|
|
510
502
|
...(category !== listedCategory ? { category_recorded_as: category } : {}),
|
|
511
503
|
...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
|
|
@@ -230,6 +230,7 @@ const doctorHandoffSchema = new mongoose.Schema({
|
|
|
230
230
|
messageId: { type: String, default: null },
|
|
231
231
|
message: { type: String, default: null },
|
|
232
232
|
alarmCount: { type: Number, default: null },
|
|
233
|
+
promptAt: { type: Date, default: null },
|
|
233
234
|
sentBy: { type: String, required: true },
|
|
234
235
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
235
236
|
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const moment = require('moment-timezone');
|
|
2
|
+
|
|
1
3
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
4
|
const { oneLineOf } = require('../utils/coercionUtils');
|
|
3
5
|
const { logger } = require('../utils/logger');
|
|
@@ -12,11 +14,16 @@ const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpen
|
|
|
12
14
|
const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, doctorAlertMessage, doctorLink, notifiedApprover, teamAlertIdentity } = require('./escalationReviewService');
|
|
13
15
|
|
|
14
16
|
const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
|
|
15
|
-
// Meta
|
|
17
|
+
// Meta classed this template as MARKETING, which WhatsApp may refuse to deliver.
|
|
16
18
|
const DIGEST_BRIEF_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_BRIEF_CONTENT_SID';
|
|
17
19
|
const ALERT_IDENTIFIED_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID';
|
|
20
|
+
const DIGEST_TIMES_KEY = 'ESCALATION_DOCTOR_DIGEST_TIMES';
|
|
21
|
+
const TIME_OF_DAY = /^(\d{1,2}):(\d{2})$/;
|
|
22
|
+
const DAY_MINUTES = 24 * 60;
|
|
18
23
|
const DEFAULT_WINDOW_MINUTES = 60;
|
|
19
24
|
const DEFAULT_LEAD_MINUTES = 120;
|
|
25
|
+
// With set times, a case whose deadline comes before the next one goes this long before its deadline instead.
|
|
26
|
+
const SLOT_LEAD_MS = 30 * 60 * 1000;
|
|
20
27
|
const MAX_CASES_PER_MESSAGE = 5;
|
|
21
28
|
// The template's fixed text plus the cases stay under WhatsApp's 1024 characters.
|
|
22
29
|
const MAX_LINES_LENGTH = 800;
|
|
@@ -41,17 +48,49 @@ async function digestRecipient() {
|
|
|
41
48
|
return PATIENT_CODE.test(code) ? code : null;
|
|
42
49
|
}
|
|
43
50
|
|
|
44
|
-
// The time a case queued now reaches the doctor at the latest, in the team's clock, for the group notice.
|
|
45
51
|
function digestTimeOf(review, now) {
|
|
46
52
|
const policy = responseDeadlinePolicy();
|
|
47
|
-
const
|
|
48
|
-
|
|
53
|
+
const { timeZone } = policy.teamHours;
|
|
54
|
+
const dueAt = moment.tz(Math.max(now.getTime(), digestDueAt([{ ...review, digestQueuedAt: now }], policy).getTime()), timeZone);
|
|
55
|
+
const days = dueAt.clone().startOf('day').diff(moment.tz(now, timeZone).startOf('day'), 'days');
|
|
56
|
+
return [days === 1 ? 'mañana' : days > 1 && `el ${dueAt.format('DD/MM')}`, dueAt.format('HH:mm')].filter(Boolean).join(' ');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
let loggedBadTimes = null;
|
|
60
|
+
|
|
61
|
+
function digestTimes() {
|
|
62
|
+
const raw = runtimeConfig.get(DIGEST_TIMES_KEY, '').trim();
|
|
63
|
+
if (!raw) return [];
|
|
64
|
+
const matches = raw.split(',').map((value) => TIME_OF_DAY.exec(value.trim()));
|
|
65
|
+
const minutes = matches.map((match) => match && Number(match[1]) * 60 + Number(match[2]));
|
|
66
|
+
// One mistyped time would silently move cases to the next day, so the whole setting is ignored instead.
|
|
67
|
+
if (matches.some((match, index) => !match || Number(match[2]) >= 60 || minutes[index] >= DAY_MINUTES)) {
|
|
68
|
+
if (loggedBadTimes !== raw) logger.error('[DoctorDigest] ESCALATION_DOCTOR_DIGEST_TIMES is not a list of HH:MM times; the rolling window is used');
|
|
69
|
+
loggedBadTimes = raw;
|
|
70
|
+
return [];
|
|
71
|
+
}
|
|
72
|
+
return minutes.sort((a, b) => a - b);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function nextDigestTime(from, times, timeZone) {
|
|
76
|
+
const day = moment.tz(from, timeZone).startOf('day');
|
|
77
|
+
const at = times.map((minutes) => day.clone().add(minutes, 'minutes')).find((slot) => !slot.isBefore(from))
|
|
78
|
+
?? day.clone().add(1, 'day').add(times[0], 'minutes');
|
|
79
|
+
return at.toDate();
|
|
49
80
|
}
|
|
50
81
|
|
|
51
|
-
//
|
|
82
|
+
// At the next set time unless a deadline comes first, else after the window or the lead before a deadline; at night, when the team day opens.
|
|
52
83
|
function digestDueAt(reviews, policy) {
|
|
53
|
-
const
|
|
84
|
+
const slots = digestTimes();
|
|
54
85
|
const lead = minutesOf('ESCALATION_DOCTOR_DIGEST_LEAD_MINUTES', DEFAULT_LEAD_MINUTES) * 60000;
|
|
86
|
+
if (slots.length) {
|
|
87
|
+
const oldest = new Date(Math.min(...reviews.map((review) => new Date(review.digestQueuedAt).getTime())));
|
|
88
|
+
// A case raised above urgent keeps the rolling lead, as its deadline runs at night too.
|
|
89
|
+
const beforeDeadlines = reviews.map((review) => [responseDeadlineOf(review, policy)?.dueAt, effectiveUrgencyOf(review)?.urgency === 'urgent' ? SLOT_LEAD_MS : lead])
|
|
90
|
+
.filter(([deadline]) => deadline).map(([deadline, before]) => deadline.getTime() - before);
|
|
91
|
+
return teamOpenAt(new Date(Math.min(nextDigestTime(oldest, slots, policy.teamHours.timeZone).getTime(), ...beforeDeadlines)), policy);
|
|
92
|
+
}
|
|
93
|
+
const window = minutesOf('ESCALATION_DOCTOR_DIGEST_WINDOW_MINUTES', DEFAULT_WINDOW_MINUTES) * 60000;
|
|
55
94
|
const times = reviews.flatMap((review) => {
|
|
56
95
|
const deadline = responseDeadlineOf(review, policy)?.dueAt;
|
|
57
96
|
return [new Date(review.digestQueuedAt).getTime() + window, ...(deadline ? [deadline.getTime() - lead] : [])];
|
|
@@ -62,7 +101,7 @@ function digestDueAt(reviews, policy) {
|
|
|
62
101
|
const briefStyle = () => runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
|
|
63
102
|
|
|
64
103
|
// Like the direct handoff, a case without drafted symptoms needs the full alert's template.
|
|
65
|
-
const perCaseBrief = (inWindow) => !inWindow && !runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY)
|
|
104
|
+
const perCaseBrief = (inWindow) => !inWindow && !digestAtSetTimes() && !runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY)
|
|
66
105
|
&& Boolean(runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY) && runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY));
|
|
67
106
|
|
|
68
107
|
function digestLines(cases, now, policy, perCase) {
|
|
@@ -105,7 +144,9 @@ function chunksOf(entries) {
|
|
|
105
144
|
|
|
106
145
|
async function sendDigest(code, entries, inWindow, perCase) {
|
|
107
146
|
const lines = entries.map(({ line }) => line);
|
|
108
|
-
|
|
147
|
+
// The old digest template's first variable is the case count.
|
|
148
|
+
const phrased = briefStyle() && (inWindow || runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
|
|
149
|
+
const title = !perCase && (phrased ? doctorDigestTitle(entries.length) : String(entries.length));
|
|
109
150
|
const outgoing = perCase
|
|
110
151
|
? { code, contentSid: lines[0].contentSid || runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY), variables: lines[0].template, triggeredBy: OPERATOR }
|
|
111
152
|
: inWindow
|
|
@@ -124,6 +165,8 @@ const audit = (review, delivered) => logPatientChange({
|
|
|
124
165
|
changes: { escalationReviewId: String(review._id), action: delivered ? 'doctor_digest_sent' : 'doctor_digest_failed' },
|
|
125
166
|
}).catch((error) => logger.error('[DoctorDigest] The audit was not written', { escalationReviewId: String(review._id), error: redacted(error) }));
|
|
126
167
|
|
|
168
|
+
const digestAtSetTimes = () => digestTimes().length > 0;
|
|
169
|
+
|
|
127
170
|
// A case whose doctor's phone already rang after it was queued (a grave flag on an update) is not repeated.
|
|
128
171
|
const digestStillDue = (review) => Boolean(review.digestQueuedAt) && !review.digestSentAt && !(review.doctorHandoffs ?? [])
|
|
129
172
|
.some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime());
|
|
@@ -186,4 +229,4 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
|
|
|
186
229
|
return sent;
|
|
187
230
|
}
|
|
188
231
|
|
|
189
|
-
module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
|
|
232
|
+
module.exports = { MAX_CASES_PER_MESSAGE, digestAtSetTimes, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
|
|
@@ -31,7 +31,7 @@ const { ensureWhatsAppFormat, whatsAppCodeFromPhone } = require('../helpers/twil
|
|
|
31
31
|
const { DrainingError } = require('../core/BatchingManager');
|
|
32
32
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
33
33
|
const { conversationLink, readGroupMessageId, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
34
|
-
const { doctorAlertHeadline, doctorAlertOpener, doctorBrief, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
34
|
+
const { doctorAlertHeadline, doctorAlertOpener, doctorBrief, patientPromptNotice, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
35
35
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
36
36
|
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
37
37
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
@@ -106,8 +106,6 @@ const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
|
|
|
106
106
|
const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
|
|
107
107
|
const FEVER_CATEGORY = 'febrile_neutropenia';
|
|
108
108
|
const ANSWER_ONLY = 'answer_only';
|
|
109
|
-
const IMPROVING = 'improving';
|
|
110
|
-
const CLOSED_HOLD_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
111
109
|
const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
|
|
112
110
|
const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
|
|
113
111
|
const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
|
|
@@ -630,47 +628,14 @@ async function closeStaleInterruption(EscalationReview, patientCode, now) {
|
|
|
630
628
|
}
|
|
631
629
|
}
|
|
632
630
|
|
|
633
|
-
const notAboveCase = (review, alarm, alarmsOf = (of) => of.alarms ?? []) => {
|
|
634
|
-
const decided = effectiveUrgencyOf({ ...review, alarms: alarmsOf(review).filter((entry) => entry.alarmId !== alarm.alarmId) })?.urgency;
|
|
635
|
-
return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
|
|
636
|
-
};
|
|
637
|
-
const isImprovingUpdate = (alarm, mode) => mode === 'update' && alarm.whatChanged === IMPROVING;
|
|
638
|
-
const isQuietImprovement = (review, alarm) => alarm.category !== FEVER_CATEGORY
|
|
639
|
-
&& !(review.alarms ?? []).some(isLiveFeverOf(review))
|
|
640
|
-
&& !((review.drafts ?? []).at(-1)?.urgentPresentRedFlags?.length);
|
|
641
|
-
const decidedEpisodeOf = (review) => {
|
|
642
|
-
const decidedAt = (review.decisions ?? []).map((decision) => new Date(decision.createdAt).getTime());
|
|
643
|
-
const from = decidedAt.length > 1 ? decidedAt.at(-2) : -Infinity;
|
|
644
|
-
return (review.alarms ?? []).filter((alarm) => new Date(alarm.raisedAt).getTime() > from && new Date(alarm.raisedAt).getTime() <= decidedAt.at(-1));
|
|
645
|
-
};
|
|
646
|
-
|
|
647
631
|
function shouldHoldInFollowUp(review, alarm, mode) {
|
|
648
632
|
if (mode !== 'update') return false;
|
|
649
|
-
if (alarm.whatChanged === IMPROVING) return isQuietImprovement(review, alarm) && notAboveCase(review, alarm);
|
|
650
633
|
if (ALERTED_URGENCIES.includes(alarm.urgencyLevel) && (alarm.whatChanged !== ANSWER_ONLY || alarm.category === FEVER_CATEGORY)) return false;
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
const shouldHoldOnOpenCase = (review, alarm, mode) => isImprovingUpdate(alarm, mode) && isQuietImprovement(review, alarm) && notAboveCase(review, alarm, currentAlarms);
|
|
655
|
-
|
|
656
|
-
async function noteOnRecentlyClosed(EscalationReview, patientCode, alarm, mode, now) {
|
|
657
|
-
if (!isImprovingUpdate(alarm, mode)) return null;
|
|
658
|
-
try {
|
|
659
|
-
const closed = await EscalationReview.findOne({ patientCode, closedAt: { $gte: new Date(now.getTime() - CLOSED_HOLD_WINDOW_MS) } }).sort({ closedAt: -1 }).lean();
|
|
660
|
-
const undecided = !closed || closed.interruptionResolution || currentAlarms(closed).some((entry) => !entry.isHeldInFollowUp);
|
|
661
|
-
if (undecided || !isQuietImprovement(closed, alarm) || !notAboveCase(closed, alarm, decidedEpisodeOf)) return null;
|
|
662
|
-
const noted = await EscalationReview
|
|
663
|
-
.findOneAndUpdate({ _id: closed._id }, { $push: { alarms: { ...alarm, isHeldInFollowUp: true } }, $set: { updatedSinceSeen: true } }, { new: true })
|
|
664
|
-
.lean();
|
|
665
|
-
if (noted) await audit(noted, AGENT_OPERATOR, null, { action: 'followup_result', result: 'update_held_closed', statusFrom: closed.status });
|
|
666
|
-
return noted;
|
|
667
|
-
} catch (error) {
|
|
668
|
-
logger.warn('[EscalationReview] The improvement was not noted on the closed case; opening a review', { error: redactedError(error) });
|
|
669
|
-
return null;
|
|
670
|
-
}
|
|
634
|
+
const decided = effectiveUrgencyOf({ ...review, alarms: (review.alarms ?? []).filter((entry) => entry.alarmId !== alarm.alarmId) })?.urgency;
|
|
635
|
+
return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
|
|
671
636
|
}
|
|
672
637
|
|
|
673
|
-
async function holdInFollowUp(review, alarm
|
|
638
|
+
async function holdInFollowUp(review, alarm) {
|
|
674
639
|
const held = await getEscalationReview()
|
|
675
640
|
.findOneAndUpdate(
|
|
676
641
|
{ _id: review._id, status: review.status, 'alarms.alarmId': alarm.alarmId },
|
|
@@ -679,7 +644,7 @@ async function holdInFollowUp(review, alarm, result = 'update_held') {
|
|
|
679
644
|
)
|
|
680
645
|
.lean();
|
|
681
646
|
if (!held) return review;
|
|
682
|
-
await audit(held, AGENT_OPERATOR, null, { action: 'followup_result', result, statusFrom: review.status });
|
|
647
|
+
await audit(held, AGENT_OPERATOR, null, { action: 'followup_result', result: 'update_held', statusFrom: review.status });
|
|
683
648
|
return held;
|
|
684
649
|
}
|
|
685
650
|
|
|
@@ -701,10 +666,6 @@ async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date
|
|
|
701
666
|
const held = await holdInFollowUp(joined, entry);
|
|
702
667
|
if (held !== joined) return held;
|
|
703
668
|
}
|
|
704
|
-
if (PRE_DECISION_STATUSES.includes(joined.status) && shouldHoldOnOpenCase(joined, entry, mode)) {
|
|
705
|
-
const held = await holdInFollowUp(joined, entry, 'update_held_open');
|
|
706
|
-
if (held !== joined) return held;
|
|
707
|
-
}
|
|
708
669
|
await scheduleDoctorAlert(joined, entry, now);
|
|
709
670
|
await armPatientTimerOnJoin(joined, entry, now);
|
|
710
671
|
if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
|
|
@@ -715,8 +676,6 @@ async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date
|
|
|
715
676
|
}
|
|
716
677
|
return joined;
|
|
717
678
|
}
|
|
718
|
-
const noted = await noteOnRecentlyClosed(EscalationReview, patientCode, entry, mode, now);
|
|
719
|
-
if (noted) return noted;
|
|
720
679
|
try {
|
|
721
680
|
const created = (await EscalationReview.create({
|
|
722
681
|
patientCode,
|
|
@@ -1335,6 +1294,13 @@ const currentAlarms = (review) => {
|
|
|
1335
1294
|
return decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
|
|
1336
1295
|
};
|
|
1337
1296
|
|
|
1297
|
+
const patientTimerLiveFor = (review) => (currentAlarms(review).some(isLiveFeverOf(review)) ? feverTimerLive() : escalationTimerLive());
|
|
1298
|
+
|
|
1299
|
+
// While a send holds the slot (attempts above 0, or a lease) its due time is not the prompt's, so only an untouched slot gives the time.
|
|
1300
|
+
const armedPromptAt = (review) => (review.doctorAlertKind === 'patient_prompt' && !review.doctorAlertAttempts ? review.doctorAlertDueAt ?? null : null);
|
|
1301
|
+
|
|
1302
|
+
const patientPromptAt = (review) => (patientTimerLiveFor(review) ? armedPromptAt(review) : null);
|
|
1303
|
+
|
|
1338
1304
|
const topUrgencyOf = (review) => {
|
|
1339
1305
|
const open = currentAlarms(review);
|
|
1340
1306
|
return (open.length ? open : review.alarms ?? [])
|
|
@@ -2025,7 +1991,7 @@ async function notifiedApprover() {
|
|
|
2025
1991
|
throw httpError(409, `More than one physician approves escalation reviews; name one of: ${approvers.map((approver) => approver.email).join(', ')}, or tick aprobador_principal on exactly one`);
|
|
2026
1992
|
}
|
|
2027
1993
|
|
|
2028
|
-
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, now = new Date() }) {
|
|
1994
|
+
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, timer = null, now = new Date() }) {
|
|
2029
1995
|
const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
|
|
2030
1996
|
// A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
|
|
2031
1997
|
if (briefSid && draft.symptoms?.length) {
|
|
@@ -2035,6 +2001,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
2035
2001
|
kind,
|
|
2036
2002
|
change,
|
|
2037
2003
|
reminder,
|
|
2004
|
+
timer,
|
|
2038
2005
|
level: level ?? lead?.urgency,
|
|
2039
2006
|
identity,
|
|
2040
2007
|
draft,
|
|
@@ -2046,7 +2013,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
2046
2013
|
});
|
|
2047
2014
|
return { body: lines.join('\n'), template: Object.fromEntries(lines.map((line, index) => [index + 1, line])), contentSid: briefSid };
|
|
2048
2015
|
}
|
|
2049
|
-
const opener = [reminder, note].filter(Boolean).join(' · ') || null;
|
|
2016
|
+
const opener = [reminder, note, timer].filter(Boolean).join(' · ') || null;
|
|
2050
2017
|
const headline = kind && doctorAlertHeadline({ review, kind, note: opener, level, symptom });
|
|
2051
2018
|
const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
|
|
2052
2019
|
return {
|
|
@@ -2097,7 +2064,10 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
2097
2064
|
const identity = await readDoctorIdentity(review);
|
|
2098
2065
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
2099
2066
|
const link = doctorLink(review);
|
|
2100
|
-
const
|
|
2067
|
+
const armedAt = mode === 'sent_whatsapp' ? patientPromptAt(review) : null;
|
|
2068
|
+
const promptAt = armedAt && new Date(armedAt) > new Date() ? new Date(armedAt) : null;
|
|
2069
|
+
const timer = promptAt && patientPromptNotice(promptAt, responseDeadlinePolicy().teamHours.timeZone);
|
|
2070
|
+
const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, timer });
|
|
2101
2071
|
|
|
2102
2072
|
const patientCaseRecordIds = await reviewCaseIds(review);
|
|
2103
2073
|
|
|
@@ -2116,7 +2086,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
2116
2086
|
if (approver) delivery = { physicianEmail: approver.email, ...(rings ? await sendDoctorAlert({ message, approver, operator }) : {}) };
|
|
2117
2087
|
const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (rings ? message.body : null);
|
|
2118
2088
|
const handoff = {
|
|
2119
|
-
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, sentBy: operator } },
|
|
2089
|
+
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, ...(sent && promptAt && { promptAt }), sentBy: operator } },
|
|
2120
2090
|
$addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
|
|
2121
2091
|
$unset: { identityBlock: '' },
|
|
2122
2092
|
};
|
|
@@ -2783,7 +2753,6 @@ module.exports = {
|
|
|
2783
2753
|
DRAFT_OPERATOR,
|
|
2784
2754
|
MAX_DOCTOR_UPDATES,
|
|
2785
2755
|
ANSWER_ONLY,
|
|
2786
|
-
IMPROVING,
|
|
2787
2756
|
FEVER_CATEGORY,
|
|
2788
2757
|
appliedLevelOf,
|
|
2789
2758
|
isLiveFeverOf,
|
|
@@ -2797,6 +2766,8 @@ module.exports = {
|
|
|
2797
2766
|
caseTakenReason,
|
|
2798
2767
|
promptedSince,
|
|
2799
2768
|
currentAlarms,
|
|
2769
|
+
armedPromptAt,
|
|
2770
|
+
patientPromptAt,
|
|
2800
2771
|
DOCTOR_BRIEF_TEMPLATE_KEY,
|
|
2801
2772
|
doctorAlertMessage,
|
|
2802
2773
|
doctorLink,
|
|
@@ -10,7 +10,6 @@ const TEAM_TIMEZONE = 'America/Mexico_City';
|
|
|
10
10
|
const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5, 6, 7], startHour: 9, endHour: 22 };
|
|
11
11
|
const UNTAKEN_STAGES = { stat: ['early', 'deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
|
|
12
12
|
const PATIENT_PROMPT_LEAD_MINUTES = 5;
|
|
13
|
-
const URGENT_REMINDER_LEAD_MINUTES = 60;
|
|
14
13
|
const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20, fever: 15 };
|
|
15
14
|
const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES', fever: 'FEVER_PATIENT_TIMER_MINUTES' };
|
|
16
15
|
const DEFAULT_UNTAKEN_EARLY_MINUTES = 15;
|
|
@@ -101,8 +100,6 @@ function untakenStagesOf(level, since, policy, { fever = false } = {}) {
|
|
|
101
100
|
|
|
102
101
|
function doctorReminderAt(level, since, policy, promptAt = null) {
|
|
103
102
|
if (promptAt) return new Date(timeOf(promptAt) - PATIENT_PROMPT_LEAD_MINUTES * 60 * 1000);
|
|
104
|
-
// addWorkingMinutes can land on the closing minute itself, which the team counts as closed.
|
|
105
|
-
if (level === 'urgent') return teamOpenAt(dueAtFor(since, level, policy, policy.responseMinutes.urgent - URGENT_REMINDER_LEAD_MINUTES), policy);
|
|
106
103
|
return untakenStagesOf(level, since, policy).find((stage) => stage.stage === 'early')?.dueAt ?? null;
|
|
107
104
|
}
|
|
108
105
|
|
|
@@ -91,10 +91,18 @@ async function doctorPingedRecently(review, physicianEmail, now) {
|
|
|
91
91
|
const remindedSince = (review, ringAt) => (review.doctorAlerts ?? []).some((sent) => sent.kind === 'reminder'
|
|
92
92
|
&& (sent.transport || sent.possiblyDelivered) && timeOf(sent.sentAt) >= ringAt.getTime());
|
|
93
93
|
|
|
94
|
+
const digestRemindedFor = async (review, ringAt, physicianEmail) => timeOf(review.digestSentAt) === ringAt.getTime()
|
|
95
|
+
&& (await getEscalationReview().countDocuments({
|
|
96
|
+
_id: { $ne: review._id },
|
|
97
|
+
digestSentAt: review.digestSentAt,
|
|
98
|
+
unopenedAlerts: { $elemMatch: { stage: 'doctor', ringAt, physicianEmail, skippedReason: null, error: null, transport: { $ne: null } } },
|
|
99
|
+
})) > 0;
|
|
100
|
+
|
|
94
101
|
async function remindDoctor(review, { ringAt, dueAt, physicianEmail, level }, now) {
|
|
95
102
|
const taken = await caseTakenReason(review, ringAt, level);
|
|
96
103
|
const testPatient = !taken && (await teamAlertIdentity(review)).identity.testPatient;
|
|
97
|
-
const skippedReason = taken || (testPatient ? 'test_patient' : null) || (remindedSince(review, ringAt) ? 'already_reminded' : null)
|
|
104
|
+
const skippedReason = taken || (testPatient ? 'test_patient' : null) || (remindedSince(review, ringAt) ? 'already_reminded' : null)
|
|
105
|
+
|| (await digestRemindedFor(review, ringAt, physicianEmail) ? 'digest_reminded' : null);
|
|
98
106
|
if (!skippedReason && await doctorPingedRecently(review, physicianEmail, now)) return false;
|
|
99
107
|
if (!await claim(review, { stage: 'doctor', ringAt, dueAt, physicianEmail, skippedReason, sentAt: now })) return false;
|
|
100
108
|
if (skippedReason) return false;
|
|
@@ -5,14 +5,14 @@ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
|
5
5
|
const { withTimeout } = require('../utils/timeoutUtils');
|
|
6
6
|
const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
|
|
7
7
|
const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
|
|
8
|
-
const { escalationAutoHandoffLive,
|
|
8
|
+
const { escalationAutoHandoffLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
|
|
9
9
|
|
|
10
10
|
const { logPatientChange } = require('./patientService');
|
|
11
11
|
const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
|
|
12
|
-
const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, PRE_DECISION_STATUSES, appliedLevelOf, isLiveFeverOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
|
|
12
|
+
const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, PRE_DECISION_STATUSES, appliedLevelOf, armedPromptAt, isLiveFeverOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, patientPromptAt, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
|
|
13
13
|
const { settleCharacterization } = require('./characterizationOutcomeService');
|
|
14
14
|
const { sendTeamAlert } = require('./teamAlertService');
|
|
15
|
-
const { digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
|
|
15
|
+
const { digestAtSetTimes, digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
|
|
16
16
|
|
|
17
17
|
const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
|
|
18
18
|
const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
@@ -37,7 +37,7 @@ const REMINDER_RETRY_MS = 3 * 60 * 1000;
|
|
|
37
37
|
const REMINDER_SEND_TIMEOUT_MS = 60 * 1000;
|
|
38
38
|
const MAX_REMINDER_ATTEMPTS = 3;
|
|
39
39
|
// Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
|
|
40
|
-
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, 'doctorHandoffs.mode': 1, 'doctorHandoffs.physicianEmail': 1, feverPromptStartedAt: 1, digestQueuedAt: 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1, digestSentAt: 1,
|
|
40
|
+
const UNTAKEN_PROJECTION = { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, autoHandoffFailedAt: 1, autoHandoffAttempts: 1, 'doctorHandoffs.createdAt': 1, 'doctorHandoffs.sentBy': 1, 'doctorHandoffs.transport': 1, 'doctorHandoffs.draftNumber': 1, 'doctorHandoffs.mode': 1, 'doctorHandoffs.physicianEmail': 1, 'doctorHandoffs.promptAt': 1, feverPromptStartedAt: 1, digestQueuedAt: 1, quietReminders: 1, blockingAsks: 1, inTurnAsks: 1, 'doctorAlerts.kind': 1, 'doctorAlerts.sentAt': 1, 'doctorAlerts.error': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.urgencyLevel': 1, draftDueAt: 1, doctorAlertKind: 1, doctorAlertDueAt: 1, doctorAlertAttempts: 1, 'updates.at': 1, digestSentAt: 1,
|
|
41
41
|
'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
|
|
42
42
|
'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
|
|
43
43
|
};
|
|
@@ -110,16 +110,6 @@ function pendingQuestionOf(review, clock) {
|
|
|
110
110
|
return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
|
|
111
111
|
}
|
|
112
112
|
|
|
113
|
-
function patientTimerLiveFor(review) {
|
|
114
|
-
const fever = currentAlarms(review).some(isLiveFeverOf(review));
|
|
115
|
-
return fever ? feverPatientTimerLive() : escalationPatientTimerLive();
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// While a send holds the slot (attempts above 0, or a lease) its due time is not the prompt's, so only an untouched slot gives the time.
|
|
119
|
-
const armedPromptAt = (review) => (review.doctorAlertKind === 'patient_prompt' && !review.doctorAlertAttempts ? review.doctorAlertDueAt ?? null : null);
|
|
120
|
-
|
|
121
|
-
const patientPromptAt = (review) => (patientTimerLiveFor(review) ? armedPromptAt(review) : null);
|
|
122
|
-
|
|
123
113
|
function patientPromptNote(review, stage, now) {
|
|
124
114
|
const promptAt = stage.stage === 'early' ? patientPromptAt(review) : null;
|
|
125
115
|
if (!promptAt) return null;
|
|
@@ -192,7 +182,9 @@ const doctorRangSince = (review, since) => (review.doctorHandoffs ?? [])
|
|
|
192
182
|
async function alertIfUntaken(review, clock, stage, now, policy) {
|
|
193
183
|
const digestAt = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor' && digestStillDue(review)
|
|
194
184
|
&& new Date(review.digestQueuedAt) >= clock.stagesFrom && digestDueAt([review], policy).getTime();
|
|
195
|
-
|
|
185
|
+
// A case waiting for a set time holds its earlier stages, since the digest goes before its deadline.
|
|
186
|
+
const held = digestAt && (digestAt <= stage.dueAt.getTime() + DIGEST_GRACE_MS || (stage.stage !== 'deadline' && digestAtSetTimes()));
|
|
187
|
+
if (held && now.getTime() < digestAt + DIGEST_GRACE_MS) return false;
|
|
196
188
|
const withDoctor = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor'
|
|
197
189
|
&& (doctorRangSince(review, clock.stagesFrom) || new Date(review.digestSentAt ?? 0) >= clock.stagesFrom);
|
|
198
190
|
const undecided = withDoctor && stage.stage === 'deadline';
|
|
@@ -234,8 +226,9 @@ const remindersSince = (review, since) => (review.doctorAlerts ?? [])
|
|
|
234
226
|
async function remindDoctorIfDue(review, clock, now, policy) {
|
|
235
227
|
if (review.status !== 'awaiting_doctor') return false;
|
|
236
228
|
const promptAt = armedPromptAt(review);
|
|
237
|
-
if (!promptAt && clock.level === 'urgent' && escalationUnopenedReminderLive() && ringAtOf(review)) return false;
|
|
238
229
|
if (review.doctorAlertKind === 'patient_prompt' && review.doctorAlertAttempts > 0) return false;
|
|
230
|
+
const announcedAt = review.doctorHandoffs?.at(-1)?.promptAt;
|
|
231
|
+
if (promptAt && announcedAt && new Date(announcedAt).getTime() === new Date(promptAt).getTime()) return false;
|
|
239
232
|
const dueAt = doctorReminderAt(clock.level, clock.stagesFrom, policy, promptAt);
|
|
240
233
|
const deadline = clock.stages.find((stage) => stage.stage === 'deadline').dueAt;
|
|
241
234
|
if (!dueAt || now < dueAt || now.getTime() - dueAt.getTime() > STALE_MS || now >= deadline) return false;
|