@peopl-health/nexus 6.6.0-dev.20939 → 6.6.0-dev.21352

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.
@@ -6,7 +6,7 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
6
6
  const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
7
7
  const { sweepUntakenAlerts } = require('./untakenAlertService');
8
8
  const { sweepExpiredWatches } = require('./watchExpiryService');
9
- const { sweepCaseFollowUps } = require('./caseFollowUpSweepService');
9
+ const { sweepCaseFollowUps, sweepStaleQueues } = require('./caseFollowUpSweepService');
10
10
 
11
11
  const SWEEP_LIMIT = 10;
12
12
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
@@ -101,7 +101,7 @@ const watchSweeper = createIntervalSweeper({
101
101
 
102
102
  const caseFollowUpSweeper = createIntervalSweeper({
103
103
  label: '[CaseFollowUpSweep]',
104
- sweep: () => sweepCaseFollowUps(),
104
+ sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()),
105
105
  defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
106
106
  });
107
107
 
@@ -5,6 +5,7 @@ const { FOLLOWUP_STATUSES, URGENCY_RANK } = require('../models/escalationReviewM
5
5
  const RESPONSE_MINUTES = { stat: 15, asap: 60, urgent: 240, routine: 720 };
6
6
  const MAX_RESPONSE_MINUTES = 7 * 24 * 60;
7
7
  const BUSINESS_HOURS_LEVELS = ['urgent', 'routine'];
8
+ const HANDOFF_TAKES_LEVELS = ['urgent'];
8
9
  const TEAM_TIMEZONE = 'America/Mexico_City';
9
10
  const DEFAULT_TEAM_HOURS = { days: [1, 2, 3, 4, 5, 6, 7], startHour: 9, endHour: 22 };
10
11
  const UNTAKEN_STAGES = { stat: ['early', 'deadline'], asap: ['early', 'half', 'deadline'], urgent: ['half', 'deadline'] };
@@ -74,18 +75,18 @@ function dueAtFor(from, level, policy, minutes = policy.responseMinutes[level])
74
75
  return new Date(timeOf(from) + minutes * 60 * 1000);
75
76
  }
76
77
 
77
- const positiveMinutes = (key, fallback) => {
78
- const minutes = Number(runtimeConfig.get(key, fallback));
79
- return Number.isFinite(minutes) && minutes > 0 ? minutes : fallback;
78
+ const positiveSetting = (key, fallback) => {
79
+ const value = Number(runtimeConfig.get(key, fallback));
80
+ return Number.isFinite(value) && value > 0 ? value : fallback;
80
81
  };
81
82
 
82
83
  // asap leaves the team its early alert before the patient gets the numbers to call.
83
- const patientTimerMinutes = (level) => positiveMinutes(PATIENT_TIMER_KEYS[level], DEFAULT_PATIENT_TIMER_MINUTES[level]);
84
- const untakenEarlyMinutes = () => positiveMinutes('ESCALATION_UNTAKEN_EARLY_MINUTES', DEFAULT_UNTAKEN_EARLY_MINUTES);
84
+ const patientTimerMinutes = (level) => positiveSetting(PATIENT_TIMER_KEYS[level], DEFAULT_PATIENT_TIMER_MINUTES[level]);
85
+ const untakenEarlyMinutes = () => positiveSetting('ESCALATION_UNTAKEN_EARLY_MINUTES', DEFAULT_UNTAKEN_EARLY_MINUTES);
85
86
  // How long a question the patient left unanswered waits before the case goes to the doctor without the answer.
86
- const pendingWaitMinutes = (level) => (PENDING_WAIT_KEYS[level] ? positiveMinutes(PENDING_WAIT_KEYS[level], DEFAULT_PENDING_WAIT_MINUTES[level]) : null);
87
+ const pendingWaitMinutes = (level) => (PENDING_WAIT_KEYS[level] ? positiveSetting(PENDING_WAIT_KEYS[level], DEFAULT_PENDING_WAIT_MINUTES[level]) : null);
87
88
  const teamOpenAt = (now, policy) => addWorkingMinutes(now, 0, policy.teamHours);
88
- const quietReminderMinutes = () => positiveMinutes('ESCALATION_QUIET_REMINDER_MINUTES', DEFAULT_QUIET_REMINDER_MINUTES);
89
+ const quietReminderMinutes = () => positiveSetting('ESCALATION_QUIET_REMINDER_MINUTES', DEFAULT_QUIET_REMINDER_MINUTES);
89
90
 
90
91
  function untakenStagesOf(level, since, policy, { fever = false } = {}) {
91
92
  const total = policy.responseMinutes[level];
@@ -119,12 +120,14 @@ function responseDeadlineOf(review, policy) {
119
120
 
120
121
  module.exports = {
121
122
  BUSINESS_HOURS_LEVELS,
123
+ HANDOFF_TAKES_LEVELS,
122
124
  doctorReminderAt,
123
125
  effectiveUrgencyOf,
124
126
  levelsOf,
125
127
  responseDeadlineOf,
126
128
  patientTimerMinutes,
127
129
  pendingWaitMinutes,
130
+ positiveSetting,
128
131
  quietReminderMinutes,
129
132
  responseDeadlinePolicy,
130
133
  teamOpenAt,
@@ -3,7 +3,7 @@ const { createIntervalSweeper } = require('../utils/intervalSweeper');
3
3
  const { withTimeout } = require('../utils/timeoutUtils');
4
4
  const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
 
6
- const { BOOKKEEPING, DOCUMENTING_STATUSES, generateBotDraft } = require('./escalationReviewService');
6
+ const { BOOKKEEPING, DOCUMENTING_STATUSES, REFRESHABLE_STATUSES, generateBotDraft } = require('./escalationReviewService');
7
7
 
8
8
  const SWEEP_LIMIT = 1;
9
9
  const DEFAULT_SWEEP_INTERVAL_MS = 10 * 1000;
@@ -38,7 +38,7 @@ async function draftReview(EscalationReview, { _id, draftDueAt, draftAttempts =
38
38
  }
39
39
  if (retry && !willRetry) {
40
40
  const marked = await EscalationReview.updateOne(
41
- { _id, draftDueAt: lease, closedAt: null, status: { $in: DOCUMENTING_STATUSES } },
41
+ { _id, draftDueAt: lease, closedAt: null, status: { $in: [...DOCUMENTING_STATUSES, ...REFRESHABLE_STATUSES] } },
42
42
  { $set: { draftDueAt: null, draftFailedAt: new Date() } },
43
43
  BOOKKEEPING,
44
44
  );
@@ -8,16 +8,17 @@ const { readGroupMessageId } = require('../clinical/services/clinicalAirtableSer
8
8
  const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
9
9
 
10
10
  const { logPatientChange } = require('./patientService');
11
- const { BUSINESS_HOURS_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
11
+ const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
12
12
  const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, caseTakenReason, currentAlarms, doctorLink, promptedSince, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
13
13
  const { settleCharacterization } = require('./characterizationOutcomeService');
14
14
  const { sendTeamAlert } = require('./teamAlertService');
15
- const { digestStillDue, sendDueDoctorDigests } = require('./doctorDigestService');
15
+ const { 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;
19
19
  // A stage reached this late (an outage, a deploy) is not sent.
20
20
  const STALE_MS = 30 * 60 * 1000;
21
+ const DIGEST_GRACE_MS = 10 * 60 * 1000;
21
22
  const SWEEP_LIMIT = 200;
22
23
  const OPERATOR = 'bot:untakenAlert';
23
24
  const AUDIT_SOURCE = 'escalation_review';
@@ -174,8 +175,13 @@ async function claimStage(review, clock, stage, now, skippedReason = null) {
174
175
  const doctorRangSince = (review, since) => (review.doctorHandoffs ?? [])
175
176
  .some((handoff) => (handoff.transport || handoff.mode === 'copied') && new Date(handoff.createdAt).getTime() >= since.getTime());
176
177
 
177
- async function alertIfUntaken(review, clock, stage, now) {
178
- const taken = await caseTakenReason(review, clock.since, clock.level);
178
+ async function alertIfUntaken(review, clock, stage, now, policy) {
179
+ const digestAt = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor' && digestStillDue(review)
180
+ && new Date(review.digestQueuedAt) >= clock.stagesFrom && digestDueAt([review], policy).getTime();
181
+ if (digestAt && digestAt <= stage.dueAt.getTime() + DIGEST_GRACE_MS && now.getTime() < digestAt + DIGEST_GRACE_MS) return false;
182
+ const withDoctor = HANDOFF_TAKES_LEVELS.includes(clock.level) && review.status === 'awaiting_doctor'
183
+ && (doctorRangSince(review, clock.stagesFrom) || new Date(review.digestSentAt ?? 0) >= clock.stagesFrom);
184
+ const taken = withDoctor ? 'with_doctor' : await caseTakenReason(review, clock.since, clock.level);
179
185
  if (taken) {
180
186
  await claimStage(review, clock, stage, now, taken);
181
187
  return false;
@@ -260,7 +266,7 @@ async function remindDoctorIfDue(review, clock, now, policy) {
260
266
  return !delivery.error;
261
267
  }
262
268
 
263
- // Alerts the team at each stage of a case nobody took (being with the doctor is not taken) and settles the bot's characterization.
269
+ // Alerts the team at each stage of a case nobody took (being with the doctor takes only an urgent case) and settles the bot's characterization.
264
270
  async function sweepUntakenAlerts({ now = new Date() } = {}) {
265
271
  const alerts = escalationUntakenAlertsLive();
266
272
  const autoHandoff = escalationAutoHandoffLive();
@@ -290,7 +296,7 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
290
296
  // A failed team alert must not keep the case from the doctor, so each step fails on its own.
291
297
  try {
292
298
  const stage = alerts && clock && dueStageOf(review, clock, now);
293
- if (stage && await alertIfUntaken(review, clock, stage, now)) sent += 1;
299
+ if (stage && await alertIfUntaken(review, clock, stage, now, policy)) sent += 1;
294
300
  } catch (error) {
295
301
  failed('[UntakenAlert] Could not check a review for an untaken alert', review, error);
296
302
  }
@@ -8,6 +8,8 @@ const getCurrentMexicoDateTime = (at) => nowInMexico(at).format(MEXICO_STAMP);
8
8
 
9
9
  const dayLabel = (day, now) => (day.year() === now.year() ? day.format('dddd D [de] MMMM') : day.format('dddd D [de] MMMM [de] YYYY'));
10
10
 
11
+ const getMexicoDayLabel = (day, at) => dayLabel(nowInMexico(day), nowInMexico(at));
12
+
11
13
  const getMexicoDayLabels = ({ days, at }) => {
12
14
  const now = nowInMexico(at);
13
15
  const labels = [];
@@ -113,6 +115,7 @@ module.exports = {
113
115
  addDays,
114
116
  addWorkingMinutes,
115
117
  getCurrentMexicoDateTime,
118
+ getMexicoDayLabel,
116
119
  getMexicoDayLabels,
117
120
  getMexicoUpcomingDayLabels,
118
121
  parseDate,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.6.0-dev.20939",
3
+ "version": "6.6.0-dev.21352",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",