@peopl-health/nexus 5.72.8 → 5.72.10
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/controllers/escalationReviewController.js +6 -13
- package/lib/helpers/patientTaskRulesHelper.js +9 -2
- package/lib/models/escalationReviewModel.js +1 -0
- package/lib/routes/index.js +0 -2
- package/lib/services/escalationCaseTaskService.js +73 -16
- package/lib/services/escalationReviewService.js +20 -18
- package/lib/services/patientTaskService.js +3 -2
- package/package.json +1 -1
- package/lib/helpers/reviewCaseCandidateHelper.js +0 -51
|
@@ -16,7 +16,6 @@ const {
|
|
|
16
16
|
requestBotDraft,
|
|
17
17
|
sendApprovedIndications,
|
|
18
18
|
setReviewCases,
|
|
19
|
-
listReviewCaseCandidates,
|
|
20
19
|
suggestDraft,
|
|
21
20
|
suggestKeyQuestions,
|
|
22
21
|
confirmNoteFacts,
|
|
@@ -98,15 +97,6 @@ const setEscalationReviewCasesController = async (req, res) => {
|
|
|
98
97
|
}
|
|
99
98
|
};
|
|
100
99
|
|
|
101
|
-
const listEscalationReviewCaseCandidatesController = async (req, res) => {
|
|
102
|
-
try {
|
|
103
|
-
const candidates = await listReviewCaseCandidates({ id: req.params.id });
|
|
104
|
-
res.status(200).json({ success: true, candidates });
|
|
105
|
-
} catch (error) {
|
|
106
|
-
respondWithError(res, error, 'listing escalation review case candidates', { reviewId: req.params?.id });
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
|
|
110
100
|
const addEscalationReviewCallLogController = async (req, res) => {
|
|
111
101
|
try {
|
|
112
102
|
const { outcome, notes, calledAt, triggeredBy } = req.body || {};
|
|
@@ -190,6 +180,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
190
180
|
doctorReply = null,
|
|
191
181
|
reason = null,
|
|
192
182
|
draftNumber = null,
|
|
183
|
+
closingCaseIds = null,
|
|
193
184
|
triggeredBy,
|
|
194
185
|
} = req.body || {};
|
|
195
186
|
const review = await recordDoctorDecision({
|
|
@@ -202,6 +193,7 @@ const recordEscalationReviewDecisionController = async (req, res) => {
|
|
|
202
193
|
doctorReply,
|
|
203
194
|
reason,
|
|
204
195
|
draftNumber,
|
|
196
|
+
closingCaseIds,
|
|
205
197
|
recordedBy: triggeredBy,
|
|
206
198
|
requestId: req.requestId,
|
|
207
199
|
});
|
|
@@ -223,12 +215,13 @@ const sendEscalationReviewIndicationsController = async (req, res) => {
|
|
|
223
215
|
|
|
224
216
|
const closeEscalationReviewController = async (req, res) => {
|
|
225
217
|
try {
|
|
226
|
-
const { triggeredBy, deliveryConfirmed = false, interruptionNotes = null } = req.body || {};
|
|
218
|
+
const { triggeredBy, deliveryConfirmed = false, interruptionNotes = null, closingCaseIds = null } = req.body || {};
|
|
227
219
|
const { review, caseMirror, caseMirrors } = await closeEscalationReview({
|
|
228
220
|
id: req.params.id,
|
|
229
221
|
closedBy: triggeredBy,
|
|
230
222
|
deliveryConfirmed,
|
|
231
223
|
interruptionNotes,
|
|
224
|
+
closingCaseIds,
|
|
232
225
|
requestId: req.requestId,
|
|
233
226
|
});
|
|
234
227
|
res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
@@ -255,11 +248,12 @@ const reclassifyEscalationReviewUrgencyController = async (req, res) => {
|
|
|
255
248
|
|
|
256
249
|
const cancelEscalationReviewController = async (req, res) => {
|
|
257
250
|
try {
|
|
258
|
-
const { triggeredBy, reason = null } = req.body || {};
|
|
251
|
+
const { triggeredBy, reason = null, closingCaseIds = null } = req.body || {};
|
|
259
252
|
const { review, caseMirror, caseMirrors } = await cancelEscalationReview({
|
|
260
253
|
id: req.params.id,
|
|
261
254
|
cancelledBy: triggeredBy,
|
|
262
255
|
reason,
|
|
256
|
+
closingCaseIds,
|
|
263
257
|
requestId: req.requestId,
|
|
264
258
|
});
|
|
265
259
|
res.status(200).json({ success: true, review: withCaseStatus(review), caseMirror, caseMirrors });
|
|
@@ -299,7 +293,6 @@ module.exports = {
|
|
|
299
293
|
recordEscalationReviewDecisionController,
|
|
300
294
|
sendEscalationReviewIndicationsController,
|
|
301
295
|
setEscalationReviewCasesController,
|
|
302
|
-
listEscalationReviewCaseCandidatesController,
|
|
303
296
|
suggestEscalationReviewDraftController,
|
|
304
297
|
suggestEscalationReviewQuestionsController,
|
|
305
298
|
syncEscalationReviewCaseController,
|
|
@@ -15,6 +15,8 @@ const ATTENTION_CASE_WINDOW_MS = ATTENTION_CASE_WINDOW_DAYS * 24 * 60 * 60 * 100
|
|
|
15
15
|
const URGENT_REQUEST_URGENCY = 'urgent';
|
|
16
16
|
const REQUEST_URGENCIES = ['routine', 'soon', 'urgent'];
|
|
17
17
|
const URGENT_CASE_TYPES = ['Urgencia', 'Emergencia'];
|
|
18
|
+
// The operations statuses that close a case in Airtable, including the legacy lowercase one.
|
|
19
|
+
const CLOSING_CASE_OPERATIONS_STATUSES = new Set(['Cerrado', 'No requiere', 'cerrado']);
|
|
18
20
|
const TASK_PROGRAM_SOURCE = 'auna';
|
|
19
21
|
|
|
20
22
|
const programSourceFilter = (field) => `FIND('${escapeFormulaValue(TASK_PROGRAM_SOURCE)}', ARRAYJOIN({${field}}))`;
|
|
@@ -28,9 +30,13 @@ const isWithinAttentionWindow = (createdAt) => {
|
|
|
28
30
|
|
|
29
31
|
const needsRequestAttention = (status) => status === ATTENTION_REQUEST_STATUS;
|
|
30
32
|
|
|
31
|
-
|
|
33
|
+
// A case stays open until it is closed: a closed_time, or a closing operations status not yet stamped.
|
|
34
|
+
const isCaseOpen = (closedTime, createdAt, operationsStatus) => !closedTime
|
|
35
|
+
&& !CLOSING_CASE_OPERATIONS_STATUSES.has(operationsStatus)
|
|
36
|
+
&& isWithinAttentionWindow(createdAt);
|
|
32
37
|
|
|
33
|
-
|
|
38
|
+
// A case needs attention until it is attended, which stamps its resolved_time.
|
|
39
|
+
const needsCaseAttention = (resolvedTime, createdAt) => !resolvedTime && isWithinAttentionWindow(createdAt);
|
|
34
40
|
|
|
35
41
|
const isRequestUrgent = (urgency) => urgency === URGENT_REQUEST_URGENCY;
|
|
36
42
|
|
|
@@ -39,6 +45,7 @@ const isCaseUrgent = (type) => URGENT_CASE_TYPES.includes(type);
|
|
|
39
45
|
module.exports = {
|
|
40
46
|
ATTENTION_CASE_WINDOW_DAYS,
|
|
41
47
|
CLOSED_REQUEST_STATUSES,
|
|
48
|
+
CLOSING_CASE_OPERATIONS_STATUSES,
|
|
42
49
|
ATTENTION_REQUEST_STATUS,
|
|
43
50
|
REQUEST_URGENCIES,
|
|
44
51
|
isCaseOpen,
|
|
@@ -217,6 +217,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
217
217
|
closedAt: { type: Date, default: null },
|
|
218
218
|
cancellationReason: { type: String, default: null },
|
|
219
219
|
caseStatusMirror: { type: mongoose.Schema.Types.Mixed, default: null },
|
|
220
|
+
closingCaseIds: { type: [String], default: undefined },
|
|
220
221
|
}, { timestamps: true });
|
|
221
222
|
|
|
222
223
|
// The fields the FHIR case Task is built from; a write that touches one tells the listeners.
|
package/lib/routes/index.js
CHANGED
|
@@ -128,7 +128,6 @@ const escalationReviewRouteDefinitions = {
|
|
|
128
128
|
'GET /by-patient/:code': 'listEscalationReviewsController',
|
|
129
129
|
'GET /:id': 'getEscalationReviewController',
|
|
130
130
|
'GET /:id/timeline': 'getReviewTimelineController',
|
|
131
|
-
'GET /:id/case-candidates': 'listEscalationReviewCaseCandidatesController',
|
|
132
131
|
'POST /:id/cases': 'setEscalationReviewCasesController',
|
|
133
132
|
'POST /:id/call-logs': 'addEscalationReviewCallLogController',
|
|
134
133
|
'POST /:id/draft-suggestions': 'suggestEscalationReviewDraftController',
|
|
@@ -312,7 +311,6 @@ const builtInControllers = {
|
|
|
312
311
|
getReviewTimelineController: escalationReviewController.getReviewTimelineController,
|
|
313
312
|
requestEscalationReviewDraftController: escalationReviewController.requestEscalationReviewDraftController,
|
|
314
313
|
setEscalationReviewCasesController: escalationReviewController.setEscalationReviewCasesController,
|
|
315
|
-
listEscalationReviewCaseCandidatesController: escalationReviewController.listEscalationReviewCaseCandidatesController,
|
|
316
314
|
addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
|
|
317
315
|
suggestEscalationReviewDraftController: escalationReviewController.suggestEscalationReviewDraftController,
|
|
318
316
|
suggestEscalationReviewQuestionsController: escalationReviewController.suggestEscalationReviewQuestionsController,
|
|
@@ -2,10 +2,11 @@ const runtimeConfig = require('../config/runtimeConfig');
|
|
|
2
2
|
const { logger } = require('../utils/logger');
|
|
3
3
|
const { isShadowRun } = require('../utils/shadowScope');
|
|
4
4
|
const { caseIdsOf, getEscalationReview, onCaseWrite, supersededCaseIds } = require('../models/escalationReviewModel');
|
|
5
|
+
const { CLOSING_CASE_OPERATIONS_STATUSES } = require('../helpers/patientTaskRulesHelper');
|
|
5
6
|
const { storeEscalationCase } = require('../fhir/services/escalationService');
|
|
6
7
|
const { caseStatusOf } = require('../fhir/constants/escalationCaseStatus');
|
|
7
8
|
const { effectiveUrgencyOf } = require('./reviewDeadlineService');
|
|
8
|
-
const { updatePatientTask } = require('./patientTaskService');
|
|
9
|
+
const { readPatientCases, updatePatientTask } = require('./patientTaskService');
|
|
9
10
|
|
|
10
11
|
const MIRROR_OPERATOR = 'bot:escalationCase';
|
|
11
12
|
const MIRROR_SOURCE = 'escalation_case';
|
|
@@ -17,36 +18,85 @@ function conditionIdsOf(review) {
|
|
|
17
18
|
return [...new Set([...(review.followUpCases ?? []), ...impressed].filter((id) => typeof id === 'string' && id))];
|
|
18
19
|
}
|
|
19
20
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
const CLOSING_TASK_STATUSES = new Set(['completed', 'cancelled']);
|
|
22
|
+
const TO_REVIEW = caseStatusOf('open');
|
|
23
|
+
|
|
24
|
+
// A closed case, by ops by hand or by a review, is left as it was closed.
|
|
25
|
+
const isClosed = (patientCase) => CLOSING_CASE_OPERATIONS_STATUSES.has(patientCase?.operationsStatus);
|
|
26
|
+
|
|
27
|
+
// A review is of the whole patient: it covers every case the patient raised before it closed that is still open.
|
|
28
|
+
// A closed review takes none once the patient has a newer review, which covers them instead.
|
|
29
|
+
async function withOpenCases(review, cases) {
|
|
30
|
+
try {
|
|
31
|
+
if (review.closedAt && await getEscalationReview().findOne({ patientCode: review.patientCode, createdAt: { $gt: review.createdAt } }, { _id: 1 }).lean()) return review;
|
|
32
|
+
const until = review.closedAt ? new Date(review.closedAt).getTime() : Infinity;
|
|
33
|
+
const covered = caseIdsOf(review);
|
|
34
|
+
const adopted = cases
|
|
35
|
+
.filter((patientCase) => patientCase.isOpen && !isClosed(patientCase))
|
|
36
|
+
.filter((patientCase) => !covered.includes(patientCase.recordId) && Date.parse(patientCase.createdAt) <= until)
|
|
37
|
+
.map((patientCase) => patientCase.recordId);
|
|
38
|
+
if (!adopted.length) return review;
|
|
39
|
+
const recordIds = [...covered, ...adopted];
|
|
40
|
+
// A review that closed while its cases were read keeps none of them; the sync of its close takes them.
|
|
41
|
+
const covering = await getEscalationReview().updateOne({ _id: review._id, closedAt: review.closedAt ?? null }, { $addToSet: { patientCaseRecordIds: { $each: recordIds } } }, { timestamps: false });
|
|
42
|
+
if (!covering?.modifiedCount) return review;
|
|
43
|
+
return { ...review, patientCaseRecordIds: recordIds };
|
|
44
|
+
} catch (error) {
|
|
45
|
+
logger.error('[EscalationCaseTask] The patient\'s open cases were not added to the review; it keeps the ones it covers', { escalationReviewId: String(review._id), error: error.message });
|
|
46
|
+
return review;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Nobody closes a case they did not see: a review closes the cases its panel showed at the close or, closed without
|
|
51
|
+
// that list (by the follow-up, or an older client), the ones raised before the team's last decision.
|
|
52
|
+
function closingIdsOf(review, cases) {
|
|
53
|
+
if (Array.isArray(review.closingCaseIds)) return new Set(review.closingCaseIds);
|
|
54
|
+
const decidedAt = Date.parse((review.decisions ?? []).at(-1)?.createdAt ?? '');
|
|
55
|
+
if (!Number.isFinite(decidedAt)) return new Set();
|
|
56
|
+
return new Set(cases.filter((patientCase) => Date.parse(patientCase.createdAt) <= decidedAt).map((patientCase) => patientCase.recordId));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// The previous shape, one status for a list of cases, reads as each of those cases showing it.
|
|
60
|
+
const mirroredByCase = (mirror) => mirror?.byCase
|
|
61
|
+
?? Object.fromEntries((mirror?.recordIds ?? []).map((recordId) => [recordId, mirror.businessStatus]));
|
|
62
|
+
|
|
63
|
+
// The covered Airtable cases show the stored Task's status in status_operaciones, except the cases a closing review
|
|
64
|
+
// does not close, which go back to "Por revisar"; only a change is written.
|
|
65
|
+
async function mirrorToCases(review, cases) {
|
|
66
|
+
const reviewStatus = caseStatusOf(review.status);
|
|
67
|
+
const closing = CLOSING_TASK_STATUSES.has(reviewStatus.status) ? closingIdsOf(review, cases) : null;
|
|
23
68
|
const superseded = await supersededCaseIds(getEscalationReview(), review);
|
|
24
|
-
const
|
|
25
|
-
const mirrored = review.caseStatusMirror;
|
|
26
|
-
const pending =
|
|
69
|
+
const byId = new Map(cases.map((patientCase) => [patientCase.recordId, patientCase]));
|
|
70
|
+
const mirrored = mirroredByCase(review.caseStatusMirror);
|
|
71
|
+
const pending = caseIdsOf(review)
|
|
72
|
+
.filter((recordId) => !superseded.has(recordId))
|
|
73
|
+
.map((recordId) => ({ recordId, caseStatus: !closing || closing.has(recordId) ? reviewStatus : TO_REVIEW }))
|
|
74
|
+
.filter(({ recordId, caseStatus }) => mirrored[recordId] !== caseStatus.businessStatus)
|
|
75
|
+
.filter(({ recordId }) => !isClosed(byId.get(recordId)))
|
|
76
|
+
// A case closed meanwhile that the review does not close is left closed; an attended one goes back to be reviewed.
|
|
77
|
+
.filter(({ recordId }) => !closing || closing.has(recordId) || byId.get(recordId)?.isOpen !== false);
|
|
27
78
|
if (!pending.length) return;
|
|
28
|
-
const settled =
|
|
29
|
-
for (const recordId of pending) {
|
|
79
|
+
const settled = {};
|
|
80
|
+
for (const { recordId, caseStatus } of pending) {
|
|
30
81
|
try {
|
|
31
82
|
await updatePatientTask({
|
|
32
|
-
code: review.patientCode, kind: 'cases', recordId, changes: { operationsStatus: label }, updatedBy: MIRROR_OPERATOR, source: MIRROR_SOURCE,
|
|
83
|
+
code: review.patientCode, kind: 'cases', recordId, changes: { operationsStatus: caseStatus.label }, updatedBy: MIRROR_OPERATOR, source: MIRROR_SOURCE,
|
|
33
84
|
});
|
|
34
|
-
settled.
|
|
85
|
+
settled[recordId] = caseStatus.businessStatus;
|
|
35
86
|
} catch (error) {
|
|
36
87
|
// A case of another patient or program is never written; it is settled rather than retried on every sync.
|
|
37
88
|
if (error?.statusCode === 404) {
|
|
38
89
|
logger.warn('[EscalationCaseTask] The linked case is not this patient\'s program case; it is left as is', { escalationReviewId: String(review._id), recordId });
|
|
39
|
-
settled.
|
|
90
|
+
settled[recordId] = caseStatus.businessStatus;
|
|
40
91
|
} else {
|
|
41
92
|
logger.error('[EscalationCaseTask] The case status did not reach the Airtable case', { escalationReviewId: String(review._id), recordId, error: error.message });
|
|
42
93
|
}
|
|
43
94
|
}
|
|
44
95
|
}
|
|
45
|
-
if (!settled.length) return;
|
|
46
|
-
const kept = mirrored?.businessStatus === businessStatus ? mirrored.recordIds ?? [] : [];
|
|
96
|
+
if (!Object.keys(settled).length) return;
|
|
47
97
|
await getEscalationReview().updateOne(
|
|
48
98
|
{ _id: review._id },
|
|
49
|
-
{ $set: { caseStatusMirror: {
|
|
99
|
+
{ $set: { caseStatusMirror: { byCase: { ...mirrored, ...settled } } } },
|
|
50
100
|
{ timestamps: false },
|
|
51
101
|
);
|
|
52
102
|
}
|
|
@@ -55,7 +105,14 @@ async function syncCaseTask(id) {
|
|
|
55
105
|
const review = await getEscalationReview().findById(id).lean();
|
|
56
106
|
if (!review) return null;
|
|
57
107
|
const stored = await storeEscalationCase({ review, priority: effectiveUrgencyOf(review)?.urgency ?? null, conditionIds: conditionIdsOf(review) });
|
|
58
|
-
|
|
108
|
+
let cases;
|
|
109
|
+
try {
|
|
110
|
+
cases = await readPatientCases(review.patientCode);
|
|
111
|
+
} catch (error) {
|
|
112
|
+
logger.error('[EscalationCaseTask] The patient\'s cases could not be read; their status waits for the next sync', { escalationReviewId: String(review._id), error: error.message });
|
|
113
|
+
return stored;
|
|
114
|
+
}
|
|
115
|
+
await mirrorToCases(await withOpenCases(review, cases), cases);
|
|
59
116
|
return stored;
|
|
60
117
|
}
|
|
61
118
|
|
|
@@ -24,7 +24,6 @@ const {
|
|
|
24
24
|
} = require('../models/escalationReviewModel');
|
|
25
25
|
const { getPatientAuditLog } = require('../models/patientAuditLogModel');
|
|
26
26
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
27
|
-
const { caseCandidates } = require('../helpers/reviewCaseCandidateHelper');
|
|
28
27
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
29
28
|
const { DrainingError } = require('../core/BatchingManager');
|
|
30
29
|
const { generateEscalationDraft } = require('../clinical/services/escalationDraftService');
|
|
@@ -51,7 +50,7 @@ const { countMessages } = require('./messageService');
|
|
|
51
50
|
const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
|
|
52
51
|
const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
|
|
53
52
|
const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
54
|
-
const { caseTaskLive } = require('./escalationCaseTaskService');
|
|
53
|
+
const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
|
|
55
54
|
|
|
56
55
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
57
56
|
|
|
@@ -69,8 +68,6 @@ const BOOKKEEPING = { timestamps: false };
|
|
|
69
68
|
const PREVIOUS_REVIEW_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;
|
|
70
69
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
71
70
|
const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
|
|
72
|
-
// The cases a review covers can change while it is open and no operation is in flight.
|
|
73
|
-
const CASE_SELECTABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor', 'approved', 'needs_intervention', ...FOLLOWUP_STATUSES];
|
|
74
71
|
const UNDRAFTED_STATUSES = DOCUMENTING_STATUSES.filter((status) => status !== 'draft_ready');
|
|
75
72
|
const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
|
|
76
73
|
const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'monitoring', 'needs_intervention'];
|
|
@@ -116,6 +113,13 @@ const patientCodeOf = (code) => {
|
|
|
116
113
|
|
|
117
114
|
const optionalText = (value) => (value == null ? null : String(value));
|
|
118
115
|
|
|
116
|
+
// The open triage cases the team saw when closing the review; null when the caller did not say.
|
|
117
|
+
function closingCaseIdsOf(value) {
|
|
118
|
+
if (value == null) return null;
|
|
119
|
+
if (!Array.isArray(value) || value.some((recordId) => typeof recordId !== 'string')) throw httpError(400, 'closingCaseIds must be a list of case ids');
|
|
120
|
+
return [...new Set(value.map((recordId) => recordId.trim()).filter(Boolean))];
|
|
121
|
+
}
|
|
122
|
+
|
|
119
123
|
const reviewIdOf = (id) => {
|
|
120
124
|
if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
|
|
121
125
|
return id;
|
|
@@ -799,7 +803,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
799
803
|
const operator = requiredText(updatedBy, 'updatedBy');
|
|
800
804
|
if (!Array.isArray(patientCaseRecordIds)) throw httpError(400, 'patientCaseRecordIds must be an array of case ids');
|
|
801
805
|
const current = await loadReview(reviewId);
|
|
802
|
-
if (!
|
|
806
|
+
if (!DOCUMENTING_STATUSES.includes(current.status)) throw httpError(409, STATUS_CONFLICT);
|
|
803
807
|
|
|
804
808
|
const recordIds = await requestedCaseIds({ patientCode: current.patientCode, patientCaseRecordIds });
|
|
805
809
|
const casesChanged = {
|
|
@@ -817,7 +821,7 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
817
821
|
};
|
|
818
822
|
const isBotDraft = (current.drafts ?? []).at(-1)?.writtenBy === DRAFT_OPERATOR;
|
|
819
823
|
|
|
820
|
-
const review = await updateReview(reviewId,
|
|
824
|
+
const review = await updateReview(reviewId, DOCUMENTING_STATUSES, [{
|
|
821
825
|
$set: {
|
|
822
826
|
patientCaseRecordIds: recordIds,
|
|
823
827
|
status: { $cond: [{ $and: [{ $eq: ['$status', 'draft_ready'] }, casesChanged] }, 'documenting', '$status'] },
|
|
@@ -838,12 +842,6 @@ async function setReviewCases({ id, patientCaseRecordIds, updatedBy, requestId =
|
|
|
838
842
|
return review;
|
|
839
843
|
}
|
|
840
844
|
|
|
841
|
-
async function listReviewCaseCandidates({ id } = {}) {
|
|
842
|
-
const review = await loadReview(reviewIdOf(id));
|
|
843
|
-
const cases = await readPatientCases(review.patientCode);
|
|
844
|
-
return caseCandidates({ review, cases, linkedIds: caseIdsOf(review) });
|
|
845
|
-
}
|
|
846
|
-
|
|
847
845
|
async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
|
|
848
846
|
const reviewId = reviewIdOf(id);
|
|
849
847
|
const operator = requiredText(loggedBy, 'loggedBy');
|
|
@@ -1657,11 +1655,13 @@ async function recordDoctorDecision({
|
|
|
1657
1655
|
doctorReply = null,
|
|
1658
1656
|
reason = null,
|
|
1659
1657
|
draftNumber: seenDraftNumber = null,
|
|
1658
|
+
closingCaseIds = null,
|
|
1660
1659
|
recordedBy,
|
|
1661
1660
|
requestId = null,
|
|
1662
1661
|
} = {}) {
|
|
1663
1662
|
const reviewId = reviewIdOf(id);
|
|
1664
1663
|
const operator = requiredText(recordedBy, 'recordedBy');
|
|
1664
|
+
const closingIds = closingCaseIdsOf(closingCaseIds);
|
|
1665
1665
|
const sources = DECISION_SOURCES.filter((entry) => entry !== 'chat');
|
|
1666
1666
|
const decisions = DOCTOR_DECISIONS.filter((entry) => entry !== 'direct_chat');
|
|
1667
1667
|
if (!sources.includes(source)) throw httpError(400, `source must be one of: ${sources.join(', ')}`);
|
|
@@ -1727,7 +1727,7 @@ async function recordDoctorDecision({
|
|
|
1727
1727
|
},
|
|
1728
1728
|
},
|
|
1729
1729
|
$set: returnReason === 'no_requiere'
|
|
1730
|
-
? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}
|
|
1730
|
+
? { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: `no_requiere${comment ? `: ${comment}` : ''}`, ...(closingIds && { closingCaseIds: closingIds }) }
|
|
1731
1731
|
: { status: statusAfter(decision) },
|
|
1732
1732
|
}, { drafts: { $size: review.drafts.length }, alarms: { $size: (review.alarms ?? []).length }, ...latestUpdateGuard(review) });
|
|
1733
1733
|
await audit(updated, operator, requestId, {
|
|
@@ -1965,10 +1965,11 @@ async function recordEpisode(review, now = new Date()) {
|
|
|
1965
1965
|
}
|
|
1966
1966
|
|
|
1967
1967
|
async function closeEscalationReview({
|
|
1968
|
-
id, closedBy, deliveryConfirmed = false, interruptionNotes = null, requestId = null, expectedAlarmCount = null, expectedUpdatedAt = null,
|
|
1968
|
+
id, closedBy, deliveryConfirmed = false, interruptionNotes = null, closingCaseIds = null, requestId = null, expectedAlarmCount = null, expectedUpdatedAt = null,
|
|
1969
1969
|
} = {}) {
|
|
1970
1970
|
const reviewId = reviewIdOf(id);
|
|
1971
1971
|
const operator = requiredText(closedBy, 'closedBy');
|
|
1972
|
+
const closingIds = closingCaseIdsOf(closingCaseIds);
|
|
1972
1973
|
|
|
1973
1974
|
const current = await loadReview(reviewId);
|
|
1974
1975
|
const queued = current.status === 'indications_queued';
|
|
@@ -1983,7 +1984,7 @@ async function closeEscalationReview({
|
|
|
1983
1984
|
if (sinceStatusChanged < INTERRUPTION_GRACE_MS) throw httpError(409, INTERRUPTION_TOO_SOON);
|
|
1984
1985
|
}
|
|
1985
1986
|
|
|
1986
|
-
const closure = { status: 'closed', closedBy: operator, closedAt: new Date() };
|
|
1987
|
+
const closure = { status: 'closed', closedBy: operator, closedAt: new Date(), ...(closingIds && { closingCaseIds: closingIds }) };
|
|
1987
1988
|
if (queued) Object.assign(closure, { 'patientDelivery.confirmedBy': operator, 'patientDelivery.confirmedAt': new Date() });
|
|
1988
1989
|
if (interrupted) closure.interruptionResolution = { fromStatus: current.status, notes };
|
|
1989
1990
|
|
|
@@ -2037,9 +2038,10 @@ async function reclassifyUrgency({ id, urgencyLevel, reason, reclassifiedBy, req
|
|
|
2037
2038
|
return { review, responseDeadline: responseDeadlineOf(review, responseDeadlinePolicy()) };
|
|
2038
2039
|
}
|
|
2039
2040
|
|
|
2040
|
-
async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
|
|
2041
|
+
async function cancelEscalationReview({ id, cancelledBy, reason = null, closingCaseIds = null, requestId = null } = {}) {
|
|
2041
2042
|
const reviewId = reviewIdOf(id);
|
|
2042
2043
|
const operator = requiredText(cancelledBy, 'cancelledBy');
|
|
2044
|
+
const closingIds = closingCaseIdsOf(closingCaseIds);
|
|
2043
2045
|
if (reason != null && typeof reason !== 'string') throw httpError(400, 'reason must be text');
|
|
2044
2046
|
const notes = String(reason ?? '').trim() || null;
|
|
2045
2047
|
|
|
@@ -2050,7 +2052,7 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
|
|
|
2050
2052
|
let review;
|
|
2051
2053
|
try {
|
|
2052
2054
|
review = await updateReview(reviewId, allowed, {
|
|
2053
|
-
$set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
|
|
2055
|
+
$set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes, ...(closingIds && { closingCaseIds: closingIds }) },
|
|
2054
2056
|
}, notes ? {} : { 'doctorHandoffs.0': { $exists: false }, 'decisions.0': { $exists: false } });
|
|
2055
2057
|
} catch (error) {
|
|
2056
2058
|
if (error?.statusCode !== 409 || notes) throw error;
|
|
@@ -2067,6 +2069,7 @@ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestI
|
|
|
2067
2069
|
async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
|
|
2068
2070
|
const reviewId = reviewIdOf(id);
|
|
2069
2071
|
const operator = requiredText(syncedBy, 'syncedBy');
|
|
2072
|
+
if (caseTaskLive()) await scheduleCaseSync(reviewId);
|
|
2070
2073
|
return syncCase(await loadReview(reviewId), operator, requestId);
|
|
2071
2074
|
}
|
|
2072
2075
|
|
|
@@ -2098,7 +2101,6 @@ module.exports = {
|
|
|
2098
2101
|
sendApprovedIndications,
|
|
2099
2102
|
setAlarmAppliedLevel,
|
|
2100
2103
|
setReviewCases,
|
|
2101
|
-
listReviewCaseCandidates,
|
|
2102
2104
|
suggestDraft,
|
|
2103
2105
|
suggestKeyQuestions,
|
|
2104
2106
|
confirmNoteFacts,
|
|
@@ -93,7 +93,8 @@ const toCase = (row) => ({
|
|
|
93
93
|
note: row.observations ?? null,
|
|
94
94
|
recommendation: row.recomendation_final ?? null,
|
|
95
95
|
resolvedAt: row.resolved_time ?? null,
|
|
96
|
-
|
|
96
|
+
closedAt: row.closed_time ?? null,
|
|
97
|
+
isOpen: isCaseOpen(row.closed_time, row.created || row._createdTime, row.status_operaciones),
|
|
97
98
|
needsAttention: needsCaseAttention(row.resolved_time, row.created || row._createdTime),
|
|
98
99
|
isUrgent: isCaseUrgent(row.type),
|
|
99
100
|
});
|
|
@@ -112,7 +113,7 @@ const TASK_KINDS = {
|
|
|
112
113
|
},
|
|
113
114
|
cases: {
|
|
114
115
|
table: 'patient_cases',
|
|
115
|
-
fields: ['case_id', 'created', 'resolved_time', 'description', 'grade', 'type', 'status', 'status_operaciones', 'seguimiento', 'observations', 'recomendation_final'],
|
|
116
|
+
fields: ['case_id', 'created', 'resolved_time', 'closed_time', 'description', 'grade', 'type', 'status', 'status_operaciones', 'seguimiento', 'observations', 'recomendation_final'],
|
|
116
117
|
scope: programSourceFilter('source'),
|
|
117
118
|
toTask: toCase,
|
|
118
119
|
writable: {
|
package/package.json
CHANGED
|
@@ -1,51 +0,0 @@
|
|
|
1
|
-
// Triage cases a review can cover: the patient's cases raised from a day before the review opened, plus
|
|
2
|
-
// the ones it already covers. A case is only suggested; the team decides which ones the review covers.
|
|
3
|
-
const LOOKBACK_MS = 24 * 60 * 60 * 1000;
|
|
4
|
-
const NEAR_ALARM_MS = 2 * 60 * 60 * 1000;
|
|
5
|
-
const STEM_LENGTH = 5;
|
|
6
|
-
// Stems too common in symptom names and alarm text to tell two symptoms apart.
|
|
7
|
-
const GENERIC_STEMS = new Set(['dolor', 'grado', 'sinto', 'para', 'del', 'con', 'las', 'los', 'una', 'que', 'por', 'sin', 'dific', 'frecu']);
|
|
8
|
-
|
|
9
|
-
const words = (text) => String(text ?? '')
|
|
10
|
-
.toLowerCase()
|
|
11
|
-
.normalize('NFD')
|
|
12
|
-
.replace(/[̀-ͯ]/g, '')
|
|
13
|
-
.split(/[^a-z]+/)
|
|
14
|
-
.filter((word) => word.length >= 3)
|
|
15
|
-
.map((word) => word.slice(0, STEM_LENGTH))
|
|
16
|
-
.filter((stem) => !GENERIC_STEMS.has(stem));
|
|
17
|
-
|
|
18
|
-
const symptomOf = (description) => String(description ?? '').replace(/\s*Grado\s*-\s*\d+\s*$/i, '');
|
|
19
|
-
|
|
20
|
-
// Suggested when an alarm of the review came within two hours of the case and names the same symptom.
|
|
21
|
-
function isSuggested(patientCase, alarms) {
|
|
22
|
-
const caseWords = words(symptomOf(patientCase.description));
|
|
23
|
-
const createdAt = Date.parse(patientCase.createdAt);
|
|
24
|
-
if (!caseWords.length || !Number.isFinite(createdAt)) return false;
|
|
25
|
-
return alarms.some((alarm) => {
|
|
26
|
-
if (!(Math.abs(new Date(alarm.raisedAt).getTime() - createdAt) <= NEAR_ALARM_MS)) return false;
|
|
27
|
-
const alarmWords = new Set(words(`${alarm.symptom ?? ''} ${alarm.suspectedCondition ?? ''}`));
|
|
28
|
-
return caseWords.some((word) => alarmWords.has(word));
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
function caseCandidates({ review, cases, linkedIds }) {
|
|
33
|
-
const since = new Date(review.createdAt).getTime() - LOOKBACK_MS;
|
|
34
|
-
const linked = new Set(linkedIds);
|
|
35
|
-
return cases
|
|
36
|
-
.filter((patientCase) => linked.has(patientCase.recordId) || Date.parse(patientCase.createdAt) >= since)
|
|
37
|
-
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
38
|
-
.map((patientCase) => ({
|
|
39
|
-
recordId: patientCase.recordId,
|
|
40
|
-
number: patientCase.number,
|
|
41
|
-
createdAt: patientCase.createdAt,
|
|
42
|
-
description: patientCase.description,
|
|
43
|
-
grade: patientCase.grade,
|
|
44
|
-
status: patientCase.status,
|
|
45
|
-
operationsStatus: patientCase.operationsStatus,
|
|
46
|
-
isLinked: linked.has(patientCase.recordId),
|
|
47
|
-
isSuggested: !linked.has(patientCase.recordId) && isSuggested(patientCase, review.alarms ?? []),
|
|
48
|
-
}));
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
module.exports = { caseCandidates };
|