@peopl-health/nexus 6.4.0-dev.18830 → 6.4.0-dev.18856
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/clinical/helpers/doctorPlanHelper.js +2 -1
- package/lib/clinical/helpers/planTextHelper.js +42 -13
- package/lib/clinical/services/doctorPlanService.js +5 -2
- package/lib/controllers/escalationReviewController.js +1 -1
- package/lib/services/escalationReviewService.js +15 -11
- package/lib/utils/httpErrorUtils.js +1 -1
- package/package.json +1 -1
|
@@ -21,7 +21,7 @@ const FOLLOW_UP_LINES = {
|
|
|
21
21
|
};
|
|
22
22
|
|
|
23
23
|
function planInstructions(plan) {
|
|
24
|
-
const lines = ['Transmítele al paciente lo que indicó el médico, con tus palabras: no cambies dosis, frecuencia ni días, y no agregues otros medicamentos ni estudios.'];
|
|
24
|
+
const lines = ['Transmítele al paciente lo que indicó el médico, con tus palabras: no cambies dosis, frecuencia ni días, y no agregues otros medicamentos ni estudios. Escribe dosis, horas y días con números, como vienen aquí, sin repetirlos con letra, y no agregues avisos de urgencia que el médico no dio.'];
|
|
25
25
|
if (plan.items.length) {
|
|
26
26
|
lines.push('Medicamentos:', ...plan.items.map((item) => `- ${itemLine(item)}`));
|
|
27
27
|
}
|
|
@@ -90,6 +90,7 @@ const plannedTextOf = (plan) => [
|
|
|
90
90
|
...plan.studies.flatMap((study) => [study.name, study.instructions]),
|
|
91
91
|
...plan.homeCare,
|
|
92
92
|
plan.note,
|
|
93
|
+
plan.followUp?.kind in FOLLOW_UP_LINES && FOLLOW_UP_LINES[plan.followUp.kind](plan.followUp.hours),
|
|
93
94
|
].filter(Boolean).join('\n');
|
|
94
95
|
|
|
95
96
|
module.exports = {
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
const { foldAccents } = require('../../utils/formatUtils');
|
|
2
2
|
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
3
3
|
|
|
4
|
-
const
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
const UNITS = ['', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
|
|
5
|
+
const TEENS = ['diez', 'once', 'doce', 'trece', 'catorce', 'quince', 'dieciseis', 'diecisiete', 'dieciocho', 'diecinueve'];
|
|
6
|
+
const TENS = ['', '', 'veinte', 'treinta', 'cuarenta', 'cincuenta', 'sesenta', 'setenta', 'ochenta', 'noventa'];
|
|
7
|
+
// 1 to 99 as written without accents: «veintiuno», «veintiun», «treinta y seis»; «un» and «una» are 1.
|
|
8
|
+
const NUMBER_WORDS = Object.freeze(Object.fromEntries([
|
|
9
|
+
['un', 1], ['una', 1], ['veintiun', 21],
|
|
10
|
+
...UNITS.slice(1).map((word, index) => [word, index + 1]),
|
|
11
|
+
...TEENS.map((word, index) => [word, index + 10]),
|
|
12
|
+
...UNITS.slice(1).map((word, index) => [`veinti${word}`, index + 21]),
|
|
13
|
+
...TENS.slice(2).map((word, index) => [word, (index + 2) * 10]),
|
|
14
|
+
...TENS.slice(3).flatMap((word, tens) => UNITS.slice(1).map((unit, index) => [`${word} y ${unit}`, (tens + 3) * 10 + index + 1])),
|
|
15
|
+
]));
|
|
9
16
|
const WORDS = Object.keys(NUMBER_WORDS).sort((a, b) => b.length - a.length).join('|');
|
|
10
17
|
const COUNT = `(?:\\d+|${WORDS})`;
|
|
11
18
|
// «y» is left out: «treinta y cinco» is one number, not a range.
|
|
@@ -17,13 +24,13 @@ const DAY_UNITS = 'd[ií]as?|semanas?|mes(?:es)?|d\\b';
|
|
|
17
24
|
const DURATION_SOURCE = `(?:por|durante|x)\\s+(?:(?:unos|unas|los|las|pr[oó]ximos|otros)\\s+)*(${COUNT})(?:${TO}(${COUNT}))?\\s*(${DAY_UNITS})`;
|
|
18
25
|
const DURATION = new RegExp(`^${DURATION_SOURCE}$`, 'i');
|
|
19
26
|
|
|
20
|
-
const ROUTES = new Set(['vo', 'po', 'oral', 'iv', 'ev', 'intravenosa', 'im', 'intramuscular', 'sc', 'subcutanea', 'sl', 'sublingual', 'topica', 'rectal']);
|
|
27
|
+
const ROUTES = new Set(['vo', 'po', 'oral', 'iv', 'ev', 'intravenosa', 'im', 'intramuscular', 'sc', 'subcutanea', 'sl', 'sublingual', 'topica', 'topico', 'cutanea', 'transdermica', 'rectal', 'vaginal', 'nasal', 'intranasal', 'inhalada', 'inhalado', 'oftalmica', 'otica']);
|
|
21
28
|
// What a drug's name may carry that does not name it: «Ondansetrón 8 mg», «Metoclopramida gotas».
|
|
22
|
-
const NOT_A_NAME = /^(?:\d+(?:mg|ml|mcg|g|ui)?|mg|ml|mcg|g|ui|vo|iv|im|sc|sl|oral|tabletas?|capsulas?|comprimidos?|gotas|jarabe|crema|gel|unguento|solucion|suspension|sobres?|ampolletas?|ampulas?|parches?|spray|colirio)$/;
|
|
29
|
+
const NOT_A_NAME = /^(?:\d+(?:mg|ml|mcg|g|ui)?|mg|ml|mcg|g|ui|vo|iv|im|sc|sl|oral|tabletas?|tab|capsulas?|caps|comprimidos?|pastillas?|gotas|jarabe|crema|pomada|gel|unguento|locion|solucion|suspension|sobres?|ampolletas?|ampulas?|ampollas?|inyectable|inyeccion|supositorios?|ovulos?|parches?|spray|colirio)$/;
|
|
23
30
|
|
|
24
|
-
const URGENCY_WORDS = /\b(urgencias?|urgente|de inmediato|inmediatamente|emergencias?|911|lo antes posible|cuanto antes|no esperes)\b/g;
|
|
31
|
+
const URGENCY_WORDS = /\b(urgencias?|urgente|de inmediato|inmediata|inmediatamente|emergencias?|911|ambulancia|hospital|guardia|lo antes posible|cuanto antes|no esperes)\b/g;
|
|
25
32
|
// Only filler may sit between: «no necesitas ir a urgencias» calms, «no es normal, ve a urgencias» does not.
|
|
26
|
-
const CALMING_BEFORE = /\b(?:no\s+(?:es|son|parece|hay|hace\s+falta|necesitas?|requiere|requieres|tienes\s+(?:que|por\s+que))|sin\s+necesidad\s+de)(?:\s+(?:ir|acudir|a|al|una|un|de|la|que))*\s*$/;
|
|
33
|
+
const CALMING_BEFORE = /\b(?:no\s+(?:es|son|parece|hay|hace\s+falta|necesitas?|requiere|requieres|tienes\s+(?:que|por\s+que))|sin\s+necesidad\s+de)(?:\s+(?:necesario|ir|acudir|a|al|una|un|de|la|que))*\s*$/;
|
|
27
34
|
|
|
28
35
|
const folded = (text) => foldAccents(text).toLowerCase();
|
|
29
36
|
|
|
@@ -36,7 +43,7 @@ const drugNameOf = (text) => normalizeForAnchor(text).split(' ').filter((word) =
|
|
|
36
43
|
|
|
37
44
|
// Null for a range or an unknown count: the doctor settles those.
|
|
38
45
|
function durationDays(phrase) {
|
|
39
|
-
const match = String(phrase ?? '').trim().match(DURATION);
|
|
46
|
+
const match = folded(String(phrase ?? '')).trim().match(DURATION);
|
|
40
47
|
if (!match || match[2]) return null;
|
|
41
48
|
const count = countOf(match[1]);
|
|
42
49
|
return count ? count * daysPer(match[3]) : null;
|
|
@@ -56,16 +63,22 @@ function dosingTextOf(text) {
|
|
|
56
63
|
.replace(/\b[1-9]\d{0,2}(?:,\d{3})+\b/g, (thousands) => thousands.replace(/,/g, ''))
|
|
57
64
|
.replace(/(\d),(\d)/g, '$1.$2')
|
|
58
65
|
.replace(NUMBER_WORD, (word) => String(countOf(word)))
|
|
66
|
+
.replace(/(\d+(?:\.\d+)?)\s*\((\d+(?:\.\d+)?)\)/g, (written, number, again) => (number === again ? number : written))
|
|
67
|
+
.replace(/(?<![\d/])([1-3])\/([2-4])(?![\d/])/g, (written, top, bottom) => (Number(top) < Number(bottom) ? String(Math.round((top / bottom) * 1000) / 1000) : written))
|
|
68
|
+
.replace(/\b(?:media|medio)\s+(?=(?:tabletas?|capsulas?|comprimidos?|pastillas?|sobres?|ampolletas?|cucharadas?|cucharaditas?|horas?)\b)/g, '0.5 ')
|
|
69
|
+
.replace(/\bcada\s+(\d+(?:\.\d+)?)\s*min(?:utos?)?\b/g, (_, minutes) => `cada ${Math.round((minutes / 60) * 1000) / 1000} horas`)
|
|
59
70
|
.replace(/\bc\/\s*(\d+)\s*(?:h|hs|hrs?|horas?)\b/g, 'cada $1 horas')
|
|
60
71
|
.replace(new RegExp(`\\b(\\d+)(?:${TO}(\\d+))?\\s+ve(?:z|ces)\\s+(?:al|por|cada)\\s+dia\\b`, 'g'), TIMES_A_DAY)
|
|
72
|
+
.replace(/\bcada\s+hora\s+y\s+media\b/g, 'cada 1.5 horas')
|
|
73
|
+
.replace(/\b(\d+)\s+(dias?|horas?)\s+y\s+medi[oa]\b/g, (_, count, unit) => `${Number(count) + 0.5} ${unit}`)
|
|
61
74
|
.replace(/\bcada\s+hora\b/g, 'cada 1 horas')
|
|
62
75
|
.replace(/\bcada\s+dia\b/g, 'cada 24 horas')
|
|
63
|
-
.replace(/\b(?:por|durante|x)\s+(?:(?:unos|unas|los|las|proximos|otros)\s+)
|
|
76
|
+
.replace(/\b(?:(?:por|durante|x)\s+(?:(?:unos|unas|los|las|proximos|otros)\s+)*|(?:los|las)\s+proxim[oa]s\s+)(?=\d)/g, 'por ')
|
|
64
77
|
.replace(IN_DAYS, DAYS_IN_UNIT)
|
|
65
78
|
.replace(/\s+/g, ' ');
|
|
66
79
|
}
|
|
67
80
|
|
|
68
|
-
const RANGE = `(\\d+)(?:${TO}(\\d+))?`;
|
|
81
|
+
const RANGE = `(\\d+(?:\\.\\d+)?)(?:${TO}(\\d+(?:\\.\\d+)?))?`;
|
|
69
82
|
const HOURS = new RegExp(`cada\\s+${RANGE}\\s*h(?:s|rs?|oras?)?\\b`, 'g');
|
|
70
83
|
const DAYS = new RegExp(`por\\s+${RANGE}\\s+dias?\\b`, 'g');
|
|
71
84
|
const AMOUNTS = /\b(\d+(?:\.\d+)?)\s*(microgramos?|miligramos?|gramos?|mcg|µg|ug|mg|gr?|ml|ui)(?![a-z])/g;
|
|
@@ -88,6 +101,22 @@ function dosingFactsOf(text) {
|
|
|
88
101
|
return { hours: valuesIn(dosing, HOURS), days: valuesIn(dosing, DAYS), amounts };
|
|
89
102
|
}
|
|
90
103
|
|
|
104
|
+
// List markers («1.», «2)») number lines, not doses.
|
|
105
|
+
const LIST_MARKER = /(^|\n)[ \t]*\d+[.)][ \t]+|(?<!\([^)\n]*)(^|\s)\d+\)[ \t]+/g;
|
|
106
|
+
// Clock times, dates, phone numbers and temperatures are not doses.
|
|
107
|
+
const NOT_DOSING = [/\b\d{1,2}:\d{2}\b/g, /\b\d{1,2}\/\d{1,2}(?:\/\d{2,4})?\b(?!\s*(?:tabletas?|capsulas?|comprimidos?|pastillas?|sobres?|ampolletas?|cucharadas?|cucharaditas?|gotas|ml|mg))/g, /\b(?=(?:\d[ -]?){8,})\d{2,4}(?:[ -]?\d{2,4}){2,}\b/g, /\b\d+(?:\.\d+)?\s*(?:°\s*c?|grados)/g, /\b(?:fiebre|temperatura)\s+(?:(?:de|es|sea|esta|mayor|menor|a|mas|que|pasa|sube|llega|arriba|encima|del|por)\s+)*\d+(?:\.\d+)?/g];
|
|
108
|
+
const NUMBER = /\d+(?:\.\d+)?/g;
|
|
109
|
+
const numbersOf = (text) => new Set([...text.matchAll(NUMBER)].map(([number]) => Number(number)));
|
|
110
|
+
|
|
111
|
+
// Every number in the text, after the same spelling as dosingFactsOf.
|
|
112
|
+
const allNumbersOf = (text) => numbersOf(dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2')));
|
|
113
|
+
|
|
114
|
+
// The numbers left once the hours, days and amounts dosingFactsOf reads are taken out: what no pattern explains.
|
|
115
|
+
function looseNumbersOf(text) {
|
|
116
|
+
const dosing = dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2'));
|
|
117
|
+
return numbersOf([...NOT_DOSING, HOURS, DAYS, AMOUNTS, URGENCY_WORDS].reduce((rest, pattern) => rest.replace(pattern, ' '), dosing));
|
|
118
|
+
}
|
|
119
|
+
|
|
91
120
|
function urgencyWordsIn(text) {
|
|
92
121
|
const plain = folded(text);
|
|
93
122
|
return new Set([...plain.matchAll(URGENCY_WORDS)]
|
|
@@ -95,4 +124,4 @@ function urgencyWordsIn(text) {
|
|
|
95
124
|
.map((match) => match[1]));
|
|
96
125
|
}
|
|
97
126
|
|
|
98
|
-
module.exports = { DURATION_SOURCE, dosingFactsOf, drugNameOf, durationDays, isRouteOnly, urgencyWordsIn };
|
|
127
|
+
module.exports = { DURATION_SOURCE, allNumbersOf, dosingFactsOf, drugNameOf, durationDays, isRouteOnly, looseNumbersOf, urgencyWordsIn };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { DEFAULT_FOLLOW_UP_HOURS, planInstructions, plannedTextOf } = require('../helpers/doctorPlanHelper');
|
|
2
|
-
const { dosingFactsOf, urgencyWordsIn } = require('../helpers/planTextHelper');
|
|
2
|
+
const { allNumbersOf, dosingFactsOf, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
|
|
3
3
|
const { httpError } = require('../../utils/httpErrorUtils');
|
|
4
4
|
const { oneLineOf } = require('../../utils/coercionUtils');
|
|
5
5
|
const { PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
|
|
@@ -97,6 +97,7 @@ function approvedInstructions(plan, edited) {
|
|
|
97
97
|
}
|
|
98
98
|
|
|
99
99
|
const strays = (said, planned) => [...said].filter((value) => !planned.has(value));
|
|
100
|
+
const everyOf = (hours) => (hours < 1 ? `cada ${Math.round(hours * 60)} minutos` : `cada ${hours} horas`);
|
|
100
101
|
|
|
101
102
|
function replyIssues(plan, reply) {
|
|
102
103
|
if (!oneLineOf(reply)) return ['no se pudo leer el mensaje enviado'];
|
|
@@ -104,11 +105,13 @@ function replyIssues(plan, reply) {
|
|
|
104
105
|
const said = dosingFactsOf(reply);
|
|
105
106
|
const allowed = dosingFactsOf(planned);
|
|
106
107
|
const issues = plan.items.filter((item) => !isDrugNamed(reply, item.drug)).map((item) => `no menciona ${item.drug}`);
|
|
107
|
-
for (const hours of strays(said.hours, allowed.hours)) issues.push(`dice
|
|
108
|
+
for (const hours of strays(said.hours, allowed.hours)) issues.push(`dice «${everyOf(hours)}», que no está en el plan`);
|
|
108
109
|
for (const days of strays(said.days, allowed.days)) issues.push(`dice «por ${days} días», que no está en el plan`);
|
|
109
110
|
for (const [amount, written] of said.amounts) {
|
|
110
111
|
if (!allowed.amounts.has(amount)) issues.push(`dice «${written}», que no está en el plan`);
|
|
111
112
|
}
|
|
113
|
+
// A number no pattern reads («tómalo 5 días», «a las 10») still flags when the plan never names it.
|
|
114
|
+
for (const number of strays(looseNumbersOf(reply), allNumbersOf(planned))) issues.push(`menciona «${number}», que no está en el plan`);
|
|
112
115
|
for (const name of unplannedDrugsIn(reply, planned)) issues.push(`menciona ${name}, que el médico no indicó`);
|
|
113
116
|
for (const word of strays(urgencyWordsIn(reply), urgencyWordsIn(planned))) issues.push(`usa «${word}», que el médico no indicó`);
|
|
114
117
|
return issues;
|
|
@@ -31,7 +31,7 @@ const respondWithError = (res, error, action, context) => {
|
|
|
31
31
|
stack: redactDirectIdentifiers(String(error.stack || '')),
|
|
32
32
|
...context,
|
|
33
33
|
});
|
|
34
|
-
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
34
|
+
res.status(error.statusCode || 500).json({ success: false, error: error.message, ...(error.errorCode && { errorCode: error.errorCode }) });
|
|
35
35
|
};
|
|
36
36
|
|
|
37
37
|
const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
|
|
@@ -108,6 +108,10 @@ const SAME_URGENCY = 'The review is already at that urgency';
|
|
|
108
108
|
const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
|
|
109
109
|
const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
|
|
110
110
|
const APPROVALS = ['approved', 'edited_approved', 'plan_approved'];
|
|
111
|
+
// The interface offers a resend only for SEND_NOT_SENT; SEND_UNCONFIRMED may have reached the patient.
|
|
112
|
+
const SEND_NOT_SENT = 'send_not_sent';
|
|
113
|
+
const SEND_UNCONFIRMED = 'send_unconfirmed';
|
|
114
|
+
const withSendCode = (error, errorCode) => (error instanceof Error && !Object.isFrozen(error) && !error.errorCode ? Object.assign(error, { errorCode }) : error);
|
|
111
115
|
const STALE_DRAFT = 'New information reached the review after this draft; wait for the updated draft before approving';
|
|
112
116
|
const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
|
|
113
117
|
const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
|
|
@@ -2086,7 +2090,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2086
2090
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
2087
2091
|
});
|
|
2088
2092
|
});
|
|
2089
|
-
throw error;
|
|
2093
|
+
throw withSendCode(error, SEND_NOT_SENT);
|
|
2090
2094
|
}
|
|
2091
2095
|
|
|
2092
2096
|
let result;
|
|
@@ -2094,7 +2098,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2094
2098
|
result = await getMessaging().sendMessage(message);
|
|
2095
2099
|
const alreadyDelivered = result?.status === 'duplicate_suppressed' && result?.completed === true;
|
|
2096
2100
|
if (!result?.success && !alreadyDelivered) {
|
|
2097
|
-
throw httpError(502, 'The indications could not be sent to the patient');
|
|
2101
|
+
throw httpError(502, 'The indications could not be sent to the patient', SEND_NOT_SENT);
|
|
2098
2102
|
}
|
|
2099
2103
|
} catch (error) {
|
|
2100
2104
|
if (!sendDidNotHappen(error)) {
|
|
@@ -2102,14 +2106,14 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2102
2106
|
escalationReviewId: String(claimed._id),
|
|
2103
2107
|
error: redactedError(error),
|
|
2104
2108
|
});
|
|
2105
|
-
throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
|
|
2109
|
+
throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2106
2110
|
}
|
|
2107
2111
|
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
2108
2112
|
logger.error('[EscalationReview] The claim was not released after a confirmed non-send', {
|
|
2109
2113
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
2110
2114
|
});
|
|
2111
2115
|
});
|
|
2112
|
-
throw error;
|
|
2116
|
+
throw withSendCode(error, SEND_NOT_SENT);
|
|
2113
2117
|
}
|
|
2114
2118
|
|
|
2115
2119
|
const deferred = result.deferred === true;
|
|
@@ -2125,7 +2129,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2125
2129
|
const recordUpdate = withCaseMirror(claimed, {
|
|
2126
2130
|
$set: { patientDelivery: delivery },
|
|
2127
2131
|
}, { recommendation: finalText });
|
|
2128
|
-
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
|
|
2132
|
+
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status).catch((error) => { throw withSendCode(error, SEND_UNCONFIRMED); });
|
|
2129
2133
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
2130
2134
|
return syncCase(review, operator, requestId);
|
|
2131
2135
|
}
|
|
@@ -2193,22 +2197,22 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
|
|
|
2193
2197
|
logger.error('[EscalationReview] The assistant turn failed after the instructions were stored; leaving the review in sending', {
|
|
2194
2198
|
escalationReviewId: String(reviewId),
|
|
2195
2199
|
});
|
|
2196
|
-
throw httpError(502, 'The assistant turn failed after the instructions were stored; check the chat before sending again');
|
|
2200
|
+
throw httpError(502, 'The assistant turn failed after the instructions were stored; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2197
2201
|
}
|
|
2198
2202
|
await release();
|
|
2199
|
-
if (error?.cause instanceof DrainingError) throw httpError(503, 'The server is restarting; send the plan again in a minute');
|
|
2200
|
-
throw error;
|
|
2203
|
+
if (error?.cause instanceof DrainingError) throw httpError(503, 'The server is restarting; send the plan again in a minute', SEND_NOT_SENT);
|
|
2204
|
+
throw withSendCode(error, SEND_NOT_SENT);
|
|
2201
2205
|
}
|
|
2202
2206
|
|
|
2203
2207
|
const outcome = replyOutcome(delivery, sendThrew);
|
|
2204
2208
|
if (outcome === 'not_sent') {
|
|
2205
2209
|
await release();
|
|
2206
|
-
throw httpError(502, 'The assistant did not send a message to the patient; check the chat and send the plan again');
|
|
2210
|
+
throw httpError(502, 'The assistant did not send a message to the patient; check the chat and send the plan again', SEND_NOT_SENT);
|
|
2207
2211
|
}
|
|
2208
2212
|
if (outcome === 'unknown') {
|
|
2209
2213
|
logger.error('[EscalationReview] The assistant reply could not be confirmed; leaving the review in sending', { escalationReviewId: String(reviewId) });
|
|
2210
2214
|
await notifyPlanIssues(claimed, ['no se pudo confirmar que el mensaje salió; el caso sigue en «enviando»']);
|
|
2211
|
-
throw httpError(502, 'The assistant reply could not be confirmed; check the chat before sending again');
|
|
2215
|
+
throw httpError(502, 'The assistant reply could not be confirmed; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2212
2216
|
}
|
|
2213
2217
|
|
|
2214
2218
|
// A queued reply goes out once the patient answers the recovery template; the receta, a template itself, goes now.
|
|
@@ -2223,7 +2227,7 @@ async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan,
|
|
|
2223
2227
|
};
|
|
2224
2228
|
const recordUpdate = withCaseMirror(claimed, { $set: { patientDelivery: record } }, { recommendation: planSummary(plan) });
|
|
2225
2229
|
const status = queued ? 'indications_queued' : 'indications_sent';
|
|
2226
|
-
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
|
|
2230
|
+
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status).catch((error) => { throw withSendCode(error, SEND_UNCONFIRMED); });
|
|
2227
2231
|
await audit(review, operator, requestId, {
|
|
2228
2232
|
action: status, decisionNumber, transport: 'assistant', checks: issues.length, ...(prescriberEmail && { prescription: prescriptionFailed ? 'failed' : 'created' }),
|
|
2229
2233
|
});
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
|
|
1
|
+
const httpError = (statusCode, message, errorCode) => Object.assign(new Error(message), { statusCode }, errorCode && { errorCode });
|
|
2
2
|
|
|
3
3
|
const requiredText = (value, name) => {
|
|
4
4
|
const text = String(value ?? '').trim();
|