@peopl-health/nexus 6.5.10 → 6.5.12

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,9 +8,8 @@ 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, DOCTOR_BRIEF_TEMPLATE_KEY, doctorAlertMessage, 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
15
  // Meta has not approved this template.
@@ -35,9 +34,9 @@ const redacted = (error) => redactDirectIdentifiers(String(error?.message || err
35
34
  // Urgent cases ready for the doctor go in a digest only once its template exists.
36
35
  const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY));
37
36
 
38
- // 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.
39
38
  async function digestRecipient() {
40
- const [approver] = await listEscalationApprovers();
39
+ const approver = await notifiedApprover();
41
40
  const code = whatsAppCodeFromPhone(approver?.phone);
42
41
  return PATIENT_CODE.test(code) ? code : null;
43
42
  }
@@ -8,6 +8,7 @@ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUti
8
8
  const { ageInYears, isoDay, mexicoDay } = require('../utils/dateUtils');
9
9
  const { safeParse } = require('../utils/jsonUtils');
10
10
  const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
11
+ const { mexicanPhoneForDisplay } = require('../utils/formatUtils');
11
12
  const {
12
13
  CALL_OUTCOMES,
13
14
  CANCELLABLE_AFTER_HANDOFF_STATUSES,
@@ -1158,7 +1159,7 @@ const alarmFor = (review, urgencyLevel, alarmId) => (alarmId && (review.alarms ?
1158
1159
  async function prepareDoctorAlert(review, urgencyLevel, { recipient = null, alarmId = null } = {}) {
1159
1160
  const identity = await readDoctorIdentity(review);
1160
1161
  if (identity.missing.length) throw new Error(`missing ${identity.missing.join(' and ')}`);
1161
- const approver = recipient ?? await soleApprover();
1162
+ const approver = recipient ?? await notifiedApprover();
1162
1163
  const link = conversationLink(review.patientCode);
1163
1164
  if (!link) throw new Error('missing the interface URL for the chat link');
1164
1165
  const alarm = alarmFor(review, urgencyLevel, alarmId);
@@ -1204,7 +1205,7 @@ async function sendPatientPrompt({ id, release, lease, now }) {
1204
1205
 
1205
1206
  let directive;
1206
1207
  try {
1207
- directive = String((await composePrompt({ promptId: timer.promptId }))?.resolvedPrompt ?? '').trim();
1208
+ directive = String((await composePrompt({ promptId: timer.promptId, variables: await primaryDoctorVariables(review) }))?.resolvedPrompt ?? '').trim();
1208
1209
  } catch (composeError) {
1209
1210
  // A failed read may be transient: the same slot comes back shortly, and the sweep's attempt cap
1210
1211
  // drops it (with a ledger entry) if Airtable stays unreachable.
@@ -1367,7 +1368,7 @@ async function sendScheduledDoctorAlert({ id, kind, lease = null, now = new Date
1367
1368
 
1368
1369
  async function fallbackRecipient() {
1369
1370
  const phone = String(runtimeConfig.get('ESCALATION_FALLBACK_ALERT_PHONE', '') ?? '').trim();
1370
- return phone ? { name: null, email: null, phone } : soleApprover();
1371
+ return phone ? { name: null, email: null, phone } : notifiedApprover();
1371
1372
  }
1372
1373
 
1373
1374
  // Who and where for a team alert; a patient record that cannot be read never holds the alert back.
@@ -1787,15 +1788,25 @@ async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId =
1787
1788
  return review;
1788
1789
  }
1789
1790
 
1790
- async function soleApprover() {
1791
+ async function primaryDoctorVariables(review) {
1792
+ try {
1793
+ const approver = await notifiedApprover();
1794
+ return { medico_principal_nombre: approver.name, medico_principal_telefono: mexicanPhoneForDisplay(approver.phone) };
1795
+ } catch (error) {
1796
+ logger.error('[EscalationReview] The primary doctor could not be read or chosen; the patient prompt goes without one', { escalationReviewId: String(review._id), error: redactedError(error) });
1797
+ return {};
1798
+ }
1799
+ }
1800
+
1801
+ async function notifiedApprover() {
1791
1802
  const approvers = await listEscalationApprovers();
1792
1803
  if (!approvers.length) {
1793
1804
  throw httpError(409, 'No escalation review approver is configured: tick aprueba_vaiven on a physician with a WhatsApp number');
1794
1805
  }
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];
1806
+ if (approvers.length === 1) return approvers[0];
1807
+ const primaries = approvers.filter((approver) => approver.primary);
1808
+ if (primaries.length === 1) return primaries[0];
1809
+ 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
1810
  }
1800
1811
 
1801
1812
  function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, now = new Date() }) {
@@ -1834,7 +1845,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1834
1845
  async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), operator }) {
1835
1846
  const review = await loadReview(reviewIdOf(id));
1836
1847
  const handoff = (review.doctorHandoffs ?? []).at(-1);
1837
- const approver = handoff?.physicianEmail ? await getEscalationApprover(handoff.physicianEmail) : await soleApprover();
1848
+ const approver = handoff?.physicianEmail ? await getEscalationApprover(handoff.physicianEmail) : await notifiedApprover();
1838
1849
  if (!approver) throw httpError(409, 'The case has no approving doctor to remind');
1839
1850
  const draft = review.drafts[(handoff?.draftNumber ?? review.drafts.length) - 1];
1840
1851
  const lead = promptAt ? Math.round((new Date(promptAt).getTime() - now.getTime()) / 60000) : 0;
@@ -1856,7 +1867,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
1856
1867
  const draft = review.drafts[draftNumber - 1];
1857
1868
  let approver = null;
1858
1869
  if (mode === 'sent_whatsapp') {
1859
- approver = physicianEmail ? await getEscalationApprover(physicianEmail) : await soleApprover();
1870
+ approver = physicianEmail ? await getEscalationApprover(physicianEmail) : await notifiedApprover();
1860
1871
  if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
1861
1872
  }
1862
1873
 
@@ -2522,6 +2533,7 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
2522
2533
 
2523
2534
  module.exports = {
2524
2535
  BOOKKEEPING,
2536
+ notifiedApprover,
2525
2537
  AUTO_HANDOFF_OPERATOR,
2526
2538
  DOCUMENTING_STATUSES,
2527
2539
  DRAFT_OPERATOR,
@@ -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
 
@@ -42,6 +42,16 @@ function stripSpreadsheetErrorsDeep(value, options = {}) {
42
42
  return value;
43
43
  }
44
44
 
45
+ // Mexico's two-digit area codes (Guadalajara, Mexico City, Monterrey); the rest have three digits.
46
+ const TWO_DIGIT_AREA_CODES = new Set(['33', '55', '56', '81']);
47
+
48
+ function mexicanPhoneForDisplay(phone) {
49
+ const national = String(phone ?? '').replace(/\D/g, '').match(/^521?(\d{10})$/)?.[1];
50
+ if (!national) return String(phone ?? '').trim();
51
+ const area = TWO_DIGIT_AREA_CODES.has(national.slice(0, 2)) ? 2 : 3;
52
+ return `+52 ${national.slice(0, area)} ${national.slice(area, 6)} ${national.slice(6)}`;
53
+ }
54
+
45
55
  function usableText(value) {
46
56
  if (value === null || value === undefined) return '';
47
57
  const text = typeof value === 'string' ? value : String(value);
@@ -54,5 +64,6 @@ module.exports = {
54
64
  hasSpreadsheetError,
55
65
  stripSpreadsheetErrors,
56
66
  stripSpreadsheetErrorsDeep,
67
+ mexicanPhoneForDisplay,
57
68
  usableText
58
69
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.10",
3
+ "version": "6.5.12",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",