@peopl-health/nexus 5.71.17 → 5.71.19

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.
@@ -1,17 +1,16 @@
1
- const { mexicoDay } = require('../../utils/dateUtils');
1
+ 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
5
 
6
6
  const ACTIVE_DAYS = 35;
7
- 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 otra cosa, créele y avisa al equipo)';
7
+ 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
8
  const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;
9
9
  const NO_ALLERGY = /^(ninguna?s?|no|negadas?|desconocidas?|(niega|no refiere|sin|no tiene|no presenta) alergias?( conocidas| a medicamentos)?)$/;
10
10
  const NEGATION = /\b(sin|niega|no|ninguna?)\b/;
11
11
 
12
12
  const isDay = (value) => typeof value === 'string' && ISO_DAY.test(value) && !Number.isNaN(Date.parse(`${value}T00:00:00Z`));
13
13
  const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
14
- const daysBetween = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
15
14
  const addDays = (iso, days) => new Date(Date.parse(`${iso}T00:00:00Z`) + days * 86400000).toISOString().slice(0, 10);
16
15
  const fold = (value) => foldAccents(String(value || '')).toLowerCase().trim();
17
16
  const text = (value) => (typeof value === 'string' ? value.trim() : '');
@@ -42,6 +41,7 @@ function normalize(raw) {
42
41
  ajusteProximoCiclo: dated(raw.ajusteProximoCiclo, ['valor']),
43
42
  esquemaPrevio: isPlainObject(raw.esquemaPrevio) && isDay(raw.esquemaPrevio.hasta) ? { farmacos: texts(raw.esquemaPrevio.farmacos), hasta: raw.esquemaPrevio.hasta } : null,
44
43
  visitaSoporte: dated(raw.visitaSoporte, ['farmacos']),
44
+ proximaVisitaSoporte: dated(raw.proximaVisitaSoporte, ['detalle']),
45
45
  antecedentes: dated(raw.antecedentes, []),
46
46
  };
47
47
  }
@@ -55,13 +55,19 @@ function daysSinceLastCytotoxic(context, today = mexicoDay(new Date())) {
55
55
  return context?.ultimaCitotoxica ? daysBetween(context.ultimaCitotoxica, today) : null;
56
56
  }
57
57
 
