@peopl-health/nexus 5.44.0-dev.7100 → 5.44.0-dev.7113

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,7 +6,6 @@ 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');
10
9
  const {
11
10
  getRecommendationCarousels,
12
11
  getRecommendationCarouselImage,
@@ -70,28 +69,6 @@ const getPatientCarePlanController = async (req, res) => {
70
69
  }
71
70
  };
72
71
 
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
-
95
72
  const getPatientRecommendationCarouselsController = async (req, res) => {
96
73
  try {
97
74
  const code = String(req.params.code || '').trim();
@@ -245,10 +222,8 @@ module.exports = {
245
222
  getPatientInfoController,
246
223
  getPatientTriageInfoController,
247
224
  getPatientCarePlanController,
248
- getPatientTasksController,
249
225
  getPatientRecommendationCarouselsController,
250
226
  getPatientRecommendationCarouselImageController,
251
227
  updatePatientController,
252
- updatePatientTaskController,
253
228
  logPatientChangeController,
254
229
  };
@@ -70,9 +70,7 @@ const patientRouteDefinitions = {
70
70
  'GET /:code': 'getPatientInfoController',
71
71
  'GET /triage/:code': 'getPatientTriageInfoController',
72
72
  'GET /careplan/:code': 'getPatientCarePlanController',
73
- 'GET /tasks/:code': 'getPatientTasksController',
74
73
  'PATCH /:code': 'updatePatientController',
75
- 'PATCH /tasks/:code/:kind/:recordId': 'updatePatientTaskController',
76
74
  'POST /audit-log': 'logPatientChangeController'
77
75
  };
78
76
 
@@ -214,11 +212,9 @@ const builtInControllers = {
214
212
  getPatientInfoController: patientController.getPatientInfoController,
215
213
  getPatientTriageInfoController: patientController.getPatientTriageInfoController,
216
214
  getPatientCarePlanController: patientController.getPatientCarePlanController,
217
- getPatientTasksController: patientController.getPatientTasksController,
218
215
  getPatientRecommendationCarouselsController: patientController.getPatientRecommendationCarouselsController,
219
216
  getPatientRecommendationCarouselImageController: patientController.getPatientRecommendationCarouselImageController,
220
217
  updatePatientController: patientController.updatePatientController,
221
- updatePatientTaskController: patientController.updatePatientTaskController,
222
218
  logPatientChangeController: patientController.logPatientChangeController,
223
219
 
224
220
  // Preset controllers
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.44.0-dev.7100",
3
+ "version": "5.44.0-dev.7113",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,189 +0,0 @@
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
- };