@peopl-health/nexus 6.5.6 → 6.5.7

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.
@@ -229,14 +229,14 @@ function briefCaseLine(identity, entry, alarmSymptom) {
229
229
  }
230
230
 
231
231
  // The four lines of the doctor's alert; each is a template variable, so none may be empty.
232
- function doctorBrief({ kind, change = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
232
+ function doctorBrief({ kind, change = null, reminder = null, level, identity, draft, alarmSymptom = null, deadline = null, now = new Date(), timeZone, link }) {
233
233
  const entry = briefSymptomOf(draft, alarmSymptom);
234
234
  // A grave flag present asks for an assessment whoever sends the case, not only the bot's act_now.
235
235
  const actNow = kind === 'act_now' || namedFlags(draft?.urgentPresentRedFlags).length > 0;
236
236
  const verb = actNow ? BRIEF_VERBS.act_now : (briefDrugs(draft).length ? BRIEF_VERBS.proposal : BRIEF_VERBS.indication);
237
237
  const mark = actNow ? '🔴' : BRIEF_MARKS[level];
238
238
  return [
239
- [[mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
239
+ [reminder, [mark, change ? `Cambió: ${verb}` : verb].filter(Boolean).join(' '), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · '),
240
240
  briefCaseLine(identity, entry, alarmSymptom),
241
241
  briefKeyLine(draft, entry, change === 'level' ? `Subió a ${URGENCY_LABELS[level]}` : null),
242
242
  link,
@@ -47,7 +47,7 @@ const impressionUpdateSchema = new mongoose.Schema({
47
47
  }, { _id: false });
48
48
 
49
49
  const doctorAlertSchema = new mongoose.Schema({
50
- kind: { type: String, enum: ['initial', 'realert', 'patient_prompt', 'fallback'], required: true },
50
+ kind: { type: String, enum: ['initial', 'realert', 'patient_prompt', 'fallback', 'reminder'], required: true },
51
51
  urgencyLevel: { type: String, enum: URGENCY_LEVELS, default: null },
52
52
  physicianEmail: { type: String, default: null },
53
53
  transport: { type: String, default: null },
@@ -114,6 +114,10 @@ const audit = (review, delivered) => logPatientChange({
114
114
  changes: { escalationReviewId: String(review._id), action: delivered ? 'doctor_digest_sent' : 'doctor_digest_failed' },
115
115
  }).catch((error) => logger.error('[DoctorDigest] The audit was not written', { escalationReviewId: String(review._id), error: redacted(error) }));
116
116
 
117
+ // A case whose doctor's phone already rang after it was queued (a grave flag on an update) is not repeated.
118
+ const digestStillDue = (review) => Boolean(review.digestQueuedAt) && !review.digestSentAt && !(review.doctorHandoffs ?? [])
119
+ .some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime());
120
+
117
121
  // Sends the queued urgent cases still waiting for the doctor in one message per few cases, once the digest is due.
118
122
  async function sendDueDoctorDigests({ now = new Date() } = {}) {
119
123
  if (!urgentDigestLive()) return 0;
@@ -122,9 +126,7 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
122
126
  .find({ closedAt: null, status: 'awaiting_doctor', digestQueuedAt: { $ne: null }, digestSentAt: null, ...unclaimed })
123
127
  .sort({ digestQueuedAt: 1 })
124
128
  .lean();
125
- // A case whose doctor's phone already rang after it was queued (a grave flag on an update) is not repeated.
126
- const queued = found.filter((review) => !(review.doctorHandoffs ?? [])
127
- .some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime()));
129
+ const queued = found.filter(digestStillDue);
128
130
  if (!queued.length) return 0;
129
131
  const policy = responseDeadlinePolicy();
130
132
  // Dropping cases only delays the digest, so nothing is read from the patient records before any of them is due.
@@ -171,4 +173,4 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
171
173
  return sent;
172
174
  }
173
175
 
174
- module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
176
+ module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
@@ -1798,7 +1798,7 @@ async function soleApprover() {
1798
1798
  return approvers[0];
1799
1799
  }
1800
1800
 
1801
- function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change }) {
1801
+ function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null }) {
1802
1802
  const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
1803
1803
  // A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
1804
1804
  if (briefSid && draft.symptoms?.length) {
@@ -1807,6 +1807,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1807
1807
  const lines = doctorBrief({
1808
1808
  kind,
1809
1809
  change,
1810
+ reminder,
1810
1811
  level: level ?? lead?.urgency,
1811
1812
  identity,
1812
1813
  draft,
@@ -1817,17 +1818,30 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1817
1818
  });
1818
1819
  return { body: lines.join('\n'), template: Object.fromEntries(lines.map((line, index) => [index + 1, line])), contentSid: briefSid };
1819
1820
  }
1820
- const headline = kind && doctorAlertHeadline({ review, kind, note, level, symptom });
1821
+ const opener = [reminder, note].filter(Boolean).join(' · ') || null;
1822
+ const headline = kind && doctorAlertHeadline({ review, kind, note: opener, level, symptom });
1821
1823
  const kindSid = kind ? runtimeConfig.get(DOCTOR_ALERT_TEMPLATE_KEYS[kind]) : null;
1822
1824
  return {
1823
- body: [headline ? doctorAlertOpener(kind, headline) : note, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
1825
+ body: [headline ? doctorAlertOpener(kind, headline) : opener, renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link })].filter(Boolean).join('\n\n'),
1824
1826
  template: kindSid
1825
1827
  ? { 1: headline, 2: oneLineOf(identity.patientName), 3: oneLineOf(identity.treatingDoctor), 4: link }
1826
- : { 1: oneLineOf(identity.patientName), 2: oneLineOf(identity.treatingDoctor), 3: oneLineOf([templateSummary(review, { level, symptom }), note].filter(Boolean).join(' · ')), 4: link },
1828
+ : { 1: oneLineOf(identity.patientName), 2: oneLineOf(identity.treatingDoctor), 3: oneLineOf([templateSummary(review, { level, symptom }), opener].filter(Boolean).join(' · ')), 4: link },
1827
1829
  ...(kindSid && { contentSid: kindSid }),
1828
1830
  };
1829
1831
  }
1830
1832
 
1833
+ async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), operator }) {
1834
+ const review = await loadReview(reviewIdOf(id));
1835
+ const handoff = (review.doctorHandoffs ?? []).at(-1);
1836
+ const approver = handoff?.physicianEmail ? await getEscalationApprover(handoff.physicianEmail) : await soleApprover();
1837
+ if (!approver) throw httpError(409, 'The case has no approving doctor to remind');
1838
+ const draft = review.drafts[(handoff?.draftNumber ?? review.drafts.length) - 1];
1839
+ const lead = promptAt ? Math.round((new Date(promptAt).getTime() - now.getTime()) / 60000) : 0;
1840
+ const reminder = lead >= 1 ? `⏰ En ${lead} min la paciente recibe los números para llamar` : '⏰ Recordatorio';
1841
+ const message = doctorAlertMessage({ review, draft, identity: await readDoctorIdentity(review), link: doctorLink(review), reminder });
1842
+ return { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
1843
+ }
1844
+
1831
1845
  // With notify false the case is handed over in the platform without a WhatsApp to the doctor; `kind` (act_now, ready) picks the alert the doctor gets.
1832
1846
  async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handoffs = null, note = null, notify = true, kind = null, change = null, level = null, symptom = null, requestId = null } = {}) {
1833
1847
  const reviewId = reviewIdOf(id);
@@ -2517,8 +2531,11 @@ module.exports = {
2517
2531
  PRE_DECISION_STATUSES,
2518
2532
  _resetEscalationReviewIndexes,
2519
2533
  addCallLog,
2534
+ remindDoctorOfCase,
2520
2535
  caseTakenReason,
2536
+ promptedSince,
2521
2537
  currentAlarms,
2538
+ DOCTOR_BRIEF_TEMPLATE_KEY,
2522
2539
  doctorLink,
2523
2540
  teamAlertIdentity,
2524
2541
  addDraft,
@@ -7,9 +7,11 @@ 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, 6, 7], startHour: 9, endHour: 22 };
10
- const UNTAKEN_STAGES = { stat: ['deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
11
- const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20 };
12
- const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES' };
10
+ const UNTAKEN_STAGES = { stat: ['early', 'deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
11
+ const PATIENT_PROMPT_LEAD_MINUTES = 5;
12
+ const URGENT_REMINDER_LEAD_MINUTES = 60;
13
+ const DEFAULT_PATIENT_TIMER_MINUTES = { stat: 15, asap: 20, fever: 15 };
14
+ const PATIENT_TIMER_KEYS = { stat: 'ESCALATION_PATIENT_TIMER_MINUTES', asap: 'ESCALATION_ASAP_PATIENT_TIMER_MINUTES', fever: 'FEVER_PATIENT_TIMER_MINUTES' };
13
15
  const DEFAULT_UNTAKEN_EARLY_MINUTES = 15;
14
16
  const DEFAULT_PENDING_WAIT_MINUTES = { asap: 5, urgent: 60 };
15
17
  const PENDING_WAIT_KEYS = { asap: 'ESCALATION_PENDING_WAIT_MINUTES_ASAP', urgent: 'ESCALATION_PENDING_WAIT_MINUTES_URGENT' };
@@ -85,15 +87,24 @@ const pendingWaitMinutes = (level) => (PENDING_WAIT_KEYS[level] ? positiveMinute
85
87
  const teamOpenAt = (now, policy) => addWorkingMinutes(now, 0, policy.teamHours);
86
88
  const quietReminderMinutes = () => positiveMinutes('ESCALATION_QUIET_REMINDER_MINUTES', DEFAULT_QUIET_REMINDER_MINUTES);
87
89
 
88
- // Untaken alerts: asap early, asap and urgent at half the response time, and every level at the deadline.
89
- function untakenStagesOf(level, since, policy) {
90
+ function untakenStagesOf(level, since, policy, { fever = false } = {}) {
90
91
  const total = policy.responseMinutes[level];
91
- const minutesOf = { early: untakenEarlyMinutes(), half: total / 2, deadline: total };
92
+ const beforePrompt = (timer) => patientTimerMinutes(timer) - PATIENT_PROMPT_LEAD_MINUTES;
93
+ const early = level === 'stat' ? beforePrompt('stat') : Math.min(untakenEarlyMinutes(), fever && beforePrompt('fever') > 0 ? beforePrompt('fever') : Infinity);
94
+ const minutesOf = { early, half: total / 2, deadline: total };
95
+ const fits = { early: early > 0 && early < (level === 'stat' ? total : minutesOf.half), half: true, deadline: true };
92
96
  return (UNTAKEN_STAGES[level] ?? [])
93
- .filter((stage) => stage !== 'early' || minutesOf.early < minutesOf.half)
97
+ .filter((stage) => fits[stage])
94
98
  .map((stage) => ({ stage, minutes: minutesOf[stage], totalMinutes: total, dueAt: dueAtFor(since, level, policy, minutesOf[stage]) }));
95
99
  }
96
100
 
101
+ function doctorReminderAt(level, since, policy, promptAt = null) {
102
+ if (promptAt) return new Date(timeOf(promptAt) - PATIENT_PROMPT_LEAD_MINUTES * 60 * 1000);
103
+ // addWorkingMinutes can land on the closing minute itself, which the team counts as closed.
104
+ if (level === 'urgent') return teamOpenAt(dueAtFor(since, level, policy, policy.responseMinutes.urgent - URGENT_REMINDER_LEAD_MINUTES), policy);
105
+ return untakenStagesOf(level, since, policy).find((stage) => stage.stage === 'early')?.dueAt ?? null;
106
+ }
107
+
97
108
  function responseDeadlineOf(review, policy) {
98
109
  if (review.closedAt || FOLLOWUP_STATUSES.includes(review.status)) return null;
99
110
  const decidedAt = timeOf((review.decisions ?? []).at(-1)?.createdAt);
@@ -108,6 +119,7 @@ function responseDeadlineOf(review, policy) {
108
119
 
109
120
  module.exports = {
110
121
  BUSINESS_HOURS_LEVELS,
122
+ doctorReminderAt,
111
123
  effectiveUrgencyOf,
112
124
  levelsOf,
113
125
  responseDeadlineOf,
@@ -68,14 +68,14 @@ async function rosterMembers(now = Date.now()) {
68
68
  }
69
69
 
70
70
  // With a level, only the members who take that level's untaken alerts; without one, every active member; doctors only when asked.
71
- async function teamPhones(level = null, { withDoctors = true } = {}) {
71
+ async function teamMembers(level = null, { withDoctors = true } = {}) {
72
72
  const members = await rosterMembers();
73
- if (!members) return configuredPhones();
74
- return members
75
- .filter((member) => (!level || member.levels.includes(level)) && (withDoctors || !member.doctor))
76
- .map((member) => member.code);
73
+ if (!members) return configuredPhones().map((code) => ({ code, doctor: false }));
74
+ return members.filter((member) => (!level || member.levels.includes(level)) && (withDoctors || !member.doctor));
77
75
  }
78
76
 
77
+ const teamPhones = async (level = null, options = {}) => (await teamMembers(level, options)).map((member) => member.code);
78
+
79
79
  const _resetRoster = () => {
80
80
  roster = { members: null, readAt: 0 };
81
81
  reading = null;
@@ -130,9 +130,10 @@ async function sendTeamAlert({ message, operator, level = null, notice = false,
130
130
  const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
131
131
  const group = await sendToGroup(message.body, quoted, message.threadBody);
132
132
  const phones = [];
133
- for (const code of await teamPhones(level, { withDoctors })) {
133
+ for (const { code, doctor } of await teamMembers(level, { withDoctors })) {
134
+ const own = doctor && message.doctorMessage;
134
135
  try {
135
- phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator, templateKey })) });
136
+ phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message: own || message, operator, templateKey: own ? own.templateKey : templateKey })) });
136
137
  } catch (error) {
137
138
  phones.push({ code, delivered: false, transport: null, messageId: null, error: redacted(error) });
138
139
  }
@@ -1,16 +1,18 @@
1
+ const runtimeConfig = require('../config/runtimeConfig');
1
2
  const { oneLineOf } = require('../utils/coercionUtils');
2
3
  const { logger } = require('../utils/logger');
3
4
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
+ const { withTimeout } = require('../utils/timeoutUtils');
4
6
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
7
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
6
8
  const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
7
9
 
8
10
  const { logPatientChange } = require('./patientService');
9
- const { BUSINESS_HOURS_LEVELS, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
10
- const { BOOKKEEPING, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, teamAlertIdentity } = require('./escalationReviewService');
11
+ const { BUSINESS_HOURS_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
12
+ const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
11
13
  const { settleCharacterization } = require('./characterizationOutcomeService');
12
14
  const { sendTeamAlert } = require('./teamAlertService');
13
- const { sendDueDoctorDigests } = require('./doctorDigestService');
15
+ const { digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
14
16
 
15
17
  const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
16
18
  const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
@@ -26,8 +28,14 @@ const ACTIONS = {
26
28
  urgent: 'Tomar el caso: escribir o llamar y registrar la llamada',
27
29
  };
28
30
  const MAX_QUESTION_LENGTH = 200;
31
+ const RECENT_DOCTOR_RING_MS = 5 * 60 * 1000;
32
+ const RECENT_DIGEST_MS = 60 * 60 * 1000;
33
+ const MIN_PROMPT_LEAD_MS = 2 * 60 * 1000;
34
+ const REMINDER_RETRY_MS = 3 * 60 * 1000;
35
+ const REMINDER_SEND_TIMEOUT_MS = 60 * 1000;
36
+ const MAX_REMINDER_ATTEMPTS = 3;
29
37
  // Every field the untaken clock, the taken check and the characterization outcome read; the board's case state reads the same.
30
- 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, 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,
38
+ 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,
31
39
  'drafts.createdAt': 1, 'drafts.writtenBy': 1, 'drafts.keyQuestions': 1, 'drafts.urgentUnassessedRedFlags': 1, 'drafts.unobtainableRedFlags': 1,
32
40
  'drafts.urgentPresentRedFlags': 1, 'drafts.sufficientForDoctor': 1, 'drafts.blockingQuestion': 1, 'drafts.blockingFlag': 1,
33
41
  };
@@ -58,7 +66,7 @@ function untakenClockOf(review, policy) {
58
66
  stagesFrom,
59
67
  symptom: oneLineOf(atLevel.at(-1).alarm.symptom),
60
68
  emergencyRecordId: atLevel.find((entry) => entry.alarm.emergencyRecordId)?.alarm.emergencyRecordId ?? null,
61
- stages: untakenStagesOf(level, stagesFrom, policy),
69
+ stages: untakenStagesOf(level, stagesFrom, policy, { fever: level === 'asap' && feverPatientTimerLive() && atLevel.some((entry) => entry.alarm.category === FEVER_CATEGORY) }),
62
70
  };
63
71
  }
64
72
 
@@ -87,33 +95,52 @@ function pendingQuestionOf(review, clock) {
87
95
  return question ? question.slice(0, MAX_QUESTION_LENGTH) : null;
88
96
  }
89
97
 
90
- // The early asap alert says when the armed prompt, the fever one included, gives the patient the numbers.
91
- function patientPromptNote(review, stage, now) {
92
- if (stage.stage !== 'early') return null;
98
+ function patientTimerLiveFor(review) {
93
99
  const fever = currentAlarms(review).some((alarm) => alarm.category === FEVER_CATEGORY);
94
- if (!(fever ? feverPatientTimerLive() : escalationPatientTimerLive())) return null;
95
- // A leased or retried slot (attempts above 0) is already being sent.
96
- if (review.doctorAlertKind !== 'patient_prompt' || (review.doctorAlertAttempts ?? 0) !== 0 || !review.doctorAlertDueAt) return null;
97
- const lead = Math.round((new Date(review.doctorAlertDueAt).getTime() - now.getTime()) / 60000);
100
+ return fever ? feverPatientTimerLive() : escalationPatientTimerLive();
101
+ }
102
+
103
+ // While a send holds the slot (attempts above 0, or a lease) its due time is not the prompt's, so only an untouched slot gives the time.
104
+ const armedPromptAt = (review) => (review.doctorAlertKind === 'patient_prompt' && !review.doctorAlertAttempts ? review.doctorAlertDueAt ?? null : null);
105
+
106
+ const patientPromptAt = (review) => (patientTimerLiveFor(review) ? armedPromptAt(review) : null);
107
+
108
+ function patientPromptNote(review, stage, now) {
109
+ const promptAt = stage.stage === 'early' ? patientPromptAt(review) : null;
110
+ if (!promptAt) return null;
111
+ const lead = Math.round((new Date(promptAt).getTime() - now.getTime()) / 60000);
98
112
  return lead >= 1 ? `Si nadie lo toma, la paciente recibe los números para llamar en ${duration(lead)}` : null;
99
113
  }
100
114
 
115
+ function doctorUntakenMessage(review, clock, { head, note, question, patient, doctor }) {
116
+ const lines = [
117
+ head,
118
+ `${[patient, clock.symptom].filter(Boolean).join(' · ')} (${doctor})`,
119
+ note || (question && `Falta saber: ${question}`) || 'Nadie del equipo lo ha tomado',
120
+ doctorLink(review),
121
+ ];
122
+ return { body: lines.join('\n'), template: Object.fromEntries(lines.map((line, index) => [index + 1, line])), templateKey: DOCTOR_BRIEF_TEMPLATE_KEY };
123
+ }
124
+
101
125
  function untakenMessage(review, clock, stage, now, { patient, doctor, link }) {
102
126
  const deadline = deadlineText(clock, stage);
103
127
  const level = LEVEL_LABELS[clock.level];
104
128
  const action = ACTIONS[clock.level];
105
129
  const question = pendingQuestionOf(review, clock);
106
130
  const note = patientPromptNote(review, stage, now);
131
+ const head = `⏰ ${level} sin tomar · ${deadline}`;
107
132
  return {
133
+ // Without the interface URL the doctor's copy has no link, so the doctors keep the team text.
134
+ ...(runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY) && runtimeConfig.get('PEOPL_INTERFACE_URL') && { doctorMessage: doctorUntakenMessage(review, clock, { head, note, question, patient, doctor }) }),
108
135
  body: [
109
- `⏰ ${level} sin tomar · ${deadline}`,
136
+ head,
110
137
  [`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
111
138
  question && `Falta saber: ${question}`,
112
139
  note,
113
140
  `Qué hacer: ${action}`,
114
141
  link,
115
142
  ].filter(Boolean).join('\n'),
116
- threadBody: [`⏰ ${level} sin tomar · ${deadline}`, question && `Falta saber: ${question}`, note, `Qué hacer: ${action}`].filter(Boolean).join('\n'),
143
+ threadBody: [head, question && `Falta saber: ${question}`, note, `Qué hacer: ${action}`].filter(Boolean).join('\n'),
117
144
  template: {
118
145
  1: `${level}, ${deadline}${clock.symptom ? ` (${clock.symptom})` : ''}`,
119
146
  2: patient,
@@ -143,6 +170,10 @@ async function claimStage(review, clock, stage, now, skippedReason = null) {
143
170
  return claimed.modifiedCount > 0;
144
171
  }
145
172
 
173
+ // A copied handoff reached the doctor outside WhatsApp, so it counts as a ring too.
174
+ const doctorRangSince = (review, since) => (review.doctorHandoffs ?? [])
175
+ .some((handoff) => (handoff.transport || handoff.mode === 'copied') && new Date(handoff.createdAt).getTime() >= since.getTime());
176
+
146
177
  async function alertIfUntaken(review, clock, stage, now) {
147
178
  const taken = await caseTakenReason(review, clock.since, clock.level);
148
179
  if (taken) {
@@ -154,8 +185,9 @@ async function alertIfUntaken(review, clock, stage, now) {
154
185
  // Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
155
186
  const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
156
187
  if (!await claimStage(review, clock, stage, now)) return false;
157
- // A roster doctor gets the levels their sin_tomar lists, like anyone else on the team.
158
- const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: !who.identity.testPatient });
188
+ // Roster doctors get the levels their sin_tomar lists, except on a case already waiting on them, which has its own reminder.
189
+ const withDoctors = !who.identity.testPatient && review.status !== 'awaiting_doctor';
190
+ const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors });
159
191
  const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
160
192
  await getEscalationReview().updateOne(
161
193
  { _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
@@ -174,6 +206,60 @@ async function alertIfUntaken(review, clock, stage, now) {
174
206
  return true;
175
207
  }
176
208
 
209
+ const remindersSince = (review, since) => (review.doctorAlerts ?? [])
210
+ .filter((sent) => sent.kind === 'reminder' && new Date(sent.sentAt).getTime() >= since.getTime());
211
+
212
+ async function remindDoctorIfDue(review, clock, now, policy) {
213
+ if (review.status !== 'awaiting_doctor') return false;
214
+ const promptAt = armedPromptAt(review);
215
+ if (review.doctorAlertKind === 'patient_prompt' && review.doctorAlertAttempts > 0) return false;
216
+ const dueAt = doctorReminderAt(clock.level, clock.stagesFrom, policy, promptAt);
217
+ const deadline = clock.stages.find((stage) => stage.stage === 'deadline').dueAt;
218
+ if (!dueAt || now < dueAt || now.getTime() - dueAt.getTime() > STALE_MS || now >= deadline) return false;
219
+ if ((promptAt && new Date(promptAt).getTime() - now.getTime() < MIN_PROMPT_LEAD_MS) || promptedSince(review, clock.stagesFrom)) return false;
220
+ const retryAfter = new Date(now.getTime() - REMINDER_RETRY_MS);
221
+ const reminders = remindersSince(review, clock.stagesFrom);
222
+ if (reminders.length >= MAX_REMINDER_ATTEMPTS || reminders.some((sent) => sent.transport || sent.possiblyDelivered || new Date(sent.sentAt) > retryAfter)) return false;
223
+ const recent = new Date(now.getTime() - RECENT_DOCTOR_RING_MS);
224
+ const recentDigest = new Date(now.getTime() - RECENT_DIGEST_MS);
225
+ const digestPending = digestStillDue(review) && new Date(review.digestQueuedAt) >= clock.stagesFrom;
226
+ if (digestPending || new Date(review.digestSentAt ?? 0) >= recentDigest || doctorRangSince(review, recent)) return false;
227
+ if (await caseTakenReason(review, clock.since, clock.level)) return false;
228
+ if ((await teamAlertIdentity(review)).identity.testPatient) return false;
229
+ const claimed = await getEscalationReview().updateOne(
230
+ {
231
+ _id: review._id,
232
+ closedAt: null,
233
+ status: 'awaiting_doctor',
234
+ doctorAlerts: { $not: { $elemMatch: { kind: 'reminder', $and: [{ sentAt: { $gte: clock.stagesFrom } }, { $or: [{ transport: { $ne: null } }, { possiblyDelivered: true }, { sentAt: { $gt: retryAfter } }] }] } } },
235
+ doctorHandoffs: { $not: { $elemMatch: { createdAt: { $gte: recent }, $or: [{ transport: { $ne: null } }, { mode: 'copied' }] } } },
236
+ digestSentAt: { $not: { $gte: recentDigest } },
237
+ $nor: [{ doctorAlertKind: 'patient_prompt', doctorAlertAttempts: { $gt: 0 } }],
238
+ feverPromptStartedAt: { $not: { $gte: clock.stagesFrom } },
239
+ decisions: { $not: { $elemMatch: { createdAt: { $gte: clock.since } } } },
240
+ callLogs: { $not: { $elemMatch: { outcome: 'contacted', calledAt: { $gte: clock.since } } } },
241
+ },
242
+ { $push: { doctorAlerts: { kind: 'reminder', urgencyLevel: clock.level, error: null, sentAt: now } } },
243
+ BOOKKEEPING,
244
+ );
245
+ if (!claimed.modifiedCount) return false;
246
+ let delivery;
247
+ try {
248
+ delivery = await withTimeout(remindDoctorOfCase({ id: review._id, promptAt, now, operator: OPERATOR }), REMINDER_SEND_TIMEOUT_MS, 'doctor reminder');
249
+ } catch (error) {
250
+ // A timed-out send may still reach the doctor, so it is not retried.
251
+ delivery = { error: redactDirectIdentifiers(String(error?.message || error)), possiblyDelivered: /timed out/.test(String(error?.message)) };
252
+ logger.error('[UntakenAlert] The doctor reminder was not sent', { escalationReviewId: String(review._id), error: delivery.error });
253
+ }
254
+ await getEscalationReview().updateOne(
255
+ { _id: review._id, doctorAlerts: { $elemMatch: { kind: 'reminder', sentAt: now } } },
256
+ { $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) } },
257
+ BOOKKEEPING,
258
+ );
259
+ await audit(review, { action: 'doctor_reminded', urgencyLevel: clock.level, delivered: !delivery.error, transport: delivery.transport ?? null });
260
+ return !delivery.error;
261
+ }
262
+
177
263
  // Alerts the team at each stage of a case nobody took (being with the doctor is not taken) and settles the bot's characterization.
178
264
  async function sweepUntakenAlerts({ now = new Date() } = {}) {
179
265
  const alerts = escalationUntakenAlertsLive();
@@ -208,11 +294,18 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
208
294
  } catch (error) {
209
295
  failed('[UntakenAlert] Could not check a review for an untaken alert', review, error);
210
296
  }
211
- if (!autoHandoff) continue;
297
+ if (autoHandoff) {
298
+ try {
299
+ await settleCharacterization(review, clock, now);
300
+ } catch (error) {
301
+ failed('[UntakenAlert] Could not settle the characterization of a review', review, error);
302
+ }
303
+ }
304
+ // After the characterization, whose update ring the claim then sees.
212
305
  try {
213
- await settleCharacterization(review, clock, now);
306
+ if (alerts && clock) await remindDoctorIfDue(review, clock, now, policy);
214
307
  } catch (error) {
215
- failed('[UntakenAlert] Could not settle the characterization of a review', review, error);
308
+ failed('[UntakenAlert] Could not check a review for a doctor reminder', review, error);
216
309
  }
217
310
  }
218
311
  if (autoHandoff) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.6",
3
+ "version": "6.5.7",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",