@peopl-health/nexus 6.8.0-dev.21713 → 6.8.0
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 +5 -2
- package/lib/clinical/tools/reportMedicalEscalationTool.js +17 -9
- package/lib/models/escalationReviewModel.js +1 -0
- package/lib/services/escalationReviewService.js +64 -9
- package/lib/services/reviewDeadlineService.js +0 -3
- package/lib/services/untakenAlertService.js +5 -14
- 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,
|
|
@@ -263,6 +265,7 @@ module.exports = {
|
|
|
263
265
|
doctorAlertHeadline,
|
|
264
266
|
doctorAlertOpener,
|
|
265
267
|
doctorBrief,
|
|
268
|
+
patientPromptNotice,
|
|
266
269
|
doctorDigestLine,
|
|
267
270
|
doctorDigestTitle,
|
|
268
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, alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
|
|
11
|
+
const { ANSWER_ONLY, FEVER_CATEGORY, IMPROVING, PRE_DECISION_STATUSES, 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,10 +170,11 @@ 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];
|
|
173
|
+
const WHAT_CHANGED = ['new_symptom', 'higher_grade', 'new_red_flag', 'worse', 'persists_unanswered', ANSWER_ONLY, IMPROVING];
|
|
174
|
+
const HOLDABLE_CHANGES = [ANSWER_ONLY, IMPROVING];
|
|
174
175
|
|
|
175
176
|
const WHAT_CHANGED_PROPERTY = nullableEnum(WHAT_CHANGED);
|
|
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
|
|
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. `improving` cuando el paciente cuenta que el síntoma ya escalado mejoró, se resolvió o sigue igual de estable, sin síntoma nuevo, sin bandera roja y sin nada que empeore (por ejemplo «ya no me duele la garganta, solo quedó la ronquera»): queda anotado en el caso, abierto o cerrado en los últimos 7 días, sin volver a avisar al equipo; no aplica a la fiebre. Ante cualquier duda usa el valor que corresponda o `null`: nunca `answer_only` ni `improving` si algo empeoró, apareció algo nuevo o la mejoría es solo parcial con un dato que preocupa.';
|
|
177
178
|
|
|
178
179
|
const FEVER_RULED_OUT_PROPERTY = nullable({
|
|
179
180
|
'type': 'boolean',
|
|
@@ -185,6 +186,12 @@ const FEVER_READING_PROPERTY = nullable({
|
|
|
185
186
|
'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.',
|
|
186
187
|
});
|
|
187
188
|
|
|
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
|
+
|
|
188
195
|
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.';
|
|
189
196
|
|
|
190
197
|
const CLINICAL_ASSESSMENT_PROPERTY = nullable({
|
|
@@ -333,7 +340,7 @@ async function handler(args, context = {}) {
|
|
|
333
340
|
const category = feverRuledOut && listedCategory === FEVER_CATEGORY ? 'treatment_concern' : listedCategory;
|
|
334
341
|
const categoryCoerced = rawCategory !== null && listedCategory === null;
|
|
335
342
|
const claimedChange = updateMode && WHAT_CHANGED.includes(args?.what_changed) ? args.what_changed : null;
|
|
336
|
-
const whatChanged = claimedChange
|
|
343
|
+
const whatChanged = HOLDABLE_CHANGES.includes(claimedChange) && feverReading !== null && !normalReading ? null : claimedChange;
|
|
337
344
|
const clinicalAssessment = escalationAssessmentLive() && isPlainObject(details.clinical_assessment) ? details.clinical_assessment : null;
|
|
338
345
|
const strictlyParsed = typeof rawDetails === 'string' && isPlainObject(safeParse(rawDetails, null));
|
|
339
346
|
const detailsArg = typeof rawDetails === 'string'
|
|
@@ -374,7 +381,7 @@ async function handler(args, context = {}) {
|
|
|
374
381
|
},
|
|
375
382
|
})
|
|
376
383
|
: null;
|
|
377
|
-
const heldInFollowUp = whatChanged
|
|
384
|
+
const heldInFollowUp = HOLDABLE_CHANGES.includes(whatChanged) && Boolean((review?.alarms ?? []).find((raised) => raised.alarmId === alarmId)?.isHeldInFollowUp);
|
|
378
385
|
const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
|
|
379
386
|
const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
|
|
380
387
|
const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
|
|
@@ -485,19 +492,20 @@ async function handler(args, context = {}) {
|
|
|
485
492
|
netReason = 'patient_context_missing';
|
|
486
493
|
}
|
|
487
494
|
|
|
495
|
+
const heldReceipt = heldInFollowUp ? heldReceiptOf(review) : null;
|
|
488
496
|
const data = {
|
|
489
497
|
urgency_level: urgencyLevel,
|
|
490
498
|
queued_for_team: queued,
|
|
491
499
|
safety_net_armed: netArmed,
|
|
492
500
|
safety_net_reason: netReason,
|
|
493
501
|
team_has_reviewed: false,
|
|
494
|
-
means:
|
|
495
|
-
?
|
|
502
|
+
means: heldReceipt
|
|
503
|
+
? heldReceipt.means
|
|
496
504
|
: queued
|
|
497
505
|
? '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.'
|
|
498
506
|
: 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
|
|
499
|
-
follow_up:
|
|
500
|
-
...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
|
|
507
|
+
follow_up: heldReceipt ? heldReceipt.followUp : followUpNote(netArmed, netReason),
|
|
508
|
+
...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: heldInFollowUp && review?.closedAt ? 'closed_case' : anchor ? 'open_escalation' : 'none' } : {}),
|
|
501
509
|
...(heldInFollowUp ? { held_in_follow_up: true } : {}),
|
|
502
510
|
...(category !== listedCategory ? { category_recorded_as: category } : {}),
|
|
503
511
|
...(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
|
|
|
@@ -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,6 +106,8 @@ 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;
|
|
109
111
|
const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
|
|
110
112
|
const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
|
|
111
113
|
const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
|
|
@@ -628,14 +630,47 @@ async function closeStaleInterruption(EscalationReview, patientCode, now) {
|
|
|
628
630
|
}
|
|
629
631
|
}
|
|
630
632
|
|
|
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
|
+
|
|
631
647
|
function shouldHoldInFollowUp(review, alarm, mode) {
|
|
632
648
|
if (mode !== 'update') return false;
|
|
649
|
+
if (alarm.whatChanged === IMPROVING) return isQuietImprovement(review, alarm) && notAboveCase(review, alarm);
|
|
633
650
|
if (ALERTED_URGENCIES.includes(alarm.urgencyLevel) && (alarm.whatChanged !== ANSWER_ONLY || alarm.category === FEVER_CATEGORY)) return false;
|
|
634
|
-
|
|
635
|
-
|
|
651
|
+
return notAboveCase(review, alarm);
|
|
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
|
+
}
|
|
636
671
|
}
|
|
637
672
|
|
|
638
|
-
async function holdInFollowUp(review, alarm) {
|
|
673
|
+
async function holdInFollowUp(review, alarm, result = 'update_held') {
|
|
639
674
|
const held = await getEscalationReview()
|
|
640
675
|
.findOneAndUpdate(
|
|
641
676
|
{ _id: review._id, status: review.status, 'alarms.alarmId': alarm.alarmId },
|
|
@@ -644,7 +679,7 @@ async function holdInFollowUp(review, alarm) {
|
|
|
644
679
|
)
|
|
645
680
|
.lean();
|
|
646
681
|
if (!held) return review;
|
|
647
|
-
await audit(held, AGENT_OPERATOR, null, { action: 'followup_result', result
|
|
682
|
+
await audit(held, AGENT_OPERATOR, null, { action: 'followup_result', result, statusFrom: review.status });
|
|
648
683
|
return held;
|
|
649
684
|
}
|
|
650
685
|
|
|
@@ -666,6 +701,10 @@ async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date
|
|
|
666
701
|
const held = await holdInFollowUp(joined, entry);
|
|
667
702
|
if (held !== joined) return held;
|
|
668
703
|
}
|
|
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
|
+
}
|
|
669
708
|
await scheduleDoctorAlert(joined, entry, now);
|
|
670
709
|
await armPatientTimerOnJoin(joined, entry, now);
|
|
671
710
|
if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
|
|
@@ -676,6 +715,8 @@ async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date
|
|
|
676
715
|
}
|
|
677
716
|
return joined;
|
|
678
717
|
}
|
|
718
|
+
const noted = await noteOnRecentlyClosed(EscalationReview, patientCode, entry, mode, now);
|
|
719
|
+
if (noted) return noted;
|
|
679
720
|
try {
|
|
680
721
|
const created = (await EscalationReview.create({
|
|
681
722
|
patientCode,
|
|
@@ -1294,6 +1335,13 @@ const currentAlarms = (review) => {
|
|
|
1294
1335
|
return decidedAt ? alarms.filter((alarm) => new Date(alarm.raisedAt) > new Date(decidedAt)) : alarms;
|
|
1295
1336
|
};
|
|
1296
1337
|
|
|
1338
|
+
const patientTimerLiveFor = (review) => (currentAlarms(review).some(isLiveFeverOf(review)) ? feverTimerLive() : escalationTimerLive());
|
|
1339
|
+
|
|
1340
|
+
// 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.
|
|
1341
|
+
const armedPromptAt = (review) => (review.doctorAlertKind === 'patient_prompt' && !review.doctorAlertAttempts ? review.doctorAlertDueAt ?? null : null);
|
|
1342
|
+
|
|
1343
|
+
const patientPromptAt = (review) => (patientTimerLiveFor(review) ? armedPromptAt(review) : null);
|
|
1344
|
+
|
|
1297
1345
|
const topUrgencyOf = (review) => {
|
|
1298
1346
|
const open = currentAlarms(review);
|
|
1299
1347
|
return (open.length ? open : review.alarms ?? [])
|
|
@@ -1984,7 +2032,7 @@ async function notifiedApprover() {
|
|
|
1984
2032
|
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`);
|
|
1985
2033
|
}
|
|
1986
2034
|
|
|
1987
|
-
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, now = new Date() }) {
|
|
2035
|
+
function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, timer = null, now = new Date() }) {
|
|
1988
2036
|
const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
|
|
1989
2037
|
// A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
|
|
1990
2038
|
if (briefSid && draft.symptoms?.length) {
|
|
@@ -1994,6 +2042,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
1994
2042
|
kind,
|
|
1995
2043
|
change,
|
|
1996
2044
|
reminder,
|
|
2045
|
+
timer,
|
|
1997
2046
|
level: level ?? lead?.urgency,
|
|
1998
2047
|
identity,
|
|
1999
2048
|
draft,
|
|
@@ -2005,7 +2054,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
|
|
|
2005
2054
|
});
|
|
2006
2055
|
return { body: lines.join('\n'), template: Object.fromEntries(lines.map((line, index) => [index + 1, line])), contentSid: briefSid };
|
|
2007
2056
|
}
|
|
2008
|
-
const opener = [reminder, note].filter(Boolean).join(' · ') || null;
|
|
2057
|
+
const opener = [reminder, note, timer].filter(Boolean).join(' · ') || null;
|
|
2009
2058
|
const headline = kind && doctorAlertHeadline({ review, kind, note: opener, level, symptom });
|
|
2010
2059
|
const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
|
|
2011
2060
|
return {
|
|
@@ -2056,7 +2105,10 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
2056
2105
|
const identity = await readDoctorIdentity(review);
|
|
2057
2106
|
if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
2058
2107
|
const link = doctorLink(review);
|
|
2059
|
-
const
|
|
2108
|
+
const armedAt = mode === 'sent_whatsapp' ? patientPromptAt(review) : null;
|
|
2109
|
+
const promptAt = armedAt && new Date(armedAt) > new Date() ? new Date(armedAt) : null;
|
|
2110
|
+
const timer = promptAt && patientPromptNotice(promptAt, responseDeadlinePolicy().teamHours.timeZone);
|
|
2111
|
+
const message = doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, timer });
|
|
2060
2112
|
|
|
2061
2113
|
const patientCaseRecordIds = await reviewCaseIds(review);
|
|
2062
2114
|
|
|
@@ -2075,7 +2127,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
|
|
|
2075
2127
|
if (approver) delivery = { physicianEmail: approver.email, ...(rings ? await sendDoctorAlert({ message, approver, operator }) : {}) };
|
|
2076
2128
|
const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (rings ? message.body : null);
|
|
2077
2129
|
const handoff = {
|
|
2078
|
-
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, sentBy: operator } },
|
|
2130
|
+
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, ...(sent && promptAt && { promptAt }), sentBy: operator } },
|
|
2079
2131
|
$addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
|
|
2080
2132
|
$unset: { identityBlock: '' },
|
|
2081
2133
|
};
|
|
@@ -2742,6 +2794,7 @@ module.exports = {
|
|
|
2742
2794
|
DRAFT_OPERATOR,
|
|
2743
2795
|
MAX_DOCTOR_UPDATES,
|
|
2744
2796
|
ANSWER_ONLY,
|
|
2797
|
+
IMPROVING,
|
|
2745
2798
|
FEVER_CATEGORY,
|
|
2746
2799
|
appliedLevelOf,
|
|
2747
2800
|
isLiveFeverOf,
|
|
@@ -2755,6 +2808,8 @@ module.exports = {
|
|
|
2755
2808
|
caseTakenReason,
|
|
2756
2809
|
promptedSince,
|
|
2757
2810
|
currentAlarms,
|
|
2811
|
+
armedPromptAt,
|
|
2812
|
+
patientPromptAt,
|
|
2758
2813
|
DOCTOR_BRIEF_TEMPLATE_KEY,
|
|
2759
2814
|
doctorAlertMessage,
|
|
2760
2815
|
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
|
|
|
@@ -5,11 +5,11 @@ 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
15
|
const { digestAtSetTimes, digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
|
|
@@ -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;
|
|
@@ -236,8 +226,9 @@ const remindersSince = (review, since) => (review.doctorAlerts ?? [])
|
|
|
236
226
|
async function remindDoctorIfDue(review, clock, now, policy) {
|
|
237
227
|
if (review.status !== 'awaiting_doctor') return false;
|
|
238
228
|
const promptAt = armedPromptAt(review);
|
|
239
|
-
if (!promptAt && clock.level === 'urgent' && escalationUnopenedReminderLive() && ringAtOf(review)) return false;
|
|
240
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;
|
|
241
232
|
const dueAt = doctorReminderAt(clock.level, clock.stagesFrom, policy, promptAt);
|
|
242
233
|
const deadline = clock.stages.find((stage) => stage.stage === 'deadline').dueAt;
|
|
243
234
|
if (!dueAt || now < dueAt || now.getTime() - dueAt.getTime() > STALE_MS || now >= deadline) return false;
|