@peopl-health/nexus 5.57.0-dev.10072 → 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/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/services/heldMessageService.js +9 -7
- package/lib/storage/MongoStorage.js +5 -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} `;
|
|
@@ -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 },
|
|
@@ -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 });
|
|
@@ -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
|
}
|