@peopl-health/nexus 5.58.1 → 5.58.3

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.
@@ -31,9 +31,8 @@ function flagsByStatus(sections) {
31
31
  function symptomLines(alarm, sections) {
32
32
  const grade = [1, 2, 3].includes(sections?.grade) ? `G${sections.grade}` : 'grado no establecido';
33
33
  const said = [
34
- inlineOf(alarm?.symptom) || inlineOf(sections?.symptom),
34
+ inlineOf(sections?.symptom) || inlineOf(alarm?.symptom),
35
35
  grade,
36
- inlineOf(alarm?.suspectedCondition),
37
36
  URGENCY_LABELS[alarm?.urgencyLevel] ?? inlineOf(alarm?.urgencyLevel),
38
37
  alarm?.raisedAt ? mexicoStamp(alarm.raisedAt) : null,
39
38
  ].filter(Boolean);
@@ -89,7 +88,7 @@ function composeDoctorBody({ alarm, sections, proposal, withheldReason }) {
89
88
  '',
90
89
  `Caracterización: ${inlineOf(sections?.characterizationSummary) || 'no disponible'}`,
91
90
  vitalsLine(sections?.vitals),
92
- `Datos objetivos: ${inlineOf(sections?.objectiveData) || 'no disponibles'}`,
91
+ ...(inlineOf(sections?.objectiveData) ? [`Datos objetivos: ${inlineOf(sections.objectiveData)}`] : []),
93
92
  '',
94
93
  `Contexto oncológico: tratamiento ${value(context?.treatment)}; última dosis ${value(context?.lastDose)}.`,
95
94
  `Manejo previo y respuesta: ${value(context?.priorManagement)}; respuesta ${value(context?.response)}.`,
@@ -100,15 +99,20 @@ function composeDoctorBody({ alarm, sections, proposal, withheldReason }) {
100
99
  ].join('\n');
101
100
  }
102
101
 
103
- function renderDoctorMessage({ identity, review, doctorText, link }) {
102
+ function identityLines({ identity, review }) {
104
103
  const phone = String(review?.patientCode ?? '').replace(/^whatsapp:/, '');
105
- return [
106
- `Paciente: ${identity.patientName} · ${phone}`,
107
- `Médico tratante: ${withTitle(identity.treatingDoctor)}`,
108
- String(doctorText ?? '').trim(),
109
- '',
110
- link,
111
- ].join('\n');
104
+ return [`Paciente: ${identity.patientName} · ${phone}`, `Médico tratante: ${withTitle(identity.treatingDoctor)}`];
105
+ }
106
+
107
+ function withIdentity({ identity, review, doctorText }) {
108
+ const lines = String(doctorText ?? '').trim().split('\n');
109
+ const hasHeader = lines[0]?.startsWith('Paciente: ') && lines[1]?.startsWith('Médico tratante: ');
110
+ const body = (hasHeader ? lines.slice(2) : lines).join('\n').trim();
111
+ return [...identityLines({ identity, review }), body].join('\n');
112
+ }
113
+
114
+ function renderDoctorMessage({ identity, review, doctorText, link }) {
115
+ return [withIdentity({ identity, review, doctorText }), '', link].join('\n');
112
116
  }
113
117
 
114
118
  function templateSummary(review) {
@@ -124,5 +128,6 @@ module.exports = {
124
128
  latestAlarm,
125
129
  composeDoctorBody,
126
130
  renderDoctorMessage,
131
+ withIdentity,
127
132
  templateSummary,
128
133
  };
@@ -221,6 +221,7 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
221
221
  const rank = EMERGENCY_URGENCY_RANK[urgencyFhir];
222
222
  const priorRank = prior ? EMERGENCY_URGENCY_RANK[prior.urgencyFhir] : undefined;
223
223
  const mergeable = Boolean(prior) && rank !== undefined && priorRank !== undefined && rank <= priorRank;
224
+ const belowPrior = mergeable && rank < priorRank;
224
225
  const meta = {};
225
226
 
226
227
  return auditedWrite({
@@ -241,14 +242,21 @@ async function recordEmergency({ code, trace, symptom, suspectedCondition = '',
241
242
 
242
243
  const open = mergeable ? await readEmergencyRow(prior.recordId, code) : null;
243
244
  if (open) {
244
- const merged = [open['Documentación_emergencia'], documentation].filter(Boolean).join('\n\n');
245
+ const incoming = belowPrior
246
+ ? [symptom && `Síntoma: ${symptom}`, suspectedCondition && `Sospecha: ${suspectedCondition}`, recommendedAction && `Acción recomendada: ${recommendedAction}`]
247
+ .filter(Boolean).join(' · ')
248
+ : '';
249
+ const note = [incoming, documentation].filter(Boolean).join('\n');
250
+ const merged = [open['Documentación_emergencia'], note].filter(Boolean).join('\n\n');
251
+ let update = merged ? { ...fields, 'Documentación_emergencia': merged } : fields;
252
+ if (belowPrior) update = { 'Documentación_emergencia': merged };
245
253
  const updated = await airtableService.updateRecordByFilter(
246
- Monitoreo_ID, 'emergencies', `RECORD_ID() = '${prior.recordId}'`,
247
- merged ? { ...fields, 'Documentación_emergencia': merged } : fields, code
254
+ Monitoreo_ID, 'emergencies', `RECORD_ID() = '${prior.recordId}'`, update, code
248
255
  );
249
256
  if (updated?.length) {
250
257
  meta.mergedInto = prior.recordId;
251
- await rememberEmergency(code, prior.recordId, urgencyFhir);
258
+ if (belowPrior) meta.keptUrgencyFhir = prior.urgencyFhir;
259
+ await rememberEmergency(code, prior.recordId, belowPrior ? prior.urgencyFhir : urgencyFhir);
252
260
  return updated;
253
261
  }
254
262
  }
@@ -25,8 +25,8 @@ function withholdReason(sections) {
25
25
  const { present, unassessed } = flagsByStatus(sections);
26
26
  const modifiers = (Array.isArray(sections?.treatmentModifiers) ? sections.treatmentModifiers : []).map(trimmed).filter(Boolean);
27
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(', ')})`);
28
+ if (present.length) reasons.push(present.length === 1 ? 'hay una bandera roja presente' : 'hay banderas rojas presentes');
29
+ if (unassessed.length) reasons.push(unassessed.length === 1 ? 'hay una bandera roja sin evaluar' : 'hay banderas rojas sin evaluar');
30
30
  if (modifiers.length) reasons.push(`condición que cambia el algoritmo (${modifiers.join(', ')})`);
31
31
  return reasons.join('; ') || null;
32
32
  }
@@ -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 { renderDoctorMessage, templateSummary } = require('../clinical/helpers/doctorReviewMessageHelper');
24
+ const { renderDoctorMessage, templateSummary, withIdentity } = 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');
@@ -324,7 +324,7 @@ async function readDoctorIdentity(review) {
324
324
  }
325
325
 
326
326
  async function blockForMissingIdentity({ review, missing, operator }) {
327
- const blocked = `El mensaje al médico no se envió: falta ${missing.join(' y ')} en el expediente`;
327
+ const blocked = `No se puede preparar ni enviar el mensaje al médico: falta ${missing.join(' y ')} en el expediente`;
328
328
  await getEscalationReview().updateOne(
329
329
  { _id: review._id },
330
330
  { $set: { identityBlock: { missing, blockedAt: new Date(), blockedBy: operator } } },
@@ -342,7 +342,7 @@ async function blockForMissingIdentity({ review, missing, operator }) {
342
342
  escalationReviewId: String(review._id), missing,
343
343
  });
344
344
  }
345
- throw httpError(422, blocked);
345
+ return httpError(422, blocked);
346
346
  }
347
347
 
348
348
  async function sendDoctorAlert({ message, approver, operator }) {
@@ -653,6 +653,9 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
653
653
  const operator = requiredText(requestedBy, 'requestedBy');
654
654
  const review = await loadReview(reviewId);
655
655
  if (!DOCUMENTING_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
656
+ const identity = await readDoctorIdentity(review);
657
+ if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
658
+ if (review.identityBlock) await getEscalationReview().updateOne({ _id: review._id }, { $unset: { identityBlock: '' } });
656
659
 
657
660
  const draft = await generateEscalationDraft({
658
661
  code: review.patientCode,
@@ -682,7 +685,7 @@ async function suggestDraft({ id, requestedBy, requestId = null } = {}) {
682
685
  const settled = await loadReview(reviewId);
683
686
  if (!DOCUMENTING_STATUSES.includes(settled.status)) throw httpError(409, STATUS_CONFLICT);
684
687
 
685
- return draft;
688
+ return { ...draft, doctorText: withIdentity({ identity, review, doctorText: draft.doctorText }) };
686
689
  }
687
690
 
688
691
  async function noteFactsContext(review) {
@@ -893,7 +896,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
893
896
  throw httpError(409, 'A new alarm arrived after this draft was written; review it and save a new draft before sending it to the doctor');
894
897
  }
895
898
  const identity = await readDoctorIdentity(review);
896
- if (identity.missing.length) await blockForMissingIdentity({ review, missing: identity.missing, operator });
899
+ if (identity.missing.length) throw await blockForMissingIdentity({ review, missing: identity.missing, operator });
897
900
  const link = doctorLink(review);
898
901
  const message = {
899
902
  body: renderDoctorMessage({ identity, review, doctorText: draft.doctorText, link }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.58.1",
3
+ "version": "5.58.3",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",