@peopl-health/nexus 6.7.1 → 6.8.0-dev.21713

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.
@@ -246,7 +246,8 @@ function doctorBrief({ kind, change = null, reminder = null, level, identity, dr
246
246
  const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
247
247
 
248
248
  function doctorDigestLine({ identity, draft, alarmSymptom, deadline, now, timeZone, link }) {
249
- const head = [briefCaseLine(identity, briefSymptomOf(draft, alarmSymptom), alarmSymptom), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · ');
249
+ const entry = briefSymptomOf(draft, alarmSymptom);
250
+ const head = [briefCaseLine(identity, entry, alarmSymptom), deadlineLabel(deadline, now, timeZone), briefKeyLine(draft, entry)].filter(Boolean).join(' · ');
250
251
  return `${head}: ${link}`;
251
252
  }
252
253
 
@@ -1,3 +1,5 @@
1
+ const moment = require('moment-timezone');
2
+
1
3
  const runtimeConfig = require('../config/runtimeConfig');
2
4
  const { oneLineOf } = require('../utils/coercionUtils');
3
5
  const { logger } = require('../utils/logger');
@@ -12,11 +14,16 @@ const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpen
12
14
  const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, doctorAlertMessage, doctorLink, notifiedApprover, teamAlertIdentity } = require('./escalationReviewService');
13
15
 
14
16
  const DIGEST_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_CONTENT_SID';
15
- // Meta has not approved this template.
17
+ // Meta classed this template as MARKETING, which WhatsApp may refuse to deliver.
16
18
  const DIGEST_BRIEF_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_DIGEST_BRIEF_CONTENT_SID';
17
19
  const ALERT_IDENTIFIED_TEMPLATE_KEY = 'ESCALATION_REVIEW_DOCTOR_ALERT_IDENTIFIED_CONTENT_SID';
20
+ const DIGEST_TIMES_KEY = 'ESCALATION_DOCTOR_DIGEST_TIMES';
21
+ const TIME_OF_DAY = /^(\d{1,2}):(\d{2})$/;
22
+ const DAY_MINUTES = 24 * 60;
18
23
  const DEFAULT_WINDOW_MINUTES = 60;
19
24
  const DEFAULT_LEAD_MINUTES = 120;
25
+ // With set times, a case whose deadline comes before the next one goes this long before its deadline instead.
26
+ const SLOT_LEAD_MS = 30 * 60 * 1000;
20
27
  const MAX_CASES_PER_MESSAGE = 5;
21
28
  // The template's fixed text plus the cases stay under WhatsApp's 1024 characters.
22
29
  const MAX_LINES_LENGTH = 800;
@@ -41,17 +48,49 @@ async function digestRecipient() {
41
48
  return PATIENT_CODE.test(code) ? code : null;
42
49
  }
43
50
 
44
- // The time a case queued now reaches the doctor at the latest, in the team's clock, for the group notice.
45
51
  function digestTimeOf(review, now) {
46
52
  const policy = responseDeadlinePolicy();
47
- const dueAt = Math.max(now.getTime(), digestDueAt([{ ...review, digestQueuedAt: now }], policy).getTime());
48
- return new Date(dueAt).toLocaleTimeString('es-MX', { timeZone: policy.teamHours.timeZone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });
53
+ const { timeZone } = policy.teamHours;
54
+ const dueAt = moment.tz(Math.max(now.getTime(), digestDueAt([{ ...review, digestQueuedAt: now }], policy).getTime()), timeZone);
55
+ const days = dueAt.clone().startOf('day').diff(moment.tz(now, timeZone).startOf('day'), 'days');
56
+ return [days === 1 ? 'mañana' : days > 1 && `el ${dueAt.format('DD/MM')}`, dueAt.format('HH:mm')].filter(Boolean).join(' ');
57
+ }
58
+
59
+ let loggedBadTimes = null;
60
+
61
+ function digestTimes() {
62
+ const raw = runtimeConfig.get(DIGEST_TIMES_KEY, '').trim();
63
+ if (!raw) return [];
64
+ const matches = raw.split(',').map((value) => TIME_OF_DAY.exec(value.trim()));
65
+ const minutes = matches.map((match) => match && Number(match[1]) * 60 + Number(match[2]));
66
+ // One mistyped time would silently move cases to the next day, so the whole setting is ignored instead.
67
+ if (matches.some((match, index) => !match || Number(match[2]) >= 60 || minutes[index] >= DAY_MINUTES)) {
68
+ if (loggedBadTimes !== raw) logger.error('[DoctorDigest] ESCALATION_DOCTOR_DIGEST_TIMES is not a list of HH:MM times; the rolling window is used');
69
+ loggedBadTimes = raw;
70
+ return [];
71
+ }
72
+ return minutes.sort((a, b) => a - b);
73
+ }
74
+
75
+ function nextDigestTime(from, times, timeZone) {
76
+ const day = moment.tz(from, timeZone).startOf('day');
77
+ const at = times.map((minutes) => day.clone().add(minutes, 'minutes')).find((slot) => !slot.isBefore(from))
78
+ ?? day.clone().add(1, 'day').add(times[0], 'minutes');
79
+ return at.toDate();
49
80
  }
50
81
 
51
- // The digest goes when the oldest queued case has waited the window, or earlier so every case keeps the lead before its deadline; at night, when the team day opens.
82
+ // At the next set time unless a deadline comes first, else after the window or the lead before a deadline; at night, when the team day opens.
52
83
  function digestDueAt(reviews, policy) {
53
- const window = minutesOf('ESCALATION_DOCTOR_DIGEST_WINDOW_MINUTES', DEFAULT_WINDOW_MINUTES) * 60000;
84
+ const slots = digestTimes();
54
85
  const lead = minutesOf('ESCALATION_DOCTOR_DIGEST_LEAD_MINUTES', DEFAULT_LEAD_MINUTES) * 60000;
86
+ if (slots.length) {
87
+ const oldest = new Date(Math.min(...reviews.map((review) => new Date(review.digestQueuedAt).getTime())));
88
+ // A case raised above urgent keeps the rolling lead, as its deadline runs at night too.
89
+ const beforeDeadlines = reviews.map((review) => [responseDeadlineOf(review, policy)?.dueAt, effectiveUrgencyOf(review)?.urgency === 'urgent' ? SLOT_LEAD_MS : lead])
90
+ .filter(([deadline]) => deadline).map(([deadline, before]) => deadline.getTime() - before);
91
+ return teamOpenAt(new Date(Math.min(nextDigestTime(oldest, slots, policy.teamHours.timeZone).getTime(), ...beforeDeadlines)), policy);
92
+ }
93
+ const window = minutesOf('ESCALATION_DOCTOR_DIGEST_WINDOW_MINUTES', DEFAULT_WINDOW_MINUTES) * 60000;
55
94
  const times = reviews.flatMap((review) => {
56
95
  const deadline = responseDeadlineOf(review, policy)?.dueAt;
57
96
  return [new Date(review.digestQueuedAt).getTime() + window, ...(deadline ? [deadline.getTime() - lead] : [])];
@@ -62,7 +101,7 @@ function digestDueAt(reviews, policy) {
62
101
  const briefStyle = () => runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY);
63
102
 
64
103
  // Like the direct handoff, a case without drafted symptoms needs the full alert's template.
65
- const perCaseBrief = (inWindow) => !inWindow && !runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY)
104
+ const perCaseBrief = (inWindow) => !inWindow && !digestAtSetTimes() && !runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY)
66
105
  && Boolean(runtimeConfig.get(DOCTOR_BRIEF_TEMPLATE_KEY) && runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY));
67
106
 
68
107
  function digestLines(cases, now, policy, perCase) {
@@ -105,7 +144,9 @@ function chunksOf(entries) {
105
144
 
106
145
  async function sendDigest(code, entries, inWindow, perCase) {
107
146
  const lines = entries.map(({ line }) => line);
108
- const title = !perCase && (briefStyle() ? doctorDigestTitle(entries.length) : String(entries.length));
147
+ // The old digest template's first variable is the case count.
148
+ const phrased = briefStyle() && (inWindow || runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY));
149
+ const title = !perCase && (phrased ? doctorDigestTitle(entries.length) : String(entries.length));
109
150
  const outgoing = perCase
110
151
  ? { code, contentSid: lines[0].contentSid || runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY), variables: lines[0].template, triggeredBy: OPERATOR }
111
152
  : inWindow
@@ -124,6 +165,8 @@ const audit = (review, delivered) => logPatientChange({
124
165
  changes: { escalationReviewId: String(review._id), action: delivered ? 'doctor_digest_sent' : 'doctor_digest_failed' },
125
166
  }).catch((error) => logger.error('[DoctorDigest] The audit was not written', { escalationReviewId: String(review._id), error: redacted(error) }));
126
167
 
168
+ const digestAtSetTimes = () => digestTimes().length > 0;
169
+
127
170
  // A case whose doctor's phone already rang after it was queued (a grave flag on an update) is not repeated.
128
171
  const digestStillDue = (review) => Boolean(review.digestQueuedAt) && !review.digestSentAt && !(review.doctorHandoffs ?? [])
129
172
  .some((handoff) => handoff.transport && new Date(handoff.createdAt).getTime() > new Date(review.digestQueuedAt).getTime());
@@ -186,4 +229,4 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
186
229
  return sent;
187
230
  }
188
231
 
189
- module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
232
+ module.exports = { MAX_CASES_PER_MESSAGE, digestAtSetTimes, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
@@ -91,10 +91,18 @@ async function doctorPingedRecently(review, physicianEmail, now) {
91
91
  const remindedSince = (review, ringAt) => (review.doctorAlerts ?? []).some((sent) => sent.kind === 'reminder'
92
92
  && (sent.transport || sent.possiblyDelivered) && timeOf(sent.sentAt) >= ringAt.getTime());
93
93
 
94
+ const digestRemindedFor = async (review, ringAt, physicianEmail) => timeOf(review.digestSentAt) === ringAt.getTime()
95
+ && (await getEscalationReview().countDocuments({
96
+ _id: { $ne: review._id },
97
+ digestSentAt: review.digestSentAt,
98
+ unopenedAlerts: { $elemMatch: { stage: 'doctor', ringAt, physicianEmail, skippedReason: null, error: null, transport: { $ne: null } } },
99
+ })) > 0;
100
+
94
101
  async function remindDoctor(review, { ringAt, dueAt, physicianEmail, level }, now) {
95
102
  const taken = await caseTakenReason(review, ringAt, level);
96
103
  const testPatient = !taken && (await teamAlertIdentity(review)).identity.testPatient;
97
- const skippedReason = taken || (testPatient ? 'test_patient' : null) || (remindedSince(review, ringAt) ? 'already_reminded' : null);
104
+ const skippedReason = taken || (testPatient ? 'test_patient' : null) || (remindedSince(review, ringAt) ? 'already_reminded' : null)
105
+ || (await digestRemindedFor(review, ringAt, physicianEmail) ? 'digest_reminded' : null);
98
106
  if (!skippedReason && await doctorPingedRecently(review, physicianEmail, now)) return false;
99
107
  if (!await claim(review, { stage: 'doctor', ringAt, dueAt, physicianEmail, skippedReason, sentAt: now })) return false;
100
108
  if (skippedReason) return false;
@@ -12,7 +12,7 @@ const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf,
12
12
  const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, PRE_DECISION_STATUSES, appliedLevelOf, isLiveFeverOf, caseSettledOrHospitalizedReason, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { settleCharacterization } = require('./characterizationOutcomeService');
14
14
  const { sendTeamAlert } = require('./teamAlertService');
15
- const { digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
15
+ const { digestAtSetTimes, digestDueAt, digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
16
16
 
17
17
  const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
18
18
  const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
@@ -192,7 +192,9 @@ const doctorRangSince = (review, since) => (review.doctorHandoffs ?? [])
192
192
  async function alertIfUntaken(review, clock, stage, now, policy) {
193
193
  const digestAt = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor' && digestStillDue(review)
194
194
  && new Date(review.digestQueuedAt) >= clock.stagesFrom && digestDueAt([review], policy).getTime();
195
- if (digestAt && digestAt <= stage.dueAt.getTime() + DIGEST_GRACE_MS && now.getTime() < digestAt + DIGEST_GRACE_MS) return false;
195
+ // A case waiting for a set time holds its earlier stages, since the digest goes before its deadline.
196
+ const held = digestAt && (digestAt <= stage.dueAt.getTime() + DIGEST_GRACE_MS || (stage.stage !== 'deadline' && digestAtSetTimes()));
197
+ if (held && now.getTime() < digestAt + DIGEST_GRACE_MS) return false;
196
198
  const withDoctor = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor'
197
199
  && (doctorRangSince(review, clock.stagesFrom) || new Date(review.digestSentAt ?? 0) >= clock.stagesFrom);
198
200
  const undecided = withDoctor && stage.stage === 'deadline';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.7.1",
3
+ "version": "6.8.0-dev.21713",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",