@peopl-health/nexus 5.57.0-dev.9415 → 5.57.0-dev.9417

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.
@@ -13,6 +13,7 @@ const FIELD_LABELS = {
13
13
  medicacion_actual: 'Medicación',
14
14
  alergias_medicamentos: 'Alergias',
15
15
  comorbilidades: 'Comorbilidades',
16
+ episodios_intercurrentes: 'Episodios',
16
17
  };
17
18
 
18
19
  const FIELD_VARIABLES = Object.freeze({
@@ -21,6 +22,7 @@ const FIELD_VARIABLES = Object.freeze({
21
22
  medicacion_actual: Object.freeze(['other_meds_summary']),
22
23
  alergias_medicamentos: Object.freeze(['allergies_list']),
23
24
  comorbilidades: Object.freeze(['comorbidities_summary']),
25
+ episodios_intercurrentes: Object.freeze(['intercurrent_events_summary']),
24
26
  });
25
27
 
26
28
  const AGE_EXTENSION_SUFFIX = 'patient-age';
@@ -1,9 +1,11 @@
1
1
  const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
2
2
  const { auditReasoningSchema } = require('../helpers/auditReasoningHelper');
3
+ const { isShadowRun } = require('../helpers/shadowHelper');
4
+ const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
3
5
  const { dispatcherService } = require('../services/dispatcherService');
4
6
  const { armEscalationNet } = require('../services/contingencyDispatchService');
5
- const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
6
7
  const { recordEmergency, writeUnresolvedRequest } = require('../services/clinicalAirtableService');
8
+ const { recordEscalationAlarm } = require('../../services/escalationReviewService');
7
9
  const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
8
10
  const { logger } = require('../../utils/logger');
9
11
 
@@ -229,6 +231,18 @@ async function handler(args, context = {}) {
229
231
  });
230
232
  queued = written || duplicate;
231
233
  } else {
234
+ if (!isShadowRun() && runtime.isLive?.() !== false) await recordEscalationAlarm({
235
+ code: runtime.patientCode,
236
+ alarm: {
237
+ urgencyLevel,
238
+ category,
239
+ symptom: details.symptom || null,
240
+ evidenceQuote: details.evidence_quote || null,
241
+ suspectedCondition: details.suspected_condition || null,
242
+ recommendedAction: details.recommended_action || null,
243
+ justification: args?.urgency_justification || null,
244
+ },
245
+ });
232
246
  queued = await recordEmergency({
233
247
  code: runtime.patientCode,
234
248
  trace,
@@ -5,6 +5,7 @@ const { getDb, getModelDatabase } = require('../config/mongoConfig');
5
5
  const { logger } = require('../utils/logger');
6
6
 
7
7
  const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
+ const URGENCY_LEVELS = ['stat', 'asap', 'urgent', 'routine'];
8
9
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
9
10
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
10
11
  const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
@@ -12,6 +13,17 @@ const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLAB
12
13
  const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
13
14
  const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
14
15
 
16
+ const alarmSchema = new mongoose.Schema({
17
+ urgencyLevel: { type: String, enum: URGENCY_LEVELS, required: true },
18
+ category: { type: String, default: null },
19
+ symptom: { type: String, default: null },
20
+ evidenceQuote: { type: String, default: null },
21
+ suspectedCondition: { type: String, default: null },
22
+ recommendedAction: { type: String, default: null },
23
+ justification: { type: String, default: null },
24
+ raisedAt: { type: Date, required: true },
25
+ }, { _id: false });
26
+
15
27
  const noteFactSchema = new mongoose.Schema({
16
28
  variableId: { type: String, required: true },
17
29
  concept: { type: String, default: null },
@@ -105,6 +117,7 @@ const escalationReviewSchema = new mongoose.Schema({
105
117
  },
106
118
  openedBy: { type: String, required: true },
107
119
  assistantPausedByReview: { type: Boolean, default: false },
120
+ alarms: { type: [alarmSchema], default: [] },
108
121
  callLogs: { type: [callLogSchema], default: [] },
109
122
  noteFacts: { type: [noteFactSchema], default: [] },
110
123
  drafts: { type: [draftSchema], default: [] },
@@ -4,6 +4,8 @@ const runtimeConfig = require('../config/runtimeConfig');
4
4
  const { httpError } = require('../utils/httpErrorUtils');
5
5
  const { logger } = require('../utils/logger');
6
6
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
+ const { mexicoStamp } = require('../utils/dateUtils');
8
+ const { isoDay } = require('../utils/dateUtils');
7
9
  const {
8
10
  CALL_OUTCOMES,
9
11
  CANCELLABLE_AFTER_HANDOFF_STATUSES,
@@ -299,13 +301,42 @@ async function syncCase(review, operator, requestId) {
299
301
  }
300
302
  }
301
303
 
304
+ const URGENCY_LABELS = {
305
+ stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
306
+ };
307
+
308
+ const inlineOf = (value) => String(Array.isArray(value) ? value[0] ?? '' : value ?? '').trim();
309
+
310
+ function doctorHeader(review, patient) {
311
+ const name = inlineOf(patient?.name);
312
+ const phone = review.patientCode.replace(/^whatsapp:/, '');
313
+ const treating = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
314
+
315
+ const lines = [name ? `${name} · ${phone}` : phone];
316
+ lines.push(`Médico tratante: ${treating || 'no registrado'}`);
317
+
318
+ const alarm = review.alarms?.[review.alarms.length - 1];
319
+ if (alarm) {
320
+ const said = [
321
+ alarm.symptom,
322
+ alarm.suspectedCondition,
323
+ URGENCY_LABELS[alarm.urgencyLevel] ?? alarm.urgencyLevel,
324
+ mexicoStamp(alarm.raisedAt),
325
+ ].map(inlineOf).filter(Boolean);
326
+ if (said.length) lines.push(`Alarma: ${said.join(' · ')}`);
327
+ }
328
+ return lines.join('\n');
329
+ }
330
+
302
331
  async function sendDoctorAlert({ review, draft, approver, operator }) {
303
332
  const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
304
333
  if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
305
334
  const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
306
335
  const inWindow = await isWithin24HourWindow(doctorCode);
336
+ const patient = await getPatientInformation(review.patientCode).catch(() => null);
337
+ const body = `${doctorHeader(review, patient)}\n\n${draft.doctorText}\n\n${link}`;
307
338
  const message = inWindow
308
- ? { code: doctorCode, body: `${draft.doctorText}\n\n${link}`, triggeredBy: operator }
339
+ ? { code: doctorCode, body, triggeredBy: operator }
309
340
  : { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
310
341
  const result = await sendMessage(message);
311
342
  if (!result?.success && !result?.completed) {
@@ -375,6 +406,43 @@ async function requestedCaseIds({ patientCode, patientCaseRecordId, patientCaseR
375
406
  return recordIds;
376
407
  }
377
408
 
409
+ const BOT_OPERATOR = 'bot:reportMedicalEscalation';
410
+
411
+ async function recordEscalationAlarm({ code, alarm, now = new Date() } = {}) {
412
+ try {
413
+ const patientCode = patientCodeOf(code);
414
+ const entry = { ...alarm, raisedAt: alarm?.raisedAt ?? now };
415
+ const EscalationReview = getEscalationReview();
416
+ const join = () => EscalationReview
417
+ .findOneAndUpdate({ patientCode, closedAt: null }, { $push: { alarms: entry } }, { new: true })
418
+ .lean();
419
+
420
+ await ensureActiveReviewIndex(EscalationReview);
421
+ const joined = await join();
422
+ if (joined) {
423
+ if (!DOCUMENTING_STATUSES.includes(joined.status)) {
424
+ logger.error('[EscalationReview] An alarm arrived after the doctor already had the case', {
425
+ escalationReviewId: String(joined._id), status: joined.status, urgencyLevel: entry.urgencyLevel,
426
+ });
427
+ }
428
+ return joined;
429
+ }
430
+ try {
431
+ return (await EscalationReview.create({
432
+ patientCode, openedBy: BOT_OPERATOR, alarms: [entry], assistantPausedByReview: false,
433
+ })).toObject();
434
+ } catch (error) {
435
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
436
+ return await join();
437
+ }
438
+ } catch (error) {
439
+ logger.error('[EscalationReview] The alarm was not recorded against a review', {
440
+ error: error.message, stack: redactedStack(error),
441
+ });
442
+ return null;
443
+ }
444
+ }
445
+
378
446
  async function openEscalationReview({
379
447
  code,
380
448
  patientCaseRecordId = null,
@@ -409,11 +477,29 @@ async function openEscalationReview({
409
477
  }
410
478
  throw error;
411
479
  }
412
- const existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
480
+ let existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
413
481
  if (!existing) {
414
482
  if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
415
483
  throw httpError(409, 'This patient already has a review being opened; try again in a moment');
416
484
  }
485
+ if (recordIds.length && !(existing.patientCaseRecordIds ?? []).length) {
486
+ const adopted = await EscalationReview.findOneAndUpdate(
487
+ { _id: existing._id, closedAt: null, patientCaseRecordIds: { $size: 0 } },
488
+ { $set: { patientCaseRecordIds: recordIds } },
489
+ { new: true },
490
+ ).lean();
491
+ if (adopted) {
492
+ existing.patientCaseRecordIds = adopted.patientCaseRecordIds;
493
+ await audit(existing, operator, requestId, { action: 'cases_attached', patientCaseRecordIds: recordIds });
494
+ } else {
495
+ const fresh = await EscalationReview.findOne({ _id: existing._id, closedAt: null }).lean();
496
+ if (!fresh) {
497
+ if (pausedHere) await switchThreadStoppedStatus(patientCode, false).catch(() => {});
498
+ throw httpError(409, 'The review closed while this one was being opened; try again');
499
+ }
500
+ existing = fresh;
501
+ }
502
+ }
417
503
  if (pausedHere && existing.assistantPausedByReview !== true) {
418
504
  try {
419
505
  await EscalationReview.updateOne({ _id: existing._id }, { $set: { assistantPausedByReview: true } });
@@ -939,6 +1025,62 @@ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy,
939
1025
  return syncCase(review, operator, requestId);
940
1026
  }
941
1027
 
1028
+ const EPISODE_TRUST = 0.7;
1029
+ const EPISODE_VARIABLE = 'intercurrent_events_summary';
1030
+ const EPISODE_SOURCE = 'doctor';
1031
+
1032
+ const DECISION_WORDS = {
1033
+ approved: 'el médico aprobó las indicaciones',
1034
+ edited_approved: 'el médico aprobó las indicaciones con cambios',
1035
+ needs_intervention: 'el médico pidió valoración presencial',
1036
+ returned: 'el médico devolvió el caso a navegación',
1037
+ };
1038
+
1039
+ function episodeFact(review, now) {
1040
+ const alarm = review.alarms?.[review.alarms.length - 1];
1041
+ const named = inlineOf(alarm?.suspectedCondition) || inlineOf(alarm?.symptom);
1042
+ if (!named) return null;
1043
+
1044
+ const raisedAt = new Date(alarm?.raisedAt ?? review.createdAt ?? now);
1045
+ // The record files list-like variables by concept, so the day keeps two episodes apart.
1046
+ const concept = `${named} (${isoDay(raisedAt.toISOString())})`;
1047
+
1048
+ const handedOffAt = review.doctorHandoffs?.[review.doctorHandoffs.length - 1]?.createdAt ?? null;
1049
+ const decided = handedOffAt && raisedAt.getTime() <= new Date(handedOffAt).getTime()
1050
+ ? review.decisions?.[review.decisions.length - 1]
1051
+ : null;
1052
+
1053
+ const delivery = decided ? review.patientDelivery : null;
1054
+ const said = [
1055
+ inlineOf(alarm?.symptom) || named,
1056
+ DECISION_WORDS[decided?.decision],
1057
+ delivery?.confirmedAt || delivery?.deferred === false ? 'se le enviaron indicaciones' : null,
1058
+ ].filter(Boolean);
1059
+
1060
+ return {
1061
+ patientId: review.patientCode,
1062
+ variableId: EPISODE_VARIABLE,
1063
+ concept,
1064
+ value: said.join('. '),
1065
+ source: EPISODE_SOURCE,
1066
+ trust: EPISODE_TRUST,
1067
+ validTime: raisedAt.toISOString(),
1068
+ recordTime: new Date(now).toISOString(),
1069
+ };
1070
+ }
1071
+
1072
+ async function recordEpisode(review, now = new Date()) {
1073
+ try {
1074
+ const assertion = episodeFact(review, now);
1075
+ if (!assertion) return;
1076
+ await storeContextFacts({ patientId: review.patientCode, assertions: [assertion] });
1077
+ } catch (error) {
1078
+ logger.error('[EscalationReview] The episode did not reach the clinical record', {
1079
+ escalationReviewId: String(review._id), error: error.message, stack: redactedStack(error),
1080
+ });
1081
+ }
1082
+ }
1083
+
942
1084
  async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null } = {}) {
943
1085
  const reviewId = reviewIdOf(id);
944
1086
  const operator = requiredText(closedBy, 'closedBy');
@@ -970,6 +1112,7 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
970
1112
  if (interrupted) closeChanges.fromStatus = current.status;
971
1113
  if (queued) closeChanges.deliveryConfirmed = true;
972
1114
  await audit(review, operator, requestId, closeChanges);
1115
+ await recordEpisode(review);
973
1116
  return syncCase(await resumeAssistant(review, operator, requestId), operator, requestId);
974
1117
  }
975
1118
 
@@ -1015,6 +1158,7 @@ module.exports = {
1015
1158
  handOffToDoctor,
1016
1159
  listEscalationReviews,
1017
1160
  openEscalationReview,
1161
+ recordEscalationAlarm,
1018
1162
  recordDoctorDecision,
1019
1163
  sendApprovedIndications,
1020
1164
  setReviewCases,
@@ -34,6 +34,11 @@ const ageInYears = (birthDate) => {
34
34
  return born.isValid() ? moment.utc().diff(born, 'years') : null;
35
35
  };
36
36
 
37
+ const mexicoStamp = (value) => {
38
+ const at = Date.parse(value instanceof Date ? value.toISOString() : value);
39
+ return Number.isFinite(at) ? moment.tz(at, MEXICO_TZ).locale('es').format('D [de] MMMM, HH:mm') : null;
40
+ };
41
+
37
42
  const isoDay = (value) => (typeof value === 'string' && value.length >= 10 ? value.slice(0, 10) : null);
38
43
 
39
44
  const mexicoDay = (value) => {
@@ -55,5 +60,6 @@ module.exports = {
55
60
  ageInYears,
56
61
  isoDay,
57
62
  mexicoDay,
63
+ mexicoStamp,
58
64
  daysSince
59
65
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.0-dev.9415",
3
+ "version": "5.57.0-dev.9417",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",