@peopl-health/nexus 6.0.0-dev.15739 → 6.0.0-dev.15839

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.
@@ -22,10 +22,20 @@ function escalationPatientTimerLive() {
22
22
  return flagOn('ESCALATION_PATIENT_TIMER_LIVE');
23
23
  }
24
24
 
25
+ function escalationGravePendingShadow() {
26
+ return flagOn('ESCALATION_GRAVE_PENDING_SHADOW');
27
+ }
28
+
29
+ function escalationUntakenAlertsLive() {
30
+ return flagOn('ESCALATION_UNTAKEN_ALERTS_LIVE');
31
+ }
32
+
25
33
  module.exports = {
26
34
  escalationApproverAlertLive,
27
35
  escalationAssessmentLive,
36
+ escalationGravePendingShadow,
28
37
  escalationPatientTimerLive,
38
+ escalationUntakenAlertsLive,
29
39
  escalationUpdateModeLive,
30
40
  feverPatientTimerLive,
31
41
  };
@@ -18,6 +18,9 @@ function latestAlarm(review) {
18
18
  return alarms[alarms.length - 1] ?? null;
19
19
  }
20
20
 
21
+ // The patient does not know it or cannot check it: still pending, but asking again will not get it.
22
+ const UNOBTAINABLE = 'no_obtenible';
23
+
21
24
  function flagsByStatus(sections) {
22
25
  const flags = (Array.isArray(sections?.redFlags) ? sections.redFlags : []).filter((flag) => inlineOf(flag?.flag));
23
26
  const named = (present) => flags.filter((flag) => flag.present === present).map((flag) => inlineOf(flag.flag));
@@ -28,6 +31,7 @@ function flagsByStatus(sections) {
28
31
  unassessed: pending.map((flag) => inlineOf(flag.flag)),
29
32
  drugSafety: pending.filter((flag) => flag.blocksDrug !== false).map((flag) => inlineOf(flag.flag)),
30
33
  urgent: pending.filter((flag) => flag.urgentIfPositive === true).map((flag) => inlineOf(flag.flag)),
34
+ unobtainable: pending.filter((flag) => flag.present === UNOBTAINABLE).map((flag) => inlineOf(flag.flag)),
31
35
  };
32
36
  }
33
37
 
@@ -418,7 +418,7 @@ class BaseLLMProvider {
418
418
  const sent = (recentCheckIns || []).map((at) => `- ${sanitizeInlineText(local(at))}`);
419
419
  const parts = [
420
420
  '[CHECK-IN QUE VENCE (prioritario) para este turno]',
421
- 'Venció el plazo para retomar algo pendiente con ella. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a buscarla o si ya no hace falta.',
421
+ 'Venció el plazo para retomar algo pendiente con esta persona. Nadie te ha escrito: decide si hoy le escribes, cuándo volver a escribirle o si ya no hace falta.',
422
422
  '', '## Qué quedó pendiente', ...pending,
423
423
  ];
424
424
  if (conversation.length) parts.push('', '## Cómo va la conversación', ...conversation);
@@ -428,13 +428,18 @@ class BaseLLMProvider {
428
428
  `Cierra el turno con \`${OUTREACH_DECISION_TOOL}\`. Antes, revisa la conversación desde que quedó pendiente:`,
429
429
  '- Este check-in es el seguimiento que está venciendo ahora, aunque lo veas programado unos minutos más tarde: ya no está pendiente y no se puede actualizar. Si decides esperar, programa uno nuevo.',
430
430
  '- Si ya lo respondió, a ti o al equipo, no se lo vuelvas a preguntar. Si es una red de contingencia, resuélvela con setContingencyPlan y registra hold con hold_reason answered_since_armed.',
431
- '- Si tu último mensaje ya le hace esta pregunta o la cubre, y ella estuvo activa hoy y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
431
+ '- Si tu último mensaje ya le hace esta pregunta o la cubre, y hoy estuvo en la conversación y dejó de contestar hace menos de 6 h, no la repitas hoy: programa la siguiente vez o resuélvela si ya no hace falta.',
432
432
  '- Si sólo quedó una pregunta tuya sin respuesta y lleva 8 h o más en silencio, retomarla es justo para lo que existe este check-in: escríbele, salvo que sea de noche.',
433
- '- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ella ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
433
+ '- Fuera de esos casos, decide la siguiente vez según el tipo de seguimiento y lo que ha ido contando: lo que puede empeorar en horas se pregunta pronto; un síntoma estable o ya en manejo puede esperar días. Si ya le llegó otro check-in hoy y esto puede esperar, no le escribas hoy: programa con schedulePatientReminder (reminder_type seguimiento, con la utility_basis de lo que quedó pendiente, nunca entre 07:30 y 11:00) la hora que corresponda y registra hold con hold_reason rescheduled_for_cadence y el mismo next_check_at.',
434
434
  '- Si la red viene de una escalación, su urgencia marca el plazo del equipo para revisarla, no una razón para volver a escribirle.',
435
435
  '- Este check-in es el seguimiento que vencía: no cuenta como otro pendiente. Si un seguimiento distinto en la lista de pendientes, o una red activa, ya va a preguntar esto, no programes otro: registra hold con next_check_at null y hold_reason contingency_already_armed.',
436
- '- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que ella contó o acordó.',
437
- 'Si escribes: breve, sin saludar ni escribir su nombre, sin listas de señales de alarma, sin mencionar recordatorios, planes ni seguimientos programados, y sin repetir un mensaje que ya le enviaste.',
436
+ '- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que contó o acordó.',
437
+ exchange?.sessionOpen === false
438
+ ? 'Si escribes, tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre; entra directo diciendo en pocas palabras qué retomas («te había preguntado por…»).'
439
+ : 'Si escribes, le llega como un mensaje normal. Si llevan horas sin hablar, ábrelo con un saludo breve y natural según la hora del día, con el nombre de quien lleva la conversación si lo conoces (a un cuidador cuyo nombre no conoces, sin nombre); luego di en pocas palabras qué retomas («te había preguntado por…»).',
440
+ 'Haz una sola pregunta por lo que sigue faltando de lo que esperabas saber. Háblale directo a quien lleva la conversación, de tú o de usted, como en la conversación; nunca hables en tercera persona de quien te está leyendo.',
441
+ 'No le comentes como novedad algo que no te dijo en el chat: sus respuestas del cuestionario las conoces tú, no son algo que te acaba de contar. No repitas lo que ya le dijiste (por ejemplo, que el equipo ya tiene el aviso) ni des por hecho detalles que no te dio.',
442
+ 'Breve, sin listas de señales de alarma y sin mencionar recordatorios, planes ni seguimientos programados.',
438
443
  );
439
444
  return [{ role: 'developer', content: parts.join('\n') }];
440
445
  }
