@peopl-health/nexus 5.72.16 → 5.72.18

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.
@@ -2,8 +2,10 @@ const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
2
2
  const { foldAccents } = require('../../utils/formatUtils');
3
3
  const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
4
4
  const { logger } = require('../../utils/logger');
5
+ const runtimeConfig = require('../../config/runtimeConfig');
5
6
 
6
7
  const ACTIVE_DAYS = 35;
8
+ const DEFAULT_CYTOTOXIC_WINDOW_DAYS = 42;
7
9
  const HEADER = 'Quimioterapia (registro de la unidad de quimioterapia; úsalo para contextualizar y priorizar síntomas, nunca para bajar la urgencia; no comuniques dosis ni ajustes de tratamiento; si el paciente dice algo distinto, créele: si es otra fecha de cita, que el paciente la confirme con el área de tratamiento, sin avisar al equipo; si es un dato clínico, o una sesión suspendida o cambiada por un motivo clínico, avisa al equipo)';
8
10
  const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
9
11
  const NO_ALLERGY = /^(ninguna?s?|no|negadas?|desconocidas?|(niega|no refiere|sin|no tiene|no presenta) alergias?( conocidas| a medicamentos)?)$/;
@@ -55,6 +57,28 @@ function daysSinceLastCytotoxic(context, today = mexicoDay(new Date())) {
55
57
  return context?.ultimaCitotoxica ? daysBetween(context.ultimaCitotoxica, today) : null;
56
58
  }
57
59
 
60
+ function cytotoxicWindowDays() {
61
+ const days = Number(runtimeConfig.get('FEVER_CHEMO_WINDOW_DAYS', DEFAULT_CYTOTOXIC_WINDOW_DAYS));
62
+ return Number.isFinite(days) && days > 0 ? days : DEFAULT_CYTOTOXIC_WINDOW_DAYS;
63
+ }
64
+
65
+ // context: null = the unit has no record of the patient; undefined = the record could not be read
66
+ function cytotoxicWindowStatus(context, today, windowDays) {
67
+ if (context === undefined) return 'desconocido: no se pudo leer el registro de la unidad';
68
+ if (context === null) return 'desconocido: la unidad no tiene registro de este paciente';
69
+ if (!context.ultimaCitotoxica) return 'desconocido: el registro de la unidad no tiene una fecha de quimioterapia citotóxica';
70
+ const last = dmy(context.ultimaCitotoxica);
71
+ const days = daysSinceLastCytotoxic(context, today);
72
+ if (!Number.isFinite(days) || days < 0) return `desconocido: no se puede contar desde hoy la última aplicación registrada (${last})`;
73
+ return days <= windowDays
74
+ ? `sí: última aplicación citotóxica ${last} (hace ${days} días)`
75
+ : `no según la unidad: última aplicación citotóxica ${last} (hace ${days} días)`;
76
+ }
77
+
78
+ function renderCytotoxicWindow(context, today, windowDays = cytotoxicWindowDays()) {
79
+ return `Quimioterapia citotóxica en los últimos ${windowDays} días (registro de la unidad de quimioterapia; no incluye otros centros ni quimioterapia oral): ${cytotoxicWindowStatus(context, today, windowDays)}`;
80
+ }
81
+
58
82
  function chemoStatus(context, today, windowDays = ACTIVE_DAYS) {
59
83
  const last = context.ultimaAplicacion?.fecha;
60
84
  if (!last) return { active: false, days: null };
@@ -178,4 +202,12 @@ function withChemoContext(clinical, context, today = mexicoDay(new Date())) {
178
202
  }
179
203
  }
180
204
 
