@peopl-health/nexus 6.8.0 → 6.8.2

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.
@@ -10,6 +10,8 @@ const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models
10
10
  const { FlowRouting } = require('../models/flowRoutingModel.js');
11
11
 
12
12
  const { ensureWhatsAppFormat, isArchivedPatientCode } = require('../helpers/twilioHelper');
13
+ const { recipientPhone } = require('../helpers/recipientHelper');
14
+ const { lastDigits } = require('../helpers/outboundAllowlistHelper');
13
15
  const { ensureFlowTokenInVariables } = require('../helpers/templateFlowControllerHelper');
14
16
  const { CAREGIVER_ROLE, registeredCaregiverCode } = require('../helpers/caregiverHelper');
15
17
 
@@ -91,6 +93,10 @@ const sendMessageController = async (req, res) => {
91
93
  if (!ensureWhatsAppFormat(code)) {
92
94
  return res.status(400).json({ success: false, error: 'code is required' });
93
95
  }
96
+ const recipient = recipientPhone(code);
97
+ if (!recipient) {
98
+ return res.status(400).json({ success: false, error: 'code is not a valid phone number' });
99
+ }
94
100
 
95
101
  if (!message && !fileUrl && !contentSid) {
96
102
  return res.status(400).json({ success: false, error: 'message, fileUrl or contentSid is required' });
@@ -99,7 +105,7 @@ const sendMessageController = async (req, res) => {
99
105
  if (!_validateExpiresAt(res, expiresAt)) return;
100
106
 
101
107
  try {
102
- const formattedCode = await resolveThreadCode(ensureWhatsAppFormat(code));
108
+ const formattedCode = await resolveThreadCode(ensureWhatsAppFormat(recipient));
103
109
  let contact = {};
104
110
  if (contactCode) {
105
111
  if (sendTime) {
@@ -189,7 +195,12 @@ const sendBulkMessageController = async (req, res) => {
189
195
 
190
196
  let extraDelay = 0;
191
197
  const staggered = [];
192
- for (const recipient of codes) {
198
+ for (const raw of codes) {
199
+ const recipient = recipientPhone(raw);
200
+ if (!recipient) {
201
+ logger.warn('[sendBulkMessageController] Skipping a recipient that is not a phone number', { recipient: lastDigits(String(raw)) });
202
+ continue;
203
+ }
193
204
  staggered.push({
194
205
  offset: extraDelay,
195
206
  payload: {
@@ -208,7 +219,7 @@ const sendBulkMessageController = async (req, res) => {
208
219
  const sendMoment = sendTime ? moment.tz(sendTime, timeZone) + 20000 : Date.now();
209
220
  const payloads = staggered.map(({ offset, payload }) => ({ ...payload, sendTime: new Date(sendMoment + offset) }));
210
221
 
211
- await _sendBulkMessages(payloads, res, `Sent bulk of ${codes.length} messages`);
222
+ await _sendBulkMessages(payloads, res, `Sent bulk of ${payloads.length} messages`);
212
223
  } catch (err) {
213
224
  logger.error('Error sending bulk messages:', { error: err.message });
214
225
  res.status(500).json({ success: false, error: err.message });
@@ -252,7 +263,12 @@ const sendBulkMessageAirtableController = async (req, res) => {
252
263
 
253
264
  let code = Array.isArray(row[columnPhone]) ? row[columnPhone][0] : row[columnPhone];
254
265
  if (!code || isArchivedPatientCode(code)) continue;
255
- code = ensureWhatsAppFormat(code);
266
+ const phone = recipientPhone(code);
267
+ if (!phone) {
268
+ logger.warn('[sendBulkMessageAirtableController] Skipping a row whose phone is not a phone number', { phone: lastDigits(String(code)) });
269
+ continue;
270
+ }
271
+ code = ensureWhatsAppFormat(phone);
256
272
  if (sentPhones.has(code)) continue;
257
273
  sentPhones.add(code);
258
274
 
@@ -28,6 +28,7 @@ const { isOutboundAllowed } = require('../helpers/outboundAllowlistHelper');
28
28
 
29
29
  const { createMessagingProvider } = require('../adapters/registry');
30
30
  const { ensureThreadExists, resolveThreadCode } = require('../services/threadService');
31
+ const { numberUnreachable } = require('../services/unreachableNumberService');
31
32
  const { observeSend, reserveSend, releaseSend } = require('../services/contactGateService');
32
33
 
33
34
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
@@ -116,6 +117,7 @@ function createDefaultLlmMonitor(options, loader = loadDefaultLlmMonitor) {
116
117
  * Core messaging orchestrator for providers, storage, and assistant processing.
117
118
  */
118
119
  const NOT_SENT_DECEASED = { success: false, messageId: null, status: 'patient_deceased', delivered: false, deferred: false };
120
+ const NOT_SENT_UNREACHABLE = { success: false, messageId: null, status: 'number_unreachable', delivered: false, deferred: false };
119
121
  const NOT_SENT_EXPIRED = { success: false, messageId: null, status: 'expired', delivered: false, deferred: false };
120
122
 
121
123
  class NexusMessaging {
@@ -397,6 +399,7 @@ class NexusMessaging {
397
399
  // Only an operator writing now still reaches a deceased patient's phone; automations and scheduled sends do not.
398
400
  const operatorNow = isStaffSend(messageData.triggeredBy) && !String(messageData.idempotencyKey || '').startsWith('scheduled:');
399
401
  if (!operatorNow && await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
402
+ if (!operatorNow && !messageData.contactCode && await numberUnreachable(messageData.code, { canRetest: Boolean(messageData.contentSid) })) return NOT_SENT_UNREACHABLE;
400
403
  const claim = await acquireSendClaim(messageData);
401
404
  if (!claim.acquired) {
402
405
  return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
@@ -519,6 +522,7 @@ class NexusMessaging {
519
522
 
520
523
  async sendAssistantReply(messageData) {
521
524
  if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
525
+ if (!messageData.contactCode && await numberUnreachable(messageData.code)) return NOT_SENT_UNREACHABLE;
522
526
  if (messageData.outreachStartedAt) {
523
527
  const patientActivity = await getMessages({
524
528
  numero: messageData.code,
@@ -1,5 +1,6 @@
1
1
  const { logger } = require('../utils/logger');
2
2
 
3
+ const { handleUnreachableNumber } = require('../services/unreachableNumberService');
3
4
  const { handle24HourWindowError } = require('./templateRecoveryHelper');
4
5
  const { handleBlockedDelivery, handleRetryableChannelError } = require('./channelRetryHelper');
5
6
 
@@ -10,6 +11,7 @@ const CHANNEL_ERROR_STRATEGIES = {
10
11
  63016: { name: 'window_recovery', handle: (message, twilioSid) => handle24HourWindowError(message, twilioSid) },
11
12
  63007: CONTENT_RETRY,
12
13
  63021: CONTENT_RETRY,
14
+ 63024: { name: 'unreachable_number', handle: handleUnreachableNumber },
13
15
  63032: BLOCKED_DELIVERY,
14
16
  63049: BLOCKED_DELIVERY
15
17
  };
@@ -16,7 +16,7 @@ const { phoneDigits } = require('./whatsappHelper');
16
16
 
17
17
  const getMessaging = () => require('../core/NexusMessaging');
18
18
 
19
- const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked']);
19
+ const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked', 'number_unreachable']);
20
20
 
21
21
  const FREEFORM_RETRYABLE_CODES = new Set(['63007']);
22
22
  const DEFAULT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];
@@ -9,11 +9,14 @@ const { DeliveryAttempt, DELIVERY_ATTEMPT_TERMINAL_STATUSES } = require('../mode
9
9
  const { cleanupRecoveryTemplate } = require('../helpers/templateRecoveryHelper');
10
10
  const { updateDeliveryAttemptByTwilioSid } = require('../helpers/deliveryAttemptHelper');
11
11
  const { handleChannelError } = require('../helpers/channelErrorHelper');
12
+ const { clearNumberUnreachable } = require('../services/unreachableNumberService');
12
13
 
13
14
  const { updateRecordByFilter } = require('../services/airtableService');
14
15
  const { recordUndeliverable } = require('../services/undeliverableService');
15
16
  const { getMessages } = require('../services/messageService');
16
17
 
18
+ const LANDED = new Set(['delivered', 'read']);
19
+
17
20
  async function updateMessageStatus(messageSid, status, errorCode = null, errorMessage = null) {
18
21
  try {
19
22
  const updateData = {
@@ -63,6 +66,9 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
63
66
  if (status === 'failed' || status === 'undelivered') {
64
67
  recordUndeliverable(updated, { status, errorCode });
65
68
  } else {
69
+ if (LANDED.has(status) && !updated.contact_code) {
70
+ clearNumberUnreachable(updated.numero).catch(err => logger.warn('[MessageStatus] Could not clear the unreachable mark', { messageSid, error: err.message }));
71
+ }
66
72
  updateRecordByFilter(
67
73
  Monitoreo_ID,
68
74
  'undelivered_messages',
@@ -0,0 +1,35 @@
1
+ const { WHATSAPP_PATIENT_CODE } = require('../utils/sanitizerUtils');
2
+
3
+ // 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.
4
+ const withCountryCode = (digits) => {
5
+ const national = digits.replace(/^04[45](?=\d{10}$)/, '');
6
+ if (/^(?!51)[2-9]\d{9}$/.test(national)) return `+52${national}`;
7
+ if (/^9\d{8}$/.test(digits)) return `+51${digits}`;
8
+ return digits;
9
+ };
10
+
11
+ // «+(811) 618-4774»: a plus typed before a parenthesised area code carries no country code.
12
+ const writtenPhone = (phone) => {
13
+ const raw = String(phone ?? '');
14
+ const written = raw.replace(/[^\d+]/g, '');
15
+ if (/^\s*\+\s*\(/.test(raw)) return withCountryCode(written.slice(1));
16
+ return written.startsWith('+') ? written : withCountryCode(written);
17
+ };
18
+
19
+ const WHATSAPP_JID = /^(?:whatsapp:)?\d[\d:-]{4,}@(s\.whatsapp\.net|g\.us|c\.us|lid)$/i;
20
+ // Without a «+», a Mexican mobile has at most 13 digits (521…); more means several numbers in one field.
21
+ const MAX_DIGITS_WITHOUT_PLUS = 13;
22
+
23
+ const recipientPhone = (raw) => {
24
+ const text = typeof raw === 'number' ? String(raw) : raw;
25
+ if (typeof text !== 'string') return null;
26
+ const trimmed = text.trim();
27
+ if (WHATSAPP_JID.test(trimmed)) return trimmed;
28
+ const phone = trimmed.replace(/^whatsapp:/i, '');
29
+ if (!phone || /[^\d\s()+.-]/.test(phone)) return null;
30
+ if (!phone.includes('+') && phone.replace(/\D/g, '').length > MAX_DIGITS_WITHOUT_PLUS) return null;
31
+ const e164 = `+${writtenPhone(phone).replace(/^\+/, '')}`;
32
+ return WHATSAPP_PATIENT_CODE.test(`whatsapp:${e164}`) ? e164 : null;
33
+ };
34
+
35
+ module.exports = { recipientPhone, writtenPhone };
@@ -1,4 +1,5 @@
1
1
  const { v4: uuidv4 } = require('uuid');
2
+ const { writtenPhone } = require('./recipientHelper');
2
3
 
3
4
  function convertTwilioToInternalFormat(twilioMessage) {
4
5
  const from = twilioMessage.From || '';
@@ -47,19 +48,8 @@ const ensureWhatsAppFormat = (code) => {
47
48
  return trimmed;
48
49
  };
49
50
 
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
51
  // 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
- };
52
+ const whatsAppCodeFromPhone = (phone) => ensureWhatsAppFormat(writtenPhone(phone));
63
53
 
64
54
  const stripWhatsAppFormat = (code) => {
65
55
  const raw = String(code).trim();
@@ -19,6 +19,7 @@ const STALE_SENDING_MS = 5 * 60 * 1000;
19
19
 
20
20
  const CANCELLED_SEND_MESSAGES = {
21
21
  patient_deceased: 'The patient is deceased',
22
+ number_unreachable: 'The number is not on WhatsApp',
22
23
  expired: 'Expired before it could be sent',
23
24
  outbound_blocked: 'The outbound allowlist refused the number',
24
25
  contact_capped: 'Contact limit reached'
@@ -16,6 +16,9 @@ const threadSchema = new mongoose.Schema({
16
16
  deceasedAt: { type: Date, default: null },
17
17
  programStatusBeforeDeath: { type: String, default: null },
18
18
  hospitalizedAt: { type: Date, default: null },
19
+ whatsappUnreachableAt: { type: Date, default: null },
20
+ whatsappRetryAt: { type: Date, default: null },
21
+ whatsappRetries: { type: Number },
19
22
  doNotAlertThrough: { type: Date, default: null },
20
23
  review: { type: Boolean, default: false },
21
24
  version: { type: Number, default: null },
@@ -59,7 +59,7 @@ async function insertMessage(values) {
59
59
  Thread.findOneAndUpdate(
60
60
  { code: values.numero },
61
61
  {
62
- $set: threadPreview(values, new Date()),
62
+ $set: { ...threadPreview(values, new Date()), ...(!values.from_me && !values.contact_code ? { whatsappUnreachableAt: null } : {}) },
63
63
  $inc: {
64
64
  messageCount: 1,
65
65
  ...(!values.from_me ? { unreadCount: 1 } : {})
@@ -174,7 +174,7 @@ const rewriteOps = (docs, setFor) => docs.map((doc) => ({
174
174
  }));
175
175
 
176
176
  // The new number may write mid-migration and get its own thread; the source thread is then archived like a merge.
177
- const renameThread = (thread, target) => Thread.updateOne({ _id: thread._id }, { $set: { code: target } }).then(() => true, (error) => {
177
+ const renameThread = (thread, target) => Thread.updateOne({ _id: thread._id }, { $set: { code: target, whatsappUnreachableAt: null } }).then(() => true, (error) => {
178
178
  if (error.code !== 11000) throw error;
179
179
  return false;
180
180
  });
@@ -0,0 +1,69 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { Thread } = require('../models/threadModel');
3
+ const { phoneDigits } = require('../helpers/whatsappHelper');
4
+ const { formatOpsAlert, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
5
+
6
+ const RETRY_DAYS = [1, 3, 7, 14, 30];
7
+ const DAY_MS = 24 * 60 * 60 * 1000;
8
+ const retryAfter = (retries) => new Date(Date.now() + RETRY_DAYS[Math.min(retries, RETRY_DAYS.length - 1)] * DAY_MS);
9
+
10
+ // The conditional update lets only one of several concurrent sends through.
11
+ async function claimRetest(thread) {
12
+ const retries = thread.whatsappRetries + 1;
13
+ const { modifiedCount } = await Thread.updateOne(
14
+ { _id: thread._id, whatsappRetryAt: thread.whatsappRetryAt },
15
+ { $set: { whatsappRetryAt: retryAfter(retries), whatsappRetries: retries } }
16
+ );
17
+ if (modifiedCount > 0) logger.info('[UnreachableNumber] Retesting a number without WhatsApp', { threadId: String(thread._id), retries });
18
+ return modifiedCount > 0;
19
+ }
20
+
21
+ // Only a template can retest: free text never reaches a number that has not written in the last 24h.
22
+ async function numberUnreachable(code, { canRetest = false } = {}) {
23
+ // Without a database connection the mark cannot be read; the query would only wait for one.
24
+ if (Thread.db?.readyState !== 1) return false;
25
+ try {
26
+ const thread = await Thread.findOne({ code, whatsappUnreachableAt: { $ne: null } }, { whatsappRetryAt: 1, whatsappRetries: 1 }).lean();
27
+ if (!thread) return false;
28
+ if (!canRetest || thread.whatsappRetryAt > new Date()) return true;
29
+ return !(await claimRetest(thread));
30
+ } catch (error) {
31
+ logger.warn('[UnreachableNumber] Thread state unreadable; sending anyway', { code, error: error.message });
32
+ return false;
33
+ }
34
+ }
35
+
36
+ async function clearNumberUnreachable(code) {
37
+ await Thread.updateOne({ code, whatsappUnreachableAt: { $ne: null } }, { $set: { whatsappUnreachableAt: null } });
38
+ }
39
+
40
+ async function markNumberUnreachable(code) {
41
+ const { modifiedCount } = await Thread.updateOne({ code, whatsappUnreachableAt: null }, { $set: { whatsappUnreachableAt: new Date(), whatsappRetryAt: retryAfter(0), whatsappRetries: 0 } });
42
+ return modifiedCount > 0;
43
+ }
44
+
45
+ const alertOps = (messageDoc, label, summary) => writeUnresolvedRequest({
46
+ code: messageDoc.numero,
47
+ trace: null,
48
+ category: 'contact_team_member',
49
+ question: label,
50
+ details: formatOpsAlert(messageDoc.numero, { label, summary })
51
+ });
52
+
53
+ // Twilio 63024: the recipient is not a WhatsApp user.
54
+ async function handleUnreachableNumber(messageDoc, twilioSid, errorCode) {
55
+ const logCtx = { twilioSid, errorCode, messageId: String(messageDoc._id) };
56
+ if (messageDoc.contact_code) {
57
+ logger.warn('[UnreachableNumber] Caregiver number is not on WhatsApp', logCtx);
58
+ await alertOps(messageDoc, 'Cuidador sin WhatsApp', `WhatsApp no reconoce el número del cuidador (+${phoneDigits(messageDoc.contact_code)}); hay que conseguir otro contacto`);
59
+ return { marked: false, reason: 'caregiver_recipient' };
60
+ }
61
+ if (!(await markNumberUnreachable(messageDoc.numero))) return { marked: false, reason: 'already_marked' };
62
+ const { written, duplicate } = await alertOps(messageDoc, 'Número sin WhatsApp', 'WhatsApp no reconoce este número. Pausamos los mensajes automáticos y lo volvemos a probar solos a 1, 3, 7 y 14 días, y luego cada 30; se reanudan en cuanto un mensaje le llegue o el paciente escriba');
63
+ if (written || duplicate) return { marked: true, reason: 'not_on_whatsapp' };
64
+ logger.error('[UnreachableNumber] Ops alert not written; leaving the number unmarked', logCtx);
65
+ await clearNumberUnreachable(messageDoc.numero);
66
+ return { marked: false, reason: 'alert_not_written' };
67
+ }
68
+
69
+ module.exports = { clearNumberUnreachable, handleUnreachableNumber, numberUnreachable };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.8.0",
3
+ "version": "6.8.2",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",