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

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.
@@ -243,7 +243,9 @@ function doctorBrief({ kind, change = null, reminder = null, level, identity, dr
243
243
  ];
244
244
  }
245
245
 
246
- const doctorDigestTitle = (count) => `${LEVEL_MARKS.urgent} ${BRIEF_VERBS.indication}: ${count} ${count === 1 ? 'caso urgente' : 'casos urgentes'}`;
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)}`;
247
249
 
248
250
  function doctorDigestLine({ identity, draft, alarmSymptom, deadline, now, timeZone, link }) {
249
251
  const head = [briefCaseLine(identity, briefSymptomOf(draft, alarmSymptom), alarmSymptom), deadlineLabel(deadline, now, timeZone)].filter(Boolean).join(' · ');
@@ -264,4 +266,5 @@ module.exports = {
264
266
  doctorBrief,
265
267
  doctorDigestLine,
266
268
  doctorDigestTitle,
269
+ doctorReminderTitle,
267
270
  };
@@ -16,7 +16,6 @@ const {
16
16
  recordDoctorDecision,
17
17
  requestBotDraft,
18
18
  sendApprovedIndications,
19
- setCaseStatuses,
20
19
  setReviewCases,
21
20
  suggestDraft,
22
21
  suggestKeyQuestions,
@@ -121,20 +120,6 @@ const setEscalationReviewCasesController = async (req, res) => {
121
120
  }
122
121
  };
123
122
 
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
-
138
123
  const addEscalationReviewCallLogController = async (req, res) => {
139
124
  try {
140
125
  const { outcome, notes, calledAt, triggeredBy } = req.body || {};
@@ -222,7 +207,6 @@ const recordEscalationReviewDecisionController = async (req, res) => {
222
207
  reason = null,
223
208
  draftNumber = null,
224
209
  closingCaseIds = null,
225
- caseStatuses = null,
226
210
  triggeredBy,
227
211
  } = req.body || {};
228
212
  const review = await recordDoctorDecision({
@@ -239,7 +223,6 @@ const recordEscalationReviewDecisionController = async (req, res) => {
239
223
  reason,
240
224
  draftNumber,
241
225
  closingCaseIds,
242
- caseStatuses,
243
226
  recordedBy: triggeredBy,
244
227
  requestId: req.requestId,
245
228
  });
@@ -339,7 +322,6 @@ module.exports = {
339
322
  reclassifyEscalationReviewUrgencyController,
340
323
  recordEscalationReviewDecisionController,
341
324
  sendEscalationReviewIndicationsController,
342
- setEscalationReviewCaseStatusesController,
343
325
  setEscalationReviewCasesController,
344
326
  suggestEscalationReviewDraftController,
345
327
  suggestEscalationReviewQuestionsController,
@@ -291,13 +291,6 @@ const pendingCaseMirrorSchema = new mongoose.Schema({
291
291
  changes: { type: mongoose.Schema.Types.Mixed, required: true },
292
292
  }, { timestamps: { createdAt: true, updatedAt: false } });
293
293
 
294
- const doctorCaseStatusSchema = new mongoose.Schema({
295
- recordId: { type: String, required: true },
296
- status: { type: String, required: true },
297
- setBy: { type: String, required: true },
298
- setAt: { type: Date, required: true },
299
- }, { _id: false });
300
-
301
294
  const interruptionResolutionSchema = new mongoose.Schema({
302
295
  fromStatus: { type: String, enum: INTERRUPTED_STATUSES, required: true },
303
296
  notes: { type: String, required: true },
@@ -395,7 +388,6 @@ const escalationReviewSchema = new mongoose.Schema({
395
388
  patientDelivery: { type: patientDeliverySchema, default: null },
396
389
  patientSends: { type: [patientSendSchema], default: undefined },
397
390
  pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
398
- doctorCaseStatuses: { type: [doctorCaseStatusSchema], default: [] },
399
391
  interruptionResolution: { type: interruptionResolutionSchema, default: null },
400
392
  identityBlock: { type: identityBlockSchema, default: null },
401
393
  closedBy: { type: String, default: null },
@@ -131,7 +131,6 @@ 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',
135
134
  'POST /:id/call-logs': 'addEscalationReviewCallLogController',
136
135
  'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
137
136
  'POST /:id/draft-requests': 'requestEscalationReviewDraftController',
@@ -318,7 +317,6 @@ const builtInControllers = {
318
317
  getReviewTimelineController: escalationReviewController.getReviewTimelineController,
319
318
  previewEscalationReviewPlanController: escalationReviewController.previewEscalationReviewPlanController,
320
319
  requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
321
- setEscalationReviewCaseStatusesController: escalationReviewController.setEscalationReviewCaseStatusesController,
322
320
  setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
323
321
  addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
324
322
  suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
@@ -5,9 +5,10 @@ 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 } = require('../clinical/helpers/doctorReviewMessageHelper');
8
+ const { doctorDigestLine, doctorDigestTitle, doctorReminderTitle } = require('../clinical/helpers/doctorReviewMessageHelper');
9
9
 
10
10
  const { logPatientChange } = require('./patientService');
11
+ const { getEscalationApprover } = require('./physicianService');
11
12
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
12
13
  const { BOOKKEEPING, DOCTOR_BRIEF_TEMPLATE_KEY, doctorAlertMessage, doctorLink, notifiedApprover, teamAlertIdentity } = require('./escalationReviewService');
13
14
 
@@ -23,6 +24,9 @@ const MAX_LINES_LENGTH = 800;
23
24
  const MAX_FIELD_LENGTH = 60;
24
25
  const STALE_CLAIM_MS = 10 * 60 * 1000;
25
26
  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})$/;
26
30
  const getMessaging = () => require('../core/NexusMessaging');
27
31
 
28
32
  const minutesOf = (key, fallback) => {
@@ -34,13 +38,15 @@ const redacted = (error) => redactDirectIdentifiers(String(error?.message || err
34
38
  // Urgent cases ready for the doctor go in a digest only once its template exists.
35
39
  const urgentDigestLive = () => Boolean(runtimeConfig.get(DIGEST_BRIEF_TEMPLATE_KEY) || runtimeConfig.get(DIGEST_TEMPLATE_KEY));
36
40
 
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();
41
+ // Throws when no single approver can be chosen.
42
+ async function approverContact(email = null) {
43
+ const approver = email ? await getEscalationApprover(email) : await notifiedApprover();
40
44
  const code = whatsAppCodeFromPhone(approver?.phone);
41
- return PATIENT_CODE.test(code) ? code : null;
45
+ return PATIENT_CODE.test(code) ? { code, email: approver.email } : null;
42
46
  }
43
47
 
48
+ const digestRecipient = async () => (await approverContact())?.code ?? null;
49
+
44
50
  // 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();
@@ -103,9 +109,9 @@ function chunksOf(entries) {
103
109
  return chunks;
104
110
  }
105
111
 
106
- async function sendDigest(code, entries, inWindow, perCase) {
112
+ async function sendDigest(code, entries, inWindow, perCase, heading = null) {
107
113
  const lines = entries.map(({ line }) => line);
108
- const title = !perCase && (briefStyle() ? doctorDigestTitle(entries.length) : String(entries.length));
114
+ const title = heading ?? (!perCase && (briefStyle() ? doctorDigestTitle(entries.length) : String(entries.length)));
109
115
  const outgoing = perCase
110
116
  ? { code, contentSid: lines[0].contentSid || runtimeConfig.get(ALERT_IDENTIFIED_TEMPLATE_KEY), variables: lines[0].template, triggeredBy: OPERATOR }
111
117
  : inWindow
@@ -186,4 +192,86 @@ async function sendDueDoctorDigests({ now = new Date() } = {}) {
186
192
  return sent;
187
193
  }
188
194
 
189
- module.exports = { MAX_CASES_PER_MESSAGE, digestDueAt, digestStillDue, digestRecipient, digestTimeOf, sendDueDoctorDigests, urgentDigestLive };
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 };
@@ -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, UNTRIAGED_CASE_STATUSES, openCaseIds, readPatientCases, updatePatientTask } = require('./patientTaskService');
59
+ const { MAX_NOTE_LENGTH, 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,48 +146,6 @@ 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
-
152
- function caseStatusMirrorsOf(value, review) {
153
- if (value == null) return [];
154
- if (!Array.isArray(value)) throw httpError(400, 'caseStatuses must be a list of { recordId, status }');
155
- const covered = new Set(caseIdsOf(review));
156
- const byCase = new Map();
157
- for (const entry of value) {
158
- const recordId = typeof entry?.recordId === 'string' ? entry.recordId.trim() : '';
159
- if (!covered.has(recordId)) throw httpError(400, `The review does not cover case ${recordId || '(none)'}`);
160
- if (!DOCTOR_CASE_STATUSES.includes(entry.status)) throw httpError(400, `status must be one of: ${DOCTOR_CASE_STATUSES.join(', ')}`);
161
- byCase.set(recordId, entry.status);
162
- }
163
- return [...byCase].map(([recordId, status]) => ({ recordId, changes: { status } }));
164
- }
165
-
166
- const IMPLIED_CASE_STATUS = { monitor: 'En vigilancia', approved: 'En tratamiento', edited_approved: 'En tratamiento', plan_approved: 'En tratamiento' };
167
-
168
- async function impliedCaseStatusMirrors(review, decision, returnReason, chosen) {
169
- const status = returnReason === 'no_requiere' ? 'Resuelto' : IMPLIED_CASE_STATUS[decision];
170
- const chosenIds = new Set(chosen.map(({ recordId }) => recordId));
171
- const covered = new Set(caseIdsOf(review).filter((recordId) => !chosenIds.has(recordId)));
172
- if (!status || !covered.size) return [];
173
- try {
174
- return (await readPatientCases(review.patientCode))
175
- .filter((patientCase) => covered.has(patientCase.recordId) && UNTRIAGED_CASE_STATUSES.includes(patientCase.status))
176
- .map((patientCase) => ({ recordId: patientCase.recordId, changes: { status } }));
177
- } catch (error) {
178
- logger.error('[EscalationReview] The cases were read for no implied clinical status', { escalationReviewId: String(review._id), error: redactedError(error) });
179
- return [];
180
- }
181
- }
182
-
183
- const caseStatusPushOf = (mirrors, setBy) => {
184
- const setAt = new Date();
185
- return {
186
- pendingCaseMirrors: { $each: mirrors },
187
- doctorCaseStatuses: { $each: mirrors.map(({ recordId, changes }) => ({ recordId, status: changes.status, setBy, setAt })) },
188
- };
189
- };
190
-
191
149
  const reviewIdOf = (id) => {
192
150
  if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
193
151
  return id;
@@ -984,20 +942,6 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
984
942
  return review;
985
943
  }
986
944
 
987
- async function setCaseStatuses({ id, caseStatuses, updatedBy, requestId = null } = {}) {
988
- const reviewId = reviewIdOf(id);
989
- const operator = requiredText(updatedBy, 'updatedBy');
990
- const current = await loadReview(reviewId);
991
- const mirrors = caseStatusMirrorsOf(caseStatuses, current);
992
- if (!mirrors.length) throw httpError(400, 'caseStatuses must name at least one case');
993
- const superseded = await supersededCaseIds(getEscalationReview(), current);
994
- const held = mirrors.find(({ recordId }) => superseded.has(recordId));
995
- if (held) throw httpError(409, `A newer review holds case ${held.recordId}; set its status there`);
996
- const review = await updateReview(reviewId, [current.status], { $push: caseStatusPushOf(mirrors, operator) });
997
- await audit(review, operator, requestId, { action: 'case_statuses_set', caseStatuses: mirrors.map(({ recordId, changes }) => ({ recordId, status: changes.status })) });
998
- return syncCase(review, operator, requestId);
999
- }
1000
-
1001
945
  async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
1002
946
  const reviewId = reviewIdOf(id);
1003
947
  const operator = requiredText(loggedBy, 'loggedBy');
@@ -2051,7 +1995,6 @@ async function recordDoctorDecision({
2051
1995
  reason = null,
2052
1996
  draftNumber: seenDraftNumber = null,
2053
1997
  closingCaseIds = null,
2054
- caseStatuses = null,
2055
1998
  recordedBy,
2056
1999
  requestId = null,
2057
2000
  } = {}) {
@@ -2090,7 +2033,6 @@ async function recordDoctorDecision({
2090
2033
  }
2091
2034
 
2092
2035
  const review = await loadReview(reviewId);
2093
- const chosenCaseMirrors = caseStatusMirrorsOf(caseStatuses, review);
2094
2036
  const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
2095
2037
  const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
2096
2038
  if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
@@ -2134,10 +2076,8 @@ async function recordDoctorDecision({
2134
2076
  }
2135
2077
  const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
2136
2078
 
2137
- const caseStatusMirrors = [...chosenCaseMirrors, ...await impliedCaseStatusMirrors(review, decision, returnReason, chosenCaseMirrors)];
2138
- let updated = await updateReview(reviewId, allowedStatuses, {
2079
+ const updated = await updateReview(reviewId, allowedStatuses, {
2139
2080
  $push: {
2140
- ...(caseStatusMirrors.length && caseStatusPushOf(caseStatusMirrors, operator)),
2141
2081
  decisions: {
2142
2082
  decision,
2143
2083
  source,
@@ -2166,7 +2106,6 @@ async function recordDoctorDecision({
2166
2106
  const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
2167
2107
  return cancelled;
2168
2108
  }
2169
- if (caseStatusMirrors.length) ({ review: updated } = await syncCase(updated, operator, requestId));
2170
2109
  return updated;
2171
2110
  }
2172
2111
 
@@ -2726,7 +2665,6 @@ module.exports = {
2726
2665
  recordReviewUpdate,
2727
2666
  requestBotDraft,
2728
2667
  sendApprovedIndications,
2729
- setCaseStatuses,
2730
2668
  setReviewCases,
2731
2669
  suggestDraft,
2732
2670
  suggestKeyQuestions,
@@ -59,7 +59,6 @@ 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'];
63
62
  // The operations status of a case is its FHIR case Task status, the same vocabulary nexus mirrors.
64
63
  const OPERATIONS_STATUSES = [...new Set(Object.values(CASE_STATUS_BY_REVIEW_STATUS).map(({ label }) => label))];
65
64
 
@@ -215,7 +214,6 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
215
214
 
216
215
  module.exports = {
217
216
  MAX_NOTE_LENGTH,
218
- UNTRIAGED_CASE_STATUSES,
219
217
  openCaseIds,
220
218
  readPatientCases,
221
219
  getPatientTasks,
@@ -12,7 +12,7 @@ const { BUSINESS_HOURS_LEVELS, HANDOFF_TAKES_LEVELS, doctorReminderAt, levelsOf,
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, sendDueDoctorDigests } = require('./doctorDigestService');
15
+ const { digestDueAt, digestStillDue, reminderDigestLive, reminderSlotOf, sendDueDoctorDigests, sendReminderDigest } = require('./doctorDigestService');
16
16
 
17
17
  const UNTAKEN_LEVELS = ['stat', 'asap', 'urgent'];
18
18
  const LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
@@ -218,6 +218,21 @@ async function alertIfUntaken(review, clock, stage, now, policy) {
218
218
  const remindersSince = (review, since) => (review.doctorAlerts ?? [])
219
219
  .filter((sent) => sent.kind === 'reminder' && new Date(sent.sentAt).getTime() >= since.getTime());
220
220
 
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
+
221
236
  async function remindDoctorIfDue(review, clock, now, policy) {
222
237
  if (review.status !== 'awaiting_doctor') return false;
223
238
  const promptAt = armedPromptAt(review);
@@ -284,6 +299,8 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
284
299
  .limit(SWEEP_LIMIT)
285
300
  .lean();
286
301
  const policy = responseDeadlinePolicy();
302
+ const slot = alerts ? reminderSlotOf(now, policy.teamHours.timeZone) : null;
303
+ const together = [];
287
304
  let sent = 0;
288
305
  const failed = (message, review, error) => logger.error(message, {
289
306
  escalationReviewId: String(review._id), error: redactDirectIdentifiers(String(error?.message || error)),
@@ -312,11 +329,14 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
312
329
  }
313
330
  // After the characterization, whose update ring the claim then sees.
314
331
  try {
315
- if (alerts && clock) await remindDoctorIfDue(review, clock, now, policy);
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);
316
335
  } catch (error) {
317
336
  failed('[UntakenAlert] Could not check a review for a doctor reminder', review, error);
318
337
  }
319
338
  }
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)) }));
320
340
  if (autoHandoff) {
321
341
  await sendDueDoctorDigests({ now }).catch((error) => logger.error('[UntakenAlert] Could not send the doctor digest', { error: redactDirectIdentifiers(String(error?.message || error)) }));
322
342
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.7.0-dev.21498",
3
+ "version": "6.7.0-dev.21500",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",