@peopl-health/nexus 6.0.16 → 6.0.18

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.
@@ -15,6 +15,7 @@ const { CAREGIVER_ROLE, resolveCaregiver } = require('../helpers/caregiverHelper
15
15
  const { getRecordByFilter } = require('../services/airtableService');
16
16
  const { getMessages } = require('../services/messageService');
17
17
  const { recordDirectIndication } = require('../services/escalationReviewService');
18
+ const { resolveThreadCode } = require('../services/threadService');
18
19
 
19
20
  const INDICATION_WAIT_MS = 5000;
20
21
 
@@ -77,9 +78,7 @@ const sendMessageController = async (req, res) => {
77
78
  asIndication = false
78
79
  } = req.body || {};
79
80
 
80
- const formattedCode = ensureWhatsAppFormat(code);
81
-
82
- if (!formattedCode) {
81
+ if (!ensureWhatsAppFormat(code)) {
83
82
  return res.status(400).json({ success: false, error: 'code is required' });
84
83
  }
85
84
 
@@ -88,6 +87,7 @@ const sendMessageController = async (req, res) => {
88
87
  }
89
88
 
90
89
  try {
90
+ const formattedCode = await resolveThreadCode(ensureWhatsAppFormat(code));
91
91
  let contact = {};
92
92
  if (contactCode) {
93
93
  if (sendTime) {
@@ -306,7 +306,7 @@ const checkMessageStatusController = async (req, res) => {
306
306
  }
307
307
 
308
308
  try {
309
- const [msg] = await getMessages({ content_sid: contentSid, numero: ensureWhatsAppFormat(code) }, { limit: 1 });
309
+ const [msg] = await getMessages({ content_sid: contentSid, numero: await resolveThreadCode(ensureWhatsAppFormat(code)) }, { limit: 1 });
310
310
  if (!msg) {
311
311
  return res.status(404).json({ success: false, error: 'Message not found' });
312
312
  }
@@ -26,7 +26,7 @@ const { isStaffSend } = require('../helpers/staffSendHelper');
26
26
  const { isOutboundAllowed } = require('../helpers/outboundAllowlistHelper');
27
27
 
28
28
  const { createMessagingProvider } = require('../adapters/registry');
29
- const { ensureThreadExists } = require('../services/threadService');
29
+ const { ensureThreadExists, resolveThreadCode } = require('../services/threadService');
30
30
  const { observeSend, reserveSend, releaseSend } = require('../services/contactGateService');
31
31
 
32
32
  const { hasPreprocessingHandler, runPreprocessingHandler } = require('../services/preprocessingService');
@@ -389,6 +389,7 @@ class NexusMessaging {
389
389
  */
390
390
 
391
391
  async sendMessage(messageData) {
392
+ messageData = { ...messageData, code: await resolveThreadCode(messageData.code) };
392
393
  // Only an operator writing now still reaches a deceased patient's phone; automations and scheduled sends do not.
393
394
  const operatorNow = isStaffSend(messageData.triggeredBy) && !String(messageData.idempotencyKey || '').startsWith('scheduled:');
394
395
  if (!operatorNow && await patientIsDeceased(messageData.code)) return NOT_SENT_DECEASED;
@@ -54,6 +54,12 @@ const stripWhatsAppFormat = (code) => {
54
54
  return beforeAt.replace(/^\+/, '');
55
55
  };
56
56
 
57
+ // Twilio reaches a Mexican mobile as 52 + 10 digits or 521 + 10 digits.
58
+ const mexicanMobileVariant = (code) => {
59
+ const match = /^whatsapp:\+52(1?)([2-9]\d{9})$/.exec(code);
60
+ return match ? `whatsapp:+52${match[1] ? '' : '1'}${match[2]}` : null;
61
+ };
62
+
57
63
  const isArchivedPatientCode = (code) => typeof code === 'string' && code.trim().startsWith('archived:');
58
64
 
59
65
  module.exports = {
@@ -62,5 +68,6 @@ module.exports = {
62
68
  extractTitle,
63
69
  ensureWhatsAppFormat,
64
70
  stripWhatsAppFormat,
65
- isArchivedPatientCode
71
+ isArchivedPatientCode,
72
+ mexicanMobileVariant
66
73
  };
@@ -119,6 +119,16 @@ messageSchema.index({ triggeredBy: 1, createdAt: -1 }, { name: 'triggered_by_idx
119
119
 
120
120
  const Message = mongoose.model('Message', messageSchema);
121
121
 
122
+ const INTERNAL_ORIGINS = new Set(['system', 'instruction']);
123
+
124
+ // A stored text message carries a media object of schema defaults, so only a populated one counts as media.
125
+ const threadPreview = (message, at) => ({
126
+ lastMessageAt: at,
127
+ lastMessageBody: message.plainBody || '',
128
+ lastMessageFromMe: !!message.from_me,
129
+ lastMessageMedia: message.media && Object.values(message.media).some((value) => value != null) ? message.media : null,
130
+ });
131
+
122
132
  function getMessageValues(message, content) {
123
133
  return {
124
134
  nombre_whatsapp: message.pushName,
@@ -132,5 +142,7 @@ function getMessageValues(message, content) {
132
142
 
133
143
  module.exports = {
134
144
  Message,
145
+ INTERNAL_ORIGINS,
146
+ threadPreview,
135
147
  getMessageValues,
136
148
  };
@@ -2,15 +2,13 @@ const { Monitoreo_ID } = require('../config/airtableConfig');
2
2
 
3
3
  const { logger } = require('../utils/logger');
4
4
 
5
- const { Message } = require('../models/messageModel');
5
+ const { Message, INTERNAL_ORIGINS, threadPreview } = require('../models/messageModel');
6
6
  const { Thread } = require('../models/threadModel');
7
7
 
8
8
  const { getClinicalContext } = require('../helpers/patientInformationHelper');
9
9
 
10
10
  const { updateRecordByFilter } = require('../services/airtableService');
11
11
 
12
- const INTERNAL_ORIGINS = new Set(['system', 'instruction']);
13
-
14
12
  async function getMessages(query, options = {}) {
15
13
  let cursor = Message.find(query);
16
14
  if (options.select) cursor = cursor.select(options.select);
@@ -61,12 +59,7 @@ async function insertMessage(values) {
61
59
  Thread.findOneAndUpdate(
62
60
  { code: values.numero },
63
61
  {
64
- $set: {
65
- lastMessageAt: new Date(),
66
- lastMessageBody: values.plainBody || '',
67
- lastMessageFromMe: !!values.from_me,
68
- lastMessageMedia: values.media || null
69
- },
62
+ $set: threadPreview(values, new Date()),
70
63
  $inc: {
71
64
  messageCount: 1,
72
65
  ...(!values.from_me ? { unreadCount: 1 } : {})
@@ -2,7 +2,7 @@ const { logger } = require('../utils/logger');
2
2
  const { normalize } = require('../utils/tokenMapUtils');
3
3
  const { mapStringsDeep } = require('../utils/sanitizerUtils');
4
4
 
5
- const { Message } = require('../models/messageModel');
5
+ const { Message, INTERNAL_ORIGINS, threadPreview } = require('../models/messageModel');
6
6
  const { Thread } = require('../models/threadModel');
7
7
  const { getTokenMap } = require('../models/tokenMapModel');
8
8
  const { ScheduledMessage } = require('../models/agendaMessageModel');
@@ -187,6 +187,18 @@ async function moveThreads(source, target, state, migrationId) {
187
187
  await Thread.bulkWrite(rewriteOps(toArchive, (doc) => ({ code: `archived:${source}:${doc._id}`, stopped: true })));
188
188
  }
189
189
  logger.debug('[migratePatientCode] Threads moved', { migrationId, renamed, archived: toArchive.length });
190
+ return renamed;
191
+ }
192
+
193
+ async function countMovedMessages(target, messages) {
194
+ const counted = messages.filter((doc) => !INTERNAL_ORIGINS.has(doc.origin));
195
+ if (!counted.length) return;
196
+ const latest = await Message.findOne({ _id: { $in: counted.map((doc) => doc._id) } }, null, { sort: { createdAt: -1 } }).lean();
197
+ await Thread.updateOne({ code: target }, { $inc: { messageCount: counted.length } });
198
+ await Thread.updateOne(
199
+ { code: target, $or: [{ lastMessageAt: null }, { lastMessageAt: { $lt: latest.createdAt } }] },
200
+ { $set: threadPreview(latest, latest.createdAt) },
201
+ );
190
202
  }
191
203
 
192
204
  async function migratePatientCode({ from, to, asCaregiver = false, apply = false, operator = null } = {}) {
@@ -238,7 +250,8 @@ async function migratePatientCode({ from, to, asCaregiver = false, apply = false
238
250
  await getPatientMemory().bulkWrite(rewriteOps(state.memories, (doc) => ({ ...retokenizedFields(doc, mapping), numero: target })));
239
251
  }
240
252
 
241
- await moveThreads(source, target, state, migrationId);
253
+ const renamed = await moveThreads(source, target, state, migrationId);
254
+ if (!renamed) await countMovedMessages(target, state.messages);
242
255
 
243
256
  if (state.scheduled.length && !asCaregiver) {
244
257
  await ScheduledMessage.bulkWrite(rewriteOps(state.scheduled, (doc) => ({ code: sameFormat(doc.code, target) })));
@@ -7,6 +7,7 @@ const { logger } = require('../utils/logger');
7
7
  const { Thread } = require('../models/threadModel.js');
8
8
  const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper.js');
9
9
  const { patientIsDeceased } = require('../helpers/pausedThreadHelper.js');
10
+ const { mexicanMobileVariant } = require('../helpers/twilioHelper.js');
10
11
 
11
12
  const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService.js');
12
13
  const { ensurePatientResource } = require('../services/patientResourceService.js');
@@ -28,6 +29,13 @@ const getThread = async (code, message = null) => {
28
29
  }
29
30
  };
30
31
 
32
+ const resolveThreadCode = async (code) => {
33
+ const variant = mexicanMobileVariant(code);
34
+ if (!variant) return code;
35
+ const existing = await Thread.distinct('code', { code: { $in: [code, variant] } });
36
+ return existing.includes(variant) && !existing.includes(code) ? variant : code;
37
+ };
38
+
31
39
  const getThreadInfo = async (code, { rethrow = false } = {}) => {
32
40
  try {
33
41
  return await Thread.findOne({ code });
@@ -123,6 +131,7 @@ module.exports = {
123
131
  getThreadInfo,
124
132
  createPlaceholderThread,
125
133
  ensureThreadExists,
134
+ resolveThreadCode,
126
135
  switchThreadStoppedStatus,
127
136
  setThreadDoNotAlert,
128
137
  setThreadPromptId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.16",
3
+ "version": "6.0.18",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",