58
- function chemoStatus(context, today) {
58
+ function chemoStatus(context, today, windowDays = ACTIVE_DAYS) {
59
59
  const last = context.ultimaAplicacion?.fecha;
60
60
  if (!last) return { active: false, days: null };
61
61
  const days = daysBetween(last, today);
62
62
  if (days < 0) return { active: true, days: null };
63
63
  const scheduled = context.proximaSesion && context.proximaSesion.fecha >= today;
64
- return { active: days <= ACTIVE_DAYS || Boolean(scheduled), days };
64
+ return { active: days <= windowDays || Boolean(scheduled), days };
65
+ }
66
+
67
+ // the unit confirms an appointment the day before: unconfirmed is the normal state of a later one
68
+ function confirmation(appointment) {
69
+ if (typeof appointment.confirmada !== 'boolean') return '';
70
+ return appointment.confirmada ? 'confirmada por la unidad' : 'la unidad aún no la confirma';
65
71
  }
66
72
 
67
73
  function regimenText(context) {
@@ -99,10 +105,15 @@ function chemoLines(context, today) {
99
105
  ? `Inicio de este esquema: antes del ${dmy(context.inicioEsquema.fecha)} (inicio del registro)`
100
106
  : `Inicio de este esquema: ${dmy(context.inicioEsquema.fecha)}`);
101
107
  }
102
- if (context.proximaSesion) {
108
+ if (context.proximaSesion && context.proximaSesion.fecha >= today) {
103
109
  lines.push(context.proximaSesion.tipo === 'agendada'
104
- ? `Próxima sesión: ${dmy(context.proximaSesion.fecha)} (agendada)`
105
- : `Próxima sesión: ${dmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
110
+ ? `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (${['agendada', confirmation(context.proximaSesion)].filter(Boolean).join('; ')})`
111
+ : `Próxima sesión de quimioterapia: ${dmy(context.proximaSesion.fecha)} (estimada; no la confirmes como cita)`);
112
+ }
113
+ const support = context.proximaVisitaSoporte;
114
+ if (support && support.fecha >= today) {
115
+ const care = texts(support.detalle);
116
+ lines.push(`Próxima visita a la unidad sin quimioterapia: ${dmy(support.fecha)} (${[care.join(', '), confirmation(support)].filter(Boolean).join('; ')})`);
106
117
  }
107
118
  if (context.noAplicadas.length) lines.push(`Sesiones no aplicadas en los últimos 90 días: ${context.noAplicadas.map(dmy).join(', ')}`);
108
119
  if (text(context.reaccionInfusion?.texto)) lines.push(`Reacción durante la infusión registrada: ${text(context.reaccionInfusion.texto)} (${dmy(context.reaccionInfusion.fecha)})`);
@@ -167,4 +178,4 @@ function withChemoContext(clinical, context, today = mexicoDay(new Date())) {
167
178
  }
168
179
  }
169
180
 
170
- module.exports = { daysSinceLastCytotoxic, parseChemoContext, renderChemoContext, withChemoContext };
181
+ module.exports = { chemoStatus, daysSinceLastCytotoxic, parseChemoContext, renderChemoContext, withChemoContext };
@@ -0,0 +1,60 @@
1
+ const { chemoStatus } = require('../helpers/chemoContextHelper');
2
+ const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
3
+ const { foldAccents } = require('../../utils/formatUtils');
4
+
5
+ // long enough for immunotherapy or a hormone depot given every three months
6
+ const UNIT_WINDOW_DAYS = 100;
7
+ const CONFIRMED_DAYS = 90;
8
+ const FACTS_WINDOW_DAYS = 60;
9
+ const ORAL_VARIABLE = 'oral_onco_summary';
10
+ const RADIOTHERAPY_VARIABLE = 'radiotherapy_summary';
11
+ const TREATMENT_VARIABLES = Object.freeze(['injectable_onco_summary', ORAL_VARIABLE, RADIOTHERAPY_VARIABLE]);
12
+ // order headings the unit's parser can leave in a regimen: a kind of treatment, not a drug
13
+ const GENERIC_ENTRY = /^(citotoxicos?|biologicos?|inmunoterapia|quimioterapia)$/;
14
+
15
+ const isTreatment = (row) => TREATMENT_VARIABLES.includes(row.variableId);
16
+ const isOral = (row) => row.variableId === ORAL_VARIABLE;
17
+ const within = (row, until, days) => {
18
+ const since = mexicoDay(row.validTime);
19
+ return since !== null && daysBetween(since, until) <= days;
20
+ };
21
+
22
+ // an ongoing oral is rarely restated, so an old one is kept but marked unconfirmed rather than dropped
23
+ const withOralAge = (row, today) => (within(row, today, CONFIRMED_DAYS) ? row : { ...row, unconfirmed: true });
24
+
25
+ function uniqueDrugs(esquema) {
26
+ const key = (drug) => foldAccents(drug).toLowerCase().replace(/[.\s]+$/, '');
27
+ const drugs = esquema.map((entry) => entry.farmaco.trim()).filter((drug) => !GENERIC_ENTRY.test(key(drug)));
28
+ return [...new Map(drugs.map((drug) => [key(drug), drug])).values()];
29
+ }
30
+
31
+ function unitRegimen(chemo, today) {
32
+ const last = chemo?.ultimaAplicacion?.fecha;
33
+ if (!last) return null;
34
+ const next = chemo.proximaSesion?.fecha >= today ? chemo.proximaSesion.fecha : null;
35
+ return {
36
+ drugs: uniqueDrugs(chemo.esquema),
37
+ since: chemo.inicioEsquema?.fecha ?? null,
38
+ lastApplication: last,
39
+ nextSession: next,
40
+ current: chemoStatus(chemo, today, UNIT_WINDOW_DAYS).active,
41
+ };
42
+ }
43
+
44
+ function currentRegimen({ chemo, facts, today = mexicoDay(new Date()) }) {
45
+ const rows = Array.isArray(facts) ? facts : [];
46
+ const others = rows.filter((row) => !isTreatment(row));
47
+ const orals = rows.filter(isOral).map((row) => withOralAge(row, today));
48
+ const unit = unitRegimen(chemo, today);
49
+ if (unit) {
50
+ const radiotherapy = rows.filter((row) => row.variableId === RADIOTHERAPY_VARIABLE && within(row, today, CONFIRMED_DAYS));
51
+ return { source: 'unit', unit, facts: [...orals, ...radiotherapy, ...others] };
52
+ }
53
+ const treatments = rows.filter(isTreatment);
54
+ const newest = treatments.map((row) => mexicoDay(row.validTime)).filter((day) => day && day <= today).sort().at(-1) ?? today;
55
+ const kept = treatments.filter((row) => !isOral(row) && within(row, newest, FACTS_WINDOW_DAYS));
56
+ const source = chemo === undefined ? 'unreadable' : kept.length || orals.length ? 'facts' : 'none';
57
+ return { source, unit: null, facts: [...kept, ...orals, ...others] };
58
+ }
59
+
60
+ module.exports = { currentRegimen };
package/lib/index.d.ts CHANGED
@@ -527,6 +527,50 @@ declare module '@peopl-health/nexus' {
527
527
  source?: 'weekly' | 'patient_scope';
528
528
  }): Promise<OutreachSweepResult>;
529
529
 
530
+ export interface ContextFactRow {
531
+ variableId: string;
532
+ value?: unknown;
533
+ status?: string | null;
534
+ validTime?: string | Date | null;
535
+ /** Set by currentRegimen on an oral fact over 90 days old: kept, but not confirmed as current. */
536
+ unconfirmed?: boolean;
537
+ [key: string]: any;
538
+ }
539
+
540
+ export interface UnitRegimen {
541
+ /** May be empty; each drug appears once. */
542
+ drugs: string[];
543
+ since: string | null;
544
+ lastApplication: string;
545
+ nextSession: string | null;
546
+ /** false when the unit's last application is over 100 days ago and no session is scheduled: the regimen is history, not treatment. */
547
+ current: boolean;
548
+ }
549
+
550
+ export interface ChemoContext {
551
+ ultimaAplicacion: { fecha: string; ciclo?: number; sesion?: number; total?: number } | null;
552
+ esquema: Array<{ farmaco: string; via?: string; tiempo?: string }>;
553
+ inicioEsquema: { fecha: string; anteriorAlRegistro: boolean } | null;
554
+ proximaSesion: { fecha: string; tipo: string; confirmada?: boolean } | null;
555
+ esquemaPrevio: { farmacos: string[]; hasta: string } | null;
556
+ [key: string]: any;
557
+ }
558
+
559
+ /** The chemo unit's record for a patient: null when there is none, undefined when it cannot be read. */
560
+ export function readRecordedChemo(code: string): Promise<ChemoContext | null | undefined>;
561
+
562
+ /**
563
+ * Narrows context-fact rows to the current treatment, preferring the chemo unit's regimen for infused drugs.
564
+ * `today` is a Mexico-time YYYY-MM-DD day. `source` is 'unreadable' when `chemo` is undefined; the facts are still narrowed.
565
+ * Oral facts are always kept (`unconfirmed` past 90 days). Without a unit record, infused and radiotherapy facts are kept within
566
+ * 60 days of the newest treatment fact of any kind. Statuses are not filtered: callers choose which to show.
567
+ */
568
+ export function currentRegimen(input: { chemo: ChemoContext | null | undefined; facts: ContextFactRow[] | null | undefined; today?: string }): {
569
+ source: 'unit' | 'facts' | 'unreadable' | 'none';
570
+ unit: UnitRegimen | null;
571
+ facts: ContextFactRow[];
572
+ };
573
+
530
574
  export const routes: any;
531
575
  export function setupDefaultRoutes(app: any): void;
532
576
  export function createRouter(routeDefinitions: Record<string, string>, controllers: Record<string, Function>): any;
package/lib/index.js CHANGED
@@ -47,6 +47,8 @@ const { retractContentlessFacts } = require('./clinical/services/contextCleanupS
47
47
  const { syncLegacyContext } = require('./clinical/services/legacyContextSyncService');
48
48
  const { syncClinicalContext } = require('./clinical/services/contextSyncRunner');
49
49
  const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
50
+ const { currentRegimen } = require('./clinical/services/currentRegimenService');
51
+ const { readRecordedChemo } = require('./clinical/helpers/clinicalProfileHelper');
50
52
  const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
51
53
  const { MapCache } = require('./utils/MapCache');
52
54
  const supportCandidateService = require('./clinical/services/supportCandidateService');
@@ -359,6 +361,8 @@ module.exports = {
359
361
  routes,
360
362
  syncClinicalContext,
361
363
  runProactiveOutreachSweep,
364
+ currentRegimen,
365
+ readRecordedChemo,
362
366
  syncContextFacts,
363
367
  retractContentlessFacts,
364
368
  syncLegacyContext,
@@ -54,6 +54,9 @@ const mexicoDay = (value) => {
54
54
  return at.isValid() ? at.format('YYYY-MM-DD') : null;
55
55
  };
56
56
 
57
+ // whole days from one YYYY-MM-DD day to another
58
+ const daysBetween = (from, to) => Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 86400000);
59
+
57
60
  const mexicoIsoWeek = (value) => {
58
61
  if (value === null || value === undefined || value === '') return null;
59
62
  const at = moment.tz(value instanceof Date ? value.toISOString() : value, moment.ISO_8601, MEXICO_TZ);
@@ -95,6 +98,7 @@ module.exports = {
95
98
  toIsoInstant,
96
99
  ageInYears,
97
100
  isoDay,
101
+ daysBetween,
98
102
  mexicoDay,
99
103
  mexicoIsoWeek,
100
104
  mexicoStamp,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.71.17",
3
+ "version": "5.71.19",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",