@peopl-health/nexus 6.7.0 → 6.7.2

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 empeoró o apareció algo nuevo.';
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 === ANSWER_ONLY && feverReading !== null && !normalReading ? null : 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 === ANSWER_ONLY && Boolean((review?.alarms ?? []).find((raised) => raised.alarmId === alarmId)?.isHeldInFollowUp);
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: 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.'
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: 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' } : {}),
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 } : {}),
@@ -44,9 +44,9 @@ const checkAgainAt = (review, at) => getEscalationReview().updateOne(
44
44
  BOOKKEEPING,
45
45
  );
46
46
 
47
- async function close(review, result) {
47
+ async function close(review, result, extra = {}) {
48
48
  const { review: closed } = await closeEscalationReview({ id: String(review._id), closedBy: OPERATOR, expectedAlarmCount: (review.alarms ?? []).length });
49
- await audit(closed, { action: 'followup_result', result });
49
+ await audit(closed, { action: 'followup_result', result, ...extra });
50
50
  if (result === 'answered') await resolveSettledCases(closed, OPERATOR);
51
51
  }
52
52
 
@@ -60,8 +60,8 @@ async function keepUnanswered(review, now) {
60
60
  }
61
61
 
62
62
  async function settleAnswer(review, now) {
63
- const { review: current, reading } = await followUpReadingOf(review);
64
- if (reading === 'settled') return close(current, 'answered');
63
+ const { review: current, reading, basis } = await followUpReadingOf(review, { canFallBackToDecisionReading: true });
64
+ if (reading === 'settled') return close(current, 'answered', { basis });
65
65
  const held = await getEscalationReview().updateOne(
66
66
  { _id: review._id, closedAt: null, status: { $in: FOLLOW_UP_STATUSES }, 'caseFollowUp.reminderId': review.caseFollowUp.reminderId, 'caseFollowUp.unsettledAt': null },
67
67
  { $set: { 'caseFollowUp.unsettledAt': now, 'caseFollowUp.nextCheckAt': null, updatedSinceSeen: true } },
@@ -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
- 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);
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: 'update_held', statusFrom: review.status });
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,
@@ -1631,23 +1672,46 @@ async function closeSettled(review) {
1631
1672
  }
1632
1673
  }
1633
1674
 
1634
- async function followUpReadingOf(snapshot) {
1675
+ // A watched case read settled at its decision stands there until read again; any alarm since the decision, held or not, voids it.
1676
+ function canStandOnDecisionReading(review, sinceMs) {
1677
+ const decisions = review.decisions ?? [];
1678
+ if (decisions.at(-1)?.decision !== 'monitor') return false;
1679
+ return !(review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > sinceMs);
1680
+ }
1681
+
1682
+ async function followUpReadingOf(snapshot, { canFallBackToDecisionReading = false } = {}) {
1635
1683
  const since = (snapshot.decisions ?? []).at(-1)?.createdAt;
1636
1684
  if (!since) return { review: snapshot, reading: null };
1637
1685
  const sinceMs = new Date(since).getTime();
1638
1686
  const { review, known } = await followUpCasesOf(snapshot, sinceMs);
1639
1687
  if (!known.size) return { review, reading: null };
1640
1688
 
1689
+ const previousDecision = (review.decisions ?? []).at(-2)?.createdAt;
1690
+ const previousMs = previousDecision ? new Date(previousDecision).getTime() : -Infinity;
1641
1691
  const latest = new Map();
1642
- (review.updates ?? []).filter((entry) => new Date(entry.at).getTime() > sinceMs)
1692
+ const decidedOn = new Map();
1693
+ [...(review.updates ?? [])]
1643
1694
  .sort((a, b) => new Date(a.at) - new Date(b.at))
1644
- .forEach((entry) => (entry.impressions ?? [])
1645
- .filter((impression) => known.has(impression.caseId) && readingOf(impression))
1646
- .forEach((impression) => latest.set(impression.caseId, readingOf(impression))));
1695
+ .forEach((entry) => {
1696
+ const atMs = new Date(entry.at).getTime();
1697
+ if (atMs <= previousMs) return;
1698
+ const readings = atMs > sinceMs ? latest : decidedOn;
1699
+ (entry.impressions ?? [])
1700
+ .filter((impression) => known.has(impression.caseId) && readingOf(impression))
1701
+ .forEach((impression) => readings.set(impression.caseId, readingOf(impression)));
1702
+ });
1703
+ let basis = 'followUp';
1704
+ if (canFallBackToDecisionReading && canStandOnDecisionReading(review, sinceMs)) {
1705
+ for (const caseId of known) {
1706
+ if (latest.has(caseId) || !SETTLED_TRAJECTORIES.includes(decidedOn.get(caseId))) continue;
1707
+ latest.set(caseId, decidedOn.get(caseId));
1708
+ basis = 'decision';
1709
+ }
1710
+ }
1647
1711
 
1648
1712
  if ([...latest.values()].includes('worsening')) return { review, reading: 'worsening' };
1649
1713
  const settled = [...known].every((caseId) => SETTLED_TRAJECTORIES.includes(latest.get(caseId)));
1650
- return { review, reading: settled ? 'settled' : 'unsettled' };
1714
+ return settled ? { review, reading: 'settled', basis } : { review, reading: 'unsettled' };
1651
1715
  }
1652
1716
 
1653
1717
  async function settleFollowUp(snapshot, { background = true, canClose = true } = {}) {
@@ -2719,6 +2783,7 @@ module.exports = {
2719
2783
  DRAFT_OPERATOR,
2720
2784
  MAX_DOCTOR_UPDATES,
2721
2785
  ANSWER_ONLY,
2786
+ IMPROVING,
2722
2787
  FEVER_CATEGORY,
2723
2788
  appliedLevelOf,
2724
2789
  isLiveFeverOf,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.7.0",
3
+ "version": "6.7.2",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",