@peopl-health/nexus 6.8.1 → 6.8.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.
@@ -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',
@@ -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 },
@@ -116,6 +116,7 @@ const ALERT_OPERATOR = 'bot:escalationAlert';
116
116
  const AIRTABLE_TRANSPORT = 'airtable';
117
117
  const NOT_RECORDED = 'no se registró en Airtable';
118
118
  const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
119
+ const FOLLOWUP_CALL_STATUSES = [...FOLLOWUP_STATUSES, 'approved', 'needs_intervention'];
119
120
  const SAME_URGENCY = 'The review is already at that urgency';
120
121
  const STAT_WATCH = 'A stat case is not watched at home; lower its urgency with a reason first';
121
122
  const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
@@ -988,6 +989,9 @@ async function appendWithDoctor(id, entry) {
988
989
  throw httpError(409, STATUS_CONFLICT);
989
990
  }
990
991
 
992
+ // After the decision the call keeps the status; it flags the case and refreshes the follow-up summary, which is where the team reads it.
993
+ const appendInFollowUp = (id, entry) => updateReview(id, FOLLOWUP_CALL_STATUSES, { $push: { callLogs: entry }, $set: { updatedSinceSeen: true, ...redraftAfterCall() } });
994
+
991
995
  async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId = null } = {}) {
992
996
  const reviewId = reviewIdOf(id);
993
997
  const operator = requiredText(updatedBy, 'updatedBy');
@@ -1058,10 +1062,11 @@ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy
1058
1062
  const review = await (outcome === 'contacted'
1059
1063
  ? updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { callLogs: entry }, $set: { status: 'documenting', ...redraftAfterCall() } })
1060
1064
  : appendKeepingDraft(reviewId, entry))
1061
- .catch((error) => (error.statusCode === 409 ? appendWithDoctor(reviewId, entry) : Promise.reject(error)));
1065
+ .catch((error) => (error.statusCode === 409 ? appendWithDoctor(reviewId, entry) : Promise.reject(error)))
1066
+ .catch((error) => (error.statusCode === 409 ? appendInFollowUp(reviewId, entry) : Promise.reject(error)));
1062
1067
  await audit(review, operator, requestId, { action: 'call_logged', outcome });
1063
- // Note facts are confirmed only while the case is documented, so none are proposed while it is with the doctor.
1064
- if (outcome !== 'contacted' || review.status === 'awaiting_doctor') return review;
1068
+ // Note facts are confirmed only while the case is documented, so none are proposed once it reached the doctor.
1069
+ if (outcome !== 'contacted' || !DOCUMENTING_STATUSES.includes(review.status)) return review;
1065
1070
  return proposeNoteFacts(review, operator, requestId);
1066
1071
  }
1067
1072
 
@@ -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.1",
3
+ "version": "6.8.3",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",