@peopl-health/nexus 5.71.33 → 5.71.35

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,6 +1,8 @@
1
1
  const { LEGACY_CONCEPT, NO_KNOWN_ALLERGY } = require('../../fhir/constants/variableRegistry');
2
2
  const { ageFrom, genderFrom } = require('../../fhir/resources/Patient');
3
- const { ageInYears } = require('../../utils/dateUtils');
3
+ const {
4
+ ageInYears, daysBetween, isoDay, mexicoDay,
5
+ } = require('../../utils/dateUtils');
4
6
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
5
7
  const { decodePair } = require('./encodedPairHelper');
6
8
 
@@ -11,6 +13,7 @@ const FIELD_LABELS = {
11
13
  diagnostico: 'Diagnóstico',
12
14
  tratamiento_actual: 'Tratamiento actual',
13
15
  medicacion_actual: 'Medicación',
16
+ tratamiento_suspendido: 'Suspendido recientemente',
14
17
  alergias_medicamentos: 'Alergias',
15
18
  comorbilidades: 'Comorbilidades',
16
19
  episodios_intercurrentes: 'Episodios',
@@ -35,8 +38,26 @@ const RETRACTED = new Set(['resolved', 'inactive', 'stopped', 'not-done']);
35
38
  // still stored and covering the field, but not rendered as what the patient has now
36
39
  const NOT_CURRENT = new Set(['completed', 'not-taking', 'preparation']);
37
40
 
41
+ // a stopped drug stays in view while its late toxicity may still show: the sign-off of 2026-10-14 asks a year for
42
+ // checkpoint inhibitors, anthracyclines, ADCs and anti-HER2; every injectable gets it to avoid a catalog read, and
43
+ // an oral anti-HER2 inhibitor gets the 90 days of any oral
44
+ const RECENTLY_STOPPED_DAYS = Object.freeze({
45
+ injectable_onco_summary: 365,
46
+ oral_onco_summary: 90,
47
+ other_meds_summary: 90,
48
+ });
49
+
38
50
  const isRetracted = (status) => RETRACTED.has(status);
39
51
 
52
+ function isRecentlyStopped(row, today = mexicoDay(new Date())) {
53
+ const windowDays = RECENTLY_STOPPED_DAYS[row.variableId];
54
+ if (!windowDays || row.status !== 'stopped') return false;
55
+ const days = daysBetween(isoDay(row.validTime), today);
56
+ return days >= 0 && days <= windowDays;
57
+ }
58
+
59
+ const dmy = (iso) => `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}`;
60
+
40
61
  function ageOf(patient) {
41
62
  const derived = ageInYears(patient?.birthDate);
42
63
  if (derived !== null && derived > 0 && derived < MAX_PLAUSIBLE_AGE) return derived;
@@ -54,9 +75,11 @@ function renderableValues(bucket) {
54
75
  return preferring(current, NO_KNOWN_ALLERGY.concept).map((row) => decodePair(row.value));
55
76
  }
56
77
 
57
- function fieldsFromFhir(rows, patient) {
78
+ function fieldsFromFhir(rows, patient, today = mexicoDay(new Date())) {
58
79
  const byVariable = new Map();
80
+ const stopped = [];
59
81
  for (const row of rows) {
82
+ if (row.value && isRecentlyStopped(row, today)) stopped.push(`${decodePair(row.value)} (a más tardar ${dmy(isoDay(row.validTime))})`);
60
83
  if (!row.value || isRetracted(row.status)) continue;
61
84
  const bucket = byVariable.get(row.variableId) || [];
62
85
  bucket.push(row);
@@ -70,6 +93,7 @@ function fieldsFromFhir(rows, patient) {
70
93
  const values = renderableValues(variables.flatMap((variableId) => byVariable.get(variableId) || []));
71
94
  if (values.length) fields[field] = values.join(VALUE_SEPARATOR);
72
95
  }
96
+ if (stopped.length) fields.tratamiento_suspendido = stopped.join(VALUE_SEPARATOR);
73
97
  return fields;
74
98
  }
75
99
 
@@ -131,6 +155,7 @@ module.exports = {
131
155
  withLegacyDemographics,
132
156
  hasClinicalContent,
133
157
  isRetracted,
158
+ isRecentlyStopped,
134
159
  renderContextBlock,
135
160
  swapProfilePortion,
136
161
  VALUE_SEPARATOR,
@@ -5,6 +5,7 @@ const { getRecordByFilter } = require('../../services/airtableService');
5
5
  const { Quimio_Ops_ID } = require('../../config/airtableConfig');
6
6
  const { MATCH_ALL } = require('../../helpers/airtableFormulaHelper');
7
7
  const { readContextFacts, listContextFactPatients, storeContextFacts } = require('../../fhir');
8
+ const { compareClaims } = require('../../fhir/helpers/contextArbitrationHelper');
8
9
  const { mapConcurrent } = require('../../utils/concurrencyUtils');
9
10
  const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
10
11
  const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
@@ -41,6 +42,7 @@ const DEFAULT_PATIENT_CONCURRENCY = 10;
41
42
  // a co-formulation such as pertuzumab/trastuzumab is each of its drugs
42
43
  const keysOf = (drug) => drug.generic.split('/').map(drugKey);
43
44
  const isCheckpoint = (key) => CHECKPOINT_INHIBITORS.has(key);
45
+ const endInstant = (day) => `${day}T00:00:00.000Z`;
44
46
  const closable = (drug) => drug.group === CLOSABLE_GROUP && !NEVER_CLOSED.has(drugKey(drug.generic));
45
47
  // the day as stated: a date-only report is stored at UTC midnight, which Mexico time would move to the day before
46
48
  const dayOf = (row) => {
@@ -49,7 +51,7 @@ const dayOf = (row) => {
49
51
  };
50
52
 
51
53
  async function loadDrugIdentity() {
52
- const catalog = await getRecordByFilter(Quimio_Ops_ID, CATALOG_TABLE, MATCH_ALL, null, CATALOG_FIELDS);
54
+ const catalog = await getRecordByFilter(Quimio_Ops_ID, CATALOG_TABLE, MATCH_ALL, null, CATALOG_FIELDS).catch(() => null);
53
55
  return catalog?.length ? buildDrugIdentity(catalog) : null;
54
56
  }
55
57
 
@@ -103,8 +105,12 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
103
105
  for (const row of facts) {
104
106
  if (row.variableId !== INJECTABLE_VARIABLE || !CURRENT_STATUSES.has(row.status ?? null)) continue;
105
107
  const reason = skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClass });
106
- if (reason) {
107
- skipped[reason] = (skipped[reason] ?? 0) + 1;
108
+ const end = reason ? null : endOf(row, chemo, identity);
109
+ // a closure that loses arbitration to the slot would change nothing and be rewritten every pass
110
+ const claim = end && { source: CLOSURE_SOURCE, trust: CLOSURE_TRUST, validTime: endInstant(end.endDate) };
111
+ const skip = reason || (compareClaims(claim, row, INJECTABLE_VARIABLE, new Date().toISOString()) > 0 ? null : 'outranked');
112
+ if (skip) {
113
+ skipped[skip] = (skipped[skip] ?? 0) + 1;
108
114
  continue;
109
115
  }
110
116
  closures.push({
@@ -114,7 +120,7 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
114
120
  status: row.status ?? null,
115
121
  since: dayOf(row),
116
122
  proposedStatus: PROPOSED_STATUS,
117
- ...endOf(row, chemo, identity),
123
+ ...end,
118
124
  evidence: {
119
125
  ultimaAplicacion: chemo.ultimaAplicacion,
120
126
  esquema: chemo.esquema.map((entry) => entry.farmaco),
@@ -134,7 +140,7 @@ const closureOf = (patientId, closure, recordTime) => ({
134
140
  status: closure.proposedStatus,
135
141
  source: CLOSURE_SOURCE,
136
142
  trust: CLOSURE_TRUST,
137
- validTime: `${closure.endDate}T00:00:00.000Z`,
143
+ validTime: endInstant(closure.endDate),
138
144
  recordTime,
139
145
  });
140
146
 
@@ -152,7 +158,12 @@ async function closeStoppedRegimens({ dryRun = true, patientScope = null, today
152
158
  if (!patientScope && !dryRun) return { ...empty, ok: false, reason: 'patient-scope-required' };
153
159
  const identity = await loadDrugIdentity();
154
160
  if (!identity) return { ...empty, ok: false, reason: 'drug-catalog-unreadable' };
155
- const scoped = inScope(await listContextFactPatients(), patientScope);
161
+ const listed = await listContextFactPatients().catch((error) => {
162
+ logger.error('[regimenCloser] Patients unreadable', { error: error.message });
163
+ return null;
164
+ });
165
+ if (!listed) return { ...empty, ok: false, reason: 'patients-unreadable' };
166
+ const scoped = inScope(listed, patientScope);
156
167
  if (!scoped) return { ...empty, ok: false, reason: 'patient-scope-must-return-boolean' };
157
168
  const patients = [];
158
169
  const skipped = {};
@@ -21,7 +21,7 @@ const { isNetActive } = require('../shared/dtos/ContingencySafetyNet');
21
21
  const { identifierValue } = require('../fhir/helpers/fhirReadHelper');
22
22
  const { resourceDisplayText } = require('../fhir/helpers/resourceDisplayHelper');
23
23
  const { RESULT_SLUG, MENTION_SLUG } = require('../fhir/constants/projectionSlugs');
24
- const { FIELD_VARIABLES, isRetracted } = require('../clinical/helpers/clinicalContextHelper');
24
+ const { FIELD_VARIABLES, isRetracted, isRecentlyStopped } = require('../clinical/helpers/clinicalContextHelper');
25
25
  const { decodePair } = require('../clinical/helpers/encodedPairHelper');
26
26
  const { warningRecord } = require('../fhir/projections/recommendationPlanProjection');
27
27
  const { getTriageRecommendationEventModel } = require('../clinical/models/triageRecommendationEventModel');
@@ -281,6 +281,7 @@ const emptyClinicalContext = () => ({
281
281
  diagnoses: [],
282
282
  treatments: [],
283
283
  medications: [],
284
+ recentlyStopped: [],
284
285
  allergies: [],
285
286
  comorbidities: [],
286
287
  performanceStatus: [],
@@ -315,8 +316,9 @@ function projectClinicalContext(contextFacts = [], riskAssessments = [], snapsho
315
316
  const group = CONTEXT_GROUPS[fact.variableId];
316
317
  const inactiveFollowup = group === 'followup' && ['revoked', 'completed'].includes(fact.status);
317
318
  if (group && !isRetracted(fact.status) && !inactiveFollowup) context[group].push(projectContextFact(fact));
319
+ if (isRecentlyStopped(fact)) context.recentlyStopped.push(projectContextFact(fact));
318
320
  }
319
- for (const group of new Set(Object.values(CONTEXT_GROUPS))) {
321
+ for (const group of new Set([...Object.values(CONTEXT_GROUPS), 'recentlyStopped'])) {
320
322
  context[group].sort((a, b) => Date.parse(b.validAt || b.recordedAt || 0) - Date.parse(a.validAt || a.recordedAt || 0));
321
323
  }
322
324
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.71.33",
3
+ "version": "5.71.35",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",