@@ -1,6 +1,8 @@
1
1
  const moment = require('moment-timezone');
2
2
 
3
3
  const { getMessages } = require('../../services/messageService');
4
+ const { replyContactFor } = require('../../helpers/caregiverHelper');
5
+ const { isWithin24HourWindow } = require('../../helpers/conversationWindowHelper');
4
6
  const { checkInsPausedUntil } = require('../../services/threadService');
5
7
  const { DEFAULT_TIMEZONE } = require('../../utils/scheduleUtils');
6
8
  const { readActiveNets, escalationUrgencyOf } = require('./contingencyDispatchService');
@@ -12,7 +14,6 @@ const RECENT_CHECK_IN_WINDOW_MS = 48 * 60 * 60 * 1000;
12
14
  const TRIGGERED_BY_PREFIX = 'send_reminder:';
13
15
  const NET_INSTRUCTION_MARKER = 'no ha vuelto a escribir y quedó un tema abierto';
14
16
  const EXCERPT_LENGTH = 160;
15
- const OWN_ORIGINS = ['assistant', 'whatsapp_platform'];
16
17
  const LAST_MESSAGE_SCAN = 5;
17
18
 
18
19
  const checkInTriggeredBy = (reminderId) => `${TRIGGERED_BY_PREFIX}${reminderId}`;
@@ -41,11 +42,13 @@ async function recentCheckIns(code, now) {
41
42
  return (rows || []).map((row) => new Date(row.createdAt).toISOString());
42
43
  }
43
44
 
44
- const originFilter = (fromMe) => (fromMe ? { $in: OWN_ORIGINS } : { $ne: 'instruction' });
45
+ // Templates (cards, forms) and automations (the triage ack) would hide what the agent or the team last wrote; staff sign with their email.
46
+ const OWN_WRITTEN = { $or: [{ origin: 'assistant' }, { origin: 'whatsapp_platform', content_sid: null, triggeredBy: { $regex: '@' } }] };
47
+ const PATIENT_WRITTEN = { origin: { $ne: 'instruction' } };
45
48
 
