@peopl-health/nexus 5.56.0-dev.8580 → 5.56.0-dev.8582
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 -25
- package/lib/clinical/services/safetyNetPledgeService.js +8 -42
- package/lib/clinical/tools/reportMedicalEscalationTool.js +2 -3
- package/lib/clinical/tools/reportResultsReceivedTool.js +2 -3
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +2 -3
- 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,16 +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
|
-
const fingerprint = createHash('sha1')
|
|
100
|
-
.update(JSON.stringify([code, category || null, question || null, urgency || null, Boolean(forDoctorOffice)]))
|
|
101
|
-
.digest('hex');
|
|
99
|
+
const fingerprint = createHash('sha1').update(`${code}\n${category || ''}\n${question || ''}`).digest('hex');
|
|
102
100
|
let recordId = null;
|
|
103
|
-
const duplicate = !replacesClosedTask && await recentUnresolvedCache.get(code) === fingerprint;
|
|
104
101
|
const written = await auditedWrite({
|
|
105
102
|
trace,
|
|
106
103
|
code,
|
|
107
104
|
table: 'unresolved_questions',
|
|
108
|
-
skip:
|
|
105
|
+
skip: !replacesClosedTask && await recentUnresolvedCache.get(code) === fingerprint ? 'duplicate' : null,
|
|
109
106
|
write: async () => {
|
|
110
107
|
const patientId = await findMonitoreoPatientRecordId(code);
|
|
111
108
|
const fields = {
|
|
@@ -124,7 +121,7 @@ async function writeUnresolvedRequest({ code, trace, question, details, resoluti
|
|
|
124
121
|
},
|
|
125
122
|
});
|
|
126
123
|
if (written) await recentUnresolvedCache.set(code, fingerprint);
|
|
127
|
-
return { written, recordId
|
|
124
|
+
return { written, recordId };
|
|
128
125
|
}
|
|
129
126
|
|
|
130
127
|
async function recordUnresolvedRequest(request) {
|
|
@@ -137,7 +134,7 @@ function conversationLink(code) {
|
|
|
137
134
|
return base && digits ? `${base}/c/${digits}` : null;
|
|
138
135
|
}
|
|
139
136
|
|
|
140
|
-
function
|
|
137
|
+
function opsAlertDetails(code, { label, summary }) {
|
|
141
138
|
const digits = phoneDigits(code);
|
|
142
139
|
const link = conversationLink(code);
|
|
143
140
|
return `${label}${digits ? ` (+${digits})` : ''}: ${summary}.${link ? ` Revisar: ${link}` : ''}`;
|
|
@@ -163,19 +160,6 @@ async function addToOpenAlert(code, open, question) {
|
|
|
163
160
|
return { handled: !written || matched, written: written && matched };
|
|
164
161
|
}
|
|
165
162
|
|
|
166
|
-
async function isTaskAttended(recordId) {
|
|
167
|
-
if (!RECORD_ID_RX.test(recordId || '')) return null;
|
|
168
|
-
try {
|
|
169
|
-
const [task] = await airtableService.getRecordByFilter(Monitoreo_ID, 'unresolved_questions', recordIdIn([recordId]), null, ['status']);
|
|
170
|
-
if (!task) return true;
|
|
171
|
-
const status = String(task.status || '').trim();
|
|
172
|
-
return status !== '' && !needsRequestAttention(status);
|
|
173
|
-
} catch (error) {
|
|
174
|
-
logger.warn('[clinicalAirtableService] Could not read whether the ops task was attended', { recordId, error: error.message });
|
|
175
|
-
return null;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
|
|
179
163
|
async function recordPausedThreadMessage({ code, text, alert = OPS_ALERTS.paused }) {
|
|
180
164
|
const question = text || 'Envió un archivo sin texto.';
|
|
181
165
|
const open = await recentPausedAlertCache.get(code);
|
|
@@ -190,7 +174,7 @@ async function recordPausedThreadMessage({ code, text, alert = OPS_ALERTS.paused
|
|
|
190
174
|
code,
|
|
191
175
|
trace: null,
|
|
192
176
|
question,
|
|
193
|
-
details:
|
|
177
|
+
details: opsAlertDetails(code, alert),
|
|
194
178
|
category: 'contact_team_member',
|
|
195
179
|
urgency: 'soon',
|
|
196
180
|
replacesClosedTask,
|
|
@@ -574,10 +558,7 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
|
|
|
574
558
|
|
|
575
559
|
module.exports = {
|
|
576
560
|
OPS_ALERTS,
|
|
577
|
-
formatOpsAlert,
|
|
578
|
-
isTaskAttended,
|
|
579
561
|
recordUnresolvedRequest,
|
|
580
|
-
writeUnresolvedRequest,
|
|
581
562
|
recordPausedThreadMessage,
|
|
582
563
|
recordEmergency,
|
|
583
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,18 +103,6 @@ async function sweepSafetyNetPledges() {
|
|
|
124
103
|
continue;
|
|
125
104
|
}
|
|
126
105
|
|
|
127
|
-
if (pledge.kind === 'onboarding' && pledge.taskRecordId) {
|
|
128
|
-
const attended = await isTaskAttended(pledge.taskRecordId);
|
|
129
|
-
if (attended) {
|
|
130
|
-
await settle(pledge._id, 'reporting', 'met');
|
|
131
|
-
continue;
|
|
132
|
-
}
|
|
133
|
-
if (attended === null) {
|
|
134
|
-
await returnToPending(pledge._id);
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
106
|
if (!await reportBreach(pledge)) {
|
|
140
107
|
await returnToPending(pledge._id);
|
|
141
108
|
logger.error('[SafetyNetPledge] Breach was not recorded, pledge returns to pending for the next sweep', { code: pledge.code });
|
|
@@ -168,6 +135,5 @@ module.exports = {
|
|
|
168
135
|
openPledge,
|
|
169
136
|
pledgeDueAt,
|
|
170
137
|
sweepSafetyNetPledges,
|
|
171
|
-
BREACH_QUESTION
|
|
172
|
-
ONBOARDING_BREACH_QUESTION
|
|
138
|
+
BREACH_QUESTION
|
|
173
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,7 +219,7 @@ async function handler(args, context = {}) {
|
|
|
219
219
|
|
|
220
220
|
if (runtime.patientCode) {
|
|
221
221
|
if (urgencyLevel === 'routine') {
|
|
222
|
-
|
|
222
|
+
queued = await recordUnresolvedRequest({
|
|
223
223
|
code: runtime.patientCode,
|
|
224
224
|
trace,
|
|
225
225
|
question: details.symptom || '',
|
|
@@ -227,7 +227,6 @@ async function handler(args, context = {}) {
|
|
|
227
227
|
category: 'medical_routine',
|
|
228
228
|
urgency: 'routine',
|
|
229
229
|
});
|
|
230
|
-
queued = written || duplicate;
|
|
231
230
|
} else {
|
|
232
231
|
queued = await recordEmergency({
|
|
233
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,7 +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
|
-
const
|
|
123
|
+
const queued = await recordUnresolvedRequest({
|
|
124
124
|
code: runtime.patientCode,
|
|
125
125
|
trace,
|
|
126
126
|
question: ['Resultados recibidos:', resultType, studyName].filter(Boolean).join(' '),
|
|
@@ -128,7 +128,6 @@ async function handler(args = {}, context = {}) {
|
|
|
128
128
|
category: 'results_review',
|
|
129
129
|
urgency: 'soon',
|
|
130
130
|
});
|
|
131
|
-
const queued = written || duplicate;
|
|
132
131
|
|
|
133
132
|
const data = { result_id: resultId, result_slug: resultSlug };
|
|
134
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,7 +111,7 @@ async function handler(args = {}, context = {}) {
|
|
|
111
111
|
const patientCode = context?.toolRuntimeContext?.patientCode;
|
|
112
112
|
let isQueued = false;
|
|
113
113
|
if (patientCode) {
|
|
114
|
-
|
|
114
|
+
isQueued = await recordUnresolvedRequest({
|
|
115
115
|
code: patientCode,
|
|
116
116
|
trace,
|
|
117
117
|
question,
|
|
@@ -121,7 +121,6 @@ async function handler(args = {}, context = {}) {
|
|
|
121
121
|
category,
|
|
122
122
|
urgency,
|
|
123
123
|
});
|
|
124
|
-
isQueued = written || duplicate;
|
|
125
124
|
}
|
|
126
125
|
|
|
127
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 } = {}) {
|