@peopl-health/nexus 5.72.15 → 5.72.17

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.
package/lib/fhir/index.js CHANGED
@@ -27,7 +27,7 @@ const {
27
27
  } = require('./services/palliativeService');
28
28
  const { storeTriage } = require('./services/triageService');
29
29
  const { storePatient, storePatientDeceased, readPatient } = require('./services/patientService');
30
- const { storeHospitalization } = require('./services/encounterService');
30
+ const { storeHospitalization, readHospitalization } = require('./services/encounterService');
31
31
  const {
32
32
  storeContextFacts, readContextFacts, retractContextFacts, listContextFactPatients,
33
33
  } = require('./services/clinicalContextService');
@@ -88,6 +88,7 @@ module.exports = {
88
88
  storePatient,
89
89
  storePatientDeceased,
90
90
  storeHospitalization,
91
+ readHospitalization,
91
92
  readPatient,
92
93
  storeContextFacts,
93
94
  readContextFacts,
@@ -27,6 +27,8 @@ const TICKET_STATUS_TO_TASK_STATUS = {
27
27
  failed: 'failed',
28
28
  };
29
29
 
30
+ const CANCEL_REASON_CODES = ['no_requiere', 'paciente_fallecido'];
31
+
30
32
  class Task {
31
33
  constructor(payload) {
32
34
  Object.assign(this, payload);
@@ -83,7 +85,7 @@ class Task {
83
85
  }
84
86
  // Only a code reaches FHIR: the operator's cancellation note is free text.
85
87
  if (review.status === 'cancelled') {
86
- const reasonCode = String(review.cancellationReason ?? '').startsWith('no_requiere') ? 'no_requiere' : 'cancelado_por_equipo';
88
+ const reasonCode = CANCEL_REASON_CODES.find((code) => String(review.cancellationReason ?? '').startsWith(code)) ?? 'cancelado_por_equipo';
87
89
  payload.statusReason = { concept: codeableConcept(reasonCode) };
88
90
  }
89
91
  const decision = review.decisions?.at(-1)?.decision;
@@ -1,4 +1,5 @@
1
1
  const { Encounter } = require('../resources/Encounter');
2
+ const { getFhirStore } = require('../stores/fhirStore');
2
3
  const { storeResources } = require('./fhirService');
3
4
 
4
5
  async function storeHospitalization({ patientId, admittedOn, dischargedOn = null }) {
@@ -7,4 +8,9 @@ async function storeHospitalization({ patientId, admittedOn, dischargedOn = null
7
8
  return { count: stored.length, ids: stored };
8
9
  }
9
10
 
10
- module.exports = { storeHospitalization };
11
+ async function readHospitalization({ patientId, admittedOn }) {
12
+ const { id } = Encounter.fromHospitalization({ patientId, admittedOn });
13
+ return getFhirStore().getByReference(`Encounter/${id}`);
14
+ }
15
+
16
+ module.exports = { storeHospitalization, readHospitalization };
@@ -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
  }
@@ -23,7 +23,7 @@ const HOSPITALIZED = 'hospitalized';
23
23
  const DISCHARGED = 'discharged';
24
24
  const STATUSES = [DECEASED, ACTIVE, HOSPITALIZED, DISCHARGED];
25
25
  const DECEASED_PROGRAM_STATUS = 'falleció';
26
- const DECEASED_REASON = 'Paciente fallecido';
26
+ const DECEASED_REASON = 'paciente_fallecido: Paciente fallecido';
27
27
  const ISO_DAY_RX = /^\d{4}-\d{2}-\d{2}$/;
28
28
 
29
29
  function pastDayOf(value, field) {
@@ -85,6 +85,13 @@ async function markThreadFields(code, fields) {
85
85
  if (!matchedCount) throw new Error('the patient has no thread');
86
86
  }
87
87
 
88
+ // The stay id is the admission day, so a same-day re-admission would overwrite the discharged stay.
89
+ async function wasDischargedOn(code, admittedOn) {
90
+ if (!patientResourceWriteLive()) return false;
91
+ const { readHospitalization } = require('../fhir');
92
+ return (await readHospitalization({ patientId: code, admittedOn }))?.status === 'completed';
93
+ }
94
+
88
95
  async function writeFhirHospitalization(code, stay) {
89
96
  if (!patientResourceWriteLive()) return;
90
97
  const { storeHospitalization } = require('../fhir');
@@ -127,6 +134,7 @@ async function markHospitalized({ code, admittedOn }) {
127
134
  const thread = await Thread.findOne({ code }, { hospitalizedAt: 1 }).lean();
128
135
  const current = thread?.hospitalizedAt?.toISOString().slice(0, 10);
129
136
  if (current && current !== admittedOn) throw httpError(409, `The patient is already hospitalized since ${current}`);
137
+ if (!current && await wasDischargedOn(code, admittedOn)) throw httpError(409, 'A stay admitted that day was already discharged');
130
138
  await writeProgramStatus(code, { internado_desde: admittedOn });
131
139
  const failed = [];
132
140
  await attempt('mark_thread', failed, () => markThreadFields(code, { hospitalizedAt: dayStart(admittedOn) }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.15",
3
+ "version": "5.72.17",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",