@peopl-health/nexus 6.7.0-dev.21499 → 6.7.0-dev.21501

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.
@@ -56,6 +56,10 @@ function escalationCaseStatusReminderLive() {
56
56
  return flagOn('ESCALATION_CASE_STATUS_REMINDER_LIVE');
57
57
  }
58
58
 
59
+ function escalationUnopenedReminderLive() {
60
+ return flagOn('ESCALATION_UNOPENED_REMINDER_LIVE');
61
+ }
62
+
59
63
  function escalationUnreviewedCaseNoticeLive() {
60
64
  return flagOn('ESCALATION_UNREVIEWED_CASE_NOTICE_LIVE');
61
65
  }
@@ -70,6 +74,7 @@ module.exports = {
70
74
  escalationInTurnAskLive,
71
75
  escalationPatientTimerLive,
72
76
  escalationUntakenAlertsLive,
77
+ escalationUnopenedReminderLive,
73
78
  escalationUpdateModeLive,
74
79
  escalationWatchExpiryLive,
75
80
  escalationStaleQueueNoticeLive,
@@ -73,6 +73,17 @@ const untakenAlertSchema = new mongoose.Schema({
73
73
  sentAt: { type: Date, required: true },
74
74
  }, { _id: false });
75
75
 
76
+ const unopenedAlertSchema = new mongoose.Schema({
77
+ stage: { type: String, enum: ['doctor', 'team'], required: true },
78
+ ringAt: { type: Date, required: true },
79
+ dueAt: { type: Date, required: true },
80
+ physicianEmail: { type: String, default: null },
81
+ skippedReason: { type: String, default: null },
82
+ transport: { type: String, default: null },
83
+ error: { type: String, default: null },
84
+ sentAt: { type: Date, required: true },
85
+ }, { _id: false });
86
+
76
87
  const graveAlertSchema = new mongoose.Schema({
77
88
  flag: { type: String, required: true },
78
89
  level: { type: String, enum: URGENCY_LEVELS, required: true },
@@ -372,6 +383,7 @@ const escalationReviewSchema = new mongoose.Schema({
372
383
  doctorAlertKind: { type: String, enum: ['initial', 'realert', 'patient_prompt', null], default: null },
373
384
  doctorAlertAttempts: { type: Number, default: 0 },
374
385
  untakenAlerts: { type: [untakenAlertSchema], default: [] },
386
+ unopenedAlerts: { type: [unopenedAlertSchema], default: [] },
375
387
  graveAlerts: { type: [graveAlertSchema], default: [] },
376
388
  autoHandoffFailedAt: { type: Date, default: null },
377
389
  autoHandoffAttempts: { type: Number, default: 0 },
@@ -1978,14 +1978,14 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1978
1978
  };
1979
1979
  }
1980
1980
 
1981
- async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), operator }) {
1981
+ async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), operator, reminder: reminderText = null }) {
1982
1982
  const review = await loadReview(reviewIdOf(id));
1983
1983
  const handoff = (review.doctorHandoffs ?? []).at(-1);
1984
1984
  const approver = handoff?.physicianEmail ? await getEscalationApprover(handoff.physicianEmail) : await notifiedApprover();
1985
1985
  if (!approver) throw httpError(409, 'The case has no approving doctor to remind');
1986
1986
  const draft = review.drafts[(handoff?.draftNumber ?? review.drafts.length) - 1];
1987
1987
  const lead = promptAt ? Math.round((new Date(promptAt).getTime() - now.getTime()) / 60000) : 0;
1988
- const reminder = lead >= 1 ? `⏰ En ${lead} min la paciente recibe los números para llamar` : '⏰ Recordatorio';
1988
+ const reminder = reminderText || (lead >= 1 ? `⏰ En ${lead} min la paciente recibe los números para llamar` : '⏰ Recordatorio');
1989
1989
  const message = doctorAlertMessage({ review, draft, identity: await readDoctorIdentity(review), link: doctorLink(review), reminder });
1990
1990
  return { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
1991
1991
  }
@@ -5,6 +5,7 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
5
5
 
6
6
  const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
7
7
  const { sweepUntakenAlerts } = require('./untakenAlertService');
8
+ const { sweepUnopenedCases } = require('./unopenedCaseService');
8
9
  const { sweepExpiredWatches } = require('./watchExpiryService');
9
10
  const { sweepCaseFollowUps, sweepCaseStatuses, sweepStaleQueues } = require('./caseFollowUpSweepService');
10
11
  const { sweepUnreviewedCases } = require('./unreviewedCaseService');
@@ -94,6 +95,12 @@ const untakenSweeper = createIntervalSweeper({
94
95
  defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
95
96
  });
96
97
 
98
+ const unopenedSweeper = createIntervalSweeper({
99
+ label: '[UnopenedCaseSweep]',
100
+ sweep: () => sweepUnopenedCases(),
101
+ defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
102
+ });
103
+
97
104
  const watchSweeper = createIntervalSweeper({
98
105
  label: '[WatchExpirySweep]',
99
106
  sweep: () => sweepExpiredWatches(),
@@ -114,12 +121,13 @@ const caseFollowUpSweeper = createIntervalSweeper({
114
121
 
115
122
  const startReviewAlertSweep = (options) => {
116
123
  untakenSweeper.start(options);
124
+ unopenedSweeper.start();
117
125
  // A watch runs out in hours, so it keeps its own slower interval.
118
126
  watchSweeper.start();
119
127
  caseFollowUpSweeper.start();
120
128
  unreviewedSweeper.start();
121
129
  return sweeper.start(options);
122
130
  };
123
- const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop(), unreviewedSweeper.stop()]);
131
+ const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), unopenedSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop(), unreviewedSweeper.stop()]);
124
132
 
