@peopl-health/nexus 6.4.2 → 6.4.3

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.
@@ -40,6 +40,9 @@ const SENTINELS = [
40
40
  /^no (he recibido|tengo) (alguno|ningun[oa])( mas)?$/,
41
41
  ];
42
42
 
43
+ // A bare «Sí» to the allergy question says there is one, so it stays as an unnamed allergy.
44
+ const UNNAMED_ALLERGY = 'Alergia a medicamentos referida, sin especificar';
45
+
43
46
  const clean = (s) => sanitizeInlineText(s, Infinity);
44
47
  const fold = (s) => foldAccents(clean(s)).toLowerCase().replace(/[.;,]+$/, '');
45
48
  const isSentinel = (s) => SENTINELS.some((re) => re.test(fold(s)));
@@ -73,8 +76,9 @@ function candidatesFor(record) {
73
76
  // 394 patients hold both keys; written separately the second arbitrates the first into `alternates`.
74
77
  const perVariable = new Map();
75
78
  for (const [key, variableId] of Object.entries(FIELD_MAP)) {
76
- const value = clean(clinical[key]);
77
- if (!value) continue;
79
+ const written = clean(clinical[key]);
80
+ if (!written) continue;
81
+ const value = key === 'alergias_medicamentos' && fold(written) === 'si' ? UNNAMED_ALLERGY : written;
78
82
  if (isSentinel(value)) { out.sentinels[key] = (out.sentinels[key] || 0) + 1; continue; }
79
83
  const bucket = perVariable.get(variableId) || [];
80
84
  if (bucket.some((held) => fold(held) === fold(value))) continue;
@@ -47,6 +47,20 @@ const ensureWhatsAppFormat = (code) => {
47
47
  return trimmed;
48
48
  };
49
49
 
50
+ // Without its country code: 10 digits is Mexico (an old 044/045 prefix dropped; never 51, Peru's code), 9 starting with 9 a Peruvian mobile.
51
+ const withCountryCode = (digits) => {
52
+ const national = digits.replace(/^04[45](?=\d{10}$)/, '');
53
+ if (/^(?!51)[2-9]\d{9}$/.test(national)) return `+52${national}`;
54
+ if (/^9\d{8}$/.test(digits)) return `+51${digits}`;
55
+ return digits;
56
+ };
57
+
58
+ // A phone as typed in Airtable («55 1234 5678», «987 654 321», «+51 987…») as a WhatsApp code.
59
+ const whatsAppCodeFromPhone = (phone) => {
60
+ const written = String(phone ?? '').replace(/[^\d+]/g, '');
61
+ return ensureWhatsAppFormat(written.startsWith('+') ? written : withCountryCode(written));
62
+ };
63
+
50
64
  const stripWhatsAppFormat = (code) => {
51
65
  const raw = String(code).trim();
52
66
  const unprefixed = raw.startsWith('whatsapp:') ? raw.slice('whatsapp:'.length) : raw;
@@ -68,6 +82,7 @@ module.exports = {
68
82
  extractTitle,
69
83
  ensureWhatsAppFormat,
70
84
  stripWhatsAppFormat,
85
+ whatsAppCodeFromPhone,
71
86
  isArchivedPatientCode,
72
87
  mexicanMobileVariant
73
88
  };
@@ -310,7 +310,10 @@ async function lastChatMessage(code) {
310
310
  return last;
311
311
  }
312
312
 
313
- const hasOpenQuestion = (last) => Boolean(last?.from_me && String(last.body ?? '').includes('?'));
313
+ const LINK = /https?:\/\/\S+|www\.\S+/gi;
314
+
315
+ // A «?» inside a link («…?id=») is no question.
316
+ const hasOpenQuestion = (last) => Boolean(last?.from_me && String(last.body ?? '').replace(LINK, ' ').includes('?'));
314
317
 
315
318
  // In urgent, a patient who left the bot's question unanswered gets one reminder, held for the team day at night.
316
319
  async function remindQuietPatient(review, clock, now) {
@@ -4,7 +4,7 @@ const { logger } = require('../utils/logger');
4
4
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
5
  const { getEscalationReview } = require('../models/escalationReviewModel');
6
6
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
7
+ const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
8
8
 
9
9
  const { logPatientChange } = require('./patientService');
10
10
  const { listEscalationApprovers } = require('./physicianService');
@@ -34,7 +34,7 @@ const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_TEMPLATE_KEY));
34
34
  // The approving doctor's WhatsApp, or null when there is none to send the digest to.
35
35
  async function digestRecipient() {
36
36
  const [approver] = await listEscalationApprovers();
37
- const code = ensureWhatsAppFormat(String(approver?.phone ?? '').replace(/[^\d+]/g, ''));
37
+ const code = whatsAppCodeFromPhone(approver?.phone);
38
38
  return PATIENT_CODE.test(code) ? code : null;
39
39
  }
40
40
 
@@ -26,7 +26,7 @@ const {
26
26
  } = require('../models/escalationReviewModel');
27
27
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
28
28
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
29
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
29
+ const { ensureWhatsAppFormat, whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
30
30
  const { DrainingError } = require('../core/BatchingManager');
31
31
  const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
32
32
  const { conversationLink, readGroupMessageId, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
@@ -403,7 +403,7 @@ async function blockForMissingIdentity({ review, missing, operator }) {
403
403
  }
404
404
 
405
405
  async function sendDoctorAlert({ message, approver, operator }) {
406
- const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
406
+ const doctorCode = whatsAppCodeFromPhone(approver.phone);
407
407
  if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
408
408
  const inWindow = await isWithin24HourWindow(doctorCode);
409
409
  const outgoing = inWindow
@@ -7,7 +7,7 @@ const { logger } = require('../utils/logger');
7
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
8
  const { withTimeout } = require('../utils/timeoutUtils');
9
9
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
10
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
10
+ const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
11
11
 
12
12
  const airtableService = require('./airtableService');
13
13
 
@@ -23,8 +23,6 @@ const ROSTER_READ_TIMEOUT_MS = 5000;
23
23
 
24
24
  const getMessaging = () => require('../core/NexusMessaging');
25
25
 
26
- const whatsAppCodeOf = (phone) => ensureWhatsAppFormat(String(phone ?? '').replace(/[^\d+]/g, ''));
27
-
28
26
  const redacted = (error) => redactDirectIdentifiers(String(error?.message || error || ''));
29
27
 
30
28
  let roster = { members: null, readAt: 0 };
@@ -36,7 +34,7 @@ function configuredPhones() {
36
34
  .split(',')
37
35
  .map((phone) => phone.trim())
38
36
  .filter(Boolean)
39
- .map(whatsAppCodeOf)
37
+ .map(whatsAppCodeFromPhone)
40
38
  .filter((code) => PATIENT_CODE.test(code));
41
39
  }
42
40
 
@@ -44,9 +42,10 @@ function configuredPhones() {
44
42
  async function readRoster() {
45
43
  const rows = await airtableService.getRecordByFilter(Monitoreo_ID, ROSTER_TABLE, `AND({activo}, ${programSourceFormula()})`, null, ROSTER_FIELDS);
46
44
  if (!Array.isArray(rows)) throw new Error('The on-call roster could not be read');
47
- return rows
48
- .map((row) => ({ code: whatsAppCodeOf(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [], doctor: row.rol === DOCTOR_ROLE }))
49
- .filter((member) => PATIENT_CODE.test(member.code));
45
+ const members = rows.map((row) => ({ code: whatsAppCodeFromPhone(row.whatsapp), levels: Array.isArray(row.sin_tomar) ? row.sin_tomar : [], doctor: row.rol === DOCTOR_ROLE }));
46
+ const usable = members.filter((member) => PATIENT_CODE.test(member.code));
47
+ if (usable.length < members.length) logger.warn('[TeamAlert] On-call members left out: their WhatsApp number is not usable', { leftOut: members.length - usable.length });
48
+ return usable;
50
49
  }
51
50
 
52
51
  async function refreshRoster(now) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.4.2",
3
+ "version": "6.4.3",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",