@peopl-health/nexus 6.3.7 → 6.3.8

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.
@@ -4,6 +4,7 @@ const twilio = require('twilio');
4
4
  const { generatePresignedUrl } = require('../config/awsConfig');
5
5
 
6
6
  const { logger } = require('../utils/logger');
7
+ const { splitAtWordBoundaries } = require('../utils/templateTextUtils');
7
8
  const {
8
9
  isJsonBlob, hasSpreadsheetError, stripSpreadsheetErrors, stripSpreadsheetErrorsDeep, usableText
9
10
  } = require('../utils/formatUtils');
@@ -241,37 +242,7 @@ class TwilioProvider extends MessageProvider {
241
242
  }
242
243
 
243
244
  _splitMessageAtWordBoundaries(text, maxLength = 1600) {
244
- if (!text || text.length <= maxLength) return [text];
245
- const chunks = [];
246
- let remaining = text;
247
- while (remaining.length > maxLength) {
248
- let splitIndex = -1;
249
- const searchStart = Math.max(0, maxLength - 500); // Look back up to 500 chars
250
- const searchArea = remaining.substring(searchStart, maxLength + 1);
251
-
252
- const regex = /[.!?]\s/g;
253
- let match;
254
- let lastMatchIndex = -1;
255
-
256
- while ((match = regex.exec(searchArea)) !== null) {
257
- const absoluteIndex = searchStart + match.index;
258
- if (absoluteIndex <= maxLength) {
259
- lastMatchIndex = absoluteIndex + match[0].length;
260
- }
261
- }
262
-
263
- if (lastMatchIndex > 0) {
264
- splitIndex = lastMatchIndex;
265
- } else {
266
- splitIndex = remaining.lastIndexOf(' ', maxLength);
267
- }
268
-
269
- const chunk = remaining.substring(0, splitIndex === -1 ? maxLength : splitIndex).trim();
270
- if (chunk) chunks.push(chunk);
271
- remaining = remaining.substring(splitIndex === -1 ? maxLength : splitIndex).trim();
272
- }
273
- if (remaining) chunks.push(remaining);
274
- return chunks;
245
+ return splitAtWordBoundaries(text, maxLength);
275
246
  }
276
247
 
277
248
  async listTemplates(options = {}) {
@@ -116,7 +116,10 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
116
116
  return { retried: false, reason: 'already_sent' };
117
117
  }
118
118
 
119
- const priorAttempts = await DeliveryAttempt.countDocuments({ messageId, kind: 'template' });
119
+ const priorAttempts = messageDoc.statusInfo?.recoveryFallbackAt
120
+ ? (await DeliveryAttempt.find({ messageId, kind: { $in: ['recovery_template', 'template'] }, contentSid: attempt.contentSid }, 'variables').lean())
121
+ .filter(sent => stableContent(sent.variables) === stableContent(variables)).length
122
+ : await DeliveryAttempt.countDocuments({ messageId, kind: 'template' });
120
123
  const delay = retryDelays()[priorAttempts - 1];
121
124
 
