@peopl-health/nexus 5.53.1 → 5.53.3

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,20 +15,10 @@ const { cleanupFiles } = require('../../helpers/filesHelper.js');
15
15
  const { getMessages, countMessages } = require('../../services/messageService');
16
16
 
17
17
  const { getAssistantById } = require('./assistantResolver');
18
- const { recordPausedThreadMessage } = require('./clinicalAirtableService');
19
- const { offerSafetyNet } = require('./pausedSafetyNetService');
18
+ const { coverUnansweredPatient } = require('./pausedSafetyNetService');
20
19
 
21
20
  const MEDIA_BACKLOG_LIMIT = 10;
22
21
 
23
- const pausedAlertText = async (code, newest) => {
24
- if (!newest.interactive_type) return newest.plainBody || newest.body;
25
- const [written] = await getMessages(
26
- { numero: code, from_me: false, interactive_type: null, createdAt: { $lte: newest.createdAt } },
27
- { sort: { createdAt: -1 }, limit: 1 }
28
- );
29
- return written ? written.plainBody || written.body : null;
30
- };
31
-
32
22
  const fetchMediaBacklog = async (code, trigger) => {
33
23
  const [lastOutbound] = await getMessages(
34
24
  { numero: code, from_me: true, createdAt: { $lt: trigger.createdAt } },
@@ -122,12 +112,7 @@ const preProcessMessagesCore = async (code, message_ = null, thread) => {
122
112
  return { shouldProcess: false, messages: null, timings, pendingMediaUpdates: [] };
123
113
  }
124
114
 
125
- if (thread.stopped) {
126
- await Promise.allSettled([
127
- recordPausedThreadMessage({ code, text: await pausedAlertText(code, lastMessage[0]) }),
128
- offerSafetyNet({ code })
129
- ]);
130
- }
115
+ if (thread.stopped) await coverUnansweredPatient({ code });
131
116
 
132
117
  const backlog = await fetchMediaBacklog(code, lastMessage[0]);
133
118
  const replies = [...backlog, ...lastMessage];
@@ -18,7 +18,7 @@ const { getMessages } = require('../../services/messageService');
18
18
  const { getPatientTasks, updatePatientTask } = require('../../services/patientTaskService');
19
19
 
20
20
  const { WriteClaimStore } = require('./writeClaimStore');
21
- const { PAUSED_THREAD_DETAILS_PREFIX, recordUnresolvedRequest } = require('./clinicalAirtableService');
21
+ const { PAUSED_THREAD_DETAILS_PREFIX, recordPausedThreadMessage, recordUnresolvedRequest } = require('./clinicalAirtableService');
22
22
  const { humanRepliedSince, openPledge, stopSafetyNetSweep } = require('./safetyNetPledgeService');
23
23
 
24
24
  const getMessaging = () => require('../../core/NexusMessaging');
@@ -132,6 +132,30 @@ async function offerIsLive(code) {
132
132
  }
133
133
  }
134
134
 
135
+ async function unansweredText(code) {
136
+ const [written] = await getMessages(
137
+ { numero: code, from_me: false, interactive_type: null },
138
+ { sort: { createdAt: -1 }, limit: 1 }
139
+ );
140
+ return written ? written.plainBody || written.body : null;
141
+ }
142
+
143
+ async function coverUnansweredPatient({ code }) {
144
+ if (!code) return;
145
+
146
+ const claim = await acquireSendClaim({ idempotencyKey: `safetynet-cover:${code}` });
147
+ if (!claim.acquired) return;
148
+
149
+ const results = await Promise.allSettled([
150
+ unansweredText(code).then((text) => recordPausedThreadMessage({ code, text })),
151
+ offerSafetyNet({ code }),
152
+ ]);
153
+
154
+ const covered = results.every((r) => r.status === 'fulfilled');
155
+ if (covered) await completeSendClaim(claim.claimId);
156
+ else await releaseSendClaim(claim.claimId);
157
+ }
158
+
135
159
  async function fileUrgentRequest(code, choice) {
136
160
  const copy = REQUEST_COPY[choice];
137
161
  return recordUnresolvedRequest({
@@ -283,6 +307,7 @@ function registerSafetyNetRoutes() {
283
307
  }
284
308
 
285
309
  module.exports = {
310
+ coverUnansweredPatient,
286
311
  disarmSafetyNet,
287
312
  offerSafetyNet,
288
313
  handleSafetyNetTap,
@@ -31,6 +31,7 @@ const { releaseHeldMessages, sweepHeldMessages } = require('../services/heldMess
31
31
  const { BatchingManager } = require('../core/BatchingManager');
32
32
  const { ProcessingPipeline } = require('../core/ProcessingPipeline');
33
33
  const { preProcessMessages, configureOpenAIProvider, AssistantProcessor, TURN_KIND } = require('../clinical');
34
+ const { coverUnansweredPatient } = require('../clinical/services/pausedSafetyNetService');
34
35
  const { buildOutreachCarrier } = require('../clinical/services/outreachCarrierService');
35
36
  const { routineOutreachCollisionReason } = require('../clinical/services/outreachSweepService');
36
37
  const {
@@ -675,8 +676,14 @@ class NexusMessaging {
675
676
  return await this._executeWithPipeline(chatId, 'message', 'preempt',
676
677
  async (preProcessResult, shouldContinue, runId) => {
677
678
  return await this._processMessages(chatId, async () => {
678
- const resolved = await this.assistantProcessor.resolveThread(chatId);
679
- if (!resolved) return null;
679
+ const resolved = await this.assistantProcessor.resolveThread(chatId).catch((error) => {
680
+ logger.warn('[NexusMessaging] Could not resolve an assistant for this patient', { code: chatId, error: error.message });
681
+ return null;
682
+ });
683
+ if (!resolved) {
684
+ await coverUnansweredPatient({ code: chatId });
685
+ return null;
686
+ }
680
687
 
681
688
  const preProcessed = await preProcessMessages(chatId, null, resolved.thread);
682
689
 
@@ -19,7 +19,7 @@ const { sendMessage } = require('../core/NexusMessaging');
19
19
 
20
20
  const { getPatientInformation, logPatientChange } = require('./patientService');
21
21
  const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
22
- const { getEscalationApprover } = require('./physicianService');
22
+ const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
23
23
 
24
24
  const AUDIT_SOURCE = 'escalation_review';
25
25
  const RECENT_REVIEW_LIMIT = 20;
@@ -371,6 +371,17 @@ async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId =
371
371
  return review;
372
372
  }
373
373
 
374
+ async function soleApprover() {
375
+ const approvers = await listEscalationApprovers();
376
+ if (!approvers.length) {
377
+ throw httpError(409, 'No escalation review approver is configured: tick aprueba_vaiven on a physician with a WhatsApp number');
378
+ }
379
+ if (approvers.length > 1) {
380
+ throw httpError(409, `More than one physician approves escalation reviews; name one of: ${approvers.map((approver) => approver.email).join(', ')}`);
381
+ }
382
+ return approvers[0];
383
+ }
384
+
374
385
  async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, requestId = null } = {}) {
375
386
  const reviewId = reviewIdOf(id);
376
387
  const operator = requiredText(sentBy, 'sentBy');
@@ -383,7 +394,7 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
383
394
  const draft = review.drafts[draftNumber - 1];
384
395
  let approver = null;
385
396
  if (mode === 'sent_whatsapp') {
386
- approver = await getEscalationApprover(physicianEmail);
397
+ approver = physicianEmail ? await getEscalationApprover(physicianEmail) : await soleApprover();
387
398
  if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
388
399
  }
389
400
 
@@ -6,6 +6,12 @@ const { getRecordByFilter } = require('./airtableService');
6
6
 
7
7
  const APPROVER_FIELDS = ['physician_name', 'email', 'phone_number'];
8
8
 
9
+ const approverOf = (physician, email = null) => ({
10
+ name: physician.physician_name || null,
11
+ email: email ?? (physician.email ? String(physician.email).trim().toLowerCase() : null),
12
+ phone: physician.phone_number || null,
13
+ });
14
+
9
15
  async function getEscalationApprover(email) {
10
16
  const normalized = String(email ?? '').trim().toLowerCase();
11
17
  if (!normalized) return null;
@@ -14,7 +20,12 @@ async function getEscalationApprover(email) {
14
20
  const [physician] = await getRecordByFilter(Monitoreo_ID, 'physicians', formula, null, APPROVER_FIELDS, true) || [];
15
21
  if (!physician) return null;
16
22
 
17
- return { name: physician.physician_name || null, email: normalized, phone: physician.phone_number || null };
23
+ return approverOf(physician, normalized);
24
+ }
25
+
26
+ async function listEscalationApprovers() {
27
+ const physicians = await getRecordByFilter(Monitoreo_ID, 'physicians', '{aprueba_vaiven}', null, APPROVER_FIELDS, true) || [];
28
+ return physicians.filter((physician) => physician.email).map((physician) => approverOf(physician));
18
29
  }
19
30
 
20
- module.exports = { getEscalationApprover };
31
+ module.exports = { getEscalationApprover, listEscalationApprovers };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.53.1",
3
+ "version": "5.53.3",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",