@peopl-health/nexus 5.52.0-dev.7754 → 5.52.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.
@@ -16,19 +16,9 @@ const { getMessages, countMessages } = require('../../services/messageService');
16
16
 
17
17
  const { getAssistantById } = require('./assistantResolver');
18
18
  const { recordPausedThreadMessage } = require('./clinicalAirtableService');
19
- const { offerSafetyNet } = 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 recordPausedThreadMessage({ code, text: lastMessage[0].plainBody || lastMessage[0].body });
131
116
 
132
117
  const backlog = await fetchMediaBacklog(code, lastMessage[0]);
133
118
  const replies = [...backlog, ...lastMessage];
@@ -14,7 +14,6 @@ const recentIntakeCache = new WriteClaimStore({ namespace: 'intake', ttlMs: INTA
14
14
  const EMERGENCY_MERGE_WINDOW_MS = 5 * 60 * 1000;
15
15
  const EMERGENCY_URGENCY_RANK = { routine: 0, urgent: 1, asap: 2, stat: 3 };
16
16
  const recentEmergencyCache = new WriteClaimStore({ namespace: 'emergency', ttlMs: EMERGENCY_MERGE_WINDOW_MS, maxSize: 500 });
17
- const PAUSED_THREAD_DETAILS_PREFIX = 'Bot en pausa:';
18
17
  const PAUSED_ALERT_WINDOW_MS = 4 * 60 * 60 * 1000;
19
18
  const recentPausedAlertCache = new WriteClaimStore({ namespace: 'paused-alert', ttlMs: PAUSED_ALERT_WINDOW_MS, maxSize: 1000 });
20
19
  const UNRESOLVED_WINDOW_MS = 30 * 60 * 1000;
@@ -120,7 +119,7 @@ async function recordPausedThreadMessage({ code, text }) {
120
119
  code,
121
120
  trace: null,
122
121
  question: text || 'El paciente envió un archivo sin texto.',
123
- details: `${PAUSED_THREAD_DETAILS_PREFIX} el paciente ${code} escribió y nadie ha respondido. Revisar la conversación.`,
122
+ details: `Bot en pausa: el paciente ${code} escribió y nadie ha respondido. Revisar la conversación.`,
124
123
  category: 'contact_team_member',
125
124
  urgency: 'soon',
126
125
  });
@@ -502,7 +501,6 @@ async function recordClusterRecommendationsMirror({ code, triageRecordId, step1
502
501
  }
503
502
 
504
503
  module.exports = {
505
- PAUSED_THREAD_DETAILS_PREFIX,
506
504
  recordUnresolvedRequest,
507
505
  recordPausedThreadMessage,
508
506
  recordEmergency,
@@ -3,11 +3,7 @@ const { _resetMetaConfig } = require('../config/metaConfig');
3
3
  const { _clearClinicalContextCache } = require('../helpers/patientInformationHelper');
4
4
  const { setPreprocessingHandler } = require('../services/preprocessingService');
5
5
  const { clearTriageHistoryCache } = require('../services/triageHistoryService');
6
- const { clearInteractiveRoutes } = require('../core/interactiveRouteService');
7
6
  const { _resetDefaultInstance } = require('../core/NexusMessaging');
8
- const { _resetSafetyNetConfig } = require('../clinical/config/safetyNetConfig');
9
- const { _resetSafetyNetState } = require('../clinical/services/pausedSafetyNetService');
10
- const { stopSafetyNetSweep } = require('../clinical/services/safetyNetPledgeService');
11
7
  const { _clearRecentIntakeCache } = require('../clinical/services/clinicalAirtableService');
12
8
  const { _clearExtractorConfigCache } = require('../clinical/services/clinicalExtractionService');
13
9
  const { _resetRegistry } = require('../clinical/services/assistantResolver');
@@ -18,10 +14,6 @@ function resetAll() {
18
14
  _resetRegistry();
19
15
  _resetLLMState();
20
16
  setPreprocessingHandler(null);
21
- clearInteractiveRoutes();
22
- _resetSafetyNetConfig();
23
- _resetSafetyNetState();
24
- stopSafetyNetSweep();
25
17
  _resetOverrides();
26
18
  _resetMetaConfig();
27
19
  _clearClinicalContextCache();
@@ -4,6 +4,7 @@ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
4
  const {
5
5
  addCallLog,
6
6
  addDraft,
7
+ cancelEscalationReview,
7
8
  closeEscalationReview,
8
9
  getEscalationReviewById,
9
10
  handOffToDoctor,
@@ -135,6 +136,16 @@ const closeEscalationReviewController = async (req, res) => {
135
136
  }
136
137
  };
137
138
 
139
+ const cancelEscalationReviewController = async (req, res) => {
140
+ try {
141
+ const { triggeredBy, reason = null } = req.body || {};
142
+ const review = await cancelEscalationReview({ id: req.params.id, cancelledBy: triggeredBy, reason, requestId: req.requestId });
143
+ res.status(200).json({ success: true, review });
144
+ } catch (error) {
145
+ respondWithError(res, error, 'cancelling escalation review', { reviewId: req.params?.id });
146
+ }
147
+ };
148
+
138
149
  const syncEscalationReviewCaseController = async (req, res) => {
139
150
  try {
140
151
  const { triggeredBy } = req.body || {};
@@ -152,6 +163,7 @@ const syncEscalationReviewCaseController = async (req, res) => {
152
163
  module.exports = {
153
164
  addEscalationReviewCallLogController,
154
165
  addEscalationReviewDraftController,
166
+ cancelEscalationReviewController,
155
167
  closeEscalationReviewController,
156
168
  getEscalationReviewController,
157
169
  handOffEscalationReviewController,
@@ -46,7 +46,6 @@ const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
46
46
  const { createQueueAdapter } = require('../queue');
47
47
  const { ScheduledMessageJob } = require('../jobs/ScheduledMessageJob');
48
48
  const { TemplateApprovalJob } = require('../jobs/TemplateApprovalJob');
49
- const { invokeInteractiveRoute } = require('./interactiveRouteService');
50
49
 
51
50
  const { PhiProcessor } = require('./PhiProcessor');
52
51
 
@@ -583,7 +582,6 @@ class NexusMessaging {
583
582
  }
584
583
 
585
584
  async handleInteractive(messageData) {
586
- await invokeInteractiveRoute(messageData);
587
585
  if (this.handlers.onInteractive) return await this.handlers.onInteractive(messageData, this);
588
586
  }
589
587
 
@@ -14,7 +14,6 @@ const ATTENTION_OPERATIONS_STATUS = 'pendiente';
14
14
  const ATTENTION_CASE_WINDOW_DAYS = 14;
15
15
  const ATTENTION_CASE_WINDOW_MS = ATTENTION_CASE_WINDOW_DAYS * 24 * 60 * 60 * 1000;
16
16
  const URGENT_REQUEST_URGENCY = 'urgent';
17
- const REQUEST_URGENCIES = ['routine', 'soon', 'urgent'];
18
17
  const URGENT_CASE_TYPES = ['Urgencia', 'Emergencia'];
19
18
 
20
19
  const isRequestOpen = (status) => !CLOSED_REQUEST_STATUSES.includes(status);
@@ -41,7 +40,6 @@ module.exports = {
41
40
  ATTENTION_CASE_WINDOW_DAYS,
42
41
  ATTENTION_OPERATIONS_STATUS,
43
42
  ATTENTION_REQUEST_STATUS,
44
- REQUEST_URGENCIES,
45
43
  isCaseOpen,
46
44
  isCaseUrgent,
47
45
  isRequestOpen,
package/lib/index.d.ts CHANGED
@@ -22,14 +22,8 @@ declare module '@peopl-health/nexus' {
22
22
  type?: 'message' | 'interactive' | 'media' | 'command' | 'keyword' | 'flow' | 'empty';
23
23
  }
24
24
 
25
- export function registerInteractiveRoute(
26
- prefix: string,
27
- handler: (tap: { code: string; payload: string | null; title: string | null; messageData: unknown }) => unknown
28
- ): void;
29
- export function clearInteractiveRoutes(): void;
30
-
31
25
  export interface InteractiveData {
32
- type: 'button' | 'list' | 'flow' | 'quick_reply';
26
+ type: 'button' | 'list' | 'flow';
33
27
  payload?: string;
34
28
  title?: string;
35
29
  description?: string;
package/lib/index.js CHANGED
@@ -26,10 +26,6 @@ const { setModelDatabases, setModelDatabase, getModelDatabase, connect: mongoCon
26
26
  const { TwilioProvider } = require('./adapters/TwilioProvider');
27
27
  const { BaileysProvider } = require('./adapters/BaileysProvider');
28
28
  const { setPreprocessingHandler, hasPreprocessingHandler, invokePreprocessingHandler } = require('./services/preprocessingService');
29
- const { registerInteractiveRoute, clearInteractiveRoutes } = require('./core/interactiveRouteService');
30
- const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
31
- const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
32
- const { startSafetyNetSweep, stopSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
33
29
  const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
34
30
  const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
35
31
  const { createWorkflowRunner } = require('./core/workflowRunner');
@@ -188,16 +184,6 @@ class Nexus {
188
184
  logger.warn('Warning: failed to register clinical tools:', e?.message || e);
189
185
  }
190
186
 
191
- try {
192
- configureSafetyNet(options.safetyNet || {});
193
- if (registerSafetyNetRoutes()) {
194
- startSafetyNetSweep();
195
- logger.info('[Nexus] paused-thread safety net armed');
196
- }
197
- } catch (e) {
198
- logger.warn('Warning: failed to arm the paused-thread safety net:', e?.message || e);
199
- }
200
-
201
187
  await this.messaging.initializeLlmMonitor();
202
188
 
203
189
  this.isInitialized = true;
@@ -252,7 +238,6 @@ class Nexus {
252
238
  }
253
239
 
254
240
  async shutdown({ drainMs, abortGraceMs, teardownMs, closeStorage = true } = {}) {
255
- stopSafetyNetSweep();
256
241
  if (this._shutdownPromise) return this._shutdownPromise;
257
242
  this._shutdownPromise = (async () => {
258
243
  const result = await this.messaging.shutdown({ drainMs, abortGraceMs, teardownMs });
@@ -295,8 +280,6 @@ module.exports = {
295
280
  setPreprocessingHandler,
296
281
  hasPreprocessingHandler,
297
282
  invokePreprocessingHandler,
298
- registerInteractiveRoute,
299
- clearInteractiveRoutes,
300
283
  routes,
301
284
  syncClinicalContext,
302
285
  runProactiveOutreachSweep,
@@ -7,6 +7,7 @@ const { logger } = require('../utils/logger');
7
7
  const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
8
  const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
9
9
  const INTERRUPTED_STATUSES = ['handing_off', 'sending'];
10
+ const CANCELLABLE_STATUSES = ['open', 'documenting', 'draft_ready'];
10
11
  const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
11
12
  const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
12
13
 
@@ -83,6 +84,7 @@ const escalationReviewSchema = new mongoose.Schema({
83
84
  'indications_queued',
84
85
  'indications_sent',
85
86
  'closed',
87
+ 'cancelled',
86
88
  ],
87
89
  default: 'open',
88
90
  },
@@ -100,6 +102,7 @@ const escalationReviewSchema = new mongoose.Schema({
100
102
 
101
103
  escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
102
104
  escalationReviewSchema.index({ activeCaseKey: 1 }, { unique: true, sparse: true });
105
+ escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
103
106
 
104
107
  const getEscalationReview = () => {
105
108
  const dbName = getModelDatabase('EscalationReview');
@@ -110,6 +113,7 @@ const getEscalationReview = () => {
110
113
 
111
114
  module.exports = {
112
115
  CALL_OUTCOMES,
116
+ CANCELLABLE_STATUSES,
113
117
  DECISION_SOURCES,
114
118
  DOCTOR_DECISIONS,
115
119
  HANDOFF_MODES,
@@ -126,6 +126,7 @@ const escalationReviewRouteDefinitions = {
126
126
  'POST /:id/decisions': 'recordEscalationReviewDecisionController',
127
127
  'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
128
128
  'POST /:id/close': 'closeEscalationReviewController',
129
+ 'POST /:id/cancel': 'cancelEscalationReviewController',
129
130
  'POST /:id/case-sync': 'syncEscalationReviewCaseController'
130
131
  };
131
132
 
@@ -285,6 +286,7 @@ const builtInControllers = {
285
286
  recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
286
287
  sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
287
288
  closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
289
+ cancelEscalationReviewController: escalationReviewController.cancelEscalationReviewController,
288
290
  syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
289
291
  };
290
292
 
@@ -6,6 +6,7 @@ const { logger } = require('../utils/logger');
6
6
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
7
  const {
8
8
  CALL_OUTCOMES,
9
+ CANCELLABLE_STATUSES,
9
10
  DECISION_SOURCES,
10
11
  DOCTOR_DECISIONS,
11
12
  HANDOFF_MODES,
@@ -248,6 +249,24 @@ const deliveryTransport = (message, result) => {
248
249
  return result.deferred ? 'template_recovery' : 'text';
249
250
  };
250
251
 
252
+ let indexesReady = new WeakMap();
253
+
254
+ function ensureActiveReviewIndex(EscalationReview) {
255
+ const pending = indexesReady.get(EscalationReview);
256
+ if (pending) return pending;
257
+
258
+ const building = EscalationReview.ensureIndexes().catch((error) => {
259
+ indexesReady.delete(EscalationReview);
260
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
261
+ logger.error('[EscalationReview] A uniqueness index could not be built', { error: redactedError(error) });
262
+ throw httpError(409, 'Escalation reviews cannot be opened: a uniqueness index could not be built. The server log names the index and the conflict; resolve it and retry.');
263
+ });
264
+ indexesReady.set(EscalationReview, building);
265
+ return building;
266
+ }
267
+
268
+ const _resetEscalationReviewIndexes = () => { indexesReady = new WeakMap(); };
269
+
251
270
  async function openEscalationReview({ code, patientCaseRecordId = null, openedBy, requestId = null } = {}) {
252
271
  const patientCode = patientCodeOf(code);
253
272
  const operator = requiredText(openedBy, 'openedBy');
@@ -264,14 +283,14 @@ async function openEscalationReview({ code, patientCaseRecordId = null, openedBy
264
283
  }
265
284
 
266
285
  const EscalationReview = getEscalationReview();
267
- await EscalationReview.init();
286
+ await ensureActiveReviewIndex(EscalationReview);
268
287
  let review;
269
288
  try {
270
289
  review = (await EscalationReview.create(fields)).toObject();
271
290
  } catch (error) {
272
- if (error?.code !== DUPLICATE_KEY_ERROR || !fields.activeCaseKey) throw error;
273
- const existing = await EscalationReview.findOne({ activeCaseKey: fields.activeCaseKey }).lean();
274
- if (!existing) throw httpError(409, 'The patient case review changed while opening; try again');
291
+ if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
292
+ const existing = await EscalationReview.findOne({ patientCode, closedAt: null }).lean();
293
+ if (!existing) throw httpError(409, 'A closed review still holds this patient case; try again in a moment');
275
294
  return { review: existing, created: false };
276
295
  }
277
296
  await audit(review, operator, requestId, { action: 'opened', patientCaseRecordId });
@@ -524,6 +543,17 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
524
543
  return syncCase(review, operator, requestId);
525
544
  }
526
545
 
546
+ async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
547
+ const reviewId = reviewIdOf(id);
548
+ const operator = requiredText(cancelledBy, 'cancelledBy');
549
+ const review = await updateReview(reviewId, CANCELLABLE_STATUSES, {
550
+ $set: { status: 'cancelled', closedBy: operator, closedAt: new Date() },
551
+ $unset: { activeCaseKey: '' },
552
+ });
553
+ await audit(review, operator, requestId, { action: 'cancelled', reason: optionalText(reason) });
554
+ return review;
555
+ }
556
+
527
557
  async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
528
558
  const reviewId = reviewIdOf(id);
529
559
  const operator = requiredText(syncedBy, 'syncedBy');
@@ -531,8 +561,10 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
531
561
  }
532
562
 
533
563
  module.exports = {
564
+ _resetEscalationReviewIndexes,
534
565
  addCallLog,
535
566
  addDraft,
567
+ cancelEscalationReview,
536
568
  closeEscalationReview,
537
569
  getEscalationReviewById,
538
570
  handOffToDoctor,
@@ -4,7 +4,6 @@ const { httpError } = require('../utils/httpErrorUtils');
4
4
 
5
5
  const { escapeFormulaValue, fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
6
6
  const {
7
- REQUEST_URGENCIES,
8
7
  isCaseOpen,
9
8
  isCaseUrgent,
10
9
  isRequestOpen,
@@ -110,7 +109,6 @@ const TASK_KINDS = {
110
109
  toTask: toRequest,
111
110
  writable: {
112
111
  status: { field: 'status', options: REQUEST_STATUSES },
113
- urgency: { field: 'urgency', options: REQUEST_URGENCIES },
114
112
  note: { field: 'Observaciones' },
115
113
  },
116
114
  },
@@ -172,7 +170,7 @@ async function getPatientTasks(code) {
172
170
  requests: requests.attentionCount,
173
171
  isUrgent: requests.isUrgent || cases.isUrgent,
174
172
  },
175
- options: { requestStatus: REQUEST_STATUSES, requestUrgency: REQUEST_URGENCIES, caseStatus: CASE_STATUSES, operationsStatus: OPERATIONS_STATUSES },
173
+ options: { requestStatus: REQUEST_STATUSES, caseStatus: CASE_STATUSES, operationsStatus: OPERATIONS_STATUSES },
176
174
  };
177
175
  }
178
176
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.52.0-dev.7754",
3
+ "version": "5.52.0",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,64 +0,0 @@
1
- const runtimeConfig = require('../../config/runtimeConfig');
2
-
3
- const DEFAULT_OFFER_WINDOW_MS = 4 * 60 * 60 * 1000;
4
- const DEFAULT_HUMAN_QUIET_MS = 60 * 60 * 1000;
5
- const DEFAULT_TAP_WINDOW_MS = 30 * 60 * 1000;
6
- const DEFAULT_PLEDGE_MS = 30 * 60 * 1000;
7
- const DEFAULT_SWEEP_INTERVAL_MS = 5 * 60 * 1000;
8
-
9
- const CONTACT_WINDOW = { timeZone: 'America/Mexico_City', startHour: 8, endHour: 21 };
10
-
11
- const SAFETY_NET_SOURCE = 'paused_safety_net';
12
-
13
- const humanReplyFilter = (code, since) => ({
14
- numero: code,
15
- from_me: true,
16
- content_sid: null,
17
- origin: { $ne: 'assistant' },
18
- triggeredBy: { $ne: SAFETY_NET_SOURCE },
19
- createdAt: { $gt: since }
20
- });
21
-
22
- const CHOICE_LABEL_KEYS = {
23
- urgent: 'PAUSED_SAFETY_NET_URGENT_LABEL',
24
- callback: 'PAUSED_SAFETY_NET_CALLBACK_LABEL',
25
- later: 'PAUSED_SAFETY_NET_LATER_LABEL'
26
- };
27
-
28
- let injected = {};
29
-
30
- const configureSafetyNet = (config = {}) => {
31
- injected = config && typeof config === 'object' ? config : {};
32
- };
33
-
34
- const _resetSafetyNetConfig = () => {
35
- injected = {};
36
- };
37
-
38
- const text = (key, envKey) => {
39
- const raw = injected[key] ?? runtimeConfig.get(envKey);
40
- const value = String(raw ?? '').trim();
41
- return value || null;
42
- };
43
-
44
- const duration = (key, envKey, fallback) => {
45
- const raw = Number(injected[key] ?? runtimeConfig.get(envKey));
46
- return Number.isFinite(raw) && raw > 0 ? raw : fallback;
47
- };
48
-
49
- module.exports = {
50
- CONTACT_WINDOW,
51
- SAFETY_NET_SOURCE,
52
- humanReplyFilter,
53
- CHOICE_LABEL_KEYS,
54
- configureSafetyNet,
55
- _resetSafetyNetConfig,
56
- getSafetyNetContentSid: () => text('contentSid', 'PAUSED_SAFETY_NET_CONTENT_SID'),
57
- getSafetyNetPhone: () => text('phone', 'PAUSED_SAFETY_NET_PHONE'),
58
- getSafetyNetLabel: (choice) => text(`${choice}Label`, CHOICE_LABEL_KEYS[choice]),
59
- getOfferWindowMs: () => duration('offerWindowMs', 'PAUSED_SAFETY_NET_WINDOW_MS', DEFAULT_OFFER_WINDOW_MS),
60
- getHumanQuietMs: () => duration('humanQuietMs', 'SAFETY_NET_HUMAN_QUIET_MS', DEFAULT_HUMAN_QUIET_MS),
61
- getTapWindowMs: () => duration('tapWindowMs', 'SAFETY_NET_TAP_WINDOW_MS', DEFAULT_TAP_WINDOW_MS),
62
- getPledgeMs: () => duration('pledgeMs', 'SAFETY_NET_PLEDGE_MS', DEFAULT_PLEDGE_MS),
63
- getSweepIntervalMs: () => duration('sweepIntervalMs', 'SAFETY_NET_SWEEP_INTERVAL_MS', DEFAULT_SWEEP_INTERVAL_MS)
64
- };
@@ -1,298 +0,0 @@
1
- const {
2
- CONTACT_WINDOW,
3
- SAFETY_NET_SOURCE,
4
- getHumanQuietMs,
5
- getOfferWindowMs,
6
- getPledgeMs,
7
- getSafetyNetContentSid,
8
- getSafetyNetLabel,
9
- getSafetyNetPhone,
10
- getTapWindowMs
11
- } = require('../config/safetyNetConfig');
12
- const { logger } = require('../../utils/logger');
13
-
14
- const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../../helpers/sendClaimHelper');
15
-
16
- const { clearInteractiveRoutes, normalizePayload: normalize, registerInteractiveRoute } = require('../../core/interactiveRouteService');
17
- const { getMessages } = require('../../services/messageService');
18
- const { getPatientTasks, updatePatientTask } = require('../../services/patientTaskService');
19
-
20
- const { WriteClaimStore } = require('./writeClaimStore');
21
- const { PAUSED_THREAD_DETAILS_PREFIX, recordUnresolvedRequest } = require('./clinicalAirtableService');
22
- const { humanRepliedSince, openPledge, stopSafetyNetSweep } = require('./safetyNetPledgeService');
23
-
24
- const getMessaging = () => require('../../core/NexusMessaging');
25
-
26
- const SOURCE = SAFETY_NET_SOURCE;
27
- const PAYLOAD_PREFIX = 'peopl_safetynet_';
28
- const CHOICES = ['urgent', 'callback', 'later'];
29
- const REQUEST_CATEGORY = 'contact_team_member';
30
- const CAN_WAIT_NOTE = 'El paciente indicó que su solicitud puede esperar.';
31
- const ATTENDED_STATUS = 'sin atender';
32
-
33
- const REQUEST_COPY = {
34
- urgent: {
35
- question: 'El paciente indicó que su situación es urgente',
36
- details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y eligió "urgencia". Se le dio el número para llamar. Revisar la conversación ahora.`
37
- },
38
- callback: {
39
- question: 'El paciente pidió que el equipo lo contacte hoy',
40
- details: (code) => `El paciente ${code} recibió el aviso de bot en pausa y pidió que lo contacten. Se le prometió contacto; revisar la conversación.`
41
- }
42
- };
43
-
44
- let offerClaimStore = null;
45
- let tapClaimStore = null;
46
- let phoneCheckedFor = null;
47
-
48
- const offerClaims = () => {
49
- if (!offerClaimStore) offerClaimStore = new WriteClaimStore({ namespace: 'paused-safety-net', ttlMs: getOfferWindowMs() });
50
- return offerClaimStore;
51
- };
52
-
53
- const tapClaims = () => {
54
- if (!tapClaimStore) tapClaimStore = new WriteClaimStore({ namespace: 'safety-net-choice', ttlMs: getTapWindowMs() });
55
- return tapClaimStore;
56
- };
57
-
58
- const disarmSafetyNet = () => {
59
- clearInteractiveRoutes();
60
- stopSafetyNetSweep();
61
- };
62
-
63
- const _resetSafetyNetState = () => {
64
- offerClaimStore = null;
65
- tapClaimStore = null;
66
- phoneCheckedFor = null;
67
- };
68
-
69
- function matchSafetyNetChoice(payload, title) {
70
- const candidate = normalize(payload);
71
- if (candidate.startsWith(PAYLOAD_PREFIX)) {
72
- const suffix = candidate.slice(PAYLOAD_PREFIX.length);
73
- return CHOICES.find((choice) => choice === suffix) || null;
74
- }
75
-
76
- const label = normalize(title) || candidate;
77
- if (!label) return null;
78
- return CHOICES.find((choice) => {
79
- const configured = normalize(getSafetyNetLabel(choice));
80
- return configured && configured === label;
81
- }) || null;
82
- }
83
-
84
- async function warnIfPhoneDiffersFromTemplate(contentSid) {
85
- const phone = getSafetyNetPhone();
86
- if (!phone || phoneCheckedFor === contentSid) return;
87
- phoneCheckedFor = contentSid;
88
- try {
89
- const body = await getMessaging().requireProvider().renderTemplate(contentSid);
90
- const digits = (value) => String(value ?? '').replace(/\D/g, '');
91
- if (body && !digits(body).includes(digits(phone))) {
92
- logger.error('[PausedSafetyNet] The configured phone number is absent from the template body', { contentSid });
93
- }
94
- } catch (error) {
95
- phoneCheckedFor = null;
96
- logger.warn('[PausedSafetyNet] Could not read the template to check the phone number', { contentSid, error: error.message });
97
- }
98
- }
99
-
100
- async function offerSafetyNet({ code }) {
101
- try {
102
- const contentSid = getSafetyNetContentSid();
103
- if (!code || !contentSid || !getSafetyNetPhone()) return { sent: false, reason: 'not_configured' };
104
- if (await offerClaims().get(code)) return { sent: false, reason: 'recent_offer' };
105
- if (await humanRepliedSince(code, new Date(Date.now() - getHumanQuietMs()))) return { sent: false, reason: 'human_active' };
106
-
107
- await warnIfPhoneDiffersFromTemplate(contentSid);
108
-
109
- const result = await getMessaging().sendMessage({ code, contentSid, triggeredBy: SOURCE });
110
- const sent = result?.success === true || result?.completed === true;
111
- if (!sent) return { sent: false, reason: result?.status || 'send_failed' };
112
-
113
- await offerClaims().set(code, true);
114
- return { sent: true, reason: null };
115
- } catch (error) {
116
- logger.error('[PausedSafetyNet] Could not offer the safety net', { code, error: error.message });
117
- return { sent: false, reason: 'error' };
118
- }
119
- }
120
-
121
- async function offerIsLive(code) {
122
- try {
123
- const since = new Date(Date.now() - getOfferWindowMs());
124
- const [sent] = await getMessages(
125
- { numero: code, from_me: true, content_sid: getSafetyNetContentSid(), createdAt: { $gt: since } },
126
- { sort: { createdAt: -1 }, limit: 1 }
127
- );
128
- return Boolean(sent);
129
- } catch (error) {
130
- logger.error('[PausedSafetyNet] Could not read the offer history; honouring the tap', { code, error: error.message });
131
- return true;
132
- }
133
- }
134
-
135
- async function fileUrgentRequest(code, choice) {
136
- const copy = REQUEST_COPY[choice];
137
- return recordUnresolvedRequest({
138
- code,
139
- trace: null,
140
- question: copy.question,
141
- details: copy.details(code),
142
- category: REQUEST_CATEGORY,
143
- urgency: 'urgent'
144
- });
145
- }
146
-
147
- async function markCanWait(code) {
148
- const { requests = [] } = await getPatientTasks(code);
149
- const target = requests.find((request) => request.status === ATTENDED_STATUS
150
- && request.category === REQUEST_CATEGORY
151
- && String(request.details || '').startsWith(PAUSED_THREAD_DETAILS_PREFIX));
152
- if (!target) return false;
153
-
154
- await updatePatientTask({
155
- code,
156
- kind: 'requests',
157
- recordId: target.recordId,
158
- changes: {
159
- urgency: 'routine',
160
- note: [target.note, CAN_WAIT_NOTE].filter(Boolean).join('\n')
161
- },
162
- updatedBy: SOURCE,
163
- source: SOURCE
164
- });
165
- return true;
166
- }
167
-
168
- async function applyChoice(code, choice) {
169
- if (choice === 'later') return { queued: true, downgraded: await markCanWait(code), pledge: null };
170
-
171
- const queued = await fileUrgentRequest(code, choice);
172
- if (choice !== 'callback') return { queued, pledge: null };
173
- if (!queued) return { queued, pledge: null };
174
-
175
- try {
176
- return { queued, pledge: await openPledge({ code }) };
177
- } catch (error) {
178
- logger.error('[PausedSafetyNet] The request was filed but no pledge was opened', { code, error: error.message });
179
- return { queued, pledge: null };
180
- }
181
- }
182
-
183
- const withPhone = (text, closing) => {
184
- const phone = getSafetyNetPhone();
185
- return phone ? `${text} ${closing.replace('{phone}', phone)}` : text;
186
- };
187
-
188
- function ackFor(choice, outcome) {
189
- if (outcome.stale) {
190
- return withPhone('Recibimos tu respuesta y el equipo va a revisar tu conversación.', 'Si necesitas ayuda ahora, llámanos al {phone}.');
191
- }
192
-
193
- if (!outcome.queued) {
194
- return withPhone('No pudimos registrar tu solicitud.', 'Por favor llámanos al {phone} para que te atendamos.');
195
- }
196
-
197
- if (choice === 'urgent') {
198
- return withPhone('Entendido, ya avisamos al equipo.', 'Si es una urgencia médica, llámanos ahora al {phone}.');
199
- }
200
-
201
- if (choice === 'later') {
202
- return outcome.downgraded
203
- ? withPhone('Gracias, lo anotamos. El equipo revisará tu mensaje.', 'Si necesitas ayuda antes, llámanos al {phone}.')
204
- : withPhone('Gracias. El equipo revisará tu mensaje.', 'Si necesitas ayuda antes, llámanos al {phone}.');
205
- }
206
-
207
- if (!outcome.pledge) {
208
- return withPhone('Listo, ya avisamos al equipo y te van a contactar.', 'Si te sientes peor antes, llámanos al {phone}.');
209
- }
210
-
211
- if (outcome.pledge.deferredToWindow) {
212
- return withPhone(
213
- `Listo, ya avisamos al equipo. Te van a contactar en cuanto abran, a partir de las ${CONTACT_WINDOW.startHour}:00.`,
214
- 'Si es una urgencia médica, llámanos ahora al {phone}.'
215
- );
216
- }
217
-
218
- const minutes = Math.round(getPledgeMs() / 60000);
219
- return withPhone(
220
- `Listo. Un miembro del equipo te va a contactar en los próximos ${minutes} minutos.`,
221
- 'Si te sientes peor antes, llámanos al {phone}.'
222
- );
223
- }
224
-
225
- async function sendAck(code, choice, outcome) {
226
- try {
227
- await getMessaging().sendMessage({ code, body: ackFor(choice, outcome), triggeredBy: SOURCE });
228
- return true;
229
- } catch (error) {
230
- logger.error('[PausedSafetyNet] Could not acknowledge the tap', { code, choice, error: error.message });
231
- return false;
232
- }
233
- }
234
-
235
- async function handleSafetyNetTap({ code, payload, title }) {
236
- const choice = matchSafetyNetChoice(payload, title);
237
- if (!choice || !code) return { handled: false };
238
-
239
- const claim = await acquireSendClaim({ idempotencyKey: `safetynet:${code}:${choice}` });
240
- if (!claim.acquired) return { handled: true, choice, reason: 'concurrent_tap' };
241
-
242
- let acknowledged = false;
243
- try {
244
- if (!await offerIsLive(code)) {
245
- acknowledged = await sendAck(code, choice, { queued: true, pledge: null, repeated: false, stale: true });
246
- return { handled: true, choice, queued: false, stale: true };
247
- }
248
- await offerClaims().set(code, true);
249
-
250
- const chosen = await tapClaims().get(code);
251
- const repeated = Boolean(chosen);
252
- const effective = repeated ? chosen : choice;
253
-
254
- let outcome = { queued: true, pledge: null, repeated };
255
- if (!repeated) {
256
- try {
257
- outcome = { ...await applyChoice(code, choice), repeated: false };
258
- await tapClaims().set(code, choice);
259
- } catch (error) {
260
- logger.error('[PausedSafetyNet] Could not record the tap', { code, choice, error: error.message });
261
- outcome = { queued: false, pledge: null, repeated: false };
262
- }
263
- }
264
-
265
- acknowledged = await sendAck(code, effective, outcome);
266
- return { handled: true, choice: effective, ...outcome };
267
- } finally {
268
- if (acknowledged) await completeSendClaim(claim.claimId);
269
- else await releaseSendClaim(claim.claimId);
270
- }
271
- }
272
-
273
- function registerSafetyNetRoutes() {
274
- const armed = Boolean(getSafetyNetContentSid()) && Boolean(getSafetyNetPhone());
275
- if (!armed) {
276
- if (getSafetyNetContentSid()) logger.error('[PausedSafetyNet] A template is configured without a phone number; the safety net stays disarmed');
277
- disarmSafetyNet();
278
- return false;
279
- }
280
-
281
- registerInteractiveRoute(PAYLOAD_PREFIX, handleSafetyNetTap);
282
- for (const choice of CHOICES) {
283
- const label = getSafetyNetLabel(choice);
284
- if (label) registerInteractiveRoute(label, handleSafetyNetTap);
285
- }
286
- return true;
287
- }
288
-
289
- module.exports = {
290
- disarmSafetyNet,
291
- offerSafetyNet,
292
- handleSafetyNetTap,
293
- matchSafetyNetChoice,
294
- registerSafetyNetRoutes,
295
- _resetSafetyNetState,
296
- PAYLOAD_PREFIX,
297
- CHOICES
298
- };
@@ -1,120 +0,0 @@
1
- const { CONTACT_WINDOW, getPledgeMs, getSweepIntervalMs, humanReplyFilter } = require('../config/safetyNetConfig');
2
- const { logger } = require('../../utils/logger');
3
- const { clampToHourWindow } = require('../../utils/scheduleUtils');
4
-
5
- const { SafetyNetPledge } = require('../../models/safetyNetPledgeModel');
6
-
7
- const { getMessages } = require('../../services/messageService');
8
-
9
- const { recordUnresolvedRequest } = require('./clinicalAirtableService');
10
-
11
- const SWEEP_LIMIT = 200;
12
- const BREACH_CATEGORY = 'contact_team_member';
13
- const BREACH_QUESTION = 'El paciente sigue esperando el contacto que se le prometió';
14
-
15
- async function humanRepliedSince(code, since) {
16
- const [reply] = await getMessages(humanReplyFilter(code, since), { sort: { createdAt: -1 }, limit: 1 });
17
- return Boolean(reply);
18
- }
19
-
20
- function pledgeDueAt(pledgedAt) {
21
- const target = new Date(pledgedAt.getTime() + getPledgeMs());
22
- const opened = clampToHourWindow(target, CONTACT_WINDOW);
23
- if (!opened) return { dueAt: target, deferredToWindow: false };
24
- return { dueAt: opened, deferredToWindow: opened.getTime() > target.getTime() };
25
- }
26
-
27
- async function openPledge({ code }) {
28
- const pledgedAt = new Date();
29
- const { dueAt, deferredToWindow } = pledgeDueAt(pledgedAt);
30
- const pledge = await SafetyNetPledge.create({ code, pledgedAt, dueAt, deferredToWindow });
31
- logger.info('[SafetyNetPledge] Contact pledged', { code, dueAt, deferredToWindow });
32
- return { pledgeId: pledge._id, dueAt, deferredToWindow };
33
- }
34
-
35
- async function reportBreach(pledge) {
36
- const waitedMinutes = Math.round((Date.now() - new Date(pledge.pledgedAt).getTime()) / 60000);
37
- return recordUnresolvedRequest({
38
- code: pledge.code,
39
- trace: null,
40
- question: BREACH_QUESTION,
41
- details: `El paciente ${pledge.code} pidió que lo contactaran y lleva ${waitedMinutes} minutos sin respuesta. Revisar la conversación ahora.`,
42
- category: BREACH_CATEGORY,
43
- urgency: 'urgent'
44
- });
45
- }
46
-
47
- const REPORT_LEASE_MS = 5 * 60 * 1000;
48
-
49
- const settle = async (id, from, state) => Boolean(
50
- await SafetyNetPledge.findOneAndUpdate({ _id: id, state: from }, { $set: { state, resolvedAt: new Date() } }).lean()
51
- );
52
-
53
- const takeReportingLease = async (id) => Boolean(
54
- await SafetyNetPledge.findOneAndUpdate(
55
- { _id: id, $or: [{ state: 'pending' }, { state: 'reporting', reportingSince: { $lt: new Date(Date.now() - REPORT_LEASE_MS) } }] },
56
- { $set: { state: 'reporting', reportingSince: new Date() } },
57
- ).lean()
58
- );
59
-
60
- async function sweepSafetyNetPledges() {
61
- const due = await SafetyNetPledge.find({
62
- state: { $in: ['pending', 'reporting'] },
63
- dueAt: { $lte: new Date() },
64
- })
65
- .select({ _id: 1, code: 1, pledgedAt: 1 })
66
- .limit(SWEEP_LIMIT)
67
- .lean();
68
-
69
- let breached = 0;
70
-
71
- for (const pledge of due) {
72
- try {
73
- if (!await takeReportingLease(pledge._id)) continue;
74
-
75
- if (await humanRepliedSince(pledge.code, pledge.pledgedAt)) {
76
- await settle(pledge._id, 'reporting', 'met');
77
- continue;
78
- }
79
-
80
- if (!await reportBreach(pledge)) {
81
- await SafetyNetPledge.updateOne({ _id: pledge._id, state: 'reporting' }, { $set: { state: 'pending', reportingSince: null } });
82
- logger.error('[SafetyNetPledge] Breach was not recorded, pledge returns to pending for the next sweep', { code: pledge.code });
83
- continue;
84
- }
85
- if (await settle(pledge._id, 'reporting', 'breached')) breached += 1;
86
- } catch (error) {
87
- logger.error('[SafetyNetPledge] Could not resolve a pledge', { code: pledge.code, error: error.message });
88
- }
89
- }
90
-
91
- return breached;
92
- }
93
-
94
- let sweepTimer = null;
95
-
96
- function startSafetyNetSweep({ intervalMs = getSweepIntervalMs() } = {}) {
97
- if (sweepTimer) return sweepTimer;
98
- sweepTimer = setInterval(() => {
99
- sweepSafetyNetPledges().catch((error) =>
100
- logger.error('[SafetyNetPledge] Sweep failed', { error: error.message }));
101
- }, intervalMs);
102
- if (typeof sweepTimer.unref === 'function') sweepTimer.unref();
103
- return sweepTimer;
104
- }
105
-
106
- function stopSafetyNetSweep() {
107
- if (!sweepTimer) return;
108
- clearInterval(sweepTimer);
109
- sweepTimer = null;
110
- }
111
-
112
- module.exports = {
113
- startSafetyNetSweep,
114
- stopSafetyNetSweep,
115
- humanRepliedSince,
116
- openPledge,
117
- pledgeDueAt,
118
- sweepSafetyNetPledges,
119
- BREACH_QUESTION
120
- };
@@ -1,59 +0,0 @@
1
- const { logger } = require('../utils/logger');
2
-
3
- const routes = new Map();
4
-
5
- const normalizePayload = (value) => String(value ?? '').trim().toLowerCase();
6
-
7
- function registerInteractiveRoute(prefix, handler) {
8
- const key = normalizePayload(prefix);
9
- if (!key) throw new Error('registerInteractiveRoute requires a payload prefix');
10
- if (typeof handler !== 'function') throw new Error('registerInteractiveRoute requires a handler function');
11
- routes.set(key, handler);
12
- }
13
-
14
- function clearInteractiveRoutes() {
15
- routes.clear();
16
- }
17
-
18
- function hasInteractiveRoutes() {
19
- return routes.size > 0;
20
- }
21
-
22
- function resolveInteractiveRoute(payload) {
23
- const candidate = normalizePayload(payload);
24
- if (!candidate) return null;
25
- for (const [prefix, handler] of routes) {
26
- if (candidate.startsWith(prefix)) return handler;
27
- }
28
- return null;
29
- }
30
-
31
- async function invokeInteractiveRoute(messageData) {
32
- if (!routes.size) return false;
33
-
34
- const interactive = messageData?.interactive || {};
35
- const handler = resolveInteractiveRoute(interactive.payload);
36
- if (!handler) return false;
37
-
38
- try {
39
- await handler({
40
- code: messageData.code,
41
- payload: interactive.payload ?? null,
42
- title: interactive.title ?? null,
43
- messageData
44
- });
45
- return true;
46
- } catch (error) {
47
- logger.error('[InteractiveRoutes] Route handler failed', { error: error?.message || error });
48
- return false;
49
- }
50
- }
51
-
52
- module.exports = {
53
- normalizePayload,
54
- registerInteractiveRoute,
55
- clearInteractiveRoutes,
56
- hasInteractiveRoutes,
57
- resolveInteractiveRoute,
58
- invokeInteractiveRoute
59
- };
@@ -1,20 +0,0 @@
1
- const mongoose = require('mongoose');
2
-
3
- const PLEDGE_STATES = ['pending', 'reporting', 'met', 'breached'];
4
-
5
- const safetyNetPledgeSchema = new mongoose.Schema({
6
- code: { type: String, required: true },
7
- pledgedAt: { type: Date, required: true },
8
- dueAt: { type: Date, required: true },
9
- deferredToWindow: { type: Boolean, default: false },
10
- state: { type: String, enum: PLEDGE_STATES, default: 'pending' },
11
- reportingSince: { type: Date, default: null },
12
- resolvedAt: { type: Date, default: null },
13
- createdAt: { type: Date, default: Date.now }
14
- });
15
-
16
- safetyNetPledgeSchema.index({ state: 1, dueAt: 1 }, { name: 'safety_net_pledge_due_idx' });
17
-
18
- const SafetyNetPledge = mongoose.model('SafetyNetPledge', safetyNetPledgeSchema);
19
-
20
- module.exports = { SafetyNetPledge, PLEDGE_STATES };