@peopl-health/nexus 5.57.0-dev.9718 → 5.57.0

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.
Files changed (37) hide show
  1. package/lib/adapters/BaileysProvider.js +3 -2
  2. package/lib/adapters/TwilioProvider.js +1 -1
  3. package/lib/clinical/memory/DefaultMemoryManager.js +5 -3
  4. package/lib/clinical/providers/AnthropicProvider.js +5 -4
  5. package/lib/clinical/providers/BaseLLMProvider.js +3 -1
  6. package/lib/clinical/services/outreachCarrierService.js +1 -4
  7. package/lib/clinical/services/riskHeadlineService.js +1 -0
  8. package/lib/clinical/services/skillService.js +1 -4
  9. package/lib/clinical/tools/reportUnresolvedRequestv2Tool.js +2 -2
  10. package/lib/clinical/tools/submitRecommendationPlanTool.js +1 -1
  11. package/lib/controllers/assistantController.js +31 -2
  12. package/lib/controllers/messageController.js +2 -2
  13. package/lib/controllers/officeAssistantController.js +55 -0
  14. package/lib/core/NexusMessaging.js +8 -2
  15. package/lib/helpers/caregiverHelper.js +101 -0
  16. package/lib/helpers/channelRetryHelper.js +1 -2
  17. package/lib/helpers/conversationWindowHelper.js +2 -2
  18. package/lib/helpers/pausedThreadHelper.js +13 -1
  19. package/lib/index.d.ts +2 -0
  20. package/lib/index.js +0 -1
  21. package/lib/jobs/TemplateApprovalJob.js +3 -0
  22. package/lib/models/deliveryAttemptModel.js +3 -0
  23. package/lib/models/messageModel.js +2 -0
  24. package/lib/models/threadModel.js +1 -0
  25. package/lib/routes/index.js +19 -2
  26. package/lib/services/escalationReviewService.js +2 -9
  27. package/lib/services/heldMessageService.js +9 -7
  28. package/lib/services/inboundRecoveryService.js +15 -5
  29. package/lib/services/officeAssistantService.js +156 -0
  30. package/lib/services/recommendationCarouselService.js +78 -9
  31. package/lib/services/threadService.js +3 -0
  32. package/lib/storage/MongoStorage.js +5 -1
  33. package/lib/utils/coercionUtils.js +2 -1
  34. package/lib/utils/httpErrorUtils.js +7 -1
  35. package/lib/utils/textMatchUtils.js +3 -0
  36. package/package.json +1 -1
  37. package/lib/core/workflowRunner.js +0 -35
@@ -7,7 +7,8 @@ const assistantRouteDefinitions = {
7
7
  'POST /info': 'getInfoAssistantController',
8
8
  'GET /list': 'listAssistantController',
9
9
  'POST /switch': 'switchAssistantController',
10
- 'POST /stop': 'stopAssistantController'
10
+ 'POST /stop': 'stopAssistantController',
11
+ 'POST /do-not-alert': 'doNotAlertController'
11
12
  };
12
13
 
