@peopl-health/nexus 6.7.0-dev.21506 → 6.7.0-dev.21610

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 { alertWithoutEmergencyRow, attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
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,7 +170,22 @@ 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 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`. El `urgency_level` del recibo es el nivel aplicado: puede ser mayor que el que pediste, nunca menor.';
173
+ const WHAT_CHANGED = ['new_symptom', 'higher_grade', 'new_red_flag', 'worse', 'persists_unanswered', ANSWER_ONLY];
174
+
175
+ 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
+
178
+ const FEVER_RULED_OUT_PROPERTY = nullable({
179
+ 'type': 'boolean',
180
+ 'description': 'Solo en `update`; llénalo siempre (`null` si no aplica). `true` solo con una lectura en `fever_reading_c`: cuando el paciente dio una temperatura medida después del dato de fiebre, entre 36.0 y 37.4 °C, niega escalofríos y no tomó paracetamol, antiinflamatorio ni corticoide en las 6 h previas a esa medición. Con un antipirético o corticoide reciente, o con malestar mientras lo toma, la fiebre no está descartada: deja `null`. Entonces la alarma se registra como `treatment_concern` y el caso deja de tratarse como fiebre. Una fiebre que vuelva después va en una alarma nueva con `febrile_neutropenia`.',
181
+ });
182
+
183
+ const FEVER_READING_PROPERTY = nullable({
184
+ 'type': 'number',
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.',
186
+ });
187
+
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.';
174
189
 
175
190
  const CLINICAL_ASSESSMENT_PROPERTY = nullable({
176
191
  'type': 'object',
@@ -222,6 +237,12 @@ function liveDefinition() {
222
237
  live.description += MODE_DESCRIPTION;
223
238
  properties.mode = MODE_PROPERTY;
224
239
  required.push('mode');
240
+ properties.what_changed = WHAT_CHANGED_PROPERTY;
241
+ required.push('what_changed');
242
+ properties.fever_reading_c = FEVER_READING_PROPERTY;
243
+ required.push('fever_reading_c');
244
+ properties.fever_ruled_out = FEVER_RULED_OUT_PROPERTY;
245
+ required.push('fever_ruled_out');
225
246
  }
226
247
  if (assessment) {
227
248
  properties.details.properties.clinical_assessment = CLINICAL_ASSESSMENT_PROPERTY;
@@ -231,6 +252,14 @@ function liveDefinition() {
231
252
  return live;
232
253
  }
233
254
 
255
+ const NORMAL_TEMP_C = [36.0, 37.4];
256
+
257
+ // A reading counts only as a plausible body temperature in °C.
258
+ function readingOf(value) {
259
+ const reading = typeof value === 'string' ? Number(value.replace(',', '.')) : value;
260
+ return typeof reading === 'number' && Number.isFinite(reading) && reading >= 30 && reading <= 45 ? reading : null;
261
+ }
262
+
234
263
  const yesNo = (value) => (value === true ? 'sí' : value === false ? 'no' : null);
235
264
 
236
265
  function knownExplanationNote(known) {
@@ -297,8 +326,14 @@ async function handler(args, context = {}) {
297
326
  const details = parsedDetails || {};
298
327
  const rawCategory = details.category ?? null;
299
328
  const requestedCategory = typeof rawCategory === 'string' ? rawCategory.trim() : rawCategory;
300
- const category = CATEGORIES.includes(requestedCategory) ? requestedCategory : null;
301
- const categoryCoerced = rawCategory !== null && category === null;
329
+ const listedCategory = CATEGORIES.includes(requestedCategory) ? requestedCategory : null;
330
+ const feverReading = updateMode ? readingOf(args?.fever_reading_c) : null;
331
+ const normalReading = feverReading !== null && feverReading >= NORMAL_TEMP_C[0] && feverReading <= NORMAL_TEMP_C[1];
332
+ const feverRuledOut = normalReading && args?.fever_ruled_out === true;
333
+ const category = feverRuledOut && listedCategory === FEVER_CATEGORY ? 'treatment_concern' : listedCategory;
334
+ const categoryCoerced = rawCategory !== null && listedCategory === null;
335
+ const claimedChange = updateMode && WHAT_CHANGED.includes(args?.what_changed) ? args.what_changed : null;
336
+ const whatChanged = claimedChange === ANSWER_ONLY && feverReading !== null && !normalReading ? null : claimedChange;
302
337
  const clinicalAssessment = escalationAssessmentLive() && isPlainObject(details.clinical_assessment) ? details.clinical_assessment : null;
303
338
  const strictlyParsed = typeof rawDetails === 'string' && isPlainObject(safeParse(rawDetails, null));
304
339
  const detailsArg = typeof rawDetails === 'string'
@@ -333,9 +368,13 @@ async function handler(args, context = {}) {
333
368
  .filter((indicator) => typeof indicator === 'string' && indicator.trim()),
334
369
  turnId: runtime.turnId || null,
335
370
  ...(clinicalAssessment ? { clinicalAssessment } : {}),
371
+ ...(feverRuledOut ? { feverRuledOut: true } : {}),
372
+ ...(feverReading !== null ? { feverReadingC: feverReading } : {}),
373
+ ...(whatChanged ? { whatChanged } : {}),
336
374
  },
337
375
  })
338
376
  : null;
377
+ const heldInFollowUp = whatChanged === ANSWER_ONLY && Boolean((review?.alarms ?? []).find((raised) => raised.alarmId === alarmId)?.isHeldInFollowUp);
339
378
  const anchor = updateMode && review ? escalationAnchorOf(review, alarmId) : null;
340
379
  const keptOpenLevel = Boolean(anchor) && (URGENCY_RANK[anchor.urgencyLevel] || 0) > (URGENCY_RANK[requestedLevel] || 0);
341
380
  const urgencyLevel = keptOpenLevel ? anchor.urgencyLevel : requestedLevel;
@@ -364,7 +403,7 @@ async function handler(args, context = {}) {
364
403
  },
365
404
  });
366
405
 
367
- if (runtime.turnId && runtime.patientCode && raisesOpen) {
406
+ if (runtime.turnId && runtime.patientCode && raisesOpen && !heldInFollowUp) {
368
407
  try {
369
408
  await dispatcherService.dispatch({
370
409
  trace,
@@ -382,7 +421,9 @@ async function handler(args, context = {}) {
382
421
  let netReason = null;
383
422
 
384
423
  if (runtime.patientCode) {
385
- if (urgencyLevel === 'routine') {
424
+ if (heldInFollowUp) {
425
+ queued = true;
426
+ } else if (urgencyLevel === 'routine') {
386
427
  const { written, duplicate } = await writeUnresolvedRequest({
387
428
  code: runtime.patientCode,
388
429
  trace,
@@ -450,11 +491,15 @@ async function handler(args, context = {}) {
450
491
  safety_net_armed: netArmed,
451
492
  safety_net_reason: netReason,
452
493
  team_has_reviewed: false,
453
- means: queued
454
- ? '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.'
455
- : 'The escalation was NOT recorded for the team. Say nothing to the patient implying they were notified, and report the failure.',
456
- follow_up: followUpNote(netArmed, netReason),
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.'
496
+ : queued
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.'
498
+ : '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),
457
500
  ...(escalationUpdateModeLive() ? { mode: updateMode ? 'update' : 'new', update_anchor: anchor ? 'open_escalation' : 'none' } : {}),
501
+ ...(heldInFollowUp ? { held_in_follow_up: true } : {}),
502
+ ...(category !== listedCategory ? { category_recorded_as: category } : {}),
458
503
  ...(keptOpenLevel ? { kept_open_level: true, requested_urgency_level: requestedLevel } : {}),
459
504
  ...(isCoerced ? { coerced_urgency: true, requested_urgency_level: requested } : {}),
460
505
  ...(categoryCoerced ? { coerced_category: true, requested_category: requestedCategory } : {}),
@@ -27,6 +27,7 @@ const { listReviewBoard } = require('../services/reviewBoardService');
27
27
  const { caseStateOf } = require('../services/escalationCaseStateService');
28
28
  const { responseDeadlinePolicy } = require('../services/reviewDeadlineService');
29
29
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
30
+ const { escalationDoctorCaseStatusLive } = require('../clinical/flags/escalationFlags');
30
31
 
31
32
  const respondWithError = (res, error, action, context) => {
32
33
  logger.error(`Error ${action}:`, {
@@ -65,7 +66,7 @@ const getEscalationReviewController = async (req, res) => {
65
66
  try {
66
67
  const { review, isApprover, responseDeadline, proposedPlan, prescribers } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
67
68
  const caseState = await safeCaseStateOf(review);
68
- res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, caseState, proposedPlan, prescribers });
69
+ res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, caseState, proposedPlan, prescribers, doctorCaseStatusLive: escalationDoctorCaseStatusLive() });
69
70
  } catch (error) {
70
71
  respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
71
72
  }
@@ -129,6 +130,10 @@ const setEscalationReviewCaseStatusesController = async (req, res) => {
129
130
  res.status(502).json({ success: false, error: 'The patient case could not be updated', review: withCaseStatus(review), caseMirror, caseMirrors });
130
131
  return;
131
132
  }
133
+ if (caseMirror === 'superseded') {
134
+ res.status(409).json({ success: false, error: 'A newer review took the case while saving', errorCode: 'CASE_HELD_ELSEWHERE', review: withCaseStatus(review), caseMirror, caseMirrors });
135
+ return;
136
+ }
132
137
  res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
133
138
  } catch (error) {
134
139
  respondWithError(res, error, 'setting escalation review case statuses', { reviewId: req.params?.id });
@@ -35,6 +35,9 @@ const alarmSchema = new mongoose.Schema({
35
35
  emergencyRecordId: { type: String, default: null },
36
36
  appliedLevel: { type: String, default: null },
37
37
  isHeldInFollowUp: { type: Boolean, default: undefined },
38
+ feverRuledOut: { type: Boolean, default: undefined },
39
+ feverReadingC: { type: Number, default: undefined },
40
+ whatChanged: { type: String, default: null },
38
41
  raisedAt: { type: Date, required: true },
39
42
  }, { _id: false });
40
43
 
@@ -105,6 +105,7 @@ const DEFAULT_FEVER_TIMER_MINUTES = 15;
105
105
  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
+ const ANSWER_ONLY = 'answer_only';
108
109
  const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
109
110
  const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
110
111
  const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
@@ -628,7 +629,8 @@ async function closeStaleInterruption(EscalationReview, patientCode, now) {
628
629
  }
629
630
 
630
631
  function shouldHoldInFollowUp(review, alarm, mode) {
631
- if (mode !== 'update' || ALERTED_URGENCIES.includes(alarm.urgencyLevel)) return false;
632
+ if (mode !== 'update') return false;
633
+ if (ALERTED_URGENCIES.includes(alarm.urgencyLevel) && (alarm.whatChanged !== ANSWER_ONLY || alarm.category === FEVER_CATEGORY)) return false;
632
634
  const decided = effectiveUrgencyOf({ ...review, alarms: (review.alarms ?? []).filter((entry) => entry.alarmId !== alarm.alarmId) })?.urgency;
633
635
  return Boolean(decided) && (URGENCY_RANK[alarm.urgencyLevel] || 0) <= (URGENCY_RANK[decided] || 0);
634
636
  }
@@ -660,11 +662,13 @@ async function recordEscalationAlarm({ code, alarm, mode = 'new', now = new Date
660
662
  await closeStaleInterruption(EscalationReview, patientCode, now);
661
663
  const joined = await join();
662
664
  if (joined) {
665
+ if (FOLLOWUP_STATUSES.includes(joined.status) && shouldHoldInFollowUp(joined, entry, mode)) {
666
+ const held = await holdInFollowUp(joined, entry);
667
+ if (held !== joined) return held;
668
+ }
663
669
  await scheduleDoctorAlert(joined, entry, now);
664
670
  await armPatientTimerOnJoin(joined, entry, now);
665
- if (FOLLOWUP_STATUSES.includes(joined.status)) {
666
- return shouldHoldInFollowUp(joined, entry, mode) ? await holdInFollowUp(joined, entry) : await reopenFromFollowUp(joined, 'new_alarm');
667
- }
671
+ if (FOLLOWUP_STATUSES.includes(joined.status)) return await reopenFromFollowUp(joined, 'new_alarm');
668
672
  if (!DOCUMENTING_STATUSES.includes(joined.status)) {
669
673
  logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
670
674
  escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
@@ -988,7 +992,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
988
992
  }
989
993
 
990
994
  async function setCaseStatuses({ id, caseStatuses, updatedBy, requestId = null } = {}) {
991
- if (!escalationDoctorCaseStatusLive()) throw httpError(409, 'Setting case statuses is not enabled');
995
+ if (!escalationDoctorCaseStatusLive()) throw httpError(409, 'Setting case statuses is not enabled', 'CASE_STATUS_OFF');
992
996
  const reviewId = reviewIdOf(id);
993
997
  const operator = requiredText(updatedBy, 'updatedBy');
994
998
  const current = await loadReview(reviewId);
@@ -996,7 +1000,7 @@ async function setCaseStatuses({ id, caseStatuses, updatedBy, requestId = null }
996
1000
  if (!mirrors.length) throw httpError(400, 'caseStatuses must name at least one case');
997
1001
  const superseded = await supersededCaseIds(getEscalationReview(), current);
998
1002
  const held = mirrors.find(({ recordId }) => superseded.has(recordId));
999
- if (held) throw httpError(409, `A newer review holds case ${held.recordId}; set its status there`);
1003
+ if (held) throw httpError(409, `A newer review holds case ${held.recordId}; set its status there`, 'CASE_HELD_ELSEWHERE');
1000
1004
  const review = await updateReview(reviewId, [current.status], { $push: caseStatusPushOf(mirrors, operator) });
1001
1005
  await audit(review, operator, requestId, { action: 'case_statuses_set', caseStatuses: mirrors.map(({ recordId, changes }) => ({ recordId, status: changes.status })) });
1002
1006
  return syncCase(review, operator, requestId);
@@ -1094,8 +1098,15 @@ const timerMs = (key, fallback) => {
1094
1098
 
1095
1099
  const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
1096
1100
 
1097
- const feverAlarmsOf = (review) => currentAlarms(review)
1098
- .filter((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
1101
+ const isLiveFeverOf = (review) => {
1102
+ const clearedMs = Math.max(-Infinity, ...(review.alarms ?? []).filter((alarm) => alarm.feverRuledOut).map((alarm) => new Date(alarm.raisedAt).getTime()));
1103
+ return (alarm) => alarm.category === FEVER_CATEGORY && new Date(alarm.raisedAt).getTime() > clearedMs;
1104
+ };
1105
+
1106
+ const feverAlarmsOf = (review) => {
1107
+ const isLiveFever = isLiveFeverOf(review);
1108
+ return currentAlarms(review).filter((alarm) => appliedLevelOf(alarm) === 'asap' && isLiveFever(alarm));
1109
+ };
1099
1110
 
1100
1111
  async function feverTimerGap(patientCode, now) {
1101
1112
  if (!chemoContextLive()) return 'chemo_context_off';
@@ -1132,7 +1143,8 @@ function timerLevelOf(review) {
1132
1143
  // level timers, a prompt that fires was armed as the fever prompt and fires as armed.
1133
1144
  async function patientTimerOf(review, level, now, { firing = false } = {}) {
1134
1145
  const levelTimer = escalationTimerLive() && Boolean(PATIENT_TIMER_PROMPT_IDS[level]);
1135
- const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && alarm.category === FEVER_CATEGORY);
1146
+ const isLiveFever = isLiveFeverOf(review);
1147
+ const armedAsFever = firing && !levelTimer && (review.alarms ?? []).some((alarm) => appliedLevelOf(alarm) === 'asap' && isLiveFever(alarm));
1136
1148
  const fever = level === 'asap' && feverTimerLive() && (armedAsFever || feverAlarmsOf(review).length > 0);
1137
1149
  const gap = fever && !armedAsFever ? await feverTimerGap(review.patientCode, now) : null;
1138
1150
  if (fever && !gap) {
@@ -2706,8 +2718,10 @@ module.exports = {
2706
2718
  DOCUMENTING_STATUSES,
2707
2719
  DRAFT_OPERATOR,
2708
2720
  MAX_DOCTOR_UPDATES,
2721
+ ANSWER_ONLY,
2709
2722
  FEVER_CATEGORY,
2710
2723
  appliedLevelOf,
2724
+ isLiveFeverOf,
2711
2725
  MAX_ALERT_ATTEMPTS,
2712
2726
  PRE_DECISION_STATUSES,
2713
2727
  _resetEscalationReviewIndexes,
@@ -110,7 +110,8 @@ async function postToGroup(body, quoted) {
110
110
  validateStatus: () => true,
111
111
  });
112
112
  if (res.status >= 200 && res.status < 300) return { delivered: true, error: null, messageId: res.data?.message?.id || null };
113
- return { delivered: false, error: `whapi responded ${res.status}` };
113
+ // A 5xx may come after Whapi posted.
114
+ return { delivered: false, error: `whapi responded ${res.status}`, possiblyDelivered: res.status >= 500 };
114
115
  }
115
116
 
116
117
  // A reply in the alarm's thread carries `threadBody`, which leaves out what the quoted alert already says.
@@ -121,7 +122,8 @@ async function sendToGroup(body, quoted = null, threadBody = null) {
121
122
  // A quoted message Whapi no longer knows must not cost the alert: it goes out unthreaded.
122
123
  return sent.delivered || !quoted ? sent : await postToGroup(body, null);
123
124
  } catch (error) {
124
- return { delivered: false, error: redacted(error) };
125
+ // Only a timeout may have posted; a refused or unresolved connection never reached Whapi.
126
+ return { delivered: false, error: redacted(error), possiblyDelivered: error?.code === 'ECONNABORTED' || /timeout|timed out|ETIMEDOUT/i.test(String(error?.message)) };
125
127
  }
126
128
  }
127
129
 
@@ -79,7 +79,10 @@ async function doctorPingedRecently(review, physicianEmail, now) {
79
79
  || (review.doctorHandoffs ?? []).some((handoff) => handoff.transport && timeOf(handoff.createdAt) >= since.getTime());
80
80
  if (ownRing) return true;
81
81
  const others = await getEscalationReview().countDocuments({
82
- unopenedAlerts: { $elemMatch: { stage: 'doctor', physicianEmail, skippedReason: null, error: null, sentAt: { $gte: since } } },
82
+ $or: [
83
+ { unopenedAlerts: { $elemMatch: { stage: 'doctor', physicianEmail, skippedReason: null, error: null, sentAt: { $gte: since } } } },
84
+ { doctorAlerts: { $elemMatch: { kind: 'reminder', physicianEmail, sentAt: { $gte: since }, $or: [{ transport: { $ne: null } }, { possiblyDelivered: true }] } } },
85
+ ],
83
86
  });
84
87
  return others > 0;
85
88
  }
@@ -155,7 +158,7 @@ async function sweepUnopenedCases({ now = new Date() } = {}) {
155
158
  }, {
156
159
  patientCode: 1, status: 1, closedAt: 1, alarms: 1, urgencyReclassifications: 1, decisions: 1, callLogs: 1,
157
160
  patientCaseRecordIds: 1, doctorHandoffs: 1, digestSentAt: 1, approverViewedAt: 1, unopenedAlerts: 1,
158
- 'doctorAlerts.sentAt': 1, 'doctorAlerts.transport': 1,
161
+ 'doctorAlerts.sentAt': 1, 'doctorAlerts.transport': 1, 'doctorAlerts.kind': 1, 'doctorAlerts.possiblyDelivered': 1,
159
162
  })
160
163
  .sort({ _id: -1 })
161
164
  .limit(SWEEP_LIMIT)
@@ -46,7 +46,7 @@ async function noticePatient(patientCode, cases, now) {
46
46
  const sent = await sendGroupNotice([header, `${patient} (${doctor})`, ...cases.map(caseLabel), action, link].join('\n'), null, [header, action].join('\n'));
47
47
  if (sent.delivered) return 'sent';
48
48
  logger.error('[UnreviewedCase] The notice did not reach the group', { error: sent.error });
49
- return 'failed';
49
+ return sent.possiblyDelivered ? 'uncertain' : 'failed';
50
50
  }
51
51
 
52
52
  async function sweepUnreviewedCases({ now = new Date() } = {}) {
@@ -9,7 +9,7 @@ const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUnopene
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, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
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
15
  const { 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, 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, 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
  };
@@ -68,6 +68,7 @@ function episodeStartOf(alarms) {
68
68
  }
69
69
 
70
70
  function untakenClockOf(review, policy) {
71
+ const isLiveFever = isLiveFeverOf(review);
71
72
  const entries = levelsOf(currentAlarms(review).filter((alarm) => !alarm.isHeldInFollowUp), review.urgencyReclassifications, appliedLevelOf).filter((entry) => UNTAKEN_LEVELS.includes(entry.level));
72
73
  const level = entries.reduce((top, entry) => (URGENCY_RANK[entry.level] > (URGENCY_RANK[top] || 0) ? entry.level : top), null);
73
74
  if (!level) return null;
@@ -80,7 +81,7 @@ function untakenClockOf(review, policy) {
80
81
  stagesFrom,
81
82
  symptom: oneLineOf(atLevel.at(-1).alarm.symptom),
82
83
  emergencyRecordId: atLevel.find((entry) => entry.alarm.emergencyRecordId)?.alarm.emergencyRecordId ?? null,
83
- stages: untakenStagesOf(level, stagesFrom, policy, { fever: level === 'asap' && feverPatientTimerLive() && atLevel.some((entry) => entry.alarm.category === FEVER_CATEGORY) }),
84
+ stages: untakenStagesOf(level, stagesFrom, policy, { fever: level === 'asap' && feverPatientTimerLive() && atLevel.some((entry) => isLiveFever(entry.alarm)) }),
84
85
  };
85
86
  }
86
87
 
@@ -110,7 +111,7 @@ function pendingQuestionOf(review, clock) {
110
111
  }
111
112
 
112
113
  function patientTimerLiveFor(review) {
113
- const fever = currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY);
114
+ const fever = currentAlarms(review).some(isLiveFeverOf(review));
114
115
  return fever ? feverPatientTimerLive() : escalationPatientTimerLive();
115
116
  }
116
117
 
@@ -261,7 +262,7 @@ async function remindDoctorIfDue(review, clock, now, policy) {
261
262
  decisions: { $not: { $elemMatch: { createdAt: { $gte: clock.since } } } },
262
263
  callLogs: { $not: { $elemMatch: { outcome: 'contacted', calledAt: { $gte: clock.since } } } },
263
264
  },
264
- { $push: { doctorAlerts: { kind: 'reminder', urgencyLevel: clock.level, error: null, sentAt: now } } },
265
+ { $push: { doctorAlerts: { kind: 'reminder', urgencyLevel: clock.level, physicianEmail: review.doctorHandoffs?.at(-1)?.physicianEmail ?? null, error: null, sentAt: now } } },
265
266
  BOOKKEEPING,
266
267
  );
267
268
  if (!claimed.modifiedCount) return false;
@@ -275,7 +276,7 @@ async function remindDoctorIfDue(review, clock, now, policy) {
275
276
  }
276
277
  await getEscalationReview().updateOne(
277
278
  { _id: review._id, doctorAlerts: { $elemMatch: { kind: 'reminder', sentAt: now } } },
278
- { $set: { 'doctorAlerts.$.transport': delivery.transport ?? null, 'doctorAlerts.$.messageId': delivery.messageId ?? null, 'doctorAlerts.$.physicianEmail': delivery.physicianEmail ?? null, 'doctorAlerts.$.error': delivery.error ?? null, 'doctorAlerts.$.possiblyDelivered': Boolean(delivery.possiblyDelivered) } },
279
+ { $set: { 'doctorAlerts.$.transport': delivery.transport ?? null, 'doctorAlerts.$.messageId': delivery.messageId ?? null, 'doctorAlerts.$.physicianEmail': delivery.physicianEmail ?? review.doctorHandoffs?.at(-1)?.physicianEmail ?? null, 'doctorAlerts.$.error': delivery.error ?? null, 'doctorAlerts.$.possiblyDelivered': Boolean(delivery.possiblyDelivered) } },
279
280
  BOOKKEEPING,
280
281
  );
281
282
  await audit(review, { action: 'doctor_reminded', urgencyLevel: clock.level, delivered: !delivery.error, transport: delivery.transport ?? null });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.7.0-dev.21506",
3
+ "version": "6.7.0-dev.21610",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",