@peopl-health/nexus 5.57.0-dev.10057 → 5.57.0-dev.10072

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.
@@ -4,7 +4,7 @@ const { logger } = require('../../utils/logger');
4
4
 
5
5
  const definition = {
6
6
  'name': 'reportUnresolvedRequestv2',
7
- 'description': '**Does:** Escalates ADMINISTRATIVE / OPERATIVE matters — and non-clinical referrals to other services (psico-oncología, paliativos, non-oncology medical) — to the appropriate team queue. Records what was left pending, why it needs the team, operational urgency, and what was already communicated to the patient. It carries NO clinical-escalation semantics for the patient\'s oncology condition — those go to `reportMedicalEscalation`.\n\n**Required inputs:** `unresolved_question`, `category` (operational routing — REQUIRED for the queue), `urgency` (`routine` | `soon` | `urgent`; default `routine`), `escalation_details`, `resolution_attempted` (bool), `for_doctor_office` (bool: `true` only for a request your instructions route to the treating doctor or their office, otherwise `false`).\n\n**When to call:**\n- Administrative matter the team has to act on (insurance / authorisations / letters / transport), including scheduling or rescheduling a session of the AUNA accompaniment program (psico-oncología, nutrición).\n- Patient request that needs human (non-clinical) intervention.\n- Outside the agent\'s scope or knowledge (non-clinical).\n- A routine referral (psico-oncología, paliativos).\n- Callback from a specific team member (`category=contact_team_member`), or enrollment in a program / workshop / support group (`category=program_enrollment`).\n- Something the patient\'s own doctor or their office has to answer or do — a report or letter, a prescription or premedication that needs the doctor\'s indication, a non-urgent question or update for the doctor: keep the category that describes it and set `for_doctor_office: true` when your instructions route it to that office. Asking for a prescription or an indication is an administrative request, not a treatment concern; a symptom or a problem with the treatment still goes to `reportMedicalEscalation`. Never tell the patient to write to the doctor or the secretary themselves.\nAlways pair with a `DeliverPatientMessage` acknowledging the escalation.\n\n**When NOT to call:**\n- ANY medical escalation — confirmed emergency, same-day evaluation, OR an asynchronous clinical concern (a symptom persisting >72h, a worrying trend, a treatment concern, stale clinical context) — use `reportMedicalEscalation` (urgency_level stat | asap | urgent | routine).\n- Active mental-health crisis — use `reportCrisis`.\n- Patient SHARED results / values / files — use `reportResultsReceived`.\n- Booking, rescheduling or cancelling a doctor appointment, a treatment session (chemo / radiotherapy / infusion) or a lab / imaging study — these are not booked through this channel; answer the patient directly with where to book, as your instructions describe. When that turn carries no clinical content, declare it with `non_clinical_request` in `extractClinicalInfo`.\n- Questions answerable from the CTCAE catalog or skill protocols — answer directly.\n\n**Returns:** an ack ({} on the happy path). Out-of-enum `urgency`/`category` are coerced (to `routine`/`other`) and disclosed via `coerced_urgency`/`coerced_category`; inputs over 500 chars are truncated and disclosed via `truncated_fields`. If the escalation could not be queued to the team it comes back with `queued: false` — do NOT tell the patient the team was notified in that case; acknowledge and say you are still working on it.\n\n**Side effects:** Emits `OUT_OF_SCOPE_LOGGED` to the appropriate team queue.',
7
+ 'description': '**Does:** Escalates ADMINISTRATIVE / OPERATIVE matters — and non-clinical referrals to other services (psico-oncología, paliativos, non-oncology medical) — to the appropriate team queue. Records what was left pending, why it needs the team, operational urgency, and what was already communicated to the patient. It carries NO clinical-escalation semantics for the patient\'s oncology condition — those go to `reportMedicalEscalation`.\n\n**Required inputs:** `unresolved_question`, `category` (operational routing — REQUIRED for the queue), `urgency` (`routine` | `soon` | `urgent`; default `routine`), `escalation_details`, `resolution_attempted` (bool), `for_doctor_office` (bool: `true` only for a request your instructions route to the treating doctor or their office, otherwise `false`).\n\n**When to call:**\n- Administrative matter the team has to act on (insurance / authorisations / letters / transport), including scheduling or rescheduling a session of the AUNA accompaniment program (psico-oncología, nutrición).\n- Patient request that needs human (non-clinical) intervention.\n- Outside the agent\'s scope or knowledge (non-clinical).\n- A routine referral (psico-oncología, paliativos).\n- Callback from a specific team member (`category=contact_team_member`), or enrollment in a program / workshop / support group (`category=program_enrollment`).\n- Something the patient\'s own doctor or their office has to answer or do that is not symptom care — a report, letter or insurance form, a prescription or premedication the doctor already indicated, a payment receipt, an administrative question for the office: keep the category that describes it and set `for_doctor_office: true` when your instructions route it to that office. Asking for a prescription or an indication the doctor already gave is an administrative request, not a treatment concern. Symptom management belongs to the accompaniment program, not to the office: a symptom, a side effect, whether or how to take a medication, or a prescription or study the patient wants because of a symptom still goes to `reportMedicalEscalation` — never here with `for_doctor_office: true` — even when the patient asks for their doctor to see, review or answer it. A study, result, image or file the patient shares still goes to `reportResultsReceived`, even when they ask for it to reach the doctor. Never tell the patient to write to the doctor or the secretary themselves.\nAlways pair with a `DeliverPatientMessage` acknowledging the escalation.\n\n**When NOT to call:**\n- ANY medical escalation — confirmed emergency, same-day evaluation, OR an asynchronous clinical concern (a symptom persisting >72h, a worrying trend, a treatment concern, stale clinical context) — use `reportMedicalEscalation` (urgency_level stat | asap | urgent | routine).\n- Active mental-health crisis — use `reportCrisis`.\n- Patient SHARED results / values / files — use `reportResultsReceived`.\n- Booking, rescheduling or cancelling a doctor appointment, a treatment session (chemo / radiotherapy / infusion) or a lab / imaging study — these are not booked through this channel; answer the patient directly with where to book, as your instructions describe. When that turn carries no clinical content, declare it with `non_clinical_request` in `extractClinicalInfo`.\n- Questions answerable from the CTCAE catalog or skill protocols — answer directly.\n\n**Returns:** an ack ({} on the happy path). Out-of-enum `urgency`/`category` are coerced (to `routine`/`other`) and disclosed via `coerced_urgency`/`coerced_category`; inputs over 500 chars are truncated and disclosed via `truncated_fields`. If the escalation could not be queued to the team it comes back with `queued: false` — do NOT tell the patient the team was notified in that case; acknowledge and say you are still working on it.\n\n**Side effects:** Emits `OUT_OF_SCOPE_LOGGED` to the appropriate team queue.',
8
8
  'strict': true,
9
9
  'parameters': {
10
10
  'type': 'object',
@@ -49,7 +49,7 @@ const definition = {
49
49
  'anyOf': [
50
50
  {
51
51
  'type': 'boolean',
52
- 'description': 'true cuando el pendiente lo tiene que responder o hacer el médico tratante o su consultorio (un informe o carta, una receta o premedicación que necesita su indicación, una pregunta o un aviso no urgente para el médico) y tus instrucciones lo mandan a ese consultorio. La categoría sigue describiendo el pendiente.'
52
+ 'description': 'true cuando el pendiente lo tiene que responder o hacer el médico tratante o su consultorio y no es manejo de síntomas (un informe, carta o formato de aseguradora, una receta o premedicación que el médico ya indicó, un comprobante de pago, una pregunta administrativa para el consultorio) y tus instrucciones lo mandan a ese consultorio. Un síntoma, un efecto adverso, una duda sobre si o cómo tomar un medicamento, o una receta o estudio que el paciente pide por un síntoma son del programa de acompañamiento y van por `reportMedicalEscalation`, aunque el paciente pida que lo vea o le conteste su médico. La categoría sigue describiendo el pendiente.'
53
53
  },
54
54
  {
55
55
  'type': 'null'
@@ -0,0 +1,55 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+
4
+ const {
5
+ listOfficePatients,
6
+ readOfficeMessages,
7
+ sendOfficeMessage,
8
+ } = require('../services/officeAssistantService');
9
+
10
+ const respondWithError = (res, error, action, context) => {
11
+ logger.error(`Error ${action}:`, {
12
+ error: redactDirectIdentifiers(String(error.message || '')),
13
+ stack: redactDirectIdentifiers(String(error.stack || '')),
14
+ ...context,
15
+ });
16
+ res.status(error.statusCode || 500).json({ success: false, error: error.message });
17
+ };
18
+
19
+ const listOfficePatientsController = async (req, res) => {
20
+ try {
21
+ const patients = await listOfficePatients({ requestedBy: req.query.requestedBy });
22
+ res.status(200).json({ success: true, patients });
23
+ } catch (error) {
24
+ respondWithError(res, error, 'listing office patients', {});
25
+ }
26
+ };
27
+
28
+ const getOfficeMessagesController = async (req, res) => {
29
+ try {
30
+ const conversation = await readOfficeMessages({
31
+ requestedBy: req.query.requestedBy,
32
+ code: req.params.code,
33
+ limit: req.query.limit,
34
+ });
35
+ res.status(200).json({ success: true, ...conversation });
36
+ } catch (error) {
37
+ respondWithError(res, error, 'reading office messages', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
38
+ }
39
+ };
40
+
41
+ const sendOfficeMessageController = async (req, res) => {
42
+ try {
43
+ const { triggeredBy, text, clientMessageId } = req.body || {};
44
+ const delivery = await sendOfficeMessage({ requestedBy: triggeredBy, code: req.params.code, text, clientMessageId });
45
+ res.status(201).json({ success: true, ...delivery });
46
+ } catch (error) {
47
+ respondWithError(res, error, 'sending office message', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
48
+ }
49
+ };
50
+
51
+ module.exports = {
52
+ listOfficePatientsController,
53
+ getOfficeMessagesController,
54
+ sendOfficeMessageController,
55
+ };
@@ -136,6 +136,12 @@ const escalationReviewRouteDefinitions = {
136
136
  'POST /:id/case-sync': 'syncEscalationReviewCaseController'
137
137
  };
138
138
 
139
+ const officeAssistantRouteDefinitions = {
140
+ 'GET /patients': 'listOfficePatientsController',
141
+ 'GET /patients/:code/messages': 'getOfficeMessagesController',
142
+ 'POST /patients/:code/messages': 'sendOfficeMessageController'
143
+ };
144
+
139
145
  const createRouter = (routeDefinitions, controllers) => {
140
146
  const router = express.Router();
141
147
 
@@ -174,6 +180,7 @@ const dashboardController = require('../controllers/dashboardController');
174
180
  const prescriptionController = require('../controllers/prescriptionController');
175
181
  const traceController = require('../controllers/traceController');
176
182
  const escalationReviewController = require('../controllers/escalationReviewController');
183
+ const officeAssistantController = require('../controllers/officeAssistantController');
177
184
 
178
185
  const builtInControllers = {
179
186
  // Assistant controllers
@@ -299,7 +306,12 @@ const builtInControllers = {
299
306
  sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
300
307
  closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
301
308
  cancelEscalationReviewController: escalationReviewController.cancelEscalationReviewController,
302
- syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
309
+ syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController,
310
+
311
+ // Office assistant controllers
312
+ listOfficePatientsController: officeAssistantController.listOfficePatientsController,
313
+ getOfficeMessagesController: officeAssistantController.getOfficeMessagesController,
314
+ sendOfficeMessageController: officeAssistantController.sendOfficeMessageController
303
315
  };
304
316
 
305
317
  const setupDefaultRoutes = (app) => {
@@ -323,6 +335,7 @@ const setupDefaultRoutes = (app) => {
323
335
  app.use('/api/dashboard', createRouter(dashboardRouteDefinitions, builtInControllers));
324
336
  app.use('/api/trace', createRouter(traceRouteDefinitions, builtInControllers));
325
337
  app.use('/api/escalation-review', createRouter(escalationReviewRouteDefinitions, builtInControllers));
338
+ app.use('/api/office', createRouter(officeAssistantRouteDefinitions, builtInControllers));
326
339
  };
327
340
 
328
341
  module.exports = {
@@ -341,6 +354,7 @@ module.exports = {
341
354
  dashboardRoutes: dashboardRouteDefinitions,
342
355
  traceRoutes: traceRouteDefinitions,
343
356
  escalationReviewRoutes: escalationReviewRouteDefinitions,
357
+ officeAssistantRoutes: officeAssistantRouteDefinitions,
344
358
 
345
359
  builtInControllers,
346
360
  createRouter,
@@ -1,7 +1,8 @@
1
1
  const mongoose = require('mongoose');
2
2
 
3
3
  const runtimeConfig = require('../config/runtimeConfig');
4
- const { httpError } = require('../utils/httpErrorUtils');
4
+ const { httpError, requiredText } = require('../utils/httpErrorUtils');
5
+ const { inlineOf } = require('../utils/coercionUtils');
5
6
  const { logger } = require('../utils/logger');
6
7
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
8
  const { mexicoStamp } = require('../utils/dateUtils');
@@ -51,12 +52,6 @@ const patientCodeOf = (code) => {
51
52
  return patientCode;
52
53
  };
53
54
 
54
- const requiredText = (value, name) => {
55
- const text = String(value ?? '').trim();
56
- if (!text) throw httpError(400, `${name} is required`);
57
- return text;
58
- };
59
-
60
55
  const optionalText = (value) => (value == null ? null : String(value));
61
56
 
62
57
  const reviewIdOf = (id) => {
@@ -305,8 +300,6 @@ const URGENCY_LABELS = {
305
300
  stat: 'inmediata', asap: 'lo antes posible', urgent: 'urgente', routine: 'rutina',
306
301
  };
307
302
 
308
- const inlineOf = (value) => String(Array.isArray(value) ? value[0] ?? '' : value ?? '').trim();
309
-
310
303
  function doctorHeader(review, patient) {
311
304
  const name = inlineOf(patient?.name);
312
305
  const phone = review.patientCode.replace(/^whatsapp:/, '');
@@ -0,0 +1,156 @@
1
+ const { Estado_General_ID, Monitoreo_ID } = require('../config/airtableConfig');
2
+
3
+ const { httpError, requiredText } = require('../utils/httpErrorUtils');
4
+ const { inlineOf } = require('../utils/coercionUtils');
5
+ const { logger } = require('../utils/logger');
6
+ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
+ const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
8
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
9
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
10
+ const { sendMessage } = require('../core/NexusMessaging');
11
+
12
+ const { getRecordByFilter } = require('./airtableService');
13
+ const { getMessages } = require('./messageService');
14
+ const { getPatientInformation } = require('./patientService');
15
+
16
+ const ASSISTANT_FIELDS = ['email', 'doctor_match', 'office_label', 'template_content_sid'];
17
+ const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
18
+ const HIDDEN_ORIGINS = ['system', 'instruction'];
19
+ const DEFAULT_MESSAGE_LIMIT = 30;
20
+ const MAX_MESSAGE_LIMIT = 50;
21
+ const MAX_TEXT_LENGTH = 1500;
22
+ const MAX_TEMPLATE_TEXT_LENGTH = 800;
23
+
24
+ async function getOfficeAssistant(email) {
25
+ const normalized = String(email ?? '').trim().toLowerCase();
26
+ if (!normalized) return null;
27
+
28
+ const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {active})`;
29
+ const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, ASSISTANT_FIELDS, true) || [];
30
+ const doctor = inlineOf(assistant?.doctor_match);
31
+ const label = inlineOf(assistant?.office_label);
32
+ if (!doctor || !label) return null;
33
+
34
+ return {
35
+ email: normalized,
36
+ doctor,
37
+ label,
38
+ templateContentSid: inlineOf(assistant.template_content_sid) || null,
39
+ };
40
+ }
41
+
42
+ async function requireOfficeAssistant(email) {
43
+ const assistant = await getOfficeAssistant(email);
44
+ if (!assistant) throw httpError(403, 'Only an active office assistant can use the office view');
45
+ return assistant;
46
+ }
47
+
48
+ async function officePatientCode(assistant, code) {
49
+ const patientCode = ensureWhatsAppFormat(String(code ?? '').trim());
50
+ if (!PATIENT_CODE.test(patientCode)) throw httpError(400, 'A valid WhatsApp ID is required');
51
+
52
+ const patient = await getPatientInformation(patientCode);
53
+ if (!patient || inlineOf(patient.doctor) !== assistant.doctor) throw httpError(404, 'Patient not found');
54
+ return patientCode;
55
+ }
56
+
57
+ async function listOfficePatients({ requestedBy }) {
58
+ const assistant = await requireOfficeAssistant(requestedBy);
59
+ const patients = await getRecordByFilter(Estado_General_ID, 'estado_general', fieldEquals('doctor', assistant.doctor), undefined, PATIENT_FIELDS) || [];
60
+
61
+ return patients
62
+ .filter((patient) => inlineOf(patient.doctor) === assistant.doctor && inlineOf(patient.whatsapp_id))
63
+ .map((patient) => ({ code: inlineOf(patient.whatsapp_id), name: inlineOf(patient.name) || null }))
64
+ .sort((a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''), 'es'));
65
+ }
66
+
67
+ const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
68
+
69
+ const officeVisibleQuery = (patientCode, assistant) => ({
70
+ numero: patientCode,
71
+ group_id: null,
72
+ origin: { $nin: HIDDEN_ORIGINS },
73
+ $or: [
74
+ { from_me: false },
75
+ { from_me: true, triggeredBy: assistant.email },
76
+ { from_me: true, plainBody: { $regex: `^${escapeRegex(assistant.label)}:` } },
77
+ ],
78
+ });
79
+
80
+ async function readOfficeMessages({ requestedBy, code, limit }) {
81
+ const assistant = await requireOfficeAssistant(requestedBy);
82
+ const patientCode = await officePatientCode(assistant, code);
83
+ const size = Math.min(Math.max(parseInt(limit, 10) || DEFAULT_MESSAGE_LIMIT, 1), MAX_MESSAGE_LIMIT);
84
+
85
+ const [messages, inWindow] = await Promise.all([
86
+ getMessages(officeVisibleQuery(patientCode, assistant), { sort: { createdAt: -1 }, limit: size }),
87
+ isWithin24HourWindow(patientCode),
88
+ ]);
89
+
90
+ return {
91
+ code: patientCode,
92
+ inWindow,
93
+ messages: messages.reverse().map((message) => ({
94
+ id: String(message._id),
95
+ body: message.plainBody ?? '',
96
+ mediaType: message.media?.mediaType ?? null,
97
+ sender: message.from_me ? 'office' : 'patient',
98
+ createdAt: message.createdAt,
99
+ })),
100
+ };
101
+ }
102
+
103
+ function officeMessage({ assistant, patientCode, text, inWindow }) {
104
+ if (inWindow) {
105
+ if (text.length > MAX_TEXT_LENGTH) throw httpError(422, `The message exceeds ${MAX_TEXT_LENGTH} characters`);
106
+ return { code: patientCode, body: `${assistant.label}: ${text}` };
107
+ }
108
+
109
+ const templateText = text.replace(/\s+/g, ' ').trim();
110
+ if (templateText.length > MAX_TEMPLATE_TEXT_LENGTH) {
111
+ throw httpError(422, `Outside the 24-hour window the message is sent as a template and cannot exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters`);
112
+ }
113
+ if (!assistant.templateContentSid) throw httpError(503, 'The office template is not configured; the patient is outside the 24-hour window');
114
+ return {
115
+ code: patientCode,
116
+ body: `${assistant.label}: ${templateText}`,
117
+ contentSid: assistant.templateContentSid,
118
+ variables: { 1: templateText },
119
+ };
120
+ }
121
+
122
+ async function sendOfficeMessage({ requestedBy, code, text, clientMessageId }) {
123
+ const assistant = await requireOfficeAssistant(requestedBy);
124
+ const patientCode = await officePatientCode(assistant, code);
125
+ const messageText = requiredText(text, 'text');
126
+ const messageKey = requiredText(clientMessageId, 'clientMessageId');
127
+
128
+ const inWindow = await isWithin24HourWindow(patientCode);
129
+ const message = {
130
+ ...officeMessage({ assistant, patientCode, text: messageText, inWindow }),
131
+ triggeredBy: assistant.email,
132
+ idempotencyKey: `office:${patientCode}:${messageKey}`,
133
+ };
134
+
135
+ const result = await sendMessage(message);
136
+ if (result?.status === 'duplicate_suppressed' && !result.completed) {
137
+ throw httpError(409, 'This message is already being sent');
138
+ }
139
+ if (!result?.success && !result?.completed) throw httpError(502, 'The WhatsApp message could not be sent');
140
+
141
+ const transport = inWindow ? 'text' : 'template';
142
+ logger.info('[Office] message sent', {
143
+ assistant: assistant.email,
144
+ code: redactDirectIdentifiers(patientCode),
145
+ transport,
146
+ duplicate: result?.duplicate === true,
147
+ });
148
+ return { transport, messageId: result?.messageId || null, duplicate: result?.duplicate === true };
149
+ }
150
+
151
+ module.exports = {
152
+ getOfficeAssistant,
153
+ listOfficePatients,
154
+ readOfficeMessages,
155
+ sendOfficeMessage,
156
+ };
@@ -2,7 +2,8 @@ const str = (value) => (typeof value === 'string' ? value : '');
2
2
  const arr = (value) => (Array.isArray(value) ? value : []);
3
3
  const strList = (value) => arr(value).map(str).map((item) => item.trim()).filter(Boolean);
4
4
  const firstOf = (value) => (Array.isArray(value) ? value[0] : value);
5
+ const inlineOf = (value) => String(firstOf(value) ?? '').trim();
5
6
 
6
7
  module.exports = {
7
- str, arr, strList, firstOf,
8
+ str, arr, strList, firstOf, inlineOf,
8
9
  };
@@ -1,3 +1,9 @@
1
1
  const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
2
2
 
3
- module.exports = { httpError };
3
+ const requiredText = (value, name) => {
4
+ const text = String(value ?? '').trim();
5
+ if (!text) throw httpError(400, `${name} is required`);
6
+ return text;
7
+ };
8
+
9
+ module.exports = { httpError, requiredText };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.0-dev.10057",
3
+ "version": "5.57.0-dev.10072",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",