@peopl-health/nexus 6.4.0-dev.18981 → 6.4.0-dev.19006
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 +97 -0
- package/lib/clinical/helpers/planTextHelper.js +114 -0
- package/lib/clinical/protocols/treatmentFormulary.js +19 -1
- package/lib/clinical/services/doctorPlanService.js +120 -0
- package/lib/clinical/services/escalationDraftService.js +4 -1
- package/lib/clinical/services/treatmentProposalService.js +26 -4
- package/lib/clinical/tools/getPatientRiskAssessmentTool.js +1 -1
- package/lib/clinical/tools/getRouterContextBundleTool.js +1 -1
- package/lib/controllers/escalationReviewController.js +20 -3
- package/lib/controllers/prescriptionController.js +4 -28
- package/lib/index.d.ts +1 -1
- package/lib/models/escalationReviewModel.js +38 -2
- package/lib/routes/index.js +2 -0
- package/lib/services/assistantMessageService.js +12 -6
- package/lib/services/escalationReviewService.js +191 -12
- package/lib/services/prescriptionService.js +30 -0
- package/lib/utils/httpErrorUtils.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
const { oneLineOf } = require('../../utils/coercionUtils');
|
|
2
|
+
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
3
|
+
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
4
|
+
|
|
5
|
+
const DEFAULT_FOLLOW_UP_HOURS = Object.freeze({ check_in: 24, vigilancia: 48 });
|
|
6
|
+
|
|
7
|
+
const needsPrescriber = (plan) => plan.items.length > 0 || plan.studies.length > 0;
|
|
8
|
+
|
|
9
|
+
const daysText = (days) => (days === 1 ? '1 día' : `${days} días`);
|
|
10
|
+
const itemLine = (item) => `${[item.drug, item.strength].filter(Boolean).join(' ')}: ${item.dose} ${item.frequency} por ${daysText(item.days)}.`;
|
|
11
|
+
const studyLine = (study) => `${study.name}${study.instructions ? `: ${study.instructions}` : ''}.`;
|
|
12
|
+
const PRESCRIPTION_LINE = 'Justo después de tu mensaje le llega aparte la receta del médico en PDF; dile que la va a recibir.';
|
|
13
|
+
|
|
14
|
+
const FOLLOW_UP_LINES = {
|
|
15
|
+
check_in: (hours) => `Seguimiento: le escribiremos en unas ${hours} horas para ver cómo va.`,
|
|
16
|
+
vigilancia: (hours) => `Seguimiento: queda en vigilancia las próximas ${hours} horas; le escribiremos para ver cómo va.`,
|
|
17
|
+
};
|
|
18
|
+
const followUpLineOf = (plan) => FOLLOW_UP_LINES[plan.followUp?.kind]?.(plan.followUp.hours) ?? null;
|
|
19
|
+
|
|
20
|
+
function planInstructions(plan) {
|
|
21
|
+
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.'];
|
|
22
|
+
if (plan.items.length) {
|
|
23
|
+
lines.push('Medicamentos:', ...plan.items.map((item) => `- ${itemLine(item)}`));
|
|
24
|
+
}
|
|
25
|
+
if (plan.studies.length) {
|
|
26
|
+
lines.push('Estudios:', ...plan.studies.map((study) => `- ${studyLine(study)}`));
|
|
27
|
+
}
|
|
28
|
+
if (plan.homeCare.length) lines.push('Cuidados en casa:', ...plan.homeCare.map((entry) => `- ${entry}`));
|
|
29
|
+
if (plan.note) lines.push(`Nota del médico: «${plan.note}».`);
|
|
30
|
+
const followUp = followUpLineOf(plan);
|
|
31
|
+
if (followUp) lines.push(followUp);
|
|
32
|
+
if (needsPrescriber(plan)) lines.push(PRESCRIPTION_LINE);
|
|
33
|
+
return lines.join('\n');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// An edit can drop or reword the receta line; the PDF goes out anyway, so the assistant is still told.
|
|
37
|
+
function assistantInstructionsOf(plan) {
|
|
38
|
+
if (!needsPrescriber(plan) || normalizeForAnchor(plan.instructions).includes(normalizeForAnchor(PRESCRIPTION_LINE))) return plan.instructions;
|
|
39
|
+
return `${plan.instructions}\n${PRESCRIPTION_LINE}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function planSummary(plan) {
|
|
43
|
+
const lines = [...plan.items.map(itemLine), ...plan.studies.map((study) => `Estudio: ${studyLine(study)}`)];
|
|
44
|
+
if (plan.homeCare.length) lines.push(`Cuidados en casa: ${plan.homeCare.join('; ')}.`);
|
|
45
|
+
if (plan.note) lines.push(`Nota: ${plan.note}`);
|
|
46
|
+
return lines.join('\n');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function prescriptionText(plan) {
|
|
50
|
+
const lines = plan.items.map(itemLine);
|
|
51
|
+
if (plan.studies.length) lines.push('Estudios:', ...plan.studies.map(studyLine));
|
|
52
|
+
return lines.join('\n');
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// The formulary's own fields; a drug it no longer lists keeps its old text as the dose, for the doctor to split.
|
|
56
|
+
function dosingOf(item, formularyKey) {
|
|
57
|
+
const entry = formularyFor(formularyKey);
|
|
58
|
+
const dosing = entry && findDrug(entry, item)?.dosing;
|
|
59
|
+
if (!dosing) return { dose: oneLineOf(item.instructions) || null, frequency: null, days: null, note: null };
|
|
60
|
+
return { dose: dosing.dose ?? null, frequency: dosing.frequency ?? null, days: dosing.days ?? null, note: dosing.note ?? null };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// What the formulary adds after the dosing («además, valoración por oftalmología») goes to the note.
|
|
64
|
+
function proposedPlanOf(draft) {
|
|
65
|
+
const seen = new Set();
|
|
66
|
+
const rests = [];
|
|
67
|
+
const items = (draft?.symptoms ?? [])
|
|
68
|
+
.filter((entry) => entry?.proposal?.confirmed)
|
|
69
|
+
.flatMap((entry) => (entry.proposal.items ?? []).map((item) => ({ item, formularyKey: entry.proposal.formularyKey })))
|
|
70
|
+
.filter(({ item }) => !seen.has(normalizeForAnchor(item.drug)) && seen.add(normalizeForAnchor(item.drug)))
|
|
71
|
+
.map(({ item, formularyKey }) => {
|
|
72
|
+
const { note, ...dosing } = dosingOf(item, formularyKey);
|
|
73
|
+
if (note) rests.push(`${item.drug}: ${note}`);
|
|
74
|
+
return { drug: item.drug, strength: item.strength ?? null, ...dosing, position: item.position ?? null, reason: null, formularyKey };
|
|
75
|
+
});
|
|
76
|
+
return { items, studies: [], homeCare: [], note: rests.join('. ') || null, followUp: { kind: 'check_in', hours: DEFAULT_FOLLOW_UP_HOURS.check_in } };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// The note and home care count, so what the doctor wrote anywhere in the plan is never flagged.
|
|
80
|
+
const plannedTextOf = (plan) => [
|
|
81
|
+
...plan.items.flatMap((item) => [item.drug, item.strength, item.dose, item.frequency, item.days && `por ${item.days} dias`]),
|
|
82
|
+
...plan.studies.flatMap((study) => [study.name, study.instructions]),
|
|
83
|
+
...plan.homeCare,
|
|
84
|
+
plan.note,
|
|
85
|
+
followUpLineOf(plan),
|
|
86
|
+
].filter(Boolean).join('\n');
|
|
87
|
+
|
|
88
|
+
module.exports = {
|
|
89
|
+
DEFAULT_FOLLOW_UP_HOURS,
|
|
90
|
+
assistantInstructionsOf,
|
|
91
|
+
needsPrescriber,
|
|
92
|
+
planInstructions,
|
|
93
|
+
planSummary,
|
|
94
|
+
plannedTextOf,
|
|
95
|
+
prescriptionText,
|
|
96
|
+
proposedPlanOf,
|
|
97
|
+
};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
const { foldAccents } = require('../../utils/formatUtils');
|
|
2
|
+
const { normalizeForAnchor } = require('../../utils/textMatchUtils');
|
|
3
|
+
|
|
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
|
+
]));
|
|
16
|
+
const WORDS = Object.keys(NUMBER_WORDS).sort((a, b) => b.length - a.length).join('|');
|
|
17
|
+
// «y» is left out: «treinta y cinco» is one number, not a range.
|
|
18
|
+
const TO = '\\s*(?:a|-|o|u)\\s*';
|
|
19
|
+
const DAYS_PER = Object.freeze({ d: 1, dia: 1, dias: 1, semana: 7, semanas: 7, mes: 30, meses: 30 });
|
|
20
|
+
|
|
21
|
+
const UNIT_SCALE = Object.freeze({
|
|
22
|
+
microgramo: ['mg', 0.001], microgramos: ['mg', 0.001], mcg: ['mg', 0.001], µg: ['mg', 0.001], ug: ['mg', 0.001],
|
|
23
|
+
miligramo: ['mg', 1], miligramos: ['mg', 1], mg: ['mg', 1],
|
|
24
|
+
gramo: ['mg', 1000], gramos: ['mg', 1000], g: ['mg', 1000], gr: ['mg', 1000],
|
|
25
|
+
ml: ['ml', 1], ui: ['ui', 1],
|
|
26
|
+
});
|
|
27
|
+
const UNITS_SOURCE = Object.keys(UNIT_SCALE).sort((a, b) => b.length - a.length).join('|');
|
|
28
|
+
// Forms a dose is counted in («media tableta», «1/2 tableta»), then forms that only name the preparation.
|
|
29
|
+
const COUNTED_FORMS = 'tabletas?|tab|capsulas?|caps|comprimidos?|pastillas?|sobres?|ampolletas?|ampulas?|ampollas?|cucharadas?|cucharaditas?|gotas|supositorios?|ovulos?|parches?';
|
|
30
|
+
const OTHER_FORMS = 'jarabe|crema|pomada|gel|unguento|locion|solucion|suspension|inyectable|inyeccion|spray|colirio';
|
|
31
|
+
// What a drug's name may carry that does not name it: «Ondansetrón 8 mg», «Metoclopramida gotas»; a spelled-out route («transdérmica») stays.
|
|
32
|
+
const NOT_A_NAME = new RegExp(`^(?:\\d+(?:${UNITS_SOURCE})?|${UNITS_SOURCE}|vo|iv|im|sc|sl|oral|${COUNTED_FORMS}|${OTHER_FORMS})$`);
|
|
33
|
+
|
|
34
|
+
const URGENCY_WORDS = /\b(urgencias?|urgente|de inmediato|inmediata|inmediatamente|emergencias?|911|ambulancia|hospital|guardia|lo antes posible|cuanto antes|no esperes)\b/g;
|
|
35
|
+
// Only filler may sit between: «no necesitas ir a urgencias» calms, «no es normal, ve a urgencias» does not.
|
|
36
|
+
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*$/;
|
|
37
|
+
|
|
38
|
+
const folded = (text) => foldAccents(text).toLowerCase();
|
|
39
|
+
|
|
40
|
+
const countOf = (word) => NUMBER_WORDS[folded(word).replace(/\s+/g, ' ')];
|
|
41
|
+
const daysPer = (unit) => DAYS_PER[folded(unit)];
|
|
42
|
+
|
|
43
|
+
const drugNameOf = (text) => normalizeForAnchor(text).split(' ').filter((word) => word && !NOT_A_NAME.test(word)).join(' ');
|
|
44
|
+
|
|
45
|
+
const NUMBER_WORD = new RegExp(`\\b(${WORDS})\\b`, 'g');
|
|
46
|
+
const IN_DAYS = new RegExp(`\\b(\\d+)(?:${TO}(\\d+))?\\s*(semanas?|mes(?:es)?|d)\\b`, 'g');
|
|
47
|
+
const DAYS_IN_UNIT = (_, from, to, unit) => [from, to].filter(Boolean).map((value) => value * daysPer(unit)).join(' a ').concat(' dias');
|
|
48
|
+
const TIMES_A_DAY = (written, ...counts) => {
|
|
49
|
+
const times = counts.slice(0, 2).filter(Boolean).map(Number);
|
|
50
|
+
return times.every((count) => count > 0 && 24 % count === 0) ? times.map((count) => `cada ${24 / count} horas`).join(' o ') : written;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// A dot stays decimal, as written in Mexico.
|
|
54
|
+
function dosingTextOf(text) {
|
|
55
|
+
return folded(text)
|
|
56
|
+
.replace(/\b[1-9]\d{0,2}(?:,\d{3})+\b/g, (thousands) => thousands.replace(/,/g, ''))
|
|
57
|
+
.replace(/(\d),(\d)/g, '$1.$2')
|
|
58
|
+
.replace(NUMBER_WORD, (word) => String(countOf(word)))
|
|
59
|
+
.replace(/(\d+(?:\.\d+)?)\s*\((\d+(?:\.\d+)?)\)/g, (written, number, again) => (number === again ? number : written))
|
|
60
|
+
.replace(/(?<![\d/])([1-3])\/([2-4])(?![\d/])/g, (written, top, bottom) => (Number(top) < Number(bottom) ? String(Math.round((top / bottom) * 1000) / 1000) : written))
|
|
61
|
+
.replace(new RegExp(`\\b(?:media|medio)\\s+(?=(?:${COUNTED_FORMS}|horas?)\\b)`, 'g'), '0.5 ')
|
|
62
|
+
.replace(/\bcada\s+(\d+(?:\.\d+)?)\s*min(?:utos?)?\b/g, (_, minutes) => `cada ${Math.round((minutes / 60) * 1000) / 1000} horas`)
|
|
63
|
+
.replace(/\bc\/\s*(\d+)\s*(?:h|hs|hrs?|horas?)\b/g, 'cada $1 horas')
|
|
64
|
+
.replace(new RegExp(`\\b(\\d+)(?:${TO}(\\d+))?\\s+ve(?:z|ces)\\s+(?:al|por|cada)\\s+dia\\b`, 'g'), TIMES_A_DAY)
|
|
65
|
+
.replace(/\bcada\s+hora\s+y\s+media\b/g, 'cada 1.5 horas')
|
|
66
|
+
.replace(/\b(\d+)\s+(dias?|horas?)\s+y\s+medi[oa]\b/g, (_, count, unit) => `${Number(count) + 0.5} ${unit}`)
|
|
67
|
+
.replace(/\bcada\s+hora\b/g, 'cada 1 horas')
|
|
68
|
+
.replace(/\bcada\s+dia\b/g, 'cada 24 horas')
|
|
69
|
+
.replace(/\b(?:(?:por|durante|x)\s+(?:(?:unos|unas|los|las|proximos|otros)\s+)*|(?:los|las)\s+proxim[oa]s\s+)(?=\d)/g, 'por ')
|
|
70
|
+
.replace(IN_DAYS, DAYS_IN_UNIT)
|
|
71
|
+
.replace(/\s+/g, ' ');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const AMOUNTS = new RegExp(`\\b(\\d+(?:\\.\\d+)?)\\s*(${UNITS_SOURCE})(?![a-z])`, 'g');
|
|
75
|
+
const RANGE = `(\\d+(?:\\.\\d+)?)(?:${TO}(\\d+(?:\\.\\d+)?))?`;
|
|
76
|
+
const HOURS = new RegExp(`cada\\s+${RANGE}\\s*h(?:s|rs?|oras?)?\\b`, 'g');
|
|
77
|
+
const DAYS = new RegExp(`por\\s+${RANGE}\\s+dias?\\b`, 'g');
|
|
78
|
+
|
|
79
|
+
const valuesIn = (text, pattern) => new Set([...text.matchAll(pattern)].flatMap((match) => [match[1], match[2]]).filter(Boolean).map(Number));
|
|
80
|
+
|
|
81
|
+
// Amounts are keyed in mg, ml or UI, so «1 g» and «1000 mg» meet.
|
|
82
|
+
function dosingFactsOf(text) {
|
|
83
|
+
const dosing = dosingTextOf(text);
|
|
84
|
+
const amounts = new Map([...dosing.matchAll(AMOUNTS)].map(([written, value, unit]) => {
|
|
85
|
+
const [base, scale] = UNIT_SCALE[unit];
|
|
86
|
+
return [`${Math.round(Number(value) * scale * 1000) / 1000} ${base}`, written];
|
|
87
|
+
}));
|
|
88
|
+
return { hours: valuesIn(dosing, HOURS), days: valuesIn(dosing, DAYS), amounts };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// List markers («1.», «2)») number lines, not doses.
|
|
92
|
+
const LIST_MARKER = /(^|\n)[ \t]*\d+[.)][ \t]+|(?<!\([^)\n]*)(^|\s)\d+\)[ \t]+/g;
|
|
93
|
+
// Clock times, dates, phone numbers and temperatures are not doses.
|
|
94
|
+
const NOT_DOSING = [/\b\d{1,2}:\d{2}\b/g, new RegExp(`\\b\\d{1,2}\\/\\d{1,2}(?:\\/\\d{2,4})?\\b(?!\\s*(?:${COUNTED_FORMS}|${UNITS_SOURCE})\\b)`, 'g'), /\b(?=(?:\d[ -]?){8,})\d{2,4}(?:[ -]?\d{2,4}){2,}\b/g, /\b\d+(?:\.\d+)?\s*(?:°\s*c?|grados)/g, /\b(?:fiebre|temperatura)\s+(?:(?:de|es|sea|esta|mayor|menor|a|mas|que|pasa|sube|llega|arriba|encima|del|por)\s+)*\d+(?:\.\d+)?/g];
|
|
95
|
+
const NUMBER = /\d+(?:\.\d+)?/g;
|
|
96
|
+
const numbersOf = (text) => new Set([...text.matchAll(NUMBER)].map(([number]) => Number(number)));
|
|
97
|
+
|
|
98
|
+
// Every number in the text, after the same spelling as dosingFactsOf.
|
|
99
|
+
const allNumbersOf = (text) => numbersOf(dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2')));
|
|
100
|
+
|
|
101
|
+
// The numbers left once the hours, days and amounts dosingFactsOf reads are taken out: what no pattern explains.
|
|
102
|
+
function looseNumbersOf(text) {
|
|
103
|
+
const dosing = dosingTextOf(String(text ?? '').replace(LIST_MARKER, '$1$2'));
|
|
104
|
+
return numbersOf([...NOT_DOSING, HOURS, DAYS, AMOUNTS, URGENCY_WORDS].reduce((rest, pattern) => rest.replace(pattern, ' '), dosing));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function urgencyWordsIn(text) {
|
|
108
|
+
const plain = folded(text);
|
|
109
|
+
return new Set([...plain.matchAll(URGENCY_WORDS)]
|
|
110
|
+
.filter((match) => !CALMING_BEFORE.test(plain.slice(0, match.index)))
|
|
111
|
+
.map((match) => match[1]));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
module.exports = { allNumbersOf, dosingFactsOf, drugNameOf, looseNumbersOf, urgencyWordsIn };
|
|
@@ -10,6 +10,7 @@ function deepFreeze(value) {
|
|
|
10
10
|
return value;
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
+
// `dosing` splits the validated `instructions` into fields, so the doctor's plan never parses the sentence.
|
|
13
14
|
const TREATMENT_FORMULARY = deepFreeze([
|
|
14
15
|
{
|
|
15
16
|
key: 'nausea_vomito',
|
|
@@ -18,6 +19,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
18
19
|
{
|
|
19
20
|
drug: 'Ondansetrón', brand: 'AMAL', strength: '8 mg', position: '1L', tableLabel: '1L', class: 'antiemetico_5ht3',
|
|
20
21
|
instructions: '1 tableta cada 24 horas por 5 días',
|
|
22
|
+
dosing: { dose: '1 tableta', frequency: 'cada 24 horas', days: 5 },
|
|
21
23
|
contextNote: 'Náusea/vómito relacionado con QT; solo o dentro de esquema antiemético según riesgo',
|
|
22
24
|
},
|
|
23
25
|
{
|
|
@@ -44,6 +46,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
44
46
|
{
|
|
45
47
|
drug: 'Esomeprazol', strength: '40 mg', position: '1L', tableLabel: '1L', class: 'ibp',
|
|
46
48
|
instructions: '1 cápsula cada 24 horas por 5 días',
|
|
49
|
+
dosing: { dose: '1 cápsula', frequency: 'cada 24 horas', days: 5 },
|
|
47
50
|
contextNote: 'ERGE/dispepsia ácido-relacionada; escoger un solo IBP',
|
|
48
51
|
},
|
|
49
52
|
{ drug: 'Pantoprazol', strength: '20 mg', position: '1L', tableLabel: '1L', class: 'ibp', contextNote: 'Escoger un solo IBP' },
|
|
@@ -51,6 +54,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
51
54
|
{
|
|
52
55
|
drug: 'Famotidina', strength: '40 mg', position: 'ALT', tableLabel: 'ALT / 1L síntomas leves', class: 'antih2',
|
|
53
56
|
instructions: '1 tableta cada 24 horas por 5 días',
|
|
57
|
+
dosing: { dose: '1 tableta', frequency: 'cada 24 horas', days: 5 },
|
|
54
58
|
contextNote: 'ERGE intermitente/nocturna o si no se requiere IBP; alternativa si ya toma esomeprazol',
|
|
55
59
|
},
|
|
56
60
|
{ drug: 'Magaldrato/dimeticona', brand: 'RIOPAN', strength: null, position: '1L', tableLabel: '1L PRN', class: 'antiacido', contextNote: 'Alivio inmediato de pirosis/dispepsia ocasional' },
|
|
@@ -75,6 +79,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
75
79
|
{
|
|
76
80
|
drug: 'Loperamida', strength: '2 mg', position: '1L', tableLabel: '1L', class: 'antidiarreico_opioide',
|
|
77
81
|
instructions: '2 tabletas (4 mg) al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
|
|
82
|
+
dosing: { dose: '2 tabletas (4 mg) al inicio y después 1 tableta', frequency: 'cada 6 horas', note: 'máximo 8 tabletas al día' },
|
|
78
83
|
ruleOutFirst: ['causa infecciosa', 'causa obstructiva', 'intolerancia'],
|
|
79
84
|
contextNote: 'Diarrea no complicada asociada al tratamiento oncológico',
|
|
80
85
|
},
|
|
@@ -91,6 +96,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
91
96
|
{
|
|
92
97
|
drug: 'Butilhioscina/metamizol', brand: 'BUSCAPINA COMPUESTA', strength: '10/250 mg', position: 'ALT', tableLabel: 'Coadyuvante', class: 'antiespasmodico',
|
|
93
98
|
instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
|
|
99
|
+
dosing: { dose: '1 tableta', frequency: 'cada 8 a 12 horas por razón necesaria' },
|
|
94
100
|
contextNote: 'Coadyuvante para cólico, no tratamiento de la diarrea',
|
|
95
101
|
},
|
|
96
102
|
],
|
|
@@ -104,11 +110,13 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
104
110
|
{
|
|
105
111
|
drug: 'Senósidos', brand: 'SENOKOT', strength: null, position: '1L', tableLabel: '1L, especialmente estreñimiento por opioides', class: 'laxante_estimulante',
|
|
106
112
|
instructions: '2 tabletas cada noche por 5 días',
|
|
113
|
+
dosing: { dose: '2 tabletas', frequency: 'cada noche', days: 5 },
|
|
107
114
|
},
|
|
108
115
|
{ drug: 'Bisacodilo', strength: null, position: '1L', tableLabel: '1L / ALT, estimulante', class: 'laxante_estimulante' },
|
|
109
116
|
{
|
|
110
117
|
drug: 'Lactulosa', brand: 'LACTULAX', strength: null, position: '1L', tableLabel: '1L / ALT osmótica', class: 'laxante_osmotico',
|
|
111
118
|
instructions: '10 ml cada 8 horas hasta lograr evacuación, después suspender',
|
|
119
|
+
dosing: { dose: '10 ml', frequency: 'cada 8 horas hasta lograr evacuación', note: 'después suspender' },
|
|
112
120
|
},
|
|
113
121
|
{
|
|
114
122
|
drug: 'Leche de magnesia', strength: null, position: 'ALT', tableLabel: 'ALT', class: 'laxante_osmotico',
|
|
@@ -124,6 +132,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
124
132
|
{
|
|
125
133
|
drug: 'Colutorios alcalinos', strength: '½ L de agua con 1 cucharadita de sal y 2 cucharaditas de bicarbonato', position: '1L', tableLabel: '1L soporte básico', class: 'enjuague',
|
|
126
134
|
instructions: 'enjuagues y gárgaras de 1 minuto cada 6 horas por 5 días',
|
|
135
|
+
dosing: { dose: 'enjuagues y gárgaras de 1 minuto', frequency: 'cada 6 horas', days: 5 },
|
|
127
136
|
isPharmacological: false,
|
|
128
137
|
},
|
|
129
138
|
{
|
|
@@ -136,6 +145,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
136
145
|
{
|
|
137
146
|
drug: 'Dexketoprofeno', brand: 'VELIAN', strength: '25 mg/10 ml en sobres', position: 'ALT', tableLabel: 'ALT analgésica', class: 'aine',
|
|
138
147
|
instructions: '1 sobre cada 8 horas, 30 minutos antes de los alimentos, y tragar, por 7 días',
|
|
148
|
+
dosing: { dose: '1 sobre', frequency: 'cada 8 horas', days: 7, note: '30 minutos antes de los alimentos, y tragar' },
|
|
139
149
|
contextNote: `Analgésico, no tratamiento específico de mucositis; si persiste, ${MEDICAL_REVIEW}`,
|
|
140
150
|
},
|
|
141
151
|
],
|
|
@@ -155,16 +165,19 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
155
165
|
{
|
|
156
166
|
drug: 'Paracetamol', brand: 'TEMPRA / TYLENOL', strength: '500 mg', position: '1L', tableLabel: '1L dolor leve', class: 'analgesico_no_opioide',
|
|
157
167
|
instructions: 'VO cada 8 horas por razón necesaria, máximo 3 días',
|
|
168
|
+
dosing: { route: 'VO', frequency: 'cada 8 horas por razón necesaria', note: 'máximo 3 días' },
|
|
158
169
|
},
|
|
159
170
|
{
|
|
160
171
|
drug: 'Ibuprofeno', strength: '400 mg', position: '1L', tableLabel: '1L/ALT dolor inflamatorio leve', class: 'aine',
|
|
161
172
|
instructions: 'VO cada 12 horas, máximo 3 días',
|
|
173
|
+
dosing: { route: 'VO', frequency: 'cada 12 horas', note: 'máximo 3 días' },
|
|
162
174
|
avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
|
|
163
175
|
},
|
|
164
176
|
{ drug: 'Naproxeno', strength: null, position: '1L', tableLabel: '1L/ALT', class: 'aine', avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'] },
|
|
165
177
|
{
|
|
166
178
|
drug: 'Celecoxib', brand: 'CELEBREX', strength: '200 mg', position: 'ALT', tableLabel: 'ALT / escalamiento de AINE', class: 'aine',
|
|
167
179
|
instructions: 'VO cada 24 horas, máximo 3 días',
|
|
180
|
+
dosing: { route: 'VO', frequency: 'cada 24 horas', note: 'máximo 3 días' },
|
|
168
181
|
avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
|
|
169
182
|
},
|
|
170
183
|
{ drug: 'Dexketoprofeno', strength: null, position: 'ALT', tableLabel: 'ALT corto plazo', class: 'aine', avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'] },
|
|
@@ -232,6 +245,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
232
245
|
drug: 'Dexametasona/neomicina', strength: null, position: '1L', tableLabel: '1L gotas oftálmicas, solo con panitumumab o cetuximab', class: 'corticoide_antibiotico_oftalmico',
|
|
233
246
|
onlyWhen: ['panitumumab', 'cetuximab'],
|
|
234
247
|
instructions: '2 gotas oftálmicas cada 12 horas por 3 días; además, valoración por oftalmología',
|
|
248
|
+
dosing: { dose: '2 gotas oftálmicas', frequency: 'cada 12 horas', days: 3, note: 'además, valoración por oftalmología' },
|
|
235
249
|
},
|
|
236
250
|
],
|
|
237
251
|
},
|
|
@@ -242,10 +256,12 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
242
256
|
{
|
|
243
257
|
drug: 'Urea', brand: 'NUTRAPLUS', strength: '10%', position: '1L', tableLabel: '1L, especialmente HFS/hiperqueratosis', class: 'queratolitico',
|
|
244
258
|
instructions: 'capa fina cada 12 horas de forma continua',
|
|
259
|
+
dosing: { dose: 'capa fina', frequency: 'cada 12 horas de forma continua' },
|
|
245
260
|
},
|
|
246
261
|
{
|
|
247
262
|
drug: 'Ceramidas', brand: 'CERAVE', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente',
|
|
248
|
-
instructions: '2 a 3 veces al día de forma continua',
|
|
263
|
+
instructions: '2 a 3 veces al día de forma continua',
|
|
264
|
+
dosing: { dose: '2 a 3 veces al día de forma continua' }, isPharmacological: false,
|
|
249
265
|
},
|
|
250
266
|
{ drug: 'Emoliente', brand: 'EUCERIN', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
|
|
251
267
|
{ drug: 'Vaselina/petrolato', strength: null, position: '1L', tableLabel: '1L barrera', class: 'barrera_cutanea', isPharmacological: false },
|
|
@@ -275,6 +291,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
275
291
|
{
|
|
276
292
|
drug: 'Cetirizina', brand: 'REACTINE', strength: '10 mg', position: '1L', tableLabel: '1L antihistamínico', class: 'antihistaminico',
|
|
277
293
|
instructions: '1 tableta cada 24 horas por 7 días',
|
|
294
|
+
dosing: { dose: '1 tableta', frequency: 'cada 24 horas', days: 7 },
|
|
278
295
|
},
|
|
279
296
|
{ drug: 'Loratadina', strength: '10 mg', position: '1L', tableLabel: '1L', class: 'antihistaminico' },
|
|
280
297
|
{ drug: 'Fexofenadina', strength: '180 mg', position: '1L', tableLabel: '1L', class: 'antihistaminico' },
|
|
@@ -328,6 +345,7 @@ const TREATMENT_FORMULARY = deepFreeze([
|
|
|
328
345
|
{
|
|
329
346
|
drug: 'Melatonina', brand: 'MELATOL', strength: '3 mg', position: 'ALT', tableLabel: 'Puede probarse; sin evidencia fuerte en insomnio crónico', class: 'melatonina',
|
|
330
347
|
instructions: '1 tableta cada 24 horas por la noche por 14 días',
|
|
348
|
+
dosing: { dose: '1 tableta', frequency: 'cada 24 horas por la noche', days: 14 },
|
|
331
349
|
},
|
|
332
350
|
{ drug: 'Zolpidem', strength: '10 mg', position: 'ALT', tableLabel: 'ALT farmacológica de corto plazo, no primera intervención global', class: 'hipnotico' },
|
|
333
351
|
],
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
const { DEFAULT_FOLLOW_UP_HOURS, planInstructions, plannedTextOf } = require('../helpers/doctorPlanHelper');
|
|
2
|
+
const { allNumbersOf, dosingFactsOf, looseNumbersOf, urgencyWordsIn } = require('../helpers/planTextHelper');
|
|
3
|
+
const { httpError } = require('../../utils/httpErrorUtils');
|
|
4
|
+
const { oneLineOf } = require('../../utils/coercionUtils');
|
|
5
|
+
const { PLAN_FOLLOW_UPS } = require('../../models/escalationReviewModel');
|
|
6
|
+
const { isDrugNamed, unplannedDrugsIn } = require('./treatmentProposalService');
|
|
7
|
+
|
|
8
|
+
const FIRST_LINE = '1L';
|
|
9
|
+
const MAX_ENTRIES = 10;
|
|
10
|
+
const MAX_FIELD_LENGTH = 300;
|
|
11
|
+
const MAX_NOTE_LENGTH = 1000;
|
|
12
|
+
const MAX_INSTRUCTIONS_LENGTH = 4000;
|
|
13
|
+
const MAX_DAYS = 90;
|
|
14
|
+
const MAX_FOLLOW_UP_HOURS = 168;
|
|
15
|
+
|
|
16
|
+
const textOf = (value, name, max = MAX_FIELD_LENGTH) => {
|
|
17
|
+
if (value != null && typeof value !== 'string') throw httpError(400, `${name} must be text`);
|
|
18
|
+
const text = oneLineOf(value);
|
|
19
|
+
if (text.length > max) throw httpError(400, `${name} exceeds ${max} characters`);
|
|
20
|
+
return text || null;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const neededText = (value, name) => {
|
|
24
|
+
const text = textOf(value, name);
|
|
25
|
+
if (!text) throw httpError(400, `${name} is required`);
|
|
26
|
+
return text;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const isPlainObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
30
|
+
|
|
31
|
+
// Only a number or a string of digits: `true`, `[5]` and `'1e1'` are not days.
|
|
32
|
+
const wholeNumber = (value, name, max) => {
|
|
33
|
+
const number = typeof value === 'number' || (typeof value === 'string' && /^\d+$/.test(value.trim())) ? Number(value) : NaN;
|
|
34
|
+
if (!Number.isInteger(number) || number < 1 || number > max) throw httpError(400, `${name} must be a whole number from 1 to ${max}`);
|
|
35
|
+
return number;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const listOf = (value, name) => {
|
|
39
|
+
if (value == null) return [];
|
|
40
|
+
if (!Array.isArray(value)) throw httpError(400, `${name} must be a list`);
|
|
41
|
+
if (value.length > MAX_ENTRIES) throw httpError(400, `${name} allows at most ${MAX_ENTRIES} entries`);
|
|
42
|
+
return value;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
function itemOf(item, index) {
|
|
46
|
+
const name = `plan.items[${index}]`;
|
|
47
|
+
const position = textOf(item?.position, `${name}.position`)?.toUpperCase() ?? null;
|
|
48
|
+
const reason = textOf(item?.reason, `${name}.reason`);
|
|
49
|
+
if (position && position !== FIRST_LINE && !reason) throw httpError(400, `${name}.reason is required for a drug that is not first line`);
|
|
50
|
+
return {
|
|
51
|
+
drug: neededText(item?.drug, `${name}.drug`),
|
|
52
|
+
strength: textOf(item?.strength, `${name}.strength`),
|
|
53
|
+
dose: neededText(item?.dose, `${name}.dose`),
|
|
54
|
+
frequency: neededText(item?.frequency, `${name}.frequency`),
|
|
55
|
+
days: wholeNumber(item?.days, `${name}.days`, MAX_DAYS),
|
|
56
|
+
position,
|
|
57
|
+
reason,
|
|
58
|
+
formularyKey: textOf(item?.formularyKey, `${name}.formularyKey`),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function followUpOf(value) {
|
|
63
|
+
if (value != null && !isPlainObject(value)) throw httpError(400, 'plan.followUp must be an object with a kind');
|
|
64
|
+
const kind = value?.kind ?? 'none';
|
|
65
|
+
if (!PLAN_FOLLOW_UPS.includes(kind)) throw httpError(400, `plan.followUp.kind must be one of: ${PLAN_FOLLOW_UPS.join(', ')}`);
|
|
66
|
+
if (kind === 'none') return { kind, hours: null };
|
|
67
|
+
return { kind, hours: wholeNumber(value?.hours ?? DEFAULT_FOLLOW_UP_HOURS[kind], 'plan.followUp.hours', MAX_FOLLOW_UP_HOURS) };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function planOf(input) {
|
|
71
|
+
if (!isPlainObject(input)) throw httpError(400, 'plan is required');
|
|
72
|
+
const plan = {
|
|
73
|
+
items: listOf(input.items, 'plan.items').map((item, index) => {
|
|
74
|
+
if (!isPlainObject(item)) throw httpError(400, `plan.items[${index}] must be an object`);
|
|
75
|
+
return itemOf(item, index);
|
|
76
|
+
}),
|
|
77
|
+
studies: listOf(input.studies, 'plan.studies').map((study, index) => ({
|
|
78
|
+
name: neededText(study?.name, `plan.studies[${index}].name`),
|
|
79
|
+
instructions: textOf(study?.instructions, `plan.studies[${index}].instructions`),
|
|
80
|
+
})),
|
|
81
|
+
homeCare: listOf(input.homeCare, 'plan.homeCare').map((entry, index) => neededText(entry, `plan.homeCare[${index}]`)),
|
|
82
|
+
note: textOf(input.note, 'plan.note', MAX_NOTE_LENGTH),
|
|
83
|
+
followUp: followUpOf(input.followUp),
|
|
84
|
+
};
|
|
85
|
+
if (!plan.items.length && !plan.studies.length && !plan.homeCare.length && !plan.note) {
|
|
86
|
+
throw httpError(400, 'plan needs a drug, a study, a home care measure or a note');
|
|
87
|
+
}
|
|
88
|
+
return plan;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function approvedInstructions(plan, edited) {
|
|
92
|
+
if (edited != null && typeof edited !== 'string') throw httpError(400, 'instructions must be text');
|
|
93
|
+
if (!edited?.trim()) return { instructions: planInstructions(plan), instructionsEdited: false };
|
|
94
|
+
const instructions = edited.trim();
|
|
95
|
+
if (instructions.length > MAX_INSTRUCTIONS_LENGTH) throw httpError(400, `instructions exceed ${MAX_INSTRUCTIONS_LENGTH} characters`);
|
|
96
|
+
return { instructions, instructionsEdited: instructions !== planInstructions(plan) };
|
|
97
|
+
}
|
|
98
|
+
|
|
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`);
|
|
101
|
+
|
|
102
|
+
function replyIssues(plan, reply) {
|
|
103
|
+
if (!oneLineOf(reply)) return ['no se pudo leer el mensaje enviado'];
|
|
104
|
+
const planned = plannedTextOf(plan);
|
|
105
|
+
const said = dosingFactsOf(reply);
|
|
106
|
+
const allowed = dosingFactsOf(planned);
|
|
107
|
+
const issues = plan.items.filter((item) => !isDrugNamed(reply, item.drug)).map((item) => `no menciona ${item.drug}`);
|
|
108
|
+
for (const hours of strays(said.hours, allowed.hours)) issues.push(`dice «${everyOf(hours)}», que no está en el plan`);
|
|
109
|
+
for (const days of strays(said.days, allowed.days)) issues.push(`dice «por ${days} días», que no está en el plan`);
|
|
110
|
+
for (const [amount, written] of said.amounts) {
|
|
111
|
+
if (!allowed.amounts.has(amount)) issues.push(`dice «${written}», que no está en el plan`);
|
|
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`);
|
|
115
|
+
for (const name of unplannedDrugsIn(reply, planned)) issues.push(`menciona ${name}, que el médico no indicó`);
|
|
116
|
+
for (const word of strays(urgencyWordsIn(reply), urgencyWordsIn(planned))) issues.push(`usa «${word}», que el médico no indicó`);
|
|
117
|
+
return issues;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = { approvedInstructions, planOf, replyIssues };
|
|
@@ -16,6 +16,9 @@ const { withTiming } = require('../../utils/tracingDecorator');
|
|
|
16
16
|
|
|
17
17
|
const { JUSTIFICATION_KINDS, crossSymptomIssues, drugsNamedIn, unproposedDrugsIn, validateProposal } = require('./treatmentProposalService');
|
|
18
18
|
|
|
19
|
+
// The model reads the validated `instructions`; `dosing` only feeds the doctor's plan.
|
|
20
|
+
const MODEL_FORMULARY = TREATMENT_FORMULARY.map((entry) => ({ ...entry, drugs: entry.drugs.map(({ dosing: _dosing, ...drug }) => drug) }));
|
|
21
|
+
|
|
19
22
|
const CONVERSATION_TURNS = 40;
|
|
20
23
|
const TRIAGE_LIMIT = 3;
|
|
21
24
|
const CALL_LOG_LIMIT = 10;
|
|
@@ -156,7 +159,7 @@ async function generateEscalationDraft({
|
|
|
156
159
|
}
|
|
157
160
|
|
|
158
161
|
const context = await getEscalationContext({ code, now });
|
|
159
|
-
const input = buildDraftInput({ context, callLogs, protocol:
|
|
162
|
+
const input = buildDraftInput({ context, callLogs, protocol: MODEL_FORMULARY, alarms, agentCharacterization });
|
|
160
163
|
|
|
161
164
|
// Past this point a generation run was issued. Whether the request actually left the process is
|
|
162
165
|
// not knowable here — the provider resolves the preset and validates the schema before it calls
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { drugNameOf } = require('../helpers/planTextHelper');
|
|
1
2
|
const { TREATMENT_FORMULARY, findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
3
|
|
|
3
4
|
const { normalizeForAnchor: key } = require('../../utils/textMatchUtils');
|
|
@@ -90,10 +91,9 @@ function validateProposal(proposal, context = {}) {
|
|
|
90
91
|
|
|
91
92
|
const namesOf = (drug) => [drug.drug, ...drug.drug.split('/'), ...String(drug.brand ?? '').split('/')].map(key).filter((name) => name.length >= 4);
|
|
92
93
|
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
.flatMap(namesOf))];
|
|
94
|
+
const ALL_FORMULARY_DRUGS = TREATMENT_FORMULARY.flatMap((entry) => entry.drugs);
|
|
95
|
+
const FORMULARY_DRUGS = ALL_FORMULARY_DRUGS.filter((drug) => drug.isPharmacological !== false);
|
|
96
|
+
const DRUG_NAMES = [...new Set(FORMULARY_DRUGS.flatMap(namesOf))];
|
|
97
97
|
|
|
98
98
|
function resolvedDrugs(proposals) {
|
|
99
99
|
return proposals.filter(Boolean).flatMap((proposal) => {
|
|
@@ -107,6 +107,14 @@ 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
|
+
|
|
110
118
|
function unproposedDrugsIn(text, proposals) {
|
|
111
119
|
const proposed = new Set(resolvedDrugs(proposals).flatMap(({ drug }) => namesOf(drug)));
|
|
112
120
|
return drugsNamedIn(text).filter((name) => !proposed.has(name));
|
|
@@ -128,10 +136,24 @@ function crossSymptomIssues(proposals) {
|
|
|
128
136
|
return issues;
|
|
129
137
|
}
|
|
130
138
|
|
|
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
|
+
|
|
131
151
|
module.exports = {
|
|
132
152
|
JUSTIFICATION_KINDS,
|
|
153
|
+
isDrugNamed,
|
|
133
154
|
validateProposal,
|
|
134
155
|
unproposedDrugsIn,
|
|
156
|
+
unplannedDrugsIn,
|
|
135
157
|
drugsNamedIn,
|
|
136
158
|
crossSymptomIssues,
|
|
137
159
|
};
|
|
@@ -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`, `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.',
|
|
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`, `plan_approved` = the doctor gave a structured plan, `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`, `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.',
|
|
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`, `plan_approved` = the doctor gave a structured plan, `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,6 +11,7 @@ const {
|
|
|
11
11
|
handOffToDoctor,
|
|
12
12
|
listEscalationReviews,
|
|
13
13
|
openEscalationReview,
|
|
14
|
+
previewPlanInstructions,
|
|
14
15
|
reclassifyUrgency,
|
|
15
16
|
recordDoctorDecision,
|
|
16
17
|
requestBotDraft,
|
|
@@ -30,7 +31,7 @@ const respondWithError = (res, error, action, context) => {
|
|
|
30
31
|
stack: redactDirectIdentifiers(String(error.stack || '')),
|
|
31
32
|
...context,
|
|
32
33
|
});
|
|
33
|
-
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 }) });
|
|
34
35
|
};
|
|
35
36
|
|
|
36
37
|
const withCaseStatus = (review) => (review ? { ...review, caseStatus: CASE_STATUS_BY_REVIEW_STATUS[review.status] ?? null } : review);
|
|
@@ -53,13 +54,22 @@ const openEscalationReviewController = async (req, res) => {
|
|
|
53
54
|
|
|
54
55
|
const getEscalationReviewController = async (req, res) => {
|
|
55
56
|
try {
|
|
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 });
|
|
57
|
+
const { review, isApprover, responseDeadline, proposedPlan, prescribers } = await getEscalationReviewById({ id: req.params.id, requestedBy: req.query.requestedBy });
|
|
58
|
+
res.status(200).json({ success: true, review: withCaseStatus(review), isApprover, responseDeadline, proposedPlan, prescribers });
|
|
58
59
|
} catch (error) {
|
|
59
60
|
respondWithError(res, error, 'reading escalation review', { reviewId: req.params?.id });
|
|
60
61
|
}
|
|
61
62
|
};
|
|
62
63
|
|
|
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
|
+
|
|
63
73
|
const getReviewTimelineController = async (req, res) => {
|
|
64
74
|
try {
|
|
65
75
|
const timeline = await getReviewTimeline({ id: req.params.id });
|
|
@@ -175,6 +185,9 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
175
185
|
source,
|
|
176
186
|
decision,
|
|
177
187
|
finalText = null,
|
|
188
|
+
plan = null,
|
|
189
|
+
instructions = null,
|
|
190
|
+
prescriberEmail = null,
|
|
178
191
|
comment = null,
|
|
179
192
|
doctorName = null,
|
|
180
193
|
doctorReply = null,
|
|
@@ -188,6 +201,9 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
188
201
|
source,
|
|
189
202
|
decision,
|
|
190
203
|
finalText,
|
|
204
|
+
plan,
|
|
205
|
+
instructions,
|
|
206
|
+
prescriberEmail,
|
|
191
207
|
comment,
|
|
192
208
|
doctorName,
|
|
193
209
|
doctorReply,
|
|
@@ -284,6 +300,7 @@ module.exports = {
|
|
|
284
300
|
closeEscalationReviewController,
|
|
285
301
|
getEscalationReviewController,
|
|
286
302
|
getReviewTimelineController,
|
|
303
|
+
previewEscalationReviewPlanController,
|
|
287
304
|
requestEscalationReviewDraftController,
|
|
288
305
|
handOffEscalationReviewController,
|
|
289
306
|
listEscalationReviewsController,
|
|
@@ -1,17 +1,11 @@
|
|
|
1
|
-
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
2
|
-
|
|
3
1
|
const { logger } = require('../utils/logger');
|
|
4
2
|
|
|
5
|
-
const {
|
|
6
|
-
|
|
7
|
-
const { addLinkedRecord } = require('../services/airtableService');
|
|
3
|
+
const { createPrescription } = require('../services/prescriptionService');
|
|
8
4
|
|
|
9
5
|
const RECORD_ID_RX = /^rec[A-Za-z0-9]{14}$/;
|
|
10
6
|
|
|
11
|
-
// physicianId links the receta to a physicians row; the Airtable automation picks the PDF template from that physician's specialty.
|
|
12
7
|
const createPrescriptionController = async (req, res) => {
|
|
13
|
-
const { prescription, triggeredBy, creationSource = 'other', physicianId } = req.body;
|
|
14
|
-
let code = req.body.code;
|
|
8
|
+
const { code, prescription, triggeredBy, creationSource = 'other', physicianId } = req.body;
|
|
15
9
|
|
|
16
10
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
17
11
|
if (!prescription) return res.status(400).json({ success: false, error: 'Prescription is required' });
|
|
@@ -21,28 +15,10 @@ const createPrescriptionController = async (req, res) => {
|
|
|
21
15
|
}
|
|
22
16
|
|
|
23
17
|
try {
|
|
24
|
-
|
|
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
|
-
);
|
|
18
|
+
const recordId = await createPrescription({ code, prescription, authorEmail: triggeredBy, creationSource, physicianId });
|
|
43
19
|
|
|
44
20
|
logger.info('[PrescriptionController] Prescription created', { code, physicianId });
|
|
45
|
-
res.status(201).json({ success: true, message: 'Prescription created', recordId
|
|
21
|
+
res.status(201).json({ success: true, message: 'Prescription created', recordId });
|
|
46
22
|
} catch (error) {
|
|
47
23
|
logger.error('[PrescriptionController] Error creating prescription', { error: error.message, code });
|
|
48
24
|
res.status(500).json({ success: false, error: 'Failed to create prescription' });
|
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<{ delivery: Record<string, unknown> | null; sendThrew: boolean; reply: string | null } | undefined>;
|
|
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>;
|
|
@@ -12,7 +12,8 @@ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
|
12
12
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
13
13
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
14
14
|
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
15
|
-
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
15
|
+
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'plan_approved', 'needs_intervention', 'returned', 'monitor', 'direct_chat'];
|
|
16
|
+
const PLAN_FOLLOW_UPS = ['none', 'check_in', 'vigilancia'];
|
|
16
17
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator', 'chat'];
|
|
17
18
|
const RETURN_REASONS = ['llamar', 'falta_dato', 'no_requiere'];
|
|
18
19
|
|
|
@@ -193,11 +194,43 @@ const doctorHandoffSchema = new mongoose.Schema({
|
|
|
193
194
|
sentBy: { type: String, required: true },
|
|
194
195
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
195
196
|
|
|
197
|
+
const planItemSchema = new mongoose.Schema({
|
|
198
|
+
drug: { type: String, required: true },
|
|
199
|
+
strength: { type: String, default: null },
|
|
200
|
+
dose: { type: String, required: true },
|
|
201
|
+
frequency: { type: String, required: true },
|
|
202
|
+
days: { type: Number, required: true },
|
|
203
|
+
position: { type: String, default: null },
|
|
204
|
+
reason: { type: String, default: null },
|
|
205
|
+
formularyKey: { type: String, default: null },
|
|
206
|
+
}, { _id: false });
|
|
207
|
+
|
|
208
|
+
const planSchema = new mongoose.Schema({
|
|
209
|
+
items: { type: [planItemSchema], default: [] },
|
|
210
|
+
studies: {
|
|
211
|
+
type: [new mongoose.Schema({ name: { type: String, required: true }, instructions: { type: String, default: null } }, { _id: false })],
|
|
212
|
+
default: [],
|
|
213
|
+
},
|
|
214
|
+
homeCare: { type: [String], default: [] },
|
|
215
|
+
note: { type: String, default: null },
|
|
216
|
+
followUp: {
|
|
217
|
+
type: new mongoose.Schema({ kind: { type: String, enum: PLAN_FOLLOW_UPS, required: true }, hours: { type: Number, default: null } }, { _id: false }),
|
|
218
|
+
required: true,
|
|
219
|
+
},
|
|
220
|
+
instructions: { type: String, required: true },
|
|
221
|
+
instructionsEdited: { type: Boolean, default: false },
|
|
222
|
+
prescriber: {
|
|
223
|
+
type: new mongoose.Schema({ name: { type: String, default: null }, email: { type: String, required: true } }, { _id: false }),
|
|
224
|
+
default: null,
|
|
225
|
+
},
|
|
226
|
+
}, { _id: false });
|
|
227
|
+
|
|
196
228
|
const decisionSchema = new mongoose.Schema({
|
|
197
229
|
decision: { type: String, enum: DOCTOR_DECISIONS, required: true },
|
|
198
230
|
source: { type: String, enum: DECISION_SOURCES, required: true },
|
|
199
231
|
draftNumber: { type: Number, required: true },
|
|
200
232
|
finalText: { type: String, default: null },
|
|
233
|
+
plan: { type: planSchema, default: undefined },
|
|
201
234
|
comment: { type: String, default: null },
|
|
202
235
|
doctorReply: { type: String, default: null },
|
|
203
236
|
returnReason: { type: String, enum: [...RETURN_REASONS, null], default: null },
|
|
@@ -210,7 +243,9 @@ const patientDeliverySchema = new mongoose.Schema({
|
|
|
210
243
|
decisionNumber: { type: Number, required: true },
|
|
211
244
|
messageId: { type: String, default: null },
|
|
212
245
|
status: { type: String, default: null },
|
|
213
|
-
transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template'], required: true },
|
|
246
|
+
transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template', 'assistant'], required: true },
|
|
247
|
+
prescriptionRecordId: { type: String, default: null },
|
|
248
|
+
checks: { type: [String], default: undefined },
|
|
214
249
|
deferred: { type: Boolean, default: false },
|
|
215
250
|
confirmedBy: { type: String, default: null },
|
|
216
251
|
confirmedAt: { type: Date, default: null },
|
|
@@ -381,6 +416,7 @@ module.exports = {
|
|
|
381
416
|
DOCTOR_DECISIONS,
|
|
382
417
|
HANDOFF_MODES,
|
|
383
418
|
INTERRUPTED_STATUSES,
|
|
419
|
+
PLAN_FOLLOW_UPS,
|
|
384
420
|
FOLLOWUP_STATUSES,
|
|
385
421
|
RETURN_REASONS,
|
|
386
422
|
URGENCY_LEVELS,
|
package/lib/routes/index.js
CHANGED
|
@@ -138,6 +138,7 @@ const escalationReviewRouteDefinitions = {
|
|
|
138
138
|
'POST /:id/note-facts': 'confirmEscalationReviewNoteFactsController',
|
|
139
139
|
'POST /:id/drafts': 'addEscalationReviewDraftController',
|
|
140
140
|
'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
|
|
141
|
+
'POST /:id/plan-instructions': 'previewEscalationReviewPlanController',
|
|
141
142
|
'POST /:id/decisions': 'recordEscalationReviewDecisionController',
|
|
142
143
|
'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
|
|
143
144
|
'POST /:id/close': 'closeEscalationReviewController',
|
|
@@ -314,6 +315,7 @@ const builtInControllers = {
|
|
|
314
315
|
listReviewBoardController: escalationReviewController.listReviewBoardController,
|
|
315
316
|
getEscalationReviewController: escalationReviewController.getEscalationReviewController,
|
|
316
317
|
getReviewTimelineController: escalationReviewController.getReviewTimelineController,
|
|
318
|
+
previewEscalationReviewPlanController: escalationReviewController.previewEscalationReviewPlanController,
|
|
317
319
|
requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
|
|
318
320
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
319
321
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
@@ -26,9 +26,9 @@ const ASSISTANT_MESSAGE_FAILURES = {
|
|
|
26
26
|
};
|
|
27
27
|
|
|
28
28
|
class AssistantMessageError extends Error {
|
|
29
|
-
constructor(reasonCode, acceptedCount = 0) {
|
|
29
|
+
constructor(reasonCode, acceptedCount = 0, cause = undefined) {
|
|
30
30
|
const [statusCode, message] = ASSISTANT_MESSAGE_FAILURES[reasonCode];
|
|
31
|
-
super(message);
|
|
31
|
+
super(message, cause === undefined ? undefined : { cause });
|
|
32
32
|
this.reasonCode = reasonCode;
|
|
33
33
|
this.statusCode = statusCode;
|
|
34
34
|
this.acceptedCount = acceptedCount;
|
|
@@ -117,8 +117,10 @@ async function processAssistantSystemMessage(code, messages, role = 'system', op
|
|
|
117
117
|
if (!reply) return;
|
|
118
118
|
recordPatientSend?.({ code, channel: 'assistant_instruction', sentBy: triggeredBy, text: input.messages.join('\n') });
|
|
119
119
|
|
|
120
|
+
let turn;
|
|
121
|
+
let settled = null;
|
|
120
122
|
try {
|
|
121
|
-
await executeWithPipeline(code, 'system', 'queue',
|
|
123
|
+
turn = await executeWithPipeline(code, 'system', 'queue',
|
|
122
124
|
async (preProcessResult, shouldContinue, runId) => {
|
|
123
125
|
return await assistantProcessor.process({
|
|
124
126
|
code,
|
|
@@ -131,11 +133,15 @@ async function processAssistantSystemMessage(code, messages, role = 'system', op
|
|
|
131
133
|
signal: getAbortSignal(runId),
|
|
132
134
|
}
|
|
133
135
|
});
|
|
134
|
-
}
|
|
136
|
+
},
|
|
137
|
+
{ onSendSettled: async (outcome) => { settled = outcome; } },
|
|
135
138
|
);
|
|
136
|
-
} catch {
|
|
137
|
-
|
|
139
|
+
} catch (error) {
|
|
140
|
+
// The cause stays internal: callers tell a drain that refused the turn from one that may have answered.
|
|
141
|
+
throw new AssistantMessageError('MESSAGE_REPLY_FAILED', acceptedCount, error);
|
|
138
142
|
}
|
|
143
|
+
// A send that threw may still have reached the patient.
|
|
144
|
+
return { delivery: turn?.delivery ?? null, sendThrew: settled === 'threw', reply: turn?.output ?? null };
|
|
139
145
|
}
|
|
140
146
|
|
|
141
147
|
module.exports = { AssistantMessageError, injectAssistantMessages, processAssistantSystemMessage };
|
|
@@ -29,11 +29,13 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
|
29
29
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
30
30
|
const { DrainingError } = require('../core/BatchingManager');
|
|
31
31
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
32
|
-
const { conversationLink, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
32
|
+
const { conversationLink, readGroupMessageId, writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
33
33
|
const { doctorAlertHeadline, doctorAlertOpener, renderDoctorMessage, templateSummary, withIdentity } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
34
34
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
35
35
|
const { drugsNamedIn } = require('../clinical/services/treatmentProposalService');
|
|
36
36
|
const { characterizationSeedOf } = require('../clinical/helpers/reviewUpdateHelper');
|
|
37
|
+
const { assistantInstructionsOf, needsPrescriber, planInstructions, planSummary, prescriptionText, proposedPlanOf } = require('../clinical/helpers/doctorPlanHelper');
|
|
38
|
+
const { approvedInstructions, planOf, replyIssues } = require('../clinical/services/doctorPlanService');
|
|
37
39
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
38
40
|
const { humanReplyFilter } = require('../clinical/config/safetyNetConfig');
|
|
39
41
|
const {
|
|
@@ -53,10 +55,11 @@ const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
|
53
55
|
const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
54
56
|
const { countMessages } = require('./messageService');
|
|
55
57
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
58
|
+
const { createPrescription } = require('./prescriptionService');
|
|
56
59
|
const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
|
|
57
60
|
const { effectiveUrgencyOf, levelsOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
58
61
|
const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
|
|
59
|
-
const { groupConfigured, sendTeamAlert, teamChannelConfigured } = require('./teamAlertService');
|
|
62
|
+
const { groupConfigured, sendGroupNotice, sendTeamAlert, teamChannelConfigured } = require('./teamAlertService');
|
|
60
63
|
|
|
61
64
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
62
65
|
|
|
@@ -105,7 +108,11 @@ const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
|
|
|
105
108
|
const SAME_URGENCY = 'The review is already at that urgency';
|
|
106
109
|
const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
|
|
107
110
|
const DIRECT_CHAT_STATUSES = ['open', 'documenting', 'draft_ready', 'returned', 'awaiting_doctor', 'approved', 'needs_intervention'];
|
|
108
|
-
const APPROVALS = ['approved', 'edited_approved'];
|
|
111
|
+
const APPROVALS = ['approved', 'edited_approved', 'plan_approved'];
|
|
112
|
+
// The interface offers a resend only for SEND_NOT_SENT; SEND_UNCONFIRMED may have reached the patient.
|
|
113
|
+
const SEND_NOT_SENT = 'send_not_sent';
|
|
114
|
+
const SEND_UNCONFIRMED = 'send_unconfirmed';
|
|
115
|
+
const withSendCode = (error, errorCode) => (error instanceof Error && !Object.isFrozen(error) && !error.errorCode ? Object.assign(error, { errorCode }) : error);
|
|
109
116
|
const STALE_DRAFT = 'New information reached the review after this draft; wait for the updated draft before approving';
|
|
110
117
|
const STALE_HANDOFF = 'New information reached the review after the draft the doctor received; it went back to documenting for a new draft';
|
|
111
118
|
const DRAFT_CHANGED = 'A newer draft was written after the one you saw; read it before deciding';
|
|
@@ -145,7 +152,7 @@ const configured = (key) => {
|
|
|
145
152
|
return value;
|
|
146
153
|
};
|
|
147
154
|
|
|
148
|
-
const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
|
|
155
|
+
const STATUS_AFTER = { edited_approved: 'approved', plan_approved: 'approved', monitor: 'monitoring' };
|
|
149
156
|
const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
|
|
150
157
|
|
|
151
158
|
const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
|
|
@@ -728,6 +735,33 @@ async function isEscalationApprover(operator) {
|
|
|
728
735
|
}
|
|
729
736
|
}
|
|
730
737
|
|
|
738
|
+
// Unpicked, the doctor is the one recording if they approve, or the only approver there is.
|
|
739
|
+
async function prescriberOf(email, operator) {
|
|
740
|
+
if (email != null && typeof email !== 'string') throw httpError(400, 'prescriberEmail must be text');
|
|
741
|
+
let approvers;
|
|
742
|
+
try {
|
|
743
|
+
approvers = await listEscalationApprovers();
|
|
744
|
+
} catch (error) {
|
|
745
|
+
logger.error('[EscalationReview] The approving doctors could not be listed; the plan was not recorded', { error: redactedError(error) });
|
|
746
|
+
throw httpError(503, 'The approving doctors could not be read; try again');
|
|
747
|
+
}
|
|
748
|
+
if (!approvers.length) throw httpError(409, 'No physician signs recetas: tick aprueba_vaiven on a physician');
|
|
749
|
+
const wanted = (email?.trim() || operator).trim().toLowerCase();
|
|
750
|
+
const chosen = approvers.find((approver) => approver.email === wanted) ?? (!email?.trim() && approvers.length === 1 ? approvers[0] : null);
|
|
751
|
+
if (!chosen) throw httpError(400, `prescriberEmail must be one of: ${approvers.map((approver) => approver.email).join(', ')}`);
|
|
752
|
+
return { name: chosen.name, email: chosen.email };
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// Null when the list could not be read; the review is still returned.
|
|
756
|
+
async function prescribersForRead() {
|
|
757
|
+
try {
|
|
758
|
+
return (await listEscalationApprovers()).map(({ name, email }) => ({ name, email }));
|
|
759
|
+
} catch (error) {
|
|
760
|
+
logger.warn('[EscalationReview] The approving doctors could not be listed for the review', { error: redactedError(error) });
|
|
761
|
+
return null;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
731
765
|
async function getEscalationReviewById({ id, requestedBy } = {}) {
|
|
732
766
|
const reviewId = reviewIdOf(id);
|
|
733
767
|
const operator = requiredText(requestedBy, 'requestedBy');
|
|
@@ -748,7 +782,19 @@ async function getEscalationReviewById({ id, requestedBy } = {}) {
|
|
|
748
782
|
.updateOne({ _id: review._id }, { $max: { approverViewedAt: readAt } }, { timestamps: false })
|
|
749
783
|
.catch(warnUnmarked);
|
|
750
784
|
}
|
|
751
|
-
|
|
785
|
+
const draft = DECIDABLE_STATUSES.includes(review.status) ? review.drafts?.at(-1) : null;
|
|
786
|
+
return {
|
|
787
|
+
review,
|
|
788
|
+
isApprover,
|
|
789
|
+
responseDeadline: responseDeadlineOf(review, responseDeadlinePolicy()),
|
|
790
|
+
proposedPlan: draft ? { draftNumber: review.drafts.length, ...proposedPlanOf(draft) } : null,
|
|
791
|
+
prescribers: draft ? await prescribersForRead() : [],
|
|
792
|
+
};
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
function previewPlanInstructions({ id, plan } = {}) {
|
|
796
|
+
reviewIdOf(id);
|
|
797
|
+
return planInstructions(planOf(plan));
|
|
752
798
|
}
|
|
753
799
|
|
|
754
800
|
async function getReviewTimeline({ id } = {}) {
|
|
@@ -1787,6 +1833,9 @@ async function recordDoctorDecision({
|
|
|
1787
1833
|
source,
|
|
1788
1834
|
decision,
|
|
1789
1835
|
finalText = null,
|
|
1836
|
+
plan: requestedPlan = null,
|
|
1837
|
+
instructions = null,
|
|
1838
|
+
prescriberEmail = null,
|
|
1790
1839
|
comment = null,
|
|
1791
1840
|
doctorName = null,
|
|
1792
1841
|
doctorReply = null,
|
|
@@ -1815,6 +1864,20 @@ async function recordDoctorDecision({
|
|
|
1815
1864
|
if (!RETURN_REASONS.includes(reason)) throw httpError(400, `reason must be one of: ${RETURN_REASONS.join(', ')}`);
|
|
1816
1865
|
returnReason = reason;
|
|
1817
1866
|
}
|
|
1867
|
+
let plan = null;
|
|
1868
|
+
if (decision === 'plan_approved') {
|
|
1869
|
+
if (source !== 'platform') throw httpError(400, 'A plan is approved by the doctor on the platform');
|
|
1870
|
+
// The plan names the draft it started from, so a newer draft is refused instead of decided unseen.
|
|
1871
|
+
if (seenDraftNumber === null) throw httpError(400, 'draftNumber is required for a plan');
|
|
1872
|
+
plan = planOf(requestedPlan);
|
|
1873
|
+
plan = { ...plan, ...approvedInstructions(plan, instructions) };
|
|
1874
|
+
// Anyone may record a plan, often beside the doctor; one with a drug, study, note or edit names the doctor who gave it.
|
|
1875
|
+
const namesDrug = drugsNamedIn(plan.homeCare.join(' ')).length > 0;
|
|
1876
|
+
if (needsPrescriber(plan) || plan.note || plan.instructionsEdited || namesDrug) {
|
|
1877
|
+
plan = { ...plan, prescriber: await prescriberOf(prescriberEmail, operator) };
|
|
1878
|
+
decidedBy = plan.prescriber.email;
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1818
1881
|
|
|
1819
1882
|
const review = await loadReview(reviewId);
|
|
1820
1883
|
const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
|
|
@@ -1858,6 +1921,7 @@ async function recordDoctorDecision({
|
|
|
1858
1921
|
source,
|
|
1859
1922
|
draftNumber,
|
|
1860
1923
|
finalText: approvedText,
|
|
1924
|
+
...(plan && { plan }),
|
|
1861
1925
|
comment: optionalText(comment),
|
|
1862
1926
|
doctorReply: reply,
|
|
1863
1927
|
...(returnReason && { returnReason }),
|
|
@@ -1993,10 +2057,10 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
1993
2057
|
const claim = newOperationClaim();
|
|
1994
2058
|
const claimed = await updateReview(reviewId, SENDABLE_STATUSES, { $set: { status: 'sending', operationClaim: claim } });
|
|
1995
2059
|
const decisionNumber = claimed.decisions.length;
|
|
1996
|
-
const { finalText, decision } = claimed.decisions[decisionNumber - 1];
|
|
2060
|
+
const { finalText, decision, plan } = claimed.decisions[decisionNumber - 1];
|
|
1997
2061
|
const claimedFrom = statusAfter(decision);
|
|
1998
2062
|
|
|
1999
|
-
if (!finalText) {
|
|
2063
|
+
if (!finalText && !plan) {
|
|
2000
2064
|
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
2001
2065
|
logger.error('[EscalationReview] The claim was not released after a decision with no text', {
|
|
2002
2066
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
@@ -2014,6 +2078,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2014
2078
|
});
|
|
2015
2079
|
throw httpError(409, 'The agent characterized the case after this decision; it went back to documenting for a new draft and decision');
|
|
2016
2080
|
}
|
|
2081
|
+
if (plan) return sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan, operator, requestId });
|
|
2017
2082
|
|
|
2018
2083
|
// Built outside the try: composing reads Mongo and Airtable, and failing there never sent.
|
|
2019
2084
|
let message;
|
|
@@ -2025,7 +2090,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2025
2090
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
2026
2091
|
});
|
|
2027
2092
|
});
|
|
2028
|
-
throw error;
|
|
2093
|
+
throw withSendCode(error, SEND_NOT_SENT);
|
|
2029
2094
|
}
|
|
2030
2095
|
|
|
2031
2096
|
let result;
|
|
@@ -2033,7 +2098,7 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2033
2098
|
result = await getMessaging().sendMessage(message);
|
|
2034
2099
|
const alreadyDelivered = result?.status === 'duplicate_suppressed' && result?.completed === true;
|
|
2035
2100
|
if (!result?.success && !alreadyDelivered) {
|
|
2036
|
-
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);
|
|
2037
2102
|
}
|
|
2038
2103
|
} catch (error) {
|
|
2039
2104
|
if (!sendDidNotHappen(error)) {
|
|
@@ -2041,14 +2106,14 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2041
2106
|
escalationReviewId: String(claimed._id),
|
|
2042
2107
|
error: redactedError(error),
|
|
2043
2108
|
});
|
|
2044
|
-
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);
|
|
2045
2110
|
}
|
|
2046
2111
|
await releaseReview(reviewId, 'sending', claimedFrom, claim).catch((releaseError) => {
|
|
2047
2112
|
logger.error('[EscalationReview] The claim was not released after a confirmed non-send', {
|
|
2048
2113
|
escalationReviewId: String(claimed._id), error: releaseError.message,
|
|
2049
2114
|
});
|
|
2050
2115
|
});
|
|
2051
|
-
throw error;
|
|
2116
|
+
throw withSendCode(error, SEND_NOT_SENT);
|
|
2052
2117
|
}
|
|
2053
2118
|
|
|
2054
2119
|
const deferred = result.deferred === true;
|
|
@@ -2064,11 +2129,123 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
2064
2129
|
const recordUpdate = withCaseMirror(claimed, {
|
|
2065
2130
|
$set: { patientDelivery: delivery },
|
|
2066
2131
|
}, { recommendation: finalText });
|
|
2067
|
-
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); });
|
|
2068
2133
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
2069
2134
|
return syncCase(review, operator, requestId);
|
|
2070
2135
|
}
|
|
2071
2136
|
|
|
2137
|
+
// The PDF goes out from the Airtable automations; a failed receta never undoes the message already sent.
|
|
2138
|
+
async function issuePrescription(review, plan, prescriberEmail) {
|
|
2139
|
+
try {
|
|
2140
|
+
return await createPrescription({
|
|
2141
|
+
code: review.patientCode, prescription: prescriptionText(plan), authorEmail: prescriberEmail, creationSource: 'patient case',
|
|
2142
|
+
});
|
|
2143
|
+
} catch (error) {
|
|
2144
|
+
logger.error('[EscalationReview] The prescription was not created after the plan was sent', {
|
|
2145
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
2146
|
+
});
|
|
2147
|
+
return null;
|
|
2148
|
+
}
|
|
2149
|
+
}
|
|
2150
|
+
|
|
2151
|
+
function replyOutcome(delivery, sendThrew) {
|
|
2152
|
+
if (sendThrew) return 'unknown';
|
|
2153
|
+
if (!delivery) return 'not_sent';
|
|
2154
|
+
if (delivery.success === true && delivery.deferred === true) return 'queued';
|
|
2155
|
+
if (delivery.success === true && typeof delivery.messageId === 'string' && delivery.messageId) return 'sent';
|
|
2156
|
+
if (delivery.success === false && delivery.deferred !== true && delivery.duplicate !== true) return 'not_sent';
|
|
2157
|
+
return 'unknown';
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
// A notice that fails is logged and never undoes the send.
|
|
2161
|
+
async function notifyPlanIssues(review, issues) {
|
|
2162
|
+
try {
|
|
2163
|
+
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
2164
|
+
const header = '⚠️ Revisar el envío del plan';
|
|
2165
|
+
const lines = issues.map((issue) => `- ${issue}`);
|
|
2166
|
+
const action = 'Qué hacer: revisar el chat; corregir con la paciente o volver a mandar la receta si hace falta';
|
|
2167
|
+
// Every alarm, not only those since the decision: the plan is always sent after it, so the case's alarm came before.
|
|
2168
|
+
const recordId = [...(review.alarms ?? [])].reverse().find((alarm) => alarm.emergencyRecordId)?.emergencyRecordId;
|
|
2169
|
+
const quoted = await readGroupMessageId(recordId, review.patientCode);
|
|
2170
|
+
const sent = await sendGroupNotice([header, `${patient} (${doctor})`, ...lines, action, link].join('\n'), quoted, [header, ...lines, action].join('\n'));
|
|
2171
|
+
if (!sent.delivered) logger.error('[EscalationReview] The plan check notice did not reach the group', { escalationReviewId: String(review._id), error: sent.error });
|
|
2172
|
+
} catch (error) {
|
|
2173
|
+
logger.error('[EscalationReview] The plan check notice failed', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
async function sendPlanThroughAssistant({ claimed, claim, decisionNumber, plan, operator, requestId }) {
|
|
2178
|
+
const reviewId = claimed._id;
|
|
2179
|
+
const release = () => releaseReview(reviewId, 'sending', 'approved', claim).catch((releaseError) => {
|
|
2180
|
+
logger.error('[EscalationReview] The claim was not released after a plan the assistant did not send', {
|
|
2181
|
+
escalationReviewId: String(reviewId), error: releaseError.message,
|
|
2182
|
+
});
|
|
2183
|
+
});
|
|
2184
|
+
|
|
2185
|
+
const prescriberEmail = needsPrescriber(plan) ? plan.prescriber?.email ?? null : null;
|
|
2186
|
+
let delivery;
|
|
2187
|
+
let sendThrew;
|
|
2188
|
+
let reply;
|
|
2189
|
+
try {
|
|
2190
|
+
if (needsPrescriber(plan) && !prescriberEmail) throw httpError(409, 'This plan names no doctor to sign the receta; record the plan again');
|
|
2191
|
+
({ delivery = null, sendThrew = false, reply = null } = await getMessaging().processSystemMessage(
|
|
2192
|
+
claimed.patientCode, [assistantInstructionsOf(plan)], 'system', { reply: true, triggeredBy: operator },
|
|
2193
|
+
) ?? {});
|
|
2194
|
+
} catch (error) {
|
|
2195
|
+
// A turn refused by a deploy's drain never ran; any other failure after the instructions were stored may have answered.
|
|
2196
|
+
if (error?.reasonCode === 'MESSAGE_REPLY_FAILED' && !(error.cause instanceof DrainingError)) {
|
|
2197
|
+
logger.error('[EscalationReview] The assistant turn failed after the instructions were stored; leaving the review in sending', {
|
|
2198
|
+
escalationReviewId: String(reviewId),
|
|
2199
|
+
});
|
|
2200
|
+
throw httpError(502, 'The assistant turn failed after the instructions were stored; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2201
|
+
}
|
|
2202
|
+
await release();
|
|
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);
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
const outcome = replyOutcome(delivery, sendThrew);
|
|
2208
|
+
if (outcome === 'not_sent') {
|
|
2209
|
+
await release();
|
|
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);
|
|
2211
|
+
}
|
|
2212
|
+
if (outcome === 'unknown') {
|
|
2213
|
+
logger.error('[EscalationReview] The assistant reply could not be confirmed; leaving the review in sending', { escalationReviewId: String(reviewId) });
|
|
2214
|
+
await notifyPlanIssues(claimed, ['no se pudo confirmar que el mensaje salió; el caso sigue en «enviando»']);
|
|
2215
|
+
throw httpError(502, 'The assistant reply could not be confirmed; check the chat before sending again', SEND_UNCONFIRMED);
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
// A queued reply goes out once the patient answers the recovery template; the receta, a template itself, goes now.
|
|
2219
|
+
const queued = outcome === 'queued';
|
|
2220
|
+
const prescriptionRecordId = prescriberEmail ? await issuePrescription(claimed, plan, prescriberEmail) : null;
|
|
2221
|
+
const prescriptionFailed = Boolean(prescriberEmail) && !prescriptionRecordId;
|
|
2222
|
+
const issues = [...replyIssues(plan, reply), ...(prescriptionFailed ? ['no se pudo crear la receta'] : [])];
|
|
2223
|
+
const record = {
|
|
2224
|
+
decisionNumber, messageId: delivery.messageId || null, status: delivery.status || null, transport: 'assistant', deferred: queued, sentBy: operator,
|
|
2225
|
+
...(prescriptionRecordId && { prescriptionRecordId }),
|
|
2226
|
+
...(issues.length && { checks: issues }),
|
|
2227
|
+
};
|
|
2228
|
+
const recordUpdate = withCaseMirror(claimed, { $set: { patientDelivery: record } }, { recommendation: planSummary(plan) });
|
|
2229
|
+
const status = queued ? 'indications_queued' : 'indications_sent';
|
|
2230
|
+
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status).catch((error) => { throw withSendCode(error, SEND_UNCONFIRMED); });
|
|
2231
|
+
await audit(review, operator, requestId, {
|
|
2232
|
+
action: status, decisionNumber, transport: 'assistant', checks: issues.length, ...(prescriberEmail && { prescription: prescriptionFailed ? 'failed' : 'created' }),
|
|
2233
|
+
});
|
|
2234
|
+
if (issues.length) await notifyPlanIssues(review, issues);
|
|
2235
|
+
// Closing waits for a sent reply that kept to the plan and the receta it promised; otherwise the team still has something to do.
|
|
2236
|
+
if (plan.followUp.kind === 'none' && !queued && !issues.length) {
|
|
2237
|
+
try {
|
|
2238
|
+
return await closeEscalationReview({ id: reviewId, closedBy: operator, requestId });
|
|
2239
|
+
} catch (error) {
|
|
2240
|
+
logger.error('[EscalationReview] The review was not closed after its plan was sent', {
|
|
2241
|
+
escalationReviewId: String(reviewId), error: redactedError(error),
|
|
2242
|
+
});
|
|
2243
|
+
return syncCase(await loadReview(reviewId), operator, requestId);
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
return syncCase(review, operator, requestId);
|
|
2247
|
+
}
|
|
2248
|
+
|
|
2072
2249
|
const EPISODE_TRUST = 0.7;
|
|
2073
2250
|
const EPISODE_VARIABLE = 'intercurrent_events_summary';
|
|
2074
2251
|
const EPISODE_SOURCE = 'doctor';
|
|
@@ -2076,6 +2253,7 @@ const EPISODE_SOURCE = 'doctor';
|
|
|
2076
2253
|
const DECISION_WORDS = {
|
|
2077
2254
|
approved: 'el médico aprobó las indicaciones',
|
|
2078
2255
|
edited_approved: 'el médico aprobó las indicaciones con cambios',
|
|
2256
|
+
plan_approved: 'el médico dio las indicaciones',
|
|
2079
2257
|
needs_intervention: 'el médico pidió valoración presencial',
|
|
2080
2258
|
returned: 'el médico devolvió el caso a navegación',
|
|
2081
2259
|
};
|
|
@@ -2259,6 +2437,7 @@ module.exports = {
|
|
|
2259
2437
|
generateBotDraft,
|
|
2260
2438
|
getEscalationReviewById,
|
|
2261
2439
|
getReviewTimeline,
|
|
2440
|
+
previewPlanInstructions,
|
|
2262
2441
|
handOffToDoctor,
|
|
2263
2442
|
listEscalationReviews,
|
|
2264
2443
|
openEscalationReview,
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
2
|
+
|
|
3
|
+
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
4
|
+
|
|
5
|
+
const { addLinkedRecord } = require('./airtableService');
|
|
6
|
+
|
|
7
|
+
// physicianId links the receta to a physicians row; the Airtable automation picks the PDF template from that physician's specialty.
|
|
8
|
+
async function createPrescription({ code, prescription, authorEmail, creationSource = 'other', physicianId }) {
|
|
9
|
+
const patientCode = ensureWhatsAppFormat(code);
|
|
10
|
+
const record = await addLinkedRecord(
|
|
11
|
+
Monitoreo_ID,
|
|
12
|
+
'patient_prescriptions',
|
|
13
|
+
{
|
|
14
|
+
prescription,
|
|
15
|
+
author_email: authorEmail,
|
|
16
|
+
creation_source: creationSource,
|
|
17
|
+
created: new Date().toISOString(),
|
|
18
|
+
...(physicianId && { physician: [physicianId] })
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
referenceTable: 'estado_general',
|
|
22
|
+
referenceFilter: `{whatsapp_id}='${patientCode}'`,
|
|
23
|
+
linkFieldName: 'patient_id'
|
|
24
|
+
},
|
|
25
|
+
patientCode
|
|
26
|
+
);
|
|
27
|
+
return record?.id || null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
module.exports = { createPrescription };
|
|
@@ -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();
|