@peopl-health/nexus 5.71.20 → 5.71.22

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.
@@ -0,0 +1,60 @@
1
+ const { foldAccents } = require('../../utils/formatUtils');
2
+
3
+ const MAX_ALIAS_WORDS = 4;
4
+ const PART_SEPARATORS = /\s*(?:\+|±|,|;|\/|\(|\)|\by\b|\bcon\b)\s*/;
5
+ // a dose or a route left between separators ("100 MG / 20 ML en 500 ML glucosado", "IV/SC") names no drug
6
+ const DOSE_OR_ROUTE = /^(\d+|iv|sc|im|vo|po|ev|mg|ml|mcg|ui)(\s|$)/;
7
+
8
+ // one key for a brand, a Spanish and an English spelling: ciclofosfamida and cyclophosphamide meet
9
+ const drugKey = (name) => foldAccents(String(name ?? '')).toLowerCase()
10
+ .replace(/[^a-z0-9\s-]/g, ' ')
11
+ .replace(/ph/g, 'f').replace(/th/g, 't').replace(/y/g, 'i').replace(/rr/g, 'r')
12
+ .replace(/(ina|ine)\b/g, 'in')
13
+ .replace(/([a-z]{3})[aeo]\b/g, '$1')
14
+ .replace(/\s+/g, ' ')
15
+ .trim();
16
+
17
+ const lines = (text) => String(text ?? '').split(/[\n,;]+/).map((line) => line.trim()).filter(Boolean);
18
+
19
+ function buildDrugIdentity(catalog) {
20
+ const generics = new Map();
21
+ const aliases = new Map();
22
+ for (const row of catalog) {
23
+ const generic = String(row.generico ?? '').trim();
24
+ if (!generic) continue;
25
+ const key = drugKey(generic);
26
+ if (!generics.has(key)) generics.set(key, { generic, group: row.grupo ?? null });
27
+ for (const alias of [generic, row.farmaco, ...lines(row.variantes)]) {
28
+ const aliasKey = drugKey(alias);
29
+ if (aliasKey && !aliases.has(aliasKey)) aliases.set(aliasKey, key);
30
+ }
31
+ }
32
+ return { generics, aliases };
33
+ }
34
+
35
+ function genericsInPart(words, identity) {
36
+ const found = new Set();
37
+ for (let at = 0; at < words.length;) {
38
+ let span = Math.min(MAX_ALIAS_WORDS, words.length - at);
39
+ for (; span > 0 && !identity.aliases.has(words.slice(at, at + span).join(' ')); span -= 1);
40
+ if (span) found.add(identity.aliases.get(words.slice(at, at + span).join(' ')));
41
+ at += span || 1;
42
+ }
43
+ return found;
44
+ }
45
+
46
+ // every drug the text names; unresolved when some part of it names none the catalog knows
47
+ function drugsNamed(text, identity) {
48
+ const whole = identity.aliases.get(drugKey(text));
49
+ if (whole) return { drugs: [identity.generics.get(whole)], unresolved: false };
50
+ const keys = new Set();
51
+ let unresolved = false;
52
+ for (const part of String(text ?? '').split(PART_SEPARATORS).map(drugKey).filter(Boolean)) {
53
+ const found = genericsInPart(part.split(' '), identity);
54
+ if (!found.size && !DOSE_OR_ROUTE.test(part)) unresolved = true;
55
+ found.forEach((key) => keys.add(key));
56
+ }
57
+ return { drugs: [...keys].map((key) => identity.generics.get(key)), unresolved: unresolved || !keys.size };
58
+ }
59
+
60
+ module.exports = { drugKey, buildDrugIdentity, drugsNamed };
@@ -21,28 +21,31 @@ const MEDICAL_URGENCY_TO_SEVERITY = {
21
21
 
22
22
  const EMERGENCY_LEVELS = new Set(['stat', 'asap']);
23
23
 
24
- function pageNavigator({ severity, reason }) {
24
+ function pageNavigator({ severity, priority = null, reason }) {
25
25
  return {
26
26
  kind: 'page_navigator',
27
27
  severity,
28
+ priority,
28
29
  reason,
29
30
  requiresAck: severity === 'critical' || severity === 'high',
30
31
  };
31
32
  }
32
33
 
33
- function pageOncologist({ severity, reason }) {
34
+ function pageOncologist({ severity, priority = null, reason }) {
34
35
  return {
35
36
  kind: 'page_oncologist',
36
37
  severity,
38
+ priority,
37
39
  reason,
38
40
  requiresAck: true,
39
41
  };
40
42
  }
41
43
 
42
- function openTicket({ severity, title, reason }) {
44
+ function openTicket({ severity, priority = null, title, reason }) {
43
45
  return {
44
46
  kind: 'open_ticket',
45
47
  severity,
48
+ priority,
46
49
  title,
47
50
  reason,
48
51
  slaMinutes: SLA_MINUTES_BY_SEVERITY[severity] ?? null,
@@ -63,19 +66,21 @@ function planMedicalUrgent(signal) {
63
66
  const level = (signal?.urgencyLevel || 'urgent').toLowerCase();
64
67
  const indicators = Array.isArray(signal?.indicators) ? signal.indicators : [];
65
68
  const label = signal?.category || signal?.symptom || signal?.suspectedCondition || 'medical';
69
+ const priority = MEDICAL_URGENCY_TO_SEVERITY[level] ? level : null;
66
70
  if (EMERGENCY_LEVELS.has(level)) {
67
71
  const severity = MEDICAL_URGENCY_TO_SEVERITY[level];
68
72
  const reason = `emergency gate fired: ${indicators.join(', ') || 'unspecified'} (level=${level})`;
69
73
  return [
70
- pageOncologist({ severity, reason }),
71
- pageNavigator({ severity, reason }),
72
- openTicket({ severity, title: `EMERG: ${indicators.join(', ') || 'unspecified'}`, reason }),
74
+ pageOncologist({ severity, priority, reason }),
75
+ pageNavigator({ severity, priority, reason }),
76
+ openTicket({ severity, priority, title: `EMERG: ${indicators.join(', ') || 'unspecified'}`, reason }),
73
77
  ];
74
78
  }
75
79
  const severity = MEDICAL_URGENCY_TO_SEVERITY[level] || 'medium';
76
80
  return [
77
81
  openTicket({
78
82
  severity,
83
+ priority,
79
84
  title: `MED-${level.toUpperCase()}: ${String(label).slice(0, 60)}`,
80
85
  reason: signal?.urgencyJustification || null,
81
86
  }),
@@ -0,0 +1,125 @@
1
+ const { buildDrugIdentity, drugKey, drugsNamed } = require('../helpers/drugIdentityHelper');
2
+ const { chemoStatus } = require('../helpers/chemoContextHelper');
3
+ const { readRecordedChemo } = require('../helpers/clinicalProfileHelper');
4
+ const { getRecordByFilter } = require('../../services/airtableService');
5
+ const { Quimio_Ops_ID } = require('../../config/airtableConfig');
6
+ const { MATCH_ALL } = require('../../helpers/airtableFormulaHelper');
7
+ const { readContextFacts, listContextFactPatients } = require('../../fhir');
8
+ const { mapConcurrent } = require('../../utils/concurrencyUtils');
9
+ const { mexicoDay } = require('../../utils/dateUtils');
10
+ const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
11
+ const { logger } = require('../../utils/logger');
12
+
13
+ const CATALOG_TABLE = 'catalogo_farmacos';
14
+ const CATALOG_FIELDS = ['farmaco', 'variantes', 'generico', 'grupo'];
15
+ const ACTIVE_WINDOW_DAYS = 100;
16
+ const INJECTABLE_VARIABLE = 'injectable_onco_summary';
17
+ const CURRENT_STATUSES = new Set([null, 'taking', 'unknown', 'on-hold']);
18
+ const PROPOSED_STATUS = 'stopped';
19
+ // the unit's catalog files support care and premedication apart; only its own antineoplastics are closed
20
+ const CLOSABLE_GROUP = 'Quimioterapia';
21
+ // in that group but oral, a hormone depot, or given outside the unit: pending oncology sign-off
22
+ const NEVER_CLOSED = new Set([
23
+ 'capecitabina', 'darolutamida', 'degarelix', 'fulvestrant', 'goserelina', 'leuprorelina', 'lanreotida',
24
+ 'octreotida', 'bacilo de Calmette-Guérin', 'ácido folínico',
25
+ ].map(drugKey));
26
+ const DEFAULT_PATIENT_CONCURRENCY = 10;
27
+
28
+ // a co-formulation such as pertuzumab/trastuzumab is each of its drugs
29
+ const keysOf = (drug) => drug.generic.split('/').map(drugKey);
30
+ const closable = (drug) => drug.group === CLOSABLE_GROUP && !NEVER_CLOSED.has(drugKey(drug.generic));
31
+ // the day as stated: a date-only report is stored at UTC midnight, which Mexico time would move to the day before
32
+ const dayOf = (row) => {
33
+ const at = new Date(row.validTime ?? NaN);
34
+ return Number.isNaN(at.getTime()) ? null : at.toISOString().slice(0, 10);
35
+ };
36
+
37
+ async function loadDrugIdentity() {
38
+ const catalog = await getRecordByFilter(Quimio_Ops_ID, CATALOG_TABLE, MATCH_ALL, null, CATALOG_FIELDS);
39
+ return catalog?.length ? buildDrugIdentity(catalog) : null;
40
+ }
41
+
42
+ function skipReason(row, { chemo, identity, regimen }) {
43
+ const named = drugsNamed(row.concept ?? row.value, identity);
44
+ if (named.unresolved) return 'unresolved';
45
+ if (named.drugs.flatMap(keysOf).some((key) => regimen.has(key))) return 'in-regimen';
46
+ if (!named.drugs.every(closable)) return 'never-closed';
47
+ const since = dayOf(row);
48
+ if (!since || since >= chemo.inicioEsquema.fecha) return 'not-before-regimen';
49
+ return null;
50
+ }
51
+
52
+ function endOf(row, chemo, identity) {
53
+ const previous = new Set((chemo.esquemaPrevio?.farmacos ?? []).flatMap((name) => drugsNamed(name, identity).drugs).flatMap(keysOf));
54
+ const named = drugsNamed(row.concept ?? row.value, identity).drugs.flatMap(keysOf);
55
+ return previous.size && named.every((key) => previous.has(key))
56
+ ? { endDate: chemo.esquemaPrevio.hasta, endFrom: 'esquemaPrevio' }
57
+ : { endDate: chemo.inicioEsquema.fecha, endFrom: 'inicioEsquema' };
58
+ }
59
+
60
+ // an injectable antineoplastic the unit stopped giving: absent from its current regimen and stated before that regimen began
61
+ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date()) }) {
62
+ const none = (reason) => ({ closures: [], skipped: { [reason]: 1 } });
63
+ if (chemo === undefined) return none('chemo-unreadable');
64
+ if (!chemo?.inicioEsquema) return none('no-regimen-start');
65
+ const status = chemoStatus(chemo, today, ACTIVE_WINDOW_DAYS);
66
+ if (!status.active) return none('inactive');
67
+ // a scheduled session keeps a regimen active, but an old last application is no evidence of what it is now
68
+ if (status.days > ACTIVE_WINDOW_DAYS) return none('stale-regimen');
69
+ const named = chemo.esquema.map((entry) => drugsNamed(entry.farmaco, identity));
70
+ // a drug of the regimen the catalog cannot name could be the very drug of a slot
71
+ if (named.some((entry) => entry.unresolved)) return none('unresolved-regimen');
72
+ const regimenDrugs = named.flatMap((entry) => entry.drugs);
73
+ // a depot or support visit is no evidence the antineoplastic line changed
74
+ if (!regimenDrugs.some(closable)) return none('no-closable-regimen');
75
+ const regimen = new Set(regimenDrugs.flatMap(keysOf));
76
+ const closures = [];
77
+ const skipped = {};
78
+ for (const row of facts) {
79
+ if (row.variableId !== INJECTABLE_VARIABLE || !CURRENT_STATUSES.has(row.status ?? null)) continue;
80
+ const reason = skipReason(row, { chemo, identity, regimen });
81
+ if (reason) {
82
+ skipped[reason] = (skipped[reason] ?? 0) + 1;
83
+ continue;
84
+ }
85
+ closures.push({
86
+ conceptKey: row.conceptKey,
87
+ drug: row.value,
88
+ status: row.status ?? null,
89
+ since: dayOf(row),
90
+ proposedStatus: PROPOSED_STATUS,
91
+ ...endOf(row, chemo, identity),
92
+ evidence: {
93
+ ultimaAplicacion: chemo.ultimaAplicacion,
94
+ esquema: chemo.esquema.map((entry) => entry.farmaco),
95
+ inicioEsquema: chemo.inicioEsquema,
96
+ esquemaPrevio: chemo.esquemaPrevio,
97
+ },
98
+ });
99
+ }
100
+ return { closures, skipped };
101
+ }
102
+
103
+ async function dryRunRegimenClosures({ today = mexicoDay(new Date()) } = {}) {
104
+ const identity = await loadDrugIdentity();
105
+ if (!identity) return { ok: false, dryRun: true, reason: 'drug-catalog-unreadable', closures: 0, unreadable: 0, skipped: {}, patients: [] };
106
+ const patients = [];
107
+ const skipped = {};
108
+ let unreadable = 0;
109
+ await mapConcurrent(await listContextFactPatients(), DEFAULT_PATIENT_CONCURRENCY, async (patientId) => {
110
+ try {
111
+ const [chemo, facts] = await Promise.all([readRecordedChemo(patientId), readContextFacts({ patientId })]);
112
+ const result = proposeClosures({ chemo, facts, identity, today });
113
+ Object.entries(result.skipped).forEach(([reason, n]) => { skipped[reason] = (skipped[reason] ?? 0) + n; });
114
+ if (result.closures.length) patients.push({ patientId, closures: result.closures });
115
+ } catch (error) {
116
+ unreadable += 1;
117
+ logger.error('[regimenCloser] Patient unreadable', { code: maskSensitiveValue(patientId), error: error.message });
118
+ }
119
+ });
120
+ const closures = patients.reduce((n, patient) => n + patient.closures.length, 0);
121
+ logger.info('[regimenCloser] Dry run complete', { patients: patients.length, closures, unreadable, skipped });
122
+ return { ok: !unreadable, dryRun: true, closures, unreadable, skipped, patients };
123
+ }
124
+
125
+ module.exports = { proposeClosures, dryRunRegimenClosures };
@@ -19,6 +19,7 @@ const Webinars_Leads_ID = runtimeConfig.get('AIRTABLE_WEBINARS_LEADS_ID') || 'ap
19
19
  const Product_ID = runtimeConfig.get('AIRTABLE_PRODUCT_ID') || 'appu2YDW2pKDYLL5H';
20
20
  const Dashboard_ID = runtimeConfig.get('AIRTABLE_DASHBOARD_ID') || 'appg9YUNlfIC82MzR';
21
21
  const Estado_General_ID = runtimeConfig.get('AIRTABLE_ESTADO_GENERAL_ID') || 'appXb7LKgAuZ1d1KI';
22
+ const Quimio_Ops_ID = runtimeConfig.get('AIRTABLE_QUIMIO_OPS_ID') || 'appK0VzrMDcVGyuE9';
22
23
 
23
24
  const DEFAULT_REQUEST_TIMEOUT_MS = 60000;
24
25
 
@@ -78,6 +79,7 @@ module.exports = {
78
79
  Product_ID,
79
80
  Dashboard_ID,
80
81
  Estado_General_ID,
82
+ Quimio_Ops_ID,
81
83
  getBase: (baseKeyOrId = runtimeConfig.get('AIRTABLE_BASE_ID')) => {
82
84
  if (!airtable) {
83
85
  throw new Error('Airtable not configured. Please set AIRTABLE_API_KEY environment variable.');
@@ -42,7 +42,7 @@ class CommunicationRequest {
42
42
  identifier: [identifier(ESCALATION_SLUG, notify.eventId)],
43
43
  status: NOTIFY_STATUS_TO_CR_STATUS[notify.status],
44
44
  intent: 'plan',
45
- priority: SEVERITY_TO_PRIORITY[notify.severity] || 'routine',
45
+ priority: notify.priority || SEVERITY_TO_PRIORITY[notify.severity] || 'routine',
46
46
  category: [codeableConcept(notify.kind, { code: notify.kind, system: codeSystemUrl(ESCALATION_KIND_SLUG) })],
47
47
  subject: patientReference(notify.patientId),
48
48
  authoredOn: toIso(notify.createdAt),
@@ -32,7 +32,7 @@ class Task {
32
32
  identifier: [identifier(ESCALATION_SLUG, ticket.eventId)],
33
33
  status: TICKET_STATUS_TO_TASK_STATUS[ticket.status],
34
34
  intent: 'order',
35
- priority: SEVERITY_TO_PRIORITY[ticket.severity] || 'routine',
35
+ priority: ticket.priority || SEVERITY_TO_PRIORITY[ticket.severity] || 'routine',
36
36
  code: codeableConcept(ticket.kind, { code: ticket.kind, system: codeSystemUrl(ESCALATION_KIND_SLUG) }),
37
37
  for: patientReference(ticket.patientId),
38
38
  authoredOn: toIso(ticket.createdAt),
package/lib/index.d.ts CHANGED
@@ -571,6 +571,28 @@ declare module '@peopl-health/nexus' {
571
571
  facts: ContextFactRow[];
572
572
  };
573
573
 
574
+ export interface RegimenClosure {
575
+ conceptKey: string;
576
+ drug: string;
577
+ status: string | null;
578
+ since: string;
579
+ proposedStatus: 'stopped';
580
+ endDate: string;
581
+ endFrom: 'esquemaPrevio' | 'inicioEsquema';
582
+ evidence: { ultimaAplicacion: ChemoContext['ultimaAplicacion']; esquema: string[]; inicioEsquema: ChemoContext['inicioEsquema']; esquemaPrevio: ChemoContext['esquemaPrevio'] };
583
+ }
584
+
585
+ /** Read-only: the injectable antineoplastic slots the chemo unit's current regimen shows as stopped. Writes nothing. */
586
+ export function dryRunRegimenClosures(options?: { today?: string }): Promise<{
587
+ ok: boolean;
588
+ dryRun: true;
589
+ closures: number;
590
+ unreadable: number;
591
+ reason?: string;
592
+ skipped: Record<string, number>;
593
+ patients: Array<{ patientId: string; closures: RegimenClosure[] }>;
594
+ }>;
595
+
574
596
  export const routes: any;
575
597
  export function setupDefaultRoutes(app: any): void;
576
598
  export function createRouter(routeDefinitions: Record<string, string>, controllers: Record<string, Function>): any;
package/lib/index.js CHANGED
@@ -48,6 +48,7 @@ const { syncLegacyContext } = require('./clinical/services/legacyContextSyncServ
48
48
  const { syncClinicalContext } = require('./clinical/services/contextSyncRunner');
49
49
  const { runProactiveOutreachSweep } = require('./clinical/services/outreachSweepRunner');
50
50
  const { currentRegimen } = require('./clinical/services/currentRegimenService');
51
+ const { dryRunRegimenClosures } = require('./clinical/services/regimenCloserService');
51
52
  const { readRecordedChemo } = require('./clinical/helpers/clinicalProfileHelper');
52
53
  const { registerTool, hasTool, getToolSchemas, clearRegistry } = require('./services/toolRegistryService');
53
54
  const { MapCache } = require('./utils/MapCache');
@@ -362,6 +363,7 @@ module.exports = {
362
363
  syncClinicalContext,
363
364
  runProactiveOutreachSweep,
364
365
  currentRegimen,
366
+ dryRunRegimenClosures,
365
367
  readRecordedChemo,
366
368
  syncContextFacts,
367
369
  retractContentlessFacts,
@@ -9,6 +9,7 @@ const baseFields = {
9
9
  eventId: z.string(),
10
10
  patientId: z.string(),
11
11
  severity: z.enum(['critical', 'high', 'medium', 'low']),
12
+ priority: z.enum(['stat', 'asap', 'urgent', 'routine']).nullable().default(null),
12
13
  createdAt: dateTime,
13
14
  status: z.enum(['queued', 'sent', 'acknowledged', 'failed']).default('queued'),
14
15
  reason: z.string().nullable().default(null),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.71.20",
3
+ "version": "5.71.22",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",