@peopl-health/nexus 5.58.0-dev.10495 → 5.58.0-dev.10497
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/doctorReviewMessageHelper.js +128 -0
- package/lib/clinical/protocols/treatmentFormulary.js +2 -88
- package/lib/clinical/services/escalationDraftService.js +51 -4
- package/lib/clinical/services/treatmentProposalService.js +106 -0
- package/lib/models/escalationReviewModel.js +8 -0
- package/lib/services/escalationReviewService.js +74 -31
- package/lib/utils/textMatchUtils.js +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
const { findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
|
+
const { inlineOf } = require('../../utils/coercionUtils');
|
|
3
|
+
const { mexicoStamp } = require('../../utils/dateUtils');
|
|
4
|
+
|
|
5
|
+
const URGENCY_LABELS = {
|
|
6
|
+
stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
const PROPOSAL_HEADING = 'Propuesta de tratamiento (sugerencia para su aprobación, no es una indicación):';
|
|
10
|
+
const REQUESTED_ACTION = 'Acción solicitada: ¿aprueba la propuesta, la modifica o prefiere una valoración presencial?';
|
|
11
|
+
const ASSESSMENT_ACTION = 'Acción solicitada: valoración médica prioritaria. ¿La valora en persona, la envía a urgencias o indica otra conducta?';
|
|
12
|
+
const DOCTOR_TITLE = /^(dr|dra)\.?\s/i;
|
|
13
|
+
|
|
14
|
+
const withTitle = (name) => (DOCTOR_TITLE.test(name) ? name : `Dr./Dra. ${name}`);
|
|
15
|
+
|
|
16
|
+
function latestAlarm(review) {
|
|
17
|
+
const alarms = Array.isArray(review?.alarms) ? review.alarms : [];
|
|
18
|
+
return alarms[alarms.length - 1] ?? null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function flagsByStatus(sections) {
|
|
22
|
+
const flags = (Array.isArray(sections?.redFlags) ? sections.redFlags : []).filter((flag) => inlineOf(flag?.flag));
|
|
23
|
+
const named = (present) => flags.filter((flag) => flag.present === present).map((flag) => inlineOf(flag.flag));
|
|
24
|
+
return {
|
|
25
|
+
present: named(true),
|
|
26
|
+
absent: named(false),
|
|
27
|
+
unassessed: flags.filter((flag) => typeof flag.present !== 'boolean').map((flag) => inlineOf(flag.flag)),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function symptomLines(alarm, sections) {
|
|
32
|
+
const grade = [1, 2, 3].includes(sections?.grade) ? `G${sections.grade}` : 'grado no establecido';
|
|
33
|
+
const said = [
|
|
34
|
+
inlineOf(alarm?.symptom) || inlineOf(sections?.symptom),
|
|
35
|
+
grade,
|
|
36
|
+
inlineOf(alarm?.suspectedCondition),
|
|
37
|
+
URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel),
|
|
38
|
+
alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null,
|
|
39
|
+
].filter(Boolean);
|
|
40
|
+
const { present, absent, unassessed } = flagsByStatus(sections);
|
|
41
|
+
if (!present.length && !absent.length && !unassessed.length) return [`Síntoma: ${said.join(' · ')}`, 'Banderas rojas: no documentadas.'];
|
|
42
|
+
return [
|
|
43
|
+
`Síntoma: ${said.join(' · ')}`,
|
|
44
|
+
`Banderas rojas presentes: ${present.length ? present.join(', ') : 'ninguna'}.`,
|
|
45
|
+
`Banderas rojas ausentes: ${absent.length ? absent.join(', ') : 'ninguna revisada'}.`,
|
|
46
|
+
...(unassessed.length ? [`Banderas rojas sin evaluar: ${unassessed.join(', ')}.`] : []),
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function vitalsLine(vitals) {
|
|
51
|
+
const parts = [];
|
|
52
|
+
if (vitals?.temperatureC != null) parts.push(`T ${vitals.temperatureC} °C`);
|
|
53
|
+
if (vitals?.heartRate != null) parts.push(`FC ${vitals.heartRate} lpm`);
|
|
54
|
+
if (vitals?.systolic != null || vitals?.diastolic != null) parts.push(`PA ${vitals.systolic ?? '?'}/${vitals.diastolic ?? '?'} mmHg`);
|
|
55
|
+
if (vitals?.spo2 != null) parts.push(`SpO2 ${vitals.spo2}%`);
|
|
56
|
+
if (vitals?.respiratoryRate != null) parts.push(`FR ${vitals.respiratoryRate} rpm`);
|
|
57
|
+
return parts.length ? `Signos vitales: ${parts.join(' · ')}.` : 'Signos vitales: no reportados.';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function proposalItemLine(symptom, item) {
|
|
61
|
+
const entry = formularyFor(symptom);
|
|
62
|
+
const drug = entry ? findDrug(entry, item) : null;
|
|
63
|
+
if (!drug) return null;
|
|
64
|
+
const name = [drug.drug, drug.brand ? `(${drug.brand})` : null, drug.strength].filter(Boolean).join(' ');
|
|
65
|
+
const parts = [`- ${name}`];
|
|
66
|
+
if (drug.instructions) parts.push(drug.instructions);
|
|
67
|
+
parts.push(`posición en la tabla: ${drug.tableLabel}`);
|
|
68
|
+
const why = inlineOf(item?.justification?.text);
|
|
69
|
+
if (why) parts.push(`motivo: ${why}`);
|
|
70
|
+
return parts.join(' — ');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function proposalLines({ proposal, withheldReason }) {
|
|
74
|
+
if (!proposal?.items?.length) {
|
|
75
|
+
const reason = inlineOf(withheldReason) || 'sin propuesta farmacológica';
|
|
76
|
+
return [PROPOSAL_HEADING, `No se propone tratamiento sintomático: ${reason}. Se prioriza la valoración médica.`];
|
|
77
|
+
}
|
|
78
|
+
const lines = proposal.items.map((item) => proposalItemLine(proposal.symptom, item)).filter(Boolean);
|
|
79
|
+
const declared = [...(proposal.conditions ?? []), ...(proposal.ruledOut ?? []).map((key) => `descartado: ${key}`)].map(inlineOf).filter(Boolean);
|
|
80
|
+
if (declared.length) lines.push(`Condiciones que se declararon para esta propuesta (verificar): ${declared.join(', ')}.`);
|
|
81
|
+
return [PROPOSAL_HEADING, ...lines];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function composeDoctorBody({ alarm, sections, proposal, withheldReason }) {
|
|
85
|
+
const context = sections?.oncologyContext;
|
|
86
|
+
const value = (text) => inlineOf(text) || 'no disponible';
|
|
87
|
+
return [
|
|
88
|
+
...symptomLines(alarm, sections),
|
|
89
|
+
'',
|
|
90
|
+
`Caracterización: ${inlineOf(sections?.characterizationSummary) || 'no disponible'}`,
|
|
91
|
+
vitalsLine(sections?.vitals),
|
|
92
|
+
`Datos objetivos: ${inlineOf(sections?.objectiveData) || 'no disponibles'}`,
|
|
93
|
+
'',
|
|
94
|
+
`Contexto oncológico: tratamiento ${value(context?.treatment)}; última dosis ${value(context?.lastDose)}.`,
|
|
95
|
+
`Manejo previo y respuesta: ${value(context?.priorManagement)}; respuesta ${value(context?.response)}.`,
|
|
96
|
+
'',
|
|
97
|
+
...proposalLines({ proposal, withheldReason }),
|
|
98
|
+
'',
|
|
99
|
+
proposal?.items?.length ? REQUESTED_ACTION : ASSESSMENT_ACTION,
|
|
100
|
+
].join('\n');
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function renderDoctorMessage({ identity, review, doctorText, link }) {
|
|
104
|
+
const phone = String(review?.patientCode ?? '').replace(/^whatsapp:/, '');
|
|
105
|
+
return [
|
|
106
|
+
`Paciente: ${identity.patientName} · ${phone}`,
|
|
107
|
+
`Médico tratante: ${withTitle(identity.treatingDoctor)}`,
|
|
108
|
+
String(doctorText ?? '').trim(),
|
|
109
|
+
'',
|
|
110
|
+
link,
|
|
111
|
+
].join('\n');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function templateSummary(review) {
|
|
115
|
+
const alarm = latestAlarm(review);
|
|
116
|
+
if (!alarm) return 'sin alarma registrada';
|
|
117
|
+
return [inlineOf(alarm.symptom), URGENCY_LABELS[alarm.urgencyLevel] ?? inlineOf(alarm.urgencyLevel)].filter(Boolean).join(' · ');
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
module.exports = {
|
|
121
|
+
REQUESTED_ACTION,
|
|
122
|
+
ASSESSMENT_ACTION,
|
|
123
|
+
flagsByStatus,
|
|
124
|
+
latestAlarm,
|
|
125
|
+
composeDoctorBody,
|
|
126
|
+
renderDoctorMessage,
|
|
127
|
+
templateSummary,
|
|
128
|
+
};
|
|
@@ -2,8 +2,6 @@ const FORMULARY_VERSION = '2026-09-28';
|
|
|
2
2
|
|
|
3
3
|
const MEDICAL_REVIEW = 'valoración médica';
|
|
4
4
|
|
|
5
|
-
const JUSTIFICATION_KINDS = Object.freeze(['prior_failure', 'contraindication', 'context']);
|
|
6
|
-
|
|
7
5
|
function deepFreeze(value) {
|
|
8
6
|
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
9
7
|
Object.freeze(value);
|
|
@@ -365,8 +363,6 @@ const byKey = new Map(TREATMENT_FORMULARY.map((entry) => [entry.key, entry]));
|
|
|
365
363
|
|
|
366
364
|
const normalize = (value) => String(value ?? '').trim().toLowerCase();
|
|
367
365
|
|
|
368
|
-
const asSet = (values) => new Set((Array.isArray(values) ? values : []).map(normalize));
|
|
369
|
-
|
|
370
366
|
function formularyFor(symptomKey) {
|
|
371
367
|
return byKey.get(String(symptomKey ?? '').trim()) ?? null;
|
|
372
368
|
}
|
|
@@ -378,96 +374,14 @@ function findDrug(entry, item) {
|
|
|
378
374
|
const brand = normalize(item?.brand);
|
|
379
375
|
const strength = compact(item?.strength);
|
|
380
376
|
const candidates = entry.drugs.filter((candidate) => normalize(candidate.drug) === drug
|
|
381
|
-
&& (!strength ||
|
|
377
|
+
&& (!strength || compact(candidate.strength) === strength));
|
|
382
378
|
if (candidates.length <= 1) return candidates[0] ?? null;
|
|
383
379
|
return candidates.find((candidate) => (brand && normalize(candidate.brand) === brand) || (strength && compact(candidate.strength) === strength)) ?? null;
|
|
384
380
|
}
|
|
385
381
|
|
|
386
|
-
function moleculesOf(drug) {
|
|
387
|
-
return drug.drug.split('/').map((part) => normalize(part).split(' ')[0]).filter(Boolean);
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
function hasAny(set, keys = []) {
|
|
391
|
-
return keys.some((key) => set.has(normalize(key)));
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function validateProposal(proposal, context = {}) {
|
|
395
|
-
const issues = [];
|
|
396
|
-
const entry = formularyFor(proposal?.symptom);
|
|
397
|
-
if (!entry) return { valid: false, issues: [`síntoma sin formulario: ${proposal?.symptom ?? '(vacío)'}`] };
|
|
398
|
-
|
|
399
|
-
const items = Array.isArray(proposal?.items) ? proposal.items : [];
|
|
400
|
-
const modifiers = asSet(context.modifiers);
|
|
401
|
-
const conditions = asSet(context.conditions);
|
|
402
|
-
const ruledOut = asSet(context.ruledOut);
|
|
403
|
-
|
|
404
|
-
const activeModifiers = (entry.algorithmModifiers ?? []).filter((key) => modifiers.has(key));
|
|
405
|
-
const pendingRuleOut = (entry.requiresRuledOut ?? []).filter((key) => !ruledOut.has(key));
|
|
406
|
-
|
|
407
|
-
if (activeModifiers.length && items.length) {
|
|
408
|
-
issues.push(`no proponer tratamiento sintomático con ${activeModifiers.join(', ')}: priorizar valoración`);
|
|
409
|
-
}
|
|
410
|
-
if (pendingRuleOut.length && items.length) {
|
|
411
|
-
issues.push(`no proponer tratamiento sintomático sin descartar ${pendingRuleOut.join(', ')}`);
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
const classes = new Map();
|
|
415
|
-
const molecules = new Map();
|
|
416
|
-
for (const item of items) {
|
|
417
|
-
const excluded = (entry.excluded ?? []).find((rule) => rule.drugs.some((name) => normalize(name) === normalize(item?.drug)));
|
|
418
|
-
if (excluded) {
|
|
419
|
-
issues.push(`${item.drug}: ${excluded.reason}`);
|
|
420
|
-
continue;
|
|
421
|
-
}
|
|
422
|
-
|
|
423
|
-
const drug = findDrug(entry, item);
|
|
424
|
-
if (!drug) {
|
|
425
|
-
issues.push(`${[item?.drug ?? '(sin fármaco)', item?.strength].filter(Boolean).join(' ')} no está en la tabla para ${entry.label}`);
|
|
426
|
-
continue;
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
for (const molecule of moleculesOf(drug)) {
|
|
430
|
-
if (molecules.has(molecule) && molecules.get(molecule) !== drug.drug) {
|
|
431
|
-
issues.push(`${molecule} aparece dos veces: ${molecules.get(molecule)} y ${drug.drug}`);
|
|
432
|
-
}
|
|
433
|
-
molecules.set(molecule, drug.drug);
|
|
434
|
-
}
|
|
435
|
-
|
|
436
|
-
if (classes.has(drug.class)) {
|
|
437
|
-
issues.push(`un solo fármaco por clase (${drug.class}): ${classes.get(drug.class)} y ${drug.drug}`);
|
|
438
|
-
} else {
|
|
439
|
-
classes.set(drug.class, drug.drug);
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
if (drug.position === 'NO_RUTINA' && !hasAny(conditions, drug.exceptWhen)) {
|
|
443
|
-
issues.push(`${drug.drug} es NO RUTINA y no se propone como tratamiento inicial`);
|
|
444
|
-
}
|
|
445
|
-
if (drug.onlyWhen && !hasAny(conditions, drug.onlyWhen)) {
|
|
446
|
-
issues.push(`${drug.drug} solo aplica con ${drug.onlyWhen.join(' / ')}`);
|
|
447
|
-
}
|
|
448
|
-
const avoided = (drug.avoidWhen ?? []).filter((key) => conditions.has(key));
|
|
449
|
-
if (avoided.length) {
|
|
450
|
-
issues.push(`${drug.drug} está excluido por ${avoided.join(', ')}`);
|
|
451
|
-
}
|
|
452
|
-
|
|
453
|
-
const justification = item?.justification;
|
|
454
|
-
const justified = JUSTIFICATION_KINDS.includes(justification?.kind) && String(justification?.text ?? '').trim().length > 0;
|
|
455
|
-
if ((drug.position === 'ALT' || drug.position === '2L+') && !justified) {
|
|
456
|
-
issues.push(`${drug.drug} es ${drug.tableLabel}: explicar por qué no se usa la 1L (fallo previo, contraindicación o contexto)`);
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
for (const rule of entry.requiresWhen ?? []) {
|
|
461
|
-
if (!conditions.has(normalize(rule.condition)) || !items.length) continue;
|
|
462
|
-
if (!items.some((item) => normalize(item?.drug) === normalize(rule.drug))) issues.push(rule.note);
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
return { valid: issues.length === 0, issues, activeModifiers, pendingRuleOut, alwaysEscalate: entry.alwaysEscalate ?? null };
|
|
466
|
-
}
|
|
467
|
-
|
|
468
382
|
module.exports = {
|
|
469
383
|
FORMULARY_VERSION,
|
|
470
384
|
TREATMENT_FORMULARY,
|
|
471
385
|
formularyFor,
|
|
472
|
-
|
|
386
|
+
findDrug,
|
|
473
387
|
};
|
|
@@ -4,6 +4,7 @@ const { FORMULARY_VERSION, TREATMENT_FORMULARY } = require('../protocols/treatme
|
|
|
4
4
|
|
|
5
5
|
const { createLLMProvider } = require('../providers/createLLMProvider');
|
|
6
6
|
|
|
7
|
+
const { composeDoctorBody, flagsByStatus } = require('../helpers/doctorReviewMessageHelper');
|
|
7
8
|
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
8
9
|
|
|
9
10
|
const { getEscalationContext } = require('../../services/escalationContextService');
|
|
@@ -12,13 +13,39 @@ const { logger } = require('../../utils/logger');
|
|
|
12
13
|
const { safeParse } = require('../../utils/jsonUtils');
|
|
13
14
|
const { withTiming } = require('../../utils/tracingDecorator');
|
|
14
15
|
|
|
16
|
+
const { drugsNamedIn, validateProposal } = require('./treatmentProposalService');
|
|
17
|
+
|
|
15
18
|
const CONVERSATION_TURNS = 40;
|
|
16
19
|
const TRIAGE_LIMIT = 3;
|
|
17
20
|
const CALL_LOG_LIMIT = 10;
|
|
18
21
|
|
|
19
22
|
const trimmed = (value) => String(value ?? '').trim();
|
|
20
23
|
|
|
21
|
-
function
|
|
24
|
+
function withholdReason(sections) {
|
|
25
|
+
const { present, unassessed } = flagsByStatus(sections);
|
|
26
|
+
const modifiers = (Array.isArray(sections?.treatmentModifiers) ? sections.treatmentModifiers : []).map(trimmed).filter(Boolean);
|
|
27
|
+
const reasons = [];
|
|
28
|
+
if (present.length) reasons.push(`bandera roja presente (${present.join(', ')})`);
|
|
29
|
+
if (unassessed.length) reasons.push(`bandera roja sin evaluar (${unassessed.join(', ')})`);
|
|
30
|
+
if (modifiers.length) reasons.push(`condición que cambia el algoritmo (${modifiers.join(', ')})`);
|
|
31
|
+
return reasons.join('; ') || null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function settleProposal(parsed) {
|
|
35
|
+
const withheld = withholdReason(parsed);
|
|
36
|
+
const raw = parsed?.treatmentProposal;
|
|
37
|
+
const items = Array.isArray(raw?.items) ? raw.items : [];
|
|
38
|
+
if (withheld) return { proposal: null, withheldReason: withheld, strippedItems: items.length };
|
|
39
|
+
if (!items.length) return { proposal: null, withheldReason: trimmed(parsed?.proposalWithheldReason) || null, strippedItems: 0 };
|
|
40
|
+
|
|
41
|
+
const conditions = Array.isArray(raw.conditions) ? raw.conditions : [];
|
|
42
|
+
const ruledOut = Array.isArray(raw.ruledOut) ? raw.ruledOut : [];
|
|
43
|
+
const proposal = { symptom: raw.symptom, items, conditions, ruledOut };
|
|
44
|
+
const { valid, issues } = validateProposal(proposal, { conditions, ruledOut });
|
|
45
|
+
return valid ? { proposal, withheldReason: null, strippedItems: 0 } : { invalid: issues };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function buildDraftInput({ context, callLogs, protocol, alarms = [] }) {
|
|
22
49
|
const conversation = Array.isArray(context?.conversation)
|
|
23
50
|
? context.conversation.slice(-CONVERSATION_TURNS)
|
|
24
51
|
: context?.conversation ?? null;
|
|
@@ -30,6 +57,7 @@ function buildDraftInput({ context, callLogs, protocol }) {
|
|
|
30
57
|
return {
|
|
31
58
|
protocolVersion: FORMULARY_VERSION,
|
|
32
59
|
protocol,
|
|
60
|
+
alarms,
|
|
33
61
|
patient: {
|
|
34
62
|
clinicalContext: context?.agentContext ?? null,
|
|
35
63
|
conversation,
|
|
@@ -55,7 +83,7 @@ function draftProvider() {
|
|
|
55
83
|
}
|
|
56
84
|
}
|
|
57
85
|
|
|
58
|
-
async function generateEscalationDraft({ code, callLogs = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
|
|
86
|
+
async function generateEscalationDraft({ code, callLogs = [], alarms = [], provider, trace = null, reviewId = null, now = Date.now() } = {}) {
|
|
59
87
|
const { presetId } = await getEscalationDraft();
|
|
60
88
|
const llm = provider ?? draftProvider();
|
|
61
89
|
|
|
@@ -64,7 +92,7 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
|
|
|
64
92
|
}
|
|
65
93
|
|
|
66
94
|
const context = await getEscalationContext({ code, now });
|
|
67
|
-
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY });
|
|
95
|
+
const input = buildDraftInput({ context, callLogs, protocol: TREATMENT_FORMULARY, alarms });
|
|
68
96
|
|
|
69
97
|
// Past this point a generation run was issued. Whether the request actually left the process is
|
|
70
98
|
// not knowable here — the provider resolves the preset and validates the schema before it calls
|
|
@@ -91,8 +119,24 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
|
|
|
91
119
|
}
|
|
92
120
|
|
|
93
121
|
const parsed = safeParse(readStructuredText(result), null);
|
|
94
|
-
const doctorText = trimmed(parsed?.doctorText);
|
|
95
122
|
const patientMessage = trimmed(parsed?.patientMessage);
|
|
123
|
+
if (!trimmed(parsed?.characterizationSummary)) {
|
|
124
|
+
logger.warn('[escalationDraft] generation did not return the sectioned doctor draft', { reviewId });
|
|
125
|
+
return { completed: false, attempted: true, reason: 'the model did not return the sectioned doctor draft (characterizationSummary missing)' };
|
|
126
|
+
}
|
|
127
|
+
const settled = settleProposal(parsed);
|
|
128
|
+
|
|
129
|
+
const patientDrugs = settled.proposal ? [] : drugsNamedIn(patientMessage);
|
|
130
|
+
if (!settled.invalid && patientDrugs.length) {
|
|
131
|
+
settled.invalid = [`el mensaje al paciente menciona ${patientDrugs.join(', ')} aunque no hay propuesta de tratamiento`];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (settled.invalid) {
|
|
135
|
+
logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues: settled.invalid });
|
|
136
|
+
return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${settled.invalid.join('; ')}` };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const doctorText = composeDoctorBody({ alarm: alarms[alarms.length - 1] ?? null, sections: parsed, proposal: settled.proposal, withheldReason: settled.withheldReason });
|
|
96
140
|
|
|
97
141
|
if (!doctorText || !patientMessage) {
|
|
98
142
|
logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
|
|
@@ -104,6 +148,9 @@ async function generateEscalationDraft({ code, callLogs = [], provider, trace =
|
|
|
104
148
|
attempted: true,
|
|
105
149
|
doctorText,
|
|
106
150
|
patientMessage,
|
|
151
|
+
proposal: settled.proposal,
|
|
152
|
+
proposalWithheldReason: settled.withheldReason,
|
|
153
|
+
...(settled.strippedItems ? { proposalStripped: settled.strippedItems } : {}),
|
|
107
154
|
protocolVersion: FORMULARY_VERSION,
|
|
108
155
|
sectionsUnavailable: context.degradedSections ?? [],
|
|
109
156
|
};
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
const { TREATMENT_FORMULARY, findDrug, formularyFor } = require('../protocols/treatmentFormulary');
|
|
2
|
+
|
|
3
|
+
const { normalizeForAnchor: key } = require('../../utils/textMatchUtils');
|
|
4
|
+
|
|
5
|
+
const JUSTIFICATION_KINDS = Object.freeze(['prior_failure', 'contraindication', 'context']);
|
|
6
|
+
|
|
7
|
+
const asSet = (values) => new Set((Array.isArray(values) ? values : []).map(key));
|
|
8
|
+
|
|
9
|
+
function moleculesOf(drug) {
|
|
10
|
+
return drug.drug.split('/').map((part) => key(part).split(' ')[0]).filter(Boolean);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function hasAny(set, keys = []) {
|
|
14
|
+
return keys.some((name) => set.has(key(name)));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function validateProposal(proposal, context = {}) {
|
|
18
|
+
const issues = [];
|
|
19
|
+
const entry = formularyFor(proposal?.symptom);
|
|
20
|
+
if (!entry) return { valid: false, issues: [`síntoma sin formulario: ${proposal?.symptom ?? '(vacío)'}`] };
|
|
21
|
+
|
|
22
|
+
const items = Array.isArray(proposal?.items) ? proposal.items : [];
|
|
23
|
+
const modifiers = asSet(context.modifiers);
|
|
24
|
+
const conditions = asSet(context.conditions);
|
|
25
|
+
const ruledOut = asSet(context.ruledOut);
|
|
26
|
+
|
|
27
|
+
const activeModifiers = (entry.algorithmModifiers ?? []).filter((name) => modifiers.has(key(name)));
|
|
28
|
+
const pendingRuleOut = (entry.requiresRuledOut ?? []).filter((name) => !ruledOut.has(key(name)));
|
|
29
|
+
|
|
30
|
+
if (activeModifiers.length && items.length) {
|
|
31
|
+
issues.push(`no proponer tratamiento sintomático con ${activeModifiers.join(', ')}: priorizar valoración`);
|
|
32
|
+
}
|
|
33
|
+
if (pendingRuleOut.length && items.length) {
|
|
34
|
+
issues.push(`no proponer tratamiento sintomático sin descartar ${pendingRuleOut.join(', ')}`);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const classes = new Map();
|
|
38
|
+
const molecules = new Map();
|
|
39
|
+
for (const item of items) {
|
|
40
|
+
const excluded = (entry.excluded ?? []).find((rule) => rule.drugs.some((name) => key(name) === key(item?.drug)));
|
|
41
|
+
if (excluded) {
|
|
42
|
+
issues.push(`${item.drug}: ${excluded.reason}`);
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const drug = findDrug(entry, item);
|
|
47
|
+
if (!drug) {
|
|
48
|
+
issues.push(`${[item?.drug ?? '(sin fármaco)', item?.strength].filter(Boolean).join(' ')} no está en la tabla para ${entry.label}`);
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
for (const molecule of moleculesOf(drug)) {
|
|
53
|
+
if (molecules.has(molecule) && molecules.get(molecule) !== drug.drug) {
|
|
54
|
+
issues.push(`${molecule} aparece dos veces: ${molecules.get(molecule)} y ${drug.drug}`);
|
|
55
|
+
}
|
|
56
|
+
molecules.set(molecule, drug.drug);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (classes.has(drug.class)) {
|
|
60
|
+
issues.push(`un solo fármaco por clase (${drug.class}): ${classes.get(drug.class)} y ${drug.drug}`);
|
|
61
|
+
} else {
|
|
62
|
+
classes.set(drug.class, drug.drug);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (drug.position === 'NO_RUTINA' && !hasAny(conditions, drug.exceptWhen)) {
|
|
66
|
+
issues.push(`${drug.drug} es NO RUTINA y no se propone como tratamiento inicial`);
|
|
67
|
+
}
|
|
68
|
+
if (drug.onlyWhen && !hasAny(conditions, drug.onlyWhen)) {
|
|
69
|
+
issues.push(`${drug.drug} solo aplica con ${drug.onlyWhen.join(' / ')}`);
|
|
70
|
+
}
|
|
71
|
+
const avoided = (drug.avoidWhen ?? []).filter((name) => conditions.has(key(name)));
|
|
72
|
+
if (avoided.length) {
|
|
73
|
+
issues.push(`${drug.drug} está excluido por ${avoided.join(', ')}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const justification = item?.justification;
|
|
77
|
+
const justified = JUSTIFICATION_KINDS.includes(justification?.kind) && String(justification?.text ?? '').trim().length > 0;
|
|
78
|
+
if ((drug.position === 'ALT' || drug.position === '2L+') && !justified) {
|
|
79
|
+
issues.push(`${drug.drug} es ${drug.tableLabel}: explicar por qué no se usa la 1L (fallo previo, contraindicación o contexto)`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
for (const rule of entry.requiresWhen ?? []) {
|
|
84
|
+
if (!conditions.has(key(rule.condition)) || !items.length) continue;
|
|
85
|
+
if (!items.some((item) => key(item?.drug) === key(rule.drug))) issues.push(rule.note);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return { valid: issues.length === 0, issues, activeModifiers, pendingRuleOut, alwaysEscalate: entry.alwaysEscalate ?? null };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const DRUG_NAMES = [...new Set(TREATMENT_FORMULARY
|
|
92
|
+
.flatMap((entry) => entry.drugs)
|
|
93
|
+
.filter((drug) => drug.isPharmacological !== false)
|
|
94
|
+
.flatMap((drug) => [drug.drug, ...String(drug.brand ?? '').split('/')])
|
|
95
|
+
.map(key)
|
|
96
|
+
.filter((name) => name.length >= 4))];
|
|
97
|
+
|
|
98
|
+
function drugsNamedIn(text) {
|
|
99
|
+
const padded = ` ${key(text)} `;
|
|
100
|
+
return DRUG_NAMES.filter((name) => padded.includes(` ${name} `));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
module.exports = {
|
|
104
|
+
validateProposal,
|
|
105
|
+
drugsNamedIn,
|
|
106
|
+
};
|
|
@@ -56,6 +56,7 @@ const doctorHandoffSchema = new mongoose.Schema({
|
|
|
56
56
|
physicianEmail: { type: String, default: null },
|
|
57
57
|
transport: { type: String, enum: [null, 'text', 'template'], default: null },
|
|
58
58
|
messageId: { type: String, default: null },
|
|
59
|
+
message: { type: String, default: null },
|
|
59
60
|
sentBy: { type: String, required: true },
|
|
60
61
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
61
62
|
|
|
@@ -91,6 +92,12 @@ const interruptionResolutionSchema = new mongoose.Schema({
|
|
|
91
92
|
notes: { type: String, required: true },
|
|
92
93
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
93
94
|
|
|
95
|
+
const identityBlockSchema = new mongoose.Schema({
|
|
96
|
+
missing: { type: [String], default: [] },
|
|
97
|
+
blockedAt: { type: Date, required: true },
|
|
98
|
+
blockedBy: { type: String, required: true },
|
|
99
|
+
}, { _id: false });
|
|
100
|
+
|
|
94
101
|
const escalationReviewSchema = new mongoose.Schema({
|
|
95
102
|
patientCode: { type: String, required: true },
|
|
96
103
|
patientCaseRecordId: { type: String, default: null },
|
|
@@ -126,6 +133,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
126
133
|
patientDelivery: { type: patientDeliverySchema, default: null },
|
|
127
134
|
pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
|
|
128
135
|
interruptionResolution: { type: interruptionResolutionSchema, default: null },
|
|
136
|
+
identityBlock: { type: identityBlockSchema, default: null },
|
|
129
137
|
closedBy: { type: String, default: null },
|
|
130
138
|
closedAt: { type: Date, default: null },
|
|
131
139
|
cancellationReason: { type: String, default: null },
|
|
@@ -5,7 +5,6 @@ const { httpError, requiredText } = require('../utils/httpErrorUtils');
|
|
|
5
5
|
const { inlineOf } = require('../utils/coercionUtils');
|
|
6
6
|
const { logger } = require('../utils/logger');
|
|
7
7
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
8
|
-
const { mexicoStamp } = require('../utils/dateUtils');
|
|
9
8
|
const { isoDay } = require('../utils/dateUtils');
|
|
10
9
|
const {
|
|
11
10
|
CALL_OUTCOMES,
|
|
@@ -21,6 +20,8 @@ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
|
21
20
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
22
21
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
23
22
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
23
|
+
const { writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
24
|
+
const { renderDoctorMessage, templateSummary } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
24
25
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
25
26
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
26
27
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
@@ -296,42 +297,62 @@ async function syncCase(review, operator, requestId) {
|
|
|
296
297
|
}
|
|
297
298
|
}
|
|
298
299
|
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
300
|
+
function doctorLink(review) {
|
|
301
|
+
return `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
|
|
302
|
+
}
|
|
302
303
|
|
|
303
|
-
function
|
|
304
|
-
const
|
|
305
|
-
const
|
|
306
|
-
const
|
|
304
|
+
function doctorIdentity(patient) {
|
|
305
|
+
const patientName = inlineOf(patient?.name);
|
|
306
|
+
const treatingDoctor = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
|
|
307
|
+
const missing = [];
|
|
308
|
+
if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
|
|
309
|
+
if (!treatingDoctor) missing.push('médico tratante');
|
|
310
|
+
return { patientName, treatingDoctor, missing };
|
|
311
|
+
}
|
|
307
312
|
|
|
308
|
-
|
|
309
|
-
|
|
313
|
+
async function readDoctorIdentity(review) {
|
|
314
|
+
let patient;
|
|
315
|
+
try {
|
|
316
|
+
patient = await getPatientInformation(review.patientCode);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
logger.error('[EscalationReview] The patient record could not be read for the doctor message', {
|
|
319
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
320
|
+
});
|
|
321
|
+
throw httpError(503, 'The patient record could not be read; the doctor message needs the patient name and the treating doctor');
|
|
322
|
+
}
|
|
323
|
+
return doctorIdentity(patient);
|
|
324
|
+
}
|
|
310
325
|
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
326
|
+
async function blockForMissingIdentity({ review, missing, operator }) {
|
|
327
|
+
const blocked = `El mensaje al médico no se envió: falta ${missing.join(' y ')} en el expediente`;
|
|
328
|
+
await getEscalationReview().updateOne(
|
|
329
|
+
{ _id: review._id },
|
|
330
|
+
{ $set: { identityBlock: { missing, blockedAt: new Date(), blockedBy: operator } } },
|
|
331
|
+
);
|
|
332
|
+
const { written, duplicate } = await writeUnresolvedRequest({
|
|
333
|
+
code: review.patientCode,
|
|
334
|
+
trace: null,
|
|
335
|
+
question: blocked,
|
|
336
|
+
details: `Revisión de escalación ${review._id}: completa ${missing.join(' y ')} en estado_general y vuelve a enviar al médico.`,
|
|
337
|
+
category: 'contact_team_member',
|
|
338
|
+
urgency: 'soon',
|
|
339
|
+
});
|
|
340
|
+
if (!written && !duplicate) {
|
|
341
|
+
logger.error('[EscalationReview] A doctor message was blocked for missing identity and the team ticket was not written', {
|
|
342
|
+
escalationReviewId: String(review._id), missing,
|
|
343
|
+
});
|
|
320
344
|
}
|
|
321
|
-
|
|
345
|
+
throw httpError(422, blocked);
|
|
322
346
|
}
|
|
323
347
|
|
|
324
|
-
async function sendDoctorAlert({
|
|
348
|
+
async function sendDoctorAlert({ message, approver, operator }) {
|
|
325
349
|
const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
|
|
326
350
|
if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
|
|
327
|
-
const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
|
|
328
351
|
const inWindow = await isWithin24HourWindow(doctorCode);
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
: { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
|
|
334
|
-
const result = await sendMessage(message);
|
|
352
|
+
const outgoing = inWindow
|
|
353
|
+
? { code: doctorCode, body: message.body, triggeredBy: operator }
|
|
354
|
+
: { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID'), variables: message.template, triggeredBy: operator };
|
|
355
|
+
const result = await sendMessage(outgoing);
|
|
335
356
|
if (!result?.success && !result?.completed) {
|
|
336
357
|
throw httpError(502, 'The WhatsApp message to the physician could not be sent');
|
|
337
358
|
}
|
|
@@ -636,6 +657,7 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
|
|
|
636
657
|
const draft = await generateEscalationDraft({
|
|
637
658
|
code: review.patientCode,
|
|
638
659
|
callLogs: review.callLogs ?? [],
|
|
660
|
+
alarms: review.alarms ?? [],
|
|
639
661
|
reviewId: String(review._id),
|
|
640
662
|
});
|
|
641
663
|
// A generation run sends the patient's context to a model. That is what the audit exists to
|
|
@@ -866,13 +888,34 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
866
888
|
if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
|
|
867
889
|
}
|
|
868
890
|
|
|
891
|
+
const draftedAt = draft.createdAt ? new Date(draft.createdAt).getTime() : null;
|
|
892
|
+
if (draftedAt && (review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > draftedAt)) {
|
|
893
|
+
throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
|
|
894
|
+
}
|
|
895
|
+
const identity = await readDoctorIdentity(review);
|
|
896
|
+
if (identity.missing.length) await blockForMissingIdentity({ review, missing: identity.missing, operator });
|
|
897
|
+
const link = doctorLink(review);
|
|
898
|
+
const message = {
|
|
899
|
+
body: renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link }),
|
|
900
|
+
template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
|
|
901
|
+
};
|
|
902
|
+
|
|
869
903
|
const claim = newOperationClaim();
|
|
870
|
-
await updateReview(
|
|
904
|
+
await updateReview(
|
|
905
|
+
reviewId,
|
|
906
|
+
[review.status],
|
|
907
|
+
{ $set: { status: 'handing_off', operationClaim: claim } },
|
|
908
|
+
{ drafts: { $size: draftNumber }, alarms: { $size: (review.alarms ?? []).length } },
|
|
909
|
+
);
|
|
871
910
|
let delivery = {};
|
|
872
911
|
let updated;
|
|
873
912
|
try {
|
|
874
|
-
if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({
|
|
875
|
-
const
|
|
913
|
+
if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
|
|
914
|
+
const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : message.body;
|
|
915
|
+
const handoff = {
|
|
916
|
+
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, sentBy: operator } },
|
|
917
|
+
$unset: { identityBlock: '' },
|
|
918
|
+
};
|
|
876
919
|
const recordUpdate = withCaseMirror(review, handoff, { status: 'en revision_medica' });
|
|
877
920
|
updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
|
|
878
921
|
} catch (error) {
|