@peopl-health/nexus 6.5.9 → 6.5.11

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,13 +8,13 @@ const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
8
8
  const { doctorDigestLine, doctorDigestTitle } = require('../clinical/helpers/doctorReviewMessageHelper');
9
9
 
10
10
  const { logPatientChange } = require('./patientService');
11
- const { listEscalationApprovers } = require('./physicianService');
12
11
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
13
- const { BOOKKEEPING, doctorLink, teamAlertIdentity } = require('./escalationReviewService');
12
+ const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, doctorAlertMessage, doctorLink, notifiedApprover, teamAlertIdentity } = require('./escalationReviewService');
14
13
 
15
14
  const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
16
- // Until Meta approves this template the earlier digest keeps going out.
15
+ // Meta has not approved this template.
17
16
  const DIGEST_BRIEF_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_BRIEF_CONTENT_SID';
17
+ const ALERT_IDENTIFIED_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID';
18
18
  const DEFAULT_WINDOW_MINUTES = 60;
19
19
  const DEFAULT_LEAD_MINUTES = 120;
20
20
  const MAX_CASES_PER_MESSAGE = 5;
@@ -34,9 +34,9 @@ const redacted = (error) => redactDirectIdentifiers(String(error?.message || err
34
34
  // Urgent cases ready for the doctor go in a digest only once its template exists.
35
35
  const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY));
36
36
 
37
- // The approving doctor's WhatsApp, or null when there is none to send the digest to.
37
+ // The notified approver's WhatsApp, or null when their number is unusable; throws when no single approver can be chosen.
38
38
  async function digestRecipient() {
39
- const [approver] = await listEscalationApprovers();
39
+ const approver = await notifiedApprover();
40
40
  const code = whatsAppCodeFromPhone(approver?.phone);
41
41
  return PATIENT_CODE.test(code) ? code : null;
42
42
  }
@@ -59,13 +59,23 @@ function digestDueAt(reviews, policy) {
59
59
  return teamOpenAt(new Date(Math.min(...times)), policy);
60
60
  }
61
61
 
