@peopl-health/nexus 6.5.9 → 6.5.10

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.
@@ -10,11 +10,12 @@ const { doctorDigestLine, doctorDigestTitle } = require('../clinical/helpers/doc
10
10
  const { logPatientChange } = require('./patientService');
11
11
  const { listEscalationApprovers } = require('./physicianService');
12
12
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
13
- const { BOOKKEEPING, doctorLink, teamAlertIdentity } = require('./escalationReviewService');
13
+ const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, doctorAlertMessage, doctorLink, teamAlertIdentity } = require('./escalationReviewService');
14
14
 
15
15
  const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
16
- // Until Meta approves this template the earlier digest keeps going out.
16
+ // Meta has not approved this template.
17
17
  const DIGEST_BRIEF_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_BRIEF_CONTENT_SID';
18
+ const ALERT_IDENTIFIED_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID';
18
19
  const DEFAULT_WINDOW_MINUTES = 60;
19
20
  const DEFAULT_LEAD_MINUTES = 120;
20
21
  const MAX_CASES_PER_MESSAGE = 5;
@@ -59,13 +60,23 @@ function digestDueAt(reviews, policy) {
59
60
  return teamOpenAt(new Date(Math.min(...times)), policy);
60
61
  }
61
62
 
62
- function digestLines(cases, now, policy) {
63
- const brief = Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
63
+ const briefStyle = () => runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
64
+
65
+ // Like the direct handoff, a case without drafted symptoms needs the full alert's template.
66
+ const perCaseBrief = (inWindow) => !inWindow && !runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY)
67
+ && Boolean(runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY) && runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY));
68
+
69
+ function digestLines(cases, now, policy, perCase) {
64
70
  const lines = [];
65
71
  for (const { review, who: { patient, identity } } of cases) {
66
- if (brief) {
72
+ const named = { ...identity, patientName: identity.patientName || patient };
73
+ if (perCase) {
74
+ lines.push(doctorAlertMessage({ review, draft: review.drafts.at(-1), identity: named, link: doctorLink(review), kind: 'ready', level: 'urgent', now }));
75
+ continue;
76
+ }
77
+ if (briefStyle()) {
67
78
  lines.push(doctorDigestLine({
68
- identity: { ...identity, patientName: identity.patientName || patient },
79
+ identity: named,
69
80
  draft: review.drafts?.at(-1),
70
81
  alarmSymptom: effectiveUrgencyOf(review)?.symptom,
71
82
  deadline: responseDeadlineOf(review, policy)?.dueAt,
@@ -93,14 +104,14 @@ function chunksOf(entries) {
93
104
  return chunks;
94
105
  }
95
106
 
96
- async function sendDigest(code, entries) {
107
+ async function sendDigest(code, entries, inWindow, perCase) {
97
108
  const lines = entries.map(({ line }) => line);
98
- const briefSid = runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY);
99
- const title = briefSid ? doctorDigestTitle(entries.length) : String(entries.length);
100
- const inWindow = await isWithin24HourWindow(code);
101
- const outgoing = inWindow
102
- ? { code, body: (briefSid ? [title, ...lines] : [`🟡 Casos urgentes listos para decidir: ${title}`, '', ...lines]).join('\n'), triggeredBy: OPERATOR }
103
- : { code, contentSid: briefSid || runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: title, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
109
+ const title = !perCase && (briefStyle() ? doctorDigestTitle(entries.length) : String(entries.length));
110
+ const outgoing = perCase
111
+ ? { code, contentSid: lines[0].contentSid || runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY), variables: lines[0].template, triggeredBy: OPERATOR }
112
+ : inWindow
113
+ ? { code, body: (briefStyle() ? [title, ...lines] : [`🟡 Casos urgentes listos para decidir: ${title}`, '', ...lines]).join('\n'), triggeredBy: OPERATOR }
114
+ : { code, contentSid: runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY), variables: { 1: title, 2: lines.join(' | ') }, triggeredBy: OPERATOR };
104
115
  const result = await getMessaging().sendMessage(outgoing);
105
116
  if (!result?.success && !result?.completed) throw new Error('The doctor digest could not be sent');
106
117
  if (result?.deferred) throw new Error('The doctor digest was queued for template approval, not sent');
@@ -118,7 +129,7 @@ const audit = (review, delivered) => logPatientChange({
118
129
  const digestStillDue = (review) => Boolean(review.digestQueuedAt) && !review.digestSentAt && !(review.doctorHandoffs ?? [])
119
130
  .some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime());
120
131
 
121
- // Sends the queued urgent cases still waiting for the doctor in one message per few cases, once the digest is due.
132
+ // Sends the queued urgent cases still waiting for the doctor in one message per few cases (or one per case, as his alert), once the digest is due.
122
133
  async function sendDueDoctorDigests({ now = new Date() } = {}) {
123
134
  if (!urgentDigestLive()) return 0;
124
135
  const unclaimed = { $or: [{ digestClaimedAt: null }, { digestClaimedAt: { $lt: new Date(now.getTime() - STALE_CLAIM_MS) } }] };
@@ -143,10 +154,13 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
143
154
  logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the digest waits');
144
155
  return 0;
145
156
  }
146
- const lines = digestLines(cases, now, policy);
157
+ const inWindow = await isWithin24HourWindow(code);
158
+ const perCase = perCaseBrief(inWindow);
159
+ const lines = digestLines(cases, now, policy, perCase);
147
160
  let sent = 0;
148
161
  // Each message claims its own cases just before it goes, so a crash in between leaves the rest for the next sweep.
149
- for (const chunk of chunksOf(cases.map(({ review }, index) => ({ review, line: lines[index] })))) {
162
+ const entries = cases.map(({ review }, index) => ({ review, line: lines[index] }));
163
+ for (const chunk of perCase ? entries.map((entry) => [entry]) : chunksOf(entries)) {
150
164
  const claimed = [];
151
165
  for (const entry of chunk) {
152
166
  const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', digestSentAt: null, ...unclaimed };
@@ -156,7 +170,7 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
156
170
  const ids = claimed.map(({ review }) => review._id);
157
171
  let delivered = false;
158
172
  try {
159
- await sendDigest(code, claimed);
173
+ await sendDigest(code, claimed, inWindow, perCase);
160
174
  delivered = true;
161
175
  sent += claimed.length;
162
176
  } catch (error) {
@@ -1798,7 +1798,7 @@ async function soleApprover() {
1798
1798
  return approvers[0];
1799
1799
  }
1800
1800
 
1801
- function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null }) {
1801
+ function doctorAlertMessage({ review, draft, identity, link, kind, note, level, symptom, change, reminder = null, now = new Date() }) {
1802
1802
  const briefSid = runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
1803
1803
  // A navigator's draft is free text with no symptoms or flags to summarize, so it keeps the full alert.
1804
1804
  if (briefSid && draft.symptoms?.length) {
@@ -1813,6 +1813,7 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1813
1813
  draft,
1814
1814
  alarmSymptom: symptom ?? lead?.symptom,
1815
1815
  deadline: responseDeadlineOf(review, policy)?.dueAt,
1816
+ now,
1816
1817
  timeZone: policy.teamHours.timeZone,
1817
1818
  link,
1818
1819
  });
@@ -2536,6 +2537,7 @@ module.exports = {
2536
2537
  promptedSince,
2537
2538
  currentAlarms,
2538
2539
  DOCTOR_BRIEF_TEMPLATE_KEY,
2540
+ doctorAlertMessage,
2539
2541
  doctorLink,
2540
2542
  teamAlertIdentity,
2541
2543
  addDraft,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.5.9",
3
+ "version": "6.5.10",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",