@peopl-health/nexus 6.3.4 → 6.3.6
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/config/recoveryTemplateConfig.js +38 -0
- package/lib/core/NexusMessaging.js +6 -4
- package/lib/helpers/templateRecoveryHelper.js +128 -4
- package/lib/jobs/TemplateApprovalJob.js +22 -18
- package/lib/models/deliveryAttemptModel.js +1 -0
- package/lib/services/escalationReviewService.js +1 -1
- package/lib/services/officeAssistantService.js +1 -1
- package/lib/utils/templateUtils.js +4 -1
- package/package.json +1 -1
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
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 REFRESH_MS = 5 * 60 * 1000;
|
|
9
|
+
const FAILED_READ_RETRY_MS = 60 * 1000;
|
|
10
|
+
const READ_TIMEOUT_MS = 5000;
|
|
11
|
+
|
|
12
|
+
let lastGoodConfig = null;
|
|
13
|
+
let nextReadAt = 0;
|
|
14
|
+
|
|
15
|
+
async function readConfig() {
|
|
16
|
+
const records = await withTimeout(getRecordByFilter(Config_ID, RECOVERY_TEMPLATES_TABLE, 'TRUE()'), READ_TIMEOUT_MS, RECOVERY_TEMPLATES_TABLE);
|
|
17
|
+
const rows = records.filter((row) => row.is_active && row.source === programConfigSource());
|
|
18
|
+
return Object.fromEntries(rows.map((row) => [row.config, row.value]));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
async function getRecoveryTemplateConfig() {
|
|
22
|
+
if (Date.now() < nextReadAt) return lastGoodConfig;
|
|
23
|
+
try {
|
|
24
|
+
lastGoodConfig = await readConfig();
|
|
25
|
+
nextReadAt = Date.now() + REFRESH_MS;
|
|
26
|
+
} catch (error) {
|
|
27
|
+
logger.warn('[recoveryTemplateConfig] Could not read the fixed templates', { error: error.message });
|
|
28
|
+
nextReadAt = lastGoodConfig ? Date.now() + FAILED_READ_RETRY_MS : 0;
|
|
29
|
+
}
|
|
30
|
+
return lastGoodConfig ?? {};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function _resetRecoveryTemplateConfig() {
|
|
34
|
+
lastGoodConfig = null;
|
|
35
|
+
nextReadAt = 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { getRecoveryTemplateConfig, _resetRecoveryTemplateConfig };
|
|
@@ -476,14 +476,15 @@ class NexusMessaging {
|
|
|
476
476
|
);
|
|
477
477
|
}
|
|
478
478
|
|
|
479
|
-
// Builds a one-off approved template from THIS message's own text and sends it once Meta approves.
|
|
480
|
-
// The window decides the transport, never the wording.
|
|
481
479
|
async _routeThroughTemplateRecovery(messageData) {
|
|
480
|
+
const { contactGateDecisionId } = messageData;
|
|
481
|
+
const fixedResult = ({ messageId, status }) => ({ success: true, messageId, status: status || 'sent', delivered: false, deferred: false });
|
|
482
482
|
if (messageData.parentMessageId) {
|
|
483
483
|
const [found] = await getMessages({ _id: messageData.parentMessageId }, { limit: 1 });
|
|
484
484
|
if (!found) return { success: false, delivered: false, deferred: true };
|
|
485
|
-
const queued = await triggerTemplateRecovery(found, { source: 'preemptive' });
|
|
485
|
+
const queued = await triggerTemplateRecovery(found, { source: 'preemptive', contactGateDecisionId });
|
|
486
486
|
if (queued?.expired) return { ...NOT_SENT_EXPIRED, messageId: String(found._id) };
|
|
487
|
+
if (queued?.fixedSend) return fixedResult(queued.fixedSend);
|
|
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,11 @@ 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 }, { source: 'preemptive', contactGateDecisionId });
|
|
503
504
|
if (queued?.expired) {
|
|
504
505
|
return { ...NOT_SENT_EXPIRED, messageId: String(_id) };
|
|
505
506
|
}
|
|
507
|
+
if (queued?.fixedSend) return fixedResult(queued.fixedSend);
|
|
506
508
|
if (!queued?.deferred) {
|
|
507
509
|
logger.error('[NexusMessaging] template recovery setup failed; message not queued', { code: messageData.code, messageId: String(_id) });
|
|
508
510
|
return { success: false, messageId: String(_id), status: 'failed', preemptive: true, delivered: false, deferred: false };
|
|
@@ -1,10 +1,15 @@
|
|
|
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');
|
|
5
|
+
const { oneLineOf } = require('../utils/coercionUtils');
|
|
6
|
+
const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
|
|
4
7
|
const { createEvent, safeEmit } = require('../utils/eventUtils');
|
|
5
8
|
const { Message } = require('../models/messageModel');
|
|
9
|
+
const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
|
|
6
10
|
const { Template: TemplateModel } = require('../models/templateModel');
|
|
7
11
|
const { Template } = require('../templates/templateStructure');
|
|
12
|
+
const { contactOf } = require('./caregiverHelper');
|
|
8
13
|
const { recordDeliveryAttempt } = require('./deliveryAttemptHelper');
|
|
9
14
|
|
|
10
15
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
@@ -12,6 +17,15 @@ const getMessaging = () => require('../core/NexusMessaging');
|
|
|
12
17
|
const TEMPLATE_BODY_LIMIT = 1024;
|
|
13
18
|
const RECOVERY_MEDIA_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
14
19
|
|
|
20
|
+
const FIXED_TEXT_TEMPLATE_KEY = 'RECOVERY_TEXT_TEMPLATE_SID';
|
|
21
|
+
const FIXED_FILE_TEMPLATE_KEYS = {
|
|
22
|
+
'application/pdf': 'RECOVERY_DOCUMENT_TEMPLATE_SID',
|
|
23
|
+
'image/jpeg': 'RECOVERY_IMAGE_TEMPLATE_SID',
|
|
24
|
+
'image/png': 'RECOVERY_IMAGE_TEMPLATE_SID'
|
|
25
|
+
};
|
|
26
|
+
const FIXED_TEMPLATE_DEFAULT_TEXT = 'Tienes un archivo nuevo.';
|
|
27
|
+
const FIXED_TEMPLATE_MEDIA_PREFIX_KEY = 'RECOVERY_TEMPLATE_MEDIA_PREFIX';
|
|
28
|
+
|
|
15
29
|
async function resolveRecoveryMediaUrl(media) {
|
|
16
30
|
if (!media?.bucketName || !media?.key) return null;
|
|
17
31
|
try {
|
|
@@ -30,12 +44,103 @@ function hasUnresolvedPhi(body) {
|
|
|
30
44
|
|
|
31
45
|
async function resolveRecoveryBody(messageDoc) {
|
|
32
46
|
if (messageDoc.plainBody) return messageDoc.plainBody;
|
|
47
|
+
if (!messageDoc.body) return '';
|
|
33
48
|
const decoded = await getMessaging().getPhiProcessor()?.decodeBody(messageDoc.body, messageDoc.numero);
|
|
34
49
|
return decoded || messageDoc.body;
|
|
35
50
|
}
|
|
36
51
|
|
|
37
52
|
const EXPIRED_ERROR_MESSAGE = 'Expired before it could be delivered';
|
|
38
53
|
|
|
54
|
+
async function fixedRecoveryTemplate(media, body) {
|
|
55
|
+
const text = oneLineOf(body);
|
|
56
|
+
if (text.length > MAX_TEMPLATE_TEXT_LENGTH) return null;
|
|
57
|
+
const config = await getRecoveryTemplateConfig();
|
|
58
|
+
|
|
59
|
+
if (!media?.key) {
|
|
60
|
+
const contentSid = config[FIXED_TEXT_TEMPLATE_KEY];
|
|
61
|
+
return contentSid && text ? { contentSid, variables: { 1: text } } : null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const contentSid = config[FIXED_FILE_TEMPLATE_KEYS[media.contentType?.split(';')[0].trim().toLowerCase()]];
|
|
65
|
+
const mediaPrefix = config[FIXED_TEMPLATE_MEDIA_PREFIX_KEY];
|
|
66
|
+
if (!contentSid || !mediaPrefix) return null;
|
|
67
|
+
const mediaUrl = await resolveRecoveryMediaUrl(media);
|
|
68
|
+
if (!mediaUrl?.startsWith(mediaPrefix)) {
|
|
69
|
+
logger.warn('[TemplateRecovery] Signed URL does not match the fixed template, using a one-off template', { contentSid });
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
return { contentSid, variables: { 1: text || FIXED_TEMPLATE_DEFAULT_TEXT, 2: mediaUrl.slice(mediaPrefix.length) } };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function fixedTemplateFor(messageDoc) {
|
|
76
|
+
try {
|
|
77
|
+
const body = await resolveRecoveryBody(messageDoc);
|
|
78
|
+
return hasUnresolvedPhi(body) ? null : await fixedRecoveryTemplate(messageDoc.media, body);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
logger.warn('[TemplateRecovery] Could not build the fixed template', { messageDocId: String(messageDoc._id), error: error.message });
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const recoverySendData = (messageDoc, template) => ({
|
|
86
|
+
code: messageDoc.numero,
|
|
87
|
+
...contactOf(messageDoc),
|
|
88
|
+
...template,
|
|
89
|
+
parentMessageId: messageDoc._id,
|
|
90
|
+
kind: 'recovery_template',
|
|
91
|
+
body: messageDoc.body
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
async function claimRecoverySend(messageId) {
|
|
95
|
+
const claim = await Message.updateOne(
|
|
96
|
+
{ _id: messageId, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
|
|
97
|
+
{ $set: { 'statusInfo.recoverySentAt': new Date() } }
|
|
98
|
+
);
|
|
99
|
+
return Boolean(claim.modifiedCount || claim.nModified);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function acceptedFixedSid(messageId, contentSid) {
|
|
103
|
+
const accepted = await DeliveryAttempt.findOne({ messageId, contentSid, twilioSid: { $ne: null } }, 'twilioSid').lean();
|
|
104
|
+
return accepted?.twilioSid ?? null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function emitRecoveryStatus(messageDoc, status) {
|
|
108
|
+
safeEmit(getMessaging().getEventBus(), 'message:status', createEvent('message:status', {
|
|
109
|
+
messageId: String(messageDoc._id),
|
|
110
|
+
to: messageDoc.numero,
|
|
111
|
+
status
|
|
112
|
+
}));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function reopenAfterFixedFailure(messageDoc) {
|
|
116
|
+
await Message.updateOne(
|
|
117
|
+
{ _id: messageDoc._id },
|
|
118
|
+
{ $set: { 'statusInfo.status': 'queued' }, $unset: { 'statusInfo.errorCode': '', 'statusInfo.errorMessage': '' } }
|
|
119
|
+
);
|
|
120
|
+
emitRecoveryStatus(messageDoc, 'queued');
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function sendFixedRecovery(messageDoc, template, logCtx, send) {
|
|
124
|
+
if (!await claimRecoverySend(messageDoc._id)) return { outcome: 'skipped' };
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
const result = await send(recoverySendData(messageDoc, template));
|
|
128
|
+
if (result?.duplicate || result?.status === 'outbound_blocked') return { outcome: 'skipped' };
|
|
129
|
+
if (!result?.messageId) throw new Error('Provider did not return a messageId for the fixed template send');
|
|
130
|
+
logger.info('[TemplateRecovery] Sent on the fixed template', { ...logCtx, contentSid: template.contentSid });
|
|
131
|
+
return { outcome: 'sent', result };
|
|
132
|
+
} catch (error) {
|
|
133
|
+
const messageId = await acceptedFixedSid(messageDoc._id, template.contentSid);
|
|
134
|
+
if (messageId) {
|
|
135
|
+
logger.error('[TemplateRecovery] Fixed template reached the provider but bookkeeping failed', { ...logCtx, error: error.message });
|
|
136
|
+
return { outcome: 'sent', result: { messageId } };
|
|
137
|
+
}
|
|
138
|
+
await Message.updateOne({ _id: messageDoc._id }, { $unset: { 'statusInfo.recoverySentAt': '' } });
|
|
139
|
+
logger.warn('[TemplateRecovery] Fixed template send failed, using a one-off template', { ...logCtx, error: error.message });
|
|
140
|
+
return { outcome: 'failed' };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
39
144
|
async function closeExpiredRecovery(messageDoc) {
|
|
40
145
|
const claim = await Message.updateOne(
|
|
41
146
|
{ _id: messageDoc._id, 'statusInfo.recoveryReleasedAt': null, 'statusInfo.recoverySentAt': null },
|
|
@@ -62,9 +167,9 @@ async function closeExpiredRecovery(messageDoc) {
|
|
|
62
167
|
await cleanupRecoveryTemplate(messageDoc);
|
|
63
168
|
}
|
|
64
169
|
|
|
65
|
-
async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messageSid = null } = {}) {
|
|
170
|
+
async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messageSid = null, contactGateDecisionId = null } = {}) {
|
|
66
171
|
try {
|
|
67
|
-
if (!messageDoc?.body || !messageDoc?.numero || !messageDoc?._id) return;
|
|
172
|
+
if ((!messageDoc?.body && !messageDoc?.media?.key) || !messageDoc?.numero || !messageDoc?._id) return;
|
|
68
173
|
|
|
69
174
|
const messageDocId = messageDoc._id;
|
|
70
175
|
const logCtx = { source, messageSid, messageDocId: String(messageDocId) };
|
|
@@ -110,6 +215,21 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
110
215
|
}
|
|
111
216
|
|
|
112
217
|
const recoveryBody = await resolveRecoveryBody(messageDoc);
|
|
218
|
+
|
|
219
|
+
let fixedSendFailed = false;
|
|
220
|
+
if (messageDoc.media?.key && !hasUnresolvedPhi(recoveryBody)) {
|
|
221
|
+
const fixedTemplate = await fixedRecoveryTemplate(messageDoc.media, recoveryBody);
|
|
222
|
+
if (fixedTemplate) {
|
|
223
|
+
const send = (data) => source === 'preemptive'
|
|
224
|
+
? getMessaging().requireDefaultInstance()._transport({ ...data, contactGateDecisionId })
|
|
225
|
+
: getMessaging().sendMessage({ ...data, idempotencyKey: `recovery-fixed:${messageDocId}` });
|
|
226
|
+
const { outcome, result } = await sendFixedRecovery(messageDoc, fixedTemplate, logCtx, send);
|
|
227
|
+
if (outcome === 'sent') return { delivered: false, deferred: false, fixedSend: result };
|
|
228
|
+
if (outcome === 'skipped') return { delivered: false, deferred: true };
|
|
229
|
+
fixedSendFailed = true;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
113
233
|
const templateName = `auto_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
|
114
234
|
const template = new Template(templateName, 'UTILITY', 'es');
|
|
115
235
|
template.setBody(recoveryBody, []);
|
|
@@ -119,7 +239,9 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
119
239
|
|
|
120
240
|
let twilioContent;
|
|
121
241
|
let setupErr = null;
|
|
122
|
-
if (
|
|
242
|
+
if (!recoveryBody) {
|
|
243
|
+
setupErr = new Error('A file with no text can only go out on a fixed template');
|
|
244
|
+
} else if (hasUnresolvedPhi(recoveryBody)) {
|
|
123
245
|
setupErr = new Error('Body still carries a PHI placeholder after decoding');
|
|
124
246
|
} else if (recoveryBody.length > TEMPLATE_BODY_LIMIT) {
|
|
125
247
|
setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length})`);
|
|
@@ -143,6 +265,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
143
265
|
|
|
144
266
|
if (setupErr) {
|
|
145
267
|
logger.error('[TemplateRecovery] Setup failed', { ...logCtx, error: setupErr.message });
|
|
268
|
+
emitRecoveryStatus(messageDoc, 'failed');
|
|
146
269
|
if (twilioContent?.sid) {
|
|
147
270
|
provider.deleteTemplate(twilioContent.sid).catch(deleteErr =>
|
|
148
271
|
logger.warn('[TemplateRecovery] Failed to delete partially-created template', { templateSid: twilioContent.sid, error: deleteErr.message })
|
|
@@ -178,6 +301,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
178
301
|
originalMessageSid: messageSid
|
|
179
302
|
});
|
|
180
303
|
|
|
304
|
+
if (fixedSendFailed) await reopenAfterFixedFailure(messageDoc);
|
|
181
305
|
return { delivered: false, deferred: true };
|
|
182
306
|
} catch (error) {
|
|
183
307
|
logger.error('[TemplateRecovery] Error', { source, messageSid, error: error.message });
|
|
@@ -207,4 +331,4 @@ async function cleanupRecoveryTemplate(messageDoc) {
|
|
|
207
331
|
}
|
|
208
332
|
}
|
|
209
333
|
|
|
210
|
-
module.exports = { handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi, closeExpiredRecovery };
|
|
334
|
+
module.exports = { acceptedFixedSid, claimRecoverySend, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, 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 { acceptedFixedSid, claimRecoverySend, closeExpiredRecovery, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure } = 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,27 +290,29 @@ 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 }) {
|
|
292
|
-
|
|
293
|
-
{ _id: message._id, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
|
|
294
|
-
{ $set: { 'statusInfo.recoverySentAt': new Date() } }
|
|
295
|
-
);
|
|
296
|
-
if (!claim.modifiedCount && !claim.nModified) {
|
|
293
|
+
async _handleApproved({ message, templateSid, originalMessageSid, category }) {
|
|
294
|
+
if (!await claimRecoverySend(message._id)) {
|
|
297
295
|
logger.info('[TemplateApprovalJob] Send already claimed by another worker', { templateSid, messageId: message._id });
|
|
298
296
|
return { success: false, reason: 'already_claimed' };
|
|
299
297
|
}
|
|
300
298
|
|
|
299
|
+
// Meta can approve a one-off template as MARKETING, which some patients never receive.
|
|
300
|
+
const replacement = category && category !== 'UTILITY' ? await fixedTemplateFor(message) : null;
|
|
301
|
+
|
|
302
|
+
const send = (template) => this.sendMessage({
|
|
303
|
+
...recoverySendData(message, template ?? { contentSid: templateSid, variables: {} }),
|
|
304
|
+
idempotencyKey: `recovery:${message._id}`
|
|
305
|
+
});
|
|
306
|
+
|
|
301
307
|
let sendResult;
|
|
302
308
|
try {
|
|
303
|
-
sendResult = await
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
body: message.body,
|
|
311
|
-
idempotencyKey: `recovery:${message._id}`
|
|
309
|
+
sendResult = await send(replacement).catch(async (err) => {
|
|
310
|
+
if (!replacement) throw err;
|
|
311
|
+
const acceptedSid = await acceptedFixedSid(message._id, replacement.contentSid);
|
|
312
|
+
if (acceptedSid) return { messageId: acceptedSid };
|
|
313
|
+
await reopenAfterFixedFailure(message);
|
|
314
|
+
logger.warn('[TemplateApprovalJob] Fixed template failed, sending as approved', { messageId: String(message._id), error: err.message });
|
|
315
|
+
return send(null);
|
|
312
316
|
});
|
|
313
317
|
if (sendResult?.duplicate) {
|
|
314
318
|
logger.info('[TemplateApprovalJob] Recovery send already claimed elsewhere', { templateSid, messageId: message._id });
|
|
@@ -335,7 +339,7 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
335
339
|
|
|
336
340
|
await DeliveryAttempt.updateOne(
|
|
337
341
|
{ messageId: message._id, kind: 'recovery_template_setup', twilioSid: templateSid },
|
|
338
|
-
{ $set: { status: 'sent', completedAt: new Date() } }
|
|
342
|
+
{ $set: { status: 'sent', ...(category && { templateCategory: category }), completedAt: new Date() } }
|
|
339
343
|
);
|
|
340
344
|
|
|
341
345
|
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: {
|
|
@@ -7,6 +7,7 @@ const { logger } = require('../utils/logger');
|
|
|
7
7
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
8
8
|
const { ageInYears, isoDay, mexicoDay } = require('../utils/dateUtils');
|
|
9
9
|
const { safeParse } = require('../utils/jsonUtils');
|
|
10
|
+
const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
|
|
10
11
|
const {
|
|
11
12
|
CALL_OUTCOMES,
|
|
12
13
|
CANCELLABLE_AFTER_HANDOFF_STATUSES,
|
|
@@ -109,7 +110,6 @@ const STALE_DRAFT = 'New information reached the review after this draft; wait f
|
|
|
109
110
|
const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
|
|
110
111
|
const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
|
|
111
112
|
const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
|
|
112
|
-
const MAX_TEMPLATE_TEXT_LENGTH = 800;
|
|
113
113
|
const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
|
|
114
114
|
const CANCEL_NEEDS_REASON = 'The doctor is already waiting on this review; cancelling it requires a reason';
|
|
115
115
|
const INTERRUPTION_CONFLICT = 'The escalation review was interrupted; closing it requires interruptionNotes stating what was verified';
|
|
@@ -6,6 +6,7 @@ const { escapeRegExp } = require('../utils/textMatchUtils');
|
|
|
6
6
|
const { ownS3Location } = require('../utils/s3Utils');
|
|
7
7
|
const { logger } = require('../utils/logger');
|
|
8
8
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
9
|
+
const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
|
|
9
10
|
const { OfficeReadMarker } = require('../models/officeReadMarkerModel');
|
|
10
11
|
const { INTERNAL_ORIGINS } = require('../models/messageModel');
|
|
11
12
|
const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
|
|
@@ -23,7 +24,6 @@ const HIDDEN_ORIGINS = [...INTERNAL_ORIGINS];
|
|
|
23
24
|
const DEFAULT_MESSAGE_LIMIT = 30;
|
|
24
25
|
const MAX_MESSAGE_LIMIT = 50;
|
|
25
26
|
const MAX_TEXT_LENGTH = 1500;
|
|
26
|
-
const MAX_TEMPLATE_TEXT_LENGTH = 800;
|
|
27
27
|
const DOCUMENT_TEMPLATE_DEFAULT_TEXT = 'Le compartimos un documento.';
|
|
28
28
|
const DOCUMENT_FILE_TYPE = 'document';
|
|
29
29
|
const UNDELIVERED_STATUSES = ['failed', 'undelivered'];
|