@peopl-health/nexus 5.45.0-dev.7117 → 5.45.0-dev.7119
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.
|
@@ -7,6 +7,7 @@ const { getPatientInformation, updatePatientInformation, logPatientChange } = re
|
|
|
7
7
|
const { getTriageHistory } = require('../services/triageHistoryService');
|
|
8
8
|
const { getCarePlanHistory } = require('../services/carePlanHistoryService');
|
|
9
9
|
const { getEscalationContext } = require('../services/escalationContextService');
|
|
10
|
+
const { getPatientTasks, updatePatientTask } = require('../services/patientTaskService');
|
|
10
11
|
const {
|
|
11
12
|
getRecommendationCarousels,
|
|
12
13
|
getRecommendationCarouselImage,
|
|
@@ -70,6 +71,28 @@ const getPatientCarePlanController = async (req, res) => {
|
|
|
70
71
|
}
|
|
71
72
|
};
|
|
72
73
|
|
|
74
|
+
const getPatientTasksController = async (req, res) => {
|
|
75
|
+
try {
|
|
76
|
+
const tasks = await getPatientTasks(req.params.code);
|
|
77
|
+
res.status(200).json({ success: true, ...tasks });
|
|
78
|
+
} catch (error) {
|
|
79
|
+
logger.error('Error fetching patient tasks:', { error: error.message, code: req.params?.code });
|
|
80
|
+
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const updatePatientTaskController = async (req, res) => {
|
|
85
|
+
try {
|
|
86
|
+
const { code, kind, recordId } = req.params;
|
|
87
|
+
const { changes, updatedBy, source } = req.body || {};
|
|
88
|
+
const task = await updatePatientTask({ code, kind, recordId, changes, updatedBy, source, requestId: req.requestId });
|
|
89
|
+
res.status(200).json({ success: true, task });
|
|
90
|
+
} catch (error) {
|
|
91
|
+
logger.error('Error updating patient task:', { error: error.message, code: req.params?.code, kind: req.params?.kind, recordId: req.params?.recordId });
|
|
92
|
+
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
|
|
73
96
|
const getPatientRecommendationCarouselsController = async (req, res) => {
|
|
74
97
|
try {
|
|
75
98
|
const code = String(req.params.code || '').trim();
|
|
@@ -224,7 +247,11 @@ const getPatientEscalationContextController = async (req, res) => {
|
|
|
224
247
|
const context = await getEscalationContext({ code: req.params.code });
|
|
225
248
|
res.status(200).json({ success: true, context });
|
|
226
249
|
} catch (error) {
|
|
227
|
-
logger.error('Error fetching patient escalation context:', {
|
|
250
|
+
logger.error('Error fetching patient escalation context:', {
|
|
251
|
+
error: redactDirectIdentifiers(String(error.message || '')),
|
|
252
|
+
stack: redactDirectIdentifiers(String(error.stack || '')),
|
|
253
|
+
code: redactDirectIdentifiers(String(req.params?.code || '')),
|
|
254
|
+
});
|
|
228
255
|
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
229
256
|
}
|
|
230
257
|
};
|
|
@@ -234,8 +261,10 @@ module.exports = {
|
|
|
234
261
|
getPatientTriageInfoController,
|
|
235
262
|
getPatientCarePlanController,
|
|
236
263
|
getPatientEscalationContextController,
|
|
264
|
+
getPatientTasksController,
|
|
237
265
|
getPatientRecommendationCarouselsController,
|
|
238
266
|
getPatientRecommendationCarouselImageController,
|
|
239
267
|
updatePatientController,
|
|
268
|
+
updatePatientTaskController,
|
|
240
269
|
logPatientChangeController,
|
|
241
270
|
};
|
package/lib/routes/index.js
CHANGED
|
@@ -71,7 +71,9 @@ const patientRouteDefinitions = {
|
|
|
71
71
|
'GET /triage/:code': 'getPatientTriageInfoController',
|
|
72
72
|
'GET /careplan/:code': 'getPatientCarePlanController',
|
|
73
73
|
'GET /escalation-context/:code': 'getPatientEscalationContextController',
|
|
74
|
+
'GET /tasks/:code': 'getPatientTasksController',
|
|
74
75
|
'PATCH /:code': 'updatePatientController',
|
|
76
|
+
'PATCH /tasks/:code/:kind/:recordId': 'updatePatientTaskController',
|
|
75
77
|
'POST /audit-log': 'logPatientChangeController'
|
|
76
78
|
};
|
|
77
79
|
|
|
@@ -214,9 +216,11 @@ const builtInControllers = {
|
|
|
214
216
|
getPatientTriageInfoController: patientController.getPatientTriageInfoController,
|
|
215
217
|
getPatientCarePlanController: patientController.getPatientCarePlanController,
|
|
216
218
|
getPatientEscalationContextController: patientController.getPatientEscalationContextController,
|
|
219
|
+
getPatientTasksController: patientController.getPatientTasksController,
|
|
217
220
|
getPatientRecommendationCarouselsController: patientController.getPatientRecommendationCarouselsController,
|
|
218
221
|
getPatientRecommendationCarouselImageController: patientController.getPatientRecommendationCarouselImageController,
|
|
219
222
|
updatePatientController: patientController.updatePatientController,
|
|
223
|
+
updatePatientTaskController: patientController.updatePatientTaskController,
|
|
220
224
|
logPatientChangeController: patientController.logPatientChangeController,
|
|
221
225
|
|
|
222
226
|
// Preset controllers
|
|
@@ -69,9 +69,10 @@ async function getEscalationContext({ code, now = Date.now(), timeoutMs = SECTIO
|
|
|
69
69
|
context.triages = context.triages.records;
|
|
70
70
|
}
|
|
71
71
|
if (context.carePlan) {
|
|
72
|
-
const { records, currentState = null } = context.carePlan;
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
const { records, pagination = null, currentState = null } = context.carePlan;
|
|
73
|
+
const { degradedSections: carePlanDegraded = [], ...state } = currentState || {};
|
|
74
|
+
context.carePlan = { records, pagination, currentState: currentState ? state : null };
|
|
75
|
+
for (const section of carePlanDegraded) context.degradedSections.push(`carePlan.${section}`);
|
|
75
76
|
}
|
|
76
77
|
|
|
77
78
|
return context;
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
2
|
+
|
|
3
|
+
const { escapeFormulaValue, fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
4
|
+
|
|
5
|
+
const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
|
|
6
|
+
const { logPatientChange } = require('../services/patientService');
|
|
7
|
+
|
|
8
|
+
const MAX_ROWS = 50;
|
|
9
|
+
const MAX_NOTE_LENGTH = 5000;
|
|
10
|
+
const WHATSAPP_ID_RX = /^whatsapp:\+\d{10,15}$/;
|
|
11
|
+
const RECORD_ID_RX = /^rec[A-Za-z0-9]{14}$/;
|
|
12
|
+
|
|
13
|
+
const REQUEST_STATUSES = [
|
|
14
|
+
'resuelto',
|
|
15
|
+
'revisado',
|
|
16
|
+
'no es requerimiento',
|
|
17
|
+
'no es ofrecimiento',
|
|
18
|
+
'en espera doctor',
|
|
19
|
+
'en espera paciente',
|
|
20
|
+
'en progreso',
|
|
21
|
+
'sin atender',
|
|
22
|
+
'en espera proveedor',
|
|
23
|
+
'solicitud repetida',
|
|
24
|
+
'fallas técnicas_paciente',
|
|
25
|
+
'alucinación',
|
|
26
|
+
'seguimiento',
|
|
27
|
+
'recordatorio',
|
|
28
|
+
'no resuelto',
|
|
29
|
+
];
|
|
30
|
+
const CASE_STATUSES = [
|
|
31
|
+
'Pendiente',
|
|
32
|
+
'Activo',
|
|
33
|
+
'En Espera',
|
|
34
|
+
'Resuelto',
|
|
35
|
+
'En vigilancia',
|
|
36
|
+
'Fallecido',
|
|
37
|
+
'En tratamiento',
|
|
38
|
+
'Invitación_charla_nutrición',
|
|
39
|
+
'En evaluación',
|
|
40
|
+
'Invitación_charla_psicología',
|
|
41
|
+
'niega síntomas',
|
|
42
|
+
'en revision_medica',
|
|
43
|
+
'derivacion_urgencias',
|
|
44
|
+
'nutrición_revisión',
|
|
45
|
+
'radioterapia_revisión',
|
|
46
|
+
'internado',
|
|
47
|
+
];
|
|
48
|
+
const OPERATIONS_STATUSES = [
|
|
49
|
+
'cerrado',
|
|
50
|
+
'coordinación médica',
|
|
51
|
+
'síntoma marcado',
|
|
52
|
+
'pendiente',
|
|
53
|
+
'notificado ops',
|
|
54
|
+
'notificado medical',
|
|
55
|
+
'sin caracterizar',
|
|
56
|
+
];
|
|
57
|
+
const CLOSED_REQUEST_STATUSES = [
|
|
58
|
+
'resuelto',
|
|
59
|
+
'no resuelto',
|
|
60
|
+
'solicitud repetida',
|
|
61
|
+
'no es requerimiento',
|
|
62
|
+
'no es ofrecimiento',
|
|
63
|
+
'alucinación',
|
|
64
|
+
'revisado',
|
|
65
|
+
];
|
|
66
|
+
const CLOSED_CASE_STATUSES = ['Resuelto', 'Fallecido'];
|
|
67
|
+
const CLOSED_OPERATIONS_STATUS = 'cerrado';
|
|
68
|
+
|
|
69
|
+
const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
|
|
70
|
+
|
|
71
|
+
const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
|
|
72
|
+
|
|
73
|
+
const toRequest = (row) => ({
|
|
74
|
+
recordId: row._recordId,
|
|
75
|
+
number: row.question_id ?? null,
|
|
76
|
+
createdAt: row.created_time || row._createdTime || null,
|
|
77
|
+
question: row.question ?? null,
|
|
78
|
+
details: row.details ?? null,
|
|
79
|
+
category: row.category ?? null,
|
|
80
|
+
urgency: row.urgency ?? null,
|
|
81
|
+
status: row.status ?? null,
|
|
82
|
+
note: row.Observaciones ?? null,
|
|
83
|
+
isForDoctorOffice: row.doctor_office === true,
|
|
84
|
+
isOpen: !CLOSED_REQUEST_STATUSES.includes(row.status),
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
const toCase = (row) => ({
|
|
88
|
+
recordId: row._recordId,
|
|
89
|
+
number: row.case_id ?? null,
|
|
90
|
+
createdAt: row.created || row._createdTime || null,
|
|
91
|
+
description: row.description ?? null,
|
|
92
|
+
grade: row.grade ?? null,
|
|
93
|
+
type: row.type ?? null,
|
|
94
|
+
status: row.status ?? null,
|
|
95
|
+
operationsStatus: row.status_operaciones ?? null,
|
|
96
|
+
followUp: row.seguimiento ?? null,
|
|
97
|
+
note: row.observations ?? null,
|
|
98
|
+
recommendation: row.recomendation_final ?? null,
|
|
99
|
+
isOpen: row.status_operaciones !== CLOSED_OPERATIONS_STATUS && !CLOSED_CASE_STATUSES.includes(row.status),
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const TASK_KINDS = {
|
|
103
|
+
requests: {
|
|
104
|
+
table: 'unresolved_questions',
|
|
105
|
+
fields: ['question_id', 'created_time', 'question', 'details', 'category', 'urgency', 'status', 'Observaciones', 'doctor_office'],
|
|
106
|
+
scope: fieldEquals('message_tag', 'request'),
|
|
107
|
+
toTask: toRequest,
|
|
108
|
+
writable: {
|
|
109
|
+
status: { field: 'status', options: REQUEST_STATUSES },
|
|
110
|
+
note: { field: 'Observaciones' },
|
|
111
|
+
},
|
|
112
|
+
},
|
|
113
|
+
cases: {
|
|
114
|
+
table: 'patient_cases',
|
|
115
|
+
fields: ['case_id', 'created', 'description', 'grade', 'type', 'status', 'status_operaciones', 'seguimiento', 'observations', 'recomendation_final'],
|
|
116
|
+
scope: null,
|
|
117
|
+
toTask: toCase,
|
|
118
|
+
writable: {
|
|
119
|
+
status: { field: 'status', options: CASE_STATUSES },
|
|
120
|
+
operationsStatus: { field: 'status_operaciones', options: OPERATIONS_STATUSES },
|
|
121
|
+
note: { field: 'observations' },
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const validWhatsappId = (code) => {
|
|
127
|
+
const whatsappId = String(code || '').trim();
|
|
128
|
+
if (!WHATSAPP_ID_RX.test(whatsappId)) throw httpError(400, 'A whatsapp:+<digits> patient code is required');
|
|
129
|
+
return whatsappId;
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const taskFilter = (kind, whatsappId) => {
|
|
133
|
+
const guard = `FIND('${escapeFormulaValue(whatsappId)},', ARRAYJOIN({whatsapp_id}, ',') & ',')`;
|
|
134
|
+
const { scope } = TASK_KINDS[kind];
|
|
135
|
+
return scope ? `AND(${guard}, ${scope})` : guard;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
const byOpenThenNewest = (a, b) => (b.isOpen - a.isOpen) || (b.createdAt || '').localeCompare(a.createdAt || '');
|
|
139
|
+
|
|
140
|
+
async function readTasks(kind, whatsappId) {
|
|
141
|
+
const { table, fields, toTask } = TASK_KINDS[kind];
|
|
142
|
+
const rows = await getRecordByFilter(Monitoreo_ID, table, taskFilter(kind, whatsappId), null, fields, true);
|
|
143
|
+
const tasks = rows.map(toTask).sort(byOpenThenNewest);
|
|
144
|
+
return { tasks: tasks.slice(0, MAX_ROWS), openCount: tasks.filter((task) => task.isOpen).length };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async function getPatientTasks(code) {
|
|
148
|
+
const whatsappId = validWhatsappId(code);
|
|
149
|
+
const [requests, cases] = await Promise.all([readTasks('requests', whatsappId), readTasks('cases', whatsappId)]);
|
|
150
|
+
return {
|
|
151
|
+
requests: requests.tasks,
|
|
152
|
+
cases: cases.tasks,
|
|
153
|
+
openCount: requests.openCount + cases.openCount,
|
|
154
|
+
options: { requestStatus: REQUEST_STATUSES, caseStatus: CASE_STATUSES, operationsStatus: OPERATIONS_STATUSES },
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function toAirtableFields(writable, changes) {
|
|
159
|
+
const entries = changes && typeof changes === 'object' && !Array.isArray(changes) ? Object.entries(changes) : [];
|
|
160
|
+
if (!entries.length) throw httpError(400, 'No changes provided');
|
|
161
|
+
return Object.fromEntries(entries.map(([key, value]) => {
|
|
162
|
+
if (!Object.hasOwn(writable, key)) throw httpError(400, `Field is not editable: ${key}`);
|
|
163
|
+
const { field, options } = writable[key];
|
|
164
|
+
const isValid = options ? options.includes(value) : typeof value === 'string' && value.length <= MAX_NOTE_LENGTH;
|
|
165
|
+
if (!isValid) throw httpError(400, `Invalid value for ${key}`);
|
|
166
|
+
return [field, value];
|
|
167
|
+
}));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async function updatePatientTask({ code, kind, recordId, changes, updatedBy, source, requestId }) {
|
|
171
|
+
const whatsappId = validWhatsappId(code);
|
|
172
|
+
if (!Object.hasOwn(TASK_KINDS, kind)) throw httpError(400, `Unknown task kind: ${kind}`);
|
|
173
|
+
if (!RECORD_ID_RX.test(String(recordId || ''))) throw httpError(400, 'A valid Airtable record id is required');
|
|
174
|
+
if (!updatedBy || !source) throw httpError(400, 'updatedBy and source are required');
|
|
175
|
+
|
|
176
|
+
const { table, toTask, writable } = TASK_KINDS[kind];
|
|
177
|
+
const fields = toAirtableFields(writable, changes);
|
|
178
|
+
const filter = `AND(${recordIdIn([recordId])}, ${taskFilter(kind, whatsappId)})`;
|
|
179
|
+
const [updated] = await updateRecordByFilter(Monitoreo_ID, table, filter, fields, whatsappId);
|
|
180
|
+
if (!updated) throw httpError(404, 'Task not found for this patient');
|
|
181
|
+
|
|
182
|
+
await logPatientChange({ code: whatsappId, updatedBy, source, requestId, changes: { table, recordId, fields } });
|
|
183
|
+
return toTask(toRow(updated));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
module.exports = {
|
|
187
|
+
getPatientTasks,
|
|
188
|
+
updatePatientTask,
|
|
189
|
+
};
|