@peopl-health/nexus 6.7.0-dev.21500 → 6.7.0-dev.21502

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.
@@ -52,14 +52,29 @@ function escalationCaseFollowUpLive() {
52
52
  return flagNotOff('ESCALATION_CASE_FOLLOW_UP_LIVE');
53
53
  }
54
54
 
55
+ function escalationCaseStatusReminderLive() {
56
+ return flagOn('ESCALATION_CASE_STATUS_REMINDER_LIVE');
57
+ }
58
+
59
+ function escalationUnopenedReminderLive() {
60
+ return flagOn('ESCALATION_UNOPENED_REMINDER_LIVE');
61
+ }
62
+
63
+ function escalationUnreviewedCaseNoticeLive() {
64
+ return flagOn('ESCALATION_UNREVIEWED_CASE_NOTICE_LIVE');
65
+ }
66
+
55
67
  module.exports = {
56
68
  escalationCaseFollowUpLive,
69
+ escalationCaseStatusReminderLive,
70
+ escalationUnreviewedCaseNoticeLive,
57
71
  escalationApproverAlertLive,
58
72
  escalationAssessmentLive,
59
73
  escalationAutoHandoffLive,
60
74
  escalationInTurnAskLive,
61
75
  escalationPatientTimerLive,
62
76
  escalationUntakenAlertsLive,
77
+ escalationUnopenedReminderLive,
63
78
  escalationUpdateModeLive,
64
79
  escalationWatchExpiryLive,
65
80
  escalationStaleQueueNoticeLive,
@@ -243,9 +243,7 @@ function doctorBrief({ kind, change = null, reminder = null, level, identity, dr
243
243
  ];
244
244
  }
245
245
 
246
- const urgentCases = (count) => `${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
247
- const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${urgentCases(count)}`;
248
- const doctorReminderTitle = (count) => `⏰ Siguen esperando tu decisión: ${urgentCases(count)}`;
246
+ const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
249
247
 
250
248
  function doctorDigestLine({ identity, draft, alarmSymptom, deadline, now, timeZone, link }) {
251
249
  const head = [briefCaseLine(identity, briefSymptomOf(draft, alarmSymptom), alarmSymptom), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · ');
@@ -266,5 +264,4 @@ module.exports = {
266
264
  doctorBrief,
267
265
  doctorDigestLine,
268
266
  doctorDigestTitle,
269
- doctorReminderTitle,
270
267
  };
@@ -16,6 +16,7 @@ const {
16
16
  recordDoctorDecision,
17
17
  requestBotDraft,
18
18
  sendApprovedIndications,
19
+ setCaseStatuses,
19
20
  setReviewCases,
20
21
  suggestDraft,
21
22
  suggestKeyQuestions,
@@ -120,6 +121,20 @@ const setEscalationReviewCasesController = async (req, res) => {
120
121
  }
121
122
  };
122
123
 
124
+ const setEscalationReviewCaseStatusesController = async (req, res) => {
125
+ try {
126
+ const { caseStatuses, triggeredBy } = req.body || {};
127
+ const { review, caseMirror, caseMirrors } = await setCaseStatuses({ id: req.params.id, caseStatuses, updatedBy: triggeredBy, requestId: req.requestId });
128
+ if (caseMirror === 'failed' || caseMirror === 'partial') {
129
+ res.status(502).json({ success: false, error: 'The patient case could not be updated', review: withCaseStatus(review), caseMirror, caseMirrors });
130
+ return;
131
+ }
132
+ res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
133
+ } catch (error) {
134
+ respondWithError(res, error, 'setting escalation review case statuses', { reviewId: req.params?.id });
135
+ }
136
+ };
137
+
123
138
  const addEscalationReviewCallLogController = async (req, res) => {
124
139
  try {
125
140
  const { outcome, notes, calledAt, triggeredBy } = req.body || {};
@@ -207,6 +222,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
207
222
  reason = null,
208
223
  draftNumber = null,
209
224
  closingCaseIds = null,
225
+ caseStatuses = null,
210
226
  triggeredBy,
211
227
  } = req.body || {};
212
228
  const review = await recordDoctorDecision({
@@ -223,6 +239,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
223
239
  reason,
224
240
  draftNumber,
225
241
  closingCaseIds,
242
+ caseStatuses,
226
243
  recordedBy: triggeredBy,
227
244
  requestId: req.requestId,
228
245
  });
@@ -322,6 +339,7 @@ module.exports = {
322
339
  reclassifyEscalationReviewUrgencyController,
323
340
  recordEscalationReviewDecisionController,
324
341
  sendEscalationReviewIndicationsController,
342
+ setEscalationReviewCaseStatusesController,
325
343
  setEscalationReviewCasesController,
326
344
  suggestEscalationReviewDraftController,
327
345
  suggestEscalationReviewQuestionsController,
@@ -8,6 +8,7 @@ const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
8
  const URGENCY_LEVELS = ['stat', 'asap', 'urgent', 'routine'];
9
9
  const URGENCY_RANK = { routine: 1, urgent: 2, asap: 3, stat: 4 };
10
10
  const FOLLOWUP_STATUSES = ['indications_sent', 'indications_queued', 'monitoring'];
11
+ const DONE_STATUSES = ['closed', 'cancelled'];
11
12
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
12
13
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
13
14
  const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
@@ -72,6 +73,17 @@ const untakenAlertSchema = new mongoose.Schema({
72
73
  sentAt: { type: Date, required: true },
73
74
  }, { _id: false });
74
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
+
75
87
  const graveAlertSchema = new mongoose.Schema({
76
88
  flag: { type: String, required: true },
77
89
  level: { type: String, enum: URGENCY_LEVELS, required: true },
@@ -291,6 +303,13 @@ const pendingCaseMirrorSchema = new mongoose.Schema({
291
303
  changes: { type: mongoose.Schema.Types.Mixed, required: true },
292
304
  }, { timestamps: { createdAt: true, updatedAt: false } });
293
305
 
306
+ const doctorCaseStatusSchema = new mongoose.Schema({
307
+ recordId: { type: String, required: true },
308
+ status: { type: String, required: true },
309
+ setBy: { type: String, required: true },
310
+ setAt: { type: Date, required: true },
311
+ }, { _id: false });
312
+
294
313
  const interruptionResolutionSchema = new mongoose.Schema({
295
314
  fromStatus: { type: String, enum: INTERRUPTED_STATUSES, required: true },
296
315
  notes: { type: String, required: true },
@@ -364,6 +383,7 @@ const escalationReviewSchema = new mongoose.Schema({
364
383
  doctorAlertKind: { type: String, enum: ['initial', 'realert', 'patient_prompt', null], default: null },
365
384
  doctorAlertAttempts: { type: Number, default: 0 },
366
385
  untakenAlerts: { type: [untakenAlertSchema], default: [] },
386
+ unopenedAlerts: { type: [unopenedAlertSchema], default: [] },
367
387
  graveAlerts: { type: [graveAlertSchema], default: [] },
368
388
  autoHandoffFailedAt: { type: Date, default: null },
369
389
  autoHandoffAttempts: { type: Number, default: 0 },
@@ -375,6 +395,7 @@ const escalationReviewSchema = new mongoose.Schema({
375
395
  watchNotices: { type: [watchNoticeSchema], default: [] },
376
396
  caseFollowUp: { type: caseFollowUpSchema, default: null },
377
397
  staleQueueNoticeAt: { type: Date, default: null },
398
+ caseStatusNoticeAt: { type: Date, default: null },
378
399
  blockingAsks: { type: [blockingAskSchema], default: [] },
379
400
  inTurnAsks: { type: [inTurnAskSchema], default: [] },
380
401
  feverPromptStartedAt: { type: Date, default: null },
@@ -388,6 +409,7 @@ const escalationReviewSchema = new mongoose.Schema({
388
409
  patientDelivery: { type: patientDeliverySchema, default: null },
389
410
  patientSends: { type: [patientSendSchema], default: undefined },
390
411
  pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
412
+ doctorCaseStatuses: { type: [doctorCaseStatusSchema], default: [] },
391
413
  interruptionResolution: { type: interruptionResolutionSchema, default: null },
392
414
  identityBlock: { type: identityBlockSchema, default: null },
393
415
  closedBy: { type: String, default: null },
@@ -462,6 +484,7 @@ module.exports = {
462
484
  INTERRUPTED_STATUSES,
463
485
  PLAN_DURATIONS,
464
486
  PLAN_FOLLOW_UPS,
487
+ DONE_STATUSES,
465
488
  FOLLOWUP_STATUSES,
466
489
  RETURN_REASONS,
467
490
  URGENCY_LEVELS,
@@ -131,6 +131,7 @@ const escalationReviewRouteDefinitions = {
131
131
  'GET /:id': 'getEscalationReviewController',
132
132
  'GET /:id/timeline': 'getReviewTimelineController',
133
133
  'POST /:id/cases': 'setEscalationReviewCasesController',
134
+ 'POST /:id/case-statuses': 'setEscalationReviewCaseStatusesController',
134
135
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
135
136
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
136
137
  'POST /:id/draft-requests': 'requestEscalationReviewDraftController',
@@ -317,6 +318,7 @@ const builtInControllers = {
317
318
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
318
319
  previewEscalationReviewPlanController: escalationReviewController.previewEscalationReviewPlanController,
319
320
  requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
321
+ setEscalationReviewCaseStatusesController: escalationReviewController.setEscalationReviewCaseStatusesController,
320
322
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
321
323
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
322
324
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
@@ -1,12 +1,13 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
- const { getEscalationReview } = require('../models/escalationReviewModel');
4
- const { escalationCaseFollowUpLive, escalationStaleQueueNoticeLive } = require('../clinical/flags/escalationFlags');
3
+ const { DONE_STATUSES, getEscalationReview, supersededCaseIds } = require('../models/escalationReviewModel');
4
+ const { escalationCaseFollowUpLive, escalationCaseStatusReminderLive, escalationStaleQueueNoticeLive } = require('../clinical/flags/escalationFlags');
5
5
 
6
6
  const { logPatientChange } = require('./patientService');
7
7
  const { getThreadInfo } = require('./threadService');
8
- const { BOOKKEEPING, closeEscalationReview, followUpReadingOf, noticeCaseThread } = require('./escalationReviewService');
9
- const { effectiveUrgencyOf, positiveSetting } = require('./reviewDeadlineService');
8
+ const { UNTRIAGED_CASE_STATUSES, readPatientCases } = require('./patientTaskService');
9
+ const { BOOKKEEPING, closeEscalationReview, followUpReadingOf, noticeCaseThread, resolveSettledCases } = require('./escalationReviewService');
10
+ const { effectiveUrgencyOf, positiveSetting, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
10
11
  const { FOLLOW_UP_STATUSES, SECOND_TRY_MS, armCaseFollowUp, askedAt, lastReplyAt, rewriteRow } = require('./caseFollowUpService');
11
12
 
12
13
  const OPERATOR = 'bot:caseFollowUp';
@@ -19,6 +20,8 @@ const STALE_QUEUE_STATUSES = ['indications_queued', 'needs_intervention'];
19
20
  const DEFAULT_STALE_QUEUE_HOURS = 72;
20
21
  const HOUR_MS = 60 * 60 * 1000;
21
22
  const STALE_QUEUE_LOOKBACK_MS = 7 * 24 * HOUR_MS;
23
+ const CASE_STATUS_NOTICE_MS = 24 * HOUR_MS;
24
+ const CASE_STATUS_LOOKBACK_MS = 7 * 24 * HOUR_MS;
22
25
  const STALE_QUEUE_HEADERS = {
23
26
  indications_queued: '⏳ Indicación en cola sin enviar desde hace días',
24
27
  needs_intervention: '⏳ Caso que requiere intervención sin movimiento desde hace días',
@@ -43,6 +46,7 @@ const checkAgainAt = (review, at) => getEscalationReview().updateOne(
43
46
  async function close(review, result) {
44
47
  const { review: closed } = await closeEscalationReview({ id: String(review._id), closedBy: OPERATOR, expectedAlarmCount: (review.alarms ?? []).length });
45
48
  await audit(closed, { action: 'followup_result', result });
49
+ if (result === 'answered') await resolveSettledCases(closed, OPERATOR);
46
50
  }
47
51
 
48
52
  async function keepUnanswered(review, now) {
@@ -153,4 +157,42 @@ async function sweepStaleQueues({ now = new Date() } = {}) {
153
157
  return noticed;
154
158
  }
155
159
 
156
- module.exports = { sweepCaseFollowUps, sweepStaleQueues };
160
+ // Only the team group hears of these; the doctor is never asked to close cases.
161
+ async function sweepCaseStatuses({ now = new Date() } = {}) {
162
+ if (!escalationCaseStatusReminderLive()) return 0;
163
+ const policy = responseDeadlinePolicy();
164
+ if (teamOpenAt(now, policy).getTime() !== now.getTime()) return 0;
165
+ const reviews = await getEscalationReview()
166
+ .find({
167
+ status: { $in: DONE_STATUSES },
168
+ closedAt: { $lte: new Date(now.getTime() - CASE_STATUS_NOTICE_MS), $gt: new Date(now.getTime() - CASE_STATUS_LOOKBACK_MS) },
169
+ caseStatusNoticeAt: null,
170
+ 'patientCaseRecordIds.0': { $exists: true },
171
+ })
172
+ .limit(SWEEP_LIMIT)
173
+ .lean();
174
+ let noticed = 0;
175
+ for (const review of reviews) {
176
+ try {
177
+ const superseded = await supersededCaseIds(getEscalationReview(), review);
178
+ const covered = new Set(review.patientCaseRecordIds.filter((recordId) => !superseded.has(recordId)));
179
+ const unset = (await readPatientCases(review.patientCode))
180
+ .filter((patientCase) => covered.has(patientCase.recordId) && UNTRIAGED_CASE_STATUSES.includes(patientCase.status));
181
+ const claimed = await getEscalationReview().updateOne({ _id: review._id, caseStatusNoticeAt: null }, { $set: { caseStatusNoticeAt: now } }, BOOKKEEPING);
182
+ if (!claimed.modifiedCount || !unset.length) continue;
183
+ const numbers = unset.map((patientCase) => (patientCase.number ? `#${patientCase.number}` : patientCase.description)).filter(Boolean).join(', ');
184
+ await noticeCaseThread(review, {
185
+ header: `📋 Caso cerrado sin estado clínico: ${numbers}`,
186
+ action: 'Qué hacer: poner En tratamiento, En vigilancia o Resuelto en Pendientes',
187
+ kind: 'case_status',
188
+ });
189
+ await audit(review, { action: 'case_status_noticed', recordIds: unset.map((patientCase) => patientCase.recordId) });
190
+ noticed += 1;
191
+ } catch (error) {
192
+ logger.error('[CaseFollowUpSweep] Could not check the clinical status of a closed review\'s cases', { escalationReviewId: String(review._id), error: errorOf(error) });
193
+ }
194
+ }
195
+ return noticed;
196
+ }
197
+
198
+ module.exports = { sweepCaseFollowUps, sweepCaseStatuses, sweepStaleQueues };
@@ -5,10 +5,9 @@ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUti
5
5
  const { getEscalationReview } = require('../models/escalationReviewModel');
6
6
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
7
7
  const { whatsAppCodeFromPhone } = require('../helpers/twilioHelper');
8
- const { doctorDigestLine, doctorDigestTitle, doctorReminderTitle } = require('../clinical/helpers/doctorReviewMessageHelper');
8
+ const { doctorDigestLine, doctorDigestTitle } = require('../clinical/helpers/doctorReviewMessageHelper');
9
9
 
10
10
  const { logPatientChange } = require('./patientService');
11
- const { getEscalationApprover } = require('./physicianService');
12
11
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
13
12
  const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, doctorAlertMessage, doctorLink, notifiedApprover, teamAlertIdentity } = require('./escalationReviewService');
14
13
 
@@ -24,9 +23,6 @@ const MAX_LINES_LENGTH = 800;
24
23
  const MAX_FIELD_LENGTH = 60;
25
24
  const STALE_CLAIM_MS = 10 * 60 * 1000;
26
25
  const OPERATOR = 'bot:doctorDigest';
27
- const REMINDER_TIMES_KEY = 'ESCALATION_DOCTOR_REMINDER_DIGEST_TIMES';
28
- const REMINDER_SLOT_MINUTES = 30;
29
- const TIME_OF_DAY = /^(\d{1,2}):(\d{2})$/;
30
26
  const getMessaging = () => require('../core/NexusMessaging');
31
27
 
32
28
  const minutesOf = (key, fallback) => {
@@ -38,15 +34,13 @@ const redacted = (error) => redactDirectIdentifiers(String(error?.message || err
38
34
  // Urgent cases ready for the doctor go in a digest only once its template exists.
39
35
  const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY));
40
36
 
41
- // Throws when no single approver can be chosen.
42
- async function approverContact(email = null) {
43
- const approver = email ? await getEscalationApprover(email) : await notifiedApprover();
37
+ // The notified approver's WhatsApp, or null when their number is unusable; throws when no single approver can be chosen.
38
+ async function digestRecipient() {
39
+ const approver = await notifiedApprover();
44
40
  const code = whatsAppCodeFromPhone(approver?.phone);
45
- return PATIENT_CODE.test(code) ? { code, email: approver.email } : null;
41
+ return PATIENT_CODE.test(code) ? code : null;
46
42
  }
47
43
 
48
- const digestRecipient = async () => (await approverContact())?.code ?? null;
49
-
50
44
  // The time a case queued now reaches the doctor at the latest, in the team's clock, for the group notice.
51
45
  function digestTimeOf(review, now) {
52
46
  const policy = responseDeadlinePolicy();
@@ -109,9 +103,9 @@ function chunksOf(entries) {
109
103
  return chunks;
110
104
  }
111
105
 
112
- async function sendDigest(code, entries, inWindow, perCase, heading = null) {
106
+ async function sendDigest(code, entries, inWindow, perCase) {
113
107
  const lines = entries.map(({ line }) => line);
114
- const title = heading ?? (!perCase && (briefStyle() ? doctorDigestTitle(entries.length) : String(entries.length)));
108
+ const title = !perCase && (briefStyle() ? doctorDigestTitle(entries.length) : String(entries.length));
115
109
  const outgoing = perCase
116
110
  ? { code, contentSid: lines[0].contentSid || runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY), variables: lines[0].template, triggeredBy: OPERATOR }
117
111
  : inWindow
@@ -192,86 +186,4 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
192
186
  return sent;
193
187
  }
194
188
 
195
- // Minutes after local midnight of each configured time ("12:00,17:00"); none keeps one reminder per case.
196
- function reminderTimes() {
197
- return String(runtimeConfig.get(REMINDER_TIMES_KEY, '') || '').split(',')
198
- .map((value) => TIME_OF_DAY.exec(value.trim()))
199
- .filter(Boolean)
200
- .map(([, hours, minutes]) => Number(hours) * 60 + Number(minutes))
201
- .filter((minutes) => minutes < 24 * 60);
202
- }
203
-
204
- // Urgent reminders go together only with a time set and a brief digest template, whose first variable is free text.
205
- const reminderDigestLive = () => reminderTimes().length > 0 && Boolean(briefStyle()) && urgentDigestLive();
206
-
207
- // When the time slot `now` falls in began, or null outside every slot.
208
- function reminderSlotOf(now, timeZone = responseDeadlinePolicy().teamHours.timeZone) {
209
- if (!reminderDigestLive()) return null;
210
- const parts = Object.fromEntries(new Intl.DateTimeFormat('en-US', { timeZone, hour: '2-digit', minute: '2-digit', hourCycle: 'h23' })
211
- .formatToParts(now).map(({ type, value }) => [type, value]));
212
- const local = Number(parts.hour) * 60 + Number(parts.minute);
213
- const start = reminderTimes().find((minutes) => local >= minutes && local < minutes + REMINDER_SLOT_MINUTES);
214
- return start === undefined ? null : new Date(Math.floor(now.getTime() / 60000) * 60000 - (local - start) * 60000);
215
- }
216
-
217
- // One reminder per approving doctor for the urgent cases still waiting on them in this slot, five per message.
218
- async function sendReminderDigest({ reviewIds, slot, now = new Date() }) {
219
- if (!reviewIds.length) return 0;
220
- const policy = responseDeadlinePolicy();
221
- const reviews = await getEscalationReview().find({ _id: { $in: reviewIds }, closedAt: null, status: 'awaiting_doctor' }).sort({ createdAt: 1 }).lean();
222
- const byApprover = new Map();
223
- for (const review of reviews) {
224
- const who = await teamAlertIdentity(review);
225
- if (who.identity.testPatient) continue;
226
- const email = (review.doctorHandoffs ?? []).at(-1)?.physicianEmail ?? null;
227
- byApprover.set(email, [...(byApprover.get(email) ?? []), { review, who }]);
228
- }
229
- let sent = 0;
230
- for (const [email, cases] of byApprover) {
231
- const recipient = await approverContact(email).catch((error) => {
232
- logger.error('[DoctorDigest] The approving doctor could not be chosen; the reminder is skipped', { cases: cases.length, error: redacted(error) });
233
- return undefined;
234
- });
235
- if (recipient === undefined) continue;
236
- if (!recipient) {
237
- logger.error('[DoctorDigest] The approving doctor has no usable WhatsApp number; the reminder is skipped', { cases: cases.length });
238
- continue;
239
- }
240
- const inWindow = await isWithin24HourWindow(recipient.code);
241
- const lines = digestLines(cases, now, policy, false);
242
- for (const chunk of chunksOf(cases.map(({ review }, index) => ({ review, line: lines[index] })))) {
243
- const claimed = [];
244
- for (const entry of chunk) {
245
- const filter = { _id: entry.review._id, closedAt: null, status: 'awaiting_doctor', doctorAlerts: { $not: { $elemMatch: { kind: 'reminder', sentAt: { $gte: slot } } } } };
246
- const push = { $push: { doctorAlerts: { kind: 'reminder', urgencyLevel: 'urgent', error: null, sentAt: now } } };
247
- if ((await getEscalationReview().updateOne(filter, push, BOOKKEEPING)).modifiedCount) claimed.push(entry);
248
- }
249
- if (!claimed.length) continue;
250
- let error = null;
251
- try {
252
- // Out of the window without the brief digest template, the old template's first variable is the case count.
253
- const heading = inWindow || runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) ? doctorReminderTitle(claimed.length) : String(claimed.length);
254
- await sendDigest(recipient.code, claimed, inWindow, false, heading);
255
- sent += claimed.length;
256
- } catch (failure) {
257
- error = redacted(failure);
258
- logger.error('[DoctorDigest] The reminder digest was not sent', { cases: claimed.length, error });
259
- }
260
- // A failed send keeps its claim: the cases wait for the next slot, and the team has its own deadline alert.
261
- for (const { review } of claimed) {
262
- await getEscalationReview().updateOne(
263
- { _id: review._id, doctorAlerts: { $elemMatch: { kind: 'reminder', sentAt: now } } },
264
- { $set: { 'doctorAlerts.$.transport': error ? null : 'digest', 'doctorAlerts.$.physicianEmail': recipient.email, 'doctorAlerts.$.error': error } },
265
- BOOKKEEPING,
266
- ).catch((failure) => logger.error('[DoctorDigest] The reminder was not recorded', { escalationReviewId: String(review._id), error: redacted(failure) }));
267
- await logPatientChange({
268
- code: review.patientCode, updatedBy: OPERATOR, source: 'escalation_review', requestId: null,
269
- changes: { escalationReviewId: String(review._id), action: 'doctor_reminded', urgencyLevel: 'urgent', delivered: !error, transport: error ? null : 'digest' },
270
- }).catch((failure) => logger.error('[DoctorDigest] The audit was not written', { escalationReviewId: String(review._id), error: redacted(failure) }));
271
- }
272
- }
273
- }
274
- return sent;
275
- }
276
-
277
- module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, reminderDigestLive, reminderSlotOf, sendDueDoctorDigests, sendReminderDigest, urgentDigestLive };
189
+ module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
@@ -1,6 +1,6 @@
1
1
  const { logger } = require('../utils/logger');
2
2
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
- const { FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
3
+ const { DONE_STATUSES, FOLLOWUP_STATUSES } = require('../models/escalationReviewModel');
4
4
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
5
5
  const { escalationUntakenAlertsLive } = require('../clinical/flags/escalationFlags');
6
6
 
@@ -10,7 +10,6 @@ const { HANDOFF_TAKES_LEVELS, pendingWaitMinutes } = require('./reviewDeadlineSe
10
10
  const { dueStageOf, untakenClockOf } = require('./untakenAlertService');
11
11
 
12
12
  const WITH_DOCTOR_STATUSES = ['handing_off', 'awaiting_doctor'];
13
- const DONE_STATUSES = ['closed', 'cancelled'];
14
13
  const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
15
14
  const timeOf = (value) => new Date(value).getTime();
16
15
 
@@ -56,7 +56,7 @@ const { ageFrom, birthDateFrom } = require('../fhir/resources/Patient');
56
56
  const { armCaseFollowUp, cancelCaseFollowUp } = require('./caseFollowUpService');
57
57
 
58
58
  const { getPatientInformation, logPatientChange } = require('./patientService');
59
- const { MAX_NOTE_LENGTH, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
59
+ const { MAX_NOTE_LENGTH, UNTRIAGED_CASE_STATUSES, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
60
60
  const { countMessages, getMessages } = require('./messageService');
61
61
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
62
62
  const { createPrescription } = require('./prescriptionService');
@@ -146,6 +146,49 @@ function closingCaseIdsOf(value) {
146
146
  return [...new Set(value.map((recordId) => recordId.trim()).filter(Boolean))];
147
147
  }
148
148
 
149
+ // The clinical statuses a doctor closes a case with from the review; ops keep the rest in Pendientes.
150
+ const DOCTOR_CASE_STATUSES = ['En tratamiento', 'En vigilancia', 'Resuelto'];
151
+ const RESOLVABLE_CASE_STATUSES = ['En tratamiento', 'En vigilancia'];
152
+
153
+ function caseStatusMirrorsOf(value, review) {
154
+ if (value == null) return [];
155
+ if (!Array.isArray(value)) throw httpError(400, 'caseStatuses must be a list of { recordId, status }');
156
+ const covered = new Set(caseIdsOf(review));
157
+ const byCase = new Map();
158
+ for (const entry of value) {
159
+ const recordId = typeof entry?.recordId === 'string' ? entry.recordId.trim() : '';
160
+ if (!covered.has(recordId)) throw httpError(400, `The review does not cover case ${recordId || '(none)'}`);
161
+ if (!DOCTOR_CASE_STATUSES.includes(entry.status)) throw httpError(400, `status must be one of: ${DOCTOR_CASE_STATUSES.join(', ')}`);
162
+ byCase.set(recordId, entry.status);
163
+ }
164
+ return [...byCase].map(([recordId, status]) => ({ recordId, changes: { status } }));
165
+ }
166
+
167
+ const IMPLIED_CASE_STATUS = { monitor: 'En vigilancia', approved: 'En tratamiento', edited_approved: 'En tratamiento', plan_approved: 'En tratamiento' };
168
+
169
+ async function impliedCaseStatusMirrors(review, decision, returnReason, chosen) {
170
+ const status = returnReason === 'no_requiere' ? 'Resuelto' : IMPLIED_CASE_STATUS[decision];
171
+ const chosenIds = new Set(chosen.map(({ recordId }) => recordId));
172
+ const covered = new Set(caseIdsOf(review).filter((recordId) => !chosenIds.has(recordId)));
173
+ if (!status || !covered.size) return [];
174
+ try {
175
+ return (await readPatientCases(review.patientCode))
176
+ .filter((patientCase) => covered.has(patientCase.recordId) && UNTRIAGED_CASE_STATUSES.includes(patientCase.status))
177
+ .map((patientCase) => ({ recordId: patientCase.recordId, changes: { status } }));
178
+ } catch (error) {
179
+ logger.error('[EscalationReview] The cases were read for no implied clinical status', { escalationReviewId: String(review._id), error: redactedError(error) });
180
+ return [];
181
+ }
182
+ }
183
+
184
+ const caseStatusPushOf = (mirrors, setBy) => {
185
+ const setAt = new Date();
186
+ return {
187
+ pendingCaseMirrors: { $each: mirrors },
188
+ doctorCaseStatuses: { $each: mirrors.map(({ recordId, changes }) => ({ recordId, status: changes.status, setBy, setAt })) },
189
+ };
190
+ };
191
+
149
192
  const reviewIdOf = (id) => {
150
193
  if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
151
194
  return id;
@@ -942,6 +985,20 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
942
985
  return review;
943
986
  }
944
987
 
988
+ async function setCaseStatuses({ id, caseStatuses, updatedBy, requestId = null } = {}) {
989
+ const reviewId = reviewIdOf(id);
990
+ const operator = requiredText(updatedBy, 'updatedBy');
991
+ const current = await loadReview(reviewId);
992
+ const mirrors = caseStatusMirrorsOf(caseStatuses, current);
993
+ if (!mirrors.length) throw httpError(400, 'caseStatuses must name at least one case');
994
+ const superseded = await supersededCaseIds(getEscalationReview(), current);
995
+ const held = mirrors.find(({ recordId }) => superseded.has(recordId));
996
+ if (held) throw httpError(409, `A newer review holds case ${held.recordId}; set its status there`);
997
+ const review = await updateReview(reviewId, [current.status], { $push: caseStatusPushOf(mirrors, operator) });
998
+ await audit(review, operator, requestId, { action: 'case_statuses_set', caseStatuses: mirrors.map(({ recordId, changes }) => ({ recordId, status: changes.status })) });
999
+ return syncCase(review, operator, requestId);
1000
+ }
1001
+
945
1002
  async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
946
1003
  const reviewId = reviewIdOf(id);
947
1004
  const operator = requiredText(loggedBy, 'loggedBy');
@@ -1523,6 +1580,23 @@ async function followUpCasesOf(review, sinceMs) {
1523
1580
  return { review: stored, known: new Set(known) };
1524
1581
  }
1525
1582
 
1583
+ async function resolveSettledCases(review, operator) {
1584
+ const setByDoctor = new Map((review.doctorCaseStatuses ?? []).map(({ recordId, status }) => [recordId, status]));
1585
+ if (![...setByDoctor.values()].some((status) => RESOLVABLE_CASE_STATUSES.includes(status))) return review;
1586
+ try {
1587
+ const superseded = await supersededCaseIds(getEscalationReview(), review);
1588
+ const caseStatuses = (await readPatientCases(review.patientCode))
1589
+ .filter((patientCase) => !superseded.has(patientCase.recordId)
1590
+ && RESOLVABLE_CASE_STATUSES.includes(patientCase.status) && setByDoctor.get(patientCase.recordId) === patientCase.status)
1591
+ .map((patientCase) => ({ recordId: patientCase.recordId, status: 'Resuelto' }));
1592
+ if (!caseStatuses.length) return review;
1593
+ return (await setCaseStatuses({ id: String(review._id), caseStatuses, updatedBy: operator })).review;
1594
+ } catch (error) {
1595
+ logger.error('[EscalationReview] The settled cases were not marked resolved', { escalationReviewId: String(review._id), error: redactedError(error) });
1596
+ return review;
1597
+ }
1598
+ }
1599
+
1526
1600
  async function closeSettled(review) {
1527
1601
  try {
1528
1602
  const { review: closed } = await closeEscalationReview({
@@ -1532,7 +1606,7 @@ async function closeSettled(review) {
1532
1606
  expectedUpdatedAt: review.updatedAt,
1533
1607
  });
1534
1608
  await audit(closed, AGENT_OPERATOR, null, { action: 'followup_result', result: 'settled' });
1535
- return closed;
1609
+ return resolveSettledCases(closed, AGENT_OPERATOR);
1536
1610
  } catch (error) {
1537
1611
  logger.warn('[EscalationReview] The follow-up settled the case but the review did not close', {
1538
1612
  escalationReviewId: String(review._id), error: redactedError(error),
@@ -1904,14 +1978,14 @@ function doctorAlertMessage({ review, draft, identity, link, kind, note, level,
1904
1978
  };
1905
1979
  }
1906
1980
 
1907
- async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), operator }) {
1981
+ async function remindDoctorOfCase({ id, promptAt = null, now = new Date(), operator, reminder: reminderText = null }) {
1908
1982
  const review = await loadReview(reviewIdOf(id));
1909
1983
  const handoff = (review.doctorHandoffs ?? []).at(-1);
1910
1984
  const approver = handoff?.physicianEmail ? await getEscalationApprover(handoff.physicianEmail) : await notifiedApprover();
1911
1985
  if (!approver) throw httpError(409, 'The case has no approving doctor to remind');
1912
1986
  const draft = review.drafts[(handoff?.draftNumber ?? review.drafts.length) - 1];
1913
1987
  const lead = promptAt ? Math.round((new Date(promptAt).getTime() - now.getTime()) / 60000) : 0;
1914
- 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');
1915
1989
  const message = doctorAlertMessage({ review, draft, identity: await readDoctorIdentity(review), link: doctorLink(review), reminder });
1916
1990
  return { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator })) };
1917
1991
  }
@@ -1995,6 +2069,7 @@ async function recordDoctorDecision({
1995
2069
  reason = null,
1996
2070
  draftNumber: seenDraftNumber = null,
1997
2071
  closingCaseIds = null,
2072
+ caseStatuses = null,
1998
2073
  recordedBy,
1999
2074
  requestId = null,
2000
2075
  } = {}) {
@@ -2033,6 +2108,7 @@ async function recordDoctorDecision({
2033
2108
  }
2034
2109
 
2035
2110
  const review = await loadReview(reviewId);
2111
+ const chosenCaseMirrors = caseStatusMirrorsOf(caseStatuses, review);
2036
2112
  const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
2037
2113
  const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
2038
2114
  if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
@@ -2076,8 +2152,10 @@ async function recordDoctorDecision({
2076
2152
  }
2077
2153
  const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
2078
2154
 
2079
- const updated = await updateReview(reviewId, allowedStatuses, {
2155
+ const caseStatusMirrors = [...chosenCaseMirrors, ...await impliedCaseStatusMirrors(review, decision, returnReason, chosenCaseMirrors)];
2156
+ let updated = await updateReview(reviewId, allowedStatuses, {
2080
2157
  $push: {
2158
+ ...(caseStatusMirrors.length && caseStatusPushOf(caseStatusMirrors, operator)),
2081
2159
  decisions: {
2082
2160
  decision,
2083
2161
  source,
@@ -2106,6 +2184,7 @@ async function recordDoctorDecision({
2106
2184
  const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
2107
2185
  return cancelled;
2108
2186
  }
2187
+ if (caseStatusMirrors.length) ({ review: updated } = await syncCase(updated, operator, requestId));
2109
2188
  return updated;
2110
2189
  }
2111
2190
 
@@ -2665,6 +2744,8 @@ module.exports = {
2665
2744
  recordReviewUpdate,
2666
2745
  requestBotDraft,
2667
2746
  sendApprovedIndications,
2747
+ resolveSettledCases,
2748
+ setCaseStatuses,
2668
2749
  setReviewCases,
2669
2750
  suggestDraft,
2670
2751
  suggestKeyQuestions,
@@ -59,6 +59,7 @@ const CASE_STATUSES = [
59
59
  'radioterapia_revisión',
60
60
  'internado',
61
61
  ];
62
+ const UNTRIAGED_CASE_STATUSES = [null, 'Pendiente', 'Activo', 'En evaluación', 'en revision_medica'];
62
63
  // The operations status of a case is its FHIR case Task status, the same vocabulary nexus mirrors.
63
64
  const OPERATIONS_STATUSES = [...new Set(Object.values(CASE_STATUS_BY_REVIEW_STATUS).map(({ label }) => label))];
64
65
 
@@ -161,6 +162,13 @@ async function readTasks(kind, whatsappId) {
161
162
 
162
163
  const readPatientCases = (code) => readAllTasks('cases', validWhatsappId(code));
163
164
 
165
+ async function readUnreviewedCaseCandidates(since) {
166
+ const untriaged = UNTRIAGED_CASE_STATUSES.map((status) => (status ? fieldEquals('status', status) : '{status}=BLANK()'));
167
+ const filter = `AND(${TASK_KINDS.cases.scope}, {grade}>=2, {closed_time}=BLANK(), OR(${untriaged.join(', ')}), IS_AFTER({created}, '${since.toISOString()}'))`;
168
+ const rows = await getRecordByFilter(Monitoreo_ID, TASK_KINDS.cases.table, filter, null, [...TASK_KINDS.cases.fields, 'whatsapp_id'], true);
169
+ return rows.map((row) => ({ ...toCase(row), patientCode: [row.whatsapp_id].flat()[0] ?? null }));
170
+ }
171
+
164
172
  async function openCaseIds(code) {
165
173
  const cases = await readPatientCases(code);
166
174
  return cases.filter((patientCase) => patientCase.isOpen).map((patientCase) => patientCase.recordId);
@@ -214,7 +222,9 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
214
222
 
215
223
  module.exports = {
216
224
  MAX_NOTE_LENGTH,
225
+ UNTRIAGED_CASE_STATUSES,
217
226
  openCaseIds,
227
+ readUnreviewedCaseCandidates,
218
228
  readPatientCases,
219
229
  getPatientTasks,
220
230
  updatePatientTask,
@@ -5,8 +5,10 @@ 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
- const { sweepCaseFollowUps, sweepStaleQueues } = require('./caseFollowUpSweepService');
10
+ const { sweepCaseFollowUps, sweepCaseStatuses, sweepStaleQueues } = require('./caseFollowUpSweepService');
11
+ const { sweepUnreviewedCases } = require('./unreviewedCaseService');
10
12
 
11
13
  const SWEEP_LIMIT = 10;
12
14
  const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
@@ -93,25 +95,39 @@ const untakenSweeper = createIntervalSweeper({
93
95
  defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
94
96
  });
95
97
 
98
+ const unopenedSweeper = createIntervalSweeper({
99
+ label: '[UnopenedCaseSweep]',
100
+ sweep: () => sweepUnopenedCases(),
101
+ defaultIntervalMs: () => DEFAULT_SWEEP_INTERVAL_MS,
102
+ });
103
+
96
104
  const watchSweeper = createIntervalSweeper({
97
105
  label: '[WatchExpirySweep]',
98
106
  sweep: () => sweepExpiredWatches(),
99
107
  defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
100
108
  });
101
109
 
110
+ const unreviewedSweeper = createIntervalSweeper({
111
+ label: '[UnreviewedCaseSweep]',
112
+ sweep: () => sweepUnreviewedCases(),
113
+ defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
114
+ });
115
+
102
116
  const caseFollowUpSweeper = createIntervalSweeper({
103
117
  label: '[CaseFollowUpSweep]',
104
- sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()),
118
+ sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()) + (await sweepCaseStatuses()),
105
119
  defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
106
120
  });
107
121
 
108
122
  const startReviewAlertSweep = (options) => {
109
123
  untakenSweeper.start(options);
124
+ unopenedSweeper.start();
110
125
  // A watch runs out in hours, so it keeps its own slower interval.
111
126
  watchSweeper.start();
112
127
  caseFollowUpSweeper.start();
128
+ unreviewedSweeper.start();
113
129
  return sweeper.start(options);
114
130
  };
115
- const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop()]);
131
+ const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), unopenedSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop(), unreviewedSweeper.stop()]);
116
132
 
117
133
  module.exports = { startReviewAlertSweep, stopReviewAlertSweep, sweepDoctorAlerts };
@@ -2,7 +2,7 @@ const { mapConcurrent } = require('../utils/concurrencyUtils');
2
2
  const { httpError } = require('../utils/httpErrorUtils');
3
3
  const { logger } = require('../utils/logger');
4
4
  const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
5
- const { FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
5
+ const { DONE_STATUSES, FOLLOWUP_STATUSES, URGENCY_RANK, getEscalationReview } = require('../models/escalationReviewModel');
6
6
 
7
7
  const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
8
8
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
@@ -10,7 +10,6 @@ const { caseStateOf } = require('./escalationCaseStateService');
10
10
  const { UNTAKEN_PROJECTION } = require('./untakenAlertService');
11
11
 
12
12
  const DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
13
- const DONE_STATUSES = ['closed', 'cancelled'];
14
13
  const BOARD_BUCKETS = ['pending', 'followup', 'done'];
15
14
  const STATE_CONCURRENCY = 10;
16
15
  const BOARD_FILTER_PREFIX = 'clinical-review-';
@@ -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 };
@@ -0,0 +1,79 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+ const { addWorkingMinutes } = require('../utils/dateUtils');
4
+ const { getEscalationReview } = require('../models/escalationReviewModel');
5
+ const { escalationUnreviewedCaseNoticeLive } = require('../clinical/flags/escalationFlags');
6
+ const { WriteClaimStore } = require('../clinical/services/writeClaimStore');
7
+
8
+ const { readUnreviewedCaseCandidates } = require('./patientTaskService');
9
+ const { sendGroupNotice } = require('./teamAlertService');
10
+ const { teamAlertIdentity } = require('./escalationReviewService');
11
+ const { duration } = require('./untakenAlertService');
12
+ const { positiveSetting, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
13
+
14
+ const MINUTE_MS = 60 * 1000;
15
+ const LOOKBACK_MS = 48 * 60 * MINUTE_MS;
16
+ const DEFAULT_MINUTES = { 3: 60, 2: 120 };
17
+ const MINUTES_KEYS = { 3: 'ESCALATION_UNREVIEWED_MINUTES_G3', 2: 'ESCALATION_UNREVIEWED_MINUTES_G2' };
18
+ const noticed = new WriteClaimStore({ namespace: 'unreviewedCaseNotice', ttlMs: 14 * 24 * 60 * MINUTE_MS });
19
+
20
+ const errorOf = (error) => redactDirectIdentifiers(String(error?.message || error));
21
+ const gradeOf = (patientCase) => (Number(String(patientCase.grade ?? '').match(/\d+/)?.[0]) >= 3 ? 3 : 2);
22
+ const caseLabel = (patientCase) => [patientCase.number ? `#${patientCase.number}` : null, patientCase.description].filter(Boolean).join(' · ');
23
+
24
+ function isDue(patientCase, now, policy) {
25
+ const created = new Date(patientCase.createdAt);
26
+ if (Number.isNaN(created.getTime())) return false;
27
+ const grade = gradeOf(patientCase);
28
+ return addWorkingMinutes(created, positiveSetting(MINUTES_KEYS[grade], DEFAULT_MINUTES[grade]), policy.teamHours) <= now;
29
+ }
30
+
31
+ async function reviewedCaseIds(recordIds) {
32
+ const reviews = await getEscalationReview()
33
+ .find({ closedAt: null, patientCaseRecordIds: { $in: recordIds } }, { patientCaseRecordIds: 1 })
34
+ .lean();
35
+ return new Set(reviews.flatMap((review) => review.patientCaseRecordIds ?? []));
36
+ }
37
+
38
+ async function noticePatient(patientCode, cases, now) {
39
+ const { patient, doctor, identity, link } = await teamAlertIdentity({ _id: null, patientCode });
40
+ if (identity.testPatient) return 'skipped';
41
+ const grade = Math.max(...cases.map(gradeOf));
42
+ const oldest = new Date(Math.min(...cases.map((patientCase) => new Date(patientCase.createdAt).getTime())));
43
+ const header = `📋 ${cases.length > 1 ? 'Casos' : 'Caso'} G${grade} sin revisión clínica · creado hace ${duration(Math.max(1, Math.round((now - oldest) / MINUTE_MS)))}`;
44
+ const action = 'Qué hacer: abrir la revisión clínica o poner su estado en Pendientes';
45
+ const sent = await sendGroupNotice([header, `${patient} (${doctor})`, ...cases.map(caseLabel), action, link].join('\n'), null, [header, action].join('\n'));
46
+ if (sent.delivered) return 'sent';
47
+ logger.error('[UnreviewedCase] The notice did not reach the group', { error: sent.error });
48
+ return 'failed';
49
+ }
50
+
51
+ async function sweepUnreviewedCases({ now = new Date() } = {}) {
52
+ if (!escalationUnreviewedCaseNoticeLive()) return 0;
53
+ const policy = responseDeadlinePolicy();
54
+ if (teamOpenAt(now, policy).getTime() !== now.getTime()) return 0;
55
+ const due = (await readUnreviewedCaseCandidates(new Date(now.getTime() - LOOKBACK_MS)))
56
+ .filter((patientCase) => patientCase.isOpen && patientCase.patientCode && isDue(patientCase, now, policy));
57
+ if (!due.length) return 0;
58
+ const reviewed = await reviewedCaseIds(due.map((patientCase) => patientCase.recordId));
59
+ const byPatient = new Map();
60
+ for (const patientCase of due) {
61
+ if (reviewed.has(patientCase.recordId)) continue;
62
+ if ((await noticed.acquire(patientCase.recordId, now.toISOString())) !== 'acquired') continue;
63
+ byPatient.set(patientCase.patientCode, [...(byPatient.get(patientCase.patientCode) ?? []), patientCase]);
64
+ }
65
+ let sent = 0;
66
+ for (const [patientCode, cases] of byPatient) {
67
+ let outcome = 'failed';
68
+ try {
69
+ outcome = await noticePatient(patientCode, cases, now);
70
+ } catch (error) {
71
+ logger.error('[UnreviewedCase] The notice failed', { error: errorOf(error) });
72
+ }
73
+ if (outcome === 'sent') sent += 1;
74
+ if (outcome === 'failed') await Promise.all(cases.map((patientCase) => noticed.release(patientCase.recordId)));
75
+ }
76
+ return sent;
77
+ }
78
+
79
+ module.exports = { sweepUnreviewedCases };
@@ -5,14 +5,14 @@ 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');
12
12
  const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, FEVER_CATEGORY, PRE_DECISION_STATUSES, appliedLevelOf, 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, reminderDigestLive, reminderSlotOf, sendDueDoctorDigests, sendReminderDigest } = 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;
@@ -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);
@@ -218,24 +230,10 @@ async function alertIfUntaken(review, clock, stage, now, policy) {
218
230
  const remindersSince = (review, since) => (review.doctorAlerts ?? [])
219
231
  .filter((sent) => sent.kind === 'reminder' && new Date(sent.sentAt).getTime() >= since.getTime());
220
232
 
221
- // An urgent case with no patient timer waits for the shared reminder at the set times instead of its own.
222
- const remindsTogether = (review, clock) => clock.level === 'urgent' && !armedPromptAt(review) && reminderDigestLive();
223
-
224
- // Whether an urgent case the doctor already has goes in this slot's shared reminder.
225
- async function inReminderDigest(review, clock, slot) {
226
- if (review.status !== 'awaiting_doctor' || remindersSince(review, slot).length) return false;
227
- if ((review.doctorAlertKind === 'patient_prompt' && review.doctorAlertAttempts > 0) || promptedSince(review, clock.stagesFrom)
228
- || new Date(review.feverPromptStartedAt ?? 0) >= clock.stagesFrom) return false;
229
- const reached = doctorRangSince(review, clock.stagesFrom) || new Date(review.digestSentAt ?? 0) >= clock.stagesFrom;
230
- // Measured from the slot start, so a case never joins a slot late in a second message.
231
- const recent = new Date(slot.getTime() - RECENT_DIGEST_MS);
232
- if (!reached || doctorRangSince(review, recent) || new Date(review.digestSentAt ?? 0) >= recent) return false;
233
- return !await caseTakenReason(review, clock.since, clock.level);
234
- }
235
-
236
233
  async function remindDoctorIfDue(review, clock, now, policy) {
237
234
  if (review.status !== 'awaiting_doctor') return false;
238
235
  const promptAt = armedPromptAt(review);
236
+ if (!promptAt && clock.level === 'urgent' && escalationUnopenedReminderLive() && ringAtOf(review)) return false;
239
237
  if (review.doctorAlertKind === 'patient_prompt' && review.doctorAlertAttempts > 0) return false;
240
238
  const dueAt = doctorReminderAt(clock.level, clock.stagesFrom, policy, promptAt);
241
239
  const deadline = clock.stages.find((stage) => stage.stage === 'deadline').dueAt;
@@ -299,8 +297,6 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
299
297
  .limit(SWEEP_LIMIT)
300
298
  .lean();
301
299
  const policy = responseDeadlinePolicy();
302
- const slot = alerts ? reminderSlotOf(now, policy.teamHours.timeZone) : null;
303
- const together = [];
304
300
  let sent = 0;
305
301
  const failed = (message, review, error) => logger.error(message, {
306
302
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -329,18 +325,15 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
329
325
  }
330
326
  // After the characterization, whose update ring the claim then sees.
331
327
  try {
332
- if (alerts && clock && remindsTogether(review, clock)) {
333
- if (slot && await inReminderDigest(review, clock, slot)) together.push(review._id);
334
- } else if (alerts && clock) await remindDoctorIfDue(review, clock, now, policy);
328
+ if (alerts && clock) await remindDoctorIfDue(review, clock, now, policy);
335
329
  } catch (error) {
336
330
  failed('[UntakenAlert] Could not check a review for a doctor reminder', review, error);
337
331
  }
338
332
  }
339
- await sendReminderDigest({ reviewIds: together, slot, now }).catch((error) => logger.error('[UntakenAlert] Could not send the shared doctor reminder', { error: redactDirectIdentifiers(String(error?.message || error)) }));
340
333
  if (autoHandoff) {
341
334
  await sendDueDoctorDigests({ now }).catch((error) => logger.error('[UntakenAlert] Could not send the doctor digest', { error: redactDirectIdentifiers(String(error?.message || error)) }));
342
335
  }
343
336
  return sent;
344
337
  }
345
338
 
346
- module.exports = { UNTAKEN_PROJECTION, dueStageOf, 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.21500",
3
+ "version": "6.7.0-dev.21502",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",