@peopl-health/nexus 5.59.0-dev.10671 → 5.59.0-dev.10731

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.
@@ -28,14 +28,9 @@ function flagsByStatus(sections) {
28
28
  };
29
29
  }
30
30
 
31
- function symptomLines(alarm, sections) {
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 proposalLines({ proposal, withheldReason }) {
67
+ function proposalBody({ proposal, withheldReason }) {
73
68
  if (!proposal?.items?.length) {
74
69
  const reason = inlineOf(withheldReason) || 'sin propuesta farmacológica';
75
- return [PROPOSAL_HEADING, `No se propone tratamiento sintomático: ${reason}. Se prioriza la valoración médica.`];
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 [PROPOSAL_HEADING, ...lines];
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, sections, proposal, withheldReason }) {
84
- const context = sections?.oncologyContext;
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(alarm, sections),
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(sections?.vitals),
91
- ...(inlineOf(sections?.objectiveData) ? [`Datos objetivos: ${inlineOf(sections.objectiveData)}`] : []),
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
- ...proposalLines({ proposal, withheldReason }),
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
- if (!trimmed(parsed?.characterizationSummary)) {
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(parsed);
128
-
129
- const patientDrugs = unproposedDrugsIn(patientMessage, settled.proposal);
130
- if (!settled.invalid && patientDrugs.length) {
131
- settled.invalid = [`el mensaje al paciente menciona ${patientDrugs.join(', ')}, que no está en la propuesta de tratamiento`];
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 (settled.invalid) {
135
- logger.warn('[escalationDraft] the treatment proposal broke the formulary rules', { reviewId, issues: settled.invalid });
136
- return { completed: false, attempted: true, reason: `the treatment proposal broke the formulary rules: ${settled.invalid.join('; ')}` };
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({ alarm: alarms[alarms.length - 1] ?? null, sections: parsed, proposal: settled.proposal, withheldReason: settled.withheldReason });
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((part) => key(part).split(' ')[0]).filter(Boolean);
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 unproposedDrugsIn(text, proposal) {
99
- const entry = proposal ? formularyFor(proposal.symptom) : null;
100
- const proposed = new Set((entry ? proposal.items : [])
101
- .map((item) => findDrug(entry, item))
102
- .filter(Boolean)
103
- .flatMap(namesOf));
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 });
@@ -930,7 +930,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
930
930
  const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : message.body;
931
931
  const handoff = {
932
932
  $push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, sentBy: operator } },
933
- $set: { patientCaseRecordIds },
933
+ $addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
934
934
  $unset: { identityBlock: '' },
935
935
  };
936
936
  const recordUpdate = withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
@@ -1075,7 +1075,27 @@ 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
- return syncCase(review, operator, requestId);
1078
+ const sent = await syncCase(review, operator, requestId);
1079
+ if (review.status !== 'indications_sent' || decision === 'needs_intervention') return sent;
1080
+ const decided = review.decisions[decisionNumber - 1];
1081
+ const decidedOn = new Date(review.drafts?.[decided?.draftNumber - 1]?.createdAt ?? decided?.createdAt ?? 0).getTime();
1082
+ if ((review.alarms ?? []).some((alarm) => new Date(alarm.raisedAt).getTime() > decidedOn)) {
1083
+ logger.warn('[EscalationReview] An alarm arrived after the draft the doctor decided on; the review stays open for it', {
1084
+ escalationReviewId: String(review._id),
1085
+ });
1086
+ return sent;
1087
+ }
1088
+ try {
1089
+ const closed = await closeEscalationReview({ id: reviewId, closedBy: operator, requestId, expectedAlarmCount: (review.alarms ?? []).length });
1090
+ return closed;
1091
+ } catch (error) {
1092
+ const stored = await loadReview(reviewId).catch(() => sent.review);
1093
+ let note = 'The indications were delivered but the review did not close; close it by hand';
1094
+ if (stored.status === 'closed') note = 'The review closed, but a step after closing failed';
1095
+ else if (error.statusCode === 409) note = 'An alarm joined while the review was closing; it stays open for it';
1096
+ logger.error(`[EscalationReview] ${note}`, { escalationReviewId: String(review._id), error: redactedError(error) });
1097
+ return { ...sent, review: stored };
1098
+ }
1079
1099
  }
1080
1100
 
1081
1101
  const EPISODE_TRUST = 0.7;
@@ -1134,7 +1154,7 @@ async function recordEpisode(review, now = new Date()) {
1134
1154
  }
1135
1155
  }
1136
1156
 
1137
- async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null } = {}) {
1157
+ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null } = {}) {
1138
1158
  const reviewId = reviewIdOf(id);
1139
1159
  const operator = requiredText(closedBy, 'closedBy');
1140
1160
 
@@ -1159,12 +1179,21 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
1159
1179
  reviewId,
1160
1180
  interrupted ? [current.status] : CLOSABLE_STATUSES,
1161
1181
  { $set: closure },
1162
- interrupted ? { operationClaim: current.operationClaim ?? null } : {},
1182
+ {
1183
+ ...(interrupted ? { operationClaim: current.operationClaim ?? null } : {}),
1184
+ ...(expectedAlarmCount === null ? {} : { alarms: { $size: expectedAlarmCount } }),
1185
+ },
1163
1186
  );
1164
1187
  const closeChanges = { action: interrupted ? 'closed_from_interruption' : 'closed' };
1165
1188
  if (interrupted) closeChanges.fromStatus = current.status;
1166
1189
  if (queued) closeChanges.deliveryConfirmed = true;
1167
- await audit(review, operator, requestId, closeChanges);
1190
+ try {
1191
+ await audit(review, operator, requestId, closeChanges);
1192
+ } catch (error) {
1193
+ logger.error('[EscalationReview] The review closed but its audit entry was not written', {
1194
+ escalationReviewId: String(review._id), error: redactedError(error),
1195
+ });
1196
+ }
1168
1197
  await recordEpisode(review);
1169
1198
  return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
1170
1199
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.0-dev.10671",
3
+ "version": "5.59.0-dev.10731",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",