62
- function digestLines(cases, now, policy) {
63
- const brief = Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
62
+ const briefStyle = () => runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
63
+
64
+ // Like the direct handoff, a case without drafted symptoms needs the full alert's template.
65
+ const perCaseBrief = (inWindow) => !inWindow && !runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY)
66
+ && Boolean(runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY) && runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY));
67
+
68
+ function digestLines(cases, now, policy, perCase) {
64
69
  const lines = [];
65
70
  for (const { review, who: { patient, identity } } of cases) {
66
- if (brief) {
71
+ const named = { ...identity, patientName: identity.patientName || patient };
72
+ if (perCase) {
73
+ lines.push(doctorAlertMessage({ review, draft: review.drafts.at(-1), identity: named, link: doctorLink(review), kind: 'ready', level: 'urgent', now }));
74
+ continue;
75
+ }
76
+ if (briefStyle()) {
67
77
  lines.push(doctorDigestLine({
68
- identity: { ...identity, patientName: identity.patientName || patient },
78
+ identity: named,
69
79
  draft: review.drafts?.at(-1),
70
80
  alarmSymptom: effectiveUrgencyOf(review)?.symptom,
71
81
  deadline: responseDeadlineOf(review, policy)?.dueAt,
@@ -93,14 +103,14 @@ function chunksOf(entries) {
93
103
  return chunks;
94
104
  }
95
105
 
96
- async function sendDigest(code, entries) {
106
+ async function sendDigest(code, entries, inWindow, perCase) {
97
107
  const lines = entries.map(({ line }) => line);
98
- const briefSid = runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY);
99
- const title = briefSid ? doctorDigestTitle(entries.length) : String(entries.length);
100
- const inWindow = await isWithin24HourWindow(code);
101
- const outgoing = inWindow
102
- ? { code, body: (briefSid ? [title, ...lines] : [`🟡 Casos urgentes listos para decidir: ${title}`, '', ...lines]).join('\n'), triggeredBy: OPERATOR }
103
- : { code, contentSid: briefSid || runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: title, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
108
+ const title = !perCase && (briefStyle() ? doctorDigestTitle(entries.length) : String(entries.length));
109
+ const outgoing = perCase
110
+ ? { code, contentSid: lines[0].contentSid || runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY), variables: lines[0].template, triggeredBy: OPERATOR }
111
+ : inWindow
112
+ ? { code, body: (briefStyle() ? [title, ...lines] : [`🟡 Casos urgentes listos para decidir: ${title}`, '', ...lines]).join('\n'), triggeredBy: OPERATOR }
113
+ : { code, contentSid: runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: title, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
104
114
  const result = await getMessaging().sendMessage(outgoing);
105
115
  if (!result?.success && !result?.completed) throw new Error('The doctor digest could not be sent');
106
116
  if (result?.deferred) throw new Error('The doctor digest was queued for template approval, not sent');
@@ -118,7 +128,7 @@ const audit = (review, delivered) => logPatientChange({
118
128
  const digestStillDue = (review) => Boolean(review.digestQueuedAt) && !review.digestSentAt && !(review.doctorHandoffs ?? [])
119
129
  .some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime());
120
130
 
121
- // Sends the queued urgent cases still waiting for the doctor in one message per few cases, once the digest is due.
131
+ // Sends the queued urgent cases still waiting for the doctor in one message per few cases (or one per case, as his alert), once the digest is due.
122
132
  async function sendDueDoctorDigests({ now = new Date() } = {}) {
123
133
  if (!urgentDigestLive()) return 0;
124
134
  const unclaimed = { $or: [{ digestClaimedAt: null }, { digestClaimedAt: { $lt: new Date(now.getTime() - STALE_CLAIM_MS) } }] };
@@ -143,10 +153,13 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
143
153
  logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
144
154
  return 0;
145
155
  }
146
- const lines = digestLines(cases, now, policy);
156
+ const inWindow = await isWithin24HourWindow(code);
157
+ const perCase = perCaseBrief(inWindow);
158
+ const lines = digestLines(cases, now, policy, perCase);
147
159
  let sent = 0;
148
160
  // Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
149
- for (const chunk of chunksOf(cases.map(({ review }, index) => ({ review, line: lines[index] })))) {
161
+ const entries = cases.map(({ review }, index) => ({ review, line: lines[index] }));
162
+ for (const chunk of perCase ? entries.map((entry) => [entry]) : chunksOf(entries)) {
150
163
  const claimed = [];
151
164
  for (const entry of chunk) {
152
165
  const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestSentAt: null, ...unclaimed };
@@ -156,7 +169,7 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
156
169
  const ids = claimed.map(({ review }) => review._id);
157
170
  let delivered = false;
158
171
  try {
159
- await sendDigest(code, claimed);
172
+ await sendDigest(code, claimed, inWindow, perCase);
160
173
  delivered = true;
161
174
  sent += claimed.length;
162
175
  } catch (error) {
@@ -1158,7 +1158,7 @@ const alarmFor = (review, urgencyLevel, alarmId) => (alarmId && (review.alarms ?
1158
1158
  async function prepareDoctorAlert(review, urgencyLevel, { recipient = null, alarmId = null } = {}) {
1159
1159
  const identity = await readDoctorIdentity(review);
1160
1160
  if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
1161
- const approver = recipient ?? await soleApprover();
1161
+ const approver = recipient ?? await notifiedApprover();
1162
1162
  const link = conversationLink(review.patientCode);
1163
1163
  if (!link) throw new Error('missing the interface URL for the chat link');
1164
1164
  const alarm = alarmFor(review, urgencyLevel, alarmId);
@@ -1367,7 +1367,7 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1367
1367
 
1368
1368
  async function fallbackRecipient() {
1369
1369
  const phone = String(runtimeConfig.get('ESCALATION_FALLBACK_ALERT_PHONE', '') ?? '').trim();
1370
- return phone ? { name: null, email: null, phone } : soleApprover();
1370
+ return phone ? { name: null, email: null, phone } : notifiedApprover();
1371
1371
  }
1372
1372
 
1373
1373
  // Who and where for a team alert; a patient record that cannot be read never holds the alert back.
@@ -1787,18 +1787,18 @@ async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId =
1787
1787
  return review;
1788
1788
  }
1789
1789
 
1790
- async function soleApprover() {
1790
+ async function notifiedApprover() {
1791
1791
  const approvers = await listEscalationApprovers();
1792
1792
  if (!approvers.length) {
1793
1793
  throw httpError(409, 'No escalation review approver is configured: tick aprueba_vaiven on a physician with a WhatsApp number');
1794
1794
  }
1795
- if (approvers.length > 1) {
1796
- throw httpError(409, `More than one physician approves escalation reviews; name one of: ${approvers.map((approver) => approver.email).join(', ')}`);
1797
- }
1798
- return approvers[0];
1795
+ if (approvers.length === 1) return approvers[0];
1796
+ const primaries = approvers.filter((approver) => approver.primary);
1797
+ if (primaries.length === 1) return primaries[0];
1798
+ throw httpError(409, `More than one physician approves escalation reviews; name one of: ${approvers.map((approver) => approver.email).join(', ')}, or tick aprobador_principal on exactly one`);
1799
1799
  }
1800
1800
 
1801
- function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null }) {
1801
+ function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, now = new Date() }) {
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) {
@@ -1813,6 +1813,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1813
1813
  draft,
1814
1814
  alarmSymptom: symptom ?? lead?.symptom,
1815
1815
  deadline: responseDeadlineOf(review, policy)?.dueAt,
1816
+ now,
1816
1817
  timeZone: policy.teamHours.timeZone,
1817
1818
  link,
1818
1819
  });
@@ -1833,7 +1834,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1833
1834
  async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), operator }) {
1834
1835
  const review = await loadReview(reviewIdOf(id));
1835
1836
  const handoff = (review.doctorHandoffs ?? []).at(-1);
1836
- const approver = handoff?.physicianEmail ? await getEscalationApprover(handoff.physicianEmail) : await soleApprover();
1837
+ const approver = handoff?.physicianEmail ? await getEscalationApprover(handoff.physicianEmail) : await notifiedApprover();
1837
1838
  if (!approver) throw httpError(409, 'The case has no approving doctor to remind');
1838
1839
  const draft = review.drafts[(handoff?.draftNumber ?? review.drafts.length) - 1];
1839
1840
  const lead = promptAt ? Math.round((new Date(promptAt).getTime() - now.getTime()) / 60000) : 0;
@@ -1855,7 +1856,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
1855
1856
  const draft = review.drafts[draftNumber - 1];
1856
1857
  let approver = null;
1857
1858
  if (mode === 'sent_whatsapp') {
1858
- approver = physicianEmail ? await getEscalationApprover(physicianEmail) : await soleApprover();
1859
+ approver = physicianEmail ? await getEscalationApprover(physicianEmail) : await notifiedApprover();
1859
1860
  if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
1860
1861
  }
1861
1862
 
@@ -2521,6 +2522,7 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
2521
2522
 
2522
2523
  module.exports = {
2523
2524
  BOOKKEEPING,
2525
+ notifiedApprover,
2524
2526
  AUTO_HANDOFF_OPERATOR,
2525
2527
  DOCUMENTING_STATUSES,
2526
2528
  DRAFT_OPERATOR,
@@ -2536,6 +2538,7 @@ module.exports = {
2536
2538
  promptedSince,
2537
2539
  currentAlarms,
2538
2540
  DOCTOR_BRIEF_TEMPLATE_KEY,
2541
+ doctorAlertMessage,
2539
2542
  doctorLink,
2540
2543
  teamAlertIdentity,
2541
2544
  addDraft,
@@ -6,11 +6,13 @@ const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper');
6
6
  const { getRecordByFilter } = require('./airtableService');
7
7
 
8
8
  const APPROVER_FIELDS = ['physician_name', 'email', 'phone_number'];
9
+ const PRIMARY_FIELD = 'aprobador_principal';
9
10
 
10
11
  const approverOf = (physician, email = null) => ({
11
12
  name: physician.physician_name || null,
12
13
  email: email ?? (physician.email ? String(physician.email).trim().toLowerCase() : null),
13
14
  phone: physician.phone_number || null,
15
+ ...(physician[PRIMARY_FIELD] && { primary: true }),
14
16
  });
15
17
 
16
18
  async function getEscalationApprover(email) {
@@ -26,7 +28,7 @@ async function getEscalationApprover(email) {
26
28
 
27
29
  // A physician approves escalations only for the programs ticked on their row.
28
30
  async function listEscalationApprovers() {
29
- const physicians = await getRecordByFilter(Monitoreo_ID, 'physicians', `AND({aprueba_vaiven}, ${programSourceFormula()})`, null, APPROVER_FIELDS, true) || [];
31
+ const physicians = await getRecordByFilter(Monitoreo_ID, 'physicians', `AND({aprueba_vaiven}, ${programSourceFormula()})`, null, [...APPROVER_FIELDS, PRIMARY_FIELD], true) || [];
30
32
  return physicians.filter((physician) => physician.email).map((physician) => approverOf(physician));
31
33
  }
32
34
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.9",
3
+ "version": "6.5.11",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",