@peopl-health/nexus 5.46.0-dev.7272 → 5.46.0-dev.7273
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/conversationController.js +2 -2
- package/lib/controllers/escalationReviewController.js +142 -0
- package/lib/models/escalationReviewModel.js +106 -0
- package/lib/routes/index.js +27 -1
- package/lib/services/conversationService.js +5 -17
- package/lib/services/escalationContextService.js +1 -2
- package/lib/services/escalationReviewService.js +415 -0
- package/lib/services/patientTaskService.js +17 -24
- package/lib/services/physicianService.js +20 -0
- package/lib/utils/httpErrorUtils.js +3 -0
- package/package.json +1 -1
- package/lib/helpers/patientTaskRulesHelper.js +0 -49
- package/lib/services/patientTaskSummaryService.js +0 -93
|
@@ -34,7 +34,7 @@ const getConversationController = async (req, res) => {
|
|
|
34
34
|
});
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
const { threads, total, airtableNameMap
|
|
37
|
+
const { threads, total, airtableNameMap } = await fetchConversationData(filter, skip, limit);
|
|
38
38
|
|
|
39
39
|
if (!threads?.length) {
|
|
40
40
|
return res.status(200).json({
|
|
@@ -44,7 +44,7 @@ const getConversationController = async (req, res) => {
|
|
|
44
44
|
});
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
const processedConversations = await processConversations(threads, airtableNameMap
|
|
47
|
+
const processedConversations = await processConversations(threads, airtableNameMap);
|
|
48
48
|
const totalPages = Math.ceil(total / limit);
|
|
49
49
|
|
|
50
50
|
res.status(200).json({
|
|
@@ -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
|
+
};
|
package/lib/routes/index.js
CHANGED
|
@@ -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
|
|
@@ -5,7 +5,6 @@ const { logger } = require('../utils/logger');
|
|
|
5
5
|
const { Thread } = require('../models/threadModel');
|
|
6
6
|
|
|
7
7
|
const { getRecordByFilter } = require('../services/airtableService');
|
|
8
|
-
const { getOpenTaskSummary } = require('../services/patientTaskSummaryService');
|
|
9
8
|
|
|
10
9
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
11
10
|
const { ensurePatientResource } = require('./patientResourceService');
|
|
@@ -15,7 +14,7 @@ const toMap = (arr, keyFn, valFn) => arr.reduce((m, item) => {
|
|
|
15
14
|
return key ? { ...m, [key]: valFn(item) } : m;
|
|
16
15
|
}, {});
|
|
17
16
|
|
|
18
|
-
const buildThreadFilter = (filter, { triageIds
|
|
17
|
+
const buildThreadFilter = (filter, { triageIds }) => {
|
|
19
18
|
const base = { lastMessageAt: { $ne: null } };
|
|
20
19
|
switch (filter) {
|
|
21
20
|
case 'unread':
|
|
@@ -28,8 +27,6 @@ const buildThreadFilter = (filter, { triageIds, pendingTaskCodes }) => {
|
|
|
28
27
|
return { ...base, lastMessageFromMe: false };
|
|
29
28
|
case 'triage-last-month':
|
|
30
29
|
return { ...base, code: { $in: triageIds } };
|
|
31
|
-
case 'pending-tasks':
|
|
32
|
-
return { ...base, code: { $in: pendingTaskCodes } };
|
|
33
30
|
case 'all':
|
|
34
31
|
default:
|
|
35
32
|
return base;
|
|
@@ -43,15 +40,7 @@ const fetchConversationData = async (filter, skip, limit) => {
|
|
|
43
40
|
triageIds = (triageRecords || []).map(r => r.whatsapp_id).filter(Boolean);
|
|
44
41
|
}
|
|
45
42
|
|
|
46
|
-
const
|
|
47
|
-
? await getOpenTaskSummary()
|
|
48
|
-
: await getOpenTaskSummary().catch((error) => {
|
|
49
|
-
logger.warn('[fetchConversationData] Open task summary unavailable', { error: error.message });
|
|
50
|
-
return null;
|
|
51
|
-
});
|
|
52
|
-
const pendingTaskCodes = [...(openTaskMap?.keys() || [])];
|
|
53
|
-
|
|
54
|
-
const threadFilter = buildThreadFilter(filter, { triageIds, pendingTaskCodes });
|
|
43
|
+
const threadFilter = buildThreadFilter(filter, { triageIds });
|
|
55
44
|
|
|
56
45
|
logger.info('[fetchConversationData] Applying filter', { filter });
|
|
57
46
|
const startTime = Date.now();
|
|
@@ -79,7 +68,7 @@ const fetchConversationData = async (filter, skip, limit) => {
|
|
|
79
68
|
}
|
|
80
69
|
}
|
|
81
70
|
|
|
82
|
-
return { threads, total, airtableNameMap
|
|
71
|
+
return { threads, total, airtableNameMap };
|
|
83
72
|
};
|
|
84
73
|
|
|
85
74
|
const getMediaType = (media) => {
|
|
@@ -90,7 +79,7 @@ const getMediaType = (media) => {
|
|
|
90
79
|
return type === 'application' ? 'document' : subtype === 'webp' ? 'sticker' : type;
|
|
91
80
|
};
|
|
92
81
|
|
|
93
|
-
const processConversations = async (threads, airtableNameMap
|
|
82
|
+
const processConversations = async (threads, airtableNameMap) => {
|
|
94
83
|
const createConversation = (thread, index) => {
|
|
95
84
|
const code = thread?.code || `error_${index}`;
|
|
96
85
|
return {
|
|
@@ -115,8 +104,7 @@ const processConversations = async (threads, airtableNameMap, openTaskMap) => {
|
|
|
115
104
|
lastMessageTime: thread?.lastMessageAt || null,
|
|
116
105
|
lastMessageFromMe: thread?.lastMessageFromMe || false,
|
|
117
106
|
isLastMessageMedia: !!thread?.lastMessageMedia,
|
|
118
|
-
lastMessageType: getMediaType(thread?.lastMessageMedia)
|
|
119
|
-
openTasks: openTaskMap?.get(code) || null
|
|
107
|
+
lastMessageType: getMediaType(thread?.lastMessageMedia)
|
|
120
108
|
};
|
|
121
109
|
};
|
|
122
110
|
|
|
@@ -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,18 +1,11 @@
|
|
|
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
|
-
const {
|
|
5
|
-
isCaseOpen,
|
|
6
|
-
isCaseUrgent,
|
|
7
|
-
isRequestOpen,
|
|
8
|
-
isRequestUrgent,
|
|
9
|
-
needsCaseAttention,
|
|
10
|
-
needsRequestAttention,
|
|
11
|
-
} = require('../helpers/patientTaskRulesHelper');
|
|
12
6
|
|
|
13
7
|
const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
|
|
14
8
|
const { logPatientChange } = require('../services/patientService');
|
|
15
|
-
const { clearOpenTaskSummary } = require('../services/patientTaskSummaryService');
|
|
16
9
|
|
|
17
10
|
const MAX_ROWS = 50;
|
|
18
11
|
const MAX_NOTE_LENGTH = 5000;
|
|
@@ -63,8 +56,17 @@ const OPERATIONS_STATUSES = [
|
|
|
63
56
|
'notificado medical',
|
|
64
57
|
'sin caracterizar',
|
|
65
58
|
];
|
|
66
|
-
|
|
67
|
-
|
|
59
|
+
const CLOSED_REQUEST_STATUSES = [
|
|
60
|
+
'resuelto',
|
|
61
|
+
'no resuelto',
|
|
62
|
+
'solicitud repetida',
|
|
63
|
+
'no es requerimiento',
|
|
64
|
+
'no es ofrecimiento',
|
|
65
|
+
'alucinación',
|
|
66
|
+
'revisado',
|
|
67
|
+
];
|
|
68
|
+
const CLOSED_CASE_STATUSES = ['Resuelto', 'Fallecido'];
|
|
69
|
+
const CLOSED_OPERATIONS_STATUS = 'cerrado';
|
|
68
70
|
|
|
69
71
|
const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
|
|
70
72
|
|
|
@@ -79,9 +81,7 @@ const toRequest = (row) => ({
|
|
|
79
81
|
status: row.status ?? null,
|
|
80
82
|
note: row.Observaciones ?? null,
|
|
81
83
|
isForDoctorOffice: row.doctor_office === true,
|
|
82
|
-
isOpen:
|
|
83
|
-
needsAttention: needsRequestAttention(row.status),
|
|
84
|
-
isUrgent: isRequestUrgent(row.urgency),
|
|
84
|
+
isOpen: !CLOSED_REQUEST_STATUSES.includes(row.status),
|
|
85
85
|
});
|
|
86
86
|
|
|
87
87
|
const toCase = (row) => ({
|
|
@@ -96,9 +96,7 @@ const toCase = (row) => ({
|
|
|
96
96
|
followUp: row.seguimiento ?? null,
|
|
97
97
|
note: row.observations ?? null,
|
|
98
98
|
recommendation: row.recomendation_final ?? null,
|
|
99
|
-
isOpen:
|
|
100
|
-
needsAttention: needsCaseAttention(row.status, row.status_operaciones, row.created || row._createdTime),
|
|
101
|
-
isUrgent: isCaseUrgent(row.type),
|
|
99
|
+
isOpen: row.status_operaciones !== CLOSED_OPERATIONS_STATUS && !CLOSED_CASE_STATUSES.includes(row.status),
|
|
102
100
|
});
|
|
103
101
|
|
|
104
102
|
const TASK_KINDS = {
|
|
@@ -121,6 +119,7 @@ const TASK_KINDS = {
|
|
|
121
119
|
status: { field: 'status', options: CASE_STATUSES },
|
|
122
120
|
operationsStatus: { field: 'status_operaciones', options: OPERATIONS_STATUSES },
|
|
123
121
|
note: { field: 'observations' },
|
|
122
|
+
recommendation: { field: 'recomendation_final' },
|
|
124
123
|
},
|
|
125
124
|
},
|
|
126
125
|
};
|
|
@@ -143,11 +142,7 @@ async function readTasks(kind, whatsappId) {
|
|
|
143
142
|
const { table, fields, toTask } = TASK_KINDS[kind];
|
|
144
143
|
const rows = await getRecordByFilter(Monitoreo_ID, table, taskFilter(kind, whatsappId), null, fields, true);
|
|
145
144
|
const tasks = rows.map(toTask).sort(byOpenThenNewest);
|
|
146
|
-
return {
|
|
147
|
-
tasks: tasks.slice(0, MAX_ROWS),
|
|
148
|
-
openCount: tasks.filter((task) => task.isOpen).length,
|
|
149
|
-
attentionCount: tasks.filter((task) => task.needsAttention).length,
|
|
150
|
-
};
|
|
145
|
+
return { tasks: tasks.slice(0, MAX_ROWS), openCount: tasks.filter((task) => task.isOpen).length };
|
|
151
146
|
}
|
|
152
147
|
|
|
153
148
|
async function getPatientTasks(code) {
|
|
@@ -157,7 +152,6 @@ async function getPatientTasks(code) {
|
|
|
157
152
|
requests: requests.tasks,
|
|
158
153
|
cases: cases.tasks,
|
|
159
154
|
openCount: requests.openCount + cases.openCount,
|
|
160
|
-
attentionCount: requests.attentionCount + cases.attentionCount,
|
|
161
155
|
options: { requestStatus: REQUEST_STATUSES, caseStatus: CASE_STATUSES, operationsStatus: OPERATIONS_STATUSES },
|
|
162
156
|
};
|
|
163
157
|
}
|
|
@@ -187,7 +181,6 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
|
|
|
187
181
|
if (!updated) throw httpError(404, 'Task not found for this patient');
|
|
188
182
|
|
|
189
183
|
await logPatientChange({ code: whatsappId, updatedBy, source, requestId, changes: { table, recordId, fields } });
|
|
190
|
-
clearOpenTaskSummary();
|
|
191
184
|
return toTask(toRow(updated));
|
|
192
185
|
}
|
|
193
186
|
|
|
@@ -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 };
|
package/package.json
CHANGED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
const CLOSED_REQUEST_STATUSES = [
|
|
2
|
-
'resuelto',
|
|
3
|
-
'no resuelto',
|
|
4
|
-
'solicitud repetida',
|
|
5
|
-
'no es requerimiento',
|
|
6
|
-
'no es ofrecimiento',
|
|
7
|
-
'alucinación',
|
|
8
|
-
'revisado',
|
|
9
|
-
];
|
|
10
|
-
const CLOSED_CASE_STATUSES = ['Resuelto', 'Fallecido'];
|
|
11
|
-
const CLOSED_OPERATIONS_STATUS = 'cerrado';
|
|
12
|
-
const ATTENTION_REQUEST_STATUS = 'sin atender';
|
|
13
|
-
const ATTENTION_OPERATIONS_STATUS = 'pendiente';
|
|
14
|
-
const ATTENTION_CASE_WINDOW_DAYS = 14;
|
|
15
|
-
const ATTENTION_CASE_WINDOW_MS = ATTENTION_CASE_WINDOW_DAYS * 24 * 60 * 60 * 1000;
|
|
16
|
-
const URGENT_REQUEST_URGENCY = 'urgent';
|
|
17
|
-
const URGENT_CASE_TYPES = ['Urgencia', 'Emergencia'];
|
|
18
|
-
|
|
19
|
-
const isRequestOpen = (status) => !CLOSED_REQUEST_STATUSES.includes(status);
|
|
20
|
-
|
|
21
|
-
const isCaseOpen = (status, operationsStatus) => operationsStatus !== CLOSED_OPERATIONS_STATUS
|
|
22
|
-
&& !CLOSED_CASE_STATUSES.includes(status);
|
|
23
|
-
|
|
24
|
-
const isWithinAttentionWindow = (createdAt) => {
|
|
25
|
-
const created = Date.parse(createdAt || '');
|
|
26
|
-
return Number.isFinite(created) && Date.now() - created <= ATTENTION_CASE_WINDOW_MS;
|
|
27
|
-
};
|
|
28
|
-
|
|
29
|
-
const needsRequestAttention = (status) => status === ATTENTION_REQUEST_STATUS;
|
|
30
|
-
|
|
31
|
-
const needsCaseAttention = (status, operationsStatus, createdAt) => operationsStatus === ATTENTION_OPERATIONS_STATUS
|
|
32
|
-
&& !CLOSED_CASE_STATUSES.includes(status)
|
|
33
|
-
&& isWithinAttentionWindow(createdAt);
|
|
34
|
-
|
|
35
|
-
const isRequestUrgent = (urgency) => urgency === URGENT_REQUEST_URGENCY;
|
|
36
|
-
|
|
37
|
-
const isCaseUrgent = (type) => URGENT_CASE_TYPES.includes(type);
|
|
38
|
-
|
|
39
|
-
module.exports = {
|
|
40
|
-
ATTENTION_CASE_WINDOW_DAYS,
|
|
41
|
-
ATTENTION_OPERATIONS_STATUS,
|
|
42
|
-
ATTENTION_REQUEST_STATUS,
|
|
43
|
-
isCaseOpen,
|
|
44
|
-
isCaseUrgent,
|
|
45
|
-
isRequestOpen,
|
|
46
|
-
isRequestUrgent,
|
|
47
|
-
needsCaseAttention,
|
|
48
|
-
needsRequestAttention,
|
|
49
|
-
};
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
2
|
-
|
|
3
|
-
const { MapCache } = require('../utils/MapCache');
|
|
4
|
-
|
|
5
|
-
const { fieldEquals } = require('../helpers/airtableFormulaHelper');
|
|
6
|
-
const {
|
|
7
|
-
ATTENTION_CASE_WINDOW_DAYS,
|
|
8
|
-
ATTENTION_OPERATIONS_STATUS,
|
|
9
|
-
ATTENTION_REQUEST_STATUS,
|
|
10
|
-
isCaseUrgent,
|
|
11
|
-
isRequestUrgent,
|
|
12
|
-
needsCaseAttention,
|
|
13
|
-
needsRequestAttention,
|
|
14
|
-
} = require('../helpers/patientTaskRulesHelper');
|
|
15
|
-
|
|
16
|
-
const { getRecordByFilter } = require('../services/airtableService');
|
|
17
|
-
|
|
18
|
-
const CACHE_KEY = 'open-tasks';
|
|
19
|
-
const CACHE_TTL_MS = 60000;
|
|
20
|
-
const REQUEST_FIELDS = ['whatsapp_id', 'status', 'urgency'];
|
|
21
|
-
const CASE_FIELDS = ['whatsapp_id', 'status', 'status_operaciones', 'type', 'created'];
|
|
22
|
-
const REQUEST_FILTER = `AND(${fieldEquals('message_tag', 'request')}, ${fieldEquals('status', ATTENTION_REQUEST_STATUS)})`;
|
|
23
|
-
const CASE_FILTER = `AND(${fieldEquals('status_operaciones', ATTENTION_OPERATIONS_STATUS)}, OR(IS_AFTER({created}, DATEADD(NOW(), -${ATTENTION_CASE_WINDOW_DAYS}, 'days')), {created} = BLANK()))`;
|
|
24
|
-
|
|
25
|
-
const cache = new MapCache({ maxSize: 1, ttl: CACHE_TTL_MS });
|
|
26
|
-
let inFlight = null;
|
|
27
|
-
let generation = 0;
|
|
28
|
-
|
|
29
|
-
const codesOf = (row) => (Array.isArray(row.whatsapp_id) ? row.whatsapp_id : [row.whatsapp_id])
|
|
30
|
-
.map((value) => String(value || '').trim())
|
|
31
|
-
.filter(Boolean);
|
|
32
|
-
|
|
33
|
-
const addTask = (summary, code, kind, isUrgent) => {
|
|
34
|
-
const entry = summary.get(code) || { requests: 0, cases: 0, isUrgent: false };
|
|
35
|
-
entry[kind] += 1;
|
|
36
|
-
entry.isUrgent = entry.isUrgent || isUrgent;
|
|
37
|
-
summary.set(code, entry);
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
async function loadSummary() {
|
|
41
|
-
const [requestRows, caseRows] = await Promise.all([
|
|
42
|
-
getRecordByFilter(Monitoreo_ID, 'unresolved_questions', REQUEST_FILTER, null, REQUEST_FIELDS, true),
|
|
43
|
-
getRecordByFilter(Monitoreo_ID, 'patient_cases', CASE_FILTER, null, CASE_FIELDS, true),
|
|
44
|
-
]);
|
|
45
|
-
const summary = new Map();
|
|
46
|
-
|
|
47
|
-
for (const row of requestRows || []) {
|
|
48
|
-
if (!needsRequestAttention(row.status)) continue;
|
|
49
|
-
for (const code of codesOf(row)) addTask(summary, code, 'requests', isRequestUrgent(row.urgency));
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
for (const row of caseRows || []) {
|
|
53
|
-
const createdAt = row.created || row._createdTime || null;
|
|
54
|
-
if (!needsCaseAttention(row.status, row.status_operaciones, createdAt)) continue;
|
|
55
|
-
for (const code of codesOf(row)) addTask(summary, code, 'cases', isCaseUrgent(row.type));
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
return summary;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
async function getOpenTaskSummary() {
|
|
62
|
-
const cached = cache.get(CACHE_KEY);
|
|
63
|
-
if (cached) return cached;
|
|
64
|
-
if (!inFlight) {
|
|
65
|
-
const loadGeneration = generation;
|
|
66
|
-
const load = loadSummary().then(
|
|
67
|
-
(summary) => {
|
|
68
|
-
if (inFlight === load) inFlight = null;
|
|
69
|
-
if (loadGeneration !== generation) return getOpenTaskSummary();
|
|
70
|
-
cache.set(CACHE_KEY, summary);
|
|
71
|
-
return summary;
|
|
72
|
-
},
|
|
73
|
-
(error) => {
|
|
74
|
-
if (inFlight === load) inFlight = null;
|
|
75
|
-
if (loadGeneration !== generation) return getOpenTaskSummary();
|
|
76
|
-
throw error;
|
|
77
|
-
}
|
|
78
|
-
);
|
|
79
|
-
inFlight = load;
|
|
80
|
-
}
|
|
81
|
-
return inFlight;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
function clearOpenTaskSummary() {
|
|
85
|
-
generation += 1;
|
|
86
|
-
cache.clear();
|
|
87
|
-
inFlight = null;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
module.exports = {
|
|
91
|
-
clearOpenTaskSummary,
|
|
92
|
-
getOpenTaskSummary,
|
|
93
|
-
};
|