@peopl-health/nexus 6.5.2 → 6.5.3

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.
@@ -59,11 +59,10 @@ function digestDueAt(reviews, policy) {
59
59
  return teamOpenAt(new Date(Math.min(...times)), policy);
60
60
  }
61
61
 
62
- async function digestLines(reviews, now, policy) {
62
+ function digestLines(cases, now, policy) {
63
63
  const brief = Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
64
64
  const lines = [];
65
- for (const review of reviews) {
66
- const { patient, identity } = await teamAlertIdentity(review);
65
+ for (const { review, who: { patient, identity } } of cases) {
67
66
  if (brief) {
68
67
  lines.push(doctorDigestLine({
69
68
  identity: { ...identity, patientName: identity.patientName || patient },
@@ -128,17 +127,24 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
128
127
  .some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime()));
129
128
  if (!queued.length) return 0;
130
129
  const policy = responseDeadlinePolicy();
130
+ // Dropping cases only delays the digest, so nothing is read from the patient records before any of them is due.
131
131
  if (now.getTime() < digestDueAt(queued, policy).getTime()) return 0;
132
+ const cases = [];
133
+ for (const review of queued) {
134
+ const who = await teamAlertIdentity(review);
135
+ if (!who.identity.testPatient) cases.push({ review, who });
136
+ }
137
+ if (!cases.length || now.getTime() < digestDueAt(cases.map(({ review }) => review), policy).getTime()) return 0;
132
138
 
133
139
  const code = await digestRecipient();
134
140
  if (!code) {
135
141
  logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
136
142
  return 0;
137
143
  }
138
- const lines = await digestLines(queued, now, policy);
144
+ const lines = digestLines(cases, now, policy);
139
145
  let sent = 0;
140
146
  // Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
141
- for (const chunk of chunksOf(queued.map((review, index) => ({ review, line: lines[index] })))) {
147
+ for (const chunk of chunksOf(cases.map(({ review }, index) => ({ review, line: lines[index] })))) {
142
148
  const claimed = [];
143
149
  for (const entry of chunk) {
144
150
  const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestSentAt: null, ...unclaimed };
@@ -361,8 +361,12 @@ function doctorLink(review) {
361
361
  return `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
362
362
  }
363
363
 
364
+ // A test record, by its tipo or a name starting with «test» (the rule of Airtable's notifyEmergency), alerts the team but not the doctors.
365
+ const TEST_NAME = /^test\b/i;
366
+
364
367
  function doctorIdentity(patient) {
365
368
  const patientName = inlineOf(patient?.name);
369
+ const testPatient = inlineOf(patient?.tipo).toLowerCase() === 'test' || TEST_NAME.test(patientName);
366
370
  const treatingDoctor = inlineOf(patient?.doctor) || inlineOf(patient?.doctor_auna);
367
371
  const missing = [];
368
372
  if (patientName.split(/\s+/).filter(Boolean).length < 2) missing.push('nombre completo del paciente');
@@ -370,7 +374,7 @@ function doctorIdentity(patient) {
370
374
  const demografia = safeParse(patient?.['clinical-context-json'], null)?.demografia;
371
375
  const born = ageInYears(birthDateFrom(demografia?.fecha_nacimiento));
372
376
  const age = born > 0 && born < 130 ? born : ageFrom(demografia?.edad);
373
- return { patientName, treatingDoctor, age, missing };
377
+ return { patientName, treatingDoctor, age, missing, testPatient };
374
378
  }
375
379
 
376
380
  async function readDoctorIdentity(review) {
@@ -1368,7 +1372,7 @@ async function fallbackRecipient() {
1368
1372
 
1369
1373
  // Who and where for a team alert; a patient record that cannot be read never holds the alert back.
1370
1374
  async function teamAlertIdentity(review) {
1371
- let identity = { patientName: '', treatingDoctor: '' };
1375
+ let identity = { patientName: '', treatingDoctor: '', testPatient: false };
1372
1376
  try {
1373
1377
  identity = doctorIdentity(await getPatientInformation(review.patientCode));
1374
1378
  } catch (error) {
@@ -1382,8 +1386,7 @@ async function teamAlertIdentity(review) {
1382
1386
  };
1383
1387
  }
1384
1388
 
1385
- async function teamFallbackNotice(review, urgencyLevel, alarmId) {
1386
- const { patient, doctor, link } = await teamAlertIdentity(review);
1389
+ function teamFallbackNotice(review, urgencyLevel, alarmId, { patient, doctor, link }) {
1387
1390
  const alarm = alarmFor(review, urgencyLevel, alarmId);
1388
1391
  const what = [urgencyLevel.toUpperCase(), oneLineOf(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
1389
1392
  return {
@@ -1394,7 +1397,8 @@ async function teamFallbackNotice(review, urgencyLevel, alarmId) {
1394
1397
 
1395
1398
  async function alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId) {
1396
1399
  try {
1397
- const result = await sendTeamAlert({ message: await teamFallbackNotice(review, urgencyLevel, alarmId), operator: ALERT_OPERATOR, notice: true });
1400
+ const who = await teamAlertIdentity(review);
1401
+ const result = await sendTeamAlert({ message: teamFallbackNotice(review, urgencyLevel, alarmId, who), operator: ALERT_OPERATOR, notice: true, ...(who.identity.testPatient && { withDoctors: false }) });
1398
1402
  const missed = result.phones.filter((phone) => !phone.delivered).length + (groupConfigured() && !result.group.delivered ? 1 : 0);
1399
1403
  if (result.delivered && missed) logger.warn('[EscalationReview] The team notice missed some recipients', { escalationReviewId: String(review._id), delivered: result.delivered, missed });
1400
1404
  return result.delivered ? { transport: 'team' } : null;
@@ -1866,8 +1870,9 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, handof
1866
1870
  let delivery = {};
1867
1871
  let updated;
1868
1872
  try {
1869
- if (approver) delivery = { physicianEmail: approver.email, ...(notify ? await sendDoctorAlert({ message, approver, operator }) : {}) };
1870
- const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (notify ? message.body : null);
1873
+ const rings = notify && !identity.testPatient;
1874
+ if (approver) delivery = { physicianEmail: approver.email, ...(rings ? await sendDoctorAlert({ message, approver, operator }) : {}) };
1875
+ const sent = delivery.transport === 'template' ? Object.values(message.template).join('\n') : (rings ? message.body : null);
1871
1876
  const handoff = {
1872
1877
  $push: { doctorHandoffs: { mode, draftNumber, ...delivery, message: sent, alarmCount: (review.alarms ?? []).length, sentBy: operator } },
1873
1878
  $addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
@@ -98,8 +98,7 @@ function patientPromptNote(review, stage, now) {
98
98
  return lead >= 1 ? `Si nadie lo toma, la paciente recibe los números para llamar en ${duration(lead)}` : null;
99
99
  }
100
100
 
101
- async function untakenMessage(review, clock, stage, now) {
102
- const { patient, doctor, link } = await teamAlertIdentity(review);
101
+ function untakenMessage(review, clock, stage, now, { patient, doctor, link }) {
103
102
  const deadline = deadlineText(clock, stage);
104
103
  const level = LEVEL_LABELS[clock.level];
105
104
  const action = ACTIONS[clock.level];
@@ -150,11 +149,12 @@ async function alertIfUntaken(review, clock, stage, now) {
150
149
  await claimStage(review, clock, stage, now, taken);
151
150
  return false;
152
151
  }
153
- const message = await untakenMessage(review, clock, stage, now);
152
+ const who = await teamAlertIdentity(review);
153
+ const message = untakenMessage(review, clock, stage, now, who);
154
154
  // Replies to the group message Airtable posted for this alarm, so the case reads as one thread.
155
155
  const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
156
156
  if (!await claimStage(review, clock, stage, now)) return false;
157
- const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: clock.level === 'stat' });
157
+ const result = await sendTeamAlert({ message, operator: OPERATOR, level: clock.level, quoted, withDoctors: clock.level === 'stat' && !who.identity.testPatient });
158
158
  const phonesDelivered = result.phones.filter((phone) => phone.delivered).length;
159
159
  await getEscalationReview().updateOne(
160
160
  { _id: review._id, untakenAlerts: { $elemMatch: sameStage(clock, stage) } },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.2",
3
+ "version": "6.5.3",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",