@peopl-health/nexus 6.3.5 → 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 +21 -14
- package/lib/core/NexusMessaging.js +9 -11
- package/lib/helpers/templateRecoveryHelper.js +75 -51
- package/lib/jobs/TemplateApprovalJob.js +7 -29
- 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
|
@@ -1,31 +1,38 @@
|
|
|
1
1
|
const { logger } = require('../utils/logger');
|
|
2
|
-
const {
|
|
2
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
3
3
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
4
4
|
const { Config_ID } = require('./airtableConfig');
|
|
5
5
|
const { programConfigSource } = require('./programConfig');
|
|
6
6
|
|
|
7
7
|
const RECOVERY_TEMPLATES_TABLE = 'recovery_templates';
|
|
8
|
-
const
|
|
9
|
-
const
|
|
8
|
+
const REFRESH_MS = 5 * 60 * 1000;
|
|
9
|
+
const FAILED_READ_RETRY_MS = 60 * 1000;
|
|
10
|
+
const READ_TIMEOUT_MS = 5000;
|
|
10
11
|
|
|
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
|
+
}
|
|
12
20
|
|
|
13
|
-
// An unreadable table reads as empty, which keeps messages on their one-off templates.
|
|
14
21
|
async function getRecoveryTemplateConfig() {
|
|
15
|
-
|
|
16
|
-
if (cached) return cached;
|
|
22
|
+
if (Date.now() < nextReadAt) return lastGoodConfig;
|
|
17
23
|
try {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const config = Object.fromEntries(rows.map((row) => [row.config, row.value]));
|
|
21
|
-
cache.set(CACHE_KEY, config);
|
|
22
|
-
return config;
|
|
24
|
+
lastGoodConfig = await readConfig();
|
|
25
|
+
nextReadAt = Date.now() + REFRESH_MS;
|
|
23
26
|
} catch (error) {
|
|
24
27
|
logger.warn('[recoveryTemplateConfig] Could not read the fixed templates', { error: error.message });
|
|
25
|
-
|
|
28
|
+
nextReadAt = lastGoodConfig ? Date.now() + FAILED_READ_RETRY_MS : 0;
|
|
26
29
|
}
|
|
30
|
+
return lastGoodConfig ?? {};
|
|
27
31
|
}
|
|
28
32
|
|
|
29
|
-
function _resetRecoveryTemplateConfig() {
|
|
33
|
+
function _resetRecoveryTemplateConfig() {
|
|
34
|
+
lastGoodConfig = null;
|
|
35
|
+
nextReadAt = 0;
|
|
36
|
+
}
|
|
30
37
|
|
|
31
38
|
module.exports = { getRecoveryTemplateConfig, _resetRecoveryTemplateConfig };
|
|
@@ -402,14 +402,14 @@ class NexusMessaging {
|
|
|
402
402
|
|
|
403
403
|
let gate = null;
|
|
404
404
|
try {
|
|
405
|
-
gate =
|
|
405
|
+
gate = 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,
|
|
412
|
-
if (result?.success !== true || result?.deferred === true
|
|
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);
|
|
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,
|
|
@@ -476,15 +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?.
|
|
487
|
+
if (queued?.fixedSend) return fixedResult(queued.fixedSend);
|
|
488
488
|
return { success: true, messageId: String(found._id), status: 'queued', preemptive: true, delivered: false, deferred: true };
|
|
489
489
|
}
|
|
490
490
|
const saveFn = this.messageStorage.savePendingMessage.bind(this.messageStorage);
|
|
@@ -500,13 +500,11 @@ class NexusMessaging {
|
|
|
500
500
|
// triggerTemplateRecovery swallows its own errors and returns undefined. Reporting "queued"
|
|
501
501
|
// regardless is how a template that was never created still counts as an outreach, and the
|
|
502
502
|
// weekly guard then stops us ever trying again.
|
|
503
|
-
const queued = await triggerTemplateRecovery({ _id, body, numero: messageData.code, media: messageData.media, expiresAt: messageData.expiresAt, contact_code: messageData.contactCode, contact_role: messageData.contactRole
|
|
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 });
|
|
504
504
|
if (queued?.expired) {
|
|
505
505
|
return { ...NOT_SENT_EXPIRED, messageId: String(_id) };
|
|
506
506
|
}
|
|
507
|
-
if (queued?.
|
|
508
|
-
return { success: true, messageId: String(_id), status: 'sent', delivered: false, deferred: false, sentByNestedSend: true };
|
|
509
|
-
}
|
|
507
|
+
if (queued?.fixedSend) return fixedResult(queued.fixedSend);
|
|
510
508
|
if (!queued?.deferred) {
|
|
511
509
|
logger.error('[NexusMessaging] template recovery setup failed; message not queued', { code: messageData.code, messageId: String(_id) });
|
|
512
510
|
return { success: false, messageId: String(_id), status: 'failed', preemptive: true, delivered: false, deferred: false };
|
|
@@ -2,6 +2,8 @@ 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');
|
|
6
8
|
const { Message } = require('../models/messageModel');
|
|
7
9
|
const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
|
|
@@ -21,8 +23,7 @@ const FIXED_FILE_TEMPLATE_KEYS = {
|
|
|
21
23
|
'image/jpeg': 'RECOVERY_IMAGE_TEMPLATE_SID',
|
|
22
24
|
'image/png': 'RECOVERY_IMAGE_TEMPLATE_SID'
|
|
23
25
|
};
|
|
24
|
-
const
|
|
25
|
-
const FIXED_TEMPLATE_DEFAULT_TEXT = 'Te compartimos un archivo.';
|
|
26
|
+
const FIXED_TEMPLATE_DEFAULT_TEXT = 'Tienes un archivo nuevo.';
|
|
26
27
|
const FIXED_TEMPLATE_MEDIA_PREFIX_KEY = 'RECOVERY_TEMPLATE_MEDIA_PREFIX';
|
|
27
28
|
|
|
28
29
|
async function resolveRecoveryMediaUrl(media) {
|
|
@@ -43,16 +44,16 @@ function hasUnresolvedPhi(body) {
|
|
|
43
44
|
|
|
44
45
|
async function resolveRecoveryBody(messageDoc) {
|
|
45
46
|
if (messageDoc.plainBody) return messageDoc.plainBody;
|
|
47
|
+
if (!messageDoc.body) return '';
|
|
46
48
|
const decoded = await getMessaging().getPhiProcessor()?.decodeBody(messageDoc.body, messageDoc.numero);
|
|
47
49
|
return decoded || messageDoc.body;
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
const EXPIRED_ERROR_MESSAGE = 'Expired before it could be delivered';
|
|
51
53
|
|
|
52
|
-
// Approved UTILITY, so Meta cannot reclassify it per message; null keeps the one-off template.
|
|
53
54
|
async function fixedRecoveryTemplate(media, body) {
|
|
54
|
-
const text =
|
|
55
|
-
if (text.length >
|
|
55
|
+
const text = oneLineOf(body);
|
|
56
|
+
if (text.length > MAX_TEMPLATE_TEXT_LENGTH) return null;
|
|
56
57
|
const config = await getRecoveryTemplateConfig();
|
|
57
58
|
|
|
58
59
|
if (!media?.key) {
|
|
@@ -60,7 +61,7 @@ async function fixedRecoveryTemplate(media, body) {
|
|
|
60
61
|
return contentSid && text ? { contentSid, variables: { 1: text } } : null;
|
|
61
62
|
}
|
|
62
63
|
|
|
63
|
-
const contentSid = config[FIXED_FILE_TEMPLATE_KEYS[media.contentType]];
|
|
64
|
+
const contentSid = config[FIXED_FILE_TEMPLATE_KEYS[media.contentType?.split(';')[0].trim().toLowerCase()]];
|
|
64
65
|
const mediaPrefix = config[FIXED_TEMPLATE_MEDIA_PREFIX_KEY];
|
|
65
66
|
if (!contentSid || !mediaPrefix) return null;
|
|
66
67
|
const mediaUrl = await resolveRecoveryMediaUrl(media);
|
|
@@ -71,50 +72,72 @@ async function fixedRecoveryTemplate(media, body) {
|
|
|
71
72
|
return { contentSid, variables: { 1: text || FIXED_TEMPLATE_DEFAULT_TEXT, 2: mediaUrl.slice(mediaPrefix.length) } };
|
|
72
73
|
}
|
|
73
74
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
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) {
|
|
80
116
|
await Message.updateOne(
|
|
81
117
|
{ _id: messageDoc._id },
|
|
82
118
|
{ $set: { 'statusInfo.status': 'queued' }, $unset: { 'statusInfo.errorCode': '', 'statusInfo.errorMessage': '' } }
|
|
83
119
|
);
|
|
84
|
-
|
|
120
|
+
emitRecoveryStatus(messageDoc, 'queued');
|
|
85
121
|
}
|
|
86
122
|
|
|
87
|
-
async function sendFixedRecovery(messageDoc, template, logCtx,
|
|
88
|
-
|
|
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';
|
|
123
|
+
async function sendFixedRecovery(messageDoc, template, logCtx, send) {
|
|
124
|
+
if (!await claimRecoverySend(messageDoc._id)) return { outcome: 'skipped' };
|
|
93
125
|
|
|
94
126
|
try {
|
|
95
|
-
const result = await
|
|
96
|
-
|
|
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';
|
|
127
|
+
const result = await send(recoverySendData(messageDoc, template));
|
|
128
|
+
if (result?.duplicate || result?.status === 'outbound_blocked') return { outcome: 'skipped' };
|
|
107
129
|
if (!result?.messageId) throw new Error('Provider did not return a messageId for the fixed template send');
|
|
108
130
|
logger.info('[TemplateRecovery] Sent on the fixed template', { ...logCtx, contentSid: template.contentSid });
|
|
109
|
-
return 'sent';
|
|
131
|
+
return { outcome: 'sent', result };
|
|
110
132
|
} catch (error) {
|
|
111
|
-
|
|
133
|
+
const messageId = await acceptedFixedSid(messageDoc._id, template.contentSid);
|
|
134
|
+
if (messageId) {
|
|
112
135
|
logger.error('[TemplateRecovery] Fixed template reached the provider but bookkeeping failed', { ...logCtx, error: error.message });
|
|
113
|
-
return 'sent';
|
|
136
|
+
return { outcome: 'sent', result: { messageId } };
|
|
114
137
|
}
|
|
115
138
|
await Message.updateOne({ _id: messageDoc._id }, { $unset: { 'statusInfo.recoverySentAt': '' } });
|
|
116
139
|
logger.warn('[TemplateRecovery] Fixed template send failed, using a one-off template', { ...logCtx, error: error.message });
|
|
117
|
-
return
|
|
140
|
+
return { outcome: 'failed' };
|
|
118
141
|
}
|
|
119
142
|
}
|
|
120
143
|
|
|
@@ -144,9 +167,9 @@ async function closeExpiredRecovery(messageDoc) {
|
|
|
144
167
|
await cleanupRecoveryTemplate(messageDoc);
|
|
145
168
|
}
|
|
146
169
|
|
|
147
|
-
async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messageSid = null } = {}) {
|
|
170
|
+
async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messageSid = null, contactGateDecisionId = null } = {}) {
|
|
148
171
|
try {
|
|
149
|
-
if (!messageDoc?.body || !messageDoc?.numero || !messageDoc?._id) return;
|
|
172
|
+
if ((!messageDoc?.body && !messageDoc?.media?.key) || !messageDoc?.numero || !messageDoc?._id) return;
|
|
150
173
|
|
|
151
174
|
const messageDocId = messageDoc._id;
|
|
152
175
|
const logCtx = { source, messageSid, messageDocId: String(messageDocId) };
|
|
@@ -196,11 +219,15 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
196
219
|
let fixedSendFailed = false;
|
|
197
220
|
if (messageDoc.media?.key && !hasUnresolvedPhi(recoveryBody)) {
|
|
198
221
|
const fixedTemplate = await fixedRecoveryTemplate(messageDoc.media, recoveryBody);
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
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
|
+
}
|
|
204
231
|
}
|
|
205
232
|
|
|
206
233
|
const templateName = `auto_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
|
|
@@ -212,7 +239,9 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
212
239
|
|
|
213
240
|
let twilioContent;
|
|
214
241
|
let setupErr = null;
|
|
215
|
-
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)) {
|
|
216
245
|
setupErr = new Error('Body still carries a PHI placeholder after decoding');
|
|
217
246
|
} else if (recoveryBody.length > TEMPLATE_BODY_LIMIT) {
|
|
218
247
|
setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length})`);
|
|
@@ -236,6 +265,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
236
265
|
|
|
237
266
|
if (setupErr) {
|
|
238
267
|
logger.error('[TemplateRecovery] Setup failed', { ...logCtx, error: setupErr.message });
|
|
268
|
+
emitRecoveryStatus(messageDoc, 'failed');
|
|
239
269
|
if (twilioContent?.sid) {
|
|
240
270
|
provider.deleteTemplate(twilioContent.sid).catch(deleteErr =>
|
|
241
271
|
logger.warn('[TemplateRecovery] Failed to delete partially-created template', { templateSid: twilioContent.sid, error: deleteErr.message })
|
|
@@ -271,13 +301,7 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
271
301
|
originalMessageSid: messageSid
|
|
272
302
|
});
|
|
273
303
|
|
|
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
|
-
}
|
|
304
|
+
if (fixedSendFailed) await reopenAfterFixedFailure(messageDoc);
|
|
281
305
|
return { delivered: false, deferred: true };
|
|
282
306
|
} catch (error) {
|
|
283
307
|
logger.error('[TemplateRecovery] Error', { source, messageSid, error: error.message });
|
|
@@ -307,4 +331,4 @@ async function cleanupRecoveryTemplate(messageDoc) {
|
|
|
307
331
|
}
|
|
308
332
|
}
|
|
309
333
|
|
|
310
|
-
module.exports = {
|
|
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 {
|
|
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
|
|
|
@@ -290,40 +290,17 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
290
290
|
return { sent: Boolean(result?.messageId), nudgeMessageId: result?.messageId || null };
|
|
291
291
|
}
|
|
292
292
|
|
|
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
293
|
async _handleApproved({ message, templateSid, originalMessageSid, category }) {
|
|
308
|
-
|
|
309
|
-
{ _id: message._id, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
|
|
310
|
-
{ $set: { 'statusInfo.recoverySentAt': new Date() } }
|
|
311
|
-
);
|
|
312
|
-
if (!claim.modifiedCount && !claim.nModified) {
|
|
294
|
+
if (!await claimRecoverySend(message._id)) {
|
|
313
295
|
logger.info('[TemplateApprovalJob] Send already claimed by another worker', { templateSid, messageId: message._id });
|
|
314
296
|
return { success: false, reason: 'already_claimed' };
|
|
315
297
|
}
|
|
316
298
|
|
|
317
|
-
|
|
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;
|
|
318
301
|
|
|
319
302
|
const send = (template) => this.sendMessage({
|
|
320
|
-
|
|
321
|
-
...contactOf(message),
|
|
322
|
-
contentSid: template?.contentSid ?? templateSid,
|
|
323
|
-
variables: template?.variables ?? {},
|
|
324
|
-
parentMessageId: message._id,
|
|
325
|
-
kind: 'recovery_template',
|
|
326
|
-
body: message.body,
|
|
303
|
+
...recoverySendData(message, template ?? { contentSid: templateSid, variables: {} }),
|
|
327
304
|
idempotencyKey: `recovery:${message._id}`
|
|
328
305
|
});
|
|
329
306
|
|
|
@@ -331,8 +308,9 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
331
308
|
try {
|
|
332
309
|
sendResult = await send(replacement).catch(async (err) => {
|
|
333
310
|
if (!replacement) throw err;
|
|
334
|
-
const acceptedSid = await
|
|
311
|
+
const acceptedSid = await acceptedFixedSid(message._id, replacement.contentSid);
|
|
335
312
|
if (acceptedSid) return { messageId: acceptedSid };
|
|
313
|
+
await reopenAfterFixedFailure(message);
|
|
336
314
|
logger.warn('[TemplateApprovalJob] Fixed template failed, sending as approved', { messageId: String(message._id), error: err.message });
|
|
337
315
|
return send(null);
|
|
338
316
|
});
|
|
@@ -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'];
|