@peopl-health/nexus 5.46.0-dev.7281 → 5.46.0-dev.7284

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/README.md CHANGED
@@ -116,38 +116,6 @@ const bus = nexus.getMessaging().getEventBus();
116
116
  bus.on('message:received', (m) => console.log('rx', m.id));
117
117
  ```
118
118
 
119
- ## Workflows (Optional)
120
-
121
- Register a named unit of work, deduplicated by a key you derive from the trigger.
122
-
123
- ```js
124
- const runner = nexus.getMessaging().getWorkflowRunner();
125
-
126
- await runner.register({
127
- kind: 'triage-projection',
128
- dedupeKey: (trigger) => String(trigger.submissionId),
129
- prepare: async (trigger, checkpoints, save) => { /* ... */ },
130
- retrySchedule: [5, 10, 20, 40], // minutes; omit for fire-and-forget
131
- });
132
-
133
- await runner.enqueue('triage-projection', { submissionId });
134
- ```
135
-
136
- With `retrySchedule` the trigger and a checkpoint journal are stored in Mongo and the schedule runs
137
- on an in-process timer — deferred workflows never touch the queue adapter, so they add no Redis load.
138
- `prepare` resumes from `checkpoints`; call `save(patch)` before each external call so a retry does
139
- not repeat completed work. Throw an error carrying `permanent: true` to give up immediately instead
140
- of walking the schedule; the Airtable helpers tag their own permanent 4xx errors that way, in
141
- `withAirtableRetry`, which all five of them route through. They rethrow on failure too, so an
142
- Airtable outage reaches `prepare` as an exception and walks the retry schedule on its own rather
143
- than reading as success.
144
-
145
- Recovery is automatic: registering sweeps for work left behind by a previous process, and the runner
146
- keeps sweeping so work whose worker died mid-`prepare` is reclaimed once its claim goes stale.
147
- `enqueue` on an abandoned key revives it, keeping its checkpoints. Work is retained for 24 hours
148
- after its last update and then expires — the dedupe key expires with it, so idempotency has the
149
- same horizon as retention.
150
-
151
119
  ## Assistants (Optional)
152
120
 
153
121
  Register assistant classes and (optionally) a custom resolver. OpenAI is supported via `llm: 'openai'`.
@@ -0,0 +1,142 @@
1
+ const { logger } = require('../utils/logger');
2
+ const { redactDirectIdentifiers } = require('../utils/sanitizerUtils');
3
+
4
+ const {
5
+ addCallLog,
6
+ addDraft,
7
+ closeEscalationReview,
8
+ handOffToDoctor,
9
+ listEscalationReviews,
10
+ openEscalationReview,
11
+ recordDoctorDecision,
12
+ sendApprovedIndications,
13
+ syncEscalationReviewCase,
14
+ } = require('../services/escalationReviewService');
15
+
16
+ const respondWithError = (res, error, action, context) => {
17
+ logger.error(`Error ${action}:`, {
18
+ error: redactDirectIdentifiers(String(error.message || '')),
19
+ stack: redactDirectIdentifiers(String(error.stack || '')),
20
+ ...context,
21
+ });
22
+ res.status(error.statusCode || 500).json({ success: false, error: error.message });
23
+ };
24
+
25
+ const openEscalationReviewController = async (req, res) => {
26
+ try {
27
+ const { code, patientCaseRecordId = null, triggeredBy } = req.body || {};
28
+ const { review, created } = await openEscalationReview({ code, patientCaseRecordId, openedBy: triggeredBy, requestId: req.requestId });
29
+ res.status(created ? 201 : 200).json({ success: true, review });
30
+ } catch (error) {
31
+ respondWithError(res, error, 'opening escalation review', { code: redactDirectIdentifiers(String(req.body?.code || '')) });
32
+ }
33
+ };
34
+
35
+ const listEscalationReviewsController = async (req, res) => {
36
+ try {
37
+ const reviews = await listEscalationReviews({ code: req.params.code });
38
+ res.status(200).json({ success: true, reviews });
39
+ } catch (error) {
40
+ respondWithError(res, error, 'listing escalation reviews', { code: redactDirectIdentifiers(String(req.params?.code || '')) });
41
+ }
42
+ };
43
+
44
+ const addEscalationReviewCallLogController = async (req, res) => {
45
+ try {
46
+ const { outcome, notes, calledAt, triggeredBy } = req.body || {};
47
+ const review = await addCallLog({ id: req.params.id, outcome, notes, calledAt, loggedBy: triggeredBy, requestId: req.requestId });
48
+ res.status(201).json({ success: true, review });
49
+ } catch (error) {
50
+ respondWithError(res, error, 'logging escalation review call', { reviewId: req.params?.id });
51
+ }
52
+ };
53
+
54
+ const addEscalationReviewDraftController = async (req, res) => {
55
+ try {
56
+ const { doctorText, patientMessage, triggeredBy } = req.body || {};
57
+ const review = await addDraft({ id: req.params.id, doctorText, patientMessage, writtenBy: triggeredBy, requestId: req.requestId });
58
+ res.status(201).json({ success: true, review });
59
+ } catch (error) {
60
+ respondWithError(res, error, 'saving escalation review draft', { reviewId: req.params?.id });
61
+ }
62
+ };
63
+
64
+ const handOffEscalationReviewController = async (req, res) => {
65
+ try {
66
+ const { mode, physicianEmail = null, triggeredBy } = req.body || {};
67
+ const { review, caseMirror } = await handOffToDoctor({ id: req.params.id, mode, physicianEmail, sentBy: triggeredBy, requestId: req.requestId });
68
+ res.status(201).json({ success: true, review, caseMirror });
69
+ } catch (error) {
70
+ respondWithError(res, error, 'handing escalation review to doctor', { reviewId: req.params?.id });
71
+ }
72
+ };
73
+
74
+ const recordEscalationReviewDecisionController = async (req, res) => {
75
+ try {
76
+ const {
77
+ source,
78
+ decision,
79
+ finalText = null,
80
+ comment = null,
81
+ doctorName = null,
82
+ doctorReply = null,
83
+ triggeredBy,
84
+ } = req.body || {};
85
+ const review = await recordDoctorDecision({
86
+ id: req.params.id,
87
+ source,
88
+ decision,
89
+ finalText,
90
+ comment,
91
+ doctorName,
92
+ doctorReply,
93
+ recordedBy: triggeredBy,
94
+ requestId: req.requestId,
95
+ });
96
+ res.status(201).json({ success: true, review });
97
+ } catch (error) {
98
+ respondWithError(res, error, 'recording escalation review decision', { reviewId: req.params?.id });
99
+ }
100
+ };
101
+
102
+ const sendEscalationReviewIndicationsController = async (req, res) => {
103
+ try {
104
+ const { outsideWindowRoute = null, triggeredBy } = req.body || {};
105
+ const { review, caseMirror } = await sendApprovedIndications({ id: req.params.id, outsideWindowRoute, sentBy: triggeredBy, requestId: req.requestId });
106
+ res.status(201).json({ success: true, review, caseMirror });
107
+ } catch (error) {
108
+ respondWithError(res, error, 'sending escalation review indications', { reviewId: req.params?.id });
109
+ }
110
+ };
111
+
112
+ const closeEscalationReviewController = async (req, res) => {
113
+ try {
114
+ const { triggeredBy } = req.body || {};
115
+ const { review, caseMirror } = await closeEscalationReview({ id: req.params.id, closedBy: triggeredBy, requestId: req.requestId });
116
+ res.status(200).json({ success: true, review, caseMirror });
117
+ } catch (error) {
118
+ respondWithError(res, error, 'closing escalation review', { reviewId: req.params?.id });
119
+ }
120
+ };
121
+
122
+ const syncEscalationReviewCaseController = async (req, res) => {
123
+ try {
124
+ const { triggeredBy } = req.body || {};
125
+ const { review, caseMirror } = await syncEscalationReviewCase({ id: req.params.id, syncedBy: triggeredBy, requestId: req.requestId });
126
+ res.status(200).json({ success: true, review, caseMirror });
127
+ } catch (error) {
128
+ respondWithError(res, error, 'syncing escalation review case', { reviewId: req.params?.id });
129
+ }
130
+ };
131
+
132
+ module.exports = {
133
+ addEscalationReviewCallLogController,
134
+ addEscalationReviewDraftController,
135
+ closeEscalationReviewController,
136
+ handOffEscalationReviewController,
137
+ listEscalationReviewsController,
138
+ openEscalationReviewController,
139
+ recordEscalationReviewDecisionController,
140
+ sendEscalationReviewIndicationsController,
141
+ syncEscalationReviewCaseController,
142
+ };
@@ -43,7 +43,6 @@ const { isLlmMonitorEnabled } = require('../clinical/flags/llmMonitorConfig');
43
43
  const { createQueueAdapter } = require('../queue');
44
44
  const { ScheduledMessageJob } = require('../jobs/ScheduledMessageJob');
45
45
  const { TemplateApprovalJob } = require('../jobs/TemplateApprovalJob');
46
- const { WorkflowRunner } = require('./WorkflowRunner');
47
46
 
48
47
  const { PhiProcessor } = require('./PhiProcessor');
49
48
 
@@ -128,8 +127,6 @@ class NexusMessaging {
128
127
  queueAdapter: this.queueAdapter,
129
128
  });
130
129
 
131
- this.workflowRunner = new WorkflowRunner({ queueAdapter: this.queueAdapter });
132
-
133
130
  this.phiProcessor = new PhiProcessor({
134
131
  encode: config.phi?.encode || false,
135
132
  ner: config.phi?.ner || null,
@@ -313,7 +310,6 @@ class NexusMessaging {
313
310
  getAssistantProcessor() { return this.assistantProcessor; }
314
311
  getLlmMonitor() { return this.llmMonitor; }
315
312
  getQueueAdapter() { return this.queueAdapter; }
316
- getWorkflowRunner() { return this.workflowRunner; }
317
313
  getPhiProcessor() { return this.phiProcessor; }
318
314
  isConnected() { return this.provider?.getConnectionStatus() ?? false; }
319
315
  isProcessing(chatId) { return this.batchingManager.isProcessing(chatId); }
@@ -1016,7 +1012,6 @@ class NexusMessaging {
1016
1012
  async disconnect() {
1017
1013
  this.queueReconciliation?.stop();
1018
1014
  if (this.provider) await this.provider.disconnect();
1019
- if (this.workflowRunner) this.workflowRunner.stop();
1020
1015
  if (this.queueAdapter) await this.queueAdapter.shutdown();
1021
1016
  this.events.removeAllListeners();
1022
1017
  }
@@ -0,0 +1,35 @@
1
+ function createWorkflowRunner({ queueAdapter } = {}) {
2
+ if (!queueAdapter) throw new Error('createWorkflowRunner requires a queueAdapter');
3
+ const workflows = new Map();
4
+
5
+ async function register(workflow = {}) {
6
+ if (!workflow.kind || typeof workflow.kind !== 'string') throw new Error('workflow requires a kind');
7
+ if (workflow.kind.includes('__')) throw new Error(`workflow '${workflow.kind}' must not contain '__' (reserved as the jobId delimiter)`);
8
+ if (typeof workflow.dedupeKey !== 'function') throw new Error(`workflow '${workflow.kind}' requires a dedupeKey function`);
9
+ if (typeof workflow.prepare !== 'function') throw new Error(`workflow '${workflow.kind}' requires a prepare function`);
10
+ if (workflows.has(workflow.kind)) throw new Error(`workflow '${workflow.kind}' is already registered`);
11
+ workflows.set(workflow.kind, workflow);
12
+ try {
13
+ await queueAdapter.process(workflow.kind, (trigger) => workflow.prepare(trigger));
14
+ } catch (error) {
15
+ workflows.delete(workflow.kind);
16
+ throw error;
17
+ }
18
+ return workflow;
19
+ }
20
+
21
+ function enqueue(kind, trigger, options = {}) {
22
+ const workflow = workflows.get(kind);
23
+ if (!workflow) throw new Error(`no workflow registered for '${kind}'`);
24
+ const dedupeKey = workflow.dedupeKey(trigger);
25
+ if (dedupeKey == null || (typeof dedupeKey === 'string' && !dedupeKey.trim())) {
26
+ throw new Error(`workflow '${kind}' produced an empty dedupe key`);
27
+ }
28
+ if (typeof dedupeKey !== 'string') throw new Error(`workflow '${kind}' produced a non-string dedupe key`);
29
+ return queueAdapter.enqueue(kind, trigger, { ...options, jobId: `${kind}__${dedupeKey}` });
30
+ }
31
+
32
+ return { register, enqueue };
33
+ }
34
+
35
+ module.exports = { createWorkflowRunner };
package/lib/index.d.ts CHANGED
@@ -243,7 +243,6 @@ declare module '@peopl-health/nexus' {
243
243
  getAssistantProcessor(): AssistantProcessor;
244
244
  getLlmMonitor(): { start(options?: { scheduleDaily?: boolean }): Promise<{ enabled: boolean }> } | null;
245
245
  initializeLlmMonitor(): Promise<{ enabled: boolean; error?: string } | undefined>;
246
- getWorkflowRunner(): WorkflowRunner;
247
246
  processInstruction(code: string, instruction: string, role?: string, options?: { triggeredBy?: string }): Promise<void>;
248
247
  processSystemMessage(code: string, messages: string | string[], role?: string, options?: { triggeredBy?: string; reply?: boolean }): Promise<void>;
249
248
  processOutreach(code: string, options?: { brief?: OutreachBrief | null; triggeredBy?: string | null; reason?: string | null; firstName?: string | null; dryRun?: boolean }): Promise<OutreachDecision>;
@@ -521,17 +520,16 @@ declare module '@peopl-health/nexus' {
521
520
  export interface Workflow {
522
521
  kind: string;
523
522
  dedupeKey: (trigger: any) => string;
524
- prepare: (trigger: any, checkpoints?: any, save?: (patch: any) => Promise<void>) => Promise<any>;
525
- retrySchedule?: number[];
523
+ prepare: (trigger: any) => Promise<any>;
526
524
  }
527
525
 
528
526
  export interface WorkflowRunner {
529
527
  register(workflow: Workflow): Promise<Workflow>;
530
- enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string | null>;
531
- sweep(only?: string[]): Promise<string[]>;
532
- stop(): void;
528
+ enqueue(kind: string, trigger: any, options?: QueueJobOptions): Promise<string>;
533
529
  }
534
530
 
531
+ export function createWorkflowRunner(options: { queueAdapter: QueueAdapter }): WorkflowRunner;
532
+
535
533
  // Memory System
536
534
  export interface PatientMemoryDocument {
537
535
  _id: any;
package/lib/index.js CHANGED
@@ -27,6 +27,7 @@ const { BaileysProvider } = require('./adapters/BaileysProvider');
27
27
  const { setPreprocessingHandler, hasPreprocessingHandler, invokePreprocessingHandler } = require('./services/preprocessingService');
28
28
  const { requestIdMiddleware, getRequestId } = require('./middleware/requestId');
29
29
  const { QueueAdapter, LocalQueueAdapter, RedisQueueAdapter, createQueueAdapter, registerQueueAdapter } = require('./queue');
30
+ const { createWorkflowRunner } = require('./core/workflowRunner');
30
31
  const routes = require('./routes');
31
32
  const { resetAll } = require('./config/lifecycle');
32
33
  const { EvalProvider } = require('./eval/EvalProvider');
@@ -228,6 +229,7 @@ class Nexus {
228
229
  }
229
230
 
230
231
  module.exports = {
232
+ createWorkflowRunner,
231
233
  Nexus,
232
234
  TwilioProvider,
233
235
  BaileysProvider,
@@ -0,0 +1,106 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const { getDb, getModelDatabase } = require('../config/mongoConfig');
4
+
5
+ const { logger } = require('../utils/logger');
6
+
7
+ const CALL_OUTCOMES = ['contacted', 'no_answer', 'voicemail'];
8
+ const HANDOFF_MODES = ['sent_whatsapp', 'copied'];
9
+ const DOCTOR_DECISIONS = ['approved', 'edited_approved', 'needs_intervention', 'returned'];
10
+ const DECISION_SOURCES = ['platform', 'registered_by_navigator'];
11
+
12
+ const callLogSchema = new mongoose.Schema({
13
+ outcome: { type: String, enum: CALL_OUTCOMES, required: true },
14
+ notes: { type: String, default: null },
15
+ calledAt: { type: Date, required: true },
16
+ loggedBy: { type: String, required: true },
17
+ }, { timestamps: { createdAt: true, updatedAt: false } });
18
+
19
+ const draftSchema = new mongoose.Schema({
20
+ doctorText: { type: String, required: true },
21
+ patientMessage: { type: String, required: true },
22
+ writtenBy: { type: String, required: true },
23
+ }, { timestamps: { createdAt: true, updatedAt: false } });
24
+
25
+ const doctorHandoffSchema = new mongoose.Schema({
26
+ mode: { type: String, enum: HANDOFF_MODES, required: true },
27
+ draftNumber: { type: Number, required: true },
28
+ physicianEmail: { type: String, default: null },
29
+ transport: { type: String, enum: [null, 'text', 'template'], default: null },
30
+ messageId: { type: String, default: null },
31
+ sentBy: { type: String, required: true },
32
+ }, { timestamps: { createdAt: true, updatedAt: false } });
33
+
34
+ const decisionSchema = new mongoose.Schema({
35
+ decision: { type: String, enum: DOCTOR_DECISIONS, required: true },
36
+ source: { type: String, enum: DECISION_SOURCES, required: true },
37
+ draftNumber: { type: Number, required: true },
38
+ finalText: { type: String, default: null },
39
+ comment: { type: String, default: null },
40
+ doctorReply: { type: String, default: null },
41
+ decidedBy: { type: String, required: true },
42
+ recordedBy: { type: String, required: true },
43
+ }, { timestamps: { createdAt: true, updatedAt: false } });
44
+
45
+ const patientDeliverySchema = new mongoose.Schema({
46
+ decisionNumber: { type: Number, required: true },
47
+ messageId: { type: String, default: null },
48
+ status: { type: String, default: null },
49
+ transport: { type: String, enum: ['text', 'template_recovery', 'predefined_template'], required: true },
50
+ sentBy: { type: String, required: true },
51
+ }, { timestamps: { createdAt: true, updatedAt: false } });
52
+
53
+ const pendingCaseMirrorSchema = new mongoose.Schema({
54
+ changes: { type: mongoose.Schema.Types.Mixed, required: true },
55
+ }, { timestamps: { createdAt: true, updatedAt: false } });
56
+
57
+ const escalationReviewSchema = new mongoose.Schema({
58
+ patientCode: { type: String, required: true },
59
+ patientCaseRecordId: { type: String, default: null },
60
+ activeCaseKey: { type: String },
61
+ status: {
62
+ type: String,
63
+ enum: [
64
+ 'open',
65
+ 'documenting',
66
+ 'draft_ready',
67
+ 'handing_off',
68
+ 'awaiting_doctor',
69
+ 'approved',
70
+ 'needs_intervention',
71
+ 'returned',
72
+ 'sending',
73
+ 'indications_sent',
74
+ 'closed',
75
+ ],
76
+ default: 'open',
77
+ },
78
+ openedBy: { type: String, required: true },
79
+ callLogs: { type: [callLogSchema], default: [] },
80
+ drafts: { type: [draftSchema], default: [] },
81
+ doctorHandoffs: { type: [doctorHandoffSchema], default: [] },
82
+ decisions: { type: [decisionSchema], default: [] },
83
+ patientDelivery: { type: patientDeliverySchema, default: null },
84
+ pendingCaseMirrors: { type: [pendingCaseMirrorSchema], default: [] },
85
+ closedBy: { type: String, default: null },
86
+ closedAt: { type: Date, default: null },
87
+ }, { timestamps: true });
88
+
89
+ escalationReviewSchema.index({ patientCode: 1, createdAt: -1 });
90
+ escalationReviewSchema.index({ activeCaseKey: 1 }, { unique: true, sparse: true });
91
+
92
+ const getEscalationReview = () => {
93
+ const dbName = getModelDatabase('EscalationReview');
94
+ const db = dbName ? getDb(dbName) : mongoose;
95
+ logger.debug('[EscalationReview] Using database', { dbName: dbName || 'default' });
96
+ return db.models.EscalationReview || db.model('EscalationReview', escalationReviewSchema);
97
+ };
98
+
99
+ module.exports = {
100
+ CALL_OUTCOMES,
101
+ DECISION_SOURCES,
102
+ DOCTOR_DECISIONS,
103
+ HANDOFF_MODES,
104
+ getEscalationReview,
105
+ escalationReviewSchema,
106
+ };
@@ -116,6 +116,18 @@ const traceRouteDefinitions = {
116
116
  'GET /:traceId': 'getTraceController'
117
117
  };
118
118
 
119
+ const escalationReviewRouteDefinitions = {
120
+ 'POST /': 'openEscalationReviewController',
121
+ 'GET /by-patient/:code': 'listEscalationReviewsController',
122
+ 'POST /:id/call-logs': 'addEscalationReviewCallLogController',
123
+ 'POST /:id/drafts': 'addEscalationReviewDraftController',
124
+ 'POST /:id/doctor-handoffs': 'handOffEscalationReviewController',
125
+ 'POST /:id/decisions': 'recordEscalationReviewDecisionController',
126
+ 'POST /:id/patient-deliveries': 'sendEscalationReviewIndicationsController',
127
+ 'POST /:id/close': 'closeEscalationReviewController',
128
+ 'POST /:id/case-sync': 'syncEscalationReviewCaseController'
129
+ };
130
+
119
131
  const createRouter = (routeDefinitions, controllers) => {
120
132
  const router = express.Router();
121
133
 
@@ -153,6 +165,7 @@ const uploadController = require('../controllers/uploadController');
153
165
  const dashboardController = require('../controllers/dashboardController');
154
166
  const prescriptionController = require('../controllers/prescriptionController');
155
167
  const traceController = require('../controllers/traceController');
168
+ const escalationReviewController = require('../controllers/escalationReviewController');
156
169
 
157
170
  const builtInControllers = {
158
171
  // Assistant controllers
@@ -259,7 +272,18 @@ const builtInControllers = {
259
272
  updateDashboardControllerById: dashboardController.updateDashboardControllerById,
260
273
 
261
274
  // Trace controllers
262
- getTraceController: traceController.getTraceController
275
+ getTraceController: traceController.getTraceController,
276
+
277
+ // Escalation review controllers
278
+ openEscalationReviewController: escalationReviewController.openEscalationReviewController,
279
+ listEscalationReviewsController: escalationReviewController.listEscalationReviewsController,
280
+ addEscalationReviewCallLogController: escalationReviewController.addEscalationReviewCallLogController,
281
+ addEscalationReviewDraftController: escalationReviewController.addEscalationReviewDraftController,
282
+ handOffEscalationReviewController: escalationReviewController.handOffEscalationReviewController,
283
+ recordEscalationReviewDecisionController: escalationReviewController.recordEscalationReviewDecisionController,
284
+ sendEscalationReviewIndicationsController: escalationReviewController.sendEscalationReviewIndicationsController,
285
+ closeEscalationReviewController: escalationReviewController.closeEscalationReviewController,
286
+ syncEscalationReviewCaseController: escalationReviewController.syncEscalationReviewCaseController
263
287
  };
264
288
 
265
289
  const setupDefaultRoutes = (app) => {
@@ -282,6 +306,7 @@ const setupDefaultRoutes = (app) => {
282
306
  app.use('/api/prescription', createRouter(prescriptionRouteDefinitions, builtInControllers));
283
307
  app.use('/api/dashboard', createRouter(dashboardRouteDefinitions, builtInControllers));
284
308
  app.use('/api/trace', createRouter(traceRouteDefinitions, builtInControllers));
309
+ app.use('/api/escalation-review', createRouter(escalationReviewRouteDefinitions, builtInControllers));
285
310
  };
286
311
 
287
312
  module.exports = {
@@ -299,6 +324,7 @@ module.exports = {
299
324
  prescriptionRoutes: prescriptionRouteDefinitions,
300
325
  dashboardRoutes: dashboardRouteDefinitions,
301
326
  traceRoutes: traceRouteDefinitions,
327
+ escalationReviewRoutes: escalationReviewRouteDefinitions,
302
328
 
303
329
  createRouter,
304
330
  setupDefaultRoutes
@@ -15,11 +15,6 @@ const AIRTABLE_API_URL = 'https://api.airtable.com/v0';
15
15
  const AXIOS_TIMEOUT_CODE = 'ECONNABORTED';
16
16
  const RETRY_BASE_DELAY_MS = 1000;
17
17
 
18
- function isPermanentAirtableError(error) {
19
- const status = error?.statusCode;
20
- return typeof status === 'number' && status >= 400 && status < 500 && status !== 429;
21
- }
22
-
23
18
  let isEvalMode = false;
24
19
 
25
20
  function setEvalMode(enabled) {
@@ -47,7 +42,6 @@ async function withAirtableRetry(operation, label, { retryNetworkErrors = true }
47
42
  const isTransient = TRANSIENT_STATUS_CODES.includes(error.statusCode)
48
43
  || (retryNetworkErrors && isTransientNetworkError(error));
49
44
  if (!isTransient || attempt === MAX_ATTEMPTS) {
50
- if (isPermanentAirtableError(error)) error.permanent = true;
51
45
  throw error;
52
46
  }
53
47
  const baseDelay = error.statusCode === RATE_LIMITED_STATUS ? RATE_LIMIT_DELAY_MS : RETRY_BASE_DELAY_MS;
@@ -235,7 +229,6 @@ async function upsertRecord(baseID, tableName, fields, { mergeOn } = {}, context
235
229
 
236
230
  module.exports = {
237
231
  setEvalMode,
238
- isPermanentAirtableError,
239
232
  addRecord,
240
233
  getRecords,
241
234
  getRecordByFilter,
@@ -1,4 +1,5 @@
1
1
  const { isoDay } = require('../utils/dateUtils');
2
+ const { httpError } = require('../utils/httpErrorUtils');
2
3
  const { logger } = require('../utils/logger');
3
4
  const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
4
5
  const { withTimeout } = require('../utils/timeoutUtils');
@@ -15,8 +16,6 @@ const TRIAGE_WINDOW_DAYS = 30;
15
16
  const CARE_PLAN_LIMIT = 5;
16
17
  const HISTORY_SCOPE = ['closed_cases_90d', 'recurrence_patterns', 'recent_medications', 'patient_reported_procedures'];
17
18
 
18
- const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
19
-
20
19
  function sectionReaders(code, now) {
21
20
  const memoryManager = new DefaultMemoryManager();
22
21
  const triageStart = isoDay(new Date(now - TRIAGE_WINDOW_DAYS * 86400000).toISOString());
@@ -0,0 +1,415 @@
1
+ const mongoose = require('mongoose');
2
+
3
+ const runtimeConfig = require('../config/runtimeConfig');
4
+ const { httpError } = require('../utils/httpErrorUtils');
5
+ const { logger } = require('../utils/logger');
6
+ const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
7
+ const {
8
+ CALL_OUTCOMES,
9
+ DECISION_SOURCES,
10
+ DOCTOR_DECISIONS,
11
+ HANDOFF_MODES,
12
+ getEscalationReview,
13
+ } = require('../models/escalationReviewModel');
14
+ const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
15
+ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
16
+ const { sendMessage } = require('../core/NexusMessaging');
17
+
18
+ const { getPatientInformation, logPatientChange } = require('./patientService');
19
+ const { getPatientTasks, updatePatientTask } = require('./patientTaskService');
20
+ const { getEscalationApprover } = require('./physicianService');
21
+
22
+ const AUDIT_SOURCE = 'escalation_review';
23
+ const RECENT_REVIEW_LIMIT = 20;
24
+ const DUPLICATE_KEY_ERROR = 11000;
25
+ const DOCUMENTING_STATUSES = ['open', 'documenting', 'draft_ready', 'returned'];
26
+ const HANDOFF_STATUSES = ['draft_ready', 'awaiting_doctor'];
27
+ const CLOSABLE_STATUSES = ['indications_sent', 'needs_intervention'];
28
+ const OUTSIDE_WINDOW_ROUTES = ['template_recovery', 'predefined_template'];
29
+ const MAX_TEMPLATE_TEXT_LENGTH = 800;
30
+ const STATUS_CONFLICT = 'The escalation review does not allow this action in its current status';
31
+
32
+ const patientCodeOf = (code) => {
33
+ const patientCode = ensureWhatsAppFormat(String(code ?? '').trim());
34
+ if (!PATIENT_CODE.test(patientCode)) throw httpError(400, 'A valid WhatsApp ID is required');
35
+ return patientCode;
36
+ };
37
+
38
+ const requiredText = (value, name) => {
39
+ const text = String(value ?? '').trim();
40
+ if (!text) throw httpError(400, `${name} is required`);
41
+ return text;
42
+ };
43
+
44
+ const optionalText = (value) => (value == null ? null : String(value));
45
+
46
+ const reviewIdOf = (id) => {
47
+ if (!mongoose.Types.ObjectId.isValid(id)) throw httpError(400, 'A valid escalation review id is required');
48
+ return id;
49
+ };
50
+
51
+ const configured = (key) => {
52
+ const value = runtimeConfig.get(key);
53
+ if (!value) throw httpError(503, `${key} is not configured`);
54
+ return value;
55
+ };
56
+
57
+ const statusAfter = (decision) => (decision === 'edited_approved' ? 'approved' : decision);
58
+
59
+ const activeCaseKeyOf = (patientCode, patientCaseRecordId) => `${patientCode}:${patientCaseRecordId}`;
60
+
61
+ const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
62
+
63
+ const redactedStack = (error) => redactDirectIdentifiers(String(error?.stack || ''));
64
+
65
+ const sendDidNotHappen = (error) => Boolean(error?.statusCode) || (Number.isInteger(error?.status) && error?.code != null);
66
+
67
+ const audit = (review, updatedBy, requestId, changes) => logPatientChange({
68
+ code: review.patientCode,
69
+ updatedBy,
70
+ source: AUDIT_SOURCE,
71
+ requestId,
72
+ changes: { escalationReviewId: String(review._id), ...changes },
73
+ });
74
+
75
+ const withCaseMirror = (review, update, changes) => (review.patientCaseRecordId
76
+ ? { ...update, $push: { ...update.$push, pendingCaseMirrors: { changes } } }
77
+ : update);
78
+
79
+ async function updateReview(id, allowedStatuses, update, extraFilter = {}) {
80
+ const EscalationReview = getEscalationReview();
81
+ const review = await EscalationReview.findOneAndUpdate({ _id: id, status: { $in: allowedStatuses }, ...extraFilter }, update, { new: true }).lean();
82
+ if (review) return review;
83
+ const exists = await EscalationReview.exists({ _id: id });
84
+ if (!exists) throw httpError(404, 'Escalation review not found');
85
+ throw httpError(409, STATUS_CONFLICT);
86
+ }
87
+
88
+ async function loadReview(id) {
89
+ const review = await getEscalationReview().findById(id).lean();
90
+ if (!review) throw httpError(404, 'Escalation review not found');
91
+ return review;
92
+ }
93
+
94
+ const releaseReview = (id, from, to) => getEscalationReview().updateOne({ _id: id, status: from }, { $set: { status: to } });
95
+
96
+ async function releaseClosedCase(EscalationReview, review) {
97
+ if (review.status !== 'closed' || review.pendingCaseMirrors.length || !review.activeCaseKey) return review;
98
+ const released = await EscalationReview.findOneAndUpdate(
99
+ { _id: review._id, status: 'closed', pendingCaseMirrors: { $size: 0 } },
100
+ { $unset: { activeCaseKey: '' } },
101
+ { new: true },
102
+ ).lean();
103
+ return released || review;
104
+ }
105
+
106
+ async function syncCase(review, operator, requestId) {
107
+ if (!review.patientCaseRecordId) return { review, caseMirror: 'skipped' };
108
+ const EscalationReview = getEscalationReview();
109
+ const pending = review.pendingCaseMirrors || [];
110
+ if (!pending.length) return { review: await releaseClosedCase(EscalationReview, review), caseMirror: 'updated' };
111
+
112
+ try {
113
+ await updatePatientTask({
114
+ code: review.patientCode,
115
+ kind: 'cases',
116
+ recordId: review.patientCaseRecordId,
117
+ changes: Object.assign({}, ...pending.map((mirror) => mirror.changes)),
118
+ updatedBy: operator,
119
+ source: AUDIT_SOURCE,
120
+ requestId,
121
+ });
122
+ } catch (error) {
123
+ logger.error('[EscalationReview] Patient case mirror failed', {
124
+ escalationReviewId: String(review._id),
125
+ error: redactedError(error),
126
+ stack: redactedStack(error),
127
+ });
128
+ return { review, caseMirror: 'failed' };
129
+ }
130
+
131
+ try {
132
+ const synced = await EscalationReview.findOneAndUpdate(
133
+ { _id: review._id },
134
+ { $pull: { pendingCaseMirrors: { _id: { $in: pending.map((mirror) => mirror._id) } } } },
135
+ { new: true },
136
+ ).lean();
137
+ return { review: await releaseClosedCase(EscalationReview, synced), caseMirror: 'updated' };
138
+ } catch (error) {
139
+ logger.error('[EscalationReview] Could not record the applied case changes', {
140
+ escalationReviewId: String(review._id),
141
+ error: redactedError(error),
142
+ stack: redactedStack(error),
143
+ });
144
+ return { review, caseMirror: 'updated' };
145
+ }
146
+ }
147
+
148
+ async function sendDoctorAlert({ review, draft, approver, operator }) {
149
+ const doctorCode = ensureWhatsAppFormat(String(approver.phone ?? '').replace(/[^\d+]/g, ''));
150
+ if (!PATIENT_CODE.test(doctorCode)) throw httpError(422, 'The physician has no usable WhatsApp number on record');
151
+ const link = `${configured('PEOPL_INTERFACE_URL').replace(/\/+$/, '')}/escalation-review/${review._id}`;
152
+ const inWindow = await isWithin24HourWindow(doctorCode);
153
+ const message = inWindow
154
+ ? { code: doctorCode, body: `${draft.doctorText}\n\n${link}`, triggeredBy: operator }
155
+ : { code: doctorCode, contentSid: configured('ESCALATION_REVIEW_DOCTOR_ALERT_CONTENT_SID'), variables: { 1: link }, triggeredBy: operator };
156
+ const result = await sendMessage(message);
157
+ if (!result?.success && result?.status !== 'duplicate_suppressed') {
158
+ throw httpError(502, 'The WhatsApp message to the physician could not be sent');
159
+ }
160
+ return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
161
+ }
162
+
163
+ async function patientIndicationsMessage({ review, finalText, outsideWindowRoute, operator }) {
164
+ const message = { code: review.patientCode, triggeredBy: operator };
165
+ if (await isWithin24HourWindow(review.patientCode)) return { ...message, body: finalText };
166
+ if (!outsideWindowRoute) {
167
+ throw httpError(422, `The patient is outside the 24-hour window; outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
168
+ }
169
+ if (outsideWindowRoute === 'template_recovery') return { ...message, body: finalText };
170
+
171
+ const text = finalText.replace(/\s+/g, ' ').trim();
172
+ if (text.length > MAX_TEMPLATE_TEXT_LENGTH) {
173
+ throw httpError(422, `The indications exceed ${MAX_TEMPLATE_TEXT_LENGTH} characters for the predefined template; use template_recovery`);
174
+ }
175
+ const patient = await getPatientInformation(review.patientCode);
176
+ const firstName = String(patient?.first_name ?? '').trim();
177
+ if (!firstName) throw httpError(422, 'The patient has no first name on record for the predefined template');
178
+ return {
179
+ ...message,
180
+ contentSid: configured('ESCALATION_REVIEW_PATIENT_INDICATIONS_CONTENT_SID'),
181
+ variables: { 1: firstName, 2: text },
182
+ };
183
+ }
184
+
185
+ const deliveryTransport = (message, result) => {
186
+ if (message.contentSid) return 'predefined_template';
187
+ return result.deferred ? 'template_recovery' : 'text';
188
+ };
189
+
190
+ async function openEscalationReview({ code, patientCaseRecordId = null, openedBy, requestId = null } = {}) {
191
+ const patientCode = patientCodeOf(code);
192
+ const operator = requiredText(openedBy, 'openedBy');
193
+ const patient = await getPatientInformation(patientCode);
194
+ if (!patient) throw httpError(404, 'Patient not found');
195
+
196
+ const fields = { patientCode, openedBy: operator };
197
+ if (patientCaseRecordId !== null) {
198
+ const { cases } = await getPatientTasks(patientCode);
199
+ if (!cases.some((patientCase) => patientCase.recordId === patientCaseRecordId)) {
200
+ throw httpError(404, 'Patient case not found for this patient');
201
+ }
202
+ Object.assign(fields, { patientCaseRecordId, activeCaseKey: activeCaseKeyOf(patientCode, patientCaseRecordId) });
203
+ }
204
+
205
+ const EscalationReview = getEscalationReview();
206
+ await EscalationReview.init();
207
+ let review;
208
+ try {
209
+ review = (await EscalationReview.create(fields)).toObject();
210
+ } catch (error) {
211
+ if (error?.code !== DUPLICATE_KEY_ERROR || !fields.activeCaseKey) throw error;
212
+ const existing = await EscalationReview.findOne({ activeCaseKey: fields.activeCaseKey }).lean();
213
+ if (!existing) throw httpError(409, 'The patient case review changed while opening; try again');
214
+ return { review: existing, created: false };
215
+ }
216
+ await audit(review, operator, requestId, { action: 'opened', patientCaseRecordId });
217
+ return { review, created: true };
218
+ }
219
+
220
+ async function listEscalationReviews({ code } = {}) {
221
+ const patientCode = patientCodeOf(code);
222
+ return getEscalationReview().find({ patientCode }).sort({ createdAt: -1 }).limit(RECENT_REVIEW_LIMIT).lean();
223
+ }
224
+
225
+ async function addCallLog({ id, outcome, notes = null, calledAt = null, loggedBy, requestId = null } = {}) {
226
+ const reviewId = reviewIdOf(id);
227
+ const operator = requiredText(loggedBy, 'loggedBy');
228
+ if (!CALL_OUTCOMES.includes(outcome)) throw httpError(400, `outcome must be one of: ${CALL_OUTCOMES.join(', ')}`);
229
+ const callTime = calledAt == null ? new Date() : new Date(calledAt);
230
+ if (Number.isNaN(callTime.getTime())) throw httpError(400, 'calledAt must be a valid date');
231
+
232
+ const review = await updateReview(reviewId, DOCUMENTING_STATUSES, {
233
+ $push: { callLogs: { outcome, notes: optionalText(notes), calledAt: callTime, loggedBy: operator } },
234
+ $set: { status: 'documenting' },
235
+ });
236
+ await audit(review, operator, requestId, { action: 'call_logged', outcome });
237
+ return review;
238
+ }
239
+
240
+ async function addDraft({ id, doctorText, patientMessage, writtenBy, requestId = null } = {}) {
241
+ const reviewId = reviewIdOf(id);
242
+ const operator = requiredText(writtenBy, 'writtenBy');
243
+ const draft = {
244
+ doctorText: requiredText(doctorText, 'doctorText'),
245
+ patientMessage: requiredText(patientMessage, 'patientMessage'),
246
+ writtenBy: operator,
247
+ };
248
+
249
+ const review = await updateReview(reviewId, DOCUMENTING_STATUSES, { $push: { drafts: draft }, $set: { status: 'draft_ready' } });
250
+ await audit(review, operator, requestId, { action: 'draft_saved', draftNumber: review.drafts.length });
251
+ return review;
252
+ }
253
+
254
+ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, requestId = null } = {}) {
255
+ const reviewId = reviewIdOf(id);
256
+ const operator = requiredText(sentBy, 'sentBy');
257
+ if (!HANDOFF_MODES.includes(mode)) throw httpError(400, `mode must be one of: ${HANDOFF_MODES.join(', ')}`);
258
+
259
+ const review = await loadReview(reviewId);
260
+ if (!HANDOFF_STATUSES.includes(review.status)) throw httpError(409, STATUS_CONFLICT);
261
+ const draftNumber = review.drafts.length;
262
+ if (!draftNumber) throw httpError(409, 'The escalation review has no draft yet');
263
+ const draft = review.drafts[draftNumber - 1];
264
+ let approver = null;
265
+ if (mode === 'sent_whatsapp') {
266
+ approver = await getEscalationApprover(physicianEmail);
267
+ if (!approver) throw httpError(403, 'The physician is not an escalation review approver');
268
+ }
269
+
270
+ await updateReview(reviewId, [review.status], { $set: { status: 'handing_off' } }, { drafts: { $size: draftNumber } });
271
+ let delivery = {};
272
+ let updated;
273
+ try {
274
+ if (approver) delivery = { physicianEmail: approver.email, ...(await sendDoctorAlert({ review, draft, approver, operator })) };
275
+ updated = await updateReview(reviewId, ['handing_off'], withCaseMirror(review, {
276
+ $push: { doctorHandoffs: { mode, draftNumber, ...delivery, sentBy: operator } },
277
+ $set: { status: 'awaiting_doctor' },
278
+ }, { status: 'en revision_medica' }));
279
+ } catch (error) {
280
+ await releaseReview(reviewId, 'handing_off', review.status);
281
+ throw error;
282
+ }
283
+ await audit(updated, operator, requestId, {
284
+ action: mode === 'copied' ? 'copied_for_doctor' : 'sent_to_doctor',
285
+ draftNumber,
286
+ transport: delivery.transport ?? null,
287
+ });
288
+ return syncCase(updated, operator, requestId);
289
+ }
290
+
291
+ async function recordDoctorDecision({
292
+ id,
293
+ source,
294
+ decision,
295
+ finalText = null,
296
+ comment = null,
297
+ doctorName = null,
298
+ doctorReply = null,
299
+ recordedBy,
300
+ requestId = null,
301
+ } = {}) {
302
+ const reviewId = reviewIdOf(id);
303
+ const operator = requiredText(recordedBy, 'recordedBy');
304
+ if (!DECISION_SOURCES.includes(source)) throw httpError(400, `source must be one of: ${DECISION_SOURCES.join(', ')}`);
305
+ if (!DOCTOR_DECISIONS.includes(decision)) throw httpError(400, `decision must be one of: ${DOCTOR_DECISIONS.join(', ')}`);
306
+
307
+ let decidedBy = operator;
308
+ let reply = null;
309
+ if (source === 'platform') {
310
+ const approver = await getEscalationApprover(operator);
311
+ if (!approver) throw httpError(403, 'Only an escalation review approver can decide in the platform');
312
+ } else {
313
+ decidedBy = requiredText(doctorName, 'doctorName');
314
+ reply = requiredText(doctorReply, 'doctorReply');
315
+ }
316
+
317
+ const review = await loadReview(reviewId);
318
+ if (review.status !== 'awaiting_doctor') throw httpError(409, STATUS_CONFLICT);
319
+ const { draftNumber } = review.doctorHandoffs[review.doctorHandoffs.length - 1];
320
+ const draft = review.drafts[draftNumber - 1];
321
+ let approvedText = null;
322
+ if (decision === 'approved') approvedText = draft.patientMessage;
323
+ if (decision === 'edited_approved') approvedText = requiredText(finalText, 'finalText');
324
+
325
+ const updated = await updateReview(reviewId, ['awaiting_doctor'], {
326
+ $push: {
327
+ decisions: {
328
+ decision,
329
+ source,
330
+ draftNumber,
331
+ finalText: approvedText,
332
+ comment: optionalText(comment),
333
+ doctorReply: reply,
334
+ decidedBy,
335
+ recordedBy: operator,
336
+ },
337
+ },
338
+ $set: { status: statusAfter(decision) },
339
+ });
340
+ await audit(updated, operator, requestId, { action: 'doctor_decision', decision, source, draftNumber });
341
+ return updated;
342
+ }
343
+
344
+ async function sendApprovedIndications({ id, outsideWindowRoute = null, sentBy, requestId = null } = {}) {
345
+ const reviewId = reviewIdOf(id);
346
+ const operator = requiredText(sentBy, 'sentBy');
347
+ if (outsideWindowRoute !== null && !OUTSIDE_WINDOW_ROUTES.includes(outsideWindowRoute)) {
348
+ throw httpError(400, `outsideWindowRoute must be one of: ${OUTSIDE_WINDOW_ROUTES.join(', ')}`);
349
+ }
350
+
351
+ const claimed = await updateReview(reviewId, ['approved'], { $set: { status: 'sending' } });
352
+ const decisionNumber = claimed.decisions.length;
353
+ const { finalText } = claimed.decisions[decisionNumber - 1];
354
+
355
+ let message;
356
+ let result;
357
+ try {
358
+ message = await patientIndicationsMessage({ review: claimed, finalText, outsideWindowRoute, operator });
359
+ result = await sendMessage(message);
360
+ if (!result?.success) throw httpError(502, 'The indications could not be sent to the patient');
361
+ } catch (error) {
362
+ if (!sendDidNotHappen(error)) {
363
+ logger.error('[EscalationReview] Patient send outcome is unknown; leaving the review in sending', {
364
+ escalationReviewId: String(claimed._id),
365
+ error: redactedError(error),
366
+ });
367
+ throw httpError(502, 'The patient send could not be confirmed; check the chat before sending again');
368
+ }
369
+ await releaseReview(reviewId, 'sending', 'approved');
370
+ throw error;
371
+ }
372
+
373
+ const delivery = {
374
+ decisionNumber,
375
+ messageId: result.messageId || null,
376
+ status: result.status || null,
377
+ transport: deliveryTransport(message, result),
378
+ sentBy: operator,
379
+ };
380
+ const review = await updateReview(reviewId, ['sending'], withCaseMirror(claimed, {
381
+ $set: { status: 'indications_sent', patientDelivery: delivery },
382
+ }, { recommendation: finalText }));
383
+ await audit(review, operator, requestId, { action: 'indications_sent', decisionNumber, transport: delivery.transport });
384
+ return syncCase(review, operator, requestId);
385
+ }
386
+
387
+ async function closeEscalationReview({ id, closedBy, requestId = null } = {}) {
388
+ const reviewId = reviewIdOf(id);
389
+ const operator = requiredText(closedBy, 'closedBy');
390
+
391
+ const current = await loadReview(reviewId);
392
+ const review = await updateReview(reviewId, CLOSABLE_STATUSES, withCaseMirror(current, {
393
+ $set: { status: 'closed', closedBy: operator, closedAt: new Date() },
394
+ }, { operationsStatus: 'cerrado' }));
395
+ await audit(review, operator, requestId, { action: 'closed' });
396
+ return syncCase(review, operator, requestId);
397
+ }
398
+
399
+ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
400
+ const reviewId = reviewIdOf(id);
401
+ const operator = requiredText(syncedBy, 'syncedBy');
402
+ return syncCase(await loadReview(reviewId), operator, requestId);
403
+ }
404
+
405
+ module.exports = {
406
+ addCallLog,
407
+ addDraft,
408
+ closeEscalationReview,
409
+ handOffToDoctor,
410
+ listEscalationReviews,
411
+ openEscalationReview,
412
+ recordDoctorDecision,
413
+ sendApprovedIndications,
414
+ syncEscalationReviewCase,
415
+ };
@@ -1,5 +1,7 @@
1
1
  const { Monitoreo_ID } = require('../config/airtableConfig');