125
133
  module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
@@ -0,0 +1,169 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+ const { addWorkingMinutes } = require('../utils/dateUtils');
4
+ const { withTimeout } = require('../utils/timeoutUtils');
5
+ const { getEscalationReview } = require('../models/escalationReviewModel');
6
+ const { escalationUnopenedReminderLive } = require('../clinical/flags/escalationFlags');
7
+
8
+ const { logPatientChange } = require('./patientService');
9
+ const { getEscalationApprover } = require('./physicianService');
10
+ const { readPatientCases } = require('./patientTaskService');
11
+ const { duration, ringAtOf } = require('./untakenAlertService');
12
+ const { BOOKKEEPING, caseTakenReason, noticeCaseThread, remindDoctorOfCase, teamAlertIdentity } = require('./escalationReviewService');
13
+ const { effectiveUrgencyOf, positiveSetting, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
14
+
15
+ const OPERATOR = 'bot:unopenedCase';
16
+ const AUDIT_SOURCE = 'escalation_review';
17
+ const SWEEP_LIMIT = 200;
18
+ const MINUTE_MS = 60 * 1000;
19
+ const LOOKBACK_MS = 7 * 24 * 60 * MINUTE_MS;
20
+ const STALE_MINUTES = 30;
21
+ const DOCTOR_PING_GAP_MS = 60 * MINUTE_MS;
22
+ const SEND_TIMEOUT_MS = 60 * 1000;
23
+ const DEFAULT_MINUTES = { 3: 60, 2: 120 };
24
+ const MINUTES_KEYS = { 3: 'ESCALATION_UNOPENED_MINUTES_G3', 2: 'ESCALATION_UNOPENED_MINUTES_G2' };
25
+ const GRADE_BY_LEVEL = { stat: 3, asap: 3 };
26
+
27
+ const timeOf = (value) => (value ? new Date(value).getTime() : NaN);
28
+ const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
29
+
30
+ const sinceText = (from, now) => duration(Math.max(1, Math.round((now.getTime() - from.getTime()) / MINUTE_MS)));
31
+
32
+ async function gradeOf(review) {
33
+ const ids = new Set(review.patientCaseRecordIds ?? []);
34
+ let grades = [];
35
+ try {
36
+ grades = (await readPatientCases(review.patientCode))
37
+ .filter((patientCase) => ids.has(patientCase.recordId))
38
+ .map((patientCase) => Number(String(patientCase.grade ?? '').match(/\d+/)?.[0]))
39
+ .filter((grade) => grade >= 2);
40
+ } catch (error) {
41
+ logger.error('[UnopenedCase] The case grades could not be read; the alarm level stands in', { escalationReviewId: String(review._id), error: errorOf(error) });
42
+ }
43
+ if (grades.length) return Math.max(...grades) >= 3 ? 3 : 2;
44
+ return GRADE_BY_LEVEL[effectiveUrgencyOf(review)?.urgency] ?? 2;
45
+ }
46
+
47
+ const windowMinutes = (grade) => positiveSetting(MINUTES_KEYS[grade], DEFAULT_MINUTES[grade]);
48
+ const workingDueAt = (from, minutes, policy) => teamOpenAt(addWorkingMinutes(from, minutes, policy.teamHours), policy);
49
+ const recorded = (review, stage, ringAt) => (review.unopenedAlerts ?? [])
50
+ .some((entry) => entry.stage === stage && timeOf(entry.ringAt) === ringAt.getTime());
51
+
52
+ const audit = (review, changes) => logPatientChange({
53
+ code: review.patientCode,
54
+ updatedBy: OPERATOR,
55
+ source: AUDIT_SOURCE,
56
+ requestId: null,
57
+ changes: { escalationReviewId: String(review._id), ...changes },
58
+ }).catch((error) => logger.error('[UnopenedCase] The audit was not written', { escalationReviewId: String(review._id), error: errorOf(error) }));
59
+
60
+ async function claim(review, entry) {
61
+ const claimed = await getEscalationReview().updateOne(
62
+ {
63
+ _id: review._id,
64
+ closedAt: null,
65
+ status: 'awaiting_doctor',
66
+ approverViewedAt: { $not: { $gte: entry.ringAt } },
67
+ unopenedAlerts: { $not: { $elemMatch: { stage: entry.stage, ringAt: entry.ringAt } } },
68
+ },
69
+ { $push: { unopenedAlerts: { error: null, ...entry } } },
70
+ BOOKKEEPING,
71
+ );
72
+ return claimed.modifiedCount > 0;
73
+ }
74
+
75
+ async function doctorPingedRecently(review, physicianEmail, now) {
76
+ const since = new Date(now.getTime() - DOCTOR_PING_GAP_MS);
77
+ const ownRing = (review.doctorAlerts ?? []).some((sent) => sent.transport && timeOf(sent.sentAt) >= since.getTime())
78
+ || timeOf(review.digestSentAt) >= since.getTime()
79
+ || (review.doctorHandoffs ?? []).some((handoff) => handoff.transport && timeOf(handoff.createdAt) >= since.getTime());
80
+ if (ownRing) return true;
81
+ const others = await getEscalationReview().countDocuments({
82
+ unopenedAlerts: { $elemMatch: { stage: 'doctor', physicianEmail, skippedReason: null, error: null, sentAt: { $gte: since } } },
83
+ });
84
+ return others > 0;
85
+ }
86
+
87
+ async function remindDoctor(review, { ringAt, dueAt, physicianEmail, level }, now) {
88
+ const taken = await caseTakenReason(review, ringAt, level);
89
+ const testPatient = !taken && (await teamAlertIdentity(review)).identity.testPatient;
90
+ const skippedReason = taken || (testPatient ? 'test_patient' : null);
91
+ if (!skippedReason && await doctorPingedRecently(review, physicianEmail, now)) return false;
92
+ if (!await claim(review, { stage: 'doctor', ringAt, dueAt, physicianEmail, skippedReason, sentAt: now })) return false;
93
+ if (skippedReason) return false;
94
+ let delivery;
95
+ try {
96
+ delivery = await withTimeout(remindDoctorOfCase({ id: review._id, now, operator: OPERATOR, reminder: `⏰ Caso sin abrir (enviado hace ${sinceText(ringAt, now)}): abre el enlace y decide` }), SEND_TIMEOUT_MS, 'unopened reminder');
97
+ } catch (error) {
98
+ delivery = { error: errorOf(error) };
99
+ logger.error('[UnopenedCase] The doctor reminder was not sent', { escalationReviewId: String(review._id), error: delivery.error });
100
+ }
101
+ await getEscalationReview().updateOne(
102
+ { _id: review._id, unopenedAlerts: { $elemMatch: { stage: 'doctor', ringAt } } },
103
+ { $set: { 'unopenedAlerts.$.transport': delivery.transport ?? null, 'unopenedAlerts.$.error': delivery.error ?? null } },
104
+ BOOKKEEPING,
105
+ );
106
+ await audit(review, { action: 'unopened_doctor_reminded', delivered: !delivery.error, transport: delivery.transport ?? null });
107
+ return !delivery.error;
108
+ }
109
+
110
+ async function noticeTeam(review, { ringAt, dueAt, physicianEmail, level }, now) {
111
+ const skippedReason = await caseTakenReason(review, ringAt, level);
112
+ if (!await claim(review, { stage: 'team', ringAt, dueAt, physicianEmail, skippedReason, sentAt: now })) return false;
113
+ if (skippedReason) return false;
114
+ const approver = physicianEmail ? await getEscalationApprover(physicianEmail).catch(() => null) : null;
115
+ const who = approver?.name ? `El Dr. ${approver.name}` : 'El médico';
116
+ await noticeCaseThread(review, {
117
+ header: `👀 ${who} no ha abierto el caso · enviado hace ${sinceText(ringAt, now)}`,
118
+ action: 'Qué hacer: llamar al médico o pasar el caso a otro médico',
119
+ kind: 'unopened',
120
+ });
121
+ await audit(review, { action: 'unopened_team_noticed' });
122
+ return true;
123
+ }
124
+
125
+ async function checkReview(review, now, policy) {
126
+ if (teamOpenAt(now, policy).getTime() !== now.getTime()) return false;
127
+ const ringAt = ringAtOf(review);
128
+ if (!ringAt || timeOf(review.approverViewedAt) >= ringAt.getTime()) return false;
129
+ if (now < workingDueAt(ringAt, Math.min(windowMinutes(3), windowMinutes(2)), policy)) return false;
130
+ const minutes = windowMinutes(await gradeOf(review));
131
+ const doctorDueAt = workingDueAt(ringAt, minutes, policy);
132
+ const teamDueAt = workingDueAt(ringAt, minutes * 2, policy);
133
+ const context = { ringAt, physicianEmail: review.doctorHandoffs.at(-1)?.physicianEmail ?? null, level: effectiveUrgencyOf(review)?.urgency ?? 'urgent' };
134
+ if (now >= teamDueAt) {
135
+ if (now > workingDueAt(teamDueAt, STALE_MINUTES, policy) || recorded(review, 'team', ringAt)) return false;
136
+ return noticeTeam(review, { ...context, dueAt: teamDueAt }, now);
137
+ }
138
+ if (now < doctorDueAt || recorded(review, 'doctor', ringAt)) return false;
139
+ return remindDoctor(review, { ...context, dueAt: doctorDueAt }, now);
140
+ }
141
+
142
+ async function sweepUnopenedCases({ now = new Date() } = {}) {
143
+ if (!escalationUnopenedReminderLive()) return 0;
144
+ const reviews = await getEscalationReview()
145
+ .find({
146
+ closedAt: null,
147
+ status: 'awaiting_doctor',
148
+ doctorHandoffs: { $elemMatch: { createdAt: { $gte: new Date(now.getTime() - LOOKBACK_MS) } } },
149
+ }, {
150
+ patientCode: 1, status: 1, closedAt: 1, alarms: 1, urgencyReclassifications: 1, decisions: 1, callLogs: 1,
151
+ patientCaseRecordIds: 1, doctorHandoffs: 1, digestSentAt: 1, approverViewedAt: 1, unopenedAlerts: 1,
152
+ 'doctorAlerts.sentAt': 1, 'doctorAlerts.transport': 1,
153
+ })
154
+ .sort({ _id: -1 })
155
+ .limit(SWEEP_LIMIT)
156
+ .lean();
157
+ const policy = responseDeadlinePolicy();
158
+ let sent = 0;
159
+ for (const review of reviews) {
160
+ try {
161
+ if (await checkReview(review, now, policy)) sent += 1;
162
+ } catch (error) {
163
+ logger.error('[UnopenedCase] Could not check a review for an unopened case', { escalationReviewId: String(review._id), error: errorOf(error) });
164
+ }
165
+ }
166
+ return sent;
167
+ }
168
+
169
+ module.exports = { sweepUnopenedCases };
@@ -5,7 +5,7 @@ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
5
  const { withTimeout } = require('../utils/timeoutUtils');
6
6
  const { URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
7
7
  const { readGroupMessageId } = require('../clinical/services/clinicalAirtableService');
8
- const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
8
+ const { escalationAutoHandoffLive, escalationPatientTimerLive, escalationUnopenedReminderLive, escalationUntakenAlertsLive, feverPatientTimerLive } = require('../clinical/flags/escalationFlags');
9
9
 
10
10
  const { logPatientChange } = require('./patientService');
11
11
  const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf, responseDeadlinePolicy, untakenStagesOf } = require('./reviewDeadlineService');
@@ -49,6 +49,18 @@ const duration = (minutes) => {
49
49
  return rest ? `${hours} h ${rest} min` : `${hours} h`;
50
50
  };
51
51
 
52
+ const timeOf = (value) => (value ? new Date(value).getTime() : NaN);
53
+
54
+ function ringAtOf(review) {
55
+ const decidedAt = timeOf((review.decisions ?? []).at(-1)?.createdAt);
56
+ const after = (at) => !(timeOf(at) <= decidedAt);
57
+ const rings = (review.doctorHandoffs ?? [])
58
+ .filter((handoff) => (handoff.transport || handoff.mode === 'copied') && after(handoff.createdAt))
59
+ .map((handoff) => timeOf(handoff.createdAt));
60
+ if (review.digestSentAt && after(review.digestSentAt)) rings.push(timeOf(review.digestSentAt));
61
+ return rings.length ? new Date(Math.max(...rings)) : null;
62
+ }
63
+
52
64
  // Only the stages restart on a raise; the episode start ignores reclassifications so drafts and grave alerts keep their key.
53
65
  function episodeStartOf(alarms) {
54
66
  const top = alarms.reduce((level, alarm) => ((URGENCY_RANK[appliedLevelOf(alarm)] || 0) > (URGENCY_RANK[level] || 0) ? appliedLevelOf(alarm) : level), null);
@@ -221,6 +233,7 @@ const remindersSince = (review, since) => (review.doctorAlerts ?? [])
221
233
  async function remindDoctorIfDue(review, clock, now, policy) {
222
234
  if (review.status !== 'awaiting_doctor') return false;
223
235
  const promptAt = armedPromptAt(review);
236
+ if (!promptAt && clock.level === 'urgent' && escalationUnopenedReminderLive() && ringAtOf(review)) return false;
224
237
  if (review.doctorAlertKind === 'patient_prompt' && review.doctorAlertAttempts > 0) return false;
225
238
  const dueAt = doctorReminderAt(clock.level, clock.stagesFrom, policy, promptAt);
226
239
  const deadline = clock.stages.find((stage) => stage.stage === 'deadline').dueAt;
@@ -323,4 +336,4 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
323
336
  return sent;
324
337
  }
325
338
 
326
- module.exports = { UNTAKEN_PROJECTION, dueStageOf, duration, sweepUntakenAlerts, untakenClockOf };
339
+ module.exports = { UNTAKEN_PROJECTION, dueStageOf, duration, ringAtOf, sweepUntakenAlerts, untakenClockOf };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.7.0-dev.21499",
3
+ "version": "6.7.0-dev.21501",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",