@peopl-health/nexus 6.8.0-dev.21714 → 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.
|
@@ -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 } : {}),
|
|
@@ -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
|
-
return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
|
|
651
|
+
return notAboveCase(review, alarm);
|
|
636
652
|
}
|
|
637
653
|
|
|
638
|
-
|
|
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
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
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,
|
|
@@ -2753,6 +2794,7 @@ module.exports = {
|
|
|
2753
2794
|
DRAFT_OPERATOR,
|
|
2754
2795
|
MAX_DOCTOR_UPDATES,
|
|
2755
2796
|
ANSWER_ONLY,
|
|
2797
|
+
IMPROVING,
|
|
2756
2798
|
FEVER_CATEGORY,
|
|
2757
2799
|
appliedLevelOf,
|
|
2758
2800
|
isLiveFeverOf,
|