@peopl-health/nexus 6.3.3 → 6.3.5

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.
@@ -0,0 +1,31 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { MapCache } = require('../utils/MapCache');
3
+ const { getRecordByFilter } = require('../services/airtableService');
4
+ const { Config_ID } = require('./airtableConfig');
5
+ const { programConfigSource } = require('./programConfig');
6
+
7
+ const RECOVERY_TEMPLATES_TABLE = 'recovery_templates';
8
+ const CACHE_TTL = 5 * 60 * 1000;
9
+ const CACHE_KEY = 'recoveryTemplates';
10
+
11
+ const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL });
12
+
13
+ // An unreadable table reads as empty, which keeps messages on their one-off templates.
14
+ async function getRecoveryTemplateConfig() {
15
+ const cached = cache.get(CACHE_KEY);
16
+ if (cached) return cached;
17
+ try {
18
+ const records = await getRecordByFilter(Config_ID, RECOVERY_TEMPLATES_TABLE, 'TRUE()');
19
+ const rows = (records || []).filter((row) => row.is_active && row.source === programConfigSource());
20
+ const config = Object.fromEntries(rows.map((row) => [row.config, row.value]));
21
+ cache.set(CACHE_KEY, config);
22
+ return config;
23
+ } catch (error) {
24
+ logger.warn('[recoveryTemplateConfig] Could not read the fixed templates', { error: error.message });
25
+ return {};
26
+ }
27
+ }
28
+
29
+ function _resetRecoveryTemplateConfig() { cache.clear(); }
30
+
31
+ module.exports = { getRecoveryTemplateConfig, _resetRecoveryTemplateConfig };
@@ -402,14 +402,14 @@ class NexusMessaging {
402
402
 
403
403
  let gate = null;
404
404
  try {
405
- gate = await reserveSend(messageData);
405
+ gate = messageData.skipContactGate ? null : await reserveSend(messageData);
406
406
  if (gate?.blocked) {
407
407
  await releaseSendClaim(claim.claimId);
408
408
  return { success: false, messageId: null, status: 'contact_capped', reason: gate.reason, category: gate.category, delivered: false, deferred: false };
409
409
  }
410
410
  const result = await this._sendMessage(gate ? { ...messageData, contactGateDecisionId: gate.decisionId } : messageData);
411
- // A deferred send is recorded when it actually leaves, so its reservation must not also count.
412
- if (result?.success !== true || result?.deferred === true) await releaseSend(gate?.decisionId);
411
+ // A deferred send is recorded when it actually leaves, and a nested send records itself, so the reservation must not also count.
412
+ if (result?.success !== true || result?.deferred === true || result?.sentByNestedSend) await releaseSend(gate?.decisionId);
413
413
  if (result?.success === true && result?.deferred !== true && !await completeSendClaim(claim.claimId)) {
414
414
  logger.error('[NexusMessaging] send claim completion failed; a retry after the claim expires may send again', {
415
415
  code: messageData.code,
@@ -430,7 +430,7 @@ class NexusMessaging {
430
430
  if (messageData.body) messageData.body = decodeUnicodeEscapes(messageData.body);
431
431
  if (messageData.variables) messageData.variables = decodeUnicodeEscapesDeep(messageData.variables);
432
432
 
433
- if (messageData.fileUrl && this._providerStores) await prepareMessageMedia(messageData);
433
+ if (messageData.fileUrl && !messageData.media?.key && this._providerStores) await prepareMessageMedia(messageData);
434
434
 
435
435
  const storesTemplateMedia = Boolean(messageData.contentSid && !messageData.fileUrl && !messageData.parentMessageId && this.provider.renderTemplateContent);
436
436
  if (messageData.contentSid && (!messageData.body || storesTemplateMedia)) {
@@ -484,6 +484,7 @@ class NexusMessaging {
484
484
  if (!found) return { success: false, delivered: false, deferred: true };
485
485
  const queued = await triggerTemplateRecovery(found, { source: 'preemptive' });
486
486
  if (queued?.expired) return { ...NOT_SENT_EXPIRED, messageId: String(found._id) };
487
+ if (queued?.sentOnFixedTemplate) return { success: true, messageId: String(found._id), status: 'sent', delivered: false, deferred: false, sentByNestedSend: true };
487
488
  return { success: true, messageId: String(found._id), status: 'queued', preemptive: true, delivered: false, deferred: true };
488
489
  }
489
490
  const saveFn = this.messageStorage.savePendingMessage.bind(this.messageStorage);
@@ -499,10 +500,13 @@ class NexusMessaging {
499
500
  // triggerTemplateRecovery swallows its own errors and returns undefined. Reporting "queued"
500
501
  // regardless is how a template that was never created still counts as an outreach, and the
501
502
  // weekly guard then stops us ever trying again.
502
- const queued = await triggerTemplateRecovery({ _id, body, numero: messageData.code, media: messageData.media, expiresAt: messageData.expiresAt }, { source: 'preemptive' });
503
+ const queued = await triggerTemplateRecovery({ _id, body, numero: messageData.code, media: messageData.media, expiresAt: messageData.expiresAt, contact_code: messageData.contactCode, contact_role: messageData.contactRole, triggeredBy: messageData.triggeredBy }, { source: 'preemptive' });
503
504
  if (queued?.expired) {
504
505
  return { ...NOT_SENT_EXPIRED, messageId: String(_id) };
505
506
  }
507
+ if (queued?.sentOnFixedTemplate) {
508
+ return { success: true, messageId: String(_id), status: 'sent', delivered: false, deferred: false, sentByNestedSend: true };
509
+ }
506
510
  if (!queued?.deferred) {
507
511
  logger.error('[NexusMessaging] template recovery setup failed; message not queued', { code: messageData.code, messageId: String(_id) });
508
512
  return { success: false, messageId: String(_id), status: 'failed', preemptive: true, delivered: false, deferred: false };
@@ -1,10 +1,13 @@
1
+ const { getRecoveryTemplateConfig } = require('../config/recoveryTemplateConfig');
1
2
  const { generatePresignedUrl } = require('../config/awsConfig');
2
3
  const { logger } = require('../utils/logger');
3
4
  const { isAtOrBefore } = require('../utils/dateUtils');
4
5
  const { createEvent, safeEmit } = require('../utils/eventUtils');
5
6
  const { Message } = require('../models/messageModel');
7
+ const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
6
8
  const { Template: TemplateModel } = require('../models/templateModel');
7
9
  const { Template } = require('../templates/templateStructure');
10
+ const { contactOf } = require('./caregiverHelper');
8
11
  const { recordDeliveryAttempt } = require('./deliveryAttemptHelper');
9
12
 
10
13
  const getMessaging = () => require('../core/NexusMessaging');
@@ -12,6 +15,16 @@ const getMessaging = () => require('../core/NexusMessaging');
12
15
  const TEMPLATE_BODY_LIMIT = 1024;
13
16
  const RECOVERY_MEDIA_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
14
17
 
18
+ const FIXED_TEXT_TEMPLATE_KEY = 'RECOVERY_TEXT_TEMPLATE_SID';
19
+ const FIXED_FILE_TEMPLATE_KEYS = {
20
+ 'application/pdf': 'RECOVERY_DOCUMENT_TEMPLATE_SID',
21
+ 'image/jpeg': 'RECOVERY_IMAGE_TEMPLATE_SID',
22
+ 'image/png': 'RECOVERY_IMAGE_TEMPLATE_SID'
23
+ };
24
+ const FIXED_TEMPLATE_TEXT_LIMIT = 800;
25
+ const FIXED_TEMPLATE_DEFAULT_TEXT = 'Te compartimos un archivo.';
26
+ const FIXED_TEMPLATE_MEDIA_PREFIX_KEY = 'RECOVERY_TEMPLATE_MEDIA_PREFIX';
27
+
15
28
  async function resolveRecoveryMediaUrl(media) {
16
29
  if (!media?.bucketName || !media?.key) return null;
17
30
  try {
@@ -36,6 +49,75 @@ async function resolveRecoveryBody(messageDoc) {
36
49
 
37
50
  const EXPIRED_ERROR_MESSAGE = 'Expired before it could be delivered';
38
51
 
52
+ // Approved UTILITY, so Meta cannot reclassify it per message; null keeps the one-off template.
53
+ async function fixedRecoveryTemplate(media, body) {
54
+ const text = String(body ?? '').replace(/\s+/g, ' ').trim();
55
+ if (text.length > FIXED_TEMPLATE_TEXT_LIMIT) return null;
56
+ const config = await getRecoveryTemplateConfig();
57
+
58
+ if (!media?.key) {
59
+ const contentSid = config[FIXED_TEXT_TEMPLATE_KEY];
60
+ return contentSid && text ? { contentSid, variables: { 1: text } } : null;
61
+ }
62
+
63
+ const contentSid = config[FIXED_FILE_TEMPLATE_KEYS[media.contentType]];
64
+ const mediaPrefix = config[FIXED_TEMPLATE_MEDIA_PREFIX_KEY];
65
+ if (!contentSid || !mediaPrefix) return null;
66
+ const mediaUrl = await resolveRecoveryMediaUrl(media);
67
+ if (!mediaUrl?.startsWith(mediaPrefix)) {
68
+ logger.warn('[TemplateRecovery] Signed URL does not match the fixed template, using a one-off template', { contentSid });
69
+ return null;
70
+ }
71
+ return { contentSid, variables: { 1: text || FIXED_TEMPLATE_DEFAULT_TEXT, 2: mediaUrl.slice(mediaPrefix.length) } };
72
+ }
73
+
74
+ // Returns the provider SID if the fixed send got through after all; otherwise the row goes back to queued.
75
+ async function settleFailedFixedSend(messageDoc, contentSid) {
76
+ const accepted = await DeliveryAttempt.findOne(
77
+ { messageId: messageDoc._id, contentSid, twilioSid: { $ne: null } }, 'twilioSid'
78
+ ).lean();
79
+ if (accepted) return accepted.twilioSid;
80
+ await Message.updateOne(
81
+ { _id: messageDoc._id },
82
+ { $set: { 'statusInfo.status': 'queued' }, $unset: { 'statusInfo.errorCode': '', 'statusInfo.errorMessage': '' } }
83
+ );
84
+ return null;
85
+ }
86
+
87
+ async function sendFixedRecovery(messageDoc, template, logCtx, { skipContactGate }) {
88
+ const claim = await Message.updateOne(
89
+ { _id: messageDoc._id, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
90
+ { $set: { 'statusInfo.recoverySentAt': new Date() } }
91
+ );
92
+ if (!claim.modifiedCount && !claim.nModified) return 'skipped';
93
+
94
+ try {
95
+ const result = await getMessaging().sendMessage({
96
+ code: messageDoc.numero,
97
+ ...contactOf(messageDoc),
98
+ ...template,
99
+ parentMessageId: messageDoc._id,
100
+ kind: 'recovery_template',
101
+ body: messageDoc.body,
102
+ triggeredBy: messageDoc.triggeredBy,
103
+ idempotencyKey: `recovery-fixed:${messageDoc._id}`,
104
+ skipContactGate
105
+ });
106
+ if (result?.duplicate || result?.status === 'outbound_blocked') return 'skipped';
107
+ if (!result?.messageId) throw new Error('Provider did not return a messageId for the fixed template send');
108
+ logger.info('[TemplateRecovery] Sent on the fixed template', { ...logCtx, contentSid: template.contentSid });
109
+ return 'sent';
110
+ } catch (error) {
111
+ if (await settleFailedFixedSend(messageDoc, template.contentSid)) {
112
+ logger.error('[TemplateRecovery] Fixed template reached the provider but bookkeeping failed', { ...logCtx, error: error.message });
113
+ return 'sent';
114
+ }
115
+ await Message.updateOne({ _id: messageDoc._id }, { $unset: { 'statusInfo.recoverySentAt': '' } });
116
+ logger.warn('[TemplateRecovery] Fixed template send failed, using a one-off template', { ...logCtx, error: error.message });
117
+ return null;
118
+ }
119
+ }
120
+
39
121
  async function closeExpiredRecovery(messageDoc) {
40
122
  const claim = await Message.updateOne(
41
123
  { _id: messageDoc._id, 'statusInfo.recoveryReleasedAt': null, 'statusInfo.recoverySentAt': null },
@@ -110,6 +192,17 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
110
192
  }
111
193
 
112
194
  const recoveryBody = await resolveRecoveryBody(messageDoc);
195
+
196
+ let fixedSendFailed = false;
197
+ if (messageDoc.media?.key && !hasUnresolvedPhi(recoveryBody)) {
198
+ const fixedTemplate = await fixedRecoveryTemplate(messageDoc.media, recoveryBody);
199
+ // The preemptive caller's own reservation would count against this send; a reactive one has none.
200
+ const outcome = fixedTemplate && await sendFixedRecovery(messageDoc, fixedTemplate, logCtx, { skipContactGate: source === 'preemptive' });
201
+ if (outcome === 'sent') return { delivered: false, deferred: false, sentOnFixedTemplate: true };
202
+ if (outcome) return { delivered: false, deferred: true };
203
+ fixedSendFailed = outcome === null;
204
+ }
205
+
113
206
  const templateName = `auto_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
114
207
  const template = new Template(templateName, 'UTILITY', 'es');
115
208
  template.setBody(recoveryBody, []);
@@ -178,6 +271,13 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
178
271
  originalMessageSid: messageSid
179
272
  });
180
273
 
274
+ if (fixedSendFailed) {
275
+ safeEmit(getMessaging().getEventBus(), 'message:status', createEvent('message:status', {
276
+ messageId: String(messageDocId),
277
+ to: messageDoc.numero,
278
+ status: 'queued'
279
+ }));
280
+ }
181
281
  return { delivered: false, deferred: true };
182
282
  } catch (error) {
183
283
  logger.error('[TemplateRecovery] Error', { source, messageSid, error: error.message });
@@ -207,4 +307,4 @@ async function cleanupRecoveryTemplate(messageDoc) {
207
307
  }
208
308
  }
209
309
 
210
- module.exports = { handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi, closeExpiredRecovery };
310
+ module.exports = { settleFailedFixedSend, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, fixedRecoveryTemplate, hasUnresolvedPhi, closeExpiredRecovery };
@@ -10,7 +10,7 @@ const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
10
10
  const { alertUndeliverable } = require('../helpers/channelRetryHelper');
11
11
 
12
12
  const { contactOf } = require('../helpers/caregiverHelper');
13
- const { closeExpiredRecovery } = require('../helpers/templateRecoveryHelper');
13
+ const { closeExpiredRecovery, fixedRecoveryTemplate, hasUnresolvedPhi, resolveRecoveryBody, settleFailedFixedSend } = require('../helpers/templateRecoveryHelper');
14
14
  const { getMessages } = require('../services/messageService');
15
15
  const { recordUndeliverable } = require('../services/undeliverableService');
16
16
 
@@ -104,6 +104,7 @@ class TemplateApprovalJob extends BaseJob {
104
104
 
105
105
  let provider;
106
106
  let approvalStatus;
107
+ let approvalCategory;
107
108
  let checkError = null;
108
109
  try {
109
110
  provider = this.requireProvider();
@@ -113,6 +114,7 @@ class TemplateApprovalJob extends BaseJob {
113
114
  'checkApprovalStatus'
114
115
  );
115
116
  approvalStatus = status?.approvalRequest?.status?.toUpperCase();
117
+ approvalCategory = status?.approvalRequest?.category?.toUpperCase();
116
118
  } catch (err) {
117
119
  checkError = err;
118
120
  }
@@ -131,7 +133,7 @@ class TemplateApprovalJob extends BaseJob {
131
133
  logger.info('[TemplateApprovalJob] Approval status', { templateSid, approvalStatus, attempt, messageId, originalMessageSid });
132
134
 
133
135
  if (approvalStatus === 'APPROVED') {
134
- return await this._handleApproved({ message, templateSid, originalMessageSid });
136
+ return await this._handleApproved({ message, templateSid, originalMessageSid, category: approvalCategory });
135
137
  }
136
138
  if (approvalStatus === 'REJECTED') {
137
139
  return await this._handleRejected({ provider, message, templateSid });
@@ -288,7 +290,21 @@ class TemplateApprovalJob extends BaseJob {
288
290
  return { sent: Boolean(result?.messageId), nudgeMessageId: result?.messageId || null };
289
291
  }
290
292
 
291
- async _handleApproved({ message, templateSid, originalMessageSid }) {
293
+ // Meta can approve a one-off template as MARKETING, which some patients never receive.
294
+ async _replacementFor(message, category) {
295
+ if (!category || category === 'UTILITY') return null;
296
+ try {
297
+ const body = await resolveRecoveryBody(message);
298
+ return hasUnresolvedPhi(body) ? null : await fixedRecoveryTemplate(message.media, body);
299
+ } catch (err) {
300
+ logger.warn('[TemplateApprovalJob] Could not build the fixed template, sending as approved', {
301
+ messageId: String(message._id), error: err.message
302
+ });
303
+ return null;
304
+ }
305
+ }
306
+
307
+ async _handleApproved({ message, templateSid, originalMessageSid, category }) {
292
308
  const claim = await Message.updateOne(
293
309
  { _id: message._id, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
294
310
  { $set: { 'statusInfo.recoverySentAt': new Date() } }
@@ -298,17 +314,27 @@ class TemplateApprovalJob extends BaseJob {
298
314
  return { success: false, reason: 'already_claimed' };
299
315
  }
300
316
 
317
+ const replacement = await this._replacementFor(message, category);
318
+
319
+ const send = (template) => this.sendMessage({
320
+ code: message.numero,
321
+ ...contactOf(message),
322
+ contentSid: template?.contentSid ?? templateSid,
323
+ variables: template?.variables ?? {},
324
+ parentMessageId: message._id,
325
+ kind: 'recovery_template',
326
+ body: message.body,
327
+ idempotencyKey: `recovery:${message._id}`
328
+ });
329
+
301
330
  let sendResult;
302
331
  try {
303
- sendResult = await this.sendMessage({
304
- code: message.numero,
305
- ...contactOf(message),
306
- contentSid: templateSid,
307
- variables: {},
308
- parentMessageId: message._id,
309
- kind: 'recovery_template',
310
- body: message.body,
311
- idempotencyKey: `recovery:${message._id}`
332
+ sendResult = await send(replacement).catch(async (err) => {
333
+ if (!replacement) throw err;
334
+ const acceptedSid = await settleFailedFixedSend(message, replacement.contentSid);
335
+ if (acceptedSid) return { messageId: acceptedSid };
336
+ logger.warn('[TemplateApprovalJob] Fixed template failed, sending as approved', { messageId: String(message._id), error: err.message });
337
+ return send(null);
312
338
  });
313
339
  if (sendResult?.duplicate) {
314
340
  logger.info('[TemplateApprovalJob] Recovery send already claimed elsewhere', { templateSid, messageId: message._id });
@@ -335,7 +361,7 @@ class TemplateApprovalJob extends BaseJob {
335
361
 
336
362
  await DeliveryAttempt.updateOne(
337
363
  { messageId: message._id, kind: 'recovery_template_setup', twilioSid: templateSid },
338
- { $set: { status: 'sent', completedAt: new Date() } }
364
+ { $set: { status: 'sent', ...(category && { templateCategory: category }), completedAt: new Date() } }
339
365
  );
340
366
 
341
367
  return { success: true, recoveryMessageId: sendResult.messageId };
@@ -26,6 +26,7 @@ const deliveryAttemptSchema = new mongoose.Schema({
26
26
  enum: STATUS_VALUES,
27
27
  default: null
28
28
  },
29
+ templateCategory: { type: String, default: null },
29
30
  errorCode: { type: String, default: null },
30
31
  errorMessage: { type: String, default: null },
31
32
  errorSource: {
@@ -53,6 +53,7 @@ async function releaseOne(message, now) {
53
53
  return false;
54
54
  }
55
55
 
56
+ const { media } = message;
56
57
  const body = await resolveRecoveryBody(message);
57
58
  if (hasUnresolvedPhi(body)) {
58
59
  logger.error('[HeldMessage] Body still carries a PHI placeholder, refusing to release', logCtx);
@@ -72,6 +73,7 @@ async function releaseOne(message, now) {
72
73
  code: message.numero,
73
74
  ...contactOf(message),
74
75
  body,
76
+ ...(media?.key && { media, fileUrl: `https://${media.bucketName}.s3.amazonaws.com/${media.key}`, fileType: media.mediaType }),
75
77
  parentMessageId: message._id,
76
78
  kind: 'freeform',
77
79
  idempotencyKey: `window-release:${message._id}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.3.3",
3
+ "version": "6.3.5",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",