@peopl-health/nexus 5.58.5 → 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/services/escalationReviewService.js +39 -5
- package/lib/services/patientTaskService.js +12 -2
- 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
|
};
|
|
@@ -27,7 +27,7 @@ const { readNoteFacts, assertionOf } = require('../clinical/services/escalationN
|
|
|
27
27
|
const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
|
|
28
28
|
|
|
29
29
|
const { getPatientInformation, logPatientChange } = require('./patientService');
|
|
30
|
-
const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
|
|
30
|
+
const { getPatientTasks, openCaseIds, updatePatientTask } = require('./patientTaskService');
|
|
31
31
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
32
32
|
const { switchThreadStoppedStatus } = require('./threadService');
|
|
33
33
|
|
|
@@ -404,6 +404,17 @@ function ensureActiveReviewIndex(EscalationReview) {
|
|
|
404
404
|
|
|
405
405
|
const _resetEscalationReviewIndexes = () => { indexesReady = new WeakMap(); };
|
|
406
406
|
|
|
407
|
+
async function reviewCaseIds(review) {
|
|
408
|
+
try {
|
|
409
|
+
return [...new Set([...caseIdsOf(review), ...await openCaseIds(review.patientCode)])];
|
|
410
|
+
} catch (error) {
|
|
411
|
+
logger.error('[EscalationReview] The patient cases could not be read; the review keeps the cases it had', {
|
|
412
|
+
escalationReviewId: String(review._id), error: redactedError(error),
|
|
413
|
+
});
|
|
414
|
+
return caseIdsOf(review);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
407
418
|
async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseRecordIds }) {
|
|
408
419
|
const requested = patientCaseRecordIds ?? (patientCaseRecordId === null ? [] : [patientCaseRecordId]);
|
|
409
420
|
if (!Array.isArray(requested)) throw httpError(400, 'patientCaseRecordIds must be an array of case ids');
|
|
@@ -903,6 +914,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
903
914
|
template: { 1: identity.patientName, 2: identity.treatingDoctor, 3: templateSummary(review), 4: link },
|
|
904
915
|
};
|
|
905
916
|
|
|
917
|
+
const patientCaseRecordIds = await reviewCaseIds(review);
|
|
918
|
+
|
|
906
919
|
const claim = newOperationClaim();
|
|
907
920
|
await updateReview(
|
|
908
921
|
reviewId,
|
|
@@ -917,9 +930,10 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
|
|
|
917
930
|
const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : message.body;
|
|
918
931
|
const handoff = {
|
|
919
932
|
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, sentBy: operator } },
|
|
933
|
+
$set: { patientCaseRecordIds },
|
|
920
934
|
$unset: { identityBlock: '' },
|
|
921
935
|
};
|
|
922
|
-
const recordUpdate = withCaseMirror(review, handoff, { status: 'en revision_medica' });
|
|
936
|
+
const recordUpdate = withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
|
|
923
937
|
updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
|
|
924
938
|
} catch (error) {
|
|
925
939
|
await releaseReview(reviewId, 'handing_off', review.status, claim);
|
|
@@ -1061,7 +1075,24 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
|
|
|
1061
1075
|
}, { recommendation: finalText });
|
|
1062
1076
|
const review = await completeOperation(reviewId, claim, 'sending', recordUpdate, status);
|
|
1063
1077
|
await audit(review, operator, requestId, { action: status, decisionNumber, transport: delivery.transport });
|
|
1064
|
-
|
|
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
|
+
}
|
|
1065
1096
|
}
|
|
1066
1097
|
|
|
1067
1098
|
const EPISODE_TRUST = 0.7;
|
|
@@ -1120,7 +1151,7 @@ async function recordEpisode(review, now = new Date()) {
|
|
|
1120
1151
|
}
|
|
1121
1152
|
}
|
|
1122
1153
|
|
|
1123
|
-
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 } = {}) {
|
|
1124
1155
|
const reviewId = reviewIdOf(id);
|
|
1125
1156
|
const operator = requiredText(closedBy, 'closedBy');
|
|
1126
1157
|
|
|
@@ -1145,7 +1176,10 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
|
|
|
1145
1176
|
reviewId,
|
|
1146
1177
|
interrupted ? [current.status] : CLOSABLE_STATUSES,
|
|
1147
1178
|
{ $set: closure },
|
|
1148
|
-
|
|
1179
|
+
{
|
|
1180
|
+
...(interrupted ? { operationClaim: current.operationClaim ?? null } : {}),
|
|
1181
|
+
...(expectedAlarmCount === null ? {} : { alarms: { $size: expectedAlarmCount } }),
|
|
1182
|
+
},
|
|
1149
1183
|
);
|
|
1150
1184
|
const closeChanges = { action: interrupted ? 'closed_from_interruption' : 'closed' };
|
|
1151
1185
|
if (interrupted) closeChanges.fromStatus = current.status;
|
|
@@ -145,10 +145,14 @@ const byOpenThenNewest = (a, b) => (b.isOpen - a.isOpen) || (b.createdAt || '').
|
|
|
145
145
|
|
|
146
146
|
const needsUrgentAttention = (task) => task.needsAttention && task.isUrgent;
|
|
147
147
|
|
|
148
|
-
async function
|
|
148
|
+
async function readAllTasks(kind, whatsappId) {
|
|
149
149
|
const { table, fields, toTask } = TASK_KINDS[kind];
|
|
150
150
|
const rows = await getRecordByFilter(Monitoreo_ID, table, taskFilter(kind, whatsappId), null, fields, true);
|
|
151
|
-
|
|
151
|
+
return rows.map(toTask);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async function readTasks(kind, whatsappId) {
|
|
155
|
+
const tasks = (await readAllTasks(kind, whatsappId)).sort(byOpenThenNewest);
|
|
152
156
|
const capped = [...tasks.filter(needsUrgentAttention), ...tasks.filter((task) => !needsUrgentAttention(task))]
|
|
153
157
|
.slice(0, MAX_ROWS)
|
|
154
158
|
.sort(byOpenThenNewest);
|
|
@@ -160,6 +164,11 @@ async function readTasks(kind, whatsappId) {
|
|
|
160
164
|
};
|
|
161
165
|
}
|
|
162
166
|
|
|
167
|
+
async function openCaseIds(code) {
|
|
168
|
+
const cases = await readAllTasks('cases', validWhatsappId(code));
|
|
169
|
+
return cases.filter((patientCase) => patientCase.isOpen).map((patientCase) => patientCase.recordId);
|
|
170
|
+
}
|
|
171
|
+
|
|
163
172
|
async function getPatientTasks(code) {
|
|
164
173
|
const whatsappId = validWhatsappId(code);
|
|
165
174
|
const [requests, cases] = await Promise.all([readTasks('requests', whatsappId), readTasks('cases', whatsappId)]);
|
|
@@ -207,6 +216,7 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
|
|
|
207
216
|
}
|
|
208
217
|
|
|
209
218
|
module.exports = {
|
|
219
|
+
openCaseIds,
|
|
210
220
|
getPatientTasks,
|
|
211
221
|
updatePatientTask,
|
|
212
222
|
};
|