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

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.
@@ -205,16 +205,21 @@ function buildSymptomsMetadata({
205
205
  return parts.join('\n');
206
206
  }
207
207
 
208
- const OPEN_CASE_RULE = 'Son contexto de razonamiento, NO material de tarjeta: úsalos para entender la '
209
- + 'evolución, agrupar, afinar el diferencial y decidir qué caracterizar. Un caso abierto que el '
210
- + 'paciente NO reportó en este triaje nunca puede aparecer en name_short, en '
211
- + 'recommendation.symptoms_patient_facing, en symptoms ni en targeted_ctcae_terms: nombrarle un '
212
- + 'síntoma que hoy no reportó le hace pensar que nos equivocamos de paciente.';
208
+ const OPEN_CASE_RULE = 'Son contexto de razonamiento, NO evidencia de hoy ni material de tarjeta. Úsalos '
209
+ + 'para ver la evolución, agrupar y afinar el diferencial. Un caso no reportado hoy no va en '
210
+ + 'events_confirmed, no abre ni sostiene un red flag y nunca aparece en name_short, '
211
+ + 'recommendation.symptoms_patient_facing, symptoms ni targeted_ctcae_terms. \'improving\' o días sin '
212
+ + 'evidencia no significan resuelto: si ya se escaló y no hay cierre documentado, anótalo como '
213
+ + 'pendiente del equipo en el resumen interno (summary en el gate, summary_internal en el plan), nunca '
214
+ + 'como tarjeta ni urgencia.';
213
215
 
214
- const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo, nunca si el equipo respondió, qué '
215
- + 'indicó, ni si el problema se resolvió. Un motivo sin cambio desde una escalación de hace un día '
216
- + 'rara vez necesita un segundo envío; uno que sigue sin control días después de su escalación '
217
- + 'necesita uno de urgencia MAYOR, y reason_for_escalation debe decir cuál de los dos es.';
216
+ const ESCALATION_RULE = 'Registran sólo lo que se ENVIÓ al equipo: nunca si respondió, qué indicó ni si se '
217
+ + 'resolvió. Son contexto, no evidencia: una escalación pasada nunca crea, sostiene ni sube una urgencia '
218
+ + 'por sí sola. Si el mismo motivo se escaló en los últimos 14 días, no lo reenvíes si hoy mejoró, se negó '
219
+ + 'o no se reportó. Reenvíalo sólo con evidencia de hoy: si subió de grado o hay un signo de alarma nuevo, '
220
+ + 'decide la ruta por sus méritos; si sigue igual, aplica la política de reenvío de tus instrucciones. El '
221
+ + 'tiempo transcurrido nunca justifica por sí solo una ruta mayor. En '
222
+ + 'reason_for_escalation cita la evidencia de hoy y di si es nuevo, empeoramiento o persistencia.';
218
223
 
219
224
  function buildOpenCaseBlock(openCases = []) {
220
225
  if (!openCases.length) return 'Sin casos clínicos abiertos.';
@@ -3,6 +3,13 @@ const { termKey } = require('../../fhir/utils/normalizeUtils');
3
3
  const { matchTerm, entriesOfKeys } = require('../../fhir/helpers/termMatchHelper');
4
4
  const { getCtcaeCatalog } = require('../stores/CtcaeCatalog');
5
5
 
6
+ const CRITICAL_FIELD_GAPS = {
7
+ functional_impact: 'la interferencia del PRO-CTCAE es una escala de 5 puntos, no la limitación de '
8
+ + 'actividades instrumentales/autocuidado que exige la cláusula',
9
+ intensity_nrs: 'la intensidad del PRO-CTCAE es verbal, no una escala 0–10',
10
+ };
11
+ const QUESTIONNAIRE_GAP = 'el cuestionario no pregunta este dato';
12
+
6
13
  function candidateKeys(catalog, term) {
7
14
  const keys = [termKey(term)];
8
15
  const ctcaeV5 = getSymptom(catalog, term)?.ctcae_v5;
@@ -48,8 +55,9 @@ function renderLadder(ladder, grade, { indent = ' ' } = {}) {
48
55
  if (ladder.criticalField) {
49
56
  lines.push(
50
57
  `${indent}Dato que decide el grado de ${ladder.ctcaeTerm} (critical_field): ${ladder.criticalField}. `
51
- + 'Si no está entre las respuestas de arriba, el grado NO está establecido por el cuestionario: '
52
- + 'pide caracterización en vez de asumirlo.',
58
+ + `No capturado por el cuestionario (${CRITICAL_FIELD_GAPS[ladder.criticalField] || QUESTIONNAIRE_GAP}): `
59
+ + 'pide caracterización en vez de asumirlo; el grado es una aproximación del cuestionario; no lo '
60
+ + 'presentes como grado CTCAE ni lo uses para confirmar un umbral.',
53
61
  );
54
62
  }
55
63
  return lines;
@@ -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
  };
@@ -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
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.44.0-dev.7113",
3
+ "version": "5.44.1",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",