@peopl-health/nexus 4.5.25 → 4.5.27
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/MessageAdapter.js +0 -6
- package/lib/controllers/conversationController.js +11 -2
- package/lib/controllers/interactionController.js +1 -1
- package/lib/core/MessageParser.js +5 -12
- package/lib/core/NexusMessaging.js +3 -10
- package/lib/core/PhiProcessor.js +9 -7
- package/lib/helpers/messageHelper.js +3 -1
- package/lib/index.d.ts +1 -2
- package/lib/models/messageModel.js +1 -0
- package/lib/services/messageService.js +2 -2
- package/lib/storage/MongoStorage.js +2 -1
- package/package.json +1 -1
|
@@ -15,12 +15,6 @@ class MessageAdapter {
|
|
|
15
15
|
case 'list':
|
|
16
16
|
return interactive.title || interactive.description || '[List item selected]';
|
|
17
17
|
case 'flow':
|
|
18
|
-
if (interactive.data) {
|
|
19
|
-
const flowData = typeof interactive.data === 'string'
|
|
20
|
-
? interactive.data
|
|
21
|
-
: JSON.stringify(interactive.data, null, 2);
|
|
22
|
-
return `Flow Response:\n${flowData}`;
|
|
23
|
-
}
|
|
24
18
|
return '[Flow response]';
|
|
25
19
|
default:
|
|
26
20
|
return '[Interactive message]';
|
|
@@ -91,6 +91,7 @@ const getConversationMessagesController = async (req, res) => {
|
|
|
91
91
|
|
|
92
92
|
const total = await countMessages(query);
|
|
93
93
|
const messages = await getMessages(query, { sort: { createdAt: -1 }, skip, limit });
|
|
94
|
+
messages.forEach(msg => { msg.body = msg.plainBody || msg.body; });
|
|
94
95
|
const totalPages = Math.ceil(total / limit);
|
|
95
96
|
|
|
96
97
|
res.status(200).json({
|
|
@@ -207,7 +208,10 @@ const searchConversationsController = async (req, res) => {
|
|
|
207
208
|
secondary: [
|
|
208
209
|
{ $match: {
|
|
209
210
|
group_id: null,
|
|
210
|
-
|
|
211
|
+
$or: [
|
|
212
|
+
{ plainBody: { $regex: escapedQuery, $options: 'i' } },
|
|
213
|
+
{ body: { $regex: escapedQuery, $options: 'i' } }
|
|
214
|
+
]
|
|
211
215
|
}},
|
|
212
216
|
{ $group: { _id: '$numero' } }
|
|
213
217
|
]
|
|
@@ -400,6 +404,7 @@ const getNewMessagesController = async (req, res) => {
|
|
|
400
404
|
const raw = parseInt(req.query.limit, 10);
|
|
401
405
|
const clampedLimit = Number.isFinite(raw) ? Math.min(Math.max(raw, 1), 100) : 20;
|
|
402
406
|
const messages = await getMessages(query, { sort: { createdAt: 1 }, limit: clampedLimit });
|
|
407
|
+
messages.forEach(msg => { msg.body = msg.plainBody || msg.body; });
|
|
403
408
|
|
|
404
409
|
res.status(200).json({
|
|
405
410
|
success: true,
|
|
@@ -554,13 +559,17 @@ const searchMessagesByNumberController = async (req, res) => {
|
|
|
554
559
|
const mongoQuery = {
|
|
555
560
|
group_id: null,
|
|
556
561
|
numero: formattedPhoneNumber,
|
|
557
|
-
|
|
562
|
+
$or: [
|
|
563
|
+
{ plainBody: { $regex: escapedQuery, $options: 'i' } },
|
|
564
|
+
{ body: { $regex: escapedQuery, $options: 'i' } }
|
|
565
|
+
]
|
|
558
566
|
};
|
|
559
567
|
|
|
560
568
|
const mongoSort = { createdAt: -1 };
|
|
561
569
|
|
|
562
570
|
const total = await countMessages(mongoQuery);
|
|
563
571
|
const messages = await getMessages(mongoQuery, { sort: mongoSort, skip, limit });
|
|
572
|
+
messages.forEach(msg => { msg.body = msg.plainBody || msg.body; });
|
|
564
573
|
const totalPages = Math.ceil(total / limit);
|
|
565
574
|
|
|
566
575
|
res.status(200).json({
|
|
@@ -15,7 +15,7 @@ async function logInteractionToAirtable(messageIds, whatsapp_id, reporter, quali
|
|
|
15
15
|
const conversation = messageObjects.map(msg => {
|
|
16
16
|
const timestamp = msg.createdAt.toISOString().slice(0, 16).replace('T', ' ');
|
|
17
17
|
const role = msg.from_me ? 'Assistant' : 'Patient';
|
|
18
|
-
return `[${timestamp}] ${role}: ${msg.body || '(media)'}`;
|
|
18
|
+
return `[${timestamp}] ${role}: ${msg.plainBody || msg.body || '(media)'}`;
|
|
19
19
|
}).join('\n');
|
|
20
20
|
|
|
21
21
|
let patientId = null;
|
|
@@ -8,17 +8,20 @@ class MessageParser {
|
|
|
8
8
|
this.config = config;
|
|
9
9
|
this.commandPrefixes = config.commandPrefixes || ['/', '!'];
|
|
10
10
|
this.keywords = config.keywords || [];
|
|
11
|
-
this.flowTriggers = config.flowTriggers || [];
|
|
12
11
|
}
|
|
13
12
|
|
|
14
13
|
async parseMessage(normalizedMessage) {
|
|
15
14
|
const {media, interactive, ...base} = normalizedMessage;
|
|
16
15
|
await parsePatientInformation(base);
|
|
17
16
|
|
|
18
|
-
if (interactive) {
|
|
17
|
+
if (interactive && interactive.type !== 'flow') {
|
|
19
18
|
return {...base, type: 'interactive', interactive, isInteractive: true};
|
|
20
19
|
}
|
|
21
20
|
|
|
21
|
+
if (interactive && interactive.type === 'flow') {
|
|
22
|
+
return {...base, type: 'flow', flow: interactive, interactive};
|
|
23
|
+
}
|
|
24
|
+
|
|
22
25
|
if (media) {
|
|
23
26
|
return {...base, type: 'media', media, isMedia: true};
|
|
24
27
|
}
|
|
@@ -38,11 +41,6 @@ class MessageParser {
|
|
|
38
41
|
return {...base, type: 'keyword', keyword};
|
|
39
42
|
}
|
|
40
43
|
|
|
41
|
-
const flow = this.findFlowTrigger(body);
|
|
42
|
-
if (flow) {
|
|
43
|
-
return {...base, type: 'flow', flow};
|
|
44
|
-
}
|
|
45
|
-
|
|
46
44
|
return {...base, type: 'message'};
|
|
47
45
|
}
|
|
48
46
|
|
|
@@ -76,15 +74,10 @@ class MessageParser {
|
|
|
76
74
|
return this._findMatch(text, this.keywords);
|
|
77
75
|
}
|
|
78
76
|
|
|
79
|
-
findFlowTrigger(text) {
|
|
80
|
-
return this._findMatch(text, this.flowTriggers);
|
|
81
|
-
}
|
|
82
|
-
|
|
83
77
|
updateConfig(newConfig) {
|
|
84
78
|
this.config = { ...this.config, ...newConfig };
|
|
85
79
|
this.commandPrefixes = this.config.commandPrefixes || this.commandPrefixes;
|
|
86
80
|
this.keywords = this.config.keywords || this.keywords;
|
|
87
|
-
this.flowTriggers = this.config.flowTriggers || this.flowTriggers;
|
|
88
81
|
}
|
|
89
82
|
}
|
|
90
83
|
|
|
@@ -380,10 +380,10 @@ class NexusMessaging {
|
|
|
380
380
|
if (stop) return;
|
|
381
381
|
}
|
|
382
382
|
|
|
383
|
+
if (messageData.flow) return this.handleFlow(messageData);
|
|
383
384
|
if (messageData.interactive) return this.handleInteractive(messageData);
|
|
384
385
|
if (messageData.command) return this.handleCommand(messageData);
|
|
385
386
|
if (messageData.keyword) return this.handleKeyword(messageData);
|
|
386
|
-
if (messageData.flow) return this.handleFlow(messageData);
|
|
387
387
|
|
|
388
388
|
if (this.batchingConfig.enabled && chatId) return this._handleWithCheckAfter(chatId);
|
|
389
389
|
return messageData.media ? this.handleMedia(messageData) : this.handleMessage(messageData);
|
|
@@ -415,6 +415,8 @@ class NexusMessaging {
|
|
|
415
415
|
|
|
416
416
|
async handleFlow(messageData) {
|
|
417
417
|
if (this.handlers.onFlow) return await this.handlers.onFlow(messageData, this);
|
|
418
|
+
// Backward compatibility for consumers who don't have onFlow handler
|
|
419
|
+
if (this.handlers.onInteractive) return await this.handlers.onInteractive(messageData, this);
|
|
418
420
|
}
|
|
419
421
|
|
|
420
422
|
/*
|
|
@@ -518,7 +520,6 @@ class NexusMessaging {
|
|
|
518
520
|
}
|
|
519
521
|
|
|
520
522
|
async processInstruction(code, instruction, role = 'developer', { triggeredBy } = {}) {
|
|
521
|
-
const assistantId = await this._getThreadAssistantId(code);
|
|
522
523
|
const messageData = {
|
|
523
524
|
pushName: 'Instruction',
|
|
524
525
|
code,
|
|
@@ -527,7 +528,6 @@ class NexusMessaging {
|
|
|
527
528
|
fromMe: true,
|
|
528
529
|
processed: true,
|
|
529
530
|
origin: 'instruction',
|
|
530
|
-
assistantId,
|
|
531
531
|
raw: { role },
|
|
532
532
|
triggeredBy: triggeredBy || null,
|
|
533
533
|
silent: true,
|
|
@@ -556,7 +556,6 @@ class NexusMessaging {
|
|
|
556
556
|
const thread = await Thread.findOne({ code }).lean();
|
|
557
557
|
if (!thread) return null;
|
|
558
558
|
|
|
559
|
-
const assistantId = await this._getThreadAssistantId(code);
|
|
560
559
|
const normalizedMessages = Array.isArray(messages) ? messages : [messages];
|
|
561
560
|
|
|
562
561
|
for (let i = 0; i < normalizedMessages.length; i++) {
|
|
@@ -569,7 +568,6 @@ class NexusMessaging {
|
|
|
569
568
|
fromMe: true,
|
|
570
569
|
processed: true,
|
|
571
570
|
origin: 'system',
|
|
572
|
-
assistantId,
|
|
573
571
|
raw: { role },
|
|
574
572
|
triggeredBy: triggeredBy || null,
|
|
575
573
|
silent: true,
|
|
@@ -597,11 +595,6 @@ class NexusMessaging {
|
|
|
597
595
|
return result?.output || null;
|
|
598
596
|
}
|
|
599
597
|
|
|
600
|
-
async _getThreadAssistantId(code) {
|
|
601
|
-
const thread = await Thread.findOne({ code }).select('assistant_id prompt_id').lean();
|
|
602
|
-
return thread?.prompt_id || thread?.assistant_id || null;
|
|
603
|
-
}
|
|
604
|
-
|
|
605
598
|
async _processMessages(chatId, processingFn, shouldFinalize = () => true) {
|
|
606
599
|
const query = { numero: chatId, from_me: false, processed: false };
|
|
607
600
|
const unprocessed = await getMessages(query, { select: '_id' });
|
package/lib/core/PhiProcessor.js
CHANGED
|
@@ -69,16 +69,18 @@ class PhiProcessor {
|
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
async inData(messageData, saveFn, handler) {
|
|
72
|
-
const
|
|
73
|
-
const
|
|
74
|
-
|
|
72
|
+
const decodedBody = messageData.body;
|
|
73
|
+
const encodedBody = await this.encodeBody(decodedBody, messageData.code);
|
|
74
|
+
const saved = await saveFn({ ...messageData, body: encodedBody, plainBody: decodedBody });
|
|
75
|
+
return handler({ body: encodedBody, _id: saved?._id });
|
|
75
76
|
}
|
|
76
77
|
|
|
77
78
|
async outDataFromPlain(messageData, saveFn, handler, { onSaved } = {}) {
|
|
78
|
-
const
|
|
79
|
-
const
|
|
79
|
+
const decodedBody = messageData.body;
|
|
80
|
+
const encodedBody = await this.encodeBody(decodedBody, messageData.code);
|
|
81
|
+
const saved = await saveFn({ ...messageData, body: encodedBody, plainBody: decodedBody });
|
|
80
82
|
await onSaved?.(saved?._id);
|
|
81
|
-
return handler({ body:
|
|
83
|
+
return handler({ body: decodedBody, _id: saved?._id });
|
|
82
84
|
}
|
|
83
85
|
|
|
84
86
|
async decodeBody(body, numero) {
|
|
@@ -100,10 +102,10 @@ class PhiProcessor {
|
|
|
100
102
|
}
|
|
101
103
|
|
|
102
104
|
async outDataFromEncoded(messageData, saveFn, handler) {
|
|
103
|
-
const saved = await saveFn(messageData);
|
|
104
105
|
const decodedBody = this._phiEnabled
|
|
105
106
|
? await this.decodeBody(messageData.body, messageData.code)
|
|
106
107
|
: messageData.body;
|
|
108
|
+
const saved = await saveFn({ ...messageData, plainBody: decodedBody });
|
|
107
109
|
return handler({ body: decodedBody, _id: saved?._id });
|
|
108
110
|
}
|
|
109
111
|
}
|
|
@@ -90,7 +90,9 @@ async function getLastNMessages(code, n, anchor = null, opts = {}) {
|
|
|
90
90
|
numero: code,
|
|
91
91
|
...(anchor ? { createdAt: { [beforeOperator]: anchor } } : {}),
|
|
92
92
|
};
|
|
93
|
-
|
|
93
|
+
const messages = await getMessages(query, { sort: { createdAt: -1 }, limit: n });
|
|
94
|
+
messages.forEach(msg => { msg.body = msg.plainBody || msg.body; });
|
|
95
|
+
return messages;
|
|
94
96
|
}
|
|
95
97
|
|
|
96
98
|
module.exports = {
|
package/lib/index.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ declare module '@peopl-health/nexus' {
|
|
|
13
13
|
media?: MediaData;
|
|
14
14
|
command?: CommandData;
|
|
15
15
|
keyword?: string;
|
|
16
|
-
flow?:
|
|
16
|
+
flow?: InteractiveData;
|
|
17
17
|
type?: 'message' | 'interactive' | 'media' | 'command' | 'keyword' | 'flow';
|
|
18
18
|
}
|
|
19
19
|
|
|
@@ -93,7 +93,6 @@ declare module '@peopl-health/nexus' {
|
|
|
93
93
|
export interface ParserConfig {
|
|
94
94
|
commandPrefixes?: string[];
|
|
95
95
|
keywords?: (string | { pattern: string; flags?: string })[];
|
|
96
|
-
flowTriggers?: (string | { pattern: string; flags?: string })[];
|
|
97
96
|
}
|
|
98
97
|
|
|
99
98
|
// Handler Types
|
|
@@ -5,6 +5,7 @@ const { DELIVERY_ATTEMPT_STATUSES } = require('./deliveryAttemptModel');
|
|
|
5
5
|
const messageSchema = new mongoose.Schema({
|
|
6
6
|
raw: { type: Object, default: null },
|
|
7
7
|
body: { type: String, default: '' },
|
|
8
|
+
plainBody: { type: String, default: null },
|
|
8
9
|
numero: { type: String, required: true },
|
|
9
10
|
nombre_whatsapp: { type: String, default: null },
|
|
10
11
|
message_id: { type: String, default: null},
|
|
@@ -63,7 +63,7 @@ async function insertMessage(values) {
|
|
|
63
63
|
{
|
|
64
64
|
$set: {
|
|
65
65
|
lastMessageAt: new Date(),
|
|
66
|
-
lastMessageBody: values.
|
|
66
|
+
lastMessageBody: values.plainBody || '',
|
|
67
67
|
lastMessageFromMe: !!values.from_me,
|
|
68
68
|
lastMessageMedia: values.media || null
|
|
69
69
|
},
|
|
@@ -77,7 +77,7 @@ async function insertMessage(values) {
|
|
|
77
77
|
}
|
|
78
78
|
|
|
79
79
|
updateRecordByFilter(Monitoreo_ID, 'message_monitor', `{whatsapp_id} = "${values.numero}"`, {
|
|
80
|
-
...(values.from_me ? { last_message_bot:
|
|
80
|
+
...(values.from_me ? { last_message_bot: doc.plainBody } : { last_message_patient: doc.plainBody, read: false }),
|
|
81
81
|
...(values.from_me ? { last_message_bot_time: doc.createdAt.toISOString() } : { last_message_patient_time: doc.createdAt.toISOString() })
|
|
82
82
|
}, values.numero).catch(err => logger.error('[MongoStorage] Failed to update message_monitor table', { numero: values.numero, error: err.message }));
|
|
83
83
|
|
|
@@ -89,7 +89,7 @@ class MongoStorage {
|
|
|
89
89
|
code: doc.numero,
|
|
90
90
|
name: doc.nombre_whatsapp,
|
|
91
91
|
origin: doc.origin,
|
|
92
|
-
body: doc.
|
|
92
|
+
body: doc.plainBody,
|
|
93
93
|
media: doc.media,
|
|
94
94
|
type: doc.interactive_type ? 'interactive' : doc.media ? 'media' : 'message',
|
|
95
95
|
triggeredBy: doc.triggeredBy,
|
|
@@ -106,6 +106,7 @@ class MongoStorage {
|
|
|
106
106
|
nombre_whatsapp: messageData.pushName ?? (fromMe ? runtimeConfig.get('USER_DB_MONGO') : null),
|
|
107
107
|
numero: ensureWhatsAppFormat(messageData.code),
|
|
108
108
|
body: messageData.body || '',
|
|
109
|
+
plainBody: messageData.plainBody || '',
|
|
109
110
|
processed: messageData.processed || false,
|
|
110
111
|
message_id: messageId,
|
|
111
112
|
interactive_type: messageData.interactive?.type || null,
|