@peopl-health/nexus 5.58.0-dev.10249 → 5.58.0-dev.10496
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 +147 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +1 -0
- package/lib/clinical/protocols/treatmentFormulary.js +474 -0
- package/lib/clinical/providers/AnthropicProvider.js +2 -2
- package/lib/clinical/providers/OpenAIResponsesProvider.js +2 -2
- package/lib/clinical/services/escalationDraftService.js +37 -7
- package/lib/clinical/services/triageRecommendationService.js +17 -1
- package/lib/controllers/officeAssistantController.js +4 -2
- package/lib/helpers/sendClaimHelper.js +3 -2
- package/lib/index.d.ts +4 -2
- package/lib/models/escalationReviewModel.js +8 -0
- package/lib/services/escalationReviewService.js +66 -32
- package/lib/services/officeAssistantService.js +62 -11
- package/lib/storage/MongoStorage.js +1 -0
- package/package.json +1 -1
- package/lib/clinical/protocols/symptomReliefProtocol.js +0 -216
|
@@ -0,0 +1,147 @@
|
|
|
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 clean = (value) => inlineOf(value);
|
|
15
|
+
|
|
16
|
+
const withTitle = (name) => (DOCTOR_TITLE.test(name) ? name : `Dr./Dra. ${name}`);
|
|
17
|
+
|
|
18
|
+
function doctorIdentity(patient) {
|
|
19
|
+
const patientName = clean(patient?.name);
|
|
20
|
+
const treatingDoctor = clean(patient?.doctor) || clean(patient?.doctor_auna);
|
|
21
|
+
const missing = [];
|
|
22
|
+
if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
|
|
23
|
+
if (!treatingDoctor) missing.push('médico tratante');
|
|
24
|
+
return { patientName, treatingDoctor, missing };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function latestAlarm(review) {
|
|
28
|
+
const alarms = Array.isArray(review?.alarms) ? review.alarms : [];
|
|
29
|
+
return alarms[alarms.length - 1] ?? null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function presentRedFlags(sections) {
|
|
33
|
+
return (Array.isArray(sections?.redFlags) ? sections.redFlags : [])
|
|
34
|
+
.filter((flag) => flag?.present === true)
|
|
35
|
+
.map((flag) => clean(flag.flag))
|
|
36
|
+
.filter(Boolean);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function withholdReason(sections) {
|
|
40
|
+
const present = presentRedFlags(sections);
|
|
41
|
+
const modifiers = (Array.isArray(sections?.treatmentModifiers) ? sections.treatmentModifiers : []).map(clean).filter(Boolean);
|
|
42
|
+
const reasons = [];
|
|
43
|
+
if (present.length) reasons.push(`bandera roja presente (${present.join(', ')})`);
|
|
44
|
+
if (modifiers.length) reasons.push(`condición que cambia el algoritmo (${modifiers.join(', ')})`);
|
|
45
|
+
return reasons.join('; ') || null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function symptomLines(alarm, sections) {
|
|
49
|
+
const grade = [1, 2, 3].includes(sections?.grade) ? `G${sections.grade}` : 'grado no establecido';
|
|
50
|
+
const said = [
|
|
51
|
+
clean(alarm?.symptom) || clean(sections?.symptom),
|
|
52
|
+
grade,
|
|
53
|
+
clean(alarm?.suspectedCondition),
|
|
54
|
+
URGENCY_LABELS[alarm?.urgencyLevel] ?? clean(alarm?.urgencyLevel),
|
|
55
|
+
alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null,
|
|
56
|
+
].filter(Boolean);
|
|
57
|
+
const flags = Array.isArray(sections?.redFlags) ? sections.redFlags : [];
|
|
58
|
+
if (!flags.length) return [`Síntoma: ${said.join(' · ')}`, 'Banderas rojas: no documentadas.'];
|
|
59
|
+
const present = presentRedFlags(sections);
|
|
60
|
+
const absent = flags.filter((flag) => flag?.present !== true).map((flag) => clean(flag?.flag)).filter(Boolean);
|
|
61
|
+
return [
|
|
62
|
+
`Síntoma: ${said.join(' · ')}`,
|
|
63
|
+
`Banderas rojas presentes: ${present.length ? present.join(', ') : 'ninguna'}.`,
|
|
64
|
+
`Banderas rojas ausentes: ${absent.length ? absent.join(', ') : 'ninguna revisada'}.`,
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function vitalsLine(vitals) {
|
|
69
|
+
const parts = [];
|
|
70
|
+
if (vitals?.temperatureC != null) parts.push(`T ${vitals.temperatureC} °C`);
|
|
71
|
+
if (vitals?.heartRate != null) parts.push(`FC ${vitals.heartRate} lpm`);
|
|
72
|
+
if (vitals?.systolic != null || vitals?.diastolic != null) parts.push(`PA ${vitals.systolic ?? '?'}/${vitals.diastolic ?? '?'} mmHg`);
|
|
73
|
+
if (vitals?.spo2 != null) parts.push(`SpO2 ${vitals.spo2}%`);
|
|
74
|
+
if (vitals?.respiratoryRate != null) parts.push(`FR ${vitals.respiratoryRate} rpm`);
|
|
75
|
+
return parts.length ? `Signos vitales: ${parts.join(' · ')}.` : 'Signos vitales: no reportados.';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function proposalItemLine(symptom, item) {
|
|
79
|
+
const entry = formularyFor(symptom);
|
|
80
|
+
const drug = entry ? findDrug(entry, item) : null;
|
|
81
|
+
if (!drug) return null;
|
|
82
|
+
const name = [drug.drug, drug.brand ? `(${drug.brand})` : null, drug.strength].filter(Boolean).join(' ');
|
|
83
|
+
const parts = [`- ${name}`];
|
|
84
|
+
if (drug.instructions) parts.push(drug.instructions);
|
|
85
|
+
parts.push(`posición en la tabla: ${drug.tableLabel}`);
|
|
86
|
+
const why = clean(item?.justification?.text);
|
|
87
|
+
if (why) parts.push(`motivo: ${why}`);
|
|
88
|
+
return parts.join(' — ');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function proposalLines({ proposal, withheldReason }) {
|
|
92
|
+
if (!proposal?.items?.length) {
|
|
93
|
+
const reason = clean(withheldReason) || 'sin propuesta farmacológica';
|
|
94
|
+
return [PROPOSAL_HEADING, `No se propone tratamiento sintomático: ${reason}. Se prioriza la valoración médica.`];
|
|
95
|
+
}
|
|
96
|
+
const lines = proposal.items.map((item) => proposalItemLine(proposal.symptom, item)).filter(Boolean);
|
|
97
|
+
const declared = [...(proposal.conditions ?? []), ...(proposal.ruledOut ?? []).map((key) => `descartado: ${key}`)].map(clean).filter(Boolean);
|
|
98
|
+
if (declared.length) lines.push(`Condiciones que se declararon para esta propuesta (verificar): ${declared.join(', ')}.`);
|
|
99
|
+
return [PROPOSAL_HEADING, ...lines];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function composeDoctorBody({ alarm, sections, proposal, withheldReason }) {
|
|
103
|
+
const context = sections?.oncologyContext;
|
|
104
|
+
const value = (text) => clean(text) || 'no disponible';
|
|
105
|
+
return [
|
|
106
|
+
...symptomLines(alarm, sections),
|
|
107
|
+
'',
|
|
108
|
+
`Caracterización: ${clean(sections?.characterizationSummary) || 'no disponible'}`,
|
|
109
|
+
vitalsLine(sections?.vitals),
|
|
110
|
+
`Datos objetivos: ${clean(sections?.objectiveData) || 'no disponibles'}`,
|
|
111
|
+
'',
|
|
112
|
+
`Contexto oncológico: tratamiento ${value(context?.treatment)}; última dosis ${value(context?.lastDose)}.`,
|
|
113
|
+
`Manejo previo y respuesta: ${value(context?.priorManagement)}; respuesta ${value(context?.response)}.`,
|
|
114
|
+
'',
|
|
115
|
+
...proposalLines({ proposal, withheldReason }),
|
|
116
|
+
'',
|
|
117
|
+
proposal?.items?.length ? REQUESTED_ACTION : ASSESSMENT_ACTION,
|
|
118
|
+
].join('\n');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function renderDoctorMessage({ identity, review, doctorText, link }) {
|
|
122
|
+
const phone = String(review?.patientCode ?? '').replace(/^whatsapp:/, '');
|
|
123
|
+
return [
|
|
124
|
+
`Paciente: ${identity.patientName} · ${phone}`,
|
|
125
|
+
`Médico tratante: ${withTitle(identity.treatingDoctor)}`,
|
|
126
|
+
String(doctorText ?? '').trim(),
|
|
127
|
+
'',
|
|
128
|
+
link,
|
|
129
|
+
].join('\n');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function templateSummary(review) {
|
|
133
|
+
const alarm = latestAlarm(review);
|
|
134
|
+
if (!alarm) return 'sin alarma registrada';
|
|
135
|
+
return [clean(alarm.symptom), URGENCY_LABELS[alarm.urgencyLevel] ?? clean(alarm.urgencyLevel)].filter(Boolean).join(' · ');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
module.exports = {
|
|
139
|
+
REQUESTED_ACTION,
|
|
140
|
+
ASSESSMENT_ACTION,
|
|
141
|
+
doctorIdentity,
|
|
142
|
+
withholdReason,
|
|
143
|
+
latestAlarm,
|
|
144
|
+
composeDoctorBody,
|
|
145
|
+
renderDoctorMessage,
|
|
146
|
+
templateSummary,
|
|
147
|
+
};
|
|
@@ -32,6 +32,7 @@ const triageRecommendationEventSchema = new mongoose.Schema({
|
|
|
32
32
|
gateAttempts: { type: Number, default: null },
|
|
33
33
|
gateLatencyMs: { type: Number, default: null },
|
|
34
34
|
planLatencyMs: { type: Number, default: null },
|
|
35
|
+
planMaxOutputTokens: { type: Number, default: null },
|
|
35
36
|
totalLatencyMs: { type: Number, default: null },
|
|
36
37
|
triageStored: { type: Boolean, default: null },
|
|
37
38
|
unmappedAnswerCount: { type: Number, default: null },
|
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
const FORMULARY_VERSION = '2026-09-28';
|
|
2
|
+
|
|
3
|
+
const MEDICAL_REVIEW = 'valoración médica';
|
|
4
|
+
|
|
5
|
+
const JUSTIFICATION_KINDS = Object.freeze(['prior_failure', 'contraindication', 'context']);
|
|
6
|
+
|
|
7
|
+
function deepFreeze(value) {
|
|
8
|
+
if (value && typeof value === 'object' && !Object.isFrozen(value)) {
|
|
9
|
+
Object.freeze(value);
|
|
10
|
+
for (const nested of Object.values(value)) deepFreeze(nested);
|
|
11
|
+
}
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const TREATMENT_FORMULARY = deepFreeze([
|
|
16
|
+
{
|
|
17
|
+
key: 'nausea_vomito',
|
|
18
|
+
label: 'Náusea y vómito',
|
|
19
|
+
drugs: [
|
|
20
|
+
{
|
|
21
|
+
drug: 'Ondansetrón', brand: 'AMAL', strength: '8 mg', position: '1L', tableLabel: '1L', class: 'antiemetico_5ht3',
|
|
22
|
+
instructions: '1 tableta cada 24 horas por 5 días',
|
|
23
|
+
contextNote: 'Náusea/vómito relacionado con QT; solo o dentro de esquema antiemético según riesgo',
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
drug: 'Olanzapina', strength: '5 mg', position: '1L', tableLabel: '1L en escenarios seleccionados', class: 'antipsicotico',
|
|
27
|
+
onlyWhen: ['cinv_alto_riesgo', 'nausea_persistente'],
|
|
28
|
+
contextNote: 'Profilaxis de esquemas altamente emetógenos y náusea persistente/breakthrough',
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
drug: 'Metoclopramida', strength: '10 mg', position: 'ALT', tableLabel: 'ALT / rescate', class: 'procinetico',
|
|
32
|
+
onlyWhen: ['rescate', 'gastroparesia'],
|
|
33
|
+
contextNote: 'Solo como rescate o si hay plenitud/gastroparesia; no como profilaxis principal de CINV moderada-alta',
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
drug: 'Cinarizina/dimenhidrinato', brand: 'ARLEVERT', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA CINV', class: 'antivertiginoso',
|
|
37
|
+
exceptWhen: ['componente_vestibular'],
|
|
38
|
+
contextNote: 'Solo si predomina componente vestibular/vértigo',
|
|
39
|
+
},
|
|
40
|
+
],
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
key: 'reflujo',
|
|
44
|
+
label: 'Reflujo / dispepsia / gases',
|
|
45
|
+
drugs: [
|
|
46
|
+
{
|
|
47
|
+
drug: 'Esomeprazol', strength: '40 mg', position: '1L', tableLabel: '1L', class: 'ibp',
|
|
48
|
+
instructions: '1 cápsula cada 24 horas por 5 días',
|
|
49
|
+
contextNote: 'ERGE/dispepsia ácido-relacionada; escoger un solo IBP',
|
|
50
|
+
},
|
|
51
|
+
{ drug: 'Pantoprazol', strength: '20 mg', position: '1L', tableLabel: '1L', class: 'ibp', contextNote: 'Escoger un solo IBP' },
|
|
52
|
+
{ drug: 'Omeprazol', strength: '20 mg', position: '1L', tableLabel: '1L', class: 'ibp', contextNote: 'Escoger un solo IBP' },
|
|
53
|
+
{
|
|
54
|
+
drug: 'Famotidina', strength: '40 mg', position: 'ALT', tableLabel: 'ALT / 1L síntomas leves', class: 'antih2',
|
|
55
|
+
instructions: '1 tableta cada 24 horas por 5 días',
|
|
56
|
+
contextNote: 'ERGE intermitente/nocturna o si no se requiere IBP; alternativa si ya toma esomeprazol',
|
|
57
|
+
},
|
|
58
|
+
{ drug: 'Magaldrato/dimeticona', brand: 'RIOPAN', strength: null, position: '1L', tableLabel: '1L PRN', class: 'antiacido', contextNote: 'Alivio inmediato de pirosis/dispepsia ocasional' },
|
|
59
|
+
{
|
|
60
|
+
drug: 'Simeticona/metoclopramida', brand: 'ESPAVEN MD', strength: null, position: 'ALT', tableLabel: 'ALT', class: 'procinetico',
|
|
61
|
+
contextNote: 'Distensión + síntomas dispépticos/náusea; no convertir metoclopramida en tratamiento crónico rutinario',
|
|
62
|
+
},
|
|
63
|
+
{ drug: 'Subsalicilato de bismuto', brand: 'PEPTO-BISMOL', strength: null, position: 'ALT', tableLabel: 'ALT', class: 'bismuto', contextNote: 'Dispepsia, diarrea; no primera línea para ERGE' },
|
|
64
|
+
{
|
|
65
|
+
drug: 'Ácido hialurónico/condroitín sulfato', brand: 'ESOXX ONE', strength: null, position: 'ALT', tableLabel: 'Coadyuvante', class: 'barrera_esofagica',
|
|
66
|
+
contextNote: 'Barrera de mucosa en reflujo; no reemplaza IBP cuando éste está indicado',
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
key: 'diarrea',
|
|
72
|
+
label: 'Diarrea',
|
|
73
|
+
algorithmModifiers: [
|
|
74
|
+
'fiebre', 'neutropenia', 'sangre_en_heces', 'hipotension', 'deshidratacion', 'dolor_intenso', 'sospecha_colitis_inmunomediada',
|
|
75
|
+
],
|
|
76
|
+
drugs: [
|
|
77
|
+
{
|
|
78
|
+
drug: 'Loperamida', strength: '2 mg', position: '1L', tableLabel: '1L', class: 'antidiarreico_opioide',
|
|
79
|
+
instructions: '2 tabletas (4 mg) al inicio y después 1 tableta cada 6 horas, máximo 8 tabletas al día',
|
|
80
|
+
ruleOutFirst: ['causa infecciosa', 'causa obstructiva', 'intolerancia'],
|
|
81
|
+
contextNote: 'Diarrea no complicada asociada al tratamiento oncológico',
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
drug: 'Racecadotrilo', strength: '100 mg', position: 'ALT', tableLabel: 'ALT', class: 'antisecretor',
|
|
85
|
+
contextNote: 'Opción sintomática; alternativa en diarrea G1 por inmunoterapia',
|
|
86
|
+
},
|
|
87
|
+
],
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
key: 'dolor_abdominal_colico',
|
|
91
|
+
label: 'Dolor abdominal tipo cólico',
|
|
92
|
+
drugs: [
|
|
93
|
+
{
|
|
94
|
+
drug: 'Butilhioscina/metamizol', brand: 'BUSCAPINA COMPUESTA', strength: '10/250 mg', position: 'ALT', tableLabel: 'Coadyuvante', class: 'antiespasmodico',
|
|
95
|
+
instructions: '1 tableta cada 8 a 12 horas por razón necesaria',
|
|
96
|
+
contextNote: 'Coadyuvante para cólico, no tratamiento de la diarrea',
|
|
97
|
+
},
|
|
98
|
+
],
|
|
99
|
+
},
|
|
100
|
+
{
|
|
101
|
+
key: 'estrenimiento',
|
|
102
|
+
label: 'Estreñimiento',
|
|
103
|
+
requiresWhen: [{ condition: 'uso_opioides', drug: 'Senósidos', note: 'Con opioides: senósido ± PEG desde el inicio' }],
|
|
104
|
+
drugs: [
|
|
105
|
+
{ drug: 'Polietilenglicol 3350', brand: 'MIRALAX / NULYTELY', strength: null, position: '1L', tableLabel: '1L preferida', class: 'laxante_osmotico_peg' },
|
|
106
|
+
{
|
|
107
|
+
drug: 'Senósidos', brand: 'SENOKOT', strength: null, position: '1L', tableLabel: '1L, especialmente estreñimiento por opioides', class: 'laxante_estimulante',
|
|
108
|
+
instructions: '2 tabletas cada noche por 5 días',
|
|
109
|
+
},
|
|
110
|
+
{ drug: 'Bisacodilo', strength: null, position: '1L', tableLabel: '1L / ALT, estimulante', class: 'laxante_estimulante' },
|
|
111
|
+
{
|
|
112
|
+
drug: 'Lactulosa', brand: 'LACTULAX', strength: null, position: '1L', tableLabel: '1L / ALT osmótica', class: 'laxante_osmotico',
|
|
113
|
+
instructions: '10 ml cada 8 horas hasta lograr evacuación, después suspender',
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
drug: 'Leche de magnesia', strength: null, position: 'ALT', tableLabel: 'ALT', class: 'laxante_osmotico',
|
|
117
|
+
avoidWhen: ['insuficiencia_renal'],
|
|
118
|
+
contextNote: 'Evitar/cautela en insuficiencia renal',
|
|
119
|
+
},
|
|
120
|
+
],
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
key: 'mucositis',
|
|
124
|
+
label: 'Mucositis',
|
|
125
|
+
drugs: [
|
|
126
|
+
{
|
|
127
|
+
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',
|
|
128
|
+
instructions: 'enjuagues y gárgaras de 1 minuto cada 6 horas por 5 días',
|
|
129
|
+
isPharmacological: false,
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
drug: 'Bencidamina', brand: 'VANTAL', strength: null, position: '1L', tableLabel: '1L en escenarios específicos', class: 'enjuague_analgesico',
|
|
133
|
+
onlyWhen: ['radioterapia_cabeza_cuello'],
|
|
134
|
+
contextNote: 'Especialmente mucositis por RT de cabeza/cuello',
|
|
135
|
+
},
|
|
136
|
+
{ drug: 'Gel barrera oral', brand: 'GELBUX', strength: null, position: 'ALT', tableLabel: 'Coadyuvante', class: 'barrera_oral', contextNote: 'Barrera para úlceras/mucositis' },
|
|
137
|
+
{ drug: 'Fórmula de Filadelfia', strength: null, position: 'ALT', tableLabel: 'ALT sintomática', class: 'enjuague_compuesto', contextNote: 'No estándar universal de primera línea' },
|
|
138
|
+
{
|
|
139
|
+
drug: 'Dexketoprofeno', brand: 'VELIAN', strength: '25 mg/10 ml en sobres', position: 'ALT', tableLabel: 'ALT analgésica', class: 'aine',
|
|
140
|
+
instructions: '1 sobre cada 8 horas, 30 minutos antes de los alimentos, y tragar, por 7 días',
|
|
141
|
+
contextNote: `Analgésico, no tratamiento específico de mucositis; si persiste, ${MEDICAL_REVIEW}`,
|
|
142
|
+
},
|
|
143
|
+
],
|
|
144
|
+
},
|
|
145
|
+
{
|
|
146
|
+
key: 'candidiasis_oral',
|
|
147
|
+
label: 'Candidiasis oral',
|
|
148
|
+
drugs: [
|
|
149
|
+
{ drug: 'Nistatina', strength: null, position: '1L', tableLabel: '1L/ALT en candidiasis oral leve', class: 'antifungico_topico', onlyWhen: ['candidiasis_leve'] },
|
|
150
|
+
{ drug: 'Fluconazol', strength: '100 mg', position: '1L', tableLabel: '1L en candidiasis moderada-severa', class: 'antifungico_azol', onlyWhen: ['candidiasis_moderada_severa'] },
|
|
151
|
+
],
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
key: 'dolor',
|
|
155
|
+
label: 'Dolor',
|
|
156
|
+
drugs: [
|
|
157
|
+
{
|
|
158
|
+
drug: 'Paracetamol', brand: 'TEMPRA / TYLENOL', strength: '500 mg', position: '1L', tableLabel: '1L dolor leve', class: 'analgesico_no_opioide',
|
|
159
|
+
instructions: 'VO cada 8 horas por razón necesaria, máximo 3 días',
|
|
160
|
+
},
|
|
161
|
+
{
|
|
162
|
+
drug: 'Ibuprofeno', strength: '400 mg', position: '1L', tableLabel: '1L/ALT dolor inflamatorio leve', class: 'aine',
|
|
163
|
+
instructions: 'VO cada 12 horas, máximo 3 días',
|
|
164
|
+
avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
|
|
165
|
+
},
|
|
166
|
+
{ drug: 'Naproxeno', strength: null, position: '1L', tableLabel: '1L/ALT', class: 'aine', avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'] },
|
|
167
|
+
{
|
|
168
|
+
drug: 'Celecoxib', brand: 'CELEBREX', strength: '200 mg', position: 'ALT', tableLabel: 'ALT / escalamiento de AINE', class: 'aine',
|
|
169
|
+
instructions: 'VO cada 24 horas, máximo 3 días',
|
|
170
|
+
avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
|
|
171
|
+
},
|
|
172
|
+
{ drug: 'Dexketoprofeno', strength: null, position: 'ALT', tableLabel: 'ALT corto plazo', class: 'aine', avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'] },
|
|
173
|
+
{
|
|
174
|
+
drug: 'Ketorolaco', strength: null, position: '2L+', tableLabel: 'Rescate corto plazo, no mantenimiento', class: 'aine',
|
|
175
|
+
avoidWhen: ['alergia_aines', 'insuficiencia_renal', 'ulcera_o_sangrado_gi'],
|
|
176
|
+
},
|
|
177
|
+
{ drug: 'Tramadol', strength: '50 mg', position: '2L+', tableLabel: '2.º escalón, dolor leve-moderado no controlado', class: 'opioide_debil' },
|
|
178
|
+
{ drug: 'Tramadol/paracetamol', strength: null, position: '2L+', tableLabel: '2.º escalón', class: 'opioide_debil' },
|
|
179
|
+
{
|
|
180
|
+
drug: 'Morfina oral', strength: null, position: '1L', tableLabel: '1L opioide para dolor oncológico moderado-severo', class: 'opioide_fuerte',
|
|
181
|
+
onlyWhen: ['dolor_moderado_severo'],
|
|
182
|
+
avoidWhen: ['insuficiencia_renal_avanzada'],
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
drug: 'Oxicodona', strength: null, position: 'ALT', tableLabel: 'ALT a morfina', class: 'opioide_fuerte',
|
|
186
|
+
onlyWhen: ['dolor_moderado_severo'],
|
|
187
|
+
avoidWhen: ['insuficiencia_renal_avanzada'],
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
drug: 'Oxicodona LP', brand: 'OXYCONTIN', strength: null, position: '2L+', tableLabel: 'Mantenimiento, no titulación inicial en opioid-naïve', class: 'opioide_fuerte',
|
|
191
|
+
avoidWhen: ['opioid_naive', 'insuficiencia_renal_avanzada'],
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
drug: 'Buprenorfina transdérmica', strength: '5–20 µg/h', position: 'ALT', tableLabel: 'ALT para dolor crónico estable', class: 'opioide_fuerte',
|
|
195
|
+
contextNote: 'Preferir si hay insuficiencia renal avanzada',
|
|
196
|
+
},
|
|
197
|
+
{
|
|
198
|
+
drug: 'Buprenorfina transdérmica', strength: '35–70 µg/h', position: 'ALT', tableLabel: 'ALT opioide para dolor crónico moderado-severo estable', class: 'opioide_fuerte',
|
|
199
|
+
contextNote: 'Preferir si hay insuficiencia renal avanzada',
|
|
200
|
+
},
|
|
201
|
+
],
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
key: 'neuropatia',
|
|
205
|
+
label: 'Neuropatía inducida por quimioterapia',
|
|
206
|
+
alwaysEscalate: MEDICAL_REVIEW,
|
|
207
|
+
recognition: 'ardor, sensación de adormecimiento o piquetes; sigue el trayecto de un nervio, o aparece en manos y pies al mismo tiempo',
|
|
208
|
+
contextNote: 'Si afecta función durante tratamiento neurotóxico, considerar reducción, retraso o suspensión del fármaco causante',
|
|
209
|
+
drugs: [
|
|
210
|
+
{ drug: 'Duloxetina', strength: '30 mg', position: '1L', tableLabel: '1L', class: 'irsn' },
|
|
211
|
+
{ drug: 'Pregabalina', strength: '75 mg', position: 'ALT', tableLabel: 'ALT', class: 'gabapentinoide' },
|
|
212
|
+
{ drug: 'Gabapentina', strength: '300 mg', position: 'ALT', tableLabel: 'ALT', class: 'gabapentinoide' },
|
|
213
|
+
{ drug: 'Núcleo CM Forte', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA para CIPN', class: 'suplemento_nucleotidos' },
|
|
214
|
+
{ drug: 'Tiaminal B12', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA, salvo deficiencia', class: 'vitamina_b', exceptWhen: ['deficiencia_documentada'] },
|
|
215
|
+
{ drug: 'Tiaminal 50', strength: null, position: 'NO_RUTINA', tableLabel: 'NO RUTINA, salvo deficiencia', class: 'vitamina_b', exceptWhen: ['deficiencia_documentada'] },
|
|
216
|
+
{ drug: 'Ácido fólico', strength: '5 mg', position: 'NO_RUTINA', tableLabel: 'NO RUTINA, salvo deficiencia/indicación específica', class: 'folato', exceptWhen: ['deficiencia_documentada'] },
|
|
217
|
+
],
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
key: 'rash',
|
|
221
|
+
label: 'Rash / dermatitis por tratamiento',
|
|
222
|
+
drugs: [
|
|
223
|
+
{ drug: 'Doxiciclina', strength: '100 mg', position: '1L', tableLabel: '1L rash EGFR moderado o profilaxis', class: 'tetraciclina', onlyWhen: ['rash_egfr'] },
|
|
224
|
+
{ drug: 'Minociclina', strength: '100 mg', position: '1L', tableLabel: '1L alternativa', class: 'tetraciclina', onlyWhen: ['rash_egfr'] },
|
|
225
|
+
{ drug: 'Clindamicina tópica', strength: '1%', position: 'ALT', tableLabel: 'ALT, lesiones localizadas', class: 'antibiotico_topico' },
|
|
226
|
+
{ drug: 'Hidrocortisona tópica', brand: 'LOCOID', strength: null, position: '1L', tableLabel: '1L en dermatitis/rash inflamatorio leve', class: 'corticoide_topico' },
|
|
227
|
+
],
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
key: 'sindrome_mano_pie',
|
|
231
|
+
label: 'Xerosis / síndrome mano-pie',
|
|
232
|
+
drugs: [
|
|
233
|
+
{
|
|
234
|
+
drug: 'Urea', brand: 'NUTRAPLUS', strength: '10%', position: '1L', tableLabel: '1L, especialmente HFS/hiperqueratosis', class: 'queratolitico',
|
|
235
|
+
instructions: 'capa fina cada 12 horas de forma continua',
|
|
236
|
+
},
|
|
237
|
+
{
|
|
238
|
+
drug: 'Ceramidas', brand: 'CERAVE', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente',
|
|
239
|
+
instructions: '2 a 3 veces al día de forma continua', isPharmacological: false,
|
|
240
|
+
},
|
|
241
|
+
{ drug: 'Emoliente', brand: 'EUCERIN', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
|
|
242
|
+
{ drug: 'Vaselina/petrolato', strength: null, position: '1L', tableLabel: '1L barrera', class: 'barrera_cutanea', isPharmacological: false },
|
|
243
|
+
{ drug: 'Emoliente', brand: 'LUBRIDERM', strength: null, position: '1L', tableLabel: '1L emoliente', class: 'emoliente', isPharmacological: false },
|
|
244
|
+
{ drug: 'Emoliente', brand: 'JERGENS', strength: null, position: 'ALT', tableLabel: 'ALT cosmética/emoliente', class: 'emoliente', isPharmacological: false },
|
|
245
|
+
],
|
|
246
|
+
},
|
|
247
|
+
{
|
|
248
|
+
key: 'tos',
|
|
249
|
+
label: 'Tos',
|
|
250
|
+
requiresRuledOut: ['infeccion', 'neumonitis', 'progresion_pulmonar', 'tep', 'derrame'],
|
|
251
|
+
drugs: [
|
|
252
|
+
{ drug: 'Dextrometorfano', strength: null, position: '1L', tableLabel: '1L tos seca sintomática', class: 'antitusivo' },
|
|
253
|
+
{ drug: 'Ambroxol', strength: null, position: 'ALT', tableLabel: 'ALT si hay secreciones', class: 'mucolitico', onlyWhen: ['secreciones'] },
|
|
254
|
+
{ drug: 'Bromhexina', strength: null, position: 'ALT', tableLabel: 'ALT si hay secreciones', class: 'mucolitico', onlyWhen: ['secreciones'] },
|
|
255
|
+
{ drug: 'Hedera helix', strength: null, position: 'ALT', tableLabel: 'ALT, menor evidencia', class: 'fitoterapico' },
|
|
256
|
+
{
|
|
257
|
+
drug: 'Bromhexina/codeína', brand: 'KODEL', strength: 'bromhexina 160 mg + codeína 200 mg por cada 100 mL', position: '2L+', tableLabel: '2L / rescate, tos intensa seleccionada', class: 'antitusivo',
|
|
258
|
+
contextNote: 'La concentración es por cada 100 mL, no por dosis',
|
|
259
|
+
},
|
|
260
|
+
],
|
|
261
|
+
},
|
|
262
|
+
{
|
|
263
|
+
key: 'rinitis_alergia',
|
|
264
|
+
label: 'Rinitis / alergia',
|
|
265
|
+
drugs: [
|
|
266
|
+
{
|
|
267
|
+
drug: 'Cetirizina', brand: 'REACTINE', strength: '10 mg', position: '1L', tableLabel: '1L antihistamínico', class: 'antihistaminico',
|
|
268
|
+
instructions: '1 tableta cada 24 horas por 7 días',
|
|
269
|
+
},
|
|
270
|
+
{ drug: 'Loratadina', strength: '10 mg', position: '1L', tableLabel: '1L', class: 'antihistaminico' },
|
|
271
|
+
{ drug: 'Fexofenadina', strength: '180 mg', position: '1L', tableLabel: '1L', class: 'antihistaminico' },
|
|
272
|
+
{ drug: 'Hidroxicina', strength: '25 mg', position: '2L+', tableLabel: '2L, por sedación/efecto anticolinérgico', class: 'antihistaminico' },
|
|
273
|
+
{ drug: 'Montelukast/loratadina', strength: null, position: 'ALT', tableLabel: 'ALT, más útil si asma/componente leucotrieno', class: 'antihistaminico' },
|
|
274
|
+
{
|
|
275
|
+
drug: 'Loratadina/betametasona', strength: null, position: 'NO_RUTINA', tableLabel: 'No rutina como 1L; corticoide sistémico aumenta riesgos', class: 'antihistaminico',
|
|
276
|
+
},
|
|
277
|
+
],
|
|
278
|
+
},
|
|
279
|
+
{
|
|
280
|
+
key: 'dermatitis_radioterapia',
|
|
281
|
+
label: 'Dermatitis por radioterapia',
|
|
282
|
+
drugs: [
|
|
283
|
+
{ drug: 'Mometasona', strength: '0.1%', position: '1L', tableLabel: 'Corticoide de potencia media favorecido (MASCC 2026) en pacientes seleccionados', class: 'corticoide_topico' },
|
|
284
|
+
{ drug: 'Desonida', brand: 'DESOWEN', strength: '0.05%', position: 'ALT', tableLabel: 'Corticoide tópico en dermatitis temprana', class: 'corticoide_topico' },
|
|
285
|
+
{ drug: 'Xondrid', strength: null, position: 'NO_RUTINA', tableLabel: 'No estándar de primera línea sin confirmar formulación y evidencia', class: 'barrera_cutanea' },
|
|
286
|
+
],
|
|
287
|
+
},
|
|
288
|
+
{
|
|
289
|
+
key: 'hta_tki',
|
|
290
|
+
label: 'HTA por VEGF/TKI',
|
|
291
|
+
excluded: [{ drugs: ['Diltiazem', 'Verapamilo'], reason: 'Evitar con TKI por interacciones' }],
|
|
292
|
+
drugs: [
|
|
293
|
+
{ drug: 'Losartán', strength: '50 mg', position: '1L', tableLabel: '1L', class: 'ara2' },
|
|
294
|
+
{ drug: 'Telmisartán', strength: '40 mg', position: '1L', tableLabel: '1L', class: 'ara2' },
|
|
295
|
+
{ drug: 'Amlodipino', strength: '5 mg', position: '1L', tableLabel: '1L/añadido, si función VI normal', class: 'calcioantagonista_dhp' },
|
|
296
|
+
{
|
|
297
|
+
drug: 'Amlodipino/valsartán/HCTZ', strength: null, position: '2L+', tableLabel: '2L/escalamiento, HTA que requiere ≥2–3 fármacos', class: 'combinacion_antihipertensiva',
|
|
298
|
+
},
|
|
299
|
+
],
|
|
300
|
+
},
|
|
301
|
+
{
|
|
302
|
+
key: 'caquexia',
|
|
303
|
+
label: 'Caquexia / anorexia',
|
|
304
|
+
drugs: [
|
|
305
|
+
{ drug: 'Olanzapina', strength: '2.5 mg', position: '1L', tableLabel: '1L farmacológica', class: 'antipsicotico' },
|
|
306
|
+
{ drug: 'Megestrol', strength: null, position: 'ALT', tableLabel: 'ALT / 2L', class: 'progestageno', contextNote: 'Riesgo de trombosis, edema y supresión adrenal' },
|
|
307
|
+
{ drug: 'Dexametasona', strength: '4 mg', position: 'ALT', tableLabel: 'ALT corto plazo, particularmente contexto paliativo', class: 'corticoide_sistemico' },
|
|
308
|
+
{
|
|
309
|
+
drug: 'Metoclopramida', strength: null, position: 'ALT', tableLabel: 'Sólo si saciedad precoz/gastroparesia/náusea', class: 'procinetico',
|
|
310
|
+
onlyWhen: ['saciedad_precoz', 'gastroparesia', 'nausea'],
|
|
311
|
+
},
|
|
312
|
+
],
|
|
313
|
+
},
|
|
314
|
+
{
|
|
315
|
+
key: 'insomnio',
|
|
316
|
+
label: 'Insomnio',
|
|
317
|
+
contextNote: 'En insomnio crónico la primera intervención es CBT-I',
|
|
318
|
+
drugs: [
|
|
319
|
+
{
|
|
320
|
+
drug: 'Melatonina', brand: 'MELATOL', strength: '3 mg', position: 'ALT', tableLabel: 'Puede probarse; sin evidencia fuerte en insomnio crónico', class: 'melatonina',
|
|
321
|
+
instructions: '1 tableta cada 24 horas por la noche por 14 días',
|
|
322
|
+
},
|
|
323
|
+
{ drug: 'Zolpidem', strength: '10 mg', position: 'ALT', tableLabel: 'ALT farmacológica de corto plazo, no primera intervención global', class: 'hipnotico' },
|
|
324
|
+
],
|
|
325
|
+
},
|
|
326
|
+
{
|
|
327
|
+
key: 'salud_vaginal',
|
|
328
|
+
label: 'Salud vaginal',
|
|
329
|
+
drugs: [
|
|
330
|
+
{ drug: 'Lubricante base agua', strength: null, position: '1L', tableLabel: '1L, especialmente para actividad sexual', class: 'lubricante', isPharmacological: false },
|
|
331
|
+
{ drug: 'Ácido hialurónico vaginal', brand: 'HIALOFEMME', strength: null, position: '1L', tableLabel: '1L hidratante vaginal no hormonal', class: 'hidratante_vaginal' },
|
|
332
|
+
{ drug: 'Hidratante vaginal', brand: 'ISDIN WOMAN', strength: null, position: '1L', tableLabel: '1L no hormonal', class: 'hidratante_vaginal' },
|
|
333
|
+
{
|
|
334
|
+
drug: 'Estriol vaginal', brand: 'OVESTIN', strength: null, position: '2L+', tableLabel: '2L, si persiste atrofia/sequedad tras hidratantes', class: 'estrogeno_vaginal',
|
|
335
|
+
contextNote: 'Individualizar especialmente en cáncer hormonosensible',
|
|
336
|
+
},
|
|
337
|
+
{ drug: 'Vagitrol-V', strength: null, position: 'NO_RUTINA', tableLabel: 'No empírico rutinario', class: 'antiinfeccioso_vaginal', exceptWhen: ['diagnostico_infeccioso'] },
|
|
338
|
+
{ drug: 'Fluconazol/tinidazol', brand: 'AFUMIX', strength: null, position: 'NO_RUTINA', tableLabel: 'No empírico rutinario', class: 'antiinfeccioso_vaginal', exceptWhen: ['diagnostico_infeccioso'] },
|
|
339
|
+
],
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
key: 'soporte_oseo',
|
|
343
|
+
label: 'Soporte óseo',
|
|
344
|
+
contextNote: 'Primera línea solo si cumple criterios de osteoporosis/riesgo de fractura; el esquema de ácido zoledrónico para osteoporosis no es el de metástasis óseas',
|
|
345
|
+
drugs: [
|
|
346
|
+
{ drug: 'Denosumab', strength: '60 mg SC', position: '1L', tableLabel: '1L posible para osteoporosis', class: 'antirresortivo', onlyWhen: ['osteoporosis_o_riesgo_fractura'] },
|
|
347
|
+
{ drug: 'Ácido zoledrónico', strength: null, position: '1L', tableLabel: '1L posible para osteoporosis', class: 'antirresortivo', onlyWhen: ['osteoporosis_o_riesgo_fractura'] },
|
|
348
|
+
{ drug: 'Colecalciferol', strength: null, position: 'ALT', tableLabel: 'Soporte basal si ingesta/niveles lo requieren', class: 'vitamina_d', contextNote: 'Corregir déficit según 25-OH-D' },
|
|
349
|
+
{ drug: 'Calcio + vitamina D', brand: 'CALTRATE 600 + D', strength: null, position: 'ALT', tableLabel: 'Soporte basal', class: 'calcio' },
|
|
350
|
+
],
|
|
351
|
+
},
|
|
352
|
+
{
|
|
353
|
+
key: 'espasticidad_hipo',
|
|
354
|
+
label: 'Espasticidad / hipo persistente',
|
|
355
|
+
drugs: [
|
|
356
|
+
{
|
|
357
|
+
drug: 'Baclofeno', strength: '10 mg', position: '1L', tableLabel: '1L/ALT para espasticidad; hipo persistente/refractario', class: 'relajante_muscular',
|
|
358
|
+
onlyWhen: ['espasticidad', 'hipo_persistente'],
|
|
359
|
+
},
|
|
360
|
+
],
|
|
361
|
+
},
|
|
362
|
+
]);
|
|
363
|
+
|
|
364
|
+
const byKey = new Map(TREATMENT_FORMULARY.map((entry) => [entry.key, entry]));
|
|
365
|
+
|
|
366
|
+
const normalize = (value) => String(value ?? '').trim().toLowerCase();
|
|
367
|
+
|
|
368
|
+
const asSet = (values) => new Set((Array.isArray(values) ? values : []).map(normalize));
|
|
369
|
+
|
|
370
|
+
function formularyFor(symptomKey) {
|
|
371
|
+
return byKey.get(String(symptomKey ?? '').trim()) ?? null;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const compact = (value) => normalize(value).replace(/\s+/g, '');
|
|
375
|
+
|
|
376
|
+
function findDrug(entry, item) {
|
|
377
|
+
const drug = normalize(item?.drug);
|
|
378
|
+
const brand = normalize(item?.brand);
|
|
379
|
+
const strength = compact(item?.strength);
|
|
380
|
+
const candidates = entry.drugs.filter((candidate) => normalize(candidate.drug) === drug
|
|
381
|
+
&& (!strength || !candidate.strength || compact(candidate.strength) === strength));
|
|
382
|
+
if (candidates.length <= 1) return candidates[0] ?? null;
|
|
383
|
+
return candidates.find((candidate) => (brand && normalize(candidate.brand) === brand) || (strength && compact(candidate.strength) === strength)) ?? null;
|
|
384
|
+
}
|
|
385
|
+
|
|
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
|
+
module.exports = {
|
|
469
|
+
FORMULARY_VERSION,
|
|
470
|
+
TREATMENT_FORMULARY,
|
|
471
|
+
formularyFor,
|
|
472
|
+
findDrug,
|
|
473
|
+
validateProposal,
|
|
474
|
+
};
|
|
@@ -331,7 +331,7 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
331
331
|
return { response: this._normalizeResponse(finalResponse), toolCalls: allToolCalls, toolsExecuted: allToolsExecuted, retries: totalRetries, usage: accumulatedUsage };
|
|
332
332
|
}
|
|
333
333
|
|
|
334
|
-
async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null } = {}) {
|
|
334
|
+
async runStructured({ promptId = null, presetId = null, instructions = null, variables = null, input = [], text = null, metadata = null, model = null, maxOutputTokens = null } = {}) {
|
|
335
335
|
let modelConfig = {};
|
|
336
336
|
let resolvedInstructions = instructions;
|
|
337
337
|
if (promptId || presetId) {
|
|
@@ -344,7 +344,7 @@ class AnthropicProvider extends BaseLLMProvider {
|
|
|
344
344
|
|
|
345
345
|
const apiConfig = {
|
|
346
346
|
model: model || (modelConfig.model && modelConfig.model.replace(/^anthropic\//, '')) || this.defaults.structuredModel,
|
|
347
|
-
max_tokens: modelConfig.max_output_tokens || this.defaults.structuredMaxTokens,
|
|
347
|
+
max_tokens: maxOutputTokens || modelConfig.max_output_tokens || this.defaults.structuredMaxTokens,
|
|
348
348
|
};
|
|
349
349
|
if (system) apiConfig.system = system;
|
|
350
350
|
|