2
2
 
3
+ const { httpError } = require('../utils/httpErrorUtils');
4
+
3
5
  const { escapeFormulaValue, fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
4
6
  const {
5
7
  isCaseOpen,
@@ -64,8 +66,6 @@ const OPERATIONS_STATUSES = [
64
66
  'sin caracterizar',
65
67
  ];
66
68
 
67
- const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
68
-
69
69
  const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
70
70
 
71
71
  const toRequest = (row) => ({
@@ -121,6 +121,7 @@ const TASK_KINDS = {
121
121
  status: { field: 'status', options: CASE_STATUSES },
122
122
  operationsStatus: { field: 'status_operaciones', options: OPERATIONS_STATUSES },
123
123
  note: { field: 'observations' },
124
+ recommendation: { field: 'recomendation_final' },
124
125
  },
125
126
  },
126
127
  };
@@ -0,0 +1,20 @@
1
+ const { Monitoreo_ID } = require('../config/airtableConfig');
2
+
3
+ const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper');
4
+
5
+ const { getRecordByFilter } = require('./airtableService');
6
+
7
+ const APPROVER_FIELDS = ['physician_name', 'email', 'phone_number'];
8
+
9
+ async function getEscalationApprover(email) {
10
+ const normalized = String(email ?? '').trim().toLowerCase();
11
+ if (!normalized) return null;
12
+
13
+ const formula = `AND(LOWER({email}) = '${escapeFormulaValue(normalized)}', {aprueba_vaiven})`;
14
+ const [physician] = await getRecordByFilter(Monitoreo_ID, 'physicians', formula, null, APPROVER_FIELDS, true) || [];
15
+ if (!physician) return null;
16
+
17
+ return { name: physician.physician_name || null, email: normalized, phone: physician.phone_number || null };
18
+ }
19
+
20
+ module.exports = { getEscalationApprover };
@@ -0,0 +1,3 @@
1
+ const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
2
+
3
+ module.exports = { httpError };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.46.0-dev.7281",
3
+ "version": "5.46.0-dev.7284",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",
@@ -1,265 +0,0 @@
1
- const { describeThrown } = require('../utils/errorUtils');
2
- const { logger } = require('../utils/logger');
3
-
4
- const { DeferredWork, RETENTION_MS } = require('../models/deferredWorkModel');
5
-
6
- const STALE_CLAIM_MS = 5 * 60 * 1000;
7
- const MINUTE_MS = 60 * 1000;
8
- const INDEX_TIMEOUT_MS = 1000;
9
- const SWEEP_INTERVAL_MS = 60 * 1000;
10
-
11
- let indexesReady = null;
12
-
13
- function ensureIndexes() {
14
- if (!indexesReady) {
15
- indexesReady = DeferredWork.init().catch((error) => {
16
- indexesReady = null;
17
- logger.error('[WorkflowRunner] Index build failed, dedupe and retention are not guaranteed', { error: error.message });
18
- });
19
- }
20
- return indexesReady;
21
- }
22
-
23
- function withIndexTimeout(promise) {
24
- let timer;
25
- const timeout = new Promise((resolve) => {
26
- timer = setTimeout(resolve, INDEX_TIMEOUT_MS);
27
- timer.unref();
28
- });
29
- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
30
- }
31
-
32
- class WorkflowRunner {
33
- constructor({ queueAdapter, sweepIntervalMs = SWEEP_INTERVAL_MS } = {}) {
34
- if (!queueAdapter) throw new Error('WorkflowRunner requires a queueAdapter');
35
- this.queueAdapter = queueAdapter;
36
- this.sweepIntervalMs = sweepIntervalMs;
37
- this.sweepTimer = null;
38
- this.timers = new Map();
39
- this.workflows = new Map();
40
- this.stopped = false;
41
- }
42
-
43
- async register(workflow = {}) {
44
- if (!workflow.kind || typeof workflow.kind !== 'string') throw new Error('workflow requires a kind');
45
- if (workflow.kind.includes('__')) throw new Error(`workflow '${workflow.kind}' must not contain '__' (reserved as the jobId delimiter)`);
46
- if (typeof workflow.dedupeKey !== 'function') throw new Error(`workflow '${workflow.kind}' requires a dedupeKey function`);
47
- if (typeof workflow.prepare !== 'function') throw new Error(`workflow '${workflow.kind}' requires a prepare function`);
48
- if (this.workflows.has(workflow.kind)) throw new Error(`workflow '${workflow.kind}' is already registered`);
49
- if (workflow.retrySchedule !== undefined) {
50
- if (!Array.isArray(workflow.retrySchedule) || !workflow.retrySchedule.length) {
51
- throw new Error(`workflow '${workflow.kind}' requires a non-empty retrySchedule array`);
52
- }
53
- if (workflow.retrySchedule.some((minutes) => !Number.isFinite(minutes) || minutes <= 0)) {
54
- throw new Error(`workflow '${workflow.kind}' requires retrySchedule entries to be positive minutes`);
55
- }
56
- if (workflow.retrySchedule.some((minutes) => minutes * MINUTE_MS >= RETENTION_MS)) {
57
- throw new Error(`workflow '${workflow.kind}' requires retrySchedule entries under the ${RETENTION_MS / MINUTE_MS}m retention, or the record expires before the attempt fires`);
58
- }
59
- }
60
-
61
- this.workflows.set(workflow.kind, workflow);
62
- if (workflow.retrySchedule) {
63
- await this.sweep([workflow.kind]).catch((error) => {
64
- logger.error('[WorkflowRunner] Sweep on register failed', { kind: workflow.kind, error: error.message });
65
- });
66
- this._startSweeping();
67
- return workflow;
68
- }
69
-
70
- try {
71
- await this.queueAdapter.process(workflow.kind, (trigger) => workflow.prepare(trigger));
72
- } catch (error) {
73
- this.workflows.delete(workflow.kind);
74
- throw error;
75
- }
76
- return workflow;
77
- }
78
-
79
- enqueue(kind, trigger, options = {}) {
80
- const workflow = this.workflows.get(kind);
81
- if (!workflow) throw new Error(`no workflow registered for '${kind}'`);
82
- const dedupeKey = workflow.dedupeKey(trigger);
83
- if (dedupeKey == null || (typeof dedupeKey === 'string' && !dedupeKey.trim())) {
84
- throw new Error(`workflow '${kind}' produced an empty dedupe key`);
85
- }
86
- if (typeof dedupeKey !== 'string') throw new Error(`workflow '${kind}' produced a non-string dedupe key`);
87
- if (!workflow.retrySchedule) {
88
- return this.queueAdapter.enqueue(kind, trigger, { ...options, jobId: `${kind}__${dedupeKey}` });
89
- }
90
- return this._armDeferred(workflow, trigger, dedupeKey);
91
- }
92
-
93
- async sweep(only = null) {
94
- const deferredKinds = [...this.workflows.values()].filter((w) => w.retrySchedule).map((w) => w.kind);
95
- const kinds = only ? deferredKinds.filter((kind) => only.includes(kind)) : deferredKinds;
96
- if (!kinds.length) return [];
97
-
98
- const orphaned = await DeferredWork.find({
99
- kind: { $in: kinds },
100
- $or: [
101
- { status: 'pending' },
102
- { status: 'processing', claimedAt: { $lt: new Date(Date.now() - STALE_CLAIM_MS) } }
103
- ]
104
- });
105
-
106
- const rearmed = orphaned.map((work) => this._arm(
107
- this.workflows.get(work.kind),
108
- work._id,
109
- this._delayUntilDue(work),
110
- ));
111
- if (rearmed.length) logger.info('[WorkflowRunner] Swept', { kinds, rearmed: rearmed.length });
112
- return rearmed;
113
- }
114
-
115
- _startSweeping() {
116
- if (this.stopped || this.sweepTimer || !this.sweepIntervalMs) return;
117
- this.sweepTimer = setInterval(() => {
118
- this.sweep().catch((error) => logger.error('[WorkflowRunner] Periodic sweep failed', { error: error.message }));
119
- }, this.sweepIntervalMs);
120
- this.sweepTimer.unref();
121
- }
122
-
123
- stop() {
124
- this.stopped = true;
125
- if (this.sweepTimer) clearInterval(this.sweepTimer);
126
- this.sweepTimer = null;
127
- for (const timer of this.timers.values()) clearTimeout(timer);
128
- this.timers.clear();
129
- }
130
-
131
- async _armDeferred(workflow, trigger, dedupeKey) {
132
- const { kind } = workflow;
133
- await withIndexTimeout(ensureIndexes());
134
- const work = await DeferredWork.findOne({ kind, dedupeKey })
135
- || await DeferredWork.create({ kind, dedupeKey, trigger }).catch(async (error) => {
136
- if (error.code !== 11000) throw error;
137
- return await DeferredWork.findOne({ kind, dedupeKey });
138
- });
139
- if (work.status === 'abandoned') {
140
- const { modifiedCount } = await DeferredWork.updateOne(
141
- { _id: work._id, status: 'abandoned' },
142
- { $set: { status: 'pending', attempt: 0, nextAttemptAt: new Date(), lastError: null, claimedAt: null } }
143
- );
144
- if (!modifiedCount) return null;
145
- logger.info('[WorkflowRunner] Re-arming abandoned work', { kind, dedupeKey });
146
- return this._arm(workflow, work._id, 0);
147
- }
148
- if (work.status !== 'pending') {
149
- logger.info('[WorkflowRunner] Skipping, work is in flight or complete', { kind, dedupeKey, status: work.status });
150
- return null;
151
- }
152
- return this._arm(workflow, work._id, this._delayUntilDue(work));
153
- }
154
-
155
- _delayUntilDue(work) {
156
- return Math.max(0, new Date(work.nextAttemptAt).getTime() - Date.now());
157
- }
158
-
159
- _arm(workflow, workId, delayMs) {
160
- const id = String(workId);
161
- // An attempt still in flight when stop() lands must not re-arm after shutdown. The
162
- // record stays pending in Mongo, so the next process recovers it on its sweep.
163
- if (this.stopped) return id;
164
- clearTimeout(this.timers.get(id));
165
- const timer = setTimeout(() => {
166
- this.timers.delete(id);
167
- this._runDeferred(workflow, id).catch((error) => {
168
- logger.error('[WorkflowRunner] Deferred run failed', { kind: workflow.kind, deferredWorkId: id, error: error.message });
169
- });
170
- }, delayMs);
171
- timer.unref();
172
- this.timers.set(id, timer);
173
- return id;
174
- }
175
-
176
- async _runDeferred(workflow, deferredWorkId) {
177
- const claimedAt = new Date();
178
- const prior = await DeferredWork.findOneAndUpdate(
179
- {
180
- _id: deferredWorkId,
181
- $or: [
182
- { status: 'pending', nextAttemptAt: { $lte: claimedAt } },
183
- { status: 'processing', claimedAt: { $lt: new Date(claimedAt.getTime() - STALE_CLAIM_MS) } }
184
- ]
185
- },
186
- { $set: { status: 'processing', claimedAt } },
187
- { new: false }
188
- );
189
- if (!prior) {
190
- logger.info('[WorkflowRunner] Claimed elsewhere or not due', { kind: workflow.kind, deferredWorkId });
191
- return { claimed: false };
192
- }
193
-
194
- const reclaimed = prior.status === 'processing';
195
- const work = { ...prior.toObject(), attempt: prior.attempt + (reclaimed ? 1 : 0) };
196
- if (reclaimed) await this._write(work, claimedAt, { attempt: work.attempt });
197
-
198
- const checkpoints = { ...(work.checkpoints || {}) };
199
- const save = async (patch) => {
200
- Object.assign(checkpoints, patch);
201
- const $set = {};
202
- for (const [key, value] of Object.entries(patch || {})) $set[`checkpoints.${key}`] = value;
203
- if (Object.keys($set).length) await this._write(work, claimedAt, $set);
204
- };
205
-
206
- try {
207
- await workflow.prepare(work.trigger, checkpoints, save);
208
- } catch (error) {
209
- return await this._rescheduleOrAbandon(workflow, work, claimedAt, error);
210
- }
211
- await this._write(work, claimedAt, { status: 'done', claimedAt: null });
212
- return { status: 'done' };
213
- }
214
-
215
- // matchedCount, not modifiedCount: the fence is "do we still hold the claim", and
216
- // modifiedCount is also 0 for a write that matched but set an identical value - a
217
- // save() rewriting an unchanged checkpoint is not a lost claim.
218
- async _write(work, claimedAt, $set) {
219
- const { matchedCount } = await DeferredWork.updateOne({ _id: work._id, claimedAt }, { $set });
220
- if (!matchedCount) logger.warn('[WorkflowRunner] Claim lost, write discarded', { deferredWorkId: String(work._id) });
221
- return matchedCount > 0;
222
- }
223
-
224
- async _rescheduleOrAbandon(workflow, work, claimedAt, error) {
225
- // prepare() is consumer code and can throw anything, including null. Dereferencing
226
- // it here used to raise a TypeError out of this handler, so neither branch ran and
227
- // the record stayed `processing` until stale recovery hit the same failure again.
228
- const lastError = describeThrown(error);
229
- const delayMinutes = workflow.retrySchedule[work.attempt];
230
- if (error?.permanent === true || delayMinutes === undefined) {
231
- await this._write(work, claimedAt, { status: 'abandoned', lastError, claimedAt: null });
232
- logger.error('[WorkflowRunner] Abandoned', {
233
- kind: workflow.kind,
234
- dedupeKey: work.dedupeKey,
235
- attempt: work.attempt,
236
- permanent: error?.permanent === true,
237
- error: lastError
238
- });
239
- return { status: 'abandoned' };
240
- }
241
-
242
- const attempt = work.attempt + 1;
243
- const delayMs = delayMinutes * MINUTE_MS;
244
- const kept = await this._write(work, claimedAt, {
245
- status: 'pending',
246
- attempt,
247
- nextAttemptAt: new Date(Date.now() + delayMs),
248
- lastError,
249
- claimedAt: null
250
- });
251
- if (!kept) return { claimed: false };
252
-
253
- logger.warn('[WorkflowRunner] Rescheduled', {
254
- kind: workflow.kind,
255
- dedupeKey: work.dedupeKey,
256
- attempt,
257
- delayMinutes,
258
- error: lastError
259
- });
260
- this._arm(workflow, work._id, delayMs);
261
- return { status: 'pending', attempt };
262
- }
263
- }
264
-
265
- module.exports = { WorkflowRunner };
@@ -1,24 +0,0 @@
1
- const mongoose = require('mongoose');
2
-
3
- const STATUS_VALUES = ['pending', 'processing', 'done', 'abandoned'];
4
- const RETENTION_MS = 24 * 60 * 60 * 1000;
5
-
6
- const deferredWorkSchema = new mongoose.Schema({
7
- kind: { type: String, required: true },
8
- dedupeKey: { type: String, required: true },
9
- trigger: { type: mongoose.Schema.Types.Mixed, default: null },
10
- checkpoints: { type: mongoose.Schema.Types.Mixed, default: () => ({}) },
11
- status: { type: String, enum: STATUS_VALUES, default: 'pending' },
12
- attempt: { type: Number, default: 0 },
13
- nextAttemptAt: { type: Date, default: Date.now },
14
- claimedAt: { type: Date, default: null },
15
- lastError: { type: String, default: null }
16
- }, { timestamps: true });
17
-
18
- deferredWorkSchema.index({ kind: 1, dedupeKey: 1 }, { unique: true, name: 'dedupe_idx' });
19
- deferredWorkSchema.index({ status: 1, nextAttemptAt: 1 }, { name: 'due_idx' });
20
- deferredWorkSchema.index({ updatedAt: 1 }, { expireAfterSeconds: RETENTION_MS / 1000, name: 'ttl_idx' });
21
-
22
- const DeferredWork = mongoose.model('DeferredWork', deferredWorkSchema);
23
-
24
- module.exports = { DeferredWork, RETENTION_MS };