@peopl-health/nexus 5.59.0-dev.10671 → 5.59.0-dev.10730
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 +25 -18
- package/lib/clinical/services/escalationDraftService.js +27 -14
- package/lib/clinical/services/treatmentProposalService.js +27 -7
- package/lib/controllers/prescriptionController.js +10 -3
- package/lib/services/escalationReviewService.js +23 -3
- package/package.json +1 -1
|
@@ -28,14 +28,9 @@ function flagsByStatus(sections) {
|
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
function symptomLines(
|
|
31
|
+
function symptomLines(sections, stamp, fallbackSymptom = null) {
|
|
32
32
|
const grade = [1, 2, 3].includes(sections?.grade) ? `G${sections.grade}` : 'grado no establecido';
|
|
33
|
-
const said = [
|
|
34
|
-
inlineOf(sections?.symptom) || inlineOf(alarm?.symptom),
|
|
35
|
-
grade,
|
|
36
|
-
URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel),
|
|
37
|
-
alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null,
|
|
38
|
-
].filter(Boolean);
|
|
33
|
+
const said = [inlineOf(sections?.symptom) || fallbackSymptom || 'síntoma no especificado', grade, ...stamp].filter(Boolean);
|
|
39
34
|
const { present, absent, unassessed } = flagsByStatus(sections);
|
|
40
35
|
if (!present.length && !absent.length && !unassessed.length) return [`Síntoma: ${said.join(' · ')}`, 'Banderas rojas: no documentadas.'];
|
|
41
36
|
return [
|
|
@@ -69,33 +64,45 @@ function proposalItemLine(symptom, item) {
|
|
|
69
64
|
return parts.join(' — ');
|
|
70
65
|
}
|
|
71
66
|
|
|
72
|
-
function
|
|
67
|
+
function proposalBody({ proposal, withheldReason }) {
|
|
73
68
|
if (!proposal?.items?.length) {
|
|
74
69
|
const reason = inlineOf(withheldReason) || 'sin propuesta farmacológica';
|
|
75
|
-
return [
|
|
70
|
+
return [`No se propone tratamiento sintomático: ${reason}. Se prioriza la valoración médica.`];
|
|
76
71
|
}
|
|
77
72
|
const lines = proposal.items.map((item) => proposalItemLine(proposal.symptom, item)).filter(Boolean);
|
|
78
73
|
const declared = [...(proposal.conditions ?? []), ...(proposal.ruledOut ?? []).map((key) => `descartado: ${key}`)].map(inlineOf).filter(Boolean);
|
|
79
74
|
if (declared.length) lines.push(`Condiciones que se declararon para esta propuesta (verificar): ${declared.join(', ')}.`);
|
|
80
|
-
return
|
|
75
|
+
return lines;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function proposalHeading(entry, symptomName) {
|
|
79
|
+
const tableLabel = entry.proposal?.items?.length ? formularyFor(entry.proposal.symptom)?.label : null;
|
|
80
|
+
return tableLabel ? `${symptomName} (tabla: ${tableLabel})` : symptomName;
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
-
function composeDoctorBody({ alarm,
|
|
84
|
-
const
|
|
83
|
+
function composeDoctorBody({ alarm, shared, symptoms }) {
|
|
84
|
+
const several = symptoms.length > 1;
|
|
85
|
+
const name = (entry) => inlineOf(entry.sections?.symptom) || 'Síntoma';
|
|
86
|
+
const stamp = [
|
|
87
|
+
URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel),
|
|
88
|
+
alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null,
|
|
89
|
+
];
|
|
90
|
+
const context = shared?.oncologyContext;
|
|
85
91
|
const value = (text) => inlineOf(text) || 'no disponible';
|
|
86
92
|
return [
|
|
87
|
-
...symptomLines(
|
|
93
|
+
...symptoms.flatMap((entry, index) => symptomLines(entry.sections, index === 0 ? stamp : [], several ? null : inlineOf(alarm?.symptom))),
|
|
88
94
|
'',
|
|
89
|
-
`Caracterización: ${inlineOf(sections?.characterizationSummary) || 'no disponible'}
|
|
90
|
-
vitalsLine(
|
|
91
|
-
...(inlineOf(
|
|
95
|
+
...symptoms.map((entry) => `${several ? `Caracterización (${name(entry)})` : 'Caracterización'}: ${inlineOf(entry.sections?.characterizationSummary) || 'no disponible'}`),
|
|
96
|
+
vitalsLine(shared?.vitals),
|
|
97
|
+
...(inlineOf(shared?.objectiveData) ? [`Datos objetivos: ${inlineOf(shared.objectiveData)}`] : []),
|
|
92
98
|
'',
|
|
93
99
|
`Contexto oncológico: tratamiento ${value(context?.treatment)}; última dosis ${value(context?.lastDose)}.`,
|
|
94
100
|
`Manejo previo y respuesta: ${value(context?.priorManagement)}; respuesta ${value(context?.response)}.`,
|
|
95
101
|
'',
|
|
96
|
-
|
|
102
|
+
PROPOSAL_HEADING,
|
|
103
|
+
...symptoms.flatMap((entry) => (several ? [`${proposalHeading(entry, name(entry))}:`, ...proposalBody(entry)] : proposalBody(entry))),
|
|
97
104
|
'',
|
|
98
|
-
proposal?.items?.length ? REQUESTED_ACTION : ASSESSMENT_ACTION,
|
|
105
|
+
symptoms.some((entry) => entry.proposal?.items?.length) ? REQUESTED_ACTION : ASSESSMENT_ACTION,
|
|
99
106
|
].join('\n');
|
|
100
107
|
}
|
|
101
108
|
|
|
@@ -13,7 +13,7 @@ const { logger } = require('../../utils/logger');
|
|
|
13
13
|
const { safeParse } = require('../../utils/jsonUtils');
|
|
14
14
|
const { withTiming } = require('../../utils/tracingDecorator');
|
|
15
15
|
|
|
16
|
-
const { unproposedDrugsIn, validateProposal } = require('./treatmentProposalService');
|
|
16
|
+
const { crossSymptomIssues, unproposedDrugsIn, validateProposal } = require('./treatmentProposalService');
|
|
17
17
|
|
|
18
18
|
const CONVERSATION_TURNS = 40;
|
|
19
19
|
const TRIAGE_LIMIT = 3;
|
|
@@ -120,23 +120,39 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
|
|
|
120
120
|
|
|
121
121
|
const parsed = safeParse(readStructuredText(result), null);
|
|
122
122
|
const patientMessage = trimmed(parsed?.patientMessage);
|
|
123
|
-
|
|
123
|
+
const blocks = parsed?.symptoms === undefined ? [parsed] : parsed.symptoms;
|
|
124
|
+
if (!Array.isArray(blocks) || !blocks.length) {
|
|
125
|
+
logger.warn('[escalationDraft] generation returned a malformed symptom list', { reviewId });
|
|
126
|
+
return { completed: false, attempted: true, reason: 'the model returned a malformed symptoms list' };
|
|
127
|
+
}
|
|
128
|
+
if (parsed?.symptoms !== undefined && blocks.some((block) => !trimmed(block?.symptom))) {
|
|
129
|
+
logger.warn('[escalationDraft] a symptom block came without its symptom', { reviewId });
|
|
130
|
+
return { completed: false, attempted: true, reason: 'the model returned a symptom block without its symptom' };
|
|
131
|
+
}
|
|
132
|
+
if (blocks.some((block) => !trimmed(block?.characterizationSummary))) {
|
|
124
133
|
logger.warn('[escalationDraft] generation did not return the sectioned doctor draft', { reviewId });
|
|
125
134
|
return { completed: false, attempted: true, reason: 'the model did not return the sectioned doctor draft (characterizationSummary missing)' };
|
|
126
135
|
}
|
|
127
|
-
const settled = settleProposal(
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
136
|
+
const settled = blocks.map((block) => ({ block, ...settleProposal(block) }));
|
|
137
|
+
const proposals = settled.map((entry) => entry.proposal).filter(Boolean);
|
|
138
|
+
|
|
139
|
+
const issues = settled.flatMap((entry) => entry.invalid ?? []);
|
|
140
|
+
if (!issues.length) issues.push(...crossSymptomIssues(proposals));
|
|
141
|
+
const patientDrugs = unproposedDrugsIn(patientMessage, proposals);
|
|
142
|
+
if (!issues.length && patientDrugs.length) {
|
|
143
|
+
issues.push(`el mensaje al paciente menciona ${patientDrugs.join(', ')}, que no está en la propuesta de tratamiento`);
|
|
132
144
|
}
|
|
133
145
|
|
|
134
|
-
if (
|
|
135
|
-
logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues
|
|
136
|
-
return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${
|
|
146
|
+
if (issues.length) {
|
|
147
|
+
logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues });
|
|
148
|
+
return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${issues.join('; ')}` };
|
|
137
149
|
}
|
|
138
150
|
|
|
139
|
-
const doctorText = composeDoctorBody({
|
|
151
|
+
const doctorText = composeDoctorBody({
|
|
152
|
+
alarm: alarms[alarms.length - 1] ?? null,
|
|
153
|
+
shared: parsed,
|
|
154
|
+
symptoms: settled.map(({ block, proposal, withheldReason }) => ({ sections: block, proposal, withheldReason })),
|
|
155
|
+
});
|
|
140
156
|
|
|
141
157
|
if (!doctorText || !patientMessage) {
|
|
142
158
|
logger.warn('[escalationDraft] generation returned no usable text', { reviewId });
|
|
@@ -148,9 +164,6 @@ async function generateEscalationDraft({ code, callLogs = [], alarms = [], provi
|
|
|
148
164
|
attempted: true,
|
|
149
165
|
doctorText,
|
|
150
166
|
patientMessage,
|
|
151
|
-
proposal: settled.proposal,
|
|
152
|
-
proposalWithheldReason: settled.withheldReason,
|
|
153
|
-
...(settled.strippedItems ? { proposalStripped: settled.strippedItems } : {}),
|
|
154
167
|
protocolVersion: FORMULARY_VERSION,
|
|
155
168
|
sectionsUnavailable: context.degradedSections ?? [],
|
|
156
169
|
};
|
|
@@ -7,7 +7,7 @@ const JUSTIFICATION_KINDS = Object.freeze(['prior_failure', 'contraindication',
|
|
|
7
7
|
const asSet = (values) => new Set((Array.isArray(values) ? values : []).map(key));
|
|
8
8
|
|
|
9
9
|
function moleculesOf(drug) {
|
|
10
|
-
return drug.drug.split('/').map(
|
|
10
|
+
return drug.drug.split('/').map(key).filter(Boolean);
|
|
11
11
|
}
|
|
12
12
|
|
|
13
13
|
function hasAny(set, keys = []) {
|
|
@@ -95,17 +95,37 @@ const DRUG_NAMES = [...new Set(TREATMENT_FORMULARY
|
|
|
95
95
|
.filter((drug) => drug.isPharmacological !== false)
|
|
96
96
|
.flatMap(namesOf))];
|
|
97
97
|
|
|
98
|
-
function
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
.map((item) => findDrug(entry, item))
|
|
102
|
-
|
|
103
|
-
|
|
98
|
+
function resolvedDrugs(proposals) {
|
|
99
|
+
return proposals.filter(Boolean).flatMap((proposal) => {
|
|
100
|
+
const entry = formularyFor(proposal.symptom);
|
|
101
|
+
return entry ? proposal.items.map((item) => findDrug(entry, item)).filter(Boolean).map((drug) => ({ drug, entry })) : [];
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function unproposedDrugsIn(text, proposals) {
|
|
106
|
+
const proposed = new Set(resolvedDrugs(proposals).flatMap(({ drug }) => namesOf(drug)));
|
|
104
107
|
const padded = ` ${key(text)} `;
|
|
105
108
|
return DRUG_NAMES.filter((name) => !proposed.has(name) && padded.includes(` ${name} `));
|
|
106
109
|
}
|
|
107
110
|
|
|
111
|
+
function crossSymptomIssues(proposals) {
|
|
112
|
+
const issues = [];
|
|
113
|
+
const classes = new Map();
|
|
114
|
+
const molecules = new Map();
|
|
115
|
+
for (const { drug, entry } of resolvedDrugs(proposals)) {
|
|
116
|
+
const owner = `${drug.drug} (${entry.label})`;
|
|
117
|
+
if (classes.has(drug.class)) issues.push(`un solo fármaco por clase (${drug.class}) entre síntomas: ${classes.get(drug.class)} y ${owner}`);
|
|
118
|
+
else classes.set(drug.class, owner);
|
|
119
|
+
for (const molecule of moleculesOf(drug)) {
|
|
120
|
+
if (molecules.has(molecule)) issues.push(`${molecule} aparece en dos síntomas: ${molecules.get(molecule)} y ${owner}`);
|
|
121
|
+
else molecules.set(molecule, owner);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return issues;
|
|
125
|
+
}
|
|
126
|
+
|
|
108
127
|
module.exports = {
|
|
109
128
|
validateProposal,
|
|
110
129
|
unproposedDrugsIn,
|
|
130
|
+
crossSymptomIssues,
|
|
111
131
|
};
|
|
@@ -6,13 +6,19 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
|
6
6
|
|
|
7
7
|
const { addLinkedRecord } = require('../services/airtableService');
|
|
8
8
|
|
|
9
|
+
const RECORD_ID_RX = /^rec[A-Za-z0-9]{14}$/;
|
|
10
|
+
|
|
11
|
+
// physicianId links the receta to a physicians row; the Airtable automation picks the PDF template from that physician's specialty.
|
|
9
12
|
const createPrescriptionController = async (req, res) => {
|
|
10
|
-
const { prescription, triggeredBy, creationSource = 'other' } = req.body;
|
|
13
|
+
const { prescription, triggeredBy, creationSource = 'other', physicianId } = req.body;
|
|
11
14
|
let code = req.body.code;
|
|
12
15
|
|
|
13
16
|
if (!code) return res.status(400).json({ success: false, error: 'Code is required' });
|
|
14
17
|
if (!prescription) return res.status(400).json({ success: false, error: 'Prescription is required' });
|
|
15
18
|
if (!triggeredBy) return res.status(400).json({ success: false, error: 'triggeredBy is required' });
|
|
19
|
+
if (physicianId !== undefined && (typeof physicianId !== 'string' || !RECORD_ID_RX.test(physicianId))) {
|
|
20
|
+
return res.status(400).json({ success: false, error: 'physicianId must be an Airtable record id' });
|
|
21
|
+
}
|
|
16
22
|
|
|
17
23
|
try {
|
|
18
24
|
code = ensureWhatsAppFormat(code);
|
|
@@ -24,7 +30,8 @@ const createPrescriptionController = async (req, res) => {
|
|
|
24
30
|
prescription,
|
|
25
31
|
author_email: triggeredBy,
|
|
26
32
|
creation_source: creationSource,
|
|
27
|
-
created: new Date().toISOString()
|
|
33
|
+
created: new Date().toISOString(),
|
|
34
|
+
...(physicianId && { physician: [physicianId] })
|
|
28
35
|
},
|
|
29
36
|
{
|
|
30
37
|
referenceTable: 'estado_general',
|
|
@@ -34,7 +41,7 @@ const createPrescriptionController = async (req, res) => {
|
|
|
34
41
|
code
|
|
35
42
|
);
|
|
36
43
|
|
|
37
|
-
logger.info('[PrescriptionController] Prescription created', { code });
|
|
44
|
+
logger.info('[PrescriptionController] Prescription created', { code, physicianId });
|
|
38
45
|
res.status(201).json({ success: true, message: 'Prescription created', recordId: record?.id || null });
|
|
39
46
|
} catch (error) {
|
|
40
47
|
logger.error('[PrescriptionController] Error creating prescription', { error: error.message, code });
|
|
@@ -1075,7 +1075,24 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
1075
1075
|
}, { recommendation: finalText });
|
|
1076
1076
|
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
|
|
1077
1077
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
1078
|
-
|
|
1078
|
+
const sent = await syncCase(review, operator, requestId);
|
|
1079
|
+
if (review.status !== 'indications_sent' || decision === 'needs_intervention' || result.success !== true) return sent;
|
|
1080
|
+
const decidedAt = new Date(review.decisions[decisionNumber - 1]?.createdAt ?? 0).getTime();
|
|
1081
|
+
if ((review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > decidedAt)) {
|
|
1082
|
+
logger.warn('[EscalationReview] An alarm arrived after the doctor decided; the review stays open for it', {
|
|
1083
|
+
escalationReviewId: String(review._id),
|
|
1084
|
+
});
|
|
1085
|
+
return sent;
|
|
1086
|
+
}
|
|
1087
|
+
try {
|
|
1088
|
+
const closed = await closeEscalationReview({ id: reviewId, closedBy: operator, requestId, expectedAlarmCount: (review.alarms ?? []).length });
|
|
1089
|
+
return { ...closed, caseMirror: sent.caseMirror, caseMirrors: sent.caseMirrors };
|
|
1090
|
+
} catch (error) {
|
|
1091
|
+
logger.error('[EscalationReview] The indications were delivered but the review did not close; close it by hand', {
|
|
1092
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
1093
|
+
});
|
|
1094
|
+
return { ...sent, review: await loadReview(reviewId).catch(() => sent.review) };
|
|
1095
|
+
}
|
|
1079
1096
|
}
|
|
1080
1097
|
|
|
1081
1098
|
const EPISODE_TRUST = 0.7;
|
|
@@ -1134,7 +1151,7 @@ async function recordEpisode(review, now = new Date()) {
|
|
|
1134
1151
|
}
|
|
1135
1152
|
}
|
|
1136
1153
|
|
|
1137
|
-
async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null } = {}) {
|
|
1154
|
+
async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null } = {}) {
|
|
1138
1155
|
const reviewId = reviewIdOf(id);
|
|
1139
1156
|
const operator = requiredText(closedBy, 'closedBy');
|
|
1140
1157
|
|
|
@@ -1159,7 +1176,10 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
|
|
|
1159
1176
|
reviewId,
|
|
1160
1177
|
interrupted ? [current.status] : CLOSABLE_STATUSES,
|
|
1161
1178
|
{ $set: closure },
|
|
1162
|
-
|
|
1179
|
+
{
|
|
1180
|
+
...(interrupted ? { operationClaim: current.operationClaim ?? null } : {}),
|
|
1181
|
+
...(expectedAlarmCount === null ? {} : { alarms: { $size: expectedAlarmCount } }),
|
|
1182
|
+
},
|
|
1163
1183
|
);
|
|
1164
1184
|
const closeChanges = { action: interrupted ? 'closed_from_interruption' : 'closed' };
|
|
1165
1185
|
if (interrupted) closeChanges.fromStatus = current.status;
|