@peopl-health/nexus 6.4.0-dev.18856 → 6.4.0-dev.18956
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/clinical/helpers/doctorPlanHelper.js +9 -7
- package/lib/clinical/helpers/planTextHelper.js +15 -11
- package/lib/config/recoveryTemplateConfig.js +21 -14
- package/lib/core/NexusMessaging.js +9 -11
- package/lib/helpers/channelErrorHelper.js +6 -2
- package/lib/helpers/channelRetryHelper.js +64 -2
- package/lib/helpers/messageStatusHelper.js +6 -1
- package/lib/helpers/templateRecoveryHelper.js +75 -51
- package/lib/jobs/TemplateApprovalJob.js +7 -29
- package/lib/models/messageModel.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
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { oneLineOf } = require('../../utils/coercionUtils');
|
|
2
|
-
const { normalizeForAnchor
|
|
2
|
+
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
3
3
|
const { DURATION_SOURCE, durationDays, isRouteOnly } = require('./planTextHelper');
|
|
4
4
|
|
|
5
5
|
const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ check_in: 24, vigilancia: 48 });
|
|
@@ -19,6 +19,7 @@ const FOLLOW_UP_LINES = {
|
|
|
19
19
|
check_in: (hours) => `Seguimiento: le escribiremos en unas ${hours} horas para ver cómo va.`,
|
|
20
20
|
vigilancia: (hours) => `Seguimiento: queda en vigilancia las próximas ${hours} horas; le escribiremos para ver cómo va.`,
|
|
21
21
|
};
|
|
22
|
+
const followUpLineOf = (plan) => FOLLOW_UP_LINES[plan.followUp?.kind]?.(plan.followUp.hours) ?? null;
|
|
22
23
|
|
|
23
24
|
function planInstructions(plan) {
|
|
24
25
|
const lines = ['Transmítele al paciente lo que indicó el médico, con tus palabras: no cambies dosis, frecuencia ni días, y no agregues otros medicamentos ni estudios. Escribe dosis, horas y días con números, como vienen aquí, sin repetirlos con letra, y no agregues avisos de urgencia que el médico no dio.'];
|
|
@@ -30,14 +31,15 @@ function planInstructions(plan) {
|
|
|
30
31
|
}
|
|
31
32
|
if (plan.homeCare.length) lines.push('Cuidados en casa:', ...plan.homeCare.map((entry) => `- ${entry}`));
|
|
32
33
|
if (plan.note) lines.push(`Nota del médico: «${plan.note}».`);
|
|
33
|
-
|
|
34
|
+
const followUp = followUpLineOf(plan);
|
|
35
|
+
if (followUp) lines.push(followUp);
|
|
34
36
|
if (needsPrescriber(plan)) lines.push(PRESCRIPTION_LINE);
|
|
35
37
|
return lines.join('\n');
|
|
36
38
|
}
|
|
37
39
|
|
|
38
|
-
// An edit can drop the receta line; the PDF goes out anyway, so the assistant is still told.
|
|
40
|
+
// An edit can drop or reword the receta line; the PDF goes out anyway, so the assistant is still told.
|
|
39
41
|
function assistantInstructionsOf(plan) {
|
|
40
|
-
if (!needsPrescriber(plan) ||
|
|
42
|
+
if (!needsPrescriber(plan) || normalizeForAnchor(plan.instructions).includes(normalizeForAnchor(PRESCRIPTION_LINE))) return plan.instructions;
|
|
41
43
|
return `${plan.instructions}\n${PRESCRIPTION_LINE}`;
|
|
42
44
|
}
|
|
43
45
|
|
|
@@ -75,7 +77,7 @@ function proposedPlanOf(draft) {
|
|
|
75
77
|
const items = (draft?.symptoms ?? [])
|
|
76
78
|
.filter((entry) => entry?.proposal?.confirmed)
|
|
77
79
|
.flatMap((entry) => (entry.proposal.items ?? []).map((item) => ({ item, formularyKey: entry.proposal.formularyKey })))
|
|
78
|
-
.filter(({ item }) => !seen.has(
|
|
80
|
+
.filter(({ item }) => !seen.has(normalizeForAnchor(item.drug)) && seen.add(normalizeForAnchor(item.drug)))
|
|
79
81
|
.map(({ item, formularyKey }) => {
|
|
80
82
|
const { rest, ...dosing } = dosingOf(item.instructions);
|
|
81
83
|
if (rest) rests.push(`${item.drug}: ${rest}`);
|
|
@@ -86,11 +88,11 @@ function proposedPlanOf(draft) {
|
|
|
86
88
|
|
|
87
89
|
// The note and home care count, so what the doctor wrote anywhere in the plan is never flagged.
|
|
88
90
|
const plannedTextOf = (plan) => [
|
|
89
|
-
...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, `por ${item.days} dias`]),
|
|
91
|
+
...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, item.days && `por ${item.days} dias`]),
|
|
90
92
|
...plan.studies.flatMap((study) => [study.name, study.instructions]),
|
|
91
93
|
...plan.homeCare,
|
|
92
94
|
plan.note,
|
|
93
|
-
|
|
95
|
+
followUpLineOf(plan),
|
|
94
96
|
].filter(Boolean).join('\n');
|
|
95
97
|
|
|
96
98
|
module.exports = {
|
|
@@ -20,13 +20,23 @@ const TO = '\\s*(?:a|-|o|u)\\s*';
|
|
|
20
20
|
const DAYS_PER = Object.freeze({ d: 1, dia: 1, dias: 1, semana: 7, semanas: 7, mes: 30, meses: 30 });
|
|
21
21
|
const DAY_UNITS = 'd[ií]as?|semanas?|mes(?:es)?|d\\b';
|
|
22
22
|
|
|
23
|
+
const UNIT_SCALE = Object.freeze({
|
|
24
|
+
microgramo: ['mg', 0.001], microgramos: ['mg', 0.001], mcg: ['mg', 0.001], µg: ['mg', 0.001], ug: ['mg', 0.001],
|
|
25
|
+
miligramo: ['mg', 1], miligramos: ['mg', 1], mg: ['mg', 1],
|
|
26
|
+
gramo: ['mg', 1000], gramos: ['mg', 1000], g: ['mg', 1000], gr: ['mg', 1000],
|
|
27
|
+
ml: ['ml', 1], ui: ['ui', 1],
|
|
28
|
+
});
|
|
29
|
+
const UNITS_SOURCE = Object.keys(UNIT_SCALE).sort((a, b) => b.length - a.length).join('|');
|
|
30
|
+
// Forms a dose is counted in («media tableta», «1/2 tableta»), then forms that only name the preparation.
|
|
31
|
+
const COUNTED_FORMS = 'tabletas?|tab|capsulas?|caps|comprimidos?|pastillas?|sobres?|ampolletas?|ampulas?|ampollas?|cucharadas?|cucharaditas?|gotas|supositorios?|ovulos?|parches?';
|
|
32
|
+
const OTHER_FORMS = 'jarabe|crema|pomada|gel|unguento|locion|solucion|suspension|inyectable|inyeccion|spray|colirio';
|
|
23
33
|
// «por 5 días», «durante una semana», «x 7 días», «por unos 5 días», «por 3 a 5 días»
|
|
24
34
|
const DURATION_SOURCE = `(?:por|durante|x)\\s+(?:(?:unos|unas|los|las|pr[oó]ximos|otros)\\s+)*(${COUNT})(?:${TO}(${COUNT}))?\\s*(${DAY_UNITS})`;
|
|
25
35
|
const DURATION = new RegExp(`^${DURATION_SOURCE}$`, 'i');
|
|
26
36
|
|
|
27
37
|
const ROUTES = new Set(['vo', 'po', 'oral', 'iv', 'ev', 'intravenosa', 'im', 'intramuscular', 'sc', 'subcutanea', 'sl', 'sublingual', 'topica', 'topico', 'cutanea', 'transdermica', 'rectal', 'vaginal', 'nasal', 'intranasal', 'inhalada', 'inhalado', 'oftalmica', 'otica']);
|
|
28
|
-
// What a drug's name may carry that does not name it: «Ondansetrón 8 mg», «Metoclopramida gotas
|
|
29
|
-
const NOT_A_NAME =
|
|
38
|
+
// What a drug's name may carry that does not name it: «Ondansetrón 8 mg», «Metoclopramida gotas»; a spelled-out route («transdérmica») stays.
|
|
39
|
+
const NOT_A_NAME = new RegExp(`^(?:\\d+(?:${UNITS_SOURCE})?|${UNITS_SOURCE}|vo|iv|im|sc|sl|oral|${COUNTED_FORMS}|${OTHER_FORMS})$`);
|
|
30
40
|
|
|
31
41
|
const URGENCY_WORDS = /\b(urgencias?|urgente|de inmediato|inmediata|inmediatamente|emergencias?|911|ambulancia|hospital|guardia|lo antes posible|cuanto antes|no esperes)\b/g;
|
|
32
42
|
// Only filler may sit between: «no necesitas ir a urgencias» calms, «no es normal, ve a urgencias» does not.
|
|
@@ -65,7 +75,7 @@ function dosingTextOf(text) {
|
|
|
65
75
|
.replace(NUMBER_WORD, (word) => String(countOf(word)))
|
|
66
76
|
.replace(/(\d+(?:\.\d+)?)\s*\((\d+(?:\.\d+)?)\)/g, (written, number, again) => (number === again ? number : written))
|
|
67
77
|
.replace(/(?<![\d/])([1-3])\/([2-4])(?![\d/])/g, (written, top, bottom) => (Number(top) < Number(bottom) ? String(Math.round((top / bottom) * 1000) / 1000) : written))
|
|
68
|
-
.replace(
|
|
78
|
+
.replace(new RegExp(`\\b(?:media|medio)\\s+(?=(?:${COUNTED_FORMS}|horas?)\\b)`, 'g'), '0.5 ')
|
|
69
79
|
.replace(/\bcada\s+(\d+(?:\.\d+)?)\s*min(?:utos?)?\b/g, (_, minutes) => `cada ${Math.round((minutes / 60) * 1000) / 1000} horas`)
|
|
70
80
|
.replace(/\bc\/\s*(\d+)\s*(?:h|hs|hrs?|horas?)\b/g, 'cada $1 horas')
|
|
71
81
|
.replace(new RegExp(`\\b(\\d+)(?:${TO}(\\d+))?\\s+ve(?:z|ces)\\s+(?:al|por|cada)\\s+dia\\b`, 'g'), TIMES_A_DAY)
|
|
@@ -78,16 +88,10 @@ function dosingTextOf(text) {
|
|
|
78
88
|
.replace(/\s+/g, ' ');
|
|
79
89
|
}
|
|
80
90
|
|
|
91
|
+
const AMOUNTS = new RegExp(`\\b(\\d+(?:\\.\\d+)?)\\s*(${UNITS_SOURCE})(?![a-z])`, 'g');
|
|
81
92
|
const RANGE = `(\\d+(?:\\.\\d+)?)(?:${TO}(\\d+(?:\\.\\d+)?))?`;
|
|
82
93
|
const HOURS = new RegExp(`cada\\s+${RANGE}\\s*h(?:s|rs?|oras?)?\\b`, 'g');
|
|
83
94
|
const DAYS = new RegExp(`por\\s+${RANGE}\\s+dias?\\b`, 'g');
|
|
84
|
-
const AMOUNTS = /\b(\d+(?:\.\d+)?)\s*(microgramos?|miligramos?|gramos?|mcg|µg|ug|mg|gr?|ml|ui)(?![a-z])/g;
|
|
85
|
-
const UNIT_SCALE = Object.freeze({
|
|
86
|
-
microgramo: ['mg', 0.001], microgramos: ['mg', 0.001], mcg: ['mg', 0.001], µg: ['mg', 0.001], ug: ['mg', 0.001],
|
|
87
|
-
miligramo: ['mg', 1], miligramos: ['mg', 1], mg: ['mg', 1],
|
|
88
|
-
gramo: ['mg', 1000], gramos: ['mg', 1000], g: ['mg', 1000], gr: ['mg', 1000],
|
|
89
|
-
ml: ['ml', 1], ui: ['ui', 1],
|
|
90
|
-
});
|
|
91
95
|
|
|
92
96
|
const valuesIn = (text, pattern) => new Set([...text.matchAll(pattern)].flatMap((match) => [match[1], match[2]]).filter(Boolean).map(Number));
|
|
93
97
|
|
|
@@ -104,7 +108,7 @@ function dosingFactsOf(text) {
|
|
|
104
108
|
// List markers («1.», «2)») number lines, not doses.
|
|
105
109
|
const LIST_MARKER = /(^|\n)[ \t]*\d+[.)][ \t]+|(?<!\([^)\n]*)(^|\s)\d+\)[ \t]+/g;
|
|
106
110
|
// Clock times, dates, phone numbers and temperatures are not doses.
|
|
107
|
-
const NOT_DOSING = [/\b\d{1,2}:\d{2}\b/g,
|
|
111
|
+
const NOT_DOSING = [/\b\d{1,2}:\d{2}\b/g, new RegExp(`\\b\\d{1,2}\\/\\d{1,2}(?:\\/\\d{2,4})?\\b(?!\\s*(?:${COUNTED_FORMS}|${UNITS_SOURCE})\\b)`, 'g'), /\b(?=(?:\d[ -]?){8,})\d{2,4}(?:[ -]?\d{2,4}){2,}\b/g, /\b\d+(?:\.\d+)?\s*(?:°\s*c?|grados)/g, /\b(?:fiebre|temperatura)\s+(?:(?:de|es|sea|esta|mayor|menor|a|mas|que|pasa|sube|llega|arriba|encima|del|por)\s+)*\d+(?:\.\d+)?/g];
|
|
108
112
|
const NUMBER = /\d+(?:\.\d+)?/g;
|
|
109
113
|
const numbersOf = (text) => new Set([...text.matchAll(NUMBER)].map(([number]) => Number(number)));
|
|
110
114
|
|
|
@@ -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 };
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
const { logger } = require('../utils/logger');
|
|
2
2
|
|
|
3
3
|
const { handle24HourWindowError } = require('./templateRecoveryHelper');
|
|
4
|
-
const { handleRetryableChannelError } = require('./channelRetryHelper');
|
|
4
|
+
const { handleBlockedDelivery, handleRetryableChannelError } = require('./channelRetryHelper');
|
|
5
|
+
|
|
6
|
+
const BLOCKED_DELIVERY = { name: 'blocked_delivery', handle: handleBlockedDelivery };
|
|
5
7
|
|
|
6
8
|
const CHANNEL_ERROR_STRATEGIES = {
|
|
7
9
|
63016: { name: 'window_recovery', handle: (message, twilioSid) => handle24HourWindowError(message, twilioSid) },
|
|
8
|
-
63021: { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) }
|
|
10
|
+
63021: { name: 'content_retry', handle: (message, twilioSid, errorCode) => handleRetryableChannelError(message, twilioSid, errorCode) },
|
|
11
|
+
63032: BLOCKED_DELIVERY,
|
|
12
|
+
63049: BLOCKED_DELIVERY
|
|
9
13
|
};
|
|
10
14
|
|
|
11
15
|
function resolveChannelErrorStrategy(errorCode) {
|
|
@@ -7,10 +7,16 @@ const { isAtOrBefore } = require('../utils/dateUtils');
|
|
|
7
7
|
const { Message } = require('../models/messageModel');
|
|
8
8
|
const { ScheduledMessage } = require('../models/agendaMessageModel');
|
|
9
9
|
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES: LANDED_STATUSES } = require('../models/deliveryAttemptModel');
|
|
10
|
-
const {
|
|
10
|
+
const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
11
|
+
const { closeExpiredRecovery, fixedTemplateFor, recoverySendData } = require('./templateRecoveryHelper');
|
|
12
|
+
const { patientIsDeceased } = require('./pausedThreadHelper');
|
|
13
|
+
const { isStaffSend } = require('./staffSendHelper');
|
|
14
|
+
const { phoneDigits } = require('./whatsappHelper');
|
|
11
15
|
|
|
12
16
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
13
17
|
|
|
18
|
+
const REFUSED_ON_PURPOSE = new Set(['patient_deceased', 'outbound_blocked']);
|
|
19
|
+
|
|
14
20
|
const DEFAULT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];
|
|
15
21
|
const SIGNED_MEDIA_PATH = /^\d+\/\d+\/(\d{13})\//;
|
|
16
22
|
|
|
@@ -162,4 +168,60 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
|
|
|
162
168
|
return { retried: true, attempt: priorAttempts, delayMs: delay, scheduledMessageId: String(scheduled._id) };
|
|
163
169
|
}
|
|
164
170
|
|
|
165
|
-
|
|
171
|
+
async function reportBlockedDelivery(messageDoc, logCtx) {
|
|
172
|
+
alertUndeliverable({ ...logCtx, reason: 'blocked_by_meta' });
|
|
173
|
+
const sender = isStaffSend(messageDoc.triggeredBy) ? `de ${messageDoc.triggeredBy}` : 'del asistente';
|
|
174
|
+
const recipient = messageDoc.contact_code ? ` a su cuidador (+${phoneDigits(messageDoc.contact_code)})` : '';
|
|
175
|
+
const written = await recordUnresolvedRequest({
|
|
176
|
+
code: messageDoc.numero,
|
|
177
|
+
trace: null,
|
|
178
|
+
category: 'contact_team_member',
|
|
179
|
+
question: 'Mensaje de WhatsApp no entregado',
|
|
180
|
+
details: formatOpsAlert(messageDoc.numero, {
|
|
181
|
+
label: 'Mensaje no entregado',
|
|
182
|
+
summary: `WhatsApp bloqueó (${logCtx.errorCode}) un mensaje ${sender}${recipient}; hay que llamarle`
|
|
183
|
+
})
|
|
184
|
+
});
|
|
185
|
+
if (written) return { retried: false, reason: 'reported' };
|
|
186
|
+
logger.error('[ChannelRetry] No new ops alert: the write failed or a recent one is still open', logCtx);
|
|
187
|
+
return { retried: false, reason: 'alert_not_written' };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function resendOnFixedTemplate(messageDoc, attempt, logCtx) {
|
|
191
|
+
try {
|
|
192
|
+
const template = await fixedTemplateFor(messageDoc);
|
|
193
|
+
if (!template || template.contentSid === attempt.contentSid) return 'failed';
|
|
194
|
+
const result = await getMessaging().sendMessage({
|
|
195
|
+
...recoverySendData(messageDoc, template),
|
|
196
|
+
idempotencyKey: `blocked-retry:${messageDoc._id}`
|
|
197
|
+
});
|
|
198
|
+
if (result?.messageId && result.status !== 'failed') return 'sent';
|
|
199
|
+
return REFUSED_ON_PURPOSE.has(result?.status) ? 'refused' : 'failed';
|
|
200
|
+
} catch (err) {
|
|
201
|
+
logger.error('[ChannelRetry] Could not resend the blocked message', { ...logCtx, error: err.message });
|
|
202
|
+
return 'failed';
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
async function handleBlockedDelivery(messageDoc, twilioSid, errorCode) {
|
|
207
|
+
if (messageDoc.origin !== 'assistant' && !isStaffSend(messageDoc.triggeredBy)) return { retried: false, reason: 'not_a_personal_send' };
|
|
208
|
+
if (isAtOrBefore(messageDoc.expiresAt, Date.now())) return { retried: false, reason: 'expired' };
|
|
209
|
+
|
|
210
|
+
const attempt = await DeliveryAttempt.findOne({ twilioSid }, 'kind contentSid').lean();
|
|
211
|
+
if (attempt && attempt.kind !== 'recovery_template') return { retried: false, reason: 'not_a_personal_send' };
|
|
212
|
+
|
|
213
|
+
if (await patientIsDeceased(messageDoc.numero)) return { retried: false, reason: 'patient_deceased' };
|
|
214
|
+
|
|
215
|
+
const logCtx = { twilioSid, errorCode, messageId: String(messageDoc._id) };
|
|
216
|
+
const claimed = attempt && (await Message.updateOne(
|
|
217
|
+
{ _id: messageDoc._id, 'statusInfo.blockedRetryAt': null },
|
|
218
|
+
{ $set: { 'statusInfo.blockedRetryAt': new Date() } }
|
|
219
|
+
)).modifiedCount;
|
|
220
|
+
const outcome = claimed ? await resendOnFixedTemplate(messageDoc, attempt, logCtx) : 'failed';
|
|
221
|
+
if (outcome === 'refused') return { retried: false, reason: 'refused' };
|
|
222
|
+
if (outcome === 'failed') return reportBlockedDelivery(messageDoc, logCtx);
|
|
223
|
+
logger.warn('[ChannelRetry] Blocked by Meta, resent on the fixed template', logCtx);
|
|
224
|
+
return { retried: true, reason: 'fixed_template' };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
module.exports = { handleBlockedDelivery, handleRetryableChannelError, alertUndeliverable };
|
|
@@ -23,6 +23,12 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
|
|
|
23
23
|
...(errorMessage && { 'statusInfo.errorMessage': errorMessage })
|
|
24
24
|
};
|
|
25
25
|
|
|
26
|
+
const attempt = await DeliveryAttempt.findOne({ twilioSid: messageSid }, '_id messageId status').lean();
|
|
27
|
+
if (DELIVERY_ATTEMPT_TERMINAL_STATUSES.includes(attempt?.status)) {
|
|
28
|
+
logger.info('[MessageStatus] Ignoring a callback for a settled attempt', { messageSid, status });
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
26
32
|
const notTerminal = { 'statusInfo.status': { $nin: DELIVERY_ATTEMPT_TERMINAL_STATUSES } };
|
|
27
33
|
|
|
28
34
|
let updated = await Message.findOneAndUpdate(
|
|
@@ -32,7 +38,6 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
|
|
|
32
38
|
);
|
|
33
39
|
|
|
34
40
|
if (!updated) {
|
|
35
|
-
const attempt = await DeliveryAttempt.findOne({ twilioSid: messageSid }, '_id messageId').lean();
|
|
36
41
|
if (attempt?.messageId) {
|
|
37
42
|
updated = await Message.findOneAndUpdate(
|
|
38
43
|
{ _id: attempt.messageId, ...notTerminal },
|
|
@@ -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
|
});
|
|
@@ -76,6 +76,7 @@ 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 },
|
|
@@ -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,
|
|
@@ -116,7 +117,6 @@ const STALE_DRAFT = 'New information reached the review after this draft; wait f
|
|
|
116
117
|
const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
|
|
117
118
|
const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
|
|
118
119
|
const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
|
|
119
|
-
const MAX_TEMPLATE_TEXT_LENGTH = 800;
|
|
120
120
|
const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
|
|
121
121
|
const CANCEL_NEEDS_REASON = 'The doctor is already waiting on this review; cancelling it requires a reason';
|
|
122
122
|
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'];
|