13
14
  const contingencyRouteDefinitions = {
@@ -135,6 +136,12 @@ const escalationReviewRouteDefinitions = {
135
136
  'POST /:id/case-sync': 'syncEscalationReviewCaseController'
136
137
  };
137
138
 
139
+ const officeAssistantRouteDefinitions = {
140
+ 'GET /patients': 'listOfficePatientsController',
141
+ 'GET /patients/:code/messages': 'getOfficeMessagesController',
142
+ 'POST /patients/:code/messages': 'sendOfficeMessageController'
143
+ };
144
+
138
145
  const createRouter = (routeDefinitions, controllers) => {
139
146
  const router = express.Router();
140
147
 
@@ -173,6 +180,7 @@ const dashboardController = require('../controllers/dashboardController');
173
180
  const prescriptionController = require('../controllers/prescriptionController');
174
181
  const traceController = require('../controllers/traceController');
175
182
  const escalationReviewController = require('../controllers/escalationReviewController');
183
+ const officeAssistantController = require('../controllers/officeAssistantController');
176
184
 
177
185
  const builtInControllers = {
178
186
  // Assistant controllers
@@ -183,6 +191,7 @@ const builtInControllers = {
183
191
  listAssistantController: assistantController.listAssistantController,
184
192
  switchAssistantController: assistantController.switchAssistantController,
185
193
  stopAssistantController: assistantController.stopAssistantController,
194
+ doNotAlertController: assistantController.doNotAlertController,
186
195
 
187
196
  // Contingency controllers
188
197
  contingencyEventController: contingencyController.contingencyEventController,
@@ -297,7 +306,12 @@ const builtInControllers = {
297
306
  sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
298
307
  closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
299
308
  cancelEscalationReviewController: escalationReviewController.cancelEscalationReviewController,
300
- syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
309
+ syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController,
310
+
311
+ // Office assistant controllers
312
+ listOfficePatientsController: officeAssistantController.listOfficePatientsController,
313
+ getOfficeMessagesController: officeAssistantController.getOfficeMessagesController,
314
+ sendOfficeMessageController: officeAssistantController.sendOfficeMessageController
301
315
  };
302
316
 
303
317
  const setupDefaultRoutes = (app) => {
@@ -321,6 +335,7 @@ const setupDefaultRoutes = (app) => {
321
335
  app.use('/api/dashboard', createRouter(dashboardRouteDefinitions, builtInControllers));
322
336
  app.use('/api/trace', createRouter(traceRouteDefinitions, builtInControllers));
323
337
  app.use('/api/escalation-review', createRouter(escalationReviewRouteDefinitions, builtInControllers));
338
+ app.use('/api/office', createRouter(officeAssistantRouteDefinitions, builtInControllers));
324
339
  };
325
340
 
326
341
  module.exports = {
@@ -339,7 +354,9 @@ module.exports = {
339
354
  dashboardRoutes: dashboardRouteDefinitions,
340
355
  traceRoutes: traceRouteDefinitions,
341
356
  escalationReviewRoutes: escalationReviewRouteDefinitions,
357
+ officeAssistantRoutes: officeAssistantRouteDefinitions,
342
358
 
359
+ builtInControllers,
343
360
  createRouter,
344
361
  setupDefaultRoutes
345
362
  };
@@ -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 codes = [...new Set(recent.map(doc => doc.numero))];
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 codes) {
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 });
@@ -3,7 +3,7 @@ const { logger } = require('../utils/logger');
3
3
  const { isWithinHourWindow } = require('../utils/scheduleUtils');
4
4
  const { createIntervalSweeper } = require('../utils/intervalSweeper');
5
5
  const { Thread } = require('../models/threadModel');
6
- const { botIsPaused } = require('../helpers/pausedThreadHelper');
6
+ const { alertsMutedFor, botIsPaused } = require('../helpers/pausedThreadHelper');
7
7
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
8
8
  const { coldInboundMode, inboundRecoveryLive } = require('../clinical/flags/inboundRecoveryFlags');
9
9
  const { formatOpsAlert, recordUnresolvedRequest } = require('../clinical/services/clinicalAirtableService');
@@ -41,6 +41,7 @@ async function unansweredThreads(now, { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AG
41
41
  stopped: false,
42
42
  lastMessageFromMe: false,
43
43
  lastMessageAt: { $gte: new Date(now.getTime() - maxAgeMs), $lte: new Date(now.getTime() - minAgeMs) },
44
+ $or: [{ doNotAlertThrough: null }, { $expr: { $lt: ['$doNotAlertThrough', '$lastMessageAt'] } }],
44
45
  },
45
46
  { code: 1, lastMessageAt: 1 },
46
47
  ).sort({ lastMessageAt: 1 }).limit(limit).lean();
@@ -68,6 +69,7 @@ async function candidateCodes(now, { threadBand = null, failedMaxAgeMs = MAX_AGE
68
69
  }
69
70
 
70
71
  const threadIsOwnedByAHuman = (code) => botIsPaused(code, { label: '[inboundRecovery]' });
72
+ const silenceWasWavedOff = (code, inboundAt) => alertsMutedFor(code, inboundAt, { label: '[inboundRecovery]' });
71
73
 
72
74
  async function stillUnanswered(code, now = new Date(), { minAgeMs = MIN_AGE_MS, maxAgeMs = MAX_AGE_MS } = {}) {
73
75
  const [newest] = await getMessages(
@@ -113,6 +115,7 @@ async function sweepUnansweredInbound({
113
115
  claims = recoveryClaims,
114
116
  ticketGate = ticketClaims,
115
117
  isPaused = threadIsOwnedByAHuman,
118
+ isMuted = silenceWasWavedOff,
116
119
  alert = recordUnresolvedRequest,
117
120
  } = {}) {
118
121
  let codes;
@@ -128,7 +131,7 @@ async function sweepUnansweredInbound({
128
131
  if (isProcessing(code)) continue;
129
132
  try {
130
133
  const inbound = await stillUnanswered(code, now);
131
- if (inbound) candidates.push({ code, inbound });
134
+ if (inbound && !await isMuted(code, inbound.createdAt)) candidates.push({ code, inbound });
132
135
  } catch (error) {
133
136
  logger.error('[inboundRecovery] could not read one conversation; leaving it for the next pass', {
134
137
  code, error: error.message,
@@ -154,7 +157,7 @@ async function sweepUnansweredInbound({
154
157
  const key = String(inbound._id);
155
158
  const ageMs = now.getTime() - new Date(inbound.createdAt).getTime();
156
159
 
157
- if (await isPaused(code)) { skipped += 1; continue; }
160
+ if (await isPaused(code) || await isMuted(code, inbound.createdAt)) { skipped += 1; continue; }
158
161
 
159
162
  const claim = await claims.acquire(key, 'handled');
160
163
  if (claim === 'unavailable') {
@@ -197,7 +200,11 @@ async function sweepUnansweredInbound({
197
200
  // Claimed before filing, like the replay branch above: a ticket filed without its marker is a
198
201
  // ticket the next pass files again.
199
202
  const ticket = await ticketGate.acquire(key, 'alerted');
200
- if (ticket !== 'acquired') { skipped += 1; continue; }
203
+ if (ticket !== 'acquired') {
204
+ skipped += 1;
205
+ if (ticket === 'unavailable') await claims.release(key);
206
+ continue;
207
+ }
201
208
 
202
209
  logger.error('[inboundRecovery] patient was left unanswered', {
203
210
  code, ageMs, recoveryLive: canRecover, reachable,
@@ -220,6 +227,7 @@ async function sweepColdUnansweredInbound({
220
227
  mode = coldInboundMode(),
221
228
  isProcessing = () => false,
222
229
  isPaused = threadIsOwnedByAHuman,
230
+ isMuted = silenceWasWavedOff,
223
231
  ticketGate = ticketClaims,
224
232
  coldGate = coldTicketClaims,
225
233
  alert = recordUnresolvedRequest,
@@ -242,7 +250,7 @@ async function sweepColdUnansweredInbound({
242
250
  if (isProcessing(code)) continue;
243
251
  try {
244
252
  const inbound = await stillUnanswered(code, now, COLD_BAND);
245
- if (inbound && !await isPaused(code)) waiting.push({ code, inbound });
253
+ if (inbound && !await isPaused(code) && !await isMuted(code, inbound.createdAt)) waiting.push({ code, inbound });
246
254
  } catch (error) {
247
255
  logger.error('[inboundRecovery] could not read one cold conversation; leaving it for the next pass', {
248
256
  code, error: error.message,
@@ -273,6 +281,7 @@ async function sweepColdUnansweredInbound({
273
281
  for (const { code, inbound } of waiting) {
274
282
  if ((await spent() ?? COLD_TICKETS_PER_DAY) >= COLD_TICKETS_PER_DAY) break;
275
283
  const key = String(inbound._id);
284
+ if (await isMuted(code, inbound.createdAt)) continue;
276
285
  if (await ticketGate.has(key) !== false) continue;
277
286
  if (await coldGate.acquire(key, 'cold') !== 'acquired') continue;
278
287
  if (await fileTicket(code, alert, now.getTime() - new Date(inbound.createdAt).getTime())) alerted += 1;
@@ -327,6 +336,7 @@ module.exports = {
327
336
  DEFAULT_SWEEP_INTERVAL_MS,
328
337
  stillUnanswered,
329
338
  threadIsOwnedByAHuman,
339
+ silenceWasWavedOff,
330
340
  _claims: recoveryClaims,
331
341
  _ticketClaims: ticketClaims,
332
342
  _coldTicketClaims: coldTicketClaims,
@@ -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 { escapeRegExp } = require('../utils/textMatchUtils');
6
+ const { logger } = require('../utils/logger');
7
+ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
8
+ const { escapeFormulaValue, fieldEquals } = require('../helpers/airtableFormulaHelper');
9
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
10
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
11
+ const { sendMessage } = require('../core/NexusMessaging');
12
+
13
+ const { getRecordByFilter } = require('./airtableService');
14
+ const { getMessages } = require('./messageService');
15
+ const { getPatientInformation } = require('./patientService');
16
+
17
+ const ASSISTANT_FIELDS = ['email', 'doctor_match', 'office_label', 'template_content_sid'];
18
+ const PATIENT_FIELDS = ['whatsapp_id', 'name', 'doctor'];
19
+ const HIDDEN_ORIGINS = ['system', 'instruction'];
20
+ const DEFAULT_MESSAGE_LIMIT = 30;
21
+ const MAX_MESSAGE_LIMIT = 50;
22
+ const MAX_TEXT_LENGTH = 1500;
23
+ const MAX_TEMPLATE_TEXT_LENGTH = 800;
24
+
25
+ async function getOfficeAssistant(email) {
26
+ const normalized = String(email ?? '').trim().toLowerCase();
27
+ if (!normalized) return null;
28
+
29
+ const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {active})`;
30
+ const [assistant] = await getRecordByFilter(Monitoreo_ID, 'office_assistants', formula, null, ASSISTANT_FIELDS, true) || [];
31
+ const doctor = inlineOf(assistant?.doctor_match);
32
+ const label = inlineOf(assistant?.office_label);
33
+ if (!doctor || !label) return null;
34
+
35
+ return {
36
+ email: normalized,
37
+ doctor,
38
+ label,
39
+ templateContentSid: inlineOf(assistant.template_content_sid) || null,
40
+ };
41
+ }
42
+
43
+ async function requireOfficeAssistant(email) {
44
+ const assistant = await getOfficeAssistant(email);
45
+ if (!assistant) throw httpError(403, 'Only an active office assistant can use the office view');
46
+ return assistant;
47
+ }
48
+
49
+ async function officePatientCode(assistant, code) {
50
+ const patientCode = ensureWhatsAppFormat(String(code ?? '').trim());
51
+ if (!PATIENT_CODE.test(patientCode)) throw httpError(400, 'A valid WhatsApp ID is required');
52
+
53
+ const patient = await getPatientInformation(patientCode);
54
+ if (!patient || inlineOf(patient.doctor) !== assistant.doctor) throw httpError(404, 'Patient not found');
55
+ return patientCode;
56
+ }
57
+
58
+ async function listOfficePatients({ requestedBy }) {
59
+ const assistant = await requireOfficeAssistant(requestedBy);
60
+ const patients = await getRecordByFilter(Estado_General_ID, 'estado_general', fieldEquals('doctor', assistant.doctor), undefined, PATIENT_FIELDS) || [];
61
+
62
+ return patients
63
+ .filter((patient) => inlineOf(patient.doctor) === assistant.doctor && inlineOf(patient.whatsapp_id))
64
+ .map((patient) => ({ code: inlineOf(patient.whatsapp_id), name: inlineOf(patient.name) || null }))
65
+ .sort((a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''), 'es'));
66
+ }
67
+
68
+ const officeVisibleQuery = (patientCode, assistant) => ({
69
+ numero: patientCode,
70
+ group_id: null,
71
+ origin: { $nin: HIDDEN_ORIGINS },
72
+ $or: [
73
+ { from_me: false },
74
+ { from_me: true, triggeredBy: assistant.email },
75
+ { from_me: true, origin: 'whatsapp_platform', plainBody: { $regex: `^${escapeRegExp(assistant.label)}:` } },
76
+ ],
77
+ });
78
+
79
+ async function readOfficeMessages({ requestedBy, code, limit }) {
80
+ const assistant = await requireOfficeAssistant(requestedBy);
81
+ const patientCode = await officePatientCode(assistant, code);
82
+ const size = Math.min(Math.max(parseInt(limit, 10) || DEFAULT_MESSAGE_LIMIT, 1), MAX_MESSAGE_LIMIT);
83
+
84
+ const [messages, inWindow] = await Promise.all([
85
+ getMessages(officeVisibleQuery(patientCode, assistant), { sort: { createdAt: -1 }, limit: size }),
86
+ isWithin24HourWindow(patientCode),
87
+ ]);
88
+
89
+ return {
90
+ code: patientCode,
91
+ inWindow,
92
+ messages: messages.reverse().map((message) => ({
93
+ id: String(message._id),
94
+ body: message.plainBody ?? '',
95
+ mediaType: message.media?.mediaType ?? null,
96
+ sender: message.from_me ? 'office' : 'patient',
97
+ status: message.statusInfo?.status ?? null,
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,15 +2,17 @@ const { Symptoms_ID: symptomsId } = require('../config/airtableConfig');
2
2
  const { firstOf } = require('../utils/coercionUtils');
3
3
  const { paginate } = require('../utils/paginationUtils');
4
4
  const { MapCache } = require('../utils/MapCache');
5
+ const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel');
6
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
5
7
  const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
6
8
  const { getRecordByFilter } = require('./airtableService');
9
+ const { getMessages } = require('./messageService');
7
10
 
8
11
  const DEFAULT_LIMIT = 50;
9
12
  const CACHE_TTL_MS = 60 * 1000;
10
13
 
11
14
  const CAROUSEL_DELIVERY_FIELDS = [
12
15
  'twilio_sent',
13
- 'first_attmp_send',
14
16
  'delivered',
15
17
  'date_delivered_at',
16
18
  'twilio_error',
@@ -28,10 +30,13 @@ const CAROUSEL_INDEX_FIELDS = ['recordID', 'Created'];
28
30
  const CAROUSEL_STATUS_FIELDS = [
29
31
  'recordID',
30
32
  'Created',
33
+ 'cluster_resolutions',
31
34
  ...CAROUSEL_DELIVERY_FIELDS,
32
35
  ];
33
36
 
34
37
  const RESOLUTION_FIELDS = ['rank', 'element_name_short'];
38
+ const FIRST_RESOLUTION_VARIABLE = '2';
39
+ const UNSUCCESSFUL_SEND_STATUSES = ['failed', 'undelivered'];
35
40
  const carouselCache = new MapCache({ maxSize: 30, ttl: CACHE_TTL_MS });
36
41
  const carouselRowCache = new MapCache({ maxSize: 500, ttl: CACHE_TTL_MS });
37
42
  const inFlight = new Map();
@@ -56,7 +61,8 @@ function deliveryStatus(row) {
56
61
  if (delivered === 'read' || delivered === 'leído' || delivered === 'leido') return 'read';
57
62
  if (delivered === 'failed' || delivered === 'undelivered') return 'failed';
58
63
  if (delivered) return 'delivered';
59
- if (firstOf(row.twilio_sent) || row.first_attmp_send) return 'sent';
64
+ // pending/queued, or an attempt Twilio never confirmed, has not left yet.
65
+ if (String(firstOf(row.twilio_sent) || '').trim().toLowerCase() === 'sent') return 'sent';
60
66
  return 'queued';
61
67
  }
62
68
 
@@ -66,6 +72,65 @@ const deliveryOf = (row) => ({
66
72
  error: row.twilio_error || null,
67
73
  });
68
74
 
75
+ function sentDeliveryStatus(status) {
76
+ if (UNSUCCESSFUL_SEND_STATUSES.includes(status)) return 'failed';
77
+ return DELIVERY_ATTEMPT_LANDED_STATUSES.includes(status) ? status : 'queued';
78
+ }
79
+
80
+ function sentDeliveryOf(message) {
81
+ const statusInfo = message.statusInfo || {};
82
+ const status = sentDeliveryStatus(statusInfo.status);
83
+ return {
84
+ status,
85
+ statusUpdatedAt: statusInfo.updatedAt || null,
86
+ error: status === 'failed' ? statusInfo.errorMessage || null : null,
87
+ };
88
+ }
89
+
90
+ const reachedPatient = (message) => DELIVERY_ATTEMPT_LANDED_STATUSES.includes(message.statusInfo?.status);
91
+
92
+ const firstResolutionOf = (row) => (
93
+ Array.isArray(row.cluster_resolutions) ? row.cluster_resolutions[0] || null : null
94
+ );
95
+
96
+ async function sendsByFirstResolution(code, rows) {
97
+ const resolutionIds = [...new Set(rows.map(firstResolutionOf).filter(Boolean))];
98
+ if (!resolutionIds.length) return new Map();
99
+
100
+ const attempts = await DeliveryAttempt.find({
101
+ [`variables.${FIRST_RESOLUTION_VARIABLE}`]: { $in: resolutionIds },
102
+ }).select('messageId variables').sort({ attemptedAt: 1 }).lean();
103
+ if (!attempts.length) return new Map();
104
+
105
+ const messages = await getMessages({
106
+ _id: { $in: attempts.map((attempt) => attempt.messageId) },
107
+ numero: ensureWhatsAppFormat(code),
108
+ }, { select: '_id createdAt statusInfo' });
109
+ const messageById = new Map(messages.map((message) => [String(message._id), message]));
110
+
111
+ const sends = new Map();
112
+ attempts.forEach((attempt) => {
113
+ const message = messageById.get(String(attempt.messageId));
114
+ if (!message) return;
115
+ const resolutionId = attempt.variables[FIRST_RESOLUTION_VARIABLE];
116
+ const current = sends.get(resolutionId);
117
+ if (!current || (!reachedPatient(current) && reachedPatient(message))) {
118
+ sends.set(resolutionId, message);
119
+ }
120
+ });
121
+ return sends;
122
+ }
123
+
124
+ function sendFieldsOf(row, sends) {
125
+ const message = sends.get(firstResolutionOf(row));
126
+ if (!message) return { sentAt: null, messageId: null, delivery: deliveryOf(row) };
127
+ return {
128
+ sentAt: message.createdAt || null,
129
+ messageId: String(message._id),
130
+ delivery: sentDeliveryOf(message),
131
+ };
132
+ }
133
+
69
134
  function recommendationIdOf(recommendation) {
70
135
  return recommendation?.recommendation_id || recommendation?.recommendationId || null;
71
136
  }
@@ -149,7 +214,7 @@ async function resolutionMapFor(rows) {
149
214
  return new Map(resolutionRows.map((row) => [row._recordId, row]));
150
215
  }
151
216
 
152
- function projectCarousel(row, resolutionById) {
217
+ function projectCarousel(row, resolutionById, sends) {
153
218
  const recommendations = parseRecommendations(row.recommendations);
154
219
  const images = Array.isArray(row.images) ? row.images : [];
155
220
  const resolutionsByRank = new Map(
@@ -179,13 +244,13 @@ function projectCarousel(row, resolutionById) {
179
244
  triageRecordId: Array.isArray(row.triaje_symptoms) ? row.triaje_symptoms[0] || null : null,
180
245
  createdAt: row.Created || row._createdTime || null,
181
246
  cards,
182
- delivery: deliveryOf(row),
247
+ ...sendFieldsOf(row, sends),
183
248
  };
184
249
  }
185
250
 
186
- const projectCarouselStatus = (row) => ({
251
+ const projectCarouselStatus = (row, sends) => ({
187
252
  id: row._recordId || row.recordID,
188
- delivery: deliveryOf(row),
253
+ ...sendFieldsOf(row, sends),
189
254
  });
190
255
 
191
256
  async function readPatientCarouselStatuses(code) {
@@ -197,8 +262,9 @@ async function readPatientCarouselStatuses(code) {
197
262
  CAROUSEL_STATUS_FIELDS,
198
263
  true,
199
264
  ) || [];
265
+ const sends = await sendsByFirstResolution(code, rows);
200
266
  return rows
201
- .map(projectCarouselStatus)
267
+ .map((row) => projectCarouselStatus(row, sends))
202
268
  .filter((record) => record.id);
203
269
  }
204
270
 
@@ -259,12 +325,15 @@ async function getRecommendationCarousels({ code, limit, page, baseUrl = '/api/p
259
325
  });
260
326
  const ids = result.records.map((row) => row._recordId || row.recordID).filter(Boolean);
261
327
  const rows = await readPatientCarouselRows(code, ids);
262
- const resolutionById = await resolutionMapFor(rows);
328
+ const [resolutionById, sends] = await Promise.all([
329
+ resolutionMapFor(rows),
330
+ sendsByFirstResolution(code, rows),
331
+ ]);
263
332
  return {
264
333
  ...result,
265
334
  records: rows.map((row) => publicCarousel(
266
335
  code,
267
- projectCarousel(row, resolutionById),
336
+ projectCarousel(row, resolutionById, sends),
268
337
  baseUrl,
269
338
  )),
270
339
  };
@@ -45,6 +45,8 @@ const switchThreadStoppedStatus = async (code, stopped, { byOperator = false } =
45
45
  return result;
46
46
  };
47
47
 
48
+ const setThreadDoNotAlert = async (code, doNotAlert, through = null) => Thread.updateMany({ code }, { $set: { doNotAlertThrough: doNotAlert ? (through || new Date()) : null } });
49
+
48
50
  const setThreadPromptId = async (code, promptId) => {
49
51
  const updateFields = {};
50
52
  Thread.setAssistantId(updateFields, promptId);
@@ -103,5 +105,6 @@ module.exports = {
103
105
  createPlaceholderThread,
104
106
  ensureThreadExists,
105
107
  switchThreadStoppedStatus,
108
+ setThreadDoNotAlert,
106
109
  setThreadPromptId
107
110
  };
@@ -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
- 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 };
@@ -67,6 +67,9 @@ function isQuoteAnchored(quote, source, { strict = false } = {}) {
67
67
  return matched / tokens.length >= QUOTE_ANCHOR_MIN_OVERLAP;
68
68
  }
69
69
 
70
+ const escapeRegExp = (value) => String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
71
+
70
72
  module.exports = {
73
+ escapeRegExp,
71
74
  isQuoteAnchored,
72
75
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.0-dev.9718",
3
+ "version": "5.57.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",