@peopl-health/nexus 5.46.0 → 5.47.0-dev.7300

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.
@@ -0,0 +1,142 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+
4
+ const {
5
+ addCallLog,
6
+ addDraft,
7
+ closeEscalationReview,
8
+ handOffToDoctor,
9
+ listEscalationReviews,
10
+ openEscalationReview,
11
+ recordDoctorDecision,
12
+ sendApprovedIndications,
13
+ syncEscalationReviewCase,
14
+ } = require('../services/escalationReviewService');
15
+
16
+ const respondWithError = (res, error, action, context) => {
17
+ logger.error(`Error ${action}:`, {
18
+ error: redactDirectIdentifiers(String(error.message || '')),
19
+ stack: redactDirectIdentifiers(String(error.stack || '')),
20
+ ...context,
21
+ });
22
+ res.status(error.statusCode || 500).json({ success: false, error: error.message });
23
+ };
24
+
25
+ const openEscalationReviewController = async (req, res) => {
26
+ try {
27
+ const { code, patientCaseRecordId = null, triggeredBy } = req.body || {};
28
+ const { review, created } = await openEscalationReview({ code, patientCaseRecordId, openedBy: triggeredBy, requestId: req.requestId });
29
+ res.status(created ? 201 : 200).json({ success: true, review });
30
+ } catch (error) {
31
+ respondWithError(res, error, 'opening escalation review', { code: redactDirectIdentifiers(String(req.body?.code || '')) });
32
+ }
33
+ };
34
+
35
+ const listEscalationReviewsController = async (req, res) => {
36
+ try {
37
+ const reviews = await listEscalationReviews({ code: req.params.code });
38
+ res.status(200).json({ success: true, reviews });
39
+ } catch (error) {
40
+ respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
41
+ }
42
+ };
43
+
44
+ const addEscalationReviewCallLogController = async (req, res) => {
45
+ try {
46
+ const { outcome, notes, calledAt, triggeredBy } = req.body || {};
47
+ const review = await addCallLog({ id: req.params.id, outcome, notes, calledAt, loggedBy: triggeredBy, requestId: req.requestId });
48
+ res.status(201).json({ success: true, review });
49
+ } catch (error) {
50
+ respondWithError(res, error, 'logging escalation review call', { reviewId: req.params?.id });
51
+ }
52
+ };
53
+
54
+ const addEscalationReviewDraftController = async (req, res) => {
55
+ try {
56
+ const { doctorText, patientMessage, triggeredBy } = req.body || {};
57
+ const review = await addDraft({ id: req.params.id, doctorText, patientMessage, writtenBy: triggeredBy, requestId: req.requestId });
58
+ res.status(201).json({ success: true, review });
59
+ } catch (error) {
60
+ respondWithError(res, error, 'saving escalation review draft', { reviewId: req.params?.id });
61
+ }
62
+ };
63
+
64
+ const handOffEscalationReviewController = async (req, res) => {
65
+ try {
66
+ const { mode, physicianEmail = null, triggeredBy } = req.body || {};
67
+ const { review, caseMirror } = await handOffToDoctor({ id: req.params.id, mode, physicianEmail, sentBy: triggeredBy, requestId: req.requestId });
68
+ res.status(201).json({ success: true, review, caseMirror });
69
+ } catch (error) {
70
+ respondWithError(res, error, 'handing escalation review to doctor', { reviewId: req.params?.id });
71
+ }
72
+ };
73
+
74
+ const recordEscalationReviewDecisionController = async (req, res) => {
75
+ try {
76
+ const {
77
+ source,
78
+ decision,
79
+ finalText = null,
80
+ comment = null,
81
+ doctorName = null,
82
+ doctorReply = null,
83
+ triggeredBy,
84
+ } = req.body || {};
85
+ const review = await recordDoctorDecision({
86
+ id: req.params.id,
87
+ source,
88
+ decision,
89
+ finalText,
90
+ comment,
91
+ doctorName,
92
+ doctorReply,
93
+ recordedBy: triggeredBy,
94
+ requestId: req.requestId,
95
+ });
96
+ res.status(201).json({ success: true, review });
97
+ } catch (error) {
98
+ respondWithError(res, error, 'recording escalation review decision', { reviewId: req.params?.id });
99
+ }
100
+ };
101
+
102
+ const sendEscalationReviewIndicationsController = async (req, res) => {
103
+ try {
104
+ const { outsideWindowRoute = null, triggeredBy } = req.body || {};
105
+ const { review, caseMirror } = await sendApprovedIndications({ id: req.params.id, outsideWindowRoute, sentBy: triggeredBy, requestId: req.requestId });
106
+ res.status(201).json({ success: true, review, caseMirror });
107
+ } catch (error) {
108
+ respondWithError(res, error, 'sending escalation review indications', { reviewId: req.params?.id });
109
+ }
110
+ };
111
+
112
+ const closeEscalationReviewController = async (req, res) => {
113
+ try {
114
+ const { triggeredBy } = req.body || {};
115
+ const { review, caseMirror } = await closeEscalationReview({ id: req.params.id, closedBy: triggeredBy, requestId: req.requestId });
116
+ res.status(200).json({ success: true, review, caseMirror });
117
+ } catch (error) {
118
+ respondWithError(res, error, 'closing escalation review', { reviewId: req.params?.id });
119
+ }
120
+ };
121
+
122
+ const syncEscalationReviewCaseController = async (req, res) => {
123
+ try {
124
+ const { triggeredBy } = req.body || {};
125
+ const { review, caseMirror } = await syncEscalationReviewCase({ id: req.params.id, syncedBy: triggeredBy, requestId: req.requestId });
126
+ res.status(200).json({ success: true, review, caseMirror });
127
+ } catch (error) {
128
+ respondWithError(res, error, 'syncing escalation review case', { reviewId: req.params?.id });
129
+ }
130
+ };
131
+
132
+ module.exports = {
133
+ addEscalationReviewCallLogController,
134
+ addEscalationReviewDraftController,
135
+ closeEscalationReviewController,
136
+ handOffEscalationReviewController,
137
+ listEscalationReviewsController,
138
+ openEscalationReviewController,
139
+ recordEscalationReviewDecisionController,
140
+ sendEscalationReviewIndicationsController,
141
+ syncEscalationReviewCaseController,
142
+ };
@@ -0,0 +1,106 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const { getDb, getModelDatabase } = require('../config/mongoConfig');
4
+
5
+ const { logger } = require('../utils/logger');
6
+
7
+ const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
+ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
9
+ const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
10
+ const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
11
+
12
+ const callLogSchema = new mongoose.Schema({
13
+ outcome: { type: String, enum: CALL_OUTCOMES, required: true },
14
+ notes: { type: String, default: null },
15
+ calledAt: { type: Date, required: true },
16
+ loggedBy: { type: String, required: true },
17
+ }, { timestamps: { createdAt: true, updatedAt: false } });
18
+
19
+ const draftSchema = new mongoose.Schema({
20
+ doctorText: { type: String, required: true },
21
+ patientMessage: { type: String, required: true },
22
+ writtenBy: { type: String, required: true },
23
+ }, { timestamps: { createdAt: true, updatedAt: false } });
24
+
25
+ const doctorHandoffSchema = new mongoose.Schema({
26
+ mode: { type: String, enum: HANDOFF_MODES, required: true },
27
+ draftNumber: { type: Number, required: true },
28
+ physicianEmail: { type: String, default: null },
29
+ transport: { type: String, enum: [null, 'text', 'template'], default: null },
30
+ messageId: { type: String, default: null },
31
+ sentBy: { type: String, required: true },
32
+ }, { timestamps: { createdAt: true, updatedAt: false } });
33
+
34
+ const decisionSchema = new mongoose.Schema({
35
+ decision: { type: String, enum: DOCTOR_DECISIONS, required: true },
36
+ source: { type: String, enum: DECISION_SOURCES, required: true },
37
+ draftNumber: { type: Number, required: true },
38
+ finalText: { type: String, default: null },
39
+ comment: { type: String, default: null },
40
+ doctorReply: { type: String, default: null },
41
+ decidedBy: { type: String, required: true },
42
+ recordedBy: { type: String, required: true },
43
+ }, { timestamps: { createdAt: true, updatedAt: false } });
44
+
45
+ const patientDeliverySchema = new mongoose.Schema({
46
+ decisionNumber: { type: Number, required: true },
47
+ messageId: { type: String, default: null },
48
+ status: { type: String, default: null },
49
+ transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template'], required: true },
50
+ sentBy: { type: String, required: true },
51
+ }, { timestamps: { createdAt: true, updatedAt: false } });
52
+
53
+ const pendingCaseMirrorSchema = new mongoose.Schema({
54
+ changes: { type: mongoose.Schema.Types.Mixed, required: true },
55
+ }, { timestamps: { createdAt: true, updatedAt: false } });
56
+
57
+ const escalationReviewSchema = new mongoose.Schema({
58
+ patientCode: { type: String, required: true },
59
+ patientCaseRecordId: { type: String, default: null },
60
+ activeCaseKey: { type: String },
61
+ status: {
62
+ type: String,
63
+ enum: [
64
+ 'open',
65
+ 'documenting',
66
+ 'draft_ready',
67
+ 'handing_off',
68
+ 'awaiting_doctor',
69
+ 'approved',
70
+ 'needs_intervention',
71
+ 'returned',
72
+ 'sending',
73
+ 'indications_sent',
74
+ 'closed',
75
+ ],
76
+ default: 'open',
77
+ },
78
+ openedBy: { type: String, required: true },
79
+ callLogs: { type: [callLogSchema], default: [] },
80
+ drafts: { type: [draftSchema], default: [] },
81
+ doctorHandoffs: { type: [doctorHandoffSchema], default: [] },
82
+ decisions: { type: [decisionSchema], default: [] },
83
+ patientDelivery: { type: patientDeliverySchema, default: null },
84
+ pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
85
+ closedBy: { type: String, default: null },
86
+ closedAt: { type: Date, default: null },
87
+ }, { timestamps: true });
88
+
89
+ escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
90
+ escalationReviewSchema.index({ activeCaseKey: 1 }, { unique: true, sparse: true });
91
+
92
+ const getEscalationReview = () => {
93
+ const dbName = getModelDatabase('EscalationReview');
94
+ const db = dbName ? getDb(dbName) : mongoose;
95
+ logger.debug('[EscalationReview] Using database', { dbName: dbName || 'default' });
96
+ return db.models.EscalationReview || db.model('EscalationReview', escalationReviewSchema);
97
+ };
98
+
99
+ module.exports = {
100
+ CALL_OUTCOMES,
101
+ DECISION_SOURCES,
102
+ DOCTOR_DECISIONS,
103
+ HANDOFF_MODES,
104
+ getEscalationReview,
105
+ escalationReviewSchema,
106
+ };
@@ -116,6 +116,18 @@ const traceRouteDefinitions = {
116
116
  'GET /:traceId': 'getTraceController'
117
117
  };