122
125
  if (isAtOrBefore(messageDoc.expiresAt, new Date(Date.now() + (delay ?? 0)))) {
@@ -213,6 +216,8 @@ async function handleBlockedDelivery(messageDoc, twilioSid, errorCode) {
213
216
  if (await patientIsDeceased(messageDoc.numero)) return { retried: false, reason: 'patient_deceased' };
214
217
 
215
218
  const logCtx = { twilioSid, errorCode, messageId: String(messageDoc._id) };
219
+ // A fallback part carries only a piece of the text, so resending the whole message would repeat what already arrived.
220
+ if (messageDoc.statusInfo?.recoveryFallbackAt) return reportBlockedDelivery(messageDoc, logCtx);
216
221
  const claimed = attempt && (await Message.updateOne(
217
222
  { _id: messageDoc._id, 'statusInfo.blockedRetryAt': null },
218
223
  { $set: { 'statusInfo.blockedRetryAt': new Date() } }
@@ -31,6 +31,7 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
31
31
 
32
32
  const notTerminal = { 'statusInfo.status': { $nin: DELIVERY_ATTEMPT_TERMINAL_STATUSES } };
33
33
 
34
+ let fallbackParent = null;
34
35
  let updated = await Message.findOneAndUpdate(
35
36
  { message_id: messageSid, ...notTerminal },
36
37
  { $set: updateData },
@@ -45,13 +46,18 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
45
46
  { new: true }
46
47
  );
47
48
  }
49
+ if (!updated && attempt?.messageId && (status === 'failed' || status === 'undelivered')) {
50
+ [fallbackParent] = await getMessages({ _id: attempt.messageId, 'statusInfo.recoveryFallbackAt': { $ne: null } }, { limit: 1 });
51
+ }
48
52
  }
49
53
 
50
54
  if (!updated) {
51
55
  logger.warn('[MessageStatus] Message not found', { messageSid });
52
56
  }
53
57
 
54
- await updateDeliveryAttemptByTwilioSid(messageSid, { status, errorCode, errorMessage });
58
+ const attemptUpdated = await updateDeliveryAttemptByTwilioSid(messageSid, { status, errorCode, errorMessage });
59
+ // A message sent in parts settles on its first part, so a later part's failure finds it already terminal.
60
+ if (fallbackParent && attemptUpdated) updated = fallbackParent;
55
61
 
56
62
  if (updated) {
57
63
  if (status === 'failed' || status === 'undelivered') {
@@ -0,0 +1,146 @@
1
+ const { getRecoveryTemplateConfig } = require('../config/recoveryTemplateConfig');
2
+ const { logger } = require('../utils/logger');
3
+ const { isAtOrBefore } = require('../utils/dateUtils');
4
+ const { Message } = require('../models/messageModel');
5
+ const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
6
+
7
+ const { alertUndeliverable } = require('./channelRetryHelper');
8
+ const {
9
+ resolveRecoveryBody, hasUnresolvedPhi, fixedTemplateFor, fixedTextMessages, cleanupRecoveryTemplate, acceptedFixedSid, claimRecoverySend, recoverySendData
10
+ } = require('./templateRecoveryHelper');
11
+
12
+ const getMessaging = () => require('../core/NexusMessaging');
13
+
14
+ const TOO_LONG_ERROR_MESSAGE = 'Too long for a template and the fixed templates could not send it';
15
+
16
+ const isFallbackEnabled = async () => Boolean((await getRecoveryTemplateConfig()).RECOVERY_TEXT_TEMPLATE_SID);
17
+
18
+ async function buildFallbackPlan(messageDoc) {
19
+ if (messageDoc.media?.key) {
20
+ const template = await fixedTemplateFor(messageDoc);
21
+ return template ? { messages: [template] } : { reason: 'no_fitting_file_template' };
22
+ }
23
+ const text = await resolveRecoveryBody(messageDoc);
24
+ if (hasUnresolvedPhi(text)) return { reason: 'unresolved_phi' };
25
+ const messages = fixedTextMessages(text, await getRecoveryTemplateConfig());
26
+ return messages ? { messages } : { reason: 'no_fitting_text_template' };
27
+ }
28
+
29
+ const hasFallbackPlan = async (messageDoc) => Boolean((await buildFallbackPlan(messageDoc)).messages);
30
+
31
+ const sentOrDone = (result) => Boolean(result?.messageId) || Boolean(result?.duplicate && result?.completed);
32
+
33
+ async function releaseFallbackClaim(messageDoc) {
34
+ await Message.updateOne(
35
+ { _id: messageDoc._id },
36
+ { $unset: { 'statusInfo.recoverySentAt': '', 'statusInfo.recoveryFallbackAt': '', 'statusInfo.recoveryFallbackReason': '' } }
37
+ );
38
+ }
39
+
40
+ const alertFallback = (messageDoc, details) => alertUndeliverable({
41
+ source: 'recovery_fallback', messageId: String(messageDoc._id), to: messageDoc.numero,
42
+ triggeredBy: messageDoc.triggeredBy || null, ...details
43
+ });
44
+
45
+ async function failTooLong(messageDoc, reason) {
46
+ await Message.updateOne(
47
+ { _id: messageDoc._id, 'statusInfo.recoverySentAt': null },
48
+ { $set: {
49
+ 'statusInfo.recoveryFailedAt': new Date(),
50
+ 'statusInfo.status': 'failed',
51
+ 'statusInfo.errorMessage': TOO_LONG_ERROR_MESSAGE,
52
+ 'statusInfo.updatedAt': new Date()
53
+ } }
54
+ );
55
+ alertFallback(messageDoc, { reason });
56
+ }
57
+
58
+ async function sendPart(messageDoc, template, index, send) {
59
+ try {
60
+ const data = {
61
+ ...recoverySendData(messageDoc, template),
62
+ ...(!messageDoc.media?.key && { body: Object.values(template.variables).join('\n\n') })
63
+ };
64
+ if (!index) return await send({ ...data, idempotencyKey: `recovery-fallback:${messageDoc._id}` });
65
+ // The patient receives one message in parts, so only the first part counts as a contact.
66
+ return await getMessaging().requireDefaultInstance()._transport({ ...data, continuesSend: true });
67
+ } catch (error) {
68
+ // The provider may have accepted the first part before the bookkeeping failed; sending it again would repeat it.
69
+ let acceptedSid;
70
+ try {
71
+ acceptedSid = index === 0 && await acceptedFixedSid(messageDoc._id, template.contentSid);
72
+ } catch {
73
+ return { status: 'state_unknown', error };
74
+ }
75
+ if (acceptedSid) return { messageId: acceptedSid };
76
+ return { status: 'send_failed', error };
77
+ }
78
+ }
79
+
80
+ async function sendParts(messageDoc, plan, send, logCtx) {
81
+ let sentParts = 0;
82
+ let firstResult = null;
83
+ for (const [index, template] of plan.messages.entries()) {
84
+ if (index > 0 && isAtOrBefore(messageDoc.expiresAt, Date.now())) {
85
+ logger.warn('[RecoveryFallback] Message expired between parts, the rest is not sent', { ...logCtx, sentParts });
86
+ break;
87
+ }
88
+ const result = await sendPart(messageDoc, template, index, send);
89
+ if (!sentOrDone(result)) {
90
+ if (!sentParts) return { sentParts, result };
91
+ alertFallback(messageDoc, {
92
+ reason: 'partial_fallback', sentParts, totalParts: plan.messages.length,
93
+ status: result?.status || null, error: result?.error?.message || null
94
+ });
95
+ break;
96
+ }
97
+ if (!sentParts) firstResult = result;
98
+ sentParts += 1;
99
+ }
100
+ return { sentParts, firstResult };
101
+ }
102
+
103
+ async function sendRecoveryFallback(messageDoc, { trigger, send }) {
104
+ const logCtx = { messageId: String(messageDoc._id), trigger };
105
+ const plan = await buildFallbackPlan(messageDoc);
106
+ if (!plan.messages) {
107
+ logger.warn('[RecoveryFallback] No fixed template fits this message', { ...logCtx, reason: plan.reason });
108
+ if (trigger === 'too_long') await failTooLong(messageDoc, plan.reason);
109
+ return { sent: false, reason: plan.reason };
110
+ }
111
+
112
+ const claimed = await claimRecoverySend(messageDoc._id, { 'statusInfo.recoveryFallbackAt': new Date(), 'statusInfo.recoveryFallbackReason': trigger });
113
+ if (!claimed) return { sent: false, reason: 'already_claimed' };
114
+
115
+ const { sentParts, firstResult, result } = await sendParts(messageDoc, plan, send, logCtx);
116
+ if (!sentParts) {
117
+ if (result?.status === 'outbound_blocked') return { sent: false, reason: 'outbound_blocked' };
118
+ // Whether the patient got the first part is unknown, so the claim stays and staff decide instead of a resend.
119
+ if (result?.status === 'state_unknown') {
120
+ alertFallback(messageDoc, { reason: 'state_unknown', error: result.error?.message || null });
121
+ return { sent: false, reason: 'state_unknown' };
122
+ }
123
+ await releaseFallbackClaim(messageDoc);
124
+ const reason = result?.status || 'send_failed';
125
+ if (trigger === 'too_long') {
126
+ await failTooLong(messageDoc, reason);
127
+ return { sent: false, reason };
128
+ }
129
+ logger.warn('[RecoveryFallback] First part not sent, leaving the message to the approval job', { ...logCtx, reason, error: result?.error?.message });
130
+ return { sent: false, reason };
131
+ }
132
+
133
+ const templateSid = messageDoc.statusInfo?.recoveryTemplateSid;
134
+ if (templateSid) {
135
+ await DeliveryAttempt.updateOne(
136
+ { messageId: messageDoc._id, kind: 'recovery_template_setup', twilioSid: templateSid },
137
+ { $set: { status: 'failed', errorSource: 'server', errorMessage: `Replaced by the fixed templates (${trigger})`, completedAt: new Date() } }
138
+ ).catch(error => logger.warn('[RecoveryFallback] Could not close the setup attempt', { ...logCtx, error: error.message }));
139
+ }
140
+ await cleanupRecoveryTemplate(messageDoc);
141
+
142
+ logger.info('[RecoveryFallback] Sent', { ...logCtx, sentParts, totalParts: plan.messages.length });
143
+ return { sent: true, sentParts, totalParts: plan.messages.length, firstResult };
144
+ }
145
+
146
+ module.exports = { isFallbackEnabled, hasFallbackPlan, sendRecoveryFallback };
@@ -5,6 +5,7 @@ const { isAtOrBefore } = require('../utils/dateUtils');
5
5
  const { oneLineOf } = require('../utils/coercionUtils');
6
6
  const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
7
7
  const { createEvent, safeEmit } = require('../utils/eventUtils');
8
+ const { shapeTemplateParts } = require('../utils/templateTextUtils');
8
9
  const { Message } = require('../models/messageModel');
9
10
  const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
10
11
  const { Template: TemplateModel } = require('../models/templateModel');
@@ -13,11 +14,15 @@ const { contactOf } = require('./caregiverHelper');
13
14
  const { recordDeliveryAttempt } = require('./deliveryAttemptHelper');
14
15
 
15
16
  const getMessaging = () => require('../core/NexusMessaging');
17
+ const getFallback = () => require('./recoveryFallbackHelper');
16
18
 
17
19
  const TEMPLATE_BODY_LIMIT = 1024;
18
20
  const RECOVERY_MEDIA_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
19
21
 
20
22
  const FIXED_TEXT_TEMPLATE_KEY = 'RECOVERY_TEXT_TEMPLATE_SID';
23
+ const FIXED_TEXT_TEMPLATE_KEYS = [FIXED_TEXT_TEMPLATE_KEY, 'RECOVERY_TEXT_2_TEMPLATE_SID', 'RECOVERY_TEXT_3_TEMPLATE_SID'];
24
+ // What is left of Meta's 1024 characters once the fixed wording of a text template is counted.
25
+ const FIXED_TEXT_BUDGET = 880;
21
26
  const FIXED_FILE_TEMPLATE_KEYS = {
22
27
  'application/pdf': 'RECOVERY_DOCUMENT_TEMPLATE_SID',
23
28
  'image/jpeg': 'RECOVERY_IMAGE_TEMPLATE_SID',
@@ -51,10 +56,23 @@ async function resolveRecoveryBody(messageDoc) {
51
56
 
52
57
  const EXPIRED_ERROR_MESSAGE = 'Expired before it could be delivered';
53
58
 
59
+ function fixedTextMessages(body, config) {
60
+ const messages = (shapeTemplateParts(body, FIXED_TEXT_BUDGET) || []).map((part) => {
61
+ const contentSid = config[FIXED_TEXT_TEMPLATE_KEYS[part.length - 1]];
62
+ return contentSid && { contentSid, variables: Object.fromEntries(part.map((text, index) => [String(index + 1), text])) };
63
+ });
64
+ return messages.length && messages.every(Boolean) ? messages : null;
65
+ }
66
+
54
67
  async function fixedRecoveryTemplate(media, body) {
68
+ const config = await getRecoveryTemplateConfig();
69
+ if (!media?.key) {
70
+ const [only, ...more] = fixedTextMessages(body, config) || [];
71
+ if (only && !more.length && Object.keys(only.variables).length > 1) return only;
72
+ }
73
+
55
74
  const text = oneLineOf(body);
56
75
  if (text.length > MAX_TEMPLATE_TEXT_LENGTH) return null;
57
- const config = await getRecoveryTemplateConfig();
58
76
 
59
77
  if (!media?.key) {
60
78
  const contentSid = config[FIXED_TEXT_TEMPLATE_KEY];
@@ -91,10 +109,10 @@ const recoverySendData = (messageDoc, template) => ({
91
109
  body: messageDoc.body
92
110
  });
93
111
 
94
- async function claimRecoverySend(messageId) {
112
+ async function claimRecoverySend(messageId, extra = {}) {
95
113
  const claim = await Message.updateOne(
96
114
  { _id: messageId, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
97
- { $set: { 'statusInfo.recoverySentAt': new Date() } }
115
+ { $set: { 'statusInfo.recoverySentAt': new Date(), ...extra } }
98
116
  );
99
117
  return Boolean(claim.modifiedCount || claim.nModified);
100
118
  }
@@ -216,13 +234,14 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
216
234
 
217
235
  const recoveryBody = await resolveRecoveryBody(messageDoc);
218
236
 
237
+ const send = (data) => source === 'preemptive'
238
+ ? getMessaging().requireDefaultInstance()._transport({ ...data, contactGateDecisionId })
239
+ : getMessaging().sendMessage({ idempotencyKey: `recovery-fixed:${messageDocId}`, ...data });
240
+
219
241
  let fixedSendFailed = false;
220
242
  if (messageDoc.media?.key && !hasUnresolvedPhi(recoveryBody)) {
221
243
  const fixedTemplate = await fixedRecoveryTemplate(messageDoc.media, recoveryBody);
222
244
  if (fixedTemplate) {
223
- const send = (data) => source === 'preemptive'
224
- ? getMessaging().requireDefaultInstance()._transport({ ...data, contactGateDecisionId })
225
- : getMessaging().sendMessage({ ...data, idempotencyKey: `recovery-fixed:${messageDocId}` });
226
245
  const { outcome, result } = await sendFixedRecovery(messageDoc, fixedTemplate, logCtx, send);
227
246
  if (outcome === 'sent') return { delivered: false, deferred: false, fixedSend: result };
228
247
  if (outcome === 'skipped') return { delivered: false, deferred: true };
@@ -237,12 +256,19 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
237
256
  const mediaUrl = await resolveRecoveryMediaUrl(messageDoc.media);
238
257
  if (mediaUrl) template.setMedia(mediaUrl);
239
258
 
259
+ const tooLongForTemplate = recoveryBody.length > TEMPLATE_BODY_LIMIT && !messageDoc.media?.key && await getFallback().isFallbackEnabled();
260
+
240
261
  let twilioContent;
241
262
  let setupErr = null;
242
263
  if (!recoveryBody) {
243
264
  setupErr = new Error('A file with no text can only go out on a fixed template');
244
265
  } else if (hasUnresolvedPhi(recoveryBody)) {
245
266
  setupErr = new Error('Body still carries a PHI placeholder after decoding');
267
+ } else if (tooLongForTemplate) {
268
+ const fallback = await getFallback().sendRecoveryFallback(messageDoc, { trigger: 'too_long', send })
269
+ .catch(error => ({ sent: false, reason: error.message }));
270
+ if (fallback.sent) return { delivered: false, deferred: false, fixedSend: fallback.firstResult };
271
+ setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length}) and the fixed templates could not send it (${fallback.reason})`);
246
272
  } else if (recoveryBody.length > TEMPLATE_BODY_LIMIT) {
247
273
  setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length})`);
248
274
  } else {
@@ -331,4 +357,4 @@ async function cleanupRecoveryTemplate(messageDoc) {
331
357
  }
332
358
  }
333
359
 
334
- module.exports = { acceptedFixedSid, claimRecoverySend, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi, closeExpiredRecovery };
360
+ module.exports = { acceptedFixedSid, claimRecoverySend, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, fixedTextMessages, hasUnresolvedPhi, closeExpiredRecovery };
@@ -11,6 +11,7 @@ const { alertUndeliverable } = require('../helpers/channelRetryHelper');
11
11
 
12
12
  const { contactOf } = require('../helpers/caregiverHelper');
13
13
  const { acceptedFixedSid, claimRecoverySend, closeExpiredRecovery, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure } = require('../helpers/templateRecoveryHelper');
14
+ const { isFallbackEnabled, hasFallbackPlan, sendRecoveryFallback } = require('../helpers/recoveryFallbackHelper');
14
15
  const { getMessages } = require('../services/messageService');
15
16
  const { recordUndeliverable } = require('../services/undeliverableService');
16
17
 
@@ -25,6 +26,7 @@ const APPROVAL_CHECK_TIMEOUT_MS = 30 * 1000;
25
26
 
26
27
  const WINDOW_REOPEN_SID_KEY = 'WINDOW_REOPEN_TEMPLATE_SID';
27
28
  const WARN_AFTER_MS = 60 * 60 * 1000;
29
+ const FALLBACK_AFTER_MS = 20 * 60 * 1000;
28
30
 
29
31
  const APPROVAL_POLL_DELAYS_MS = [30 * 1000, 60 * 1000, 2 * 60 * 1000, 5 * 60 * 1000, 10 * 60 * 1000];
30
32
 
@@ -123,6 +125,13 @@ class TemplateApprovalJob extends BaseJob {
123
125
  await closeExpiredRecovery(message);
124
126
  return { success: false, reason: 'expired' };
125
127
  }
128
+
129
+ const trigger = await this._fallbackTrigger(message, approvalStatus);
130
+ if (trigger) {
131
+ const fallback = await this._sendFallback(message, trigger);
132
+ if (fallback) return fallback;
133
+ }
134
+
126
135
  if (checkError) {
127
136
  logger.error('[TemplateApprovalJob] Provider error during approval check, treating as transient', {
128
137
  templateSid, messageId, attempt, error: checkError.message
@@ -162,10 +171,35 @@ class TemplateApprovalJob extends BaseJob {
162
171
  return { success: false, reason: 'max_attempts', priorReason: reason };
163
172
  }
164
173
  await this._warnIfSlow(message, templateSid);
165
- await this.schedule({ templateSid, messageId, originalMessageSid, attempt: nextAttempt });
174
+ await this.schedule({ templateSid, messageId, originalMessageSid, attempt: nextAttempt, delayMs: await this._delayBeforeFallback(message, nextAttempt) });
166
175
  return { success: false, reason, nextAttempt };
167
176
  }
168
177
 
178
+ _waitingMs(message) {
179
+ const startedAt = message.statusInfo?.recoveryStartedAt;
180
+ return startedAt ? Date.now() - new Date(startedAt).getTime() : null;
181
+ }
182
+
183
+ async _fallbackTrigger(message, approvalStatus) {
184
+ if (approvalStatus === 'APPROVED' || !await isFallbackEnabled()) return null;
185
+ if (approvalStatus === 'REJECTED') return 'rejected';
186
+ const waitingMs = this._waitingMs(message);
187
+ return waitingMs !== null && waitingMs >= FALLBACK_AFTER_MS ? 'pending' : null;
188
+ }
189
+
190
+ async _delayBeforeFallback(message, attempt) {
191
+ const waitingMs = this._waitingMs(message);
192
+ if (waitingMs === null || waitingMs >= FALLBACK_AFTER_MS || !await isFallbackEnabled()) return undefined;
193
+ return Math.min(delayForAttempt(attempt), FALLBACK_AFTER_MS - waitingMs);
194
+ }
195
+
196
+ async _sendFallback(message, trigger) {
197
+ const result = await sendRecoveryFallback(message, { trigger, send: (data) => this.sendMessage(data) });
198
+ if (result.sent) return { success: true, reason: 'fallback', trigger, sentParts: result.sentParts };
199
+ if (['already_claimed', 'outbound_blocked', 'state_unknown'].includes(result.reason)) return { success: false, reason: result.reason };
200
+ return null;
201
+ }
202
+
169
203
  async _warnIfSlow(message, templateSid) {
170
204
  const startedAt = message.statusInfo?.recoveryStartedAt;
171
205
  if (!startedAt) return { warned: false, reason: 'no_start' };
@@ -249,7 +283,7 @@ class TemplateApprovalJob extends BaseJob {
249
283
  messageId: String(message._id), error: err.message
250
284
  }));
251
285
 
252
- await this._sendWindowReopenNudge(message);
286
+ if (!await isFallbackEnabled() || !await hasFallbackPlan(message)) await this._sendWindowReopenNudge(message);
253
287
  }
254
288
 
255
289
  async _sendWindowReopenNudge(message) {
@@ -82,7 +82,9 @@ const messageSchema = new mongoose.Schema({
82
82
  recoveryCheckedAt: { type: Date, default: null },
83
83
  recoveryAttempt: { type: Number, default: null },
84
84
  recoveryWarnedAt: { type: Date, default: null },
85
- recoveryReleasedAt: { type: Date, default: null }
85
+ recoveryReleasedAt: { type: Date, default: null },
86
+ recoveryFallbackAt: { type: Date, default: null },
87
+ recoveryFallbackReason: { type: String, default: null }
86
88
  },
87
89
  prompt: { type: Object, default: null },
88
90
  preset: { type: Object, default: null },
@@ -157,11 +157,11 @@ async function releaseSend(decisionId) {
157
157
  }
158
158
  }
159
159
 
160
- // Records every send that left; a send the gate reserved only confirms its row.
160
+ // Records every send that left, except a later part of one message; a send the gate reserved only confirms its row.
161
161
  async function observeSend(messageData, now = new Date()) {
162
162
  const code = messageData?.code;
163
163
  try {
164
- if (contactGateMode() === 'off' || !code) return null;
164
+ if (contactGateMode() === 'off' || !code || messageData.continuesSend) return null;
165
165
  if (messageData.contactGateDecisionId) {
166
166
  return await ContactGateDecision.findOneAndUpdate({ _id: messageData.contactGateDecisionId }, { $set: { status: 'sent' } }, { new: true });
167
167
  }
@@ -0,0 +1,64 @@
1
+ const MAX_PARAGRAPHS = 3;
2
+ const MAX_PARTS = 3;
3
+
4
+ const clean = (text) => text.replace(/\s+/g, ' ').trim();
5
+
6
+ // A template variable cannot hold a line break, so a single break inside a paragraph becomes « · ».
7
+ function paragraphsOf(text) {
8
+ return String(text || '').split(/\n\s*\n/)
9
+ .map(paragraph => paragraph.split('\n').map(clean).filter(Boolean).join(' · '))
10
+ .filter(Boolean);
11
+ }
12
+
13
+ function splitAtWordBoundaries(text, maxLength) {
14
+ if (!text || text.length <= maxLength) return [text];
15
+ const chunks = [];
16
+ let remaining = text;
17
+ while (remaining.length > maxLength) {
18
+ let splitIndex = -1;
19
+ const searchStart = Math.max(0, maxLength - 500); // Look back up to 500 chars
20
+ const searchArea = remaining.substring(searchStart, maxLength + 1);
21
+
22
+ const regex = /[.!?]\s/g;
23
+ let match;
24
+ let lastMatchIndex = -1;
25
+
26
+ while ((match = regex.exec(searchArea)) !== null) {
27
+ const absoluteIndex = searchStart + match.index;
28
+ if (absoluteIndex <= maxLength) {
29
+ lastMatchIndex = absoluteIndex + match[0].length;
30
+ }
31
+ }
32
+
33
+ if (lastMatchIndex > 0) {
34
+ splitIndex = lastMatchIndex;
35
+ } else {
36
+ splitIndex = remaining.lastIndexOf(' ', maxLength);
37
+ }
38
+
39
+ const chunk = remaining.substring(0, splitIndex === -1 ? maxLength : splitIndex).trim();
40
+ if (chunk) chunks.push(chunk);
41
+ remaining = remaining.substring(splitIndex === -1 ? maxLength : splitIndex).trim();
42
+ }
43
+ if (remaining) chunks.push(remaining);
44
+ return chunks;
45
+ }
46
+
47
+ const partLength = (part) => part.join('').length + (part.length - 1) * 2;
48
+
49
+ function shapeTemplateParts(text, budget) {
50
+ const parts = [];
51
+ for (const piece of paragraphsOf(text).flatMap(paragraph => splitAtWordBoundaries(paragraph, budget))) {
52
+ const part = parts[parts.length - 1];
53
+ if (part && part.length < MAX_PARAGRAPHS && partLength(part) + 2 + piece.length <= budget) {
54
+ part.push(piece);
55
+ } else if (part && part.length === MAX_PARAGRAPHS && partLength(part) + 1 + piece.length <= budget) {
56
+ part[part.length - 1] = `${part[part.length - 1]} ${piece}`;
57
+ } else {
58
+ parts.push([piece]);
59
+ }
60
+ }
61
+ return parts.length && parts.length <= MAX_PARTS ? parts : null;
62
+ }
63
+
64
+ module.exports = { shapeTemplateParts, splitAtWordBoundaries };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.3.7",
3
+ "version": "6.3.8",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",