@peopl-health/nexus 6.4.0-dev.18956 → 6.4.0-dev.18958
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/adapters/TwilioProvider.js +2 -31
- package/lib/clinical/services/treatmentProposalService.js +4 -26
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
- package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
- package/lib/controllers/escalationReviewController.js +3 -20
- package/lib/controllers/prescriptionController.js +28 -4
- package/lib/helpers/channelRetryHelper.js +6 -1
- package/lib/helpers/messageStatusHelper.js +7 -1
- package/lib/helpers/recoveryFallbackHelper.js +146 -0
- package/lib/helpers/templateRecoveryHelper.js +33 -7
- package/lib/index.d.ts +1 -1
- package/lib/jobs/TemplateApprovalJob.js +36 -2
- package/lib/models/escalationReviewModel.js +2 -38
- package/lib/models/messageModel.js +3 -1
- package/lib/routes/index.js +0 -2
- package/lib/services/assistantMessageService.js +6 -12
- package/lib/services/contactGateService.js +2 -2
- package/lib/services/escalationReviewService.js +12 -191
- package/lib/utils/httpErrorUtils.js +1 -1
- package/lib/utils/templateTextUtils.js +64 -0
- package/package.json +1 -1
- package/lib/clinical/helpers/doctorPlanHelper.js +0 -107
- package/lib/clinical/helpers/planTextHelper.js +0 -131
- package/lib/clinical/services/doctorPlanService.js +0 -120
- package/lib/services/prescriptionService.js +0 -30
|
@@ -4,6 +4,7 @@ const twilio = require('twilio');
|
|
|
4
4
|
const { generatePresignedUrl } = require('../config/awsConfig');
|
|
5
5
|
|
|
6
6
|
const { logger } = require('../utils/logger');
|
|
7
|
+
const { splitAtWordBoundaries } = require('../utils/templateTextUtils');
|
|
7
8
|
const {
|
|
8
9
|
isJsonBlob, hasSpreadsheetError, stripSpreadsheetErrors, stripSpreadsheetErrorsDeep, usableText
|
|
9
10
|
} = require('../utils/formatUtils');
|
|
@@ -241,37 +242,7 @@ class TwilioProvider extends MessageProvider {
|
|
|
241
242
|
}
|
|
242
243
|
|
|
243
244
|
_splitMessageAtWordBoundaries(text, maxLength = 1600) {
|
|
244
|
-
|
|
245
|
-
const chunks = [];
|
|
246
|
-
let remaining = text;
|
|
247
|
-
while (remaining.length > maxLength) {
|
|
248
|
-
let splitIndex = -1;
|
|
249
|
-
const searchStart = Math.max(0, maxLength - 500); // Look back up to 500 chars
|
|
250
|
-
const searchArea = remaining.substring(searchStart, maxLength + 1);
|
|
251
|
-
|
|
252
|
-
const regex = /[.!?]\s/g;
|
|
253
|
-
let match;
|
|
254
|
-
let lastMatchIndex = -1;
|
|
255
|
-
|
|
256
|
-
while ((match = regex.exec(searchArea)) !== null) {
|
|
257
|
-
const absoluteIndex = searchStart + match.index;
|
|
258
|
-
if (absoluteIndex <= maxLength) {
|
|
259
|
-
lastMatchIndex = absoluteIndex + match[0].length;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
if (lastMatchIndex > 0) {
|
|
264
|
-
splitIndex = lastMatchIndex;
|
|
265
|
-
} else {
|
|
266
|
-
splitIndex = remaining.lastIndexOf(' ', maxLength);
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
const chunk = remaining.substring(0, splitIndex === -1 ? maxLength : splitIndex).trim();
|
|
270
|
-
if (chunk) chunks.push(chunk);
|
|
271
|
-
remaining = remaining.substring(splitIndex === -1 ? maxLength : splitIndex).trim();
|
|
272
|
-
}
|
|
273
|
-
if (remaining) chunks.push(remaining);
|
|
274
|
-
return chunks;
|
|
245
|
+
return splitAtWordBoundaries(text, maxLength);
|
|
275
246
|
}
|
|
276
247
|
|
|
277
248
|
async listTemplates(options = {}) {
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
const { drugNameOf } = require('../helpers/planTextHelper');
|
|
2
1
|
const { TREATMENT_FORMULARY, findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
3
2
|
|
|
4
3
|
const { normalizeForAnchor: key } = require('../../utils/textMatchUtils');
|
|
@@ -91,9 +90,10 @@ function validateProposal(proposal, context = {}) {
|
|
|
91
90
|
|
|
92
91
|
const namesOf = (drug) => [drug.drug, ...drug.drug.split('/'), ...String(drug.brand ?? '').split('/')].map(key).filter((name) => name.length >= 4);
|
|
93
92
|
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
93
|
+
const DRUG_NAMES = [...new Set(TREATMENT_FORMULARY
|
|
94
|
+
.flatMap((entry) => entry.drugs)
|
|
95
|
+
.filter((drug) => drug.isPharmacological !== false)
|
|
96
|
+
.flatMap(namesOf))];
|
|
97
97
|
|
|
98
98
|
function resolvedDrugs(proposals) {
|
|
99
99
|
return proposals.filter(Boolean).flatMap((proposal) => {
|
|
@@ -107,14 +107,6 @@ function drugsNamedIn(text) {
|
|
|
107
107
|
return DRUG_NAMES.filter((name) => padded.includes(` ${name} `));
|
|
108
108
|
}
|
|
109
109
|
|
|
110
|
-
// A brand of a planned drug counts as planned; a combination only when named whole.
|
|
111
|
-
function unplannedDrugsIn(text, plannedText) {
|
|
112
|
-
const planned = new Set(drugsNamedIn(plannedText));
|
|
113
|
-
const ownNames = (drug) => [drug.drug, ...String(drug.brand ?? '').split('/')].map(key).filter(Boolean);
|
|
114
|
-
const allowed = new Set([...planned, ...FORMULARY_DRUGS.filter((drug) => ownNames(drug).some((name) => planned.has(name))).flatMap(namesOf)]);
|
|
115
|
-
return [...new Set(drugsNamedIn(text).filter((name) => !allowed.has(name)))];
|
|
116
|
-
}
|
|
117
|
-
|
|
118
110
|
function unproposedDrugsIn(text, proposals) {
|
|
119
111
|
const proposed = new Set(resolvedDrugs(proposals).flatMap(({ drug }) => namesOf(drug)));
|
|
120
112
|
return drugsNamedIn(text).filter((name) => !proposed.has(name));
|
|
@@ -136,24 +128,10 @@ function crossSymptomIssues(proposals) {
|
|
|
136
128
|
return issues;
|
|
137
129
|
}
|
|
138
130
|
|
|
139
|
-
// A combination needs every part; the dose or form beside a name («Ondansetrón 8 mg») need not be said.
|
|
140
|
-
function isDrugNamed(text, drugName) {
|
|
141
|
-
const padded = ` ${key(text)} `;
|
|
142
|
-
const says = (name) => Boolean(name) && padded.includes(` ${name} `);
|
|
143
|
-
const name = String(drugName ?? '');
|
|
144
|
-
const outside = name.replace(/\(.*?\)/g, ' ');
|
|
145
|
-
const inside = [...name.matchAll(/\((.*?)\)/g)].map((match) => drugNameOf(match[1]));
|
|
146
|
-
const brands = ALL_FORMULARY_DRUGS.filter((drug) => drugNameOf(drug.drug) === drugNameOf(outside)).flatMap((drug) => String(drug.brand ?? '').split('/').map(key));
|
|
147
|
-
const parts = outside.split(/\s*[/+]\s*/).map(drugNameOf).filter(Boolean);
|
|
148
|
-
return (parts.length > 0 && parts.every(says)) || [...inside, ...brands].some(says);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
131
|
module.exports = {
|
|
152
132
|
JUSTIFICATION_KINDS,
|
|
153
|
-
isDrugNamed,
|
|
154
133
|
validateProposal,
|
|
155
134
|
unproposedDrugsIn,
|
|
156
|
-
unplannedDrugsIn,
|
|
157
135
|
drugsNamedIn,
|
|
158
136
|
crossSymptomIssues,
|
|
159
137
|
};
|
|
@@ -5,7 +5,7 @@ const { logger } = require('../../utils/logger');
|
|
|
5
5
|
|
|
6
6
|
const definition = {
|
|
7
7
|
name: 'getPatientRiskAssessment',
|
|
8
|
-
description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `
|
|
8
|
+
description: '**Does:** Returns the patient\'s latest full risk assessment and a deterministic `turn_focus` for the symptoms extracted in this turn. Read-only; no model call.\n\n**Required inputs:** none.\n\n**When to call:** immediately before `submitRoutingDecision` only when `getRouterContextBundle.sections_returned` does not contain `risk`, including a bundle result with `_diagnostics.risk_error`. The routine load is the bundle\'s mandatory `risk` section, which resolves the same assessment through the same code path.\n\n**When NOT to call:** when `getRouterContextBundle` already returned `risk` this turn — it is the same assessment, and a second read cannot change it. Nor again in the same turn after a `not_generated` result — generation runs between turns and the result cannot change mid-turn.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**How to use:** read `turn_focus.current_concerns`, then each `relevant_risks[].checks_now` and `escalation_threshold`. It preserves concurrent symptoms. Any `selection` containing `fallback` marks a precaution to check, not a confirmed explanation. When `selection` is `no_current_concerns` the patient reported no current symptom this turn. Use `profile` only for supporting detail.\n\n**`profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `turn_focus.current_concerns`.\n\n**Returns:** `status` — `final` when an assessment exists and carries findings, `no_signal` when one exists but the synthesis found nothing usable, or `not_generated`; `turn_focus`, always present; and the full `profile` (`predicted_aes[]`, `disease_risks[]`, `comorbidity_amplifiers[]`, lifecycle and missing-information fields). `profile` is null when not yet generated.',
|
|
9
9
|
strict: false,
|
|
10
10
|
replayScope: 'turn',
|
|
11
11
|
parameters: {
|
|
@@ -10,7 +10,7 @@ const REQUIRED_SECTION = 'risk';
|
|
|
10
10
|
|
|
11
11
|
const definition = {
|
|
12
12
|
name: 'getRouterContextBundle',
|
|
13
|
-
description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `
|
|
13
|
+
description: '**Does:** Batched router-context fetch — always evaluates and returns the mandatory `risk` section, plus the requested `landscape` and/or `history` sections. Read-only.\n\n**Required inputs:** none. Optional `include` selects additional sections (`landscape`, `history`; a supplied `risk` value is accepted but redundant), plus optional `landscape_min_priority`, `history_scope`, `history_filter`. Omitting `include` returns all three sections.\n\n**When to call:** after intake at the start of every routing turn, as the single load of the patient\'s clinical context. Do not call it in parallel with `Skill(clinical_routing)`: first read the skill body, then call this bundle. The patient\'s risk disposition cannot be excluded by `include`. Prefer this over calling `getActiveSymptomLandscape`, `getPatientHistory` or `getPatientRiskAssessment` for the same context.\n\n**`turn_focus.recent_escalations` — what you already sent the team.** Every escalation dispatched for this patient in the last 14 days, newest first, with `escalated_at`, `days_since`, `urgency`, `reason` and the `channels` used. Read it before `reportMedicalEscalation`. It records only what was SENT; where the team is with it is in `team_cases`. A complaint unchanged since an escalation a day ago rarely needs a second dispatch; one still uncontrolled days after its escalation needs one at a HIGHER urgency, and `urgency_justification` should say which of the two this is. Empty means nothing was escalated in the window.\n\n**`turn_focus.team_cases` — where the care team is with each case.** Every case the team still holds, and those it closed in the last 14 days, newest first: `status`, `is_open`, `level`, `opened_at`, `days_since`, `doctor_decision` and `case_ids` (the symptom cases it covers).\n- `Por revisar`, `En evaluación`, `Con el médico`, `Indicación por enviar`, `Requiere valoración`: the team has it and has not answered yet. Tell the patient it is with the team, without promising a time. A new escalation is for a new symptom, a higher grade, a new red flag, or a symptom that persists or worsens while it waits (send it as an update).\n- `Esperando paciente`, `Indicaciones dadas`, `En vigilancia`: the team already answered (an indication on its way to the patient, given, or under watch). This comes first: ask how the indication is going before escalating again.\n- `Cerrado`, `No requiere`: the team closed it. A new complaint is a new decision.\n`doctor_decision` is internal (`approved`, `edited_approved`, `monitor`, `needs_intervention` = the doctor asked for an in-person evaluation, `returned`, `direct_chat`): use it to understand the case, never quote it. `team_cases` never says whether the problem resolved; ask the patient. An escalation in `recent_escalations` with no case here has an unknown team status, not an absent one.\n\n**Use `turn_focus.symptom_history` before grading or escalating.** It carries what no other section does: how this patient compares to their own past. `worst_grade` and `worst_reported_at` are the worst they have ever been recorded, `at_personal_worst` says whether they are back at it, and `days_since_last_report` says how stale `last_grade` is. (The current grade and trajectory are already in `landscape.active_cases` — do not expect them repeated here.) Escalate on the comparison, not on severity alone: a patient at their personal worst is a different decision from one below it, and a grade unchanged for weeks is different from the same grade reported yesterday. When you ask about it, anchor the question in the value and the date so the patient can compare. Empty means no graded case on record. \n\n**A case flagged `stale_no_recent_evidence` has had no new evidence for two weeks or more.** `days_since_evidence` says how long. Ask whether the symptom is still there, and close the case with `recordClinicalImpression` `close` when it is not: an open case keeps consuming the landscape and keeps the symptom reading as active on the record.\n\n**How to use risk:** read `risk.turn_focus` first — it is always present. It deterministically keeps every current symptom and maps it to relevant full-profile risks, `checks_now`, and `escalation_threshold`; use the full `risk.profile` only for supporting detail. A highest-severity fallback is labelled explicitly when no direct symptom match exists. When `turn_focus.selection` is `no_current_concerns` the patient reported no current symptom this turn.\n\n**`risk.profile` is a forecast, not history:** `predicted_aes[].minimum_symptom_set`, `disease_risks[].warning_symptoms` and every other profile list name symptoms to watch for, none of which the patient has reported. Never tell the patient a profile symptom appears in their report, and never attach a CTCAE grade to one. Reported symptoms come only from `landscape`, `history` and `turn_focus.current_concerns`.\n\n**Recovery:** verify `sections_returned` contains `risk`. If it does not, inspect `_diagnostics.risk_error` and call `getPatientRiskAssessment` before `submitRoutingDecision`.\n\n**Returns:** `patient_id`, `sections_requested[]`, `sections_returned[]` (only sections that succeeded), mandatory `risk` (always including `turn_focus`), and requested `landscape` / `history`. A section that errors is omitted and its error reported under `_diagnostics`. The attempted risk read and deterministic turn processing are recorded on the turn trace even when no profile exists.',
|
|
14
14
|
strict: false,
|
|
15
15
|
replayScope: 'turn',
|
|
16
16
|
parameters: {
|
|
@@ -11,7 +11,6 @@ const {
|
|
|
11
11
|
handOffToDoctor,
|
|
12
12
|
listEscalationReviews,
|
|
13
13
|
openEscalationReview,
|
|
14
|
-
previewPlanInstructions,
|
|
15
14
|
reclassifyUrgency,
|
|
16
15
|
recordDoctorDecision,
|
|
17
16
|
requestBotDraft,
|
|
@@ -31,7 +30,7 @@ const respondWithError = (res, error, action, context) => {
|
|
|
31
30
|
stack: redactDirectIdentifiers(String(error.stack || '')),
|
|
32
31
|
...context,
|
|
33
32
|
});
|
|
34
|
-
res.status(error.statusCode || 500).json({ success: false, error: error.message
|
|
33
|
+
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
35
34
|
};
|
|
36
35
|
|
|
37
36
|
const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
|
|
@@ -54,22 +53,13 @@ const openEscalationReviewController = async (req, res) => {
|
|
|
54
53
|
|
|
55
54
|
const getEscalationReviewController = async (req, res) => {
|
|
56
55
|
try {
|
|
57
|
-
const { review, isApprover, responseDeadline
|
|
58
|
-
res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline
|
|
56
|
+
const { review, isApprover, responseDeadline } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
|
|
57
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline });
|
|
59
58
|
} catch (error) {
|
|
60
59
|
respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
|
|
61
60
|
}
|
|
62
61
|
};
|
|
63
62
|
|
|
64
|
-
const previewEscalationReviewPlanController = async (req, res) => {
|
|
65
|
-
try {
|
|
66
|
-
const instructions = previewPlanInstructions({ id: req.params.id, plan: req.body?.plan });
|
|
67
|
-
res.status(200).json({ success: true, instructions });
|
|
68
|
-
} catch (error) {
|
|
69
|
-
respondWithError(res, error, 'previewing the plan instructions', { reviewId: req.params?.id });
|
|
70
|
-
}
|
|
71
|
-
};
|
|
72
|
-
|
|
73
63
|
const getReviewTimelineController = async (req, res) => {
|
|
74
64
|
try {
|
|
75
65
|
const timeline = await getReviewTimeline({ id: req.params.id });
|
|
@@ -185,9 +175,6 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
185
175
|
source,
|
|
186
176
|
decision,
|
|
187
177
|
finalText = null,
|
|
188
|
-
plan = null,
|
|
189
|
-
instructions = null,
|
|
190
|
-
prescriberEmail = null,
|
|
191
178
|
comment = null,
|
|
192
179
|
doctorName = null,
|
|
193
180
|
doctorReply = null,
|
|
@@ -201,9 +188,6 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
201
188
|
source,
|
|
202
189
|
decision,
|
|
203
190
|
finalText,
|
|
204
|
-
plan,
|
|
205
|
-
instructions,
|
|
206
|
-
prescriberEmail,
|
|
207
191
|
comment,
|
|
208
192
|
doctorName,
|
|
209
193
|
doctorReply,
|
|
@@ -300,7 +284,6 @@ module.exports = {
|
|
|
300
284
|
closeEscalationReviewController,
|
|
301
285
|
getEscalationReviewController,
|
|
302
286
|
getReviewTimelineController,
|
|
303
|
-
previewEscalationReviewPlanController,
|
|
304
287
|
requestEscalationReviewDraftController,
|
|
305
288
|
handOffEscalationReviewController,
|
|
306
289
|
listEscalationReviewsController,
|
|
@@ -1,11 +1,17 @@
|
|
|
1
|
+
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
2
|
+
|
|
1
3
|
const { logger } = require('../utils/logger');
|
|
2
4
|
|
|
3
|
-
const {
|
|
5
|
+
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
6
|
+
|
|
7
|
+
const { addLinkedRecord } = require('../services/airtableService');
|
|
4
8
|
|
|
5
9
|
const RECORD_ID_RX = /^rec[A-Za-z0-9]{14}$/;
|
|
6
10
|
|
|
11
|
+
// physicianId links the receta to a physicians row; the Airtable automation picks the PDF template from that physician's specialty.
|
|
7
12
|
const createPrescriptionController = async (req, res) => {
|
|
8
|
-
const {
|
|
13
|
+
const { prescription, triggeredBy, creationSource = 'other', physicianId } = req.body;
|
|
14
|
+
let code = req.body.code;
|
|
9
15
|
|
|
10
16
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
11
17
|
if (!prescription) return res.status(400).json({ success: false, error: 'Prescription is required' });
|
|
@@ -15,10 +21,28 @@ const createPrescriptionController = async (req, res) => {
|
|
|
15
21
|
}
|
|
16
22
|
|
|
17
23
|
try {
|
|
18
|
-
|
|
24
|
+
code = ensureWhatsAppFormat(code);
|
|
25
|
+
|
|
26
|
+
const record = await addLinkedRecord(
|
|
27
|
+
Monitoreo_ID,
|
|
28
|
+
'patient_prescriptions',
|
|
29
|
+
{
|
|
30
|
+
prescription,
|
|
31
|
+
author_email: triggeredBy,
|
|
32
|
+
creation_source: creationSource,
|
|
33
|
+
created: new Date().toISOString(),
|
|
34
|
+
...(physicianId && { physician: [physicianId] })
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
referenceTable: 'estado_general',
|
|
38
|
+
referenceFilter: `{whatsapp_id}='${code}'`,
|
|
39
|
+
linkFieldName: 'patient_id'
|
|
40
|
+
},
|
|
41
|
+
code
|
|
42
|
+
);
|
|
19
43
|
|
|
20
44
|
logger.info('[PrescriptionController] Prescription created', { code, physicianId });
|
|
21
|
-
res.status(201).json({ success: true, message: 'Prescription created', recordId });
|
|
45
|
+
res.status(201).json({ success: true, message: 'Prescription created', recordId: record?.id || null });
|
|
22
46
|
} catch (error) {
|
|
23
47
|
logger.error('[PrescriptionController] Error creating prescription', { error: error.message, code });
|
|
24
48
|
res.status(500).json({ success: false, error: 'Failed to create prescription' });
|
|
@@ -116,7 +116,10 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
|
|
|
116
116
|
return { retried: false, reason: 'already_sent' };
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
-
const priorAttempts =
|
|
119
|
+
const priorAttempts = messageDoc.statusInfo?.recoveryFallbackAt
|
|
120
|
+
? (await DeliveryAttempt.find({ messageId, kind: { $in: ['recovery_template', 'template'] }, contentSid: attempt.contentSid }, 'variables').lean())
|
|
121
|
+
.filter(sent => stableContent(sent.variables) === stableContent(variables)).length
|
|
122
|
+
: await DeliveryAttempt.countDocuments({ messageId, kind: 'template' });
|
|
120
123
|
const delay = retryDelays()[priorAttempts - 1];
|
|
121
124
|
|
|
122
125
|
if (isAtOrBefore(messageDoc.expiresAt, new Date(Date.now() + (delay ?? 0)))) {
|
|
@@ -213,6 +216,8 @@ async function handleBlockedDelivery(messageDoc, twilioSid, errorCode) {
|
|
|
213
216
|
if (await patientIsDeceased(messageDoc.numero)) return { retried: false, reason: 'patient_deceased' };
|
|
214
217
|
|
|
215
218
|
const logCtx = { twilioSid, errorCode, messageId: String(messageDoc._id) };
|
|
219
|
+
// A fallback part carries only a piece of the text, so resending the whole message would repeat what already arrived.
|
|
220
|
+
if (messageDoc.statusInfo?.recoveryFallbackAt) return reportBlockedDelivery(messageDoc, logCtx);
|
|
216
221
|
const claimed = attempt && (await Message.updateOne(
|
|
217
222
|
{ _id: messageDoc._id, 'statusInfo.blockedRetryAt': null },
|
|
218
223
|
{ $set: { 'statusInfo.blockedRetryAt': new Date() } }
|
|
@@ -31,6 +31,7 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
|
|
|
31
31
|
|
|
32
32
|
const notTerminal = { 'statusInfo.status': { $nin: DELIVERY_ATTEMPT_TERMINAL_STATUSES } };
|
|
33
33
|
|
|
34
|
+
let fallbackParent = null;
|
|
34
35
|
let updated = await Message.findOneAndUpdate(
|
|
35
36
|
{ message_id: messageSid, ...notTerminal },
|
|
36
37
|
{ $set: updateData },
|
|
@@ -45,13 +46,18 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
|
|
|
45
46
|
{ new: true }
|
|
46
47
|
);
|
|
47
48
|
}
|
|
49
|
+
if (!updated && attempt?.messageId && (status === 'failed' || status === 'undelivered')) {
|
|
50
|
+
[fallbackParent] = await getMessages({ _id: attempt.messageId, 'statusInfo.recoveryFallbackAt': { $ne: null } }, { limit: 1 });
|
|
51
|
+
}
|
|
48
52
|
}
|
|
49
53
|
|
|
50
54
|
if (!updated) {
|
|
51
55
|
logger.warn('[MessageStatus] Message not found', { messageSid });
|
|
52
56
|
}
|
|
53
57
|
|
|
54
|
-
await updateDeliveryAttemptByTwilioSid(messageSid, { status, errorCode, errorMessage });
|
|
58
|
+
const attemptUpdated = await updateDeliveryAttemptByTwilioSid(messageSid, { status, errorCode, errorMessage });
|
|
59
|
+
// A message sent in parts settles on its first part, so a later part's failure finds it already terminal.
|
|
60
|
+
if (fallbackParent && attemptUpdated) updated = fallbackParent;
|
|
55
61
|
|
|
56
62
|
if (updated) {
|
|
57
63
|
if (status === 'failed' || status === 'undelivered') {
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
const { getRecoveryTemplateConfig } = require('../config/recoveryTemplateConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
const { isAtOrBefore } = require('../utils/dateUtils');
|
|
4
|
+
const { Message } = require('../models/messageModel');
|
|
5
|
+
const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
|
|
6
|
+
|
|
7
|
+
const { alertUndeliverable } = require('./channelRetryHelper');
|
|
8
|
+
const {
|
|
9
|
+
resolveRecoveryBody, hasUnresolvedPhi, fixedTemplateFor, fixedTextMessages, cleanupRecoveryTemplate, acceptedFixedSid, claimRecoverySend, recoverySendData
|
|
10
|
+
} = require('./templateRecoveryHelper');
|
|
11
|
+
|
|
12
|
+
const getMessaging = () => require('../core/NexusMessaging');
|
|
13
|
+
|
|
14
|
+
const TOO_LONG_ERROR_MESSAGE = 'Too long for a template and the fixed templates could not send it';
|
|
15
|
+
|
|
16
|
+
const isFallbackEnabled = async () => Boolean((await getRecoveryTemplateConfig()).RECOVERY_TEXT_TEMPLATE_SID);
|
|
17
|
+
|
|
18
|
+
async function buildFallbackPlan(messageDoc) {
|
|
19
|
+
if (messageDoc.media?.key) {
|
|
20
|
+
const template = await fixedTemplateFor(messageDoc);
|
|
21
|
+
return template ? { messages: [template] } : { reason: 'no_fitting_file_template' };
|
|
22
|
+
}
|
|
23
|
+
const text = await resolveRecoveryBody(messageDoc);
|
|
24
|
+
if (hasUnresolvedPhi(text)) return { reason: 'unresolved_phi' };
|
|
25
|
+
const messages = fixedTextMessages(text, await getRecoveryTemplateConfig());
|
|
26
|
+
return messages ? { messages } : { reason: 'no_fitting_text_template' };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const hasFallbackPlan = async (messageDoc) => Boolean((await buildFallbackPlan(messageDoc)).messages);
|
|
30
|
+
|
|
31
|
+
const sentOrDone = (result) => Boolean(result?.messageId) || Boolean(result?.duplicate && result?.completed);
|
|
32
|
+
|
|
33
|
+
async function releaseFallbackClaim(messageDoc) {
|
|
34
|
+
await Message.updateOne(
|
|
35
|
+
{ _id: messageDoc._id },
|
|
36
|
+
{ $unset: { 'statusInfo.recoverySentAt': '', 'statusInfo.recoveryFallbackAt': '', 'statusInfo.recoveryFallbackReason': '' } }
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const alertFallback = (messageDoc, details) => alertUndeliverable({
|
|
41
|
+
source: 'recovery_fallback', messageId: String(messageDoc._id), to: messageDoc.numero,
|
|
42
|
+
triggeredBy: messageDoc.triggeredBy || null, ...details
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
async function failTooLong(messageDoc, reason) {
|
|
46
|
+
await Message.updateOne(
|
|
47
|
+
{ _id: messageDoc._id, 'statusInfo.recoverySentAt': null },
|
|
48
|
+
{ $set: {
|
|
49
|
+
'statusInfo.recoveryFailedAt': new Date(),
|
|
50
|
+
'statusInfo.status': 'failed',
|
|
51
|
+
'statusInfo.errorMessage': TOO_LONG_ERROR_MESSAGE,
|
|
52
|
+
'statusInfo.updatedAt': new Date()
|
|
53
|
+
} }
|
|
54
|
+
);
|
|
55
|
+
alertFallback(messageDoc, { reason });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async function sendPart(messageDoc, template, index, send) {
|
|
59
|
+
try {
|
|
60
|
+
const data = {
|
|
61
|
+
...recoverySendData(messageDoc, template),
|
|
62
|
+
...(!messageDoc.media?.key && { body: Object.values(template.variables).join('\n\n') })
|
|
63
|
+
};
|
|
64
|
+
if (!index) return await send({ ...data, idempotencyKey: `recovery-fallback:${messageDoc._id}` });
|
|
65
|
+
// The patient receives one message in parts, so only the first part counts as a contact.
|
|
66
|
+
return await getMessaging().requireDefaultInstance()._transport({ ...data, continuesSend: true });
|
|
67
|
+
} catch (error) {
|
|
68
|
+
// The provider may have accepted the first part before the bookkeeping failed; sending it again would repeat it.
|
|
69
|
+
let acceptedSid;
|
|
70
|
+
try {
|
|
71
|
+
acceptedSid = index === 0 && await acceptedFixedSid(messageDoc._id, template.contentSid);
|
|
72
|
+
} catch {
|
|
73
|
+
return { status: 'state_unknown', error };
|
|
74
|
+
}
|
|
75
|
+
if (acceptedSid) return { messageId: acceptedSid };
|
|
76
|
+
return { status: 'send_failed', error };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function sendParts(messageDoc, plan, send, logCtx) {
|
|
81
|
+
let sentParts = 0;
|
|
82
|
+
let firstResult = null;
|
|
83
|
+
for (const [index, template] of plan.messages.entries()) {
|
|
84
|
+
if (index > 0 && isAtOrBefore(messageDoc.expiresAt, Date.now())) {
|
|
85
|
+
logger.warn('[RecoveryFallback] Message expired between parts, the rest is not sent', { ...logCtx, sentParts });
|
|
86
|
+
break;
|
|
87
|
+
}
|
|
88
|
+
const result = await sendPart(messageDoc, template, index, send);
|
|
89
|
+
if (!sentOrDone(result)) {
|
|
90
|
+
if (!sentParts) return { sentParts, result };
|
|
91
|
+
alertFallback(messageDoc, {
|
|
92
|
+
reason: 'partial_fallback', sentParts, totalParts: plan.messages.length,
|
|
93
|
+
status: result?.status || null, error: result?.error?.message || null
|
|
94
|
+
});
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
if (!sentParts) firstResult = result;
|
|
98
|
+
sentParts += 1;
|
|
99
|
+
}
|
|
100
|
+
return { sentParts, firstResult };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function sendRecoveryFallback(messageDoc, { trigger, send }) {
|
|
104
|
+
const logCtx = { messageId: String(messageDoc._id), trigger };
|
|
105
|
+
const plan = await buildFallbackPlan(messageDoc);
|
|
106
|
+
if (!plan.messages) {
|
|
107
|
+
logger.warn('[RecoveryFallback] No fixed template fits this message', { ...logCtx, reason: plan.reason });
|
|
108
|
+
if (trigger === 'too_long') await failTooLong(messageDoc, plan.reason);
|
|
109
|
+
return { sent: false, reason: plan.reason };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const claimed = await claimRecoverySend(messageDoc._id, { 'statusInfo.recoveryFallbackAt': new Date(), 'statusInfo.recoveryFallbackReason': trigger });
|
|
113
|
+
if (!claimed) return { sent: false, reason: 'already_claimed' };
|
|
114
|
+
|
|
115
|
+
const { sentParts, firstResult, result } = await sendParts(messageDoc, plan, send, logCtx);
|
|
116
|
+
if (!sentParts) {
|
|
117
|
+
if (result?.status === 'outbound_blocked') return { sent: false, reason: 'outbound_blocked' };
|
|
118
|
+
// Whether the patient got the first part is unknown, so the claim stays and staff decide instead of a resend.
|
|
119
|
+
if (result?.status === 'state_unknown') {
|
|
120
|
+
alertFallback(messageDoc, { reason: 'state_unknown', error: result.error?.message || null });
|
|
121
|
+
return { sent: false, reason: 'state_unknown' };
|
|
122
|
+
}
|
|
123
|
+
await releaseFallbackClaim(messageDoc);
|
|
124
|
+
const reason = result?.status || 'send_failed';
|
|
125
|
+
if (trigger === 'too_long') {
|
|
126
|
+
await failTooLong(messageDoc, reason);
|
|
127
|
+
return { sent: false, reason };
|
|
128
|
+
}
|
|
129
|
+
logger.warn('[RecoveryFallback] First part not sent, leaving the message to the approval job', { ...logCtx, reason, error: result?.error?.message });
|
|
130
|
+
return { sent: false, reason };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const templateSid = messageDoc.statusInfo?.recoveryTemplateSid;
|
|
134
|
+
if (templateSid) {
|
|
135
|
+
await DeliveryAttempt.updateOne(
|
|
136
|
+
{ messageId: messageDoc._id, kind: 'recovery_template_setup', twilioSid: templateSid },
|
|
137
|
+
{ $set: { status: 'failed', errorSource: 'server', errorMessage: `Replaced by the fixed templates (${trigger})`, completedAt: new Date() } }
|
|
138
|
+
).catch(error => logger.warn('[RecoveryFallback] Could not close the setup attempt', { ...logCtx, error: error.message }));
|
|
139
|
+
}
|
|
140
|
+
await cleanupRecoveryTemplate(messageDoc);
|
|
141
|
+
|
|
142
|
+
logger.info('[RecoveryFallback] Sent', { ...logCtx, sentParts, totalParts: plan.messages.length });
|
|
143
|
+
return { sent: true, sentParts, totalParts: plan.messages.length, firstResult };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
module.exports = { isFallbackEnabled, hasFallbackPlan, sendRecoveryFallback };
|
|
@@ -5,6 +5,7 @@ const { isAtOrBefore } = require('../utils/dateUtils');
|
|
|
5
5
|
const { oneLineOf } = require('../utils/coercionUtils');
|
|
6
6
|
const { MAX_TEMPLATE_TEXT_LENGTH } = require('../utils/templateUtils');
|
|
7
7
|
const { createEvent, safeEmit } = require('../utils/eventUtils');
|
|
8
|
+
const { shapeTemplateParts } = require('../utils/templateTextUtils');
|
|
8
9
|
const { Message } = require('../models/messageModel');
|
|
9
10
|
const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
|
|
10
11
|
const { Template: TemplateModel } = require('../models/templateModel');
|
|
@@ -13,11 +14,15 @@ const { contactOf } = require('./caregiverHelper');
|
|
|
13
14
|
const { recordDeliveryAttempt } = require('./deliveryAttemptHelper');
|
|
14
15
|
|
|
15
16
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
17
|
+
const getFallback = () => require('./recoveryFallbackHelper');
|
|
16
18
|
|
|
17
19
|
const TEMPLATE_BODY_LIMIT = 1024;
|
|
18
20
|
const RECOVERY_MEDIA_URL_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
19
21
|
|
|
20
22
|
const FIXED_TEXT_TEMPLATE_KEY = 'RECOVERY_TEXT_TEMPLATE_SID';
|
|
23
|
+
const FIXED_TEXT_TEMPLATE_KEYS = [FIXED_TEXT_TEMPLATE_KEY, 'RECOVERY_TEXT_2_TEMPLATE_SID', 'RECOVERY_TEXT_3_TEMPLATE_SID'];
|
|
24
|
+
// What is left of Meta's 1024 characters once the fixed wording of a text template is counted.
|
|
25
|
+
const FIXED_TEXT_BUDGET = 880;
|
|
21
26
|
const FIXED_FILE_TEMPLATE_KEYS = {
|
|
22
27
|
'application/pdf': 'RECOVERY_DOCUMENT_TEMPLATE_SID',
|
|
23
28
|
'image/jpeg': 'RECOVERY_IMAGE_TEMPLATE_SID',
|
|
@@ -51,10 +56,23 @@ async function resolveRecoveryBody(messageDoc) {
|
|
|
51
56
|
|
|
52
57
|
const EXPIRED_ERROR_MESSAGE = 'Expired before it could be delivered';
|
|
53
58
|
|
|
59
|
+
function fixedTextMessages(body, config) {
|
|
60
|
+
const messages = (shapeTemplateParts(body, FIXED_TEXT_BUDGET) || []).map((part) => {
|
|
61
|
+
const contentSid = config[FIXED_TEXT_TEMPLATE_KEYS[part.length - 1]];
|
|
62
|
+
return contentSid && { contentSid, variables: Object.fromEntries(part.map((text, index) => [String(index + 1), text])) };
|
|
63
|
+
});
|
|
64
|
+
return messages.length && messages.every(Boolean) ? messages : null;
|
|
65
|
+
}
|
|
66
|
+
|
|
54
67
|
async function fixedRecoveryTemplate(media, body) {
|
|
68
|
+
const config = await getRecoveryTemplateConfig();
|
|
69
|
+
if (!media?.key) {
|
|
70
|
+
const [only, ...more] = fixedTextMessages(body, config) || [];
|
|
71
|
+
if (only && !more.length && Object.keys(only.variables).length > 1) return only;
|
|
72
|
+
}
|
|
73
|
+
|
|
55
74
|
const text = oneLineOf(body);
|
|
56
75
|
if (text.length > MAX_TEMPLATE_TEXT_LENGTH) return null;
|
|
57
|
-
const config = await getRecoveryTemplateConfig();
|
|
58
76
|
|
|
59
77
|
if (!media?.key) {
|
|
60
78
|
const contentSid = config[FIXED_TEXT_TEMPLATE_KEY];
|
|
@@ -91,10 +109,10 @@ const recoverySendData = (messageDoc, template) => ({
|
|
|
91
109
|
body: messageDoc.body
|
|
92
110
|
});
|
|
93
111
|
|
|
94
|
-
async function claimRecoverySend(messageId) {
|
|
112
|
+
async function claimRecoverySend(messageId, extra = {}) {
|
|
95
113
|
const claim = await Message.updateOne(
|
|
96
114
|
{ _id: messageId, 'statusInfo.recoverySentAt': null, 'statusInfo.recoveryReleasedAt': null },
|
|
97
|
-
{ $set: { 'statusInfo.recoverySentAt': new Date() } }
|
|
115
|
+
{ $set: { 'statusInfo.recoverySentAt': new Date(), ...extra } }
|
|
98
116
|
);
|
|
99
117
|
return Boolean(claim.modifiedCount || claim.nModified);
|
|
100
118
|
}
|
|
@@ -216,13 +234,14 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
216
234
|
|
|
217
235
|
const recoveryBody = await resolveRecoveryBody(messageDoc);
|
|
218
236
|
|
|
237
|
+
const send = (data) => source === 'preemptive'
|
|
238
|
+
? getMessaging().requireDefaultInstance()._transport({ ...data, contactGateDecisionId })
|
|
239
|
+
: getMessaging().sendMessage({ idempotencyKey: `recovery-fixed:${messageDocId}`, ...data });
|
|
240
|
+
|
|
219
241
|
let fixedSendFailed = false;
|
|
220
242
|
if (messageDoc.media?.key && !hasUnresolvedPhi(recoveryBody)) {
|
|
221
243
|
const fixedTemplate = await fixedRecoveryTemplate(messageDoc.media, recoveryBody);
|
|
222
244
|
if (fixedTemplate) {
|
|
223
|
-
const send = (data) => source === 'preemptive'
|
|
224
|
-
? getMessaging().requireDefaultInstance()._transport({ ...data, contactGateDecisionId })
|
|
225
|
-
: getMessaging().sendMessage({ ...data, idempotencyKey: `recovery-fixed:${messageDocId}` });
|
|
226
245
|
const { outcome, result } = await sendFixedRecovery(messageDoc, fixedTemplate, logCtx, send);
|
|
227
246
|
if (outcome === 'sent') return { delivered: false, deferred: false, fixedSend: result };
|
|
228
247
|
if (outcome === 'skipped') return { delivered: false, deferred: true };
|
|
@@ -237,12 +256,19 @@ async function triggerTemplateRecovery(messageDoc, { source = 'reactive', messag
|
|
|
237
256
|
const mediaUrl = await resolveRecoveryMediaUrl(messageDoc.media);
|
|
238
257
|
if (mediaUrl) template.setMedia(mediaUrl);
|
|
239
258
|
|
|
259
|
+
const tooLongForTemplate = recoveryBody.length > TEMPLATE_BODY_LIMIT && !messageDoc.media?.key && await getFallback().isFallbackEnabled();
|
|
260
|
+
|
|
240
261
|
let twilioContent;
|
|
241
262
|
let setupErr = null;
|
|
242
263
|
if (!recoveryBody) {
|
|
243
264
|
setupErr = new Error('A file with no text can only go out on a fixed template');
|
|
244
265
|
} else if (hasUnresolvedPhi(recoveryBody)) {
|
|
245
266
|
setupErr = new Error('Body still carries a PHI placeholder after decoding');
|
|
267
|
+
} else if (tooLongForTemplate) {
|
|
268
|
+
const fallback = await getFallback().sendRecoveryFallback(messageDoc, { trigger: 'too_long', send })
|
|
269
|
+
.catch(error => ({ sent: false, reason: error.message }));
|
|
270
|
+
if (fallback.sent) return { delivered: false, deferred: false, fixedSend: fallback.firstResult };
|
|
271
|
+
setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length}) and the fixed templates could not send it (${fallback.reason})`);
|
|
246
272
|
} else if (recoveryBody.length > TEMPLATE_BODY_LIMIT) {
|
|
247
273
|
setupErr = new Error(`Body exceeds ${TEMPLATE_BODY_LIMIT}-char template limit (${recoveryBody.length})`);
|
|
248
274
|
} else {
|
|
@@ -331,4 +357,4 @@ async function cleanupRecoveryTemplate(messageDoc) {
|
|
|
331
357
|
}
|
|
332
358
|
}
|
|
333
359
|
|
|
334
|
-
module.exports = { acceptedFixedSid, claimRecoverySend, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi, closeExpiredRecovery };
|
|
360
|
+
module.exports = { acceptedFixedSid, claimRecoverySend, fixedTemplateFor, recoverySendData, reopenAfterFixedFailure, handle24HourWindowError, triggerTemplateRecovery, cleanupRecoveryTemplate, resolveRecoveryBody, fixedTextMessages, hasUnresolvedPhi, closeExpiredRecovery };
|
package/lib/index.d.ts
CHANGED
|
@@ -274,7 +274,7 @@ declare module '@peopl-health/nexus' {
|
|
|
274
274
|
initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
|
|
275
275
|
getWorkflowRunner(): WorkflowRunner;
|
|
276
276
|
processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string; beforeRun?: () => Promise<string | null | undefined> | string | null | undefined; dedupeWithinMs?: number }): Promise<{ outcome: string | null; reason?: string; error?: string }>;
|
|
277
|
-
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<
|
|
277
|
+
processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
|
|
278
278
|
processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean; replyToContact?: boolean; allowFollowUp?: boolean }): Promise<OutreachDecision>;
|
|
279
279
|
processCheckInDue(code: string, options: { reminderId: string; type: 'contingencia' | 'seguimiento'; question?: string; firstName?: string | null }): Promise<CheckInDueResult>;
|
|
280
280
|
processScheduledFollowUp(code: string, options: { reminderId: string; firstName: string; now?: Date }): Promise<ScheduledFollowUpResult>;
|