@peopl-health/nexus 5.56.0-dev.8570 → 5.56.0-dev.8574
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/services/clinicalAirtableService.js +6 -27
- package/lib/clinical/services/safetyNetPledgeService.js +8 -43
- package/lib/clinical/tools/reportMedicalEscalationTool.js +2 -4
- package/lib/clinical/tools/reportResultsReceivedTool.js +2 -4
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +2 -4
- package/lib/controllers/escalationReviewController.js +7 -2
- package/lib/models/escalationReviewModel.js +4 -1
- package/lib/models/safetyNetPledgeModel.js +1 -4
- package/lib/services/escalationReviewService.js +36 -6
- package/package.json +1 -1
|
@@ -7,7 +7,7 @@ const runtimeConfig = require('../../config/runtimeConfig');
|
|
|
7
7
|
const airtableService = require('../../services/airtableService');
|
|
8
8
|
const { logger } = require('../../utils/logger');
|
|
9
9
|
const { fieldEquals, recordIdIn } = require('../../helpers/airtableFormulaHelper');
|
|
10
|
-
const { CLOSED_REQUEST_STATUSES
|
|
10
|
+
const { CLOSED_REQUEST_STATUSES } = require('../../helpers/patientTaskRulesHelper');
|
|
11
11
|
const { phoneDigits } = require('../../helpers/whatsappHelper');
|
|
12
12
|
const { WriteClaimStore } = require('./writeClaimStore');
|
|
13
13
|
|
|
@@ -96,18 +96,13 @@ async function findIntakePatientRecordId(code) {
|
|
|
96
96
|
}
|
|
97
97
|
|
|
98
98
|
async function writeUnresolvedRequest({ code, trace, question, details, resolutionAttempted = false, forDoctorOffice = false, category = null, urgency = null, replacesClosedTask = false }) {
|
|
99
|
-
|
|
100
|
-
// as a repeat. Free text is left out on purpose: a reworded retry of the same ask is a repeat.
|
|
101
|
-
const fingerprint = createHash('sha1')
|
|
102
|
-
.update([code, category || '', question || '', urgency || '', forDoctorOffice ? 'doctor_office' : ''].join('\n'))
|
|
103
|
-
.digest('hex');
|
|
99
|
+
const fingerprint = createHash('sha1').update(`${code}\n${category || ''}\n${question || ''}`).digest('hex');
|
|
104
100
|
let recordId = null;
|
|
105
|
-
const duplicate = !replacesClosedTask && await recentUnresolvedCache.get(code) === fingerprint;
|
|
106
101
|
const written = await auditedWrite({
|
|
107
102
|
trace,
|
|
108
103
|
code,
|
|
109
104
|
table: 'unresolved_questions',
|
|
110
|
-
skip:
|
|
105
|
+
skip: !replacesClosedTask && await recentUnresolvedCache.get(code) === fingerprint ? 'duplicate' : null,
|
|
111
106
|
write: async () => {
|
|
112
107
|
const patientId = await findMonitoreoPatientRecordId(code);
|
|
113
108
|
const fields = {
|
|
@@ -126,7 +121,7 @@ async function writeUnresolvedRequest({ code, trace, question, details, resoluti
|
|
|
126
121
|
},
|
|
127
122
|
});
|
|
128
123
|
if (written) await recentUnresolvedCache.set(code, fingerprint);
|
|
129
|
-
return { written, recordId
|
|
124
|
+
return { written, recordId };
|
|
130
125
|
}
|
|
131
126
|
|
|
132
127
|
async function recordUnresolvedRequest(request) {
|
|
@@ -139,7 +134,7 @@ function conversationLink(code) {
|
|
|
139
134
|
return base && digits ? `${base}/c/${digits}` : null;
|
|
140
135
|
}
|
|
141
136
|
|
|
142
|
-
function
|
|
137
|
+
function opsAlertDetails(code, { label, summary }) {
|
|
143
138
|
const digits = phoneDigits(code);
|
|
144
139
|
const link = conversationLink(code);
|
|
145
140
|
return `${label}${digits ? ` (+${digits})` : ''}: ${summary}.${link ? ` Revisar: ${link}` : ''}`;
|
|
@@ -165,19 +160,6 @@ async function addToOpenAlert(code, open, question) {
|
|
|
165
160
|
return { handled: !written || matched, written: written && matched };
|
|
166
161
|
}
|
|
167
162
|
|
|
168
|
-
async function isTaskAttended(recordId) {
|
|
169
|
-
if (!RECORD_ID_RX.test(recordId || '')) return null;
|
|
170
|
-
try {
|
|
171
|
-
const [task] = await airtableService.getRecordByFilter(Monitoreo_ID, 'unresolved_questions', recordIdIn([recordId]), null, ['status']);
|
|
172
|
-
if (!task) return true;
|
|
173
|
-
const status = String(task.status || '').trim();
|
|
174
|
-
return status !== '' && !needsRequestAttention(status);
|
|
175
|
-
} catch (error) {
|
|
176
|
-
logger.warn('[clinicalAirtableService] Could not read whether the ops task was attended', { recordId, error: error.message });
|
|
177
|
-
return null;
|
|
178
|
-
}
|
|
179
|
-
}
|
|
180
|
-
|
|
181
163
|
async function recordPausedThreadMessage({ code, text, alert = OPS_ALERTS.paused }) {
|
|
182
164
|
const question = text || 'Envió un archivo sin texto.';
|
|
183
165
|
const open = await recentPausedAlertCache.get(code);
|
|
@@ -192,7 +174,7 @@ async function recordPausedThreadMessage({ code, text, alert = OPS_ALERTS.paused
|
|
|
192
174
|
code,
|
|
193
175
|
trace: null,
|
|
194
176
|
question,
|
|
195
|
-
details:
|
|
177
|
+
details: opsAlertDetails(code, alert),
|
|
196
178
|
category: 'contact_team_member',
|
|
197
179
|
urgency: 'soon',
|
|
198
180
|
replacesClosedTask,
|
|
@@ -576,10 +558,7 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
|
|
|
576
558
|
|
|
577
559
|
module.exports = {
|
|
578
560
|
OPS_ALERTS,
|
|
579
|
-
formatOpsAlert,
|
|
580
|
-
isTaskAttended,
|
|
581
561
|
recordUnresolvedRequest,
|
|
582
|
-
writeUnresolvedRequest,
|
|
583
562
|
recordPausedThreadMessage,
|
|
584
563
|
recordEmergency,
|
|
585
564
|
recordClinicalIntake,
|
|
@@ -10,25 +10,11 @@ const { SafetyNetPledge } = require('../../models/safetyNetPledgeModel');
|
|
|
10
10
|
|
|
11
11
|
const { getMessages } = require('../../services/messageService');
|
|
12
12
|
|
|
13
|
-
const {
|
|
13
|
+
const { recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
14
14
|
|
|
15
15
|
const SWEEP_LIMIT = 200;
|
|
16
16
|
const BREACH_CATEGORY = 'contact_team_member';
|
|
17
17
|
const BREACH_QUESTION = 'El paciente sigue esperando el contacto que se le prometió';
|
|
18
|
-
const ONBOARDING_BREACH_QUESTION = 'El contacto sigue esperando la llamada de bienvenida';
|
|
19
|
-
|
|
20
|
-
const BREACHES = {
|
|
21
|
-
safety_net: {
|
|
22
|
-
question: BREACH_QUESTION,
|
|
23
|
-
label: 'Contacto prometido sin cumplir',
|
|
24
|
-
summary: (waitedMinutes) => `pidió que lo contactaran y lleva ${waitedMinutes} minutos sin respuesta`,
|
|
25
|
-
},
|
|
26
|
-
onboarding: {
|
|
27
|
-
question: ONBOARDING_BREACH_QUESTION,
|
|
28
|
-
label: 'Llamada de bienvenida sin hacer',
|
|
29
|
-
summary: (waitedMinutes) => `pidió la llamada de bienvenida y lleva ${waitedMinutes} minutos sin que nadie lo contacte`,
|
|
30
|
-
},
|
|
31
|
-
};
|
|
32
18
|
|
|
33
19
|
const DELIVERY_GRACE_MS = 10 * 60 * 1000;
|
|
34
20
|
const HOUR_MS = 60 * 60 * 1000;
|
|
@@ -54,28 +40,21 @@ function pledgeDueAt(pledgedAt) {
|
|
|
54
40
|
return { dueAt: addContactHours(pledgedAt, DEFAULT_PLEDGE_MS / HOUR_MS, CONTACT_WINDOW) };
|
|
55
41
|
}
|
|
56
42
|
|
|
57
|
-
async function openPledge({ code
|
|
43
|
+
async function openPledge({ code }) {
|
|
58
44
|
const pledgedAt = new Date();
|
|
59
45
|
const { dueAt } = pledgeDueAt(pledgedAt);
|
|
60
|
-
const pledge = await SafetyNetPledge.create({
|
|
61
|
-
|
|
62
|
-
pledgedAt,
|
|
63
|
-
dueAt,
|
|
64
|
-
...(kind === 'safety_net' ? {} : { kind }),
|
|
65
|
-
...(taskRecordId ? { taskRecordId } : {}),
|
|
66
|
-
});
|
|
67
|
-
logger.info('[SafetyNetPledge] Contact pledged', { code, kind, dueAt });
|
|
46
|
+
const pledge = await SafetyNetPledge.create({ code, pledgedAt, dueAt });
|
|
47
|
+
logger.info('[SafetyNetPledge] Contact pledged', { code, dueAt });
|
|
68
48
|
return { pledgeId: pledge._id, dueAt };
|
|
69
49
|
}
|
|
70
50
|
|
|
71
51
|
async function reportBreach(pledge) {
|
|
72
52
|
const waitedMinutes = Math.round((Date.now() - new Date(pledge.pledgedAt).getTime()) / 60000);
|
|
73
|
-
const breach = BREACHES[pledge.kind] || BREACHES.safety_net;
|
|
74
53
|
return recordUnresolvedRequest({
|
|
75
54
|
code: pledge.code,
|
|
76
55
|
trace: null,
|
|
77
|
-
question:
|
|
78
|
-
details:
|
|
56
|
+
question: BREACH_QUESTION,
|
|
57
|
+
details: `El paciente ${pledge.code} pidió que lo contactaran y lleva ${waitedMinutes} minutos sin respuesta. Revisar la conversación ahora.`,
|
|
79
58
|
category: BREACH_CATEGORY,
|
|
80
59
|
urgency: 'urgent'
|
|
81
60
|
});
|
|
@@ -104,7 +83,7 @@ async function sweepSafetyNetPledges() {
|
|
|
104
83
|
state: { $in: ['pending', 'reporting'] },
|
|
105
84
|
dueAt: { $lte: new Date() },
|
|
106
85
|
})
|
|
107
|
-
.select({ _id: 1, code: 1,
|
|
86
|
+
.select({ _id: 1, code: 1, pledgedAt: 1 })
|
|
108
87
|
.limit(SWEEP_LIMIT)
|
|
109
88
|
.lean();
|
|
110
89
|
|
|
@@ -124,19 +103,6 @@ async function sweepSafetyNetPledges() {
|
|
|
124
103
|
continue;
|
|
125
104
|
}
|
|
126
105
|
|
|
127
|
-
// Last, so the least time passes between reading the task and alarming about it.
|
|
128
|
-
if (pledge.kind === 'onboarding' && pledge.taskRecordId) {
|
|
129
|
-
const attended = await isTaskAttended(pledge.taskRecordId);
|
|
130
|
-
if (attended) {
|
|
131
|
-
await settle(pledge._id, 'reporting', 'met');
|
|
132
|
-
continue;
|
|
133
|
-
}
|
|
134
|
-
if (attended === null) {
|
|
135
|
-
await returnToPending(pledge._id);
|
|
136
|
-
continue;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
106
|
if (!await reportBreach(pledge)) {
|
|
141
107
|
await returnToPending(pledge._id);
|
|
142
108
|
logger.error('[SafetyNetPledge] Breach was not recorded, pledge returns to pending for the next sweep', { code: pledge.code });
|
|
@@ -169,6 +135,5 @@ module.exports = {
|
|
|
169
135
|
openPledge,
|
|
170
136
|
pledgeDueAt,
|
|
171
137
|
sweepSafetyNetPledges,
|
|
172
|
-
BREACH_QUESTION
|
|
173
|
-
ONBOARDING_BREACH_QUESTION
|
|
138
|
+
BREACH_QUESTION
|
|
174
139
|
};
|
|
@@ -3,7 +3,7 @@ const { auditReasoningSchema } = require('../helpers/auditReasoningHelper');
|
|
|
3
3
|
const { dispatcherService } = require('../services/dispatcherService');
|
|
4
4
|
const { armEscalationNet } = require('../services/contingencyDispatchService');
|
|
5
5
|
const { evidenceQuoteAnchoring } = require('../helpers/evidenceAnchorHelper');
|
|
6
|
-
const { recordEmergency,
|
|
6
|
+
const { recordEmergency, recordUnresolvedRequest } = require('../services/clinicalAirtableService');
|
|
7
7
|
const { objectArg, safeParse, isPlainObject } = require('../../utils/jsonUtils');
|
|
8
8
|
const { logger } = require('../../utils/logger');
|
|
9
9
|
|
|
@@ -219,8 +219,7 @@ async function handler(args, context = {}) {
|
|
|
219
219
|
|
|
220
220
|
if (runtime.patientCode) {
|
|
221
221
|
if (urgencyLevel === 'routine') {
|
|
222
|
-
|
|
223
|
-
const { written, duplicate } = await writeUnresolvedRequest({
|
|
222
|
+
queued = await recordUnresolvedRequest({
|
|
224
223
|
code: runtime.patientCode,
|
|
225
224
|
trace,
|
|
226
225
|
question: details.symptom || '',
|
|
@@ -228,7 +227,6 @@ async function handler(args, context = {}) {
|
|
|
228
227
|
category: 'medical_routine',
|
|
229
228
|
urgency: 'routine',
|
|
230
229
|
});
|
|
231
|
-
queued = written || duplicate;
|
|
232
230
|
} else {
|
|
233
231
|
queued = await recordEmergency({
|
|
234
232
|
code: runtime.patientCode,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { DEGRADED_NUMERIC_REASON, DEGRADED_SUPPRESSED_REASON, VERBATIM_SOURCES, patientVerbatimHasNumericValues, resolveVerbatimSource, slugify, stampProvenance } = require('../helpers/resultsHelper');
|
|
2
|
-
const {
|
|
2
|
+
const { recordUnresolvedRequest } = require('../services/clinicalAirtableService');
|
|
3
3
|
const { storeResultObservations } = require('../../fhir');
|
|
4
4
|
const { logger } = require('../../utils/logger');
|
|
5
5
|
|
|
@@ -120,8 +120,7 @@ async function handler(args = {}, context = {}) {
|
|
|
120
120
|
logger.warn('[reportResultsReceived] no trace on runtime context; results-received signal not recorded', { turnId: runtime.turnId });
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
-
|
|
124
|
-
const { written, duplicate } = await writeUnresolvedRequest({
|
|
123
|
+
const queued = await recordUnresolvedRequest({
|
|
125
124
|
code: runtime.patientCode,
|
|
126
125
|
trace,
|
|
127
126
|
question: ['Resultados recibidos:', resultType, studyName].filter(Boolean).join(' '),
|
|
@@ -129,7 +128,6 @@ async function handler(args = {}, context = {}) {
|
|
|
129
128
|
category: 'results_review',
|
|
130
129
|
urgency: 'soon',
|
|
131
130
|
});
|
|
132
|
-
const queued = written || duplicate;
|
|
133
131
|
|
|
134
132
|
const data = { result_id: resultId, result_slug: resultSlug };
|
|
135
133
|
if (resultType !== rawType) data.result_type = resultType;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
const { auditReasoningSchema } = require('../helpers/auditReasoningHelper');
|
|
2
|
-
const {
|
|
2
|
+
const { recordUnresolvedRequest } = require('../services/clinicalAirtableService');
|
|
3
3
|
const { logger } = require('../../utils/logger');
|
|
4
4
|
|
|
5
5
|
const definition = {
|
|
@@ -111,8 +111,7 @@ async function handler(args = {}, context = {}) {
|
|
|
111
111
|
const patientCode = context?.toolRuntimeContext?.patientCode;
|
|
112
112
|
let isQueued = false;
|
|
113
113
|
if (patientCode) {
|
|
114
|
-
|
|
115
|
-
const { written, duplicate } = await writeUnresolvedRequest({
|
|
114
|
+
isQueued = await recordUnresolvedRequest({
|
|
116
115
|
code: patientCode,
|
|
117
116
|
trace,
|
|
118
117
|
question,
|
|
@@ -122,7 +121,6 @@ async function handler(args = {}, context = {}) {
|
|
|
122
121
|
category,
|
|
123
122
|
urgency,
|
|
124
123
|
});
|
|
125
|
-
isQueued = written || duplicate;
|
|
126
124
|
}
|
|
127
125
|
|
|
128
126
|
if (isQueued) {
|
|
@@ -167,8 +167,13 @@ const closeEscalationReviewController = async (req, res) => {
|
|
|
167
167
|
const cancelEscalationReviewController = async (req, res) => {
|
|
168
168
|
try {
|
|
169
169
|
const { triggeredBy, reason = null } = req.body || {};
|
|
170
|
-
const review = await cancelEscalationReview({
|
|
171
|
-
|
|
170
|
+
const { review, caseMirror, caseMirrors } = await cancelEscalationReview({
|
|
171
|
+
id: req.params.id,
|
|
172
|
+
cancelledBy: triggeredBy,
|
|
173
|
+
reason,
|
|
174
|
+
requestId: req.requestId,
|
|
175
|
+
});
|
|
176
|
+
res.status(200).json({ success: true, review, caseMirror, caseMirrors });
|
|
172
177
|
} catch (error) {
|
|
173
178
|
respondWithError(res, error, 'cancelling escalation review', { reviewId: req.params?.id });
|
|
174
179
|
}
|
|
@@ -7,7 +7,8 @@ const { logger } = require('../utils/logger');
|
|
|
7
7
|
const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
|
|
8
8
|
const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
|
|
9
9
|
const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
|
|
10
|
-
const
|
|
10
|
+
const CANCELLABLE_AFTER_HANDOFF_STATUSES = ['awaiting_doctor', 'approved', 'returned'];
|
|
11
|
+
const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready', ...CANCELLABLE_AFTER_HANDOFF_STATUSES];
|
|
11
12
|
const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
|
|
12
13
|
const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
|
|
13
14
|
|
|
@@ -99,6 +100,7 @@ const escalationReviewSchema = new mongoose.Schema({
|
|
|
99
100
|
interruptionResolution: { type: interruptionResolutionSchema, default: null },
|
|
100
101
|
closedBy: { type: String, default: null },
|
|
101
102
|
closedAt: { type: Date, default: null },
|
|
103
|
+
cancellationReason: { type: String, default: null },
|
|
102
104
|
}, { timestamps: true });
|
|
103
105
|
|
|
104
106
|
escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
|
|
@@ -113,6 +115,7 @@ const getEscalationReview = () => {
|
|
|
113
115
|
|
|
114
116
|
module.exports = {
|
|
115
117
|
CALL_OUTCOMES,
|
|
118
|
+
CANCELLABLE_AFTER_HANDOFF_STATUSES,
|
|
116
119
|
CANCELLABLE_STATUSES,
|
|
117
120
|
DECISION_SOURCES,
|
|
118
121
|
DOCTOR_DECISIONS,
|
|
@@ -1,12 +1,9 @@
|
|
|
1
1
|
const mongoose = require('mongoose');
|
|
2
2
|
|
|
3
3
|
const PLEDGE_STATES = ['pending', 'reporting', 'met', 'breached'];
|
|
4
|
-
const PLEDGE_KINDS = ['safety_net', 'onboarding'];
|
|
5
4
|
|
|
6
5
|
const safetyNetPledgeSchema = new mongoose.Schema({
|
|
7
6
|
code: { type: String, required: true },
|
|
8
|
-
kind: { type: String, enum: PLEDGE_KINDS, default: 'safety_net' },
|
|
9
|
-
taskRecordId: { type: String, default: null },
|
|
10
7
|
pledgedAt: { type: Date, required: true },
|
|
11
8
|
dueAt: { type: Date, required: true },
|
|
12
9
|
state: { type: String, enum: PLEDGE_STATES, default: 'pending' },
|
|
@@ -19,4 +16,4 @@ safetyNetPledgeSchema.index({ state: 1, dueAt: 1 }, { name: 'safety_net_pledge_d
|
|
|
19
16
|
|
|
20
17
|
const SafetyNetPledge = mongoose.model('SafetyNetPledge', safetyNetPledgeSchema);
|
|
21
18
|
|
|
22
|
-
module.exports = { SafetyNetPledge, PLEDGE_STATES
|
|
19
|
+
module.exports = { SafetyNetPledge, PLEDGE_STATES };
|
|
@@ -6,6 +6,7 @@ const { logger } = require('../utils/logger');
|
|
|
6
6
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
7
7
|
const {
|
|
8
8
|
CALL_OUTCOMES,
|
|
9
|
+
CANCELLABLE_AFTER_HANDOFF_STATUSES,
|
|
9
10
|
CANCELLABLE_STATUSES,
|
|
10
11
|
DECISION_SOURCES,
|
|
11
12
|
DOCTOR_DECISIONS,
|
|
@@ -32,6 +33,7 @@ const CLOSABLE_STATUSES = ['indications_queued', 'indications_sent', 'needs_inte
|
|
|
32
33
|
const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
|
|
33
34
|
const MAX_TEMPLATE_TEXT_LENGTH = 800;
|
|
34
35
|
const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
|
|
36
|
+
const CANCEL_NEEDS_REASON = 'The doctor is already waiting on this review; cancelling it requires a reason';
|
|
35
37
|
const INTERRUPTION_CONFLICT = 'The escalation review was interrupted; closing it requires interruptionNotes stating what was verified';
|
|
36
38
|
// A send still in flight also sits in handing_off or sending, and the patient-send path reaches
|
|
37
39
|
// Airtable, whose shared client waits up to 300s. Adjudicating before then can close the review
|
|
@@ -174,7 +176,6 @@ async function syncCase(review, operator, requestId) {
|
|
|
174
176
|
const pending = review.pendingCaseMirrors || [];
|
|
175
177
|
if (!pending.length) return { review, caseMirror: 'updated', caseMirrors: [] };
|
|
176
178
|
|
|
177
|
-
const superseded = await supersededCaseIds(EscalationReview, review);
|
|
178
179
|
const covered = new Set(recordIds);
|
|
179
180
|
const byRecord = new Map();
|
|
180
181
|
const abandoned = [];
|
|
@@ -195,6 +196,19 @@ async function syncCase(review, operator, requestId) {
|
|
|
195
196
|
byRecord.set(recordId, entries);
|
|
196
197
|
}
|
|
197
198
|
|
|
199
|
+
let superseded;
|
|
200
|
+
try {
|
|
201
|
+
superseded = await supersededCaseIds(EscalationReview, review);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
logger.error('[EscalationReview] Could not check whether a newer review supersedes these cases', {
|
|
204
|
+
escalationReviewId: String(review._id),
|
|
205
|
+
error: redactedError(error),
|
|
206
|
+
stack: redactedStack(error),
|
|
207
|
+
});
|
|
208
|
+
const outcomes = [...byRecord.keys()].map((recordId) => ({ recordId, status: 'failed' }));
|
|
209
|
+
return { review, caseMirror: summarise(outcomes), caseMirrors: outcomes };
|
|
210
|
+
}
|
|
211
|
+
|
|
198
212
|
const applied = await Promise.all([...byRecord].map(async ([recordId, entries]) => {
|
|
199
213
|
const ids = entries.map((entry) => entry._id);
|
|
200
214
|
if (superseded.has(recordId)) {
|
|
@@ -703,11 +717,27 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
|
|
|
703
717
|
async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
|
|
704
718
|
const reviewId = reviewIdOf(id);
|
|
705
719
|
const operator = requiredText(cancelledBy, 'cancelledBy');
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
720
|
+
if (reason != null && typeof reason !== 'string') throw httpError(400, 'reason must be text');
|
|
721
|
+
const notes = String(reason ?? '').trim() || null;
|
|
722
|
+
|
|
723
|
+
const allowed = notes
|
|
724
|
+
? CANCELLABLE_STATUSES
|
|
725
|
+
: CANCELLABLE_STATUSES.filter((status) => !CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(status));
|
|
726
|
+
|
|
727
|
+
let review;
|
|
728
|
+
try {
|
|
729
|
+
review = await updateReview(reviewId, allowed, {
|
|
730
|
+
$set: { status: 'cancelled', closedBy: operator, closedAt: new Date(), cancellationReason: notes },
|
|
731
|
+
});
|
|
732
|
+
} catch (error) {
|
|
733
|
+
if (error?.statusCode !== 409 || notes) throw error;
|
|
734
|
+
const current = await loadReview(reviewId);
|
|
735
|
+
if (CANCELLABLE_AFTER_HANDOFF_STATUSES.includes(current.status)) throw httpError(409, CANCEL_NEEDS_REASON);
|
|
736
|
+
throw error;
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
await audit(review, operator, requestId, { action: 'cancelled', reason: notes });
|
|
740
|
+
return syncCase(review, operator, requestId);
|
|
711
741
|
}
|
|
712
742
|
|
|
713
743
|
async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
|