@peopl-health/nexus 6.7.2 → 6.8.0-dev.21713
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 +2 -1
- package/lib/clinical/tools/reportMedicalEscalationTool.js +9 -17
- package/lib/services/doctorDigestService.js +52 -9
- package/lib/services/escalationReviewService.js +4 -46
- package/lib/services/unopenedCaseService.js +9 -1
- package/lib/services/untakenAlertService.js +4 -2
- package/package.json +1 -1
|
@@ -246,7 +246,8 @@ function doctorBrief({ kind, change = null, reminder = null, level, identity, dr
|
|
|
246
246
|
const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
|
|
247
247
|
|
|
248
248
|
function doctorDigestLine({ identity, draft, alarmSymptom, deadline, now, timeZone, link }) {
|
|
249
|
-
const
|
|
249
|
+
const entry = briefSymptomOf(draft, alarmSymptom);
|
|
250
|
+
const head = [briefCaseLine(identity, entry, alarmSymptom), deadlineLabel(deadline, now, timeZone), briefKeyLine(draft, entry)].filter(Boolean).join(' · ');
|
|
250
251
|
return `${head}: ${link}`;
|
|
251
252
|
}
|
|
252
253
|
|
|
@@ -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 } : {}),
|
|
@@ -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 };
|
|
@@ -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,
|
|
@@ -2783,7 +2742,6 @@ module.exports = {
|
|
|
2783
2742
|
DRAFT_OPERATOR,
|
|
2784
2743
|
MAX_DOCTOR_UPDATES,
|
|
2785
2744
|
ANSWER_ONLY,
|
|
2786
|
-
IMPROVING,
|
|
2787
2745
|
FEVER_CATEGORY,
|
|
2788
2746
|
appliedLevelOf,
|
|
2789
2747
|
isLiveFeverOf,
|
|
@@ -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;
|
|
@@ -12,7 +12,7 @@ const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf,
|
|
|
12
12
|
const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, PRE_DECISION_STATUSES, appliedLevelOf, isLiveFeverOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, 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;
|
|
@@ -192,7 +192,9 @@ const doctorRangSince = (review, since) => (review.doctorHandoffs ?? [])
|
|
|
192
192
|
async function alertIfUntaken(review, clock, stage, now, policy) {
|
|
193
193
|
const digestAt = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor' && digestStillDue(review)
|
|
194
194
|
&& new Date(review.digestQueuedAt) >= clock.stagesFrom && digestDueAt([review], policy).getTime();
|
|
195
|
-
|
|
195
|
+
// A case waiting for a set time holds its earlier stages, since the digest goes before its deadline.
|
|
196
|
+
const held = digestAt && (digestAt <= stage.dueAt.getTime() + DIGEST_GRACE_MS || (stage.stage !== 'deadline' && digestAtSetTimes()));
|
|
197
|
+
if (held && now.getTime() < digestAt + DIGEST_GRACE_MS) return false;
|
|
196
198
|
const withDoctor = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor'
|
|
197
199
|
&& (doctorRangSince(review, clock.stagesFrom) || new Date(review.digestSentAt ?? 0) >= clock.stagesFrom);
|
|
198
200
|
const undecided = withDoctor && stage.stage === 'deadline';
|