@peopl-health/nexus 6.8.1 → 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.
- package/lib/core/NexusMessaging.js +4 -0
- package/lib/helpers/channelErrorHelper.js +2 -0
- package/lib/helpers/channelRetryHelper.js +1 -1
- package/lib/helpers/messageStatusHelper.js +6 -0
- package/lib/jobs/ScheduledMessageJob.js +1 -0
- package/lib/models/threadModel.js +3 -0
- package/lib/services/messageService.js +1 -1
- package/lib/services/patientCodeMigrationService.js +1 -1
- package/lib/services/unreachableNumberService.js +69 -0
- package/package.json +1 -1
|
@@ -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 },
|
|
@@ -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 };
|