181
- module.exports = { chemoStatus, daysSinceLastCytotoxic, parseChemoContext, renderChemoContext, withChemoContext };
205
+ module.exports = {
206
+ chemoStatus,
207
+ cytotoxicWindowDays,
208
+ daysSinceLastCytotoxic,
209
+ parseChemoContext,
210
+ renderChemoContext,
211
+ renderCytotoxicWindow,
212
+ withChemoContext,
213
+ };
@@ -386,6 +386,7 @@ function buildExposureBlock(profile) {
386
386
 
387
387
  function buildCasoBase({
388
388
  profile,
389
+ chemoWindow = null,
389
390
  graded = [],
390
391
  askedTerms = [],
391
392
  notApplicable = [],
@@ -419,6 +420,7 @@ function buildCasoBase({
419
420
  '### Contexto clínico del paciente (patient_context)',
420
421
  profile ? JSON.stringify(profile) : 'No disponible.',
421
422
  ...(exposure ? ['', '### Exposición antineoplásica y medicación documentadas', exposure] : []),
423
+ ...(chemoWindow ? ['', chemoWindow] : []),
422
424
  '',
423
425
  '### Síntomas del triaje (symptoms_metadata)',
424
426
  buildSymptomsMetadata({
@@ -10,7 +10,8 @@ const {
10
10
  str, arr, buildRedFlag, normalizeGateEscalation, applyRouteFloor,
11
11
  } = require('../helpers/recommendationGateHelper');
12
12
  const { buildElement, nullableStr } = require('../helpers/recommendationPlanHelper');
13
- const { readClinicalProfile } = require('../helpers/clinicalProfileHelper');
13
+ const { readClinicalProfile, readRecordedChemo } = require('../helpers/clinicalProfileHelper');
14
+ const { renderCytotoxicWindow } = require('../helpers/chemoContextHelper');
14
15
  const {
15
16
  askedTermsOf,
16
17
  sentinelTermsOf,
@@ -20,6 +21,8 @@ const {
20
21
  hasActionableFindings,
21
22
  } = require('../helpers/triageCaseBaseHelper');
22
23
  const { buildLegacyStep1, buildLegacyStep2, buildLegacyStep3 } = require('../helpers/legacyRecommendationFormatHelper');
24
+ const { chemoContextLive } = require('../flags/clinicalContextFlags');
25
+ const { mexicoDay } = require('../../utils/dateUtils');
23
26
 
24
27
  const runtimeConfig = require('../../config/runtimeConfig');
25
28
  const { triageRecommendationLive } = require('../flags/triageRecommendationFlags');
@@ -476,6 +479,9 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
476
479
  const profile = await readClinicalProfile(code);
477
480
  if (profile === undefined) return finish({ status: 'failed', stage: 'assemble', reason: 'profile_read_failed' });
478
481
  if (!profile) return finish({ status: 'failed', stage: 'assemble', reason: 'no_clinical_profile' });
482
+ const chemoWindow = chemoContextLive()
483
+ ? renderCytotoxicWindow(await readRecordedChemo(code), mexicoDay(payload.authored) || mexicoDay(new Date()))
484
+ : null;
479
485
 
480
486
  const riskRead = await readPatientRiskAssessments({ patientId: code, limit: 1, includeDiagnostics: true })
481
487
  .then(({ records, omittedCount }) => {
@@ -515,6 +521,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
515
521
  const additionalSymptoms = resolveAdditionalSymptoms(catalog, triageResponse.additionalSymptoms);
516
522
  const casoBaseFor = (stage, symptomSignals) => buildCasoBase({
517
523
  profile,
524
+ chemoWindow,
518
525
  graded,
519
526
  askedTerms,
520
527
  ...sentinels,
@@ -39,7 +39,7 @@ const {
39
39
  escalationPatientTimerLive: escalationTimerLive,
40
40
  } = require('../clinical/flags/escalationFlags');
41
41
  const { chemoContextLive } = require('../clinical/flags/clinicalContextFlags');
42
- const { daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
42
+ const { cytotoxicWindowDays, daysSinceLastCytotoxic } = require('../clinical/helpers/chemoContextHelper');
43
43
  const { readRecordedChemo } = require('../clinical/helpers/clinicalProfileHelper');
44
44
  const { composePrompt } = require('../clinical/services/promptComposerService');
45
45
  const { storeContextFacts, readContextFacts } = require('../fhir/services/clinicalContextService');
@@ -79,7 +79,6 @@ const SETTLED_TRAJECTORIES = ['improving', 'stable'];
79
79
  const ALERTED_URGENCIES = ['stat', 'asap'];
80
80
  const ALERT_MARKS = { stat: '🔴', asap: '🟠' };
81
81
  const DEFAULT_FEVER_TIMER_MINUTES = 15;
82
- const DEFAULT_FEVER_CHEMO_WINDOW_DAYS = 42;
83
82
  const FEVER_TIMER_PROMPT_ID = 'fever_patient_timer';
84
83
  const FEVER_TIMER_OPERATOR = 'fever_patient_timer';
85
84
  const FEVER_CATEGORY = 'febrile_neutropenia';
@@ -929,11 +928,6 @@ const timerMs = (key, fallback) => {
929
928
  return (Number.isFinite(minutes) && minutes > 0 ? minutes : fallback) * 60 * 1000;
930
929
  };
931
930
 
932
- const feverChemoWindowDays = () => {
933
- const days = Number(runtimeConfig.get('FEVER_CHEMO_WINDOW_DAYS', DEFAULT_FEVER_CHEMO_WINDOW_DAYS));
934
- return Number.isFinite(days) && days > 0 ? days : DEFAULT_FEVER_CHEMO_WINDOW_DAYS;
935
- };
936
-
937
931
  const appliedLevelOf = (alarm) => alarm.appliedLevel || alarm.urgencyLevel;
938
932
 
939
933
  const feverAlarmsOf = (review) => currentAlarms(review)
@@ -946,7 +940,7 @@ async function feverTimerGap(patientCode, now) {
946
940
  if (!chemo?.ultimaCitotoxica) return 'no_recorded_cytotoxic';
947
941
  const days = daysSinceLastCytotoxic(chemo, mexicoDay(now));
948
942
  if (days < 0) return 'last_cycle_in_future';
949
- return days > feverChemoWindowDays() ? 'outside_chemo_window' : null;
943
+ return days > cytotoxicWindowDays() ? 'outside_chemo_window' : null;
950
944
  }
951
945
 
952
946
  // The timer runs from the first alert of this episode at its level, so a retried alert never restarts it
@@ -3,7 +3,9 @@ const { logger } = require('../utils/logger');
3
3
  const { mapConcurrent } = require('../utils/concurrencyUtils');
4
4
  const { mexicoClock, mexicoWeekStart } = require('../utils/dateUtils');
5
5
  const { withTimeout } = require('../utils/timeoutUtils');
6
+ const { inlineOf } = require('../utils/coercionUtils');
6
7
  const { createdBetween } = require('../helpers/airtableFormulaHelper');
8
+ const { isArchivedPatientCode } = require('../helpers/twilioHelper');
7
9
  const { STATUS, worst, signatureOf, countBySignature, lastDigits, hoursAgo } = require('../helpers/healthHelper');
8
10
  const { getTurnTraceModel } = require('../clinical/models/turnTraceModel');
9
11
 
@@ -93,7 +95,8 @@ async function checkWeeklyCoverage(now) {
93
95
  ]);
94
96
  const covered = new Set(weeklies.flatMap((q) => q.patient_id || []));
95
97
  // A patient whose first triage landed this week is not due a weekly until next Sunday.
96
- const expected = patients.filter((p) => !(p.first_triage_date_received && new Date(p.first_triage_date_received) >= weekStart));
98
+ const expected = patients.filter((p) => !isArchivedPatientCode(inlineOf(p.whatsapp_id))
99
+ && !(p.first_triage_date_received && new Date(p.first_triage_date_received) >= weekStart));
97
100
  const base = {
98
101
  check: 'H2',
99
102
  key: 'weekly_coverage',
@@ -9,7 +9,7 @@ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUti
9
9
  const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
10
10
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
11
11
  const { prepareMessageMedia } = require('../helpers/mediaHelper');
12
- const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
12
+ const { ensureWhatsAppFormat, isArchivedPatientCode } = require('../helpers/twilioHelper');
13
13
  const { sendMessage } = require('../core/NexusMessaging');
14
14
 
15
15
  const { getRecordByFilter } = require('./airtableService');
@@ -66,7 +66,7 @@ async function listOfficePatients({ requestedBy }) {
66
66
  const patients = await getRecordByFilter(Estado_General_ID, 'estado_general', fieldEquals('doctor', assistant.doctor), undefined, PATIENT_FIELDS) || [];
67
67
 
68
68
  return patients
69
- .filter((patient) => inlineOf(patient.doctor) === assistant.doctor && inlineOf(patient.whatsapp_id))
69
+ .filter((patient) => inlineOf(patient.doctor) === assistant.doctor && inlineOf(patient.whatsapp_id) && !isArchivedPatientCode(inlineOf(patient.whatsapp_id)))
70
70
  .map((patient) => ({ code: inlineOf(patient.whatsapp_id), name: inlineOf(patient.name) || null }))
71
71
  .sort((a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''), 'es'));
72
72
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.16",
3
+ "version": "5.72.18",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",