118
118
 
119
+ const escalationReviewRouteDefinitions = {
120
+ 'POST /': 'openEscalationReviewController',
121
+ 'GET /by-patient/:code': 'listEscalationReviewsController',
122
+ 'POST /:id/call-logs': 'addEscalationReviewCallLogController',
123
+ 'POST /:id/drafts': 'addEscalationReviewDraftController',
124
+ 'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
125
+ 'POST /:id/decisions': 'recordEscalationReviewDecisionController',
126
+ 'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
127
+ 'POST /:id/close': 'closeEscalationReviewController',
128
+ 'POST /:id/case-sync': 'syncEscalationReviewCaseController'
129
+ };
130
+
119
131
  const createRouter = (routeDefinitions, controllers) => {
120
132
  const router = express.Router();
121
133
 
@@ -153,6 +165,7 @@ const uploadController = require('../controllers/uploadController');
153
165
  const dashboardController = require('../controllers/dashboardController');
154
166
  const prescriptionController = require('../controllers/prescriptionController');
155
167
  const traceController = require('../controllers/traceController');
168
+ const escalationReviewController = require('../controllers/escalationReviewController');
156
169
 
157
170
  const builtInControllers = {
158
171
  // Assistant controllers
@@ -259,7 +272,18 @@ const builtInControllers = {
259
272
  updateDashboardControllerById: dashboardController.updateDashboardControllerById,
260
273
 
261
274
  // Trace controllers
262
- getTraceController: traceController.getTraceController
275
+ getTraceController: traceController.getTraceController,
276
+
277
+ // Escalation review controllers
278
+ openEscalationReviewController: escalationReviewController.openEscalationReviewController,
279
+ listEscalationReviewsController: escalationReviewController.listEscalationReviewsController,
280
+ addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
281
+ addEscalationReviewDraftController: escalationReviewController.addEscalationReviewDraftController,
282
+ handOffEscalationReviewController: escalationReviewController.handOffEscalationReviewController,
283
+ recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
284
+ sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
285
+ closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
286
+ syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
263
287
  };
264
288
 
265
289
  const setupDefaultRoutes = (app) => {
@@ -282,6 +306,7 @@ const setupDefaultRoutes = (app) => {
282
306
  app.use('/api/prescription', createRouter(prescriptionRouteDefinitions, builtInControllers));
283
307
  app.use('/api/dashboard', createRouter(dashboardRouteDefinitions, builtInControllers));
284
308
  app.use('/api/trace', createRouter(traceRouteDefinitions, builtInControllers));
309
+ app.use('/api/escalation-review', createRouter(escalationReviewRouteDefinitions, builtInControllers));
285
310
  };
286
311
 
287
312
  module.exports = {
@@ -299,6 +324,7 @@ module.exports = {
299
324
  prescriptionRoutes: prescriptionRouteDefinitions,
300
325
  dashboardRoutes: dashboardRouteDefinitions,
301
326
  traceRoutes: traceRouteDefinitions,
327
+ escalationReviewRoutes: escalationReviewRouteDefinitions,
302
328
 
303
329
  createRouter,
304
330
  setupDefaultRoutes
@@ -1,4 +1,5 @@
1
1
  const { isoDay } = require('../utils/dateUtils');
2
+ const { httpError } = require('../utils/httpErrorUtils');
2
3
  const { logger } = require('../utils/logger');
3
4
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
5
  const { withTimeout } = require('../utils/timeoutUtils');
@@ -15,8 +16,6 @@ const TRIAGE_WINDOW_DAYS = 30;
15
16
  const CARE_PLAN_LIMIT = 5;
16
17
  const HISTORY_SCOPE = ['closed_cases_90d', 'recurrence_patterns', 'recent_medications', 'patient_reported_procedures'];
17
18
 
18
- const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
19
-
20
19
  function sectionReaders(code, now) {
21
20
  const memoryManager = new DefaultMemoryManager();
22
21
  const triageStart = isoDay(new Date(now - TRIAGE_WINDOW_DAYS * 86400000).toISOString());
@@ -0,0 +1,415 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const runtimeConfig = require('../config/runtimeConfig');
4
+ const { httpError } = require('../utils/httpErrorUtils');
5
+ const { logger } = require('../utils/logger');
6
+ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
+ const {
8
+ CALL_OUTCOMES,
9
+ DECISION_SOURCES,
10
+ DOCTOR_DECISIONS,
11
+ HANDOFF_MODES,
12
+ getEscalationReview,
13
+ } = require('../models/escalationReviewModel');
14
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
15
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
16
+ const { sendMessage } = require('../core/NexusMessaging');
17
+
18
+ const { getPatientInformation, logPatientChange } = require('./patientService');
19
+ const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
20
+ const { getEscalationApprover } = require('./physicianService');
21
+
22
+ const AUDIT_SOURCE = 'escalation_review';
23
+ const RECENT_REVIEW_LIMIT = 20;
24
+ const DUPLICATE_KEY_ERROR = 11000;
25
+ const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
26
+ const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
27
+ const CLOSABLE_STATUSES = ['indications_sent', 'needs_intervention'];
28
+ const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
29
+ const MAX_TEMPLATE_TEXT_LENGTH = 800;
30
+ const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
31
+
32
+ const patientCodeOf = (code) => {
33
+ const patientCode = ensureWhatsAppFormat(String(code ?? '').trim());
34
+ if (!PATIENT_CODE.test(patientCode)) throw httpError(400, 'A valid WhatsApp ID is required');
35
+ return patientCode;
36
+ };
37
+
38
+ const requiredText = (value, name) => {
39
+ const text = String(value ?? '').trim();
40
+ if (!text) throw httpError(400, `${name} is required`);
41
+ return text;
42
+ };
43
+
44
+ const optionalText = (value) => (value == null ? null : String(value));
45
+
46
+ const reviewIdOf = (id) => {
47
+ if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
48
+ return id;
49
+ };
50
+
51
+ const configured = (key) => {
52
+ const value = runtimeConfig.get(key);
53
+ if (!value) throw httpError(503, `${key} is not configured`);
54
+ return value;
55
+ };
56
+
57
+ const statusAfter = (decision) => (decision === 'edited_approved' ? 'approved' : decision);
58
+
59
+ const activeCaseKeyOf = (patientCode, patientCaseRecordId) => `${patientCode}:${patientCaseRecordId}`;
60
+
61
+ const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
62
+
63
+ const redactedStack = (error) => redactDirectIdentifiers(String(error?.stack || ''));
64
+
65
+ const sendDidNotHappen = (error) => Boolean(error?.statusCode) || (Number.isInteger(error?.status) && error?.code != null);
66
+
67
+ const audit = (review, updatedBy, requestId, changes) => logPatientChange({
68
+ code: review.patientCode,
69
+ updatedBy,
70
+ source: AUDIT_SOURCE,
71
+ requestId,
72
+ changes: { escalationReviewId: String(review._id), ...changes },
73
+ });
74
+
75
+ const withCaseMirror = (review, update, changes) => (review.patientCaseRecordId
76
+ ? { ...update, $push: { ...update.$push, pendingCaseMirrors: { changes } } }
77
+ : update);
78
+
79
+ async function updateReview(id, allowedStatuses, update, extraFilter = {}) {
80
+ const EscalationReview = getEscalationReview();
81
+ const review = await EscalationReview.findOneAndUpdate({ _id: id, status: { $in: allowedStatuses }, ...extraFilter }, update, { new: true }).lean();
82
+ if (review) return review;
83
+ const exists = await EscalationReview.exists({ _id: id });
84
+ if (!exists) throw httpError(404, 'Escalation review not found');
85
+ throw httpError(409, STATUS_CONFLICT);
86
+ }
87
+
88
+ async function loadReview(id) {
89
+ const review = await getEscalationReview().findById(id).lean();
90
+ if (!review) throw httpError(404, 'Escalation review not found');
91
+ return review;
92
+ }
93
+
94
+ const releaseReview = (id, from, to) => getEscalationReview().updateOne({ _id: id, status: from }, { $set: { status: to } });
95
+
96
+ async function releaseClosedCase(EscalationReview, review) {
97
+ if (review.status !== 'closed' || review.pendingCaseMirrors.length || !review.activeCaseKey) return review;
98
+ const released = await EscalationReview.findOneAndUpdate(
99
+ { _id: review._id, status: 'closed', pendingCaseMirrors: { $size: 0 } },
100
+ { $unset: { activeCaseKey: '' } },
101
+ { new: true },
102
+ ).lean();
103
+ return released || review;
104
+ }
105
+
106
+ async function syncCase(review, operator, requestId) {
107
+ if (!review.patientCaseRecordId) return { review, caseMirror: 'skipped' };
108
+ const EscalationReview = getEscalationReview();
109
+ const pending = review.pendingCaseMirrors || [];
110
+ if (!pending.length) return { review: await releaseClosedCase(EscalationReview, review), caseMirror: 'updated' };
111
+
112
+ try {
113
+ await updatePatientTask({
114
+ code: review.patientCode,
115
+ kind: 'cases',
116
+ recordId: review.patientCaseRecordId,
117
+ changes: Object.assign({}, ...pending.map((mirror) => mirror.changes)),
118
+ updatedBy: operator,
119
+ source: AUDIT_SOURCE,
120
+ requestId,
121
+ });
122
+ } catch (error) {
123
+ logger.error('[EscalationReview] Patient case mirror failed', {
124
+ escalationReviewId: String(review._id),
125
+ error: redactedError(error),
126
+ stack: redactedStack(error),
127
+ });
128
+ return { review, caseMirror: 'failed' };
129
+ }
130
+
131
+ try {
132
+ const synced = await EscalationReview.findOneAndUpdate(
133
+ { _id: review._id },
134
+ { $pull: { pendingCaseMirrors: { _id: { $in: pending.map((mirror) => mirror._id) } } } },
135
+ { new: true },
136
+ ).lean();
137
+ return { review: await releaseClosedCase(EscalationReview, synced), caseMirror: 'updated' };
138
+ } catch (error) {
139
+ logger.error('[EscalationReview] Could not record the applied case changes', {
140
+ escalationReviewId: String(review._id),
141
+ error: redactedError(error),
142
+ stack: redactedStack(error),
143
+ });
144
+ return { review, caseMirror: 'updated' };
145
+ }
146
+ }
147
+
148
+ async function sendDoctorAlert({ review, draft, approver, operator }) {
149
+ const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
150
+ if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
151
+ const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
152
+ const inWindow = await isWithin24HourWindow(doctorCode);
153
+ const message = inWindow
154
+ ? { code: doctorCode, body: `${draft.doctorText}\n\n${link}`, triggeredBy: operator }
155
+ : { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
156
+ const result = await sendMessage(message);
157
+ if (!result?.success && result?.status !== 'duplicate_suppressed') {
158
+ throw httpError(502, 'The WhatsApp message to the physician could not be sent');
159
+ }
160
+ return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
161
+ }
162
+
163
+ async function patientIndicationsMessage({ review, finalText, outsideWindowRoute, operator }) {
164
+ const message = { code: review.patientCode, triggeredBy: operator };
165
+ if (await isWithin24HourWindow(review.patientCode)) return { ...message, body: finalText };
166
+ if (!outsideWindowRoute) {
167
+ throw httpError(422, `The patient is outside the 24-hour window; outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
168
+ }
169
+ if (outsideWindowRoute === 'template_recovery') return { ...message, body: finalText };
170
+
171
+ const text = finalText.replace(/\s+/g, ' ').trim();
172
+ if (text.length > MAX_TEMPLATE_TEXT_LENGTH) {
173
+ throw httpError(422, `The indications exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters for the predefined template; use template_recovery`);
174
+ }
175
+ const patient = await getPatientInformation(review.patientCode);
176
+ const firstName = String(patient?.first_name ?? '').trim();
177
+ if (!firstName) throw httpError(422, 'The patient has no first name on record for the predefined template');
178
+ return {
179
+ ...message,
180
+ contentSid: configured('ESCALATION_REVIEW_PATIENT_INDICATIONS_CONTENT_SID'),
181
+ variables: { 1: firstName, 2: text },
182
+ };
183
+ }
184
+
185
+ const deliveryTransport = (message, result) => {
186
+ if (message.contentSid) return 'predefined_template';
187
+ return result.deferred ? 'template_recovery' : 'text';
188
+ };
189
+
190
+ async function openEscalationReview({ code, patientCaseRecordId = null, openedBy, requestId = null } = {}) {
191
+ const patientCode = patientCodeOf(code);
192
+ const operator = requiredText(openedBy, 'openedBy');
193
+ const patient = await getPatientInformation(patientCode);
194
+ if (!patient) throw httpError(404, 'Patient not found');
195
+
196
+ const fields = { patientCode, openedBy: operator };
197
+ if (patientCaseRecordId !== null) {
198
+ const { cases } = await getPatientTasks(patientCode);
199
+ if (!cases.some((patientCase) => patientCase.recordId === patientCaseRecordId)) {
200
+ throw httpError(404, 'Patient case not found for this patient');
201
+ }
202
+ Object.assign(fields, { patientCaseRecordId, activeCaseKey: activeCaseKeyOf(patientCode, patientCaseRecordId) });
203
+ }
204
+
205
+ const EscalationReview = getEscalationReview();
206
+ await EscalationReview.init();
207
+ let review;
208
+ try {
209
+ review = (await EscalationReview.create(fields)).toObject();
210
+ } catch (error) {
211
+ if (error?.code !== DUPLICATE_KEY_ERROR || !fields.activeCaseKey) throw error;
212
+ const existing = await EscalationReview.findOne({ activeCaseKey: fields.activeCaseKey }).lean();
213
+ if (!existing) throw httpError(409, 'The patient case review changed while opening; try again');
214
+ return { review: existing, created: false };
215
+ }
216
+ await audit(review, operator, requestId, { action: 'opened', patientCaseRecordId });
217
+ return { review, created: true };
218
+ }
219
+
220
+ async function listEscalationReviews({ code } = {}) {
221
+ const patientCode = patientCodeOf(code);
222
+ return getEscalationReview().find({ patientCode }).sort({ createdAt: -1 }).limit(RECENT_REVIEW_LIMIT).lean();
223
+ }
224
+
225
+ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
226
+ const reviewId = reviewIdOf(id);
227
+ const operator = requiredText(loggedBy, 'loggedBy');
228
+ if (!CALL_OUTCOMES.includes(outcome)) throw httpError(400, `outcome must be one of: ${CALL_OUTCOMES.join(', ')}`);
229
+ const callTime = calledAt == null ? new Date() : new Date(calledAt);
230
+ if (Number.isNaN(callTime.getTime())) throw httpError(400, 'calledAt must be a valid date');
231
+
232
+ const review = await updateReview(reviewId, DOCUMENTING_STATUSES, {
233
+ $push: { callLogs: { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator } },
234
+ $set: { status: 'documenting' },
235
+ });
236
+ await audit(review, operator, requestId, { action: 'call_logged', outcome });
237
+ return review;
238
+ }
239
+
240
+ async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId = null } = {}) {
241
+ const reviewId = reviewIdOf(id);
242
+ const operator = requiredText(writtenBy, 'writtenBy');
243
+ const draft = {
244
+ doctorText: requiredText(doctorText, 'doctorText'),
245
+ patientMessage: requiredText(patientMessage, 'patientMessage'),
246
+ writtenBy: operator,
247
+ };
248
+
249
+ const review = await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { drafts: draft }, $set: { status: 'draft_ready' } });
250
+ await audit(review, operator, requestId, { action: 'draft_saved', draftNumber: review.drafts.length });
251
+ return review;
252
+ }
253
+
254
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, requestId = null } = {}) {
255
+ const reviewId = reviewIdOf(id);
256
+ const operator = requiredText(sentBy, 'sentBy');
257
+ if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
258
+
259
+ const review = await loadReview(reviewId);
260
+ if (!HANDOFF_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
261
+ const draftNumber = review.drafts.length;
262
+ if (!draftNumber) throw httpError(409, 'The escalation review has no draft yet');
263
+ const draft = review.drafts[draftNumber - 1];
264
+ let approver = null;
265
+ if (mode === 'sent_whatsapp') {
266
+ approver = await getEscalationApprover(physicianEmail);
267
+ if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
268
+ }
269
+
270
+ await updateReview(reviewId, [review.status], { $set: { status: 'handing_off' } }, { drafts: { $size: draftNumber } });
271
+ let delivery = {};
272
+ let updated;
273
+ try {
274
+ if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ review, draft, approver, operator })) };
275
+ updated = await updateReview(reviewId, ['handing_off'], withCaseMirror(review, {
276
+ $push: { doctorHandoffs: { mode, draftNumber, ...delivery, sentBy: operator } },
277
+ $set: { status: 'awaiting_doctor' },
278
+ }, { status: 'en revision_medica' }));
279
+ } catch (error) {
280
+ await releaseReview(reviewId, 'handing_off', review.status);
281
+ throw error;
282
+ }
283
+ await audit(updated, operator, requestId, {
284
+ action: mode === 'copied' ? 'copied_for_doctor' : 'sent_to_doctor',
285
+ draftNumber,
286
+ transport: delivery.transport ?? null,
287
+ });
288
+ return syncCase(updated, operator, requestId);
289
+ }
290
+
291
+ async function recordDoctorDecision({
292
+ id,
293
+ source,
294
+ decision,
295
+ finalText = null,
296
+ comment = null,
297
+ doctorName = null,
298
+ doctorReply = null,
299
+ recordedBy,
300
+ requestId = null,
301
+ } = {}) {
302
+ const reviewId = reviewIdOf(id);
303
+ const operator = requiredText(recordedBy, 'recordedBy');
304
+ if (!DECISION_SOURCES.includes(source)) throw httpError(400, `source must be one of: ${DECISION_SOURCES.join(', ')}`);
305
+ if (!DOCTOR_DECISIONS.includes(decision)) throw httpError(400, `decision must be one of: ${DOCTOR_DECISIONS.join(', ')}`);
306
+
307
+ let decidedBy = operator;
308
+ let reply = null;
309
+ if (source === 'platform') {
310
+ const approver = await getEscalationApprover(operator);
311
+ if (!approver) throw httpError(403, 'Only an escalation review approver can decide in the platform');
312
+ } else {
313
+ decidedBy = requiredText(doctorName, 'doctorName');
314
+ reply = requiredText(doctorReply, 'doctorReply');
315
+ }
316
+
317
+ const review = await loadReview(reviewId);
318
+ if (review.status !== 'awaiting_doctor') throw httpError(409, STATUS_CONFLICT);
319
+ const { draftNumber } = review.doctorHandoffs[review.doctorHandoffs.length - 1];
320
+ const draft = review.drafts[draftNumber - 1];
321
+ let approvedText = null;
322
+ if (decision === 'approved') approvedText = draft.patientMessage;
323
+ if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
324
+
325
+ const updated = await updateReview(reviewId, ['awaiting_doctor'], {
326
+ $push: {
327
+ decisions: {
328
+ decision,
329
+ source,
330
+ draftNumber,
331
+ finalText: approvedText,
332
+ comment: optionalText(comment),
333
+ doctorReply: reply,
334
+ decidedBy,
335
+ recordedBy: operator,
336
+ },
337
+ },
338
+ $set: { status: statusAfter(decision) },
339
+ });
340
+ await audit(updated, operator, requestId, { action: 'doctor_decision', decision, source, draftNumber });
341
+ return updated;
342
+ }
343
+
344
+ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy, requestId = null } = {}) {
345
+ const reviewId = reviewIdOf(id);
346
+ const operator = requiredText(sentBy, 'sentBy');
347
+ if (outsideWindowRoute !== null && !OUTSIDE_WINDOW_ROUTES.includes(outsideWindowRoute)) {
348
+ throw httpError(400, `outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
349
+ }
350
+
351
+ const claimed = await updateReview(reviewId, ['approved'], { $set: { status: 'sending' } });
352
+ const decisionNumber = claimed.decisions.length;
353
+ const { finalText } = claimed.decisions[decisionNumber - 1];
354
+
355
+ let message;
356
+ let result;
357
+ try {
358
+ message = await patientIndicationsMessage({ review: claimed, finalText, outsideWindowRoute, operator });
359
+ result = await sendMessage(message);
360
+ if (!result?.success) throw httpError(502, 'The indications could not be sent to the patient');
361
+ } catch (error) {
362
+ if (!sendDidNotHappen(error)) {
363
+ logger.error('[EscalationReview] Patient send outcome is unknown; leaving the review in sending', {
364
+ escalationReviewId: String(claimed._id),
365
+ error: redactedError(error),
366
+ });
367
+ throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
368
+ }
369
+ await releaseReview(reviewId, 'sending', 'approved');
370
+ throw error;
371
+ }
372
+
373
+ const delivery = {
374
+ decisionNumber,
375
+ messageId: result.messageId || null,
376
+ status: result.status || null,
377
+ transport: deliveryTransport(message, result),
378
+ sentBy: operator,
379
+ };
380
+ const review = await updateReview(reviewId, ['sending'], withCaseMirror(claimed, {
381
+ $set: { status: 'indications_sent', patientDelivery: delivery },
382
+ }, { recommendation: finalText }));
383
+ await audit(review, operator, requestId, { action: 'indications_sent', decisionNumber, transport: delivery.transport });
384
+ return syncCase(review, operator, requestId);
385
+ }
386
+
387
+ async function closeEscalationReview({ id, closedBy, requestId = null } = {}) {
388
+ const reviewId = reviewIdOf(id);
389
+ const operator = requiredText(closedBy, 'closedBy');
390
+
391
+ const current = await loadReview(reviewId);
392
+ const review = await updateReview(reviewId, CLOSABLE_STATUSES, withCaseMirror(current, {
393
+ $set: { status: 'closed', closedBy: operator, closedAt: new Date() },
394
+ }, { operationsStatus: 'cerrado' }));
395
+ await audit(review, operator, requestId, { action: 'closed' });
396
+ return syncCase(review, operator, requestId);
397
+ }
398
+
399
+ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
400
+ const reviewId = reviewIdOf(id);
401
+ const operator = requiredText(syncedBy, 'syncedBy');
402
+ return syncCase(await loadReview(reviewId), operator, requestId);
403
+ }
404
+
405
+ module.exports = {
406
+ addCallLog,
407
+ addDraft,
408
+ closeEscalationReview,
409
+ handOffToDoctor,
410
+ listEscalationReviews,
411
+ openEscalationReview,
412
+ recordDoctorDecision,
413
+ sendApprovedIndications,
414
+ syncEscalationReviewCase,
415
+ };
@@ -1,5 +1,7 @@
1
1
  const { Monitoreo_ID } = require('../config/airtableConfig');
2
2
 
3
+ const { httpError } = require('../utils/httpErrorUtils');
4
+
3
5
  const { escapeFormulaValue, fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
4
6
  const {
5
7
  isCaseOpen,
@@ -64,8 +66,6 @@ const OPERATIONS_STATUSES = [
64
66
  'sin caracterizar',
65
67
  ];
66
68
 
67
- const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
68
-
69
69
  const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
70
70
 
71
71
  const toRequest = (row) => ({
@@ -121,6 +121,7 @@ const TASK_KINDS = {
121
121
  status: { field: 'status', options: CASE_STATUSES },
122
122
  operationsStatus: { field: 'status_operaciones', options: OPERATIONS_STATUSES },
123
123
  note: { field: 'observations' },
124
+ recommendation: { field: 'recomendation_final' },
124
125
  },
125
126
  },
126
127
  };
@@ -0,0 +1,20 @@
1
+ const { Monitoreo_ID } = require('../config/airtableConfig');
2
+
3
+ const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper');
4
+
5
+ const { getRecordByFilter } = require('./airtableService');
6
+
7
+ const APPROVER_FIELDS = ['physician_name', 'email', 'phone_number'];
8
+
9
+ async function getEscalationApprover(email) {
10
+ const normalized = String(email ?? '').trim().toLowerCase();
11
+ if (!normalized) return null;
12
+
13
+ const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {aprueba_vaiven})`;
14
+ const [physician] = await getRecordByFilter(Monitoreo_ID, 'physicians', formula, null, APPROVER_FIELDS, true) || [];
15
+ if (!physician) return null;
16
+
17
+ return { name: physician.physician_name || null, email: normalized, phone: physician.phone_number || null };
18
+ }
19
+
20
+ module.exports = { getEscalationApprover };
@@ -0,0 +1,3 @@
1
+ const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
2
+
3
+ module.exports = { httpError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.46.0",
3
+ "version": "5.47.0-dev.7300",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",