@peopl-health/nexus 5.58.0-dev.10496 → 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 +22 -41
- package/lib/clinical/protocols/treatmentFormulary.js +1 -88
- package/lib/clinical/services/escalationDraftService.js +19 -2
- package/lib/clinical/services/treatmentProposalService.js +106 -0
- package/lib/services/escalationReviewService.js +10 -1
- package/lib/utils/textMatchUtils.js +1 -0
- package/package.json +1 -1
|
@@ -11,57 +11,39 @@ const REQUESTED_ACTION = 'Acción solicitada: ¿aprueba la propuesta, la modific
|
|
|
11
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
12
|
const DOCTOR_TITLE = /^(dr|dra)\.?\s/i;
|
|
13
13
|
|
|
14
|
-
const clean = (value) => inlineOf(value);
|
|
15
|
-
|
|
16
14
|
const withTitle = (name) => (DOCTOR_TITLE.test(name) ? name : `Dr./Dra. ${name}`);
|
|
17
15
|
|
|
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
16
|
function latestAlarm(review) {
|
|
28
17
|
const alarms = Array.isArray(review?.alarms) ? review.alarms : [];
|
|
29
18
|
return alarms[alarms.length - 1] ?? null;
|
|
30
19
|
}
|
|
31
20
|
|
|
32
|
-
function
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
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;
|
|
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
|
+
};
|
|
46
29
|
}
|
|
47
30
|
|
|
48
31
|
function symptomLines(alarm, sections) {
|
|
49
32
|
const grade = [1, 2, 3].includes(sections?.grade) ? `G${sections.grade}` : 'grado no establecido';
|
|
50
33
|
const said = [
|
|
51
|
-
|
|
34
|
+
inlineOf(alarm?.symptom) || inlineOf(sections?.symptom),
|
|
52
35
|
grade,
|
|
53
|
-
|
|
54
|
-
URGENCY_LABELS[alarm?.urgencyLevel] ??
|
|
36
|
+
inlineOf(alarm?.suspectedCondition),
|
|
37
|
+
URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel),
|
|
55
38
|
alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null,
|
|
56
39
|
].filter(Boolean);
|
|
57
|
-
const
|
|
58
|
-
if (!
|
|
59
|
-
const present = presentRedFlags(sections);
|
|
60
|
-
const absent = flags.filter((flag) => flag?.present !== true).map((flag) => clean(flag?.flag)).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.'];
|
|
61
42
|
return [
|
|
62
43
|
`Síntoma: ${said.join(' · ')}`,
|
|
63
44
|
`Banderas rojas presentes: ${present.length ? present.join(', ') : 'ninguna'}.`,
|
|
64
45
|
`Banderas rojas ausentes: ${absent.length ? absent.join(', ') : 'ninguna revisada'}.`,
|
|
46
|
+
...(unassessed.length ? [`Banderas rojas sin evaluar: ${unassessed.join(', ')}.`] : []),
|
|
65
47
|
];
|
|
66
48
|
}
|
|
67
49
|
|
|
@@ -83,31 +65,31 @@ function proposalItemLine(symptom, item) {
|
|
|
83
65
|
const parts = [`- ${name}`];
|
|
84
66
|
if (drug.instructions) parts.push(drug.instructions);
|
|
85
67
|
parts.push(`posición en la tabla: ${drug.tableLabel}`);
|
|
86
|
-
const why =
|
|
68
|
+
const why = inlineOf(item?.justification?.text);
|
|
87
69
|
if (why) parts.push(`motivo: ${why}`);
|
|
88
70
|
return parts.join(' — ');
|
|
89
71
|
}
|
|
90
72
|
|
|
91
73
|
function proposalLines({ proposal, withheldReason }) {
|
|
92
74
|
if (!proposal?.items?.length) {
|
|
93
|
-
const reason =
|
|
75
|
+
const reason = inlineOf(withheldReason) || 'sin propuesta farmacológica';
|
|
94
76
|
return [PROPOSAL_HEADING, `No se propone tratamiento sintomático: ${reason}. Se prioriza la valoración médica.`];
|
|
95
77
|
}
|
|
96
78
|
const lines = proposal.items.map((item) => proposalItemLine(proposal.symptom, item)).filter(Boolean);
|
|
97
|
-
const declared = [...(proposal.conditions ?? []), ...(proposal.ruledOut ?? []).map((key) => `descartado: ${key}`)].map(
|
|
79
|
+
const declared = [...(proposal.conditions ?? []), ...(proposal.ruledOut ?? []).map((key) => `descartado: ${key}`)].map(inlineOf).filter(Boolean);
|
|
98
80
|
if (declared.length) lines.push(`Condiciones que se declararon para esta propuesta (verificar): ${declared.join(', ')}.`);
|
|
99
81
|
return [PROPOSAL_HEADING, ...lines];
|
|
100
82
|
}
|
|
101
83
|
|
|
102
84
|
function composeDoctorBody({ alarm, sections, proposal, withheldReason }) {
|
|
103
85
|
const context = sections?.oncologyContext;
|
|
104
|
-
const value = (text) =>
|
|
86
|
+
const value = (text) => inlineOf(text) || 'no disponible';
|
|
105
87
|
return [
|
|
106
88
|
...symptomLines(alarm, sections),
|
|
107
89
|
'',
|
|
108
|
-
`Caracterización: ${
|
|
90
|
+
`Caracterización: ${inlineOf(sections?.characterizationSummary) || 'no disponible'}`,
|
|
109
91
|
vitalsLine(sections?.vitals),
|
|
110
|
-
`Datos objetivos: ${
|
|
92
|
+
`Datos objetivos: ${inlineOf(sections?.objectiveData) || 'no disponibles'}`,
|
|
111
93
|
'',
|
|
112
94
|
`Contexto oncológico: tratamiento ${value(context?.treatment)}; última dosis ${value(context?.lastDose)}.`,
|
|
113
95
|
`Manejo previo y respuesta: ${value(context?.priorManagement)}; respuesta ${value(context?.response)}.`,
|
|
@@ -132,14 +114,13 @@ function renderDoctorMessage({ identity, review, doctorText, link }) {
|
|
|
132
114
|
function templateSummary(review) {
|
|
133
115
|
const alarm = latestAlarm(review);
|
|
134
116
|
if (!alarm) return 'sin alarma registrada';
|
|
135
|
-
return [
|
|
117
|
+
return [inlineOf(alarm.symptom), URGENCY_LABELS[alarm.urgencyLevel] ?? inlineOf(alarm.urgencyLevel)].filter(Boolean).join(' · ');
|
|
136
118
|
}
|
|
137
119
|
|
|
138
120
|
module.exports = {
|
|
139
121
|
REQUESTED_ACTION,
|
|
140
122
|
ASSESSMENT_ACTION,
|
|
141
|
-
|
|
142
|
-
withholdReason,
|
|
123
|
+
flagsByStatus,
|
|
143
124
|
latestAlarm,
|
|
144
125
|
composeDoctorBody,
|
|
145
126
|
renderDoctorMessage,
|
|
@@ -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,97 +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
|
-
validateProposal,
|
|
474
387
|
};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
const { getEscalationDraft } = require('../config/subAgentsConfig');
|
|
2
2
|
|
|
3
|
-
const { FORMULARY_VERSION, TREATMENT_FORMULARY
|
|
3
|
+
const { FORMULARY_VERSION, TREATMENT_FORMULARY } = require('../protocols/treatmentFormulary');
|
|
4
4
|
|
|
5
5
|
const { createLLMProvider } = require('../providers/createLLMProvider');
|
|
6
6
|
|
|
7
|
-
const { composeDoctorBody,
|
|
7
|
+
const { composeDoctorBody, flagsByStatus } = require('../helpers/doctorReviewMessageHelper');
|
|
8
8
|
const { readStructuredText } = require('../helpers/structuredTextHelper');
|
|
9
9
|
|
|
10
10
|
const { getEscalationContext } = require('../../services/escalationContextService');
|
|
@@ -13,12 +13,24 @@ const { logger } = require('../../utils/logger');
|
|
|
13
13
|
const { safeParse } = require('../../utils/jsonUtils');
|
|
14
14
|
const { withTiming } = require('../../utils/tracingDecorator');
|
|
15
15
|
|
|
16
|
+
const { drugsNamedIn, validateProposal } = require('./treatmentProposalService');
|
|
17
|
+
|
|
16
18
|
const CONVERSATION_TURNS = 40;
|
|
17
19
|
const TRIAGE_LIMIT = 3;
|
|
18
20
|
const CALL_LOG_LIMIT = 10;
|
|
19
21
|
|
|
20
22
|
const trimmed = (value) => String(value ?? '').trim();
|
|
21
23
|
|
|
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
|
+
|
|
22
34
|
function settleProposal(parsed) {
|
|
23
35
|
const withheld = withholdReason(parsed);
|
|
24
36
|
const raw = parsed?.treatmentProposal;
|
|
@@ -114,6 +126,11 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
|
|
|
114
126
|
}
|
|
115
127
|
const settled = settleProposal(parsed);
|
|
116
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
|
+
|
|
117
134
|
if (settled.invalid) {
|
|
118
135
|
logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues: settled.invalid });
|
|
119
136
|
return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${settled.invalid.join('; ')}` };
|
|
@@ -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
|
+
};
|
|
@@ -21,7 +21,7 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
|
21
21
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
22
22
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
23
23
|
const { writeUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
|
|
24
|
-
const {
|
|
24
|
+
const { renderDoctorMessage, templateSummary } = require('../clinical/helpers/doctorReviewMessageHelper');
|
|
25
25
|
const { generateKeyQuestions } = require('../clinical/services/escalationQuestionsService');
|
|
26
26
|
const { readNoteFacts, assertionOf } = require('../clinical/services/escalationNoteFactsService');
|
|
27
27
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
@@ -301,6 +301,15 @@ function doctorLink(review) {
|
|
|
301
301
|
return `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
|
|
302
302
|
}
|
|
303
303
|
|
|
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
|
+
}
|
|
312
|
+
|
|
304
313
|
async function readDoctorIdentity(review) {
|
|
305
314
|
let patient;
|
|
306
315
|
try {
|