46
49
  async function lastMessage(code, now, fromMe) {
47
50
  const rows = await getMessages(
48
- { numero: code, from_me: fromMe, origin: originFilter(fromMe), createdAt: { $lt: now } },
51
+ { numero: code, from_me: fromMe, ...(fromMe ? OWN_WRITTEN : PATIENT_WRITTEN), createdAt: { $lt: now } },
49
52
  { sort: { createdAt: -1 }, limit: LAST_MESSAGE_SCAN, select: 'createdAt plainBody body' },
50
53
  ) || [];
51
54
  const row = rows.find((candidate) => String(candidate.plainBody || candidate.body || '').trim());
@@ -56,12 +59,13 @@ async function lastMessage(code, now, fromMe) {
56
59
 
57
60
  async function recentExchange(code, now) {
58
61
  const startOfDay = moment(now).tz(DEFAULT_TIMEZONE).startOf('day').toDate();
59
- const [patient, own, ownToday] = await Promise.all([
62
+ const [patient, own, ownToday, sessionOpen] = await Promise.all([
60
63
  lastMessage(code, now, false),
61
64
  lastMessage(code, now, true),
62
- getMessages({ numero: code, from_me: true, origin: originFilter(true), createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
65
+ getMessages({ numero: code, from_me: true, ...OWN_WRITTEN, createdAt: { $gte: startOfDay, $lt: now } }, { select: 'createdAt' }),
66
+ replyContactFor(code).then((contact) => isWithin24HourWindow(code, { contactCode: contact?.contactCode || null })),
63
67
  ]);
64
- return { patient, own, ownMessagesToday: (ownToday || []).length };
68
+ return { patient, own, ownMessagesToday: (ownToday || []).length, sessionOpen };
65
69
  }
66
70
 
67
71
  async function briefFor(code, now, checkIn) {
@@ -194,6 +194,8 @@ async function generateEscalationDraft({
194
194
  protocolVersion: FORMULARY_VERSION,
195
195
  keyQuestions: textList(parsed?.keyQuestions),
196
196
  unassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unassessed))],
197
+ urgentUnassessedRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).urgent))],
198
+ unobtainableRedFlags: [...new Set(blocks.flatMap((block) => flagsByStatus(block).unobtainable))],
197
199
  missingCharacterization: textList(parsed?.missingCharacterization),
198
200
  suggestCall: suggestCallOf(parsed?.suggestCall),
199
201
  sectionsUnavailable: context.degradedSections ?? [],
@@ -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, escalationUpdateModeLive, feverPatientTimerLive } = require('../flags/escalationFlags');
11
- const { attachEmergencyRow, escalationAnchorOf, recordEscalationAlarm } = require('../../services/escalationReviewService');
11
+ const { 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');
@@ -401,6 +401,10 @@ async function handler(args, context = {}) {
401
401
  onRecorded: (recordId) => { emergencyRecordId = recordId; },
402
402
  });
403
403
  if (review && emergencyRecordId) await attachEmergencyRow({ reviewId: review._id, alarmId, emergencyRecordId, appliedLevel: urgencyLevel });
404
+ // A merge into an existing row never alerts, so only a row that had to be created falls back.
405
+ if (review && !queued && (raisesOpen || !anchor?.emergencyRecordId)) {
406
+ alertWithoutEmergencyRow({ reviewId: review._id, alarmId, urgencyLevel }).catch(() => {});
407
+ }
404
408
  if (urgencyLevel !== 'routine') {
405
409
  try {
406
410
  const net = queued ? await armEscalationNet({
@@ -58,7 +58,7 @@ const definition = {
58
58
  },
59
59
  patient_followup_reminder: {
60
60
  type: 'object',
61
- description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, in the patient's voice and language, about the symptom only: never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
61
+ description: `Required. ${STEP_SHAPE}: the check-in sent to the patient — message (string, addressed directly to whoever is in the conversation, in second person and in their language — tú or usted, as in the conversation; never about the reader in third person — about the symptom only: never ask whether the care team contacted them or gave an indication — that is not yours to ask, and it may arrive after the team already did) + fires_after_silence_minutes (> 0 and <= ${MAX_PATIENT_SILENCE_MIN}, ~23h, so it stays inside the WhatsApp session window) + window_reasoning: ONE sentence on why that wait — what you expect to happen in it, and why waiting longer would be unsafe or shorter would be noise. A check-in never goes out between 21:00 and 09:00 patient-local time (08:00–09:00 is when the daily symptom forms arrive) — a window landing in those hours is held until 09:00, so pick the window the concern needs and do not shorten it to dodge the small hours. If a concern cannot wait until morning, it needs an escalation, not a net. priority and action_requested are optional.`,
62
62
  },
63
63
  },
64
64
  required: ['action'],
package/lib/index.d.ts CHANGED
@@ -470,7 +470,7 @@ declare module '@peopl-health/nexus' {
470
470
  lastOutreach?: string | null;
471
471
  checkIn?: { type: string; reminderId?: string | null; dueAt?: string | null; question: string; concern?: string | null; awaiting?: string | null; armedAt?: string | null; urgency?: string | null; otherPlans?: number | null } | null;
472
472
  recentCheckIns?: string[];
473
- exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number } | null;
473
+ exchange?: { patient: { at: string; text: string } | null; own: { at: string; text: string } | null; ownMessagesToday: number; sessionOpen?: boolean } | null;
474
474
  asOf?: string | null;
475
475
  }
476
476
 
@@ -44,7 +44,7 @@ const impressionUpdateSchema = new mongoose.Schema({
44
44
  }, { _id: false });
45
45
 
46
46
  const doctorAlertSchema = new mongoose.Schema({
47
- kind: { type: String, enum: ['initial', 'realert', 'patient_prompt'], required: true },
47
+ kind: { type: String, enum: ['initial', 'realert', 'patient_prompt', 'fallback'], required: true },
48
48
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
49
49
  physicianEmail: { type: String, default: null },
50
50
  transport: { type: String, default: null },
@@ -55,6 +55,31 @@ const doctorAlertSchema = new mongoose.Schema({
55
55
  sentAt: { type: Date, required: true },
56
56
  }, { _id: false });
57
57
 
58
+ const untakenAlertSchema = new mongoose.Schema({
59
+ level: { type: String, enum: URGENCY_LEVELS, required: true },
60
+ stage: { type: String, enum: ['early', 'half', 'deadline'], required: true },
61
+ since: { type: Date, required: true },
62
+ dueAt: { type: Date, required: true },
63
+ skippedReason: { type: String, default: null },
64
+ delivered: { type: Number, default: null },
65
+ groupDelivered: { type: Boolean, default: null },
66
+ phonesDelivered: { type: Number, default: null },
67
+ phones: { type: Number, default: null },
68
+ sentAt: { type: Date, required: true },
69
+ }, { _id: false });
70
+
71
+ const graveAlertSchema = new mongoose.Schema({
72
+ flag: { type: String, required: true },
73
+ level: { type: String, enum: URGENCY_LEVELS, required: true },
74
+ since: { type: Date, required: true },
75
+ firstSeenAt: { type: Date, required: true },
76
+ reason: { type: String, enum: ['unobtainable', 'unanswered'], required: true },
77
+ takenReason: { type: String, default: null },
78
+ audience: { type: String, enum: ['all', 'group_doctor'], required: true },
79
+ shadow: { type: Boolean, default: true },
80
+ at: { type: Date, required: true },
81
+ }, { _id: false });
82
+
58
83
  const reviewUpdateSchema = new mongoose.Schema({
59
84
  turnId: { type: String, required: true },
60
85
  tools: { type: [String], default: [] },
@@ -96,6 +121,8 @@ const draftSchema = new mongoose.Schema({
96
121
  protocolVersion: { type: String, default: null },
97
122
  keyQuestions: { type: [String], default: undefined },
98
123
  unassessedRedFlags: { type: [String], default: undefined },
124
+ urgentUnassessedRedFlags: { type: [String], default: undefined },
125
+ unobtainableRedFlags: { type: [String], default: undefined },
99
126
  missingCharacterization: { type: [String], default: undefined },
100
127
  suggestCall: { type: suggestCallSchema, default: undefined },
101
128
  sectionsUnavailable: { type: [String], default: undefined },
@@ -201,6 +228,8 @@ const escalationReviewSchema = new mongoose.Schema({
201
228
  doctorAlertDueAt: { type: Date, default: null },
202
229
  doctorAlertKind: { type: String, enum: ['initial', 'realert', 'patient_prompt', null], default: null },
203
230
  doctorAlertAttempts: { type: Number, default: 0 },
231
+ untakenAlerts: { type: [untakenAlertSchema], default: [] },
232
+ graveAlerts: { type: [graveAlertSchema], default: [] },
204
233
  feverPromptStartedAt: { type: Date, default: null },
205
234
  approverViewedAt: { type: Date, default: null },
206
235
  previousReviewId: { type: String, default: null },
@@ -50,7 +50,7 @@ const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = re
50
50
  const { countMessages } = require('./messageService');
51
51
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
52
52
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
53
- const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
53
+ const { effectiveUrgencyOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
54
54
  const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
55
55
 
56
56
  const getMessaging = () => require('../core/NexusMessaging');
@@ -78,12 +78,11 @@ const SETTLEABLE_STATUSES = ['indications_sent', 'monitoring'];
78
78
  const DRAFTLESS_DECISIONS = ['monitor', 'returned'];
79
79
  const SETTLED_TRAJECTORIES = ['improving', 'stable'];
80
80
  const ALERTED_URGENCIES = ['stat', 'asap'];
81
- const ALERT_MARKS = { stat: '🔴', asap: '🟠' };
81
+ const ALERT_MARKS = { stat: '🔴', asap: '🟠', urgent: '🟡' };
82
82
  const DEFAULT_FEVER_TIMER_MINUTES = 15;
83
83
  const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
84
84
  const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
85
85
  const FEVER_CATEGORY = 'febrile_neutropenia';
86
- const DEFAULT_PATIENT_TIMER_MINUTES = 15;
87
86
  const PATIENT_TIMER_PROMPT_IDS = { stat: 'stat_patient_timer', asap: 'asap_patient_timer' };
88
87
  const PATIENT_TIMER_OPERATOR = 'escalation_patient_timer';
89
88
  const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
@@ -963,7 +962,7 @@ async function patientTimerOf(review, level, now, { firing = false } = {}) {
963
962
  return { timer: { level, fever: true, promptId: FEVER_TIMER_PROMPT_ID, operator: FEVER_TIMER_OPERATOR, ms: timerMs('FEVER_PATIENT_TIMER_MINUTES', DEFAULT_FEVER_TIMER_MINUTES) }, gap };
964
963
  }
965
964
  if (levelTimer) {
966
- return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: timerMs('ESCALATION_PATIENT_TIMER_MINUTES', DEFAULT_PATIENT_TIMER_MINUTES) }, gap };
965
+ return { timer: { level, fever: false, promptId: PATIENT_TIMER_PROMPT_IDS[level], operator: PATIENT_TIMER_OPERATOR, ms: patientTimerMinutes() * 60 * 1000 }, gap };
967
966
  }
968
967
  return { timer: null, gap };
969
968
  }
@@ -987,12 +986,17 @@ async function takenReason(review, since, timer, ownStart = null) {
987
986
  const atLevel = (alarm) => alarm.urgencyLevel === timer.level || appliedLevelOf(alarm) === timer.level;
988
987
  const first = (timer.fever ? feverAlarmsOf(review) : currentAlarms(review).filter(atLevel))[0];
989
988
  const from = new Date(Math.max(since.getTime(), first ? new Date(first.raisedAt).getTime() : -Infinity));
990
- const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
991
989
  if (review.closedAt || !PRE_DECISION_STATUSES.includes(review.status)) return 'review_moved_on';
992
990
  if (promptedSince(review, since, ownStart)) return 'already_prompted';
991
+ return caseTakenReason(review, from, timer.level);
992
+ }
993
+
994
+ // What says the team took the case from `from` on, for a case timed at `level`.
995
+ async function caseTakenReason(review, from, level) {
996
+ const atOrAfter = (at) => at != null && new Date(at).getTime() >= from.getTime();
993
997
  if ((review.decisions ?? []).some((decision) => atOrAfter(decision.createdAt))) return 'decision';
994
998
  const stat = (alarm) => alarm.urgencyLevel === 'stat' || alarm.appliedLevel === 'stat';
995
- if (timer.level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
999
+ if (level !== 'stat' && currentAlarms(review).some(stat)) return 'stat_alarm';
996
1000
  if ((review.urgencyReclassifications ?? []).some((change) => atOrAfter(change.at))) return 'reclassified';
997
1001
  if ((review.callLogs ?? []).some((call) => call.outcome === 'contacted' && atOrAfter(call.calledAt))) return 'call_contacted';
998
1002
  // A read error goes back to the sweep to retry; only a thread that does not exist (no turn to run
@@ -1031,13 +1035,14 @@ async function armPatientTimerOnJoin(review, alarm, now) {
1031
1035
  }
1032
1036
  }
1033
1037
 
1034
- async function prepareDoctorAlert(review, urgencyLevel) {
1038
+ async function prepareDoctorAlert(review, urgencyLevel, { recipient = null, alarmId = null } = {}) {
1035
1039
  const identity = await readDoctorIdentity(review);
1036
1040
  if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
1037
- const approver = await soleApprover();
1041
+ const approver = recipient ?? await soleApprover();
1038
1042
  const link = conversationLink(review.patientCode);
1039
1043
  if (!link) throw new Error('missing the interface URL for the chat link');
1040
- const alarm = (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1044
+ const alarm = (alarmId && review.alarms?.find((raised) => raised.alarmId === alarmId))
1045
+ ?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
1041
1046
  const symptom = inlineOf(alarm?.symptom);
1042
1047
  const urgency = urgencyLevel.toUpperCase();
1043
1048
  const patient = `${identity.patientName} (${identity.treatingDoctor})`;
@@ -1241,6 +1246,37 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1241
1246
  return updated;
1242
1247
  }
1243
1248
 
1249
+ async function fallbackRecipient() {
1250
+ const phone = String(runtimeConfig.get('ESCALATION_FALLBACK_ALERT_PHONE', '') ?? '').trim();
1251
+ return phone ? { name: null, email: null, phone } : soleApprover();
1252
+ }
1253
+
1254
+ // Airtable alerts the team only once its emergencies row exists; when that write failed, nexus alerts instead.
1255
+ async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel, now = new Date() }) {
1256
+ if (escalationApproverAlertLive() || !ALERT_MARKS[urgencyLevel]) return null;
1257
+ let review;
1258
+ let delivery;
1259
+ try {
1260
+ review = await loadReview(reviewIdOf(reviewId));
1261
+ const recipient = await fallbackRecipient();
1262
+ const { approver, message } = await prepareDoctorAlert(review, urgencyLevel, { recipient, alarmId });
1263
+ delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
1264
+ } catch (error) {
1265
+ delivery = { error: redactedError(error) };
1266
+ logger.error('[EscalationReview] The alert for a missing emergencies row was not sent', { escalationReviewId: String(reviewId), urgencyLevel, error: delivery.error });
1267
+ }
1268
+ if (!review) return null;
1269
+ const sent = { kind: 'fallback', urgencyLevel, transport: null, messageId: null, physicianEmail: null, error: null, ...delivery, sentAt: now };
1270
+ try {
1271
+ const updated = await getEscalationReview().findOneAndUpdate({ _id: review._id }, { $push: { doctorAlerts: sent } }, { ...BOOKKEEPING, new: true }).lean();
1272
+ await audit(updated ?? review, ALERT_OPERATOR, null, { action: 'emergency_row_fallback_alerted', urgencyLevel, delivered: !sent.error, transport: sent.transport });
1273
+ return updated;
1274
+ } catch (error) {
1275
+ logger.error('[EscalationReview] The fallback alert was not recorded', { escalationReviewId: String(reviewId), error: redactedError(error) });
1276
+ return null;
1277
+ }
1278
+ }
1279
+
1244
1280
  async function reopenFromFollowUp(review, reason) {
1245
1281
  const reopened = await getEscalationReview()
1246
1282
  .findOneAndUpdate({ _id: review._id, status: review.status }, { $set: { status: 'documenting', updatedSinceSeen: true } }, { new: true })
@@ -1353,6 +1389,8 @@ async function generateBotDraft({ id, lease = null } = {}) {
1353
1389
  protocolVersion: draft.protocolVersion,
1354
1390
  keyQuestions: draft.keyQuestions,
1355
1391
  unassessedRedFlags: draft.unassessedRedFlags,
1392
+ urgentUnassessedRedFlags: draft.urgentUnassessedRedFlags,
1393
+ unobtainableRedFlags: draft.unobtainableRedFlags,
1356
1394
  missingCharacterization: draft.missingCharacterization,
1357
1395
  ...(draft.suggestCall && { suggestCall: draft.suggestCall }),
1358
1396
  ...(draft.sectionsUnavailable?.length && { sectionsUnavailable: draft.sectionsUnavailable }),
@@ -2068,7 +2106,11 @@ module.exports = {
2068
2106
  PRE_DECISION_STATUSES,
2069
2107
  _resetEscalationReviewIndexes,
2070
2108
  addCallLog,
2109
+ caseTakenReason,
2110
+ currentAlarms,
2111
+ doctorIdentity,
2071
2112
  addDraft,
2113
+ alertWithoutEmergencyRow,
2072
2114
  attachEmergencyRow,
2073
2115
  cancelEscalationReview,
2074
2116
  closeEscalationReview,
@@ -0,0 +1,79 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+ const { getEscalationReview } = require('../models/escalationReviewModel');
4
+
5
+ const { logPatientChange } = require('./patientService');
6
+ const { BOOKKEEPING, DOCUMENTING_STATUSES, PRE_DECISION_STATUSES, caseTakenReason } = require('./escalationReviewService');
7
+
8
+ const UNANSWERED_MINUTES = { asap: 15, urgent: 60 };
9
+ const OPERATOR = 'bot:gravePending';
10
+ const AUDIT_SOURCE = 'escalation_review';
11
+
12
+ const keyOf = (flag) => String(flag ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
13
+ const keysOf = (flags) => [...new Set((flags ?? []).map(keyOf).filter(Boolean))];
14
+
15
+ // The urgent red flags still pending in the latest draft of this episode, and since when each has been pending without a break.
16
+ function pendingFlagsOf(review, since) {
17
+ // A draft written before these fields existed says nothing about the flags, so it neither clears nor starts a wait.
18
+ const drafts = (review.drafts ?? [])
19
+ .filter((draft) => new Date(draft.createdAt).getTime() >= since.getTime() && Array.isArray(draft.urgentUnassessedRedFlags));
20
+ const firstSeen = new Map();
21
+ for (const draft of drafts) {
22
+ const pending = keysOf(draft.urgentUnassessedRedFlags);
23
+ for (const flag of [...firstSeen.keys()]) if (!pending.includes(flag)) firstSeen.delete(flag);
24
+ for (const flag of pending) if (!firstSeen.has(flag)) firstSeen.set(flag, new Date(draft.createdAt));
25
+ }
26
+ const unobtainable = keysOf(drafts.at(-1)?.unobtainableRedFlags);
27
+ return { latest: drafts.at(-1) ?? null, flags: [...firstSeen].map(([flag, firstSeenAt]) => ({ flag, firstSeenAt, unobtainable: unobtainable.includes(flag) })) };
28
+ }
29
+
30
+ // The latest draft speaks for the case only while no newer patient turn or redraft is waiting to replace it.
31
+ const isCurrent = (review, latest) => !review.draftDueAt
32
+ && !(review.updates ?? []).some((update) => new Date(update.at).getTime() > new Date(latest.createdAt).getTime());
33
+
34
+ // A grave datum becomes C at once when the patient cannot give it, or once it stays unanswered past the level's limit.
35
+ function graveMissingOf(review, clock, now) {
36
+ const limit = UNANSWERED_MINUTES[clock?.level];
37
+ if (!limit) return [];
38
+ const { latest, flags } = pendingFlagsOf(review, clock.since);
39
+ if (!latest || !isCurrent(review, latest)) return [];
40
+ // Once the case left documenting (with the doctor) no new draft comes, so the wait no longer means unanswered.
41
+ const waiting = DOCUMENTING_STATUSES.includes(review.status);
42
+ return flags.flatMap(({ flag, firstSeenAt, unobtainable }) => {
43
+ if (unobtainable) return [{ flag, firstSeenAt, reason: 'unobtainable' }];
44
+ return waiting && now.getTime() - firstSeenAt.getTime() >= limit * 60 * 1000 ? [{ flag, firstSeenAt, reason: 'unanswered' }] : [];
45
+ });
46
+ }
47
+
48
+ const recordedFor = (review, clock, flag) => (review.graveAlerts ?? [])
49
+ .some((entry) => entry.flag === flag && new Date(entry.since).getTime() === clock.since.getTime());
50
+
51
+ // Shadow only: records when a grave datum would have gone to C and who would have been alerted, without alerting anyone.
52
+ async function recordGraveMissing(review, clock, now) {
53
+ const missing = graveMissingOf(review, clock, now).filter(({ flag }) => !recordedFor(review, clock, flag));
54
+ if (!missing.length) return 0;
55
+ const taken = await caseTakenReason(review, clock.since, clock.level);
56
+ let recorded = 0;
57
+ for (const { flag, firstSeenAt, reason } of missing) {
58
+ const entry = { flag, level: clock.level, since: clock.since, firstSeenAt, reason, takenReason: taken, audience: taken ? 'group_doctor' : 'all', shadow: true, at: now };
59
+ const claimed = await getEscalationReview().updateOne(
60
+ { _id: review._id, closedAt: null, status: { $in: PRE_DECISION_STATUSES }, graveAlerts: { $not: { $elemMatch: { flag, since: clock.since } } } },
61
+ { $push: { graveAlerts: entry } },
62
+ BOOKKEEPING,
63
+ );
64
+ if (!claimed.modifiedCount) continue;
65
+ recorded += 1;
66
+ await logPatientChange({
67
+ code: review.patientCode,
68
+ updatedBy: OPERATOR,
69
+ source: AUDIT_SOURCE,
70
+ requestId: null,
71
+ changes: { escalationReviewId: String(review._id), action: 'grave_missing_shadow', urgencyLevel: clock.level, reason, audience: entry.audience, takenReason: taken },
72
+ }).catch((error) => logger.error('[GravePending] The shadow audit was not written', {
73
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
74
+ }));
75
+ }
76
+ return recorded;
77
+ }
78
+
79
+ module.exports = { graveMissingOf, recordGraveMissing };
@@ -4,6 +4,7 @@ const { withTimeout } = require('../utils/timeoutUtils');
4
4
  const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
 
6
6
  const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
7
+ const { sweepUntakenAlerts } = require('./untakenAlertService');
7
8
 
8
9
  const SWEEP_LIMIT = 10;
9
10
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
@@ -19,7 +20,7 @@ const dueQuery = (now) => ({
19
20
  {
20
21
  doctorAlertDueAt: null,
21
22
  status: { $in: PRE_DECISION_STATUSES },
22
- 'doctorAlerts.0': { $exists: false },
23
+ doctorAlerts: { $not: { $elemMatch: { kind: 'initial' } } },
23
24
  alarms: { $elemMatch: { urgencyLevel: { $in: ALERTED_URGENCIES }, raisedAt: { $gte: new Date(now.getTime() - SELF_HEAL_WINDOW_MS) } } },
24
25
  },
25
26
  ],
@@ -82,7 +83,17 @@ const sweeper = createIntervalSweeper({
82
83
  defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
83
84
  });
84
85
 
85
- const startReviewAlertSweep = (options) => sweeper.start(options);
86
- const stopReviewAlertSweep = () => sweeper.stop();
86
+ // Its own sweeper, so a slow doctor alert never holds the untaken alerts back.
87
+ const untakenSweeper = createIntervalSweeper({
88
+ label: '[UntakenAlertSweep]',
89
+ sweep: () => sweepUntakenAlerts(),
90
+ defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
91
+ });
92
+
93
+ const startReviewAlertSweep = (options) => {
94
+ untakenSweeper.start(options);
95
+ return sweeper.start(options);
96
+ };
97
+ const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop()]);
87
98
 
88
99
  module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
@@ -7,6 +7,8 @@ const MAX_RESPONSE_MINUTES = 7 * 24 * 60;
7
7
  const BUSINESS_HOURS_LEVELS = ['urgent', 'routine'];
8
8
  const TEAM_TIMEZONE = 'America/Mexico_City';
9
9
  const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5], startHour: 8, endHour: 20 };
10
+ const UNTAKEN_STAGES = { stat: ['deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
11
+ const DEFAULT_PATIENT_TIMER_MINUTES = 15;
10
12
 
11
13
  const rankOf = (level) => URGENCY_RANK[level] || 0;
12
14
  const timeOf = (value) => (value ? new Date(value).getTime() : NaN);
@@ -57,12 +59,25 @@ function effectiveUrgencyOf(review) {
57
59
  return lead ? { urgency: lead.level, symptom: lead.alarm.symptom ?? null } : null;
58
60
  }
59
61
 
60
- function dueAtFor(from, level, policy) {
61
- const minutes = policy.responseMinutes[level];
62
+ function dueAtFor(from, level, policy, minutes = policy.responseMinutes[level]) {
62
63
  if (BUSINESS_HOURS_LEVELS.includes(level)) return addWorkingMinutes(new Date(from), minutes, policy.teamHours);
63
64
  return new Date(timeOf(from) + minutes * 60 * 1000);
64
65
  }
65
66
 
67
+ const patientTimerMinutes = () => {
68
+ const minutes = Number(runtimeConfig.get('ESCALATION_PATIENT_TIMER_MINUTES', DEFAULT_PATIENT_TIMER_MINUTES));
69
+ return Number.isFinite(minutes) && minutes > 0 ? minutes : DEFAULT_PATIENT_TIMER_MINUTES;
70
+ };
71
+
72
+ // Untaken alerts: asap at the patient prompt's timer, asap and urgent at half the response time, and every level at the deadline.
73
+ function untakenStagesOf(level, since, policy) {
74
+ const total = policy.responseMinutes[level];
75
+ const minutesOf = { early: patientTimerMinutes(), half: total / 2, deadline: total };
76
+ return (UNTAKEN_STAGES[level] ?? [])
77
+ .filter((stage) => stage !== 'early' || minutesOf.early < minutesOf.half)
78
+ .map((stage) => ({ stage, minutes: minutesOf[stage], totalMinutes: total, dueAt: dueAtFor(since, level, policy, minutesOf[stage]) }));
79
+ }
80
+
66
81
  function responseDeadlineOf(review, policy) {
67
82
  if (review.closedAt || FOLLOWUP_STATUSES.includes(review.status)) return null;
68
83
  const decidedAt = timeOf((review.decisions ?? []).at(-1)?.createdAt);
@@ -76,7 +91,10 @@ function responseDeadlineOf(review, policy) {
76
91
  }
77
92
 
78
93
  module.exports = {
94
+ BUSINESS_HOURS_LEVELS,
79
95
  effectiveUrgencyOf,
80
96
  responseDeadlineOf,
97
+ patientTimerMinutes,
81
98
  responseDeadlinePolicy,
99
+ untakenStagesOf,
82
100
  };
@@ -0,0 +1,79 @@
1
+ const axios = require('axios');
2
+
3
+ const runtimeConfig = require('../config/runtimeConfig');
4
+ const { logger } = require('../utils/logger');
5
+ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
6
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
8
+
9
+ const WHAPI_MESSAGES_URL = 'https://gate.whapi.cloud/messages/text';
10
+ const REQUEST_TIMEOUT_MS = 15000;
11
+ const ALERT_TEMPLATE_KEY = 'ESCALATION_TEAM_ALERT_CONTENT_SID';
12
+
13
+ const getMessaging = () => require('../core/NexusMessaging');
14
+
15
+ const whatsAppCodeOf = (phone) => ensureWhatsAppFormat(String(phone ?? '').replace(/[^\d+]/g, ''));
16
+
17
+ const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
18
+
19
+ function teamPhones() {
20
+ return String(runtimeConfig.get('ESCALATION_TEAM_ALERT_PHONES', '') ?? '')
21
+ .split(',')
22
+ .map((phone) => phone.trim())
23
+ .filter(Boolean)
24
+ .map(whatsAppCodeOf)
25
+ .filter((code) => PATIENT_CODE.test(code));
26
+ }
27
+
28
+ // Inside the 24-hour window the plain text goes out; outside it, the approved alert template.
29
+ async function sendAlertTo({ code, message, operator }) {
30
+ const inWindow = await isWithin24HourWindow(code);
31
+ const contentSid = inWindow ? null : runtimeConfig.get(ALERT_TEMPLATE_KEY);
32
+ if (!inWindow && !contentSid) throw new Error(`${ALERT_TEMPLATE_KEY} is not configured`);
33
+ const outgoing = inWindow
34
+ ? { code, body: message.body, triggeredBy: operator }
35
+ : { code, contentSid, variables: message.template, triggeredBy: operator };
36
+ const result = await getMessaging().sendMessage(outgoing);
37
+ if (!result?.success && !result?.completed) throw new Error('The WhatsApp alert could not be sent');
38
+ if (result?.deferred) throw new Error('The WhatsApp alert was queued for template approval, not sent');
39
+ return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
40
+ }
41
+
42
+ async function sendToGroup(body) {
43
+ const token = runtimeConfig.get('WHAPI_TOKEN');
44
+ const group = runtimeConfig.get('ESCALATION_TEAM_GROUP_ID');
45
+ if (!token || !group) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
46
+ try {
47
+ const res = await axios({
48
+ url: WHAPI_MESSAGES_URL,
49
+ method: 'POST',
50
+ data: { to: group, body },
51
+ timeout: REQUEST_TIMEOUT_MS,
52
+ headers: { authorization: `Bearer ${token}` },
53
+ validateStatus: () => true,
54
+ });
55
+ if (res.status >= 200 && res.status < 300) return { delivered: true, error: null };
56
+ return { delivered: false, error: `whapi responded ${res.status}` };
57
+ } catch (error) {
58
+ return { delivered: false, error: redacted(error) };
59
+ }
60
+ }
61
+
62
+ // Alerts the team group and every on-call phone. One failed recipient never stops the others,
63
+ // and nothing throws: the caller records what reached whom.
64
+ async function sendTeamAlert({ message, operator }) {
65
+ const group = await sendToGroup(message.body);
66
+ const phones = [];
67
+ for (const code of teamPhones()) {
68
+ try {
69
+ phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator })) });
70
+ } catch (error) {
71
+ phones.push({ code, delivered: false, transport: null, messageId: null, error: redacted(error) });
72
+ }
73
+ }
74
+ const delivered = (group.delivered ? 1 : 0) + phones.filter((phone) => phone.delivered).length;
75
+ if (!delivered) logger.error('[TeamAlert] The team alert reached no one', { groupError: group.error, phones: phones.length });
76
+ return { group, phones, delivered };
77
+ }
78
+
79
+ module.exports = { sendTeamAlert, teamPhones };
@@ -0,0 +1,197 @@
1
+ const { inlineOf } = require('../utils/coercionUtils');
2
+ const { logger } = require('../utils/logger');
3
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
+ const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
+ const { conversationLink } = require('../clinical/services/clinicalAirtableService');
6
+ const { escalationGravePendingShadow, escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
7
+
8
+ const { getPatientInformation, logPatientChange } = require('./patientService');
9
+ const { BUSINESS_HOURS_LEVELS, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
10
+ const { BOOKKEEPING, PRE_DECISION_STATUSES, caseTakenReason, currentAlarms, doctorIdentity } = require('./escalationReviewService');
11
+ const { recordGraveMissing } = require('./gravePendingService');
12
+ const { sendTeamAlert } = require('./teamAlertService');
13
+
14
+ const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
15
+ const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
16
+ // A stage reached this late (an outage, a deploy) is not sent.
17
+ const STALE_MS = 30 * 60 * 1000;
18
+ const SWEEP_LIMIT = 200;
19
+ const OPERATOR = 'bot:untakenAlert';
20
+ const AUDIT_SOURCE = 'escalation_review';
21
+ const LEVEL_LABELS = { stat: 'STAT', asap: 'ASAP', urgent: 'URGENT' };
22
+ const ACTIONS = {
23
+ stat: 'Llamar ahora y registrar la llamada',
24
+ asap: 'Tomar el caso: escribir o llamar y registrar la llamada',
25
+ urgent: 'Tomar el caso: escribir o llamar y registrar la llamada',
26
+ };
27
+ const NO_NAME = 'sin nombre registrado';
28
+ const NO_DOCTOR = 'sin médico registrado';
29
+ const NO_LINK = 'abrir el chat en la plataforma';
30
+ const MAX_QUESTION_LENGTH = 200;
31
+
32
+ const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
33
+
34
+ // A WhatsApp template variable cannot hold a line break.
35
+ const oneLine = (value) => inlineOf(value).replace(/\s+/g, ' ');
36
+
37
+ const duration = (minutes) => {
38
+ const hours = Math.floor(minutes / 60);
39
+ const rest = Math.round(minutes % 60);
40
+ if (!hours) return `${rest} min`;
41
+ return rest ? `${hours} h ${rest} min` : `${hours} h`;
42
+ };
43
+
44
+ // The clock runs at the highest level raised since the last decision, from the first alarm at that level.
45
+ function untakenClockOf(review, policy) {
46
+ const alarms = currentAlarms(review).filter((alarm) => UNTAKEN_LEVELS.includes(appliedLevelOf(alarm)));
47
+ const level = alarms.reduce((top, alarm) => (
48
+ URGENCY_RANK[appliedLevelOf(alarm)] > (URGENCY_RANK[top] || 0) ? appliedLevelOf(alarm) : top
49
+ ), null);
50
+ if (!level) return null;
51
+ const since = new Date(alarms.find((alarm) => appliedLevelOf(alarm) === level).raisedAt);
52
+ return { level, since, symptom: oneLine(alarms.findLast((alarm) => appliedLevelOf(alarm) === level).symptom), stages: untakenStagesOf(level, since, policy) };
53
+ }
54
+
55
+ const sameStage = (clock, stage) => ({ level: clock.level, stage: stage.stage, since: clock.since });
56
+
57
+ function dueStageOf(review, clock, now) {
58
+ const due = clock.stages.filter((stage) => stage.dueAt && stage.dueAt <= now).at(-1);
59
+ if (!due || now.getTime() - due.dueAt.getTime() > STALE_MS) return null;
60
+ const recorded = (review.untakenAlerts ?? []).some((entry) => entry.level === clock.level
61
+ && entry.stage === due.stage && new Date(entry.since).getTime() === clock.since.getTime());
62
+ return recorded ? null : due;
63
+ }
64
+
65
+ function deadlineText(clock, stage) {
66
+ const hours = BUSINESS_HOURS_LEVELS.includes(clock.level) ? ' hábiles' : '';
67
+ return stage.stage === 'deadline'
68
+ ? `venció el plazo de ${duration(stage.totalMinutes)}${hours}`
69
+ : `vence en ${duration(stage.totalMinutes - stage.minutes)}${hours}`;
70
+ }
71
+
72
+ // The first key question of a draft written since the clock started; an older draft is about another moment.
73
+ function pendingQuestionOf(review, clock) {
74
+ const draft = (review.drafts ?? []).at(-1);
75
+ if (!draft || new Date(draft.createdAt).getTime() < clock.since.getTime()) return null;
76
+ const question = oneLine(draft.keyQuestions?.[0]);
77
+ return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
78
+ }
79
+
80
+ async function identityOf(review) {
81
+ try {
82
+ return doctorIdentity(await getPatientInformation(review.patientCode));
83
+ } catch (error) {
84
+ logger.error('[UntakenAlert] The patient record could not be read; the alert goes out without the name', {
85
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
86
+ });
87
+ return { patientName: '', treatingDoctor: '' };
88
+ }
89
+ }
90
+
91
+ async function untakenMessage(review, clock, stage) {
92
+ const { patientName, treatingDoctor } = await identityOf(review);
93
+ const patient = patientName || NO_NAME;
94
+ const doctor = treatingDoctor || NO_DOCTOR;
95
+ const link = conversationLink(review.patientCode) || NO_LINK;
96
+ const deadline = deadlineText(clock, stage);
97
+ const level = LEVEL_LABELS[clock.level];
98
+ const action = ACTIONS[clock.level];
99
+ const question = pendingQuestionOf(review, clock);
100
+ return {
101
+ body: [
102
+ `⏰ ${level} sin tomar · ${deadline}`,
103
+ [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
104
+ question && `Falta saber: ${question}`,
105
+ `Qué hacer: ${action}`,
106
+ link,
107
+ ].filter(Boolean).join('\n'),
108
+ template: {
109
+ 1: `${level}, ${deadline}${clock.symptom ? ` (${clock.symptom})` : ''}`,
110
+ 2: patient,
111
+ 3: doctor,
112
+ 4: question ? `Falta saber: ${question} · ${action}` : action,
113
+ 5: link,
114
+ },
115
+ };
116
+ }
117
+
118
+ const audit = (review, changes) => logPatientChange({
119
+ code: review.patientCode,
120
+ updatedBy: OPERATOR,
121
+ source: AUDIT_SOURCE,
122
+ requestId: null,
123
+ changes: { escalationReviewId: String(review._id), ...changes },
124
+ });
125
+
126
+ // Claims the stage on the review before sending, so two sweeps never alert the team twice for it.
127
+ async function claimStage(review, clock, stage, now, skippedReason = null) {
128
+ const key = sameStage(clock, stage);
129
+ const claimed = await getEscalationReview().updateOne(
130
+ { _id: review._id, closedAt: null, status: { $in: PRE_DECISION_STATUSES }, untakenAlerts: { $not: { $elemMatch: key } } },
131
+ { $push: { untakenAlerts: { ...key, dueAt: stage.dueAt, skippedReason, sentAt: now } } },
132
+ BOOKKEEPING,
133
+ );
134
+ return claimed.modifiedCount > 0;
135
+ }
136
+
137
+ async function alertIfUntaken(review, clock, stage, now) {
138
+ const taken = await caseTakenReason(review, clock.since, clock.level);
139
+ if (taken) {
140
+ await claimStage(review, clock, stage, now, taken);
141
+ return false;
142
+ }
143
+ const message = await untakenMessage(review, clock, stage);
144
+ if (!await claimStage(review, clock, stage, now)) return false;
145
+ const result = await sendTeamAlert({ message, operator: OPERATOR });
146
+ const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
147
+ await getEscalationReview().updateOne(
148
+ { _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
149
+ { $set: {
150
+ 'untakenAlerts.$.delivered': result.delivered,
151
+ 'untakenAlerts.$.groupDelivered': result.group.delivered,
152
+ 'untakenAlerts.$.phonesDelivered': phonesDelivered,
153
+ 'untakenAlerts.$.phones': result.phones.length,
154
+ } },
155
+ BOOKKEEPING,
156
+ );
157
+ await audit(review, {
158
+ action: 'untaken_team_alerted', urgencyLevel: clock.level, stage: stage.stage,
159
+ delivered: result.delivered, groupDelivered: result.group.delivered, phonesDelivered, phones: result.phones.length,
160
+ });
161
+ return true;
162
+ }
163
+
164
+ // Alerts the whole team at each stage of a case nobody took (asap also at the patient timer); being with the doctor is not taken.
165
+ async function sweepUntakenAlerts({ now = new Date() } = {}) {
166
+ const alerts = escalationUntakenAlertsLive();
167
+ const graveShadow = escalationGravePendingShadow();
168
+ if (!alerts && !graveShadow) return 0;
169
+ const reviews = await getEscalationReview()
170
+ .find({
171
+ closedAt: null,
172
+ status: { $in: PRE_DECISION_STATUSES },
173
+ alarms: { $elemMatch: { raisedAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
174
+ }, { patientCode: 1, status: 1, closedAt: 1, alarms: 1, decisions: 1, urgencyReclassifications: 1, callLogs: 1, untakenAlerts: 1, graveAlerts: 1, draftDueAt: 1, 'updates.at': 1,
175
+ 'drafts.createdAt': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
176
+ })
177
+ .sort({ _id: -1 })
178
+ .limit(SWEEP_LIMIT)
179
+ .lean();
180
+ const policy = responseDeadlinePolicy();
181
+ let sent = 0;
182
+ for (const review of reviews) {
183
+ try {
184
+ const clock = untakenClockOf(review, policy);
185
+ const stage = alerts && clock && dueStageOf(review, clock, now);
186
+ if (stage && await alertIfUntaken(review, clock, stage, now)) sent += 1;
187
+ if (graveShadow && clock) await recordGraveMissing(review, clock, now);
188
+ } catch (error) {
189
+ logger.error('[UntakenAlert] Could not check a review for an untaken alert', {
190
+ escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
191
+ });
192
+ }
193
+ }
194
+ return sent;
195
+ }
196
+
197
+ module.exports = { sweepUntakenAlerts, untakenClockOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.0-dev.15739",
3
+ "version": "6.0.0-dev.15839",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",