@peopl-health/nexus 6.6.2 → 6.7.0-dev.21499
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 +10 -0
- package/lib/controllers/escalationReviewController.js +18 -0
- package/lib/models/escalationReviewModel.js +11 -0
- package/lib/routes/index.js +2 -0
- package/lib/services/caseFollowUpSweepService.js +47 -5
- package/lib/services/escalationCaseStateService.js +1 -2
- package/lib/services/escalationReviewService.js +84 -3
- package/lib/services/patientTaskService.js +10 -0
- package/lib/services/reviewAlertSweepService.js +11 -3
- package/lib/services/reviewBoardService.js +1 -2
- package/lib/services/unreviewedCaseService.js +75 -0
- package/lib/services/untakenAlertService.js +1 -1
- package/package.json +1 -1
|
@@ -52,8 +52,18 @@ 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
|
+
|
|
55
63
|
module.exports = {
|
|
56
64
|
escalationCaseFollowUpLive,
|
|
65
|
+
escalationCaseStatusReminderLive,
|
|
66
|
+
escalationUnreviewedCaseNoticeLive,
|
|
57
67
|
escalationApproverAlertLive,
|
|
58
68
|
escalationAssessmentLive,
|
|
59
69
|
escalationAutoHandoffLive,
|
|
@@ -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'];
|
|
@@ -291,6 +292,13 @@ const pendingCaseMirrorSchema = new mongoose.Schema({
|
|
|
291
292
|
changes: { type: mongoose.Schema.Types.Mixed, required: true },
|
|
292
293
|
}, { timestamps: { createdAt: true, updatedAt: false } });
|
|
293
294
|
|
|
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
|
+
|
|
294
302
|
const interruptionResolutionSchema = new mongoose.Schema({
|
|
295
303
|
fromStatus: { type: String, enum: INTERRUPTED_STATUSES, required: true },
|
|
296
304
|
notes: { type: String, required: true },
|
|
@@ -375,6 +383,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
375
383
|
watchNotices: { type: [watchNoticeSchema], default: [] },
|
|
376
384
|
caseFollowUp: { type: caseFollowUpSchema, default: null },
|
|
377
385
|
staleQueueNoticeAt: { type: Date, default: null },
|
|
386
|
+
caseStatusNoticeAt: { type: Date, default: null },
|
|
378
387
|
blockingAsks: { type: [blockingAskSchema], default: [] },
|
|
379
388
|
inTurnAsks: { type: [inTurnAskSchema], default: [] },
|
|
380
389
|
feverPromptStartedAt: { type: Date, default: null },
|
|
@@ -388,6 +397,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
388
397
|
patientDelivery: { type: patientDeliverySchema, default: null },
|
|
389
398
|
patientSends: { type: [patientSendSchema], default: undefined },
|
|
390
399
|
pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
|
|
400
|
+
doctorCaseStatuses: { type: [doctorCaseStatusSchema], default: [] },
|
|
391
401
|
interruptionResolution: { type: interruptionResolutionSchema, default: null },
|
|
392
402
|
identityBlock: { type: identityBlockSchema, default: null },
|
|
393
403
|
closedBy: { type: String, default: null },
|
|
@@ -462,6 +472,7 @@ module.exports = {
|
|
|
462
472
|
INTERRUPTED_STATUSES,
|
|
463
473
|
PLAN_DURATIONS,
|
|
464
474
|
PLAN_FOLLOW_UPS,
|
|
475
|
+
DONE_STATUSES,
|
|
465
476
|
FOLLOWUP_STATUSES,
|
|
466
477
|
RETURN_REASONS,
|
|
467
478
|
URGENCY_LEVELS,
|
package/lib/routes/index.js
CHANGED
|
@@ -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 {
|
|
9
|
-
const {
|
|
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
|
-
|
|
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 };
|
|
@@ -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),
|
|
@@ -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
|
|
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,
|
|
@@ -6,7 +6,8 @@ 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, sweepStaleQueues } = require('./caseFollowUpSweepService');
|
|
9
|
+
const { sweepCaseFollowUps, sweepCaseStatuses, sweepStaleQueues } = require('./caseFollowUpSweepService');
|
|
10
|
+
const { sweepUnreviewedCases } = require('./unreviewedCaseService');
|
|
10
11
|
|
|
11
12
|
const SWEEP_LIMIT = 10;
|
|
12
13
|
const DEFAULT_SWEEP_INTERVAL_MS = 30 * 1000;
|
|
@@ -99,9 +100,15 @@ const watchSweeper = createIntervalSweeper({
|
|
|
99
100
|
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
100
101
|
});
|
|
101
102
|
|
|
103
|
+
const unreviewedSweeper = createIntervalSweeper({
|
|
104
|
+
label: '[UnreviewedCaseSweep]',
|
|
105
|
+
sweep: () => sweepUnreviewedCases(),
|
|
106
|
+
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
107
|
+
});
|
|
108
|
+
|
|
102
109
|
const caseFollowUpSweeper = createIntervalSweeper({
|
|
103
110
|
label: '[CaseFollowUpSweep]',
|
|
104
|
-
sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()),
|
|
111
|
+
sweep: async () => (await sweepCaseFollowUps()) + (await sweepStaleQueues()) + (await sweepCaseStatuses()),
|
|
105
112
|
defaultIntervalMs: () => WATCH_SWEEP_INTERVAL_MS,
|
|
106
113
|
});
|
|
107
114
|
|
|
@@ -110,8 +117,9 @@ const startReviewAlertSweep = (options) => {
|
|
|
110
117
|
// A watch runs out in hours, so it keeps its own slower interval.
|
|
111
118
|
watchSweeper.start();
|
|
112
119
|
caseFollowUpSweeper.start();
|
|
120
|
+
unreviewedSweeper.start();
|
|
113
121
|
return sweeper.start(options);
|
|
114
122
|
};
|
|
115
|
-
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop()]);
|
|
123
|
+
const stopReviewAlertSweep = () => Promise.all([sweeper.stop(), untakenSweeper.stop(), watchSweeper.stop(), caseFollowUpSweeper.stop(), unreviewedSweeper.stop()]);
|
|
116
124
|
|
|
117
125
|
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,75 @@
|
|
|
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 };
|
|
@@ -323,4 +323,4 @@ async function sweepUntakenAlerts({ now = new Date() } = {}) {
|
|
|
323
323
|
return sent;
|
|
324
324
|
}
|
|
325
325
|
|
|
326
|
-
module.exports = { UNTAKEN_PROJECTION, dueStageOf, sweepUntakenAlerts, untakenClockOf };
|
|
326
|
+
module.exports = { UNTAKEN_PROJECTION, dueStageOf, duration, sweepUntakenAlerts, untakenClockOf };
|