@peopl-health/nexus 6.4.0-dev.18856 → 6.4.0-dev.18958

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.
Files changed (30) hide show
  1. package/lib/adapters/TwilioProvider.js +2 -31
  2. package/lib/clinical/services/treatmentProposalService.js +4 -26
  3. package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
  4. package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
  5. package/lib/config/recoveryTemplateConfig.js +21 -14
  6. package/lib/controllers/escalationReviewController.js +3 -20
  7. package/lib/controllers/prescriptionController.js +28 -4
  8. package/lib/core/NexusMessaging.js +9 -11
  9. package/lib/helpers/channelErrorHelper.js +6 -2
  10. package/lib/helpers/channelRetryHelper.js +70 -3
  11. package/lib/helpers/messageStatusHelper.js +13 -2
  12. package/lib/helpers/recoveryFallbackHelper.js +146 -0
  13. package/lib/helpers/templateRecoveryHelper.js +101 -51
  14. package/lib/index.d.ts +1 -1
  15. package/lib/jobs/TemplateApprovalJob.js +43 -31
  16. package/lib/models/escalationReviewModel.js +2 -38
  17. package/lib/models/messageModel.js +4 -1
  18. package/lib/routes/index.js +0 -2
  19. package/lib/services/assistantMessageService.js +6 -12
  20. package/lib/services/contactGateService.js +2 -2
  21. package/lib/services/escalationReviewService.js +13 -192
  22. package/lib/services/officeAssistantService.js +1 -1
  23. package/lib/utils/httpErrorUtils.js +1 -1
  24. package/lib/utils/templateTextUtils.js +64 -0
  25. package/lib/utils/templateUtils.js +4 -1
  26. package/package.json +1 -1
  27. package/lib/clinical/helpers/doctorPlanHelper.js +0 -105
  28. package/lib/clinical/helpers/planTextHelper.js +0 -127
  29. package/lib/clinical/services/doctorPlanService.js +0 -120
  30. package/lib/services/prescriptionService.js +0 -30
