@peopl-health/nexus 6.7.0-dev.21499 → 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.
- package/lib/clinical/flags/escalationFlags.js +0 -10
- package/lib/clinical/helpers/doctorReviewMessageHelper.js +4 -1
- package/lib/controllers/escalationReviewController.js +0 -18
- package/lib/models/escalationReviewModel.js +0 -11
- package/lib/routes/index.js +0 -2
- package/lib/services/caseFollowUpSweepService.js +5 -47
- package/lib/services/doctorDigestService.js +96 -8
- package/lib/services/escalationCaseStateService.js +2 -1
- package/lib/services/escalationReviewService.js +3 -84
- package/lib/services/patientTaskService.js +0 -10
- package/lib/services/reviewAlertSweepService.js +3 -11
- package/lib/services/reviewBoardService.js +2 -1
- package/lib/services/untakenAlertService.js +23 -3
- package/package.json +1 -1
- package/lib/services/unreviewedCaseService.js +0 -75
|
@@ -52,18 +52,8 @@ 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 escalationUnreviewedCaseNoticeLive() {
|
|
60
|
-
return flagOn('ESCALATION_UNREVIEWED_CASE_NOTICE_LIVE');
|
|
61
|
-
}
|
|
62
|
-
|
|
63
55
|
module.exports = {
|
|
64
56
|
escalationCaseFollowUpLive,
|
|
65
|
-
escalationCaseStatusReminderLive,
|
|
66
|
-
escalationUnreviewedCaseNoticeLive,
|
|
67
57
|
escalationApproverAlertLive,
|
|
68
58
|
escalationAssessmentLive,
|
|
69
59
|
escalationAutoHandoffLive,
|
|
@@ -243,7 +243,9 @@ function doctorBrief({ kind, change = null, reminder = null, level, identity, dr
|
|
|
243
243
|
];
|
|
244
244
|
}
|
|
245
245
|
|
|
246
|
-
const
|
|
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,
|
|
@@ -8,7 +8,6 @@ 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'];
|
|
12
11
|
const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
13
12
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
14
13
|
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned', 'indications_queued'];
|
|
@@ -292,13 +291,6 @@ const pendingCaseMirrorSchema = new mongoose.Schema({
|
|
|
292
291
|
changes: { type: mongoose.Schema.Types.Mixed, required: true },
|
|
293
292
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
294
293
|
|
|
295
|
-
const doctorCaseStatusSchema = new mongoose.Schema({
|
|
296
|
-
recordId: { type: String, required: true },
|
|
297
|
-
status: { type: String, required: true },
|
|
298
|
-
setBy: { type: String, required: true },
|
|
299
|
-
setAt: { type: Date, required: true },
|
|
300
|
-
}, { _id: false });
|
|
301
|
-
|
|
302
294
|
const interruptionResolutionSchema = new mongoose.Schema({
|
|
303
295
|
fromStatus: { type: String, enum: INTERRUPTED_STATUSES, required: true },
|
|
304
296
|
notes: { type: String, required: true },
|
|
@@ -383,7 +375,6 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
383
375
|
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
384
376
|
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
385
377
|
staleQueueNoticeAt: { type: Date, default: null },
|
|
386
|
-
caseStatusNoticeAt: { type: Date, default: null },
|
|
387
378
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
388
379
|
inTurnAsks: { type: [inTurnAskSchema], default: [] },
|
|
389
380
|
feverPromptStartedAt: { type: Date, default: null },
|
|
@@ -397,7 +388,6 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
397
388
|
patientDelivery: { type: patientDeliverySchema, default: null },
|
|
398
389
|
patientSends: { type: [patientSendSchema], default: undefined },
|
|
399
390
|
pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
|
|
400
|
-
doctorCaseStatuses: { type: [doctorCaseStatusSchema], default: [] },
|
|
401
391
|
interruptionResolution: { type: interruptionResolutionSchema, default: null },
|
|
402
392
|
identityBlock: { type: identityBlockSchema, default: null },
|
|
403
393
|
closedBy: { type: String, default: null },
|
|
@@ -472,7 +462,6 @@ module.exports = {
|
|
|
472
462
|
INTERRUPTED_STATUSES,
|
|
473
463
|
PLAN_DURATIONS,
|
|
474
464
|
PLAN_FOLLOW_UPS,
|
|
475
|
-
DONE_STATUSES,
|
|
476
465
|
FOLLOWUP_STATUSES,
|
|
477
466
|
RETURN_REASONS,
|
|
478
467
|
URGENCY_LEVELS,
|
package/lib/routes/index.js
CHANGED
|
@@ -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,
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
const { logger } = require('../utils/logger');
|
|
2
2
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
3
|
-
const {
|
|
4
|
-
const { escalationCaseFollowUpLive,
|
|
3
|
+
const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
4
|
+
const { escalationCaseFollowUpLive, escalationStaleQueueNoticeLive } = require('../clinical/flags/escalationFlags');
|
|
5
5
|
|
|
6
6
|
const { logPatientChange } = require('./patientService');
|
|
7
7
|
const { getThreadInfo } = require('./threadService');
|
|
8
|
-
const {
|
|
9
|
-
const {
|
|
10
|
-
const { effectiveUrgencyOf, positiveSetting, responseDeadlinePolicy, teamOpenAt } = require('./reviewDeadlineService');
|
|
8
|
+
const { BOOKKEEPING, closeEscalationReview, followUpReadingOf, noticeCaseThread } = require('./escalationReviewService');
|
|
9
|
+
const { effectiveUrgencyOf, positiveSetting } = require('./reviewDeadlineService');
|
|
11
10
|
const { FOLLOW_UP_STATUSES, SECOND_TRY_MS, armCaseFollowUp, askedAt, lastReplyAt, rewriteRow } = require('./caseFollowUpService');
|
|
12
11
|
|
|
13
12
|
const OPERATOR = 'bot:caseFollowUp';
|
|
@@ -20,8 +19,6 @@ const STALE_QUEUE_STATUSES = ['indications_queued', 'needs_intervention'];
|
|
|
20
19
|
const DEFAULT_STALE_QUEUE_HOURS = 72;
|
|
21
20
|
const HOUR_MS = 60 * 60 * 1000;
|
|
22
21
|
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;
|
|
25
22
|
const STALE_QUEUE_HEADERS = {
|
|
26
23
|
indications_queued: '⏳ Indicación en cola sin enviar desde hace días',
|
|
27
24
|
needs_intervention: '⏳ Caso que requiere intervención sin movimiento desde hace días',
|
|
@@ -46,7 +43,6 @@ const checkAgainAt = (review, at) => getEscalationReview().updateOne(
|
|
|
46
43
|
async function close(review, result) {
|
|
47
44
|
const { review: closed } = await closeEscalationReview({ id: String(review._id), closedBy: OPERATOR, expectedAlarmCount: (review.alarms ?? []).length });
|
|
48
45
|
await audit(closed, { action: 'followup_result', result });
|
|
49
|
-
if (result === 'answered') await resolveSettledCases(closed, OPERATOR);
|
|
50
46
|
}
|
|
51
47
|
|
|
52
48
|
async function keepUnanswered(review, now) {
|
|
@@ -157,42 +153,4 @@ async function sweepStaleQueues({ now = new Date() } = {}) {
|
|
|
157
153
|
return noticed;
|
|
158
154
|
}
|
|
159
155
|
|
|
160
|
-
|
|
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 };
|
|
156
|
+
module.exports = { sweepCaseFollowUps, sweepStaleQueues };
|
|
@@ -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
|
-
//
|
|
38
|
-
async function
|
|
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
|
-
|
|
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 };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const { logger } = require('../utils/logger');
|
|
2
2
|
const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
3
|
-
const {
|
|
3
|
+
const { 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,6 +10,7 @@ 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'];
|
|
13
14
|
const ANSWERABLE_OUTCOMES = ['sent', 'unknown'];
|
|
14
15
|
const timeOf = (value) => new Date(value).getTime();
|
|
15
16
|
|
|
@@ -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,
|
|
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,49 +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
|
-
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
|
-
|
|
192
149
|
const reviewIdOf = (id) => {
|
|
193
150
|
if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
|
|
194
151
|
return id;
|
|
@@ -985,20 +942,6 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
985
942
|
return review;
|
|
986
943
|
}
|
|
987
944
|
|
|
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
|
-
|
|
1002
945
|
async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
|
|
1003
946
|
const reviewId = reviewIdOf(id);
|
|
1004
947
|
const operator = requiredText(loggedBy, 'loggedBy');
|
|
@@ -1580,23 +1523,6 @@ async function followUpCasesOf(review, sinceMs) {
|
|
|
1580
1523
|
return { review: stored, known: new Set(known) };
|
|
1581
1524
|
}
|
|
1582
1525
|
|
|
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
|
-
|
|
1600
1526
|
async function closeSettled(review) {
|
|
1601
1527
|
try {
|
|
1602
1528
|
const { review: closed } = await closeEscalationReview({
|
|
@@ -1606,7 +1532,7 @@ async function closeSettled(review) {
|
|
|
1606
1532
|
expectedUpdatedAt: review.updatedAt,
|
|
1607
1533
|
});
|
|
1608
1534
|
await audit(closed, AGENT_OPERATOR, null, { action: 'followup_result', result: 'settled' });
|
|
1609
|
-
return
|
|
1535
|
+
return closed;
|
|
1610
1536
|
} catch (error) {
|
|
1611
1537
|
logger.warn('[EscalationReview] The follow-up settled the case but the review did not close', {
|
|
1612
1538
|
escalationReviewId: String(review._id), error: redactedError(error),
|
|
@@ -2069,7 +1995,6 @@ async function recordDoctorDecision({
|
|
|
2069
1995
|
reason = null,
|
|
2070
1996
|
draftNumber: seenDraftNumber = null,
|
|
2071
1997
|
closingCaseIds = null,
|
|
2072
|
-
caseStatuses = null,
|
|
2073
1998
|
recordedBy,
|
|
2074
1999
|
requestId = null,
|
|
2075
2000
|
} = {}) {
|
|
@@ -2108,7 +2033,6 @@ async function recordDoctorDecision({
|
|
|
2108
2033
|
}
|
|
2109
2034
|
|
|
2110
2035
|
const review = await loadReview(reviewId);
|
|
2111
|
-
const chosenCaseMirrors = caseStatusMirrorsOf(caseStatuses, review);
|
|
2112
2036
|
const isDraftless = DRAFTLESS_DECISIONS.includes(decision);
|
|
2113
2037
|
const allowedStatuses = isDraftless ? [...new Set([...DOCUMENTING_STATUSES, ...DECIDABLE_STATUSES])] : DECIDABLE_STATUSES;
|
|
2114
2038
|
if (!allowedStatuses.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
@@ -2152,10 +2076,8 @@ async function recordDoctorDecision({
|
|
|
2152
2076
|
}
|
|
2153
2077
|
const warnings = decision === 'edited_approved' ? draftlessDrugWarnings(approvedText, draft) : [];
|
|
2154
2078
|
|
|
2155
|
-
const
|
|
2156
|
-
let updated = await updateReview(reviewId, allowedStatuses, {
|
|
2079
|
+
const updated = await updateReview(reviewId, allowedStatuses, {
|
|
2157
2080
|
$push: {
|
|
2158
|
-
...(caseStatusMirrors.length && caseStatusPushOf(caseStatusMirrors, operator)),
|
|
2159
2081
|
decisions: {
|
|
2160
2082
|
decision,
|
|
2161
2083
|
source,
|
|
@@ -2184,7 +2106,6 @@ async function recordDoctorDecision({
|
|
|
2184
2106
|
const { review: cancelled } = await syncCase(await resumeAssistant(updated, operator, requestId), operator, requestId);
|
|
2185
2107
|
return cancelled;
|
|
2186
2108
|
}
|
|
2187
|
-
if (caseStatusMirrors.length) ({ review: updated } = await syncCase(updated, operator, requestId));
|
|
2188
2109
|
return updated;
|
|
2189
2110
|
}
|
|
2190
2111
|
|
|
@@ -2744,8 +2665,6 @@ module.exports = {
|
|
|
2744
2665
|
recordReviewUpdate,
|
|
2745
2666
|
requestBotDraft,
|
|
2746
2667
|
sendApprovedIndications,
|
|
2747
|
-
resolveSettledCases,
|
|
2748
|
-
setCaseStatuses,
|
|
2749
2668
|
setReviewCases,
|
|
2750
2669
|
suggestDraft,
|
|
2751
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
|
|
|
@@ -162,13 +161,6 @@ async function readTasks(kind, whatsappId) {
|
|
|
162
161
|
|
|
163
162
|
const readPatientCases = (code) => readAllTasks('cases', validWhatsappId(code));
|
|
164
163
|
|
|
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
|
-
|
|
172
164
|
async function openCaseIds(code) {
|
|
173
165
|
const cases = await readPatientCases(code);
|
|
174
166
|
return cases.filter((patientCase) => patientCase.isOpen).map((patientCase) => patientCase.recordId);
|
|
@@ -222,9 +214,7 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
|
|
|
222
214
|
|
|
223
215
|
module.exports = {
|
|
224
216
|
MAX_NOTE_LENGTH,
|
|
225
|
-
UNTRIAGED_CASE_STATUSES,
|
|
226
217
|
openCaseIds,
|
|
227
|
-
readUnreviewedCaseCandidates,
|
|
228
218
|
readPatientCases,
|
|
229
219
|
getPatientTasks,
|
|
230
220
|
updatePatientTask,
|
|
@@ -6,8 +6,7 @@ const { getEscalationReview } = require('../models/escalationReviewModel');
|
|
|
6
6
|
const { BOOKKEEPING, MAX_ALERT_ATTEMPTS, PRE_DECISION_STATUSES, sendScheduledDoctorAlert } = require('./escalationReviewService');
|
|
7
7
|
const { sweepUntakenAlerts } = require('./untakenAlertService');
|
|
8
8
|
const { sweepExpiredWatches } = require('./watchExpiryService');
|
|
9
|
-
const { sweepCaseFollowUps,
|
|
10
|
-
const { sweepUnreviewedCases } = require('./unreviewedCaseService');
|
|
9
|
+
const { sweepCaseFollowUps, sweepStaleQueues } = require('./caseFollowUpSweepService');
|
|
11
10
|
|
|
12
11
|
const SWEEP_LIMIT = 10;
|
|
13
12
|
const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
|
|
@@ -100,15 +99,9 @@ const watchSweeper = createIntervalSweeper({
|
|
|
100
99
|
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
101
100
|
});
|
|
102
101
|
|
|
103
|
-
const unreviewedSweeper = createIntervalSweeper({
|
|
104
|
-
label: '[UnreviewedCaseSweep]',
|
|
105
|
-
sweep: () => sweepUnreviewedCases(),
|
|
106
|
-
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
107
|
-
});
|
|
108
|
-
|
|
109
102
|
const caseFollowUpSweeper = createIntervalSweeper({
|
|
110
103
|
label: '[CaseFollowUpSweep]',
|
|
111
|
-
sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues())
|
|
104
|
+
sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()),
|
|
112
105
|
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
113
106
|
});
|
|
114
107
|
|
|
@@ -117,9 +110,8 @@ const startReviewAlertSweep = (options) => {
|
|
|
117
110
|
// A watch runs out in hours, so it keeps its own slower interval.
|
|
118
111
|
watchSweeper.start();
|
|
119
112
|
caseFollowUpSweeper.start();
|
|
120
|
-
unreviewedSweeper.start();
|
|
121
113
|
return sweeper.start(options);
|
|
122
114
|
};
|
|
123
|
-
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop()
|
|
115
|
+
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop()]);
|
|
124
116
|
|
|
125
117
|
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 {
|
|
5
|
+
const { 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,6 +10,7 @@ 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'];
|
|
13
14
|
const BOARD_BUCKETS = ['pending', 'followup', 'done'];
|
|
14
15
|
const STATE_CONCURRENCY = 10;
|
|
15
16
|
const BOARD_FILTER_PREFIX = 'clinical-review-';
|
|
@@ -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,15 +329,18 @@ 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
|
|
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
|
}
|
|
323
343
|
return sent;
|
|
324
344
|
}
|
|
325
345
|
|
|
326
|
-
module.exports = { UNTAKEN_PROJECTION, dueStageOf,
|
|
346
|
+
module.exports = { UNTAKEN_PROJECTION, dueStageOf, sweepUntakenAlerts, untakenClockOf };
|
package/package.json
CHANGED
|
@@ -1,75 +0,0 @@
|
|
|
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 = 24 * 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 false;
|
|
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 = `📋 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) logger.error('[UnreviewedCase] The notice did not reach the group', { error: sent.error });
|
|
47
|
-
return true;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
async function sweepUnreviewedCases({ now = new Date() } = {}) {
|
|
51
|
-
if (!escalationUnreviewedCaseNoticeLive()) return 0;
|
|
52
|
-
const policy = responseDeadlinePolicy();
|
|
53
|
-
if (teamOpenAt(now, policy).getTime() !== now.getTime()) return 0;
|
|
54
|
-
const due = (await readUnreviewedCaseCandidates(new Date(now.getTime() - LOOKBACK_MS)))
|
|
55
|
-
.filter((patientCase) => patientCase.patientCode && isDue(patientCase, now, policy));
|
|
56
|
-
if (!due.length) return 0;
|
|
57
|
-
const reviewed = await reviewedCaseIds(due.map((patientCase) => patientCase.recordId));
|
|
58
|
-
const byPatient = new Map();
|
|
59
|
-
for (const patientCase of due) {
|
|
60
|
-
if (reviewed.has(patientCase.recordId)) continue;
|
|
61
|
-
if ((await noticed.acquire(patientCase.recordId, now.toISOString())) !== 'acquired') continue;
|
|
62
|
-
byPatient.set(patientCase.patientCode, [...(byPatient.get(patientCase.patientCode) ?? []), patientCase]);
|
|
63
|
-
}
|
|
64
|
-
let sent = 0;
|
|
65
|
-
for (const [patientCode, cases] of byPatient) {
|
|
66
|
-
try {
|
|
67
|
-
if (await noticePatient(patientCode, cases, now)) sent += 1;
|
|
68
|
-
} catch (error) {
|
|
69
|
-
logger.error('[UnreviewedCase] The notice failed', { error: errorOf(error) });
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
return sent;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
module.exports = { sweepUnreviewedCases };
|