@peopl-health/nexus 5.44.0-dev.7113 → 5.44.0
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.
|
@@ -6,6 +6,7 @@ const { isAllowedUrl, redactDirectIdentifiers } = require('../utils/sanitizerUti
|
|
|
6
6
|
const { getPatientInformation, updatePatientInformation, logPatientChange } = require('../services/patientService');
|
|
7
7
|
const { getTriageHistory } = require('../services/triageHistoryService');
|
|
8
8
|
const { getCarePlanHistory } = require('../services/carePlanHistoryService');
|
|
9
|
+
const { getPatientTasks, updatePatientTask } = require('../services/patientTaskService');
|
|
9
10
|
const {
|
|
10
11
|
getRecommendationCarousels,
|
|
11
12
|
getRecommendationCarouselImage,
|
|
@@ -69,6 +70,28 @@ const getPatientCarePlanController = async (req, res) => {
|
|
|
69
70
|
}
|
|
70
71
|
};
|
|
71
72
|
|
|
73
|
+
const getPatientTasksController = async (req, res) => {
|
|
74
|
+
try {
|
|
75
|
+
const tasks = await getPatientTasks(req.params.code);
|
|
76
|
+
res.status(200).json({ success: true, ...tasks });
|
|
77
|
+
} catch (error) {
|
|
78
|
+
logger.error('Error fetching patient tasks:', { error: error.message, code: req.params?.code });
|
|
79
|
+
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const updatePatientTaskController = async (req, res) => {
|
|
84
|
+
try {
|
|
85
|
+
const { code, kind, recordId } = req.params;
|
|
86
|
+
const { changes, updatedBy, source } = req.body || {};
|
|
87
|
+
const task = await updatePatientTask({ code, kind, recordId, changes, updatedBy, source, requestId: req.requestId });
|
|
88
|
+
res.status(200).json({ success: true, task });
|
|
89
|
+
} catch (error) {
|
|
90
|
+
logger.error('Error updating patient task:', { error: error.message, code: req.params?.code, kind: req.params?.kind, recordId: req.params?.recordId });
|
|
91
|
+
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
72
95
|
const getPatientRecommendationCarouselsController = async (req, res) => {
|
|
73
96
|
try {
|
|
74
97
|
const code = String(req.params.code || '').trim();
|
|
@@ -222,8 +245,10 @@ module.exports = {
|
|
|
222
245
|
getPatientInfoController,
|
|
223
246
|
getPatientTriageInfoController,
|
|
224
247
|
getPatientCarePlanController,
|
|
248
|
+
getPatientTasksController,
|
|
225
249
|
getPatientRecommendationCarouselsController,
|
|
226
250
|
getPatientRecommendationCarouselImageController,
|
|
227
251
|
updatePatientController,
|
|
252
|
+
updatePatientTaskController,
|
|
228
253
|
logPatientChangeController,
|
|
229
254
|
};
|
package/lib/routes/index.js
CHANGED
|
@@ -70,7 +70,9 @@ const patientRouteDefinitions = {
|
|
|
70
70
|
'GET /:code': 'getPatientInfoController',
|
|
71
71
|
'GET /triage/:code': 'getPatientTriageInfoController',
|
|
72
72
|
'GET /careplan/:code': 'getPatientCarePlanController',
|
|
73
|
+
'GET /tasks/:code': 'getPatientTasksController',
|
|
73
74
|
'PATCH /:code': 'updatePatientController',
|
|
75
|
+
'PATCH /tasks/:code/:kind/:recordId': 'updatePatientTaskController',
|
|
74
76
|
'POST /audit-log': 'logPatientChangeController'
|
|
75
77
|
};
|
|
76
78
|
|
|
@@ -212,9 +214,11 @@ const builtInControllers = {
|
|
|
212
214
|
getPatientInfoController: patientController.getPatientInfoController,
|
|
213
215
|
getPatientTriageInfoController: patientController.getPatientTriageInfoController,
|
|
214
216
|
getPatientCarePlanController: patientController.getPatientCarePlanController,
|
|
217
|
+
getPatientTasksController: patientController.getPatientTasksController,
|
|
215
218
|
getPatientRecommendationCarouselsController: patientController.getPatientRecommendationCarouselsController,
|
|
216
219
|
getPatientRecommendationCarouselImageController: patientController.getPatientRecommendationCarouselImageController,
|
|
217
220
|
updatePatientController: patientController.updatePatientController,
|
|
221
|
+
updatePatientTaskController: patientController.updatePatientTaskController,
|
|
218
222
|
logPatientChangeController: patientController.logPatientChangeController,
|
|
219
223
|
|
|
220
224
|
// Preset controllers
|
|
@@ -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
|
+
};
|