@peopl-health/nexus 5.57.0-dev.10058 → 5.57.0-dev.10092
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.
- package/lib/adapters/BaileysProvider.js +3 -2
- package/lib/adapters/TwilioProvider.js +1 -1
- package/lib/clinical/memory/DefaultMemoryManager.js +5 -3
- package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +2 -2
- package/lib/controllers/officeAssistantController.js +55 -0
- package/lib/core/NexusMessaging.js +8 -2
- package/lib/helpers/caregiverHelper.js +101 -0
- package/lib/helpers/conversationWindowHelper.js +2 -2
- package/lib/index.d.ts +2 -0
- package/lib/jobs/TemplateApprovalJob.js +3 -0
- package/lib/models/messageModel.js +2 -0
- package/lib/routes/index.js +15 -1
- package/lib/services/escalationReviewService.js +2 -9
- package/lib/services/heldMessageService.js +9 -7
- package/lib/services/officeAssistantService.js +156 -0
- package/lib/storage/MongoStorage.js +5 -1
- package/lib/utils/coercionUtils.js +2 -1
- package/lib/utils/httpErrorUtils.js +7 -1
- package/package.json +1 -1
|
@@ -67,7 +67,8 @@ class BaileysProvider extends MessageProvider {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
formatCode(code) {
|
|
70
|
-
|
|
70
|
+
if (code.includes('@s.whatsapp.net')) return code;
|
|
71
|
+
return `${code.replace(/^whatsapp:/, '').replace(/^\+/, '')}@s.whatsapp.net`;
|
|
71
72
|
}
|
|
72
73
|
|
|
73
74
|
formatMessage(message) {
|
|
@@ -89,7 +90,7 @@ class BaileysProvider extends MessageProvider {
|
|
|
89
90
|
throw new Error('Message or file URL is required');
|
|
90
91
|
}
|
|
91
92
|
|
|
92
|
-
const formattedCode = this.formatCode(code);
|
|
93
|
+
const formattedCode = this.formatCode(messageData.contactCode || code);
|
|
93
94
|
let sendOptions = {};
|
|
94
95
|
let formattedMessage = this.formatMessage(body || '');
|
|
95
96
|
|
|
@@ -71,7 +71,7 @@ class TwilioProvider extends MessageProvider {
|
|
|
71
71
|
const { code, body, fileUrl, fileType, variables, contentSid } = messageData;
|
|
72
72
|
|
|
73
73
|
const formattedFrom = ensureWhatsAppFormat(this.whatsappNumber);
|
|
74
|
-
const formattedCode = ensureWhatsAppFormat(code);
|
|
74
|
+
const formattedCode = ensureWhatsAppFormat(messageData.contactCode || code);
|
|
75
75
|
|
|
76
76
|
if (!formattedFrom || !formattedCode) {
|
|
77
77
|
throw new Error('Invalid sender or recipient number');
|
|
@@ -24,6 +24,7 @@ const DEFAULT_CONTEXT_ANCHOR_STEP = 50;
|
|
|
24
24
|
const OPERATOR_TURN_PREFIX = '[sistema]';
|
|
25
25
|
const TEAM_TURN_PREFIX = '[equipo]';
|
|
26
26
|
const PLATFORM_TURN_PREFIX = '[plataforma]';
|
|
27
|
+
const CAREGIVER_TURN_PREFIX = '[cuidador]';
|
|
27
28
|
const CURRENT_TURN_GAP_MS = 15 * 60 * 1000;
|
|
28
29
|
const CURRENT_TURN_MAX_MESSAGES = 15;
|
|
29
30
|
const OUTBOUND_TAIL_MAX_MESSAGES = 10;
|
|
@@ -95,9 +96,9 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
95
96
|
});
|
|
96
97
|
|
|
97
98
|
const turnLines = currentTurn
|
|
98
|
-
.flatMap(msg => formatMessage(msg)
|
|
99
|
-
|
|
100
|
-
.replace(TURN_TIMESTAMP_PREFIX_RX, ''))
|
|
99
|
+
.flatMap(msg => formatMessage(msg)
|
|
100
|
+
.filter(Boolean)
|
|
101
|
+
.map(line => `${this._speakerPrefix(msg, 'user')}${line.replace(TURN_TIMESTAMP_PREFIX_RX, '')}`))
|
|
101
102
|
.map(escapePatientMessageMarkers);
|
|
102
103
|
if (turnLines.length) {
|
|
103
104
|
context.push({
|
|
@@ -173,6 +174,7 @@ class DefaultMemoryManager extends MemoryManager {
|
|
|
173
174
|
|
|
174
175
|
_speakerPrefix(msg, role) {
|
|
175
176
|
if (this._isInlineOperatorTurn(msg, role)) return `${OPERATOR_TURN_PREFIX} `;
|
|
177
|
+
if (msg.origin === 'patient' && msg.contact_role === 'caregiver') return `${CAREGIVER_TURN_PREFIX} `;
|
|
176
178
|
if (msg.origin !== 'whatsapp_platform') return '';
|
|
177
179
|
// The send API records the authenticated sender; without one the send was automated.
|
|
178
180
|
return msg.triggeredBy ? `${TEAM_TURN_PREFIX} ` : `${PLATFORM_TURN_PREFIX} `;
|
|
@@ -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
|
|
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
|
|
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
|
+
};
|
|
@@ -16,6 +16,7 @@ const { Thread } = require('../models/threadModel');
|
|
|
16
16
|
|
|
17
17
|
const { storeRunMetrics } = require('../helpers/metricsHelper');
|
|
18
18
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
19
|
+
const { remapCaregiverSender, replyContactFor } = require('../helpers/caregiverHelper');
|
|
19
20
|
const { triggerTemplateRecovery } = require('../helpers/templateRecoveryHelper');
|
|
20
21
|
const { prepareMessageMedia } = require('../helpers/mediaHelper');
|
|
21
22
|
const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
|
|
@@ -392,7 +393,7 @@ class NexusMessaging {
|
|
|
392
393
|
if (rendered) messageData.body = rendered;
|
|
393
394
|
}
|
|
394
395
|
|
|
395
|
-
if (this._needsTemplateRoute(messageData) && !(await isWithin24HourWindow(messageData.code))) {
|
|
396
|
+
if (this._needsTemplateRoute(messageData) && !(await isWithin24HourWindow(messageData.code, { contactCode: messageData.contactCode }))) {
|
|
396
397
|
return this._routeThroughTemplateRecovery(messageData);
|
|
397
398
|
}
|
|
398
399
|
|
|
@@ -461,6 +462,10 @@ class NexusMessaging {
|
|
|
461
462
|
}
|
|
462
463
|
|
|
463
464
|
async sendAssistantReply(messageData) {
|
|
465
|
+
if (!messageData.contactCode && !messageData.preemptiveWindowRoute && !messageData.outreachStartedAt) {
|
|
466
|
+
const contact = await replyContactFor(messageData.code);
|
|
467
|
+
if (contact) messageData = { ...messageData, ...contact };
|
|
468
|
+
}
|
|
464
469
|
if (messageData.outreachStartedAt) {
|
|
465
470
|
const patientActivity = await getMessages({
|
|
466
471
|
numero: messageData.code,
|
|
@@ -562,6 +567,7 @@ class NexusMessaging {
|
|
|
562
567
|
*/
|
|
563
568
|
|
|
564
569
|
async processIncomingMessage(messageData, { onSaved = null } = {}) {
|
|
570
|
+
await remapCaregiverSender(messageData);
|
|
565
571
|
const chatId = messageData.code;
|
|
566
572
|
|
|
567
573
|
if (chatId) {
|
|
@@ -590,7 +596,7 @@ class NexusMessaging {
|
|
|
590
596
|
logger.error('[processIncomingMessage] Contingency stand-down failed', { code: chatId, error: error.message })
|
|
591
597
|
);
|
|
592
598
|
}
|
|
593
|
-
await releaseHeldMessages(chatId).catch(error =>
|
|
599
|
+
await releaseHeldMessages(chatId, { contactCode: messageData.contactCode || null }).catch(error =>
|
|
594
600
|
logger.error('[processIncomingMessage] Held message release failed', { code: chatId, error: error.message })
|
|
595
601
|
);
|
|
596
602
|
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
const { Monitoreo_ID } = require('../config/airtableConfig');
|
|
2
|
+
|
|
3
|
+
const { logger } = require('../utils/logger');
|
|
4
|
+
const { MapCache } = require('../utils/MapCache');
|
|
5
|
+
|
|
6
|
+
const { getRecordByFilter } = require('../services/airtableService');
|
|
7
|
+
const { getMessages } = require('../services/messageService');
|
|
8
|
+
|
|
9
|
+
const { ensureWhatsAppFormat, stripWhatsAppFormat } = require('./twilioHelper');
|
|
10
|
+
const { escapeFormulaValue } = require('./airtableFormulaHelper');
|
|
11
|
+
|
|
12
|
+
const CAREGIVERS_FIELD = 'cuidadores_whatsapp';
|
|
13
|
+
const CAREGIVER_ROLE = 'caregiver';
|
|
14
|
+
|
|
15
|
+
const caregiverCache = new MapCache({ maxSize: 1000, ttl: 5 * 60 * 1000 });
|
|
16
|
+
|
|
17
|
+
const listedNumbers = (value) => String(value || '')
|
|
18
|
+
.split(/[,;\n]/)
|
|
19
|
+
.map((entry) => stripWhatsAppFormat(entry.replace(/[^\d+]/g, '')))
|
|
20
|
+
.filter(Boolean);
|
|
21
|
+
|
|
22
|
+
async function lookupCaregiver(code) {
|
|
23
|
+
const digits = stripWhatsAppFormat(code);
|
|
24
|
+
if (!/^\d+$/.test(digits)) return null;
|
|
25
|
+
|
|
26
|
+
const safeCode = escapeFormulaValue(code);
|
|
27
|
+
const records = await getRecordByFilter(
|
|
28
|
+
Monitoreo_ID,
|
|
29
|
+
'estado_general',
|
|
30
|
+
`OR({whatsapp_id}='${safeCode}', FIND('${digits}', {${CAREGIVERS_FIELD}}))`,
|
|
31
|
+
);
|
|
32
|
+
if (!records?.length) return null;
|
|
33
|
+
if (records.some((row) => row.whatsapp_id === code)) return null;
|
|
34
|
+
|
|
35
|
+
const patients = records.filter((row) => row.whatsapp_id && listedNumbers(row[CAREGIVERS_FIELD]).includes(digits));
|
|
36
|
+
if (patients.length > 1) {
|
|
37
|
+
logger.warn('[caregiverHelper] number listed as caregiver of several patients; not remapping', { count: patients.length });
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
if (!patients.length) return null;
|
|
41
|
+
return { patientCode: ensureWhatsAppFormat(patients[0].whatsapp_id) };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function resolveCaregiver(code) {
|
|
45
|
+
if (!code) return null;
|
|
46
|
+
const cached = caregiverCache.get(code);
|
|
47
|
+
if (cached !== undefined) return cached;
|
|
48
|
+
|
|
49
|
+
let resolved = null;
|
|
50
|
+
try {
|
|
51
|
+
resolved = await lookupCaregiver(code);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
logger.error('[caregiverHelper] caregiver lookup failed', { error: error.message });
|
|
54
|
+
}
|
|
55
|
+
caregiverCache.set(code, resolved);
|
|
56
|
+
return resolved;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function remapCaregiverSender(messageData) {
|
|
60
|
+
if (!messageData?.code || messageData.fromMe !== false || messageData.contactCode) return messageData;
|
|
61
|
+
const caregiver = await resolveCaregiver(messageData.code);
|
|
62
|
+
if (!caregiver) return messageData;
|
|
63
|
+
messageData.contactCode = messageData.code;
|
|
64
|
+
messageData.contactRole = CAREGIVER_ROLE;
|
|
65
|
+
messageData.code = caregiver.patientCode;
|
|
66
|
+
messageData.from = caregiver.patientCode;
|
|
67
|
+
return messageData;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function replyContactFor(code) {
|
|
71
|
+
if (!code) return null;
|
|
72
|
+
try {
|
|
73
|
+
const [latest] = await getMessages(
|
|
74
|
+
{ numero: code, from_me: false },
|
|
75
|
+
{ sort: { createdAt: -1 }, limit: 1, select: 'contact_code contact_role' },
|
|
76
|
+
) || [];
|
|
77
|
+
if (!latest?.contact_code) return null;
|
|
78
|
+
return { contactCode: latest.contact_code, contactRole: latest.contact_role };
|
|
79
|
+
} catch (error) {
|
|
80
|
+
logger.error('[caregiverHelper] reply contact lookup failed; replying to the patient', { error: error.message });
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function contactOf(message) {
|
|
86
|
+
return message?.contact_code ? { contactCode: message.contact_code, contactRole: message.contact_role } : {};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function _clearCaregiverCache() {
|
|
90
|
+
caregiverCache.clear();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
module.exports = {
|
|
94
|
+
CAREGIVERS_FIELD,
|
|
95
|
+
CAREGIVER_ROLE,
|
|
96
|
+
contactOf,
|
|
97
|
+
remapCaregiverSender,
|
|
98
|
+
replyContactFor,
|
|
99
|
+
resolveCaregiver,
|
|
100
|
+
_clearCaregiverCache,
|
|
101
|
+
};
|
|
@@ -2,11 +2,11 @@ const { getMessages } = require('../services/messageService');
|
|
|
2
2
|
|
|
3
3
|
const WINDOW_MS = 24 * 60 * 60 * 1000;
|
|
4
4
|
|
|
5
|
-
async function isWithin24HourWindow(code) {
|
|
5
|
+
async function isWithin24HourWindow(code, { contactCode = null } = {}) {
|
|
6
6
|
if (!code) return false;
|
|
7
7
|
const cutoff = new Date(Date.now() - WINDOW_MS);
|
|
8
8
|
const [recent] = await getMessages(
|
|
9
|
-
{ numero: code, from_me: false, createdAt: { $gte: cutoff } },
|
|
9
|
+
{ numero: code, from_me: false, contact_code: contactCode, createdAt: { $gte: cutoff } },
|
|
10
10
|
{ select: '_id', limit: 1 }
|
|
11
11
|
);
|
|
12
12
|
return !!recent;
|
package/lib/index.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ const { DeliveryAttempt } = require('../models/deliveryAttemptModel');
|
|
|
8
8
|
|
|
9
9
|
const { alertUndeliverable } = require('../helpers/channelRetryHelper');
|
|
10
10
|
|
|
11
|
+
const { contactOf } = require('../helpers/caregiverHelper');
|
|
11
12
|
const { getMessages } = require('../services/messageService');
|
|
12
13
|
const { recordUndeliverable } = require('../services/undeliverableService');
|
|
13
14
|
|
|
@@ -251,6 +252,7 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
251
252
|
try {
|
|
252
253
|
result = await this.sendMessage({
|
|
253
254
|
code: message.numero,
|
|
255
|
+
...contactOf(message),
|
|
254
256
|
contentSid,
|
|
255
257
|
variables: {},
|
|
256
258
|
kind: 'window_reopen_nudge',
|
|
@@ -289,6 +291,7 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
289
291
|
try {
|
|
290
292
|
sendResult = await this.sendMessage({
|
|
291
293
|
code: message.numero,
|
|
294
|
+
...contactOf(message),
|
|
292
295
|
contentSid: templateSid,
|
|
293
296
|
variables: {},
|
|
294
297
|
parentMessageId: message._id,
|
|
@@ -26,6 +26,8 @@ const messageSchema = new mongoose.Schema({
|
|
|
26
26
|
enum: ['whatsapp_platform', 'assistant', 'patient', 'system', 'instruction'],
|
|
27
27
|
default: 'whatsapp_platform'
|
|
28
28
|
},
|
|
29
|
+
contact_code: { type: String, default: null },
|
|
30
|
+
contact_role: { type: String, enum: [null, 'caregiver'], default: null },
|
|
29
31
|
tools_executed: {
|
|
30
32
|
type: [{
|
|
31
33
|
tool_name: { type: String, required: true },
|
package/lib/routes/index.js
CHANGED
|
@@ -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:/, '');
|
|
@@ -4,6 +4,7 @@ const { isWithinHourWindow, contactHoursBetween } = require('../utils/scheduleUt
|
|
|
4
4
|
const { Message } = require('../models/messageModel');
|
|
5
5
|
|
|
6
6
|
const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
|
|
7
|
+
const { contactOf } = require('../helpers/caregiverHelper');
|
|
7
8
|
const { cleanupRecoveryTemplate, resolveRecoveryBody, hasUnresolvedPhi } = require('../helpers/templateRecoveryHelper');
|
|
8
9
|
|
|
9
10
|
const { getMessages } = require('./messageService');
|
|
@@ -63,6 +64,7 @@ async function releaseOne(message, now) {
|
|
|
63
64
|
try {
|
|
64
65
|
result = await getMessaging().sendMessage({
|
|
65
66
|
code: message.numero,
|
|
67
|
+
...contactOf(message),
|
|
66
68
|
body,
|
|
67
69
|
parentMessageId: message._id,
|
|
68
70
|
kind: 'freeform',
|
|
@@ -95,7 +97,7 @@ async function releaseOne(message, now) {
|
|
|
95
97
|
return true;
|
|
96
98
|
}
|
|
97
99
|
|
|
98
|
-
async function releaseHeldMessages(code) {
|
|
100
|
+
async function releaseHeldMessages(code, { contactCode = null } = {}) {
|
|
99
101
|
if (!code) return { released: 0, reason: 'no_code' };
|
|
100
102
|
|
|
101
103
|
const now = new Date();
|
|
@@ -103,7 +105,7 @@ async function releaseHeldMessages(code) {
|
|
|
103
105
|
return { released: 0, reason: 'quiet_hours' };
|
|
104
106
|
}
|
|
105
107
|
|
|
106
|
-
const held = await getMessages(heldQuery({ numero: code }), { sort: { createdAt: 1 }, limit: MAX_RELEASE_BATCH });
|
|
108
|
+
const held = await getMessages(heldQuery({ numero: code, contact_code: contactCode }), { sort: { createdAt: 1 }, limit: MAX_RELEASE_BATCH });
|
|
107
109
|
if (!held.length) return { released: 0, reason: 'none_held' };
|
|
108
110
|
|
|
109
111
|
let released = 0;
|
|
@@ -118,15 +120,15 @@ async function sweepHeldMessages() {
|
|
|
118
120
|
if (!isWithinHourWindow(new Date(), PATIENT_CONTACT_WINDOW)) return 0;
|
|
119
121
|
|
|
120
122
|
const recent = await getMessages(heldQuery(), {
|
|
121
|
-
select: 'numero', sort: { createdAt: -1 }, limit: MAX_SWEEP_CANDIDATES
|
|
123
|
+
select: 'numero contact_code', sort: { createdAt: -1 }, limit: MAX_SWEEP_CANDIDATES
|
|
122
124
|
});
|
|
123
|
-
const
|
|
125
|
+
const phones = new Map(recent.map(doc => [`${doc.numero}|${doc.contact_code || ''}`, { code: doc.numero, contactCode: doc.contact_code || null }]));
|
|
124
126
|
let released = 0;
|
|
125
127
|
|
|
126
|
-
for (const code of
|
|
128
|
+
for (const { code, contactCode } of phones.values()) {
|
|
127
129
|
try {
|
|
128
|
-
if (!(await isWithin24HourWindow(code))) continue;
|
|
129
|
-
const outcome = await releaseHeldMessages(code);
|
|
130
|
+
if (!(await isWithin24HourWindow(code, { contactCode }))) continue;
|
|
131
|
+
const outcome = await releaseHeldMessages(code, { contactCode });
|
|
130
132
|
released += outcome.released;
|
|
131
133
|
} catch (error) {
|
|
132
134
|
logger.error('[HeldMessage] Sweep failed for one conversation', { code, error: error.message });
|
|
@@ -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
|
+
};
|
|
@@ -128,7 +128,11 @@ class MongoStorage {
|
|
|
128
128
|
traceId: messageData.traceId || undefined,
|
|
129
129
|
statusInfo: messageData.statusInfo,
|
|
130
130
|
clinical_context: messageData.clinicalContext || null,
|
|
131
|
-
triggeredBy: messageData.triggeredBy || null
|
|
131
|
+
triggeredBy: messageData.triggeredBy || null,
|
|
132
|
+
...(messageData.contactCode && {
|
|
133
|
+
contact_code: ensureWhatsAppFormat(messageData.contactCode),
|
|
134
|
+
contact_role: messageData.contactRole || null
|
|
135
|
+
})
|
|
132
136
|
};
|
|
133
137
|
return values;
|
|
134
138
|
}
|
|
@@ -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
|
-
|
|
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 };
|