@peopl-health/nexus 6.4.0-dev.18856 → 6.4.0-dev.18958
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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/config/recoveryTemplateConfig.js +21 -14
- package/lib/controllers/escalationReviewController.js +3 -20
- package/lib/controllers/prescriptionController.js +28 -4
- package/lib/core/NexusMessaging.js +9 -11
- package/lib/helpers/channelErrorHelper.js +6 -2
- package/lib/helpers/channelRetryHelper.js +70 -3
- package/lib/helpers/messageStatusHelper.js +13 -2
- package/lib/helpers/recoveryFallbackHelper.js +146 -0
- package/lib/helpers/templateRecoveryHelper.js +101 -51
- package/lib/index.d.ts +1 -1
- package/lib/jobs/TemplateApprovalJob.js +43 -31
- package/lib/models/escalationReviewModel.js +2 -38
- package/lib/models/messageModel.js +4 -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 +13 -192
- package/lib/services/officeAssistantService.js +1 -1
- package/lib/utils/httpErrorUtils.js +1 -1
- package/lib/utils/templateTextUtils.js +64 -0
- package/lib/utils/templateUtils.js +4 -1
- package/package.json +1 -1
- package/lib/clinical/helpers/doctorPlanHelper.js +0 -105
- package/lib/clinical/helpers/planTextHelper.js +0 -127
- 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: {
|
|
@@ -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 };
|
|
@@ -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' });
|
|
@@ -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
|
|
|
@@ -110,7 +116,10 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
|
|
|
110
116
|
return { retried: false, reason: 'already_sent' };
|
|
111
117
|
}
|
|
112
118
|
|
|
113
|
-
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' });
|
|
114
123
|
const delay = retryDelays()[priorAttempts - 1];
|
|
115
124
|
|
|
116
125
|
if (isAtOrBefore(messageDoc.expiresAt, new Date(Date.now() + (delay ?? 0)))) {
|
|
@@ -162,4 +171,62 @@ async function handleRetryableChannelError(messageDoc, twilioSid, errorCode) {
|
|
|
162
171
|
return { retried: true, attempt: priorAttempts, delayMs: delay, scheduledMessageId: String(scheduled._id) };
|
|
163
172
|
}
|
|
164
173
|
|
|
165
|
-
|
|
174
|
+
async function reportBlockedDelivery(messageDoc, logCtx) {
|
|
175
|
+
alertUndeliverable({ ...logCtx, reason: 'blocked_by_meta' });
|
|
176
|
+
const sender = isStaffSend(messageDoc.triggeredBy) ? `de ${messageDoc.triggeredBy}` : 'del asistente';
|
|
177
|
+
const recipient = messageDoc.contact_code ? ` a su cuidador (+${phoneDigits(messageDoc.contact_code)})` : '';
|
|
178
|
+
const written = await recordUnresolvedRequest({
|
|
179
|
+
code: messageDoc.numero,
|
|
180
|
+
trace: null,
|
|
181
|
+
category: 'contact_team_member',
|
|
182
|
+
question: 'Mensaje de WhatsApp no entregado',
|
|
183
|
+
details: formatOpsAlert(messageDoc.numero, {
|
|
184
|
+
label: 'Mensaje no entregado',
|
|
185
|
+
summary: `WhatsApp bloqueó (${logCtx.errorCode}) un mensaje ${sender}${recipient}; hay que llamarle`
|
|
186
|
+
})
|
|
187
|
+
});
|
|
188
|
+
if (written) return { retried: false, reason: 'reported' };
|
|
189
|
+
logger.error('[ChannelRetry] No new ops alert: the write failed or a recent one is still open', logCtx);
|
|
190
|
+
return { retried: false, reason: 'alert_not_written' };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function resendOnFixedTemplate(messageDoc, attempt, logCtx) {
|
|
194
|
+
try {
|
|
195
|
+
const template = await fixedTemplateFor(messageDoc);
|
|
196
|
+
if (!template || template.contentSid === attempt.contentSid) return 'failed';
|
|
197
|
+
const result = await getMessaging().sendMessage({
|
|
198
|
+
...recoverySendData(messageDoc, template),
|
|
199
|
+
idempotencyKey: `blocked-retry:${messageDoc._id}`
|
|
200
|
+
});
|
|
201
|
+
if (result?.messageId && result.status !== 'failed') return 'sent';
|
|
202
|
+
return REFUSED_ON_PURPOSE.has(result?.status) ? 'refused' : 'failed';
|
|
203
|
+
} catch (err) {
|
|
204
|
+
logger.error('[ChannelRetry] Could not resend the blocked message', { ...logCtx, error: err.message });
|
|
205
|
+
return 'failed';
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
async function handleBlockedDelivery(messageDoc, twilioSid, errorCode) {
|
|
210
|
+
if (messageDoc.origin !== 'assistant' && !isStaffSend(messageDoc.triggeredBy)) return { retried: false, reason: 'not_a_personal_send' };
|
|
211
|
+
if (isAtOrBefore(messageDoc.expiresAt, Date.now())) return { retried: false, reason: 'expired' };
|
|
212
|
+
|
|
213
|
+
const attempt = await DeliveryAttempt.findOne({ twilioSid }, 'kind contentSid').lean();
|
|
214
|
+
if (attempt && attempt.kind !== 'recovery_template') return { retried: false, reason: 'not_a_personal_send' };
|
|
215
|
+
|
|
216
|
+
if (await patientIsDeceased(messageDoc.numero)) return { retried: false, reason: 'patient_deceased' };
|
|
217
|
+
|
|
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);
|
|
221
|
+
const claimed = attempt && (await Message.updateOne(
|
|
222
|
+
{ _id: messageDoc._id, 'statusInfo.blockedRetryAt': null },
|
|
223
|
+
{ $set: { 'statusInfo.blockedRetryAt': new Date() } }
|
|
224
|
+
)).modifiedCount;
|
|
225
|
+
const outcome = claimed ? await resendOnFixedTemplate(messageDoc, attempt, logCtx) : 'failed';
|
|
226
|
+
if (outcome === 'refused') return { retried: false, reason: 'refused' };
|
|
227
|
+
if (outcome === 'failed') return reportBlockedDelivery(messageDoc, logCtx);
|
|
228
|
+
logger.warn('[ChannelRetry] Blocked by Meta, resent on the fixed template', logCtx);
|
|
229
|
+
return { retried: true, reason: 'fixed_template' };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
module.exports = { handleBlockedDelivery, handleRetryableChannelError, alertUndeliverable };
|
|
@@ -23,8 +23,15 @@ 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
|
|
|
34
|
+
let fallbackParent = null;
|
|
28
35
|
let updated = await Message.findOneAndUpdate(
|
|
29
36
|
{ message_id: messageSid, ...notTerminal },
|
|
30
37
|
{ $set: updateData },
|
|
@@ -32,7 +39,6 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
|
|
|
32
39
|
);
|
|
33
40
|
|
|
34
41
|
if (!updated) {
|
|
35
|
-
const attempt = await DeliveryAttempt.findOne({ twilioSid: messageSid }, '_id messageId').lean();
|
|
36
42
|
if (attempt?.messageId) {
|
|
37
43
|
updated = await Message.findOneAndUpdate(
|
|
38
44
|
{ _id: attempt.messageId, ...notTerminal },
|
|
@@ -40,13 +46,18 @@ async function updateMessageStatus(messageSid, status, errorCode = null, errorMe
|
|
|
40
46
|
{ new: true }
|
|
41
47
|
);
|
|
42
48
|
}
|
|
49
|
+
if (!updated && attempt?.messageId && (status === 'failed' || status === 'undelivered')) {
|
|
50
|
+
[fallbackParent] = await getMessages({ _id: attempt.messageId, 'statusInfo.recoveryFallbackAt': { $ne: null } }, { limit: 1 });
|
|
51
|
+
}
|
|
43
52
|
}
|
|
44
53
|
|
|
45
54
|
if (!updated) {
|
|
46
55
|
logger.warn('[MessageStatus] Message not found', { messageSid });
|
|
47
56
|
}
|
|
48
57
|
|
|
49
|
-
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;
|
|
50
61
|
|
|
51
62
|
if (updated) {
|
|
52
63
|
if (status === 'failed' || status === 'undelivered') {
|