@peopl-health/nexus 6.8.2 → 6.9.0-dev.21839

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,7 +28,6 @@ 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');
32
31
  const { observeSend, reserveSend, releaseSend } = require('../services/contactGateService');
33
32
 
34
33
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
@@ -117,7 +116,6 @@ function createDefaultLlmMonitor(options, loader = loadDefaultLlmMonitor) {
117
116
  * Core messaging orchestrator for providers, storage, and assistant processing.
118
117
  */
119
118
  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 };
121
119
  const NOT_SENT_EXPIRED = { success: false, messageId: null, status: 'expired', delivered: false, deferred: false };
122
120
 
123
121
  class NexusMessaging {
@@ -399,7 +397,6 @@ class NexusMessaging {
399
397
  // Only an operator writing now still reaches a deceased patient's phone; automations and scheduled sends do not.
400
398
  const operatorNow = isStaffSend(messageData.triggeredBy) && !String(messageData.idempotencyKey || '').startsWith('scheduled:');
401
399
  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;
403
400
  const claim = await acquireSendClaim(messageData);
404
401
  if (!claim.acquired) {
405
402
  return { success: false, messageId: null, status: 'duplicate_suppressed', duplicate: true, completed: claim.completed === true, delivered: false, deferred: false };
@@ -522,7 +519,6 @@ class NexusMessaging {
522
519
 
523
520
  async sendAssistantReply(messageData) {
524
521
  if (await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
525
- if (!messageData.contactCode && await numberUnreachable(messageData.code)) return NOT_SENT_UNREACHABLE;
526
522
  if (messageData.outreachStartedAt) {
527
523
  const patientActivity = await getMessages({
528
524
  numero: messageData.code,
@@ -1,6 +1,5 @@
1
1
  const { logger } = require('../utils/logger');
2
2
 
3
- const { handleUnreachableNumber } = require('../services/unreachableNumberService');
4
3
  const { handle24HourWindowError } = require('./templateRecoveryHelper');
5
4
  const { handleBlockedDelivery, handleRetryableChannelError } = require('./channelRetryHelper');
6
5
 
@@ -11,7 +10,6 @@ const CHANNEL_ERROR_STRATEGIES = {
11
10
  63016: { name: 'window_recovery', handle: (message, twilioSid) => handle24HourWindowError(message, twilioSid) },
12
11
  63007: CONTENT_RETRY,
13
12
  63021: CONTENT_RETRY,
14
- 63024: { name: 'unreachable_number', handle: handleUnreachableNumber },
15
13
  63032: BLOCKED_DELIVERY,
16
14
  63049: BLOCKED_DELIVERY
17
15
  };
@@ -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', 'number_unreachable']);
19
+ const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked']);
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,14 +9,11 @@ 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');
13
12
 
14
13
  const { updateRecordByFilter } = require('../services/airtableService');
15
14
  const { recordUndeliverable } = require('../services/undeliverableService');
16
15
  const { getMessages } = require('../services/messageService');
17
16
 
18
- const LANDED = new Set(['delivered', 'read']);
19
-
20
17
  async function updateMessageStatus(messageSid, status, errorCode = null, errorMessage = null) {
21
18
  try {
22
19
  const updateData = {
@@ -66,9 +63,6 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
66
63
  if (status === 'failed' || status === 'undelivered') {
67
64
  recordUndeliverable(updated, { status, errorCode });
68
65
  } 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
- }
72
66
  updateRecordByFilter(
73
67
  Monitoreo_ID,
74
68
  'undelivered_messages',
@@ -19,7 +19,6 @@ 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',
23
22
  expired: 'Expired before it could be sent',
24
23
  outbound_blocked: 'The outbound allowlist refused the number',
25
24
  contact_capped: 'Contact limit reached'
@@ -16,9 +16,6 @@ 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 },
22
19
  doNotAlertThrough: { type: Date, default: null },
23
20
  review: { type: Boolean, default: false },
24
21
  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()), ...(!values.from_me && !values.contact_code ? { whatsappUnreachableAt: null } : {}) },
62
+ $set: threadPreview(values, new Date()),
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, whatsappUnreachableAt: null } }).then(() => true, (error) => {
177
+ const renameThread = (thread, target) => Thread.updateOne({ _id: thread._id }, { $set: { code: target } }).then(() => true, (error) => {
178
178
  if (error.code !== 11000) throw error;
179
179
  return false;
180
180
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.8.2",
3
+ "version": "6.9.0-dev.21839",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,69 +0,0 @@
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 };