@peopl-health/nexus 5.46.0-dev.7271 → 5.46.0-dev.7272
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/helpers/patientTaskRulesHelper.js +49 -0
- package/lib/routes/index.js +1 -27
- package/lib/services/conversationService.js +17 -5
- package/lib/services/escalationContextService.js +2 -1
- package/lib/services/patientTaskService.js +24 -17
- package/lib/services/patientTaskSummaryService.js +93 -0
- package/package.json +1 -1
- package/lib/controllers/escalationReviewController.js +0 -142
- package/lib/models/escalationReviewModel.js +0 -106
- package/lib/services/escalationReviewService.js +0 -411
- package/lib/services/physicianService.js +0 -20
- package/lib/utils/httpErrorUtils.js +0 -3
|
@@ -34,7 +34,7 @@ const getConversationController = async (req, res) => {
|
|
|
34
34
|
});
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
const { threads, total, airtableNameMap } = await fetchConversationData(filter, skip, limit);
|
|
37
|
+
const { threads, total, airtableNameMap, openTaskMap } = 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, openTaskMap);
|
|
48
48
|
const totalPages = Math.ceil(total / limit);
|
|
49
49
|
|
|
50
50
|
res.status(200).json({
|
|
@@ -0,0 +1,49 @@
|
|
|
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
|
+
};
|
package/lib/routes/index.js
CHANGED
|
@@ -116,18 +116,6 @@ 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
|
-
|
|
131
119
|
const createRouter = (routeDefinitions, controllers) => {
|
|
132
120
|
const router = express.Router();
|
|
133
121
|
|
|
@@ -165,7 +153,6 @@ const uploadController = require('../controllers/uploadController');
|
|
|
165
153
|
const dashboardController = require('../controllers/dashboardController');
|
|
166
154
|
const prescriptionController = require('../controllers/prescriptionController');
|
|
167
155
|
const traceController = require('../controllers/traceController');
|
|
168
|
-
const escalationReviewController = require('../controllers/escalationReviewController');
|
|
169
156
|
|
|
170
157
|
const builtInControllers = {
|
|
171
158
|
// Assistant controllers
|
|
@@ -272,18 +259,7 @@ const builtInControllers = {
|
|
|
272
259
|
updateDashboardControllerById: dashboardController.updateDashboardControllerById,
|
|
273
260
|
|
|
274
261
|
// Trace controllers
|
|
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
|
|
262
|
+
getTraceController: traceController.getTraceController
|
|
287
263
|
};
|
|
288
264
|
|
|
289
265
|
const setupDefaultRoutes = (app) => {
|
|
@@ -306,7 +282,6 @@ const setupDefaultRoutes = (app) => {
|
|
|
306
282
|
app.use('/api/prescription', createRouter(prescriptionRouteDefinitions, builtInControllers));
|
|
307
283
|
app.use('/api/dashboard', createRouter(dashboardRouteDefinitions, builtInControllers));
|
|
308
284
|
app.use('/api/trace', createRouter(traceRouteDefinitions, builtInControllers));
|
|
309
|
-
app.use('/api/escalation-review', createRouter(escalationReviewRouteDefinitions, builtInControllers));
|
|
310
285
|
};
|
|
311
286
|
|
|
312
287
|
module.exports = {
|
|
@@ -324,7 +299,6 @@ module.exports = {
|
|
|
324
299
|
prescriptionRoutes: prescriptionRouteDefinitions,
|
|
325
300
|
dashboardRoutes: dashboardRouteDefinitions,
|
|
326
301
|
traceRoutes: traceRouteDefinitions,
|
|
327
|
-
escalationReviewRoutes: escalationReviewRouteDefinitions,
|
|
328
302
|
|
|
329
303
|
createRouter,
|
|
330
304
|
setupDefaultRoutes
|
|
@@ -5,6 +5,7 @@ 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');
|
|
8
9
|
|
|
9
10
|
const { sendMessage } = require('../core/NexusMessaging');
|
|
10
11
|
const { ensurePatientResource } = require('./patientResourceService');
|
|
@@ -14,7 +15,7 @@ const toMap = (arr, keyFn, valFn) => arr.reduce((m, item) => {
|
|
|
14
15
|
return key ? { ...m, [key]: valFn(item) } : m;
|
|
15
16
|
}, {});
|
|
16
17
|
|
|
17
|
-
const buildThreadFilter = (filter, { triageIds }) => {
|
|
18
|
+
const buildThreadFilter = (filter, { triageIds, pendingTaskCodes }) => {
|
|
18
19
|
const base = { lastMessageAt: { $ne: null } };
|
|
19
20
|
switch (filter) {
|
|
20
21
|
case 'unread':
|
|
@@ -27,6 +28,8 @@ const buildThreadFilter = (filter, { triageIds }) => {
|
|
|
27
28
|
return { ...base, lastMessageFromMe: false };
|
|
28
29
|
case 'triage-last-month':
|
|
29
30
|
return { ...base, code: { $in: triageIds } };
|
|
31
|
+
case 'pending-tasks':
|
|
32
|
+
return { ...base, code: { $in: pendingTaskCodes } };
|
|
30
33
|
case 'all':
|
|
31
34
|
default:
|
|
32
35
|
return base;
|
|
@@ -40,7 +43,15 @@ const fetchConversationData = async (filter, skip, limit) => {
|
|
|
40
43
|
triageIds = (triageRecords || []).map(r => r.whatsapp_id).filter(Boolean);
|
|
41
44
|
}
|
|
42
45
|
|
|
43
|
-
const
|
|
46
|
+
const openTaskMap = filter === 'pending-tasks'
|
|
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 });
|
|
44
55
|
|
|
45
56
|
logger.info('[fetchConversationData] Applying filter', { filter });
|
|
46
57
|
const startTime = Date.now();
|
|
@@ -68,7 +79,7 @@ const fetchConversationData = async (filter, skip, limit) => {
|
|
|
68
79
|
}
|
|
69
80
|
}
|
|
70
81
|
|
|
71
|
-
return { threads, total, airtableNameMap };
|
|
82
|
+
return { threads, total, airtableNameMap, openTaskMap };
|
|
72
83
|
};
|
|
73
84
|
|
|
74
85
|
const getMediaType = (media) => {
|
|
@@ -79,7 +90,7 @@ const getMediaType = (media) => {
|
|
|
79
90
|
return type === 'application' ? 'document' : subtype === 'webp' ? 'sticker' : type;
|
|
80
91
|
};
|
|
81
92
|
|
|
82
|
-
const processConversations = async (threads, airtableNameMap) => {
|
|
93
|
+
const processConversations = async (threads, airtableNameMap, openTaskMap) => {
|
|
83
94
|
const createConversation = (thread, index) => {
|
|
84
95
|
const code = thread?.code || `error_${index}`;
|
|
85
96
|
return {
|
|
@@ -104,7 +115,8 @@ const processConversations = async (threads, airtableNameMap) => {
|
|
|
104
115
|
lastMessageTime: thread?.lastMessageAt || null,
|
|
105
116
|
lastMessageFromMe: thread?.lastMessageFromMe || false,
|
|
106
117
|
isLastMessageMedia: !!thread?.lastMessageMedia,
|
|
107
|
-
lastMessageType: getMediaType(thread?.lastMessageMedia)
|
|
118
|
+
lastMessageType: getMediaType(thread?.lastMessageMedia),
|
|
119
|
+
openTasks: openTaskMap?.get(code) || null
|
|
108
120
|
};
|
|
109
121
|
};
|
|
110
122
|
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
const { isoDay } = require('../utils/dateUtils');
|
|
2
|
-
const { httpError } = require('../utils/httpErrorUtils');
|
|
3
2
|
const { logger } = require('../utils/logger');
|
|
4
3
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
5
4
|
const { withTimeout } = require('../utils/timeoutUtils');
|
|
@@ -16,6 +15,8 @@ const TRIAGE_WINDOW_DAYS = 30;
|
|
|
16
15
|
const CARE_PLAN_LIMIT = 5;
|
|
17
16
|
const HISTORY_SCOPE = ['closed_cases_90d', 'recurrence_patterns', 'recent_medications', 'patient_reported_procedures'];
|
|
18
17
|
|
|
18
|
+
const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
|
|
19
|
+
|
|
19
20
|
function sectionReaders(code, now) {
|
|
20
21
|
const memoryManager = new DefaultMemoryManager();
|
|
21
22
|
const triageStart = isoDay(new Date(now - TRIAGE_WINDOW_DAYS * 86400000).toISOString());
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
2
2
|
|
|
3
|
-
const { httpError } = require('../utils/httpErrorUtils');
|
|
4
|
-
|
|
5
3
|
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');
|
|
6
12
|
|
|
7
13
|
const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
|
|
8
14
|
const { logPatientChange } = require('../services/patientService');
|
|
15
|
+
const { clearOpenTaskSummary } = require('../services/patientTaskSummaryService');
|
|
9
16
|
|
|
10
17
|
const MAX_ROWS = 50;
|
|
11
18
|
const MAX_NOTE_LENGTH = 5000;
|
|
@@ -56,17 +63,8 @@ const OPERATIONS_STATUSES = [
|
|
|
56
63
|
'notificado medical',
|
|
57
64
|
'sin caracterizar',
|
|
58
65
|
];
|
|
59
|
-
|
|
60
|
-
|
|
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';
|
|
66
|
+
|
|
67
|
+
const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
|
|
70
68
|
|
|
71
69
|
const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
|
|
72
70
|
|
|
@@ -81,7 +79,9 @@ const toRequest = (row) => ({
|
|
|
81
79
|
status: row.status ?? null,
|
|
82
80
|
note: row.Observaciones ?? null,
|
|
83
81
|
isForDoctorOffice: row.doctor_office === true,
|
|
84
|
-
isOpen:
|
|
82
|
+
isOpen: isRequestOpen(row.status),
|
|
83
|
+
needsAttention: needsRequestAttention(row.status),
|
|
84
|
+
isUrgent: isRequestUrgent(row.urgency),
|
|
85
85
|
});
|
|
86
86
|
|
|
87
87
|
const toCase = (row) => ({
|
|
@@ -96,7 +96,9 @@ const toCase = (row) => ({
|
|
|
96
96
|
followUp: row.seguimiento ?? null,
|
|
97
97
|
note: row.observations ?? null,
|
|
98
98
|
recommendation: row.recomendation_final ?? null,
|
|
99
|
-
isOpen: row.
|
|
99
|
+
isOpen: isCaseOpen(row.status, row.status_operaciones),
|
|
100
|
+
needsAttention: needsCaseAttention(row.status, row.status_operaciones, row.created || row._createdTime),
|
|
101
|
+
isUrgent: isCaseUrgent(row.type),
|
|
100
102
|
});
|
|
101
103
|
|
|
102
104
|
const TASK_KINDS = {
|
|
@@ -119,7 +121,6 @@ const TASK_KINDS = {
|
|
|
119
121
|
status: { field: 'status', options: CASE_STATUSES },
|
|
120
122
|
operationsStatus: { field: 'status_operaciones', options: OPERATIONS_STATUSES },
|
|
121
123
|
note: { field: 'observations' },
|
|
122
|
-
recommendation: { field: 'recomendation_final' },
|
|
123
124
|
},
|
|
124
125
|
},
|
|
125
126
|
};
|
|
@@ -142,7 +143,11 @@ async function readTasks(kind, whatsappId) {
|
|
|
142
143
|
const { table, fields, toTask } = TASK_KINDS[kind];
|
|
143
144
|
const rows = await getRecordByFilter(Monitoreo_ID, table, taskFilter(kind, whatsappId), null, fields, true);
|
|
144
145
|
const tasks = rows.map(toTask).sort(byOpenThenNewest);
|
|
145
|
-
return {
|
|
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
|
+
};
|
|
146
151
|
}
|
|
147
152
|
|
|
148
153
|
async function getPatientTasks(code) {
|
|
@@ -152,6 +157,7 @@ async function getPatientTasks(code) {
|
|
|
152
157
|
requests: requests.tasks,
|
|
153
158
|
cases: cases.tasks,
|
|
154
159
|
openCount: requests.openCount + cases.openCount,
|
|
160
|
+
attentionCount: requests.attentionCount + cases.attentionCount,
|
|
155
161
|
options: { requestStatus: REQUEST_STATUSES, caseStatus: CASE_STATUSES, operationsStatus: OPERATIONS_STATUSES },
|
|
156
162
|
};
|
|
157
163
|
}
|
|
@@ -181,6 +187,7 @@ async function updatePatientTask({ code, kind, recordId, changes, updatedBy, sou
|
|
|
181
187
|
if (!updated) throw httpError(404, 'Task not found for this patient');
|
|
182
188
|
|
|
183
189
|
await logPatientChange({ code: whatsappId, updatedBy, source, requestId, changes: { table, recordId, fields } });
|
|
190
|
+
clearOpenTaskSummary();
|
|
184
191
|
return toTask(toRow(updated));
|
|
185
192
|
}
|
|
186
193
|
|
|
@@ -0,0 +1,93 @@
|
|
|
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
|
+
};
|
package/package.json
CHANGED
|
@@ -1,142 +0,0 @@
|
|
|
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
|
-
};
|
|
@@ -1,106 +0,0 @@
|
|
|
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
|
-
};
|
|
@@ -1,411 +0,0 @@
|
|
|
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 sendDidNotHappen = (error) => Boolean(error?.statusCode) || (Number.isInteger(error?.status) && error?.code != null);
|
|
64
|
-
|
|
65
|
-
const audit = (review, updatedBy, requestId, changes) => logPatientChange({
|
|
66
|
-
code: review.patientCode,
|
|
67
|
-
updatedBy,
|
|
68
|
-
source: AUDIT_SOURCE,
|
|
69
|
-
requestId,
|
|
70
|
-
changes: { escalationReviewId: String(review._id), ...changes },
|
|
71
|
-
});
|
|
72
|
-
|
|
73
|
-
const withCaseMirror = (review, update, changes) => (review.patientCaseRecordId
|
|
74
|
-
? { ...update, $push: { ...update.$push, pendingCaseMirrors: { changes } } }
|
|
75
|
-
: update);
|
|
76
|
-
|
|
77
|
-
async function updateReview(id, allowedStatuses, update, extraFilter = {}) {
|
|
78
|
-
const EscalationReview = getEscalationReview();
|
|
79
|
-
const review = await EscalationReview.findOneAndUpdate({ _id: id, status: { $in: allowedStatuses }, ...extraFilter }, update, { new: true }).lean();
|
|
80
|
-
if (review) return review;
|
|
81
|
-
const exists = await EscalationReview.exists({ _id: id });
|
|
82
|
-
if (!exists) throw httpError(404, 'Escalation review not found');
|
|
83
|
-
throw httpError(409, STATUS_CONFLICT);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
async function loadReview(id) {
|
|
87
|
-
const review = await getEscalationReview().findById(id).lean();
|
|
88
|
-
if (!review) throw httpError(404, 'Escalation review not found');
|
|
89
|
-
return review;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const releaseReview = (id, from, to) => getEscalationReview().updateOne({ _id: id, status: from }, { $set: { status: to } });
|
|
93
|
-
|
|
94
|
-
async function releaseClosedCase(EscalationReview, review) {
|
|
95
|
-
if (review.status !== 'closed' || review.pendingCaseMirrors.length || !review.activeCaseKey) return review;
|
|
96
|
-
const released = await EscalationReview.findOneAndUpdate(
|
|
97
|
-
{ _id: review._id, status: 'closed', pendingCaseMirrors: { $size: 0 } },
|
|
98
|
-
{ $unset: { activeCaseKey: '' } },
|
|
99
|
-
{ new: true },
|
|
100
|
-
).lean();
|
|
101
|
-
return released || review;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
async function syncCase(review, operator, requestId) {
|
|
105
|
-
if (!review.patientCaseRecordId) return { review, caseMirror: 'skipped' };
|
|
106
|
-
const EscalationReview = getEscalationReview();
|
|
107
|
-
const pending = review.pendingCaseMirrors || [];
|
|
108
|
-
if (!pending.length) return { review: await releaseClosedCase(EscalationReview, review), caseMirror: 'updated' };
|
|
109
|
-
|
|
110
|
-
try {
|
|
111
|
-
await updatePatientTask({
|
|
112
|
-
code: review.patientCode,
|
|
113
|
-
kind: 'cases',
|
|
114
|
-
recordId: review.patientCaseRecordId,
|
|
115
|
-
changes: Object.assign({}, ...pending.map((mirror) => mirror.changes)),
|
|
116
|
-
updatedBy: operator,
|
|
117
|
-
source: AUDIT_SOURCE,
|
|
118
|
-
requestId,
|
|
119
|
-
});
|
|
120
|
-
} catch (error) {
|
|
121
|
-
logger.error('[EscalationReview] Patient case mirror failed', {
|
|
122
|
-
escalationReviewId: String(review._id),
|
|
123
|
-
error: redactedError(error),
|
|
124
|
-
});
|
|
125
|
-
return { review, caseMirror: 'failed' };
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
try {
|
|
129
|
-
const synced = await EscalationReview.findOneAndUpdate(
|
|
130
|
-
{ _id: review._id },
|
|
131
|
-
{ $pull: { pendingCaseMirrors: { _id: { $in: pending.map((mirror) => mirror._id) } } } },
|
|
132
|
-
{ new: true },
|
|
133
|
-
).lean();
|
|
134
|
-
return { review: await releaseClosedCase(EscalationReview, synced), caseMirror: 'updated' };
|
|
135
|
-
} catch (error) {
|
|
136
|
-
logger.error('[EscalationReview] Could not record the applied case changes', {
|
|
137
|
-
escalationReviewId: String(review._id),
|
|
138
|
-
error: redactedError(error),
|
|
139
|
-
});
|
|
140
|
-
return { review, caseMirror: 'updated' };
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
async function sendDoctorAlert({ review, draft, approver, operator }) {
|
|
145
|
-
const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
|
|
146
|
-
if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
|
|
147
|
-
const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
|
|
148
|
-
const inWindow = await isWithin24HourWindow(doctorCode);
|
|
149
|
-
const message = inWindow
|
|
150
|
-
? { code: doctorCode, body: `${draft.doctorText}\n\n${link}`, triggeredBy: operator }
|
|
151
|
-
: { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
|
|
152
|
-
const result = await sendMessage(message);
|
|
153
|
-
if (!result?.success && result?.status !== 'duplicate_suppressed') {
|
|
154
|
-
throw httpError(502, 'The WhatsApp message to the physician could not be sent');
|
|
155
|
-
}
|
|
156
|
-
return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
async function patientIndicationsMessage({ review, finalText, outsideWindowRoute, operator }) {
|
|
160
|
-
const message = { code: review.patientCode, triggeredBy: operator };
|
|
161
|
-
if (await isWithin24HourWindow(review.patientCode)) return { ...message, body: finalText };
|
|
162
|
-
if (!outsideWindowRoute) {
|
|
163
|
-
throw httpError(422, `The patient is outside the 24-hour window; outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
|
|
164
|
-
}
|
|
165
|
-
if (outsideWindowRoute === 'template_recovery') return { ...message, body: finalText };
|
|
166
|
-
|
|
167
|
-
const text = finalText.replace(/\s+/g, ' ').trim();
|
|
168
|
-
if (text.length > MAX_TEMPLATE_TEXT_LENGTH) {
|
|
169
|
-
throw httpError(422, `The indications exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters for the predefined template; use template_recovery`);
|
|
170
|
-
}
|
|
171
|
-
const patient = await getPatientInformation(review.patientCode);
|
|
172
|
-
const firstName = String(patient?.first_name ?? '').trim();
|
|
173
|
-
if (!firstName) throw httpError(422, 'The patient has no first name on record for the predefined template');
|
|
174
|
-
return {
|
|
175
|
-
...message,
|
|
176
|
-
contentSid: configured('ESCALATION_REVIEW_PATIENT_INDICATIONS_CONTENT_SID'),
|
|
177
|
-
variables: { 1: firstName, 2: text },
|
|
178
|
-
};
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
const deliveryTransport = (message, result) => {
|
|
182
|
-
if (message.contentSid) return 'predefined_template';
|
|
183
|
-
return result.deferred ? 'template_recovery' : 'text';
|
|
184
|
-
};
|
|
185
|
-
|
|
186
|
-
async function openEscalationReview({ code, patientCaseRecordId = null, openedBy, requestId = null } = {}) {
|
|
187
|
-
const patientCode = patientCodeOf(code);
|
|
188
|
-
const operator = requiredText(openedBy, 'openedBy');
|
|
189
|
-
const patient = await getPatientInformation(patientCode);
|
|
190
|
-
if (!patient) throw httpError(404, 'Patient not found');
|
|
191
|
-
|
|
192
|
-
const fields = { patientCode, openedBy: operator };
|
|
193
|
-
if (patientCaseRecordId !== null) {
|
|
194
|
-
const { cases } = await getPatientTasks(patientCode);
|
|
195
|
-
if (!cases.some((patientCase) => patientCase.recordId === patientCaseRecordId)) {
|
|
196
|
-
throw httpError(404, 'Patient case not found for this patient');
|
|
197
|
-
}
|
|
198
|
-
Object.assign(fields, { patientCaseRecordId, activeCaseKey: activeCaseKeyOf(patientCode, patientCaseRecordId) });
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
const EscalationReview = getEscalationReview();
|
|
202
|
-
await EscalationReview.init();
|
|
203
|
-
let review;
|
|
204
|
-
try {
|
|
205
|
-
review = (await EscalationReview.create(fields)).toObject();
|
|
206
|
-
} catch (error) {
|
|
207
|
-
if (error?.code !== DUPLICATE_KEY_ERROR || !fields.activeCaseKey) throw error;
|
|
208
|
-
const existing = await EscalationReview.findOne({ activeCaseKey: fields.activeCaseKey }).lean();
|
|
209
|
-
if (!existing) throw httpError(409, 'The patient case review changed while opening; try again');
|
|
210
|
-
return { review: existing, created: false };
|
|
211
|
-
}
|
|
212
|
-
await audit(review, operator, requestId, { action: 'opened', patientCaseRecordId });
|
|
213
|
-
return { review, created: true };
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
async function listEscalationReviews({ code } = {}) {
|
|
217
|
-
const patientCode = patientCodeOf(code);
|
|
218
|
-
return getEscalationReview().find({ patientCode }).sort({ createdAt: -1 }).limit(RECENT_REVIEW_LIMIT).lean();
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
|
|
222
|
-
const reviewId = reviewIdOf(id);
|
|
223
|
-
const operator = requiredText(loggedBy, 'loggedBy');
|
|
224
|
-
if (!CALL_OUTCOMES.includes(outcome)) throw httpError(400, `outcome must be one of: ${CALL_OUTCOMES.join(', ')}`);
|
|
225
|
-
const callTime = calledAt == null ? new Date() : new Date(calledAt);
|
|
226
|
-
if (Number.isNaN(callTime.getTime())) throw httpError(400, 'calledAt must be a valid date');
|
|
227
|
-
|
|
228
|
-
const review = await updateReview(reviewId, DOCUMENTING_STATUSES, {
|
|
229
|
-
$push: { callLogs: { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator } },
|
|
230
|
-
$set: { status: 'documenting' },
|
|
231
|
-
});
|
|
232
|
-
await audit(review, operator, requestId, { action: 'call_logged', outcome });
|
|
233
|
-
return review;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId = null } = {}) {
|
|
237
|
-
const reviewId = reviewIdOf(id);
|
|
238
|
-
const operator = requiredText(writtenBy, 'writtenBy');
|
|
239
|
-
const draft = {
|
|
240
|
-
doctorText: requiredText(doctorText, 'doctorText'),
|
|
241
|
-
patientMessage: requiredText(patientMessage, 'patientMessage'),
|
|
242
|
-
writtenBy: operator,
|
|
243
|
-
};
|
|
244
|
-
|
|
245
|
-
const review = await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { drafts: draft }, $set: { status: 'draft_ready' } });
|
|
246
|
-
await audit(review, operator, requestId, { action: 'draft_saved', draftNumber: review.drafts.length });
|
|
247
|
-
return review;
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, requestId = null } = {}) {
|
|
251
|
-
const reviewId = reviewIdOf(id);
|
|
252
|
-
const operator = requiredText(sentBy, 'sentBy');
|
|
253
|
-
if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
|
|
254
|
-
|
|
255
|
-
const review = await loadReview(reviewId);
|
|
256
|
-
if (!HANDOFF_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
|
|
257
|
-
const draftNumber = review.drafts.length;
|
|
258
|
-
if (!draftNumber) throw httpError(409, 'The escalation review has no draft yet');
|
|
259
|
-
const draft = review.drafts[draftNumber - 1];
|
|
260
|
-
let approver = null;
|
|
261
|
-
if (mode === 'sent_whatsapp') {
|
|
262
|
-
approver = await getEscalationApprover(physicianEmail);
|
|
263
|
-
if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
await updateReview(reviewId, [review.status], { $set: { status: 'handing_off' } }, { drafts: { $size: draftNumber } });
|
|
267
|
-
let delivery = {};
|
|
268
|
-
let updated;
|
|
269
|
-
try {
|
|
270
|
-
if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ review, draft, approver, operator })) };
|
|
271
|
-
updated = await updateReview(reviewId, ['handing_off'], withCaseMirror(review, {
|
|
272
|
-
$push: { doctorHandoffs: { mode, draftNumber, ...delivery, sentBy: operator } },
|
|
273
|
-
$set: { status: 'awaiting_doctor' },
|
|
274
|
-
}, { status: 'en revision_medica' }));
|
|
275
|
-
} catch (error) {
|
|
276
|
-
await releaseReview(reviewId, 'handing_off', review.status);
|
|
277
|
-
throw error;
|
|
278
|
-
}
|
|
279
|
-
await audit(updated, operator, requestId, {
|
|
280
|
-
action: mode === 'copied' ? 'copied_for_doctor' : 'sent_to_doctor',
|
|
281
|
-
draftNumber,
|
|
282
|
-
transport: delivery.transport ?? null,
|
|
283
|
-
});
|
|
284
|
-
return syncCase(updated, operator, requestId);
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
async function recordDoctorDecision({
|
|
288
|
-
id,
|
|
289
|
-
source,
|
|
290
|
-
decision,
|
|
291
|
-
finalText = null,
|
|
292
|
-
comment = null,
|
|
293
|
-
doctorName = null,
|
|
294
|
-
doctorReply = null,
|
|
295
|
-
recordedBy,
|
|
296
|
-
requestId = null,
|
|
297
|
-
} = {}) {
|
|
298
|
-
const reviewId = reviewIdOf(id);
|
|
299
|
-
const operator = requiredText(recordedBy, 'recordedBy');
|
|
300
|
-
if (!DECISION_SOURCES.includes(source)) throw httpError(400, `source must be one of: ${DECISION_SOURCES.join(', ')}`);
|
|
301
|
-
if (!DOCTOR_DECISIONS.includes(decision)) throw httpError(400, `decision must be one of: ${DOCTOR_DECISIONS.join(', ')}`);
|
|
302
|
-
|
|
303
|
-
let decidedBy = operator;
|
|
304
|
-
let reply = null;
|
|
305
|
-
if (source === 'platform') {
|
|
306
|
-
const approver = await getEscalationApprover(operator);
|
|
307
|
-
if (!approver) throw httpError(403, 'Only an escalation review approver can decide in the platform');
|
|
308
|
-
} else {
|
|
309
|
-
decidedBy = requiredText(doctorName, 'doctorName');
|
|
310
|
-
reply = requiredText(doctorReply, 'doctorReply');
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
const review = await loadReview(reviewId);
|
|
314
|
-
if (review.status !== 'awaiting_doctor') throw httpError(409, STATUS_CONFLICT);
|
|
315
|
-
const { draftNumber } = review.doctorHandoffs[review.doctorHandoffs.length - 1];
|
|
316
|
-
const draft = review.drafts[draftNumber - 1];
|
|
317
|
-
let approvedText = null;
|
|
318
|
-
if (decision === 'approved') approvedText = draft.patientMessage;
|
|
319
|
-
if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
|
|
320
|
-
|
|
321
|
-
const updated = await updateReview(reviewId, ['awaiting_doctor'], {
|
|
322
|
-
$push: {
|
|
323
|
-
decisions: {
|
|
324
|
-
decision,
|
|
325
|
-
source,
|
|
326
|
-
draftNumber,
|
|
327
|
-
finalText: approvedText,
|
|
328
|
-
comment: optionalText(comment),
|
|
329
|
-
doctorReply: reply,
|
|
330
|
-
decidedBy,
|
|
331
|
-
recordedBy: operator,
|
|
332
|
-
},
|
|
333
|
-
},
|
|
334
|
-
$set: { status: statusAfter(decision) },
|
|
335
|
-
});
|
|
336
|
-
await audit(updated, operator, requestId, { action: 'doctor_decision', decision, source, draftNumber });
|
|
337
|
-
return updated;
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy, requestId = null } = {}) {
|
|
341
|
-
const reviewId = reviewIdOf(id);
|
|
342
|
-
const operator = requiredText(sentBy, 'sentBy');
|
|
343
|
-
if (outsideWindowRoute !== null && !OUTSIDE_WINDOW_ROUTES.includes(outsideWindowRoute)) {
|
|
344
|
-
throw httpError(400, `outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
const claimed = await updateReview(reviewId, ['approved'], { $set: { status: 'sending' } });
|
|
348
|
-
const decisionNumber = claimed.decisions.length;
|
|
349
|
-
const { finalText } = claimed.decisions[decisionNumber - 1];
|
|
350
|
-
|
|
351
|
-
let message;
|
|
352
|
-
let result;
|
|
353
|
-
try {
|
|
354
|
-
message = await patientIndicationsMessage({ review: claimed, finalText, outsideWindowRoute, operator });
|
|
355
|
-
result = await sendMessage(message);
|
|
356
|
-
if (!result?.success) throw httpError(502, 'The indications could not be sent to the patient');
|
|
357
|
-
} catch (error) {
|
|
358
|
-
if (!sendDidNotHappen(error)) {
|
|
359
|
-
logger.error('[EscalationReview] Patient send outcome is unknown; leaving the review in sending', {
|
|
360
|
-
escalationReviewId: String(claimed._id),
|
|
361
|
-
error: redactedError(error),
|
|
362
|
-
});
|
|
363
|
-
throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
|
|
364
|
-
}
|
|
365
|
-
await releaseReview(reviewId, 'sending', 'approved');
|
|
366
|
-
throw error;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
const delivery = {
|
|
370
|
-
decisionNumber,
|
|
371
|
-
messageId: result.messageId || null,
|
|
372
|
-
status: result.status || null,
|
|
373
|
-
transport: deliveryTransport(message, result),
|
|
374
|
-
sentBy: operator,
|
|
375
|
-
};
|
|
376
|
-
const review = await updateReview(reviewId, ['sending'], withCaseMirror(claimed, {
|
|
377
|
-
$set: { status: 'indications_sent', patientDelivery: delivery },
|
|
378
|
-
}, { recommendation: finalText }));
|
|
379
|
-
await audit(review, operator, requestId, { action: 'indications_sent', decisionNumber, transport: delivery.transport });
|
|
380
|
-
return syncCase(review, operator, requestId);
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
async function closeEscalationReview({ id, closedBy, requestId = null } = {}) {
|
|
384
|
-
const reviewId = reviewIdOf(id);
|
|
385
|
-
const operator = requiredText(closedBy, 'closedBy');
|
|
386
|
-
|
|
387
|
-
const current = await loadReview(reviewId);
|
|
388
|
-
const review = await updateReview(reviewId, CLOSABLE_STATUSES, withCaseMirror(current, {
|
|
389
|
-
$set: { status: 'closed', closedBy: operator, closedAt: new Date() },
|
|
390
|
-
}, { operationsStatus: 'cerrado' }));
|
|
391
|
-
await audit(review, operator, requestId, { action: 'closed' });
|
|
392
|
-
return syncCase(review, operator, requestId);
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
|
|
396
|
-
const reviewId = reviewIdOf(id);
|
|
397
|
-
const operator = requiredText(syncedBy, 'syncedBy');
|
|
398
|
-
return syncCase(await loadReview(reviewId), operator, requestId);
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
module.exports = {
|
|
402
|
-
addCallLog,
|
|
403
|
-
addDraft,
|
|
404
|
-
closeEscalationReview,
|
|
405
|
-
handOffToDoctor,
|
|
406
|
-
listEscalationReviews,
|
|
407
|
-
openEscalationReview,
|
|
408
|
-
recordDoctorDecision,
|
|
409
|
-
sendApprovedIndications,
|
|
410
|
-
syncEscalationReviewCase,
|
|
411
|
-
};
|
|
@@ -1,20 +0,0 @@
|
|
|
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 };
|