@@ -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 };
@@ -2,7 +2,10 @@ const { getRecoveryTemplateConfig } = require('../config/recoveryTemplateConfig'
2
2
  const { generatePresignedUrl } = require('../config/awsConfig');
3
3
  const { logger } = require('../utils/logger');
4
4
  const { isAtOrBefore } = require('../utils/dateUtils');
5
+ const { oneLineOf } = require('../utils/coercionUtils');
6
+ const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
5
7
  const { createEvent, safeEmit } = require('../utils/eventUtils');
8
+ const { shapeTemplateParts } = require('../utils/templateTextUtils');
6
9
  const { Message } = require('../models/messageModel');
7
10
  const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
8
11
  const { Template: TemplateModel } = require('../models/templateModel');
@@ -11,18 +14,21 @@ const { contactOf } = require('./caregiverHelper');
11
14
  const { recordDeliveryAttempt } = require('./deliveryAttemptHelper');
12
15
 
13
16
  const getMessaging = () => require('../core/NexusMessaging');
17
+ const getFallback = () => require('./recoveryFallbackHelper');
14
18
 
15
19
  const TEMPLATE_BODY_LIMIT = 1024;
16
20
  const RECOVERY_MEDIA_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
17
21
 
18
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;
19
26
  const FIXED_FILE_TEMPLATE_KEYS = {
20
27
  'application/pdf': 'RECOVERY_DOCUMENT_TEMPLATE_SID',
21
28
  'image/jpeg': 'RECOVERY_IMAGE_TEMPLATE_SID',
22
29
  'image/png': 'RECOVERY_IMAGE_TEMPLATE_SID'
23
30
  };
24
- const FIXED_TEMPLATE_TEXT_LIMIT = 800;
25
- const FIXED_TEMPLATE_DEFAULT_TEXT = 'Te compartimos un archivo.';
31
+ const FIXED_TEMPLATE_DEFAULT_TEXT = 'Tienes un archivo nuevo.';
26
32
  const FIXED_TEMPLATE_MEDIA_PREFIX_KEY = 'RECOVERY_TEMPLATE_MEDIA_PREFIX';
27
33
 
28
34
  async function resolveRecoveryMediaUrl(media) {
@@ -43,24 +49,37 @@ function hasUnresolvedPhi(body) {
43
49
 
44
50
  async function resolveRecoveryBody(messageDoc) {
45
51
  if (messageDoc.plainBody) return messageDoc.plainBody;
52
+ if (!messageDoc.body) return '';
46
53
  const decoded = await getMessaging().getPhiProcessor()?.decodeBody(messageDoc.body, messageDoc.numero);
47
54
  return decoded || messageDoc.body;
48
55
  }
49
56
 
50
57
  const EXPIRED_ERROR_MESSAGE = 'Expired before it could be delivered';
51
58
 
52
- // Approved UTILITY, so Meta cannot reclassify it per message; null keeps the one-off template.
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
+
53
67
  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
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
+
74
+ const text = oneLineOf(body);
75
+ if (text.length > MAX_TEMPLATE_TEXT_LENGTH) return null;
57
76
 
58
77
  if (!media?.key) {
59
78
  const contentSid = config[FIXED_TEXT_TEMPLATE_KEY];
60
79
  return contentSid && text ? { contentSid, variables: { 1: text } } : null;
61
80
  }
62
81
 
63
- const contentSid = config[FIXED_FILE_TEMPLATE_KEYS[media.contentType]];
82
+ const contentSid = config[FIXED_FILE_TEMPLATE_KEYS[media.contentType?.split(';')[0].trim().toLowerCase()]];
64
83
  const mediaPrefix = config[FIXED_TEMPLATE_MEDIA_PREFIX_KEY];
65
84
  if (!contentSid || !mediaPrefix) return null;
66
85
  const mediaUrl = await resolveRecoveryMediaUrl(media);
@@ -71,50 +90,72 @@ async function fixedRecoveryTemplate(media, body) {
71
90
  return { contentSid, variables: { 1: text || FIXED_TEMPLATE_DEFAULT_TEXT, 2: mediaUrl.slice(mediaPrefix.length) } };
72
91
  }
73
92
 
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;
93
+ async function fixedTemplateFor(messageDoc) {
94
+ try {
95
+ const body = await resolveRecoveryBody(messageDoc);
96
+ return hasUnresolvedPhi(body) ? null : await fixedRecoveryTemplate(messageDoc.media, body);
97
+ } catch (error) {
98
+ logger.warn('[TemplateRecovery] Could not build the fixed template', { messageDocId: String(messageDoc._id), error: error.message });
99
+ return null;
100
+ }
101
+ }
102
+
103
+ const recoverySendData = (messageDoc, template) => ({
104
+ code: messageDoc.numero,
105
+ ...contactOf(messageDoc),
106
+ ...template,
107
+ parentMessageId: messageDoc._id,
108
+ kind: 'recovery_template',
109
+ body: messageDoc.body
110
+ });
111
+
112
+ async function claimRecoverySend(messageId, extra = {}) {
113
+ const claim = await Message.updateOne(
114
+ { _id: messageId, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
115
+ { $set: { 'statusInfo.recoverySentAt': new Date(), ...extra } }
116
+ );
117
+ return Boolean(claim.modifiedCount || claim.nModified);
118
+ }
119
+
120
+ async function acceptedFixedSid(messageId, contentSid) {
121
+ const accepted = await DeliveryAttempt.findOne({ messageId, contentSid, twilioSid: { $ne: null } }, 'twilioSid').lean();
122
+ return accepted?.twilioSid ?? null;
123
+ }
124
+
125
+ function emitRecoveryStatus(messageDoc, status) {
126
+ safeEmit(getMessaging().getEventBus(), 'message:status', createEvent('message:status', {
127
+ messageId: String(messageDoc._id),
128
+ to: messageDoc.numero,
129
+ status
130
+ }));
131
+ }
132
+
133
+ async function reopenAfterFixedFailure(messageDoc) {
80
134
  await Message.updateOne(
81
135
  { _id: messageDoc._id },
82
136
  { $set: { 'statusInfo.status': 'queued' }, $unset: { 'statusInfo.errorCode': '', 'statusInfo.errorMessage': '' } }
83
137
  );
84
- return null;
138
+ emitRecoveryStatus(messageDoc, 'queued');
85
139
  }
86
140
 
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';
141
+ async function sendFixedRecovery(messageDoc, template, logCtx, send) {
142
+ if (!await claimRecoverySend(messageDoc._id)) return { outcome: 'skipped' };
93
143
 
94
144
  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';
145
+ const result = await send(recoverySendData(messageDoc, template));
146
+ if (result?.duplicate || result?.status === 'outbound_blocked') return { outcome: 'skipped' };
107
147
  if (!result?.messageId) throw new Error('Provider did not return a messageId for the fixed template send');
108
148
  logger.info('[TemplateRecovery] Sent on the fixed template', { ...logCtx, contentSid: template.contentSid });
109
- return 'sent';
149
+ return { outcome: 'sent', result };
110
150
  } catch (error) {
111
- if (await settleFailedFixedSend(messageDoc, template.contentSid)) {
151
+ const messageId = await acceptedFixedSid(messageDoc._id, template.contentSid);
152
+ if (messageId) {
112
153
  logger.error('[TemplateRecovery] Fixed template reached the provider but bookkeeping failed', { ...logCtx, error: error.message });
113
- return 'sent';
154
+ return { outcome: 'sent', result: { messageId } };
114
155
  }
115
156
  await Message.updateOne({ _id: messageDoc._id }, { $unset: { 'statusInfo.recoverySentAt': '' } });
116
157
  logger.warn('[TemplateRecovery] Fixed template send failed, using a one-off template', { ...logCtx, error: error.message });
117
- return null;
158
+ return { outcome: 'failed' };
118
159
  }
119
160
  }
120
161
 
@@ -144,9 +185,9 @@ async function closeExpiredRecovery(messageDoc) {
144
185
  await cleanupRecoveryTemplate(messageDoc);
145
186
  }
146
187
 
147
- async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messageSid = null } = {}) {
188
+ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messageSid = null, contactGateDecisionId = null } = {}) {
148
189
  try {
149
- if (!messageDoc?.body || !messageDoc?.numero || !messageDoc?._id) return;
190
+ if ((!messageDoc?.body && !messageDoc?.media?.key) || !messageDoc?.numero || !messageDoc?._id) return;
150
191
 
151
192
  const messageDocId = messageDoc._id;
152
193
  const logCtx = { source, messageSid, messageDocId: String(messageDocId) };
@@ -193,14 +234,19 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
193
234
 
194
235
  const recoveryBody = await resolveRecoveryBody(messageDoc);
195
236
 
237
+ const send = (data) => source === 'preemptive'
238
+ ? getMessaging().requireDefaultInstance()._transport({ ...data, contactGateDecisionId })
239
+ : getMessaging().sendMessage({ idempotencyKey: `recovery-fixed:${messageDocId}`, ...data });
240
+
196
241
  let fixedSendFailed = false;
197
242
  if (messageDoc.media?.key && !hasUnresolvedPhi(recoveryBody)) {
198
243
  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;
244
+ if (fixedTemplate) {
245
+ const { outcome, result } = await sendFixedRecovery(messageDoc, fixedTemplate, logCtx, send);
246
+ if (outcome === 'sent') return { delivered: false, deferred: false, fixedSend: result };
247
+ if (outcome === 'skipped') return { delivered: false, deferred: true };
248
+ fixedSendFailed = true;
249
+ }
204
250
  }
205
251
 
206
252
  const templateName = `auto_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
@@ -210,10 +256,19 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
210
256
  const mediaUrl = await resolveRecoveryMediaUrl(messageDoc.media);
211
257
  if (mediaUrl) template.setMedia(mediaUrl);
212
258
 
259
+ const tooLongForTemplate = recoveryBody.length > TEMPLATE_BODY_LIMIT && !messageDoc.media?.key && await getFallback().isFallbackEnabled();
260
+
213
261
  let twilioContent;
214
262
  let setupErr = null;
215
- if (hasUnresolvedPhi(recoveryBody)) {
263
+ if (!recoveryBody) {
264
+ setupErr = new Error('A file with no text can only go out on a fixed template');
265
+ } else if (hasUnresolvedPhi(recoveryBody)) {
216
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})`);
217
272
  } else if (recoveryBody.length > TEMPLATE_BODY_LIMIT) {
218
273
  setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length})`);
219
274
  } else {
@@ -236,6 +291,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
236
291
 
237
292
  if (setupErr) {
238
293
  logger.error('[TemplateRecovery] Setup failed', { ...logCtx, error: setupErr.message });
294
+ emitRecoveryStatus(messageDoc, 'failed');
239
295
  if (twilioContent?.sid) {
240
296
  provider.deleteTemplate(twilioContent.sid).catch(deleteErr =>
241
297
  logger.warn('[TemplateRecovery] Failed to delete partially-created template', { templateSid: twilioContent.sid, error: deleteErr.message })
@@ -271,13 +327,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
271
327
  originalMessageSid: messageSid
272
328
  });
273
329
 
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
- }
330
+ if (fixedSendFailed) await reopenAfterFixedFailure(messageDoc);
281
331
  return { delivered: false, deferred: true };
282
332
  } catch (error) {
283
333
  logger.error('[TemplateRecovery] Error', { source, messageSid, error: error.message });
@@ -307,4 +357,4 @@ async function cleanupRecoveryTemplate(messageDoc) {
307
357
  }
308
358
  }
309
359
 
310
- module.exports = { settleFailedFixedSend, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, fixedRecoveryTemplate, hasUnresolvedPhi, closeExpiredRecovery };
360
+ module.exports = { acceptedFixedSid, claimRecoverySend, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, fixedTextMessages, hasUnresolvedPhi, closeExpiredRecovery };
package/lib/index.d.ts CHANGED
@@ -274,7 +274,7 @@ declare module '@peopl-health/nexus' {
274
274
  initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
275
275
  getWorkflowRunner(): WorkflowRunner;
276
276
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
277
- processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<{ delivery: Record<string, unknown> | null; sendThrew: boolean; reply: string | null } | undefined>;
277
+ processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
278
278
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
279
279
  processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
280
280
  processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
@@ -10,7 +10,8 @@ const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
10
10
  const { alertUndeliverable } = require('../helpers/channelRetryHelper');
11
11
 
12
12
  const { contactOf } = require('../helpers/caregiverHelper');
13
- const { closeExpiredRecovery, fixedRecoveryTemplate, hasUnresolvedPhi, resolveRecoveryBody, settleFailedFixedSend } = require('../helpers/templateRecoveryHelper');
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) {
@@ -290,40 +324,17 @@ class TemplateApprovalJob extends BaseJob {
290
324
  return { sent: Boolean(result?.messageId), nudgeMessageId: result?.messageId || null };
291
325
  }
292
326
 
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
327
  async _handleApproved({ message, templateSid, originalMessageSid, category }) {
308
- const claim = await Message.updateOne(
309
- { _id: message._id, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
310
- { $set: { 'statusInfo.recoverySentAt': new Date() } }
311
- );
312
- if (!claim.modifiedCount && !claim.nModified) {
328
+ if (!await claimRecoverySend(message._id)) {
313
329
  logger.info('[TemplateApprovalJob] Send already claimed by another worker', { templateSid, messageId: message._id });
314
330
  return { success: false, reason: 'already_claimed' };
315
331
  }
316
332
 
317
- const replacement = await this._replacementFor(message, category);
333
+ // Meta can approve a one-off template as MARKETING, which some patients never receive.
334
+ const replacement = category && category !== 'UTILITY' ? await fixedTemplateFor(message) : null;
318
335
 
319
336
  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,
337
+ ...recoverySendData(message, template ?? { contentSid: templateSid, variables: {} }),
327
338
  idempotencyKey: `recovery:${message._id}`
328
339
  });
329
340
 
@@ -331,8 +342,9 @@ class TemplateApprovalJob extends BaseJob {
331
342
  try {
332
343
  sendResult = await send(replacement).catch(async (err) => {
333
344
  if (!replacement) throw err;
334
- const acceptedSid = await settleFailedFixedSend(message, replacement.contentSid);
345
+ const acceptedSid = await acceptedFixedSid(message._id, replacement.contentSid);
335
346
  if (acceptedSid) return { messageId: acceptedSid };
347
+ await reopenAfterFixedFailure(message);
336
348
  logger.warn('[TemplateApprovalJob] Fixed template failed, sending as approved', { messageId: String(message._id), error: err.message });
337
349
  return send(null);
338
350
  });
@@ -12,8 +12,7 @@ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
12
12
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
13
13
  const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
14
14
  const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
15
- const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'plan_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
16
- const PLAN_FOLLOW_UPS = ['none', 'check_in', 'vigilancia'];
15
+ const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
17
16
  const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
18
17
  const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
19
18
 
@@ -194,43 +193,11 @@ const doctorHandoffSchema = new mongoose.Schema({
194
193
  sentBy: { type: String, required: true },
195
194
  }, { timestamps: { createdAt: true, updatedAt: false } });
196
195
 
197
- const planItemSchema = new mongoose.Schema({
198
- drug: { type: String, required: true },
199
- strength: { type: String, default: null },
200
- dose: { type: String, required: true },
201
- frequency: { type: String, required: true },
202
- days: { type: Number, required: true },
203
- position: { type: String, default: null },
204
- reason: { type: String, default: null },
205
- formularyKey: { type: String, default: null },
206
- }, { _id: false });
207
-
208
- const planSchema = new mongoose.Schema({
209
- items: { type: [planItemSchema], default: [] },
210
- studies: {
211
- type: [new mongoose.Schema({ name: { type: String, required: true }, instructions: { type: String, default: null } }, { _id: false })],
212
- default: [],
213
- },
214
- homeCare: { type: [String], default: [] },
215
- note: { type: String, default: null },
216
- followUp: {
217
- type: new mongoose.Schema({ kind: { type: String, enum: PLAN_FOLLOW_UPS, required: true }, hours: { type: Number, default: null } }, { _id: false }),
218
- required: true,
219
- },
220
- instructions: { type: String, required: true },
221
- instructionsEdited: { type: Boolean, default: false },
222
- prescriber: {
223
- type: new mongoose.Schema({ name: { type: String, default: null }, email: { type: String, required: true } }, { _id: false }),
224
- default: null,
225
- },
226
- }, { _id: false });
227
-
228
196
  const decisionSchema = new mongoose.Schema({
229
197
  decision: { type: String, enum: DOCTOR_DECISIONS, required: true },
230
198
  source: { type: String, enum: DECISION_SOURCES, required: true },
231
199
  draftNumber: { type: Number, required: true },
232
200
  finalText: { type: String, default: null },
233
- plan: { type: planSchema, default: undefined },
234
201
  comment: { type: String, default: null },
235
202
  doctorReply: { type: String, default: null },
236
203
  returnReason: { type: String, enum: [...RETURN_REASONS, null], default: null },
@@ -243,9 +210,7 @@ const patientDeliverySchema = new mongoose.Schema({
243
210
  decisionNumber: { type: Number, required: true },
244
211
  messageId: { type: String, default: null },
245
212
  status: { type: String, default: null },
246
- transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template', 'assistant'], required: true },
247
- prescriptionRecordId: { type: String, default: null },
248
- checks: { type: [String], default: undefined },
213
+ transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template'], required: true },
249
214
  deferred: { type: Boolean, default: false },
250
215
  confirmedBy: { type: String, default: null },
251
216
  confirmedAt: { type: Date, default: null },
@@ -416,7 +381,6 @@ module.exports = {
416
381
  DOCTOR_DECISIONS,
417
382
  HANDOFF_MODES,
418
383
  INTERRUPTED_STATUSES,
419
- PLAN_FOLLOW_UPS,
420
384
  FOLLOWUP_STATUSES,
421
385
  RETURN_REASONS,
422
386
  URGENCY_LEVELS,
@@ -76,12 +76,15 @@ const messageSchema = new mongoose.Schema({
76
76
  recoveryTemplateSid: { type: String, default: null },
77
77
  recoveryStartedAt: { type: Date, default: null },
78
78
  recoverySentAt: { type: Date, default: null },
79
+ blockedRetryAt: { type: Date, default: null },
79
80
  recoveryRejectedAt: { type: Date, default: null },
80
81
  recoveryFailedAt: { type: Date, default: null },
81
82
  recoveryCheckedAt: { type: Date, default: null },
82
83
  recoveryAttempt: { type: Number, default: null },
83
84
  recoveryWarnedAt: { type: Date, default: null },
84
- recoveryReleasedAt: { type: Date, default: null }
85
+ recoveryReleasedAt: { type: Date, default: null },
86
+ recoveryFallbackAt: { type: Date, default: null },
87
+ recoveryFallbackReason: { type: String, default: null }
85
88
  },
86
89
  prompt: { type: Object, default: null },
87
90
  preset: { type: Object, default: null },
@@ -138,7 +138,6 @@ const escalationReviewRouteDefinitions = {
138
138
  'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
139
139
  'POST /:id/drafts': 'addEscalationReviewDraftController',
140
140
  'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
141
- 'POST /:id/plan-instructions': 'previewEscalationReviewPlanController',
142
141
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
143
142
  'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
144
143
  'POST /:id/close': 'closeEscalationReviewController',
@@ -315,7 +314,6 @@ const builtInControllers = {
315
314
  listReviewBoardController: escalationReviewController.listReviewBoardController,
316
315
  getEscalationReviewController: escalationReviewController.getEscalationReviewController,
317
316
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
318
- previewEscalationReviewPlanController: escalationReviewController.previewEscalationReviewPlanController,
319
317
  requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
320
318
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
321
319
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,