@peopl-health/nexus 5.77.0 → 5.77.2
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/lib/adapters/BaileysProvider.js +6 -0
- package/lib/adapters/TwilioProvider.js +6 -0
- package/lib/clinical/services/recommendationRecoveryService.js +3 -1
- package/lib/clinical/services/triageRecommendationService.js +15 -2
- package/lib/config/programConfig.js +20 -0
- package/lib/core/NexusMessaging.js +9 -1
- package/lib/helpers/outboundAllowlistHelper.js +51 -0
- package/lib/helpers/patientTaskRulesHelper.js +2 -3
- package/lib/index.d.ts +10 -0
- package/lib/index.js +8 -0
- package/lib/jobs/ScheduledMessageJob.js +9 -0
- package/lib/jobs/TemplateApprovalJob.js +5 -0
- package/lib/services/threadService.js +12 -3
- package/package.json +1 -1
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const { logger } = require('../utils/logger');
|
|
2
|
+
const { blockedSendResult, isOutboundAllowed, lastDigits } = require('../helpers/outboundAllowlistHelper');
|
|
1
3
|
const { MessageProvider } = require('../adapters/MessageProvider');
|
|
2
4
|
|
|
3
5
|
class BaileysProvider extends MessageProvider {
|
|
@@ -91,6 +93,10 @@ class BaileysProvider extends MessageProvider {
|
|
|
91
93
|
}
|
|
92
94
|
|
|
93
95
|
const formattedCode = this.formatCode(messageData.contactCode || code);
|
|
96
|
+
if (!isOutboundAllowed(formattedCode)) {
|
|
97
|
+
logger.warn('[BaileysProvider] outbound_blocked', { event: 'outbound_blocked', to: lastDigits(formattedCode) });
|
|
98
|
+
return blockedSendResult('baileys');
|
|
99
|
+
}
|
|
94
100
|
let sendOptions = {};
|
|
95
101
|
let formattedMessage = this.formatMessage(body || '');
|
|
96
102
|
|
|
@@ -11,6 +11,7 @@ const { isBenchMode } = require('../utils/benchModeHelper');
|
|
|
11
11
|
|
|
12
12
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
13
13
|
const { recordDeliveryAttempt } = require('../helpers/deliveryAttemptHelper');
|
|
14
|
+
const { blockedSendResult, isOutboundAllowed, lastDigits } = require('../helpers/outboundAllowlistHelper');
|
|
14
15
|
|
|
15
16
|
const { MessageProvider } = require('../adapters/MessageProvider');
|
|
16
17
|
const { isShadowRun } = require('../clinical/helpers/shadowHelper');
|
|
@@ -77,6 +78,11 @@ class TwilioProvider extends MessageProvider {
|
|
|
77
78
|
throw new Error('Invalid sender or recipient number');
|
|
78
79
|
}
|
|
79
80
|
|
|
81
|
+
if (!isOutboundAllowed(formattedCode)) {
|
|
82
|
+
logger.warn('[TwilioProvider] outbound_blocked', { event: 'outbound_blocked', to: lastDigits(formattedCode) });
|
|
83
|
+
return blockedSendResult('twilio');
|
|
84
|
+
}
|
|
85
|
+
|
|
80
86
|
const messageParams = {
|
|
81
87
|
from: formattedFrom,
|
|
82
88
|
to: formattedCode
|
|
@@ -5,6 +5,8 @@ const { logger } = require('../../utils/logger');
|
|
|
5
5
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
6
6
|
const { recommendationRetryLive } = require('../flags/recommendationRecoveryFlags');
|
|
7
7
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
8
|
+
const { programSource } = require('../../config/programConfig');
|
|
9
|
+
const { escapeFormulaValue } = require('../../helpers/airtableFormulaHelper');
|
|
8
10
|
const { createIntervalSweeper } = require('../../utils/intervalSweeper');
|
|
9
11
|
const { botIsPaused: threadIsPaused } = require('../../helpers/pausedThreadHelper');
|
|
10
12
|
const { recordUnresolvedRequest } = require('./clinicalAirtableService');
|
|
@@ -50,7 +52,7 @@ function orphanFormula(now) {
|
|
|
50
52
|
const oldest = new Date(now.getTime() - SCAN_WINDOW_MS).toISOString();
|
|
51
53
|
return [
|
|
52
54
|
'AND(',
|
|
53
|
-
|
|
55
|
+
`ARRAYJOIN({source})='${escapeFormulaValue(programSource())}',`,
|
|
54
56
|
'COUNTA({symptom_name_positive})>0,',
|
|
55
57
|
'COUNTA({cluster_recommendations})=0,',
|
|
56
58
|
`IS_AFTER({Created}, '${oldest}'),`,
|
|
@@ -44,6 +44,7 @@ const { buildTriageResponse } = require('../../fhir/helpers/triagePayloadHelper'
|
|
|
44
44
|
const { keyOf } = require('../../fhir/helpers/symptomAliasHelper');
|
|
45
45
|
const { getCatalog } = require('../../fhir/services/terminologyService');
|
|
46
46
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
47
|
+
const { findArchivedByRecordIds } = require('../../services/airtableArchiveReadService');
|
|
47
48
|
const { RecommendationPlan } = require('../../shared/dtos/RecommendationPlan');
|
|
48
49
|
const { recommendationId } = require('../../fhir/helpers/recommendationIds');
|
|
49
50
|
const { RecommendationSafetyGate } = require('../../shared/dtos/RecommendationSafetyGate');
|
|
@@ -1130,8 +1131,9 @@ async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
|
1130
1131
|
.filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
|
|
1131
1132
|
if (!ids.length) return [];
|
|
1132
1133
|
const formula = `OR(${ids.map((id) => `{recordID}='${id}'`).join(',')})`;
|
|
1133
|
-
const
|
|
1134
|
-
if (!
|
|
1134
|
+
const live = await getRecordByFilter(Symptoms_ID, 'cluster_resolutions', formula).catch(() => null);
|
|
1135
|
+
if (!live) return [];
|
|
1136
|
+
const rows = [...live, ...await readArchivedResolutions(ids.filter((id) => !live.some((row) => row.recordID === id)))];
|
|
1135
1137
|
if (!patientRecordId && rows.length) {
|
|
1136
1138
|
logger.warn('[triageRecommendation] prior resolutions unverified: payload carries no patientRecordId', { count: rows.length });
|
|
1137
1139
|
}
|
|
@@ -1145,6 +1147,17 @@ async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
|
1145
1147
|
.filter(Boolean);
|
|
1146
1148
|
}
|
|
1147
1149
|
|
|
1150
|
+
// A resolution deleted from Airtable is read from its archived copy; an unreadable archive only loses that context.
|
|
1151
|
+
async function readArchivedResolutions(ids) {
|
|
1152
|
+
if (!ids.length) return [];
|
|
1153
|
+
try {
|
|
1154
|
+
return await findArchivedByRecordIds({ baseId: Symptoms_ID, tableName: 'cluster_resolutions', recordIds: ids });
|
|
1155
|
+
} catch (error) {
|
|
1156
|
+
logger.warn('[triageRecommendation] archived prior resolutions unreadable', { count: ids.length, error: error?.message });
|
|
1157
|
+
return [];
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1148
1161
|
function ownedByPatient(row, patientRecordId) {
|
|
1149
1162
|
const owners = Array.isArray(row[PATIENT_LOOKUP_FIELD]) ? row[PATIENT_LOOKUP_FIELD] : [];
|
|
1150
1163
|
if (owners.includes(patientRecordId)) return true;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const runtimeConfig = require('./runtimeConfig');
|
|
2
|
+
|
|
3
|
+
// Symptoms/Monitoreo use `programa AMI`; Config uses `programa_AMI`.
|
|
4
|
+
const DEFAULT_PROGRAM_SOURCE = 'auna';
|
|
5
|
+
|
|
6
|
+
const programSource = () => runtimeConfig.get('PROGRAM_SOURCE') || DEFAULT_PROGRAM_SOURCE;
|
|
7
|
+
|
|
8
|
+
const programConfigSource = () => runtimeConfig.get('PROGRAM_CONFIG_SOURCE') || DEFAULT_PROGRAM_SOURCE;
|
|
9
|
+
|
|
10
|
+
function configureProgram({ source, configSource } = {}) {
|
|
11
|
+
if (source) runtimeConfig.set('PROGRAM_SOURCE', String(source));
|
|
12
|
+
if (configSource) runtimeConfig.set('PROGRAM_CONFIG_SOURCE', String(configSource));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
module.exports = {
|
|
16
|
+
DEFAULT_PROGRAM_SOURCE,
|
|
17
|
+
configureProgram,
|
|
18
|
+
programConfigSource,
|
|
19
|
+
programSource,
|
|
20
|
+
};
|
|
@@ -23,6 +23,7 @@ const { prepareMessageMedia } = require('../helpers/mediaHelper');
|
|
|
23
23
|
const { botIsPaused, patientIsDeceased } = require('../helpers/pausedThreadHelper');
|
|
24
24
|
const { acquireSendClaim, completeSendClaim, releaseSendClaim } = require('../helpers/sendClaimHelper');
|
|
25
25
|
const { isStaffSend } = require('../helpers/staffSendHelper');
|
|
26
|
+
const { isOutboundAllowed } = require('../helpers/outboundAllowlistHelper');
|
|
26
27
|
|
|
27
28
|
const { createMessagingProvider } = require('../adapters/registry');
|
|
28
29
|
const { ensureThreadExists } = require('../services/threadService');
|
|
@@ -65,6 +66,11 @@ const { PhiProcessor } = require('./PhiProcessor');
|
|
|
65
66
|
|
|
66
67
|
const FOLLOW_UP_SPACING_MIN = 180;
|
|
67
68
|
|
|
69
|
+
// A refused send is saved as `undelivered` so memory and the safety net skip it.
|
|
70
|
+
const unsentStatusInfo = (result) => (deliveryOutcome(result) === 'known_not_sent'
|
|
71
|
+
? { statusInfo: { status: 'undelivered', updatedAt: new Date() } }
|
|
72
|
+
: {});
|
|
73
|
+
|
|
68
74
|
async function followUpCollisionReason(code, reminderId, now) {
|
|
69
75
|
if (!reminderId.startsWith('followup_')) return routineOutreachCollisionReason(code, { now });
|
|
70
76
|
return isWithinTriageProtectionWindow(now) ? 'triage_protection_window' : null;
|
|
@@ -442,7 +448,7 @@ class NexusMessaging {
|
|
|
442
448
|
await this.messageStorage.saveMessage({
|
|
443
449
|
...messageData, body: encodedBody,
|
|
444
450
|
messageId: result?.messageId, provider: result?.provider,
|
|
445
|
-
fromMe: true, processed: true,
|
|
451
|
+
fromMe: true, processed: true, ...unsentStatusInfo(result),
|
|
446
452
|
});
|
|
447
453
|
}
|
|
448
454
|
return result;
|
|
@@ -552,6 +558,7 @@ class NexusMessaging {
|
|
|
552
558
|
...messageData, body: encodedBody, plainBody: decodedBody,
|
|
553
559
|
messageId: result?.messageId, provider: result?.provider,
|
|
554
560
|
fromMe: true, processed: true, origin: messageData.origin || 'assistant',
|
|
561
|
+
...unsentStatusInfo(result),
|
|
555
562
|
});
|
|
556
563
|
}
|
|
557
564
|
return result;
|
|
@@ -574,6 +581,7 @@ class NexusMessaging {
|
|
|
574
581
|
if (!this._providerStores) return false;
|
|
575
582
|
if (messageData.contentSid) return false;
|
|
576
583
|
if (!messageData.code) return false;
|
|
584
|
+
if (!isOutboundAllowed(messageData.contactCode || messageData.code)) return false;
|
|
577
585
|
return true;
|
|
578
586
|
}
|
|
579
587
|
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
2
|
+
const { logger } = require('../utils/logger');
|
|
3
|
+
|
|
4
|
+
// Compares digits only, so `whatsapp:+521...` and `521...@s.whatsapp.net` match.
|
|
5
|
+
const digitsOf = (code) => String(code ?? '').replace(/@.*$/, '').replace(/\D/g, '');
|
|
6
|
+
|
|
7
|
+
let warnedEmptyValue = null;
|
|
8
|
+
|
|
9
|
+
function outboundAllowlist() {
|
|
10
|
+
const raw = runtimeConfig.get('OUTBOUND_ALLOWLIST');
|
|
11
|
+
const entries = (Array.isArray(raw) ? raw : String(raw ?? '').split(','))
|
|
12
|
+
.map((entry) => String(entry ?? '').trim())
|
|
13
|
+
.filter(Boolean);
|
|
14
|
+
if (!entries.length) return null;
|
|
15
|
+
const digits = entries.map(digitsOf).filter(Boolean);
|
|
16
|
+
// A value with no digits blocks every send instead of allowing all.
|
|
17
|
+
if (!digits.length && warnedEmptyValue !== String(raw)) {
|
|
18
|
+
warnedEmptyValue = String(raw);
|
|
19
|
+
logger.warn('[outboundAllowlist] OUTBOUND_ALLOWLIST lists no number; every send is refused');
|
|
20
|
+
}
|
|
21
|
+
return new Set(digits);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function isOutboundAllowed(code) {
|
|
25
|
+
const allowlist = outboundAllowlist();
|
|
26
|
+
if (!allowlist) return true;
|
|
27
|
+
return allowlist.has(digitsOf(code));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const lastDigits = (code) => digitsOf(code).slice(-4);
|
|
31
|
+
|
|
32
|
+
// `undelivered`, not `failed`: inbound recovery would chase a `failed` send and alert ops.
|
|
33
|
+
function blockedSendResult(provider) {
|
|
34
|
+
return {
|
|
35
|
+
success: false,
|
|
36
|
+
messageId: null,
|
|
37
|
+
provider,
|
|
38
|
+
status: 'outbound_blocked',
|
|
39
|
+
result: null,
|
|
40
|
+
finalize: { sid: null, status: 'undelivered' },
|
|
41
|
+
delivered: false,
|
|
42
|
+
deferred: false
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
module.exports = {
|
|
47
|
+
blockedSendResult,
|
|
48
|
+
isOutboundAllowed,
|
|
49
|
+
lastDigits,
|
|
50
|
+
outboundAllowlist,
|
|
51
|
+
};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { programSource } = require('../config/programConfig');
|
|
1
2
|
const { escapeFormulaValue } = require('./airtableFormulaHelper');
|
|
2
3
|
|
|
3
4
|
const CLOSED_REQUEST_STATUSES = [
|
|
@@ -17,9 +18,7 @@ const REQUEST_URGENCIES = ['routine', 'soon', 'urgent'];
|
|
|
17
18
|
const URGENT_CASE_TYPES = ['Urgencia', 'Emergencia'];
|
|
18
19
|
// The operations statuses that close a case in Airtable, including the legacy lowercase one.
|
|
19
20
|
const CLOSING_CASE_OPERATIONS_STATUSES = new Set(['Cerrado', 'No requiere', 'cerrado']);
|
|
20
|
-
const
|
|
21
|
-
|
|
22
|
-
const programSourceFilter = (field) => `FIND('${escapeFormulaValue(TASK_PROGRAM_SOURCE)}', ARRAYJOIN({${field}}))`;
|
|
21
|
+
const programSourceFilter = (field) => `FIND('${escapeFormulaValue(programSource())}', ARRAYJOIN({${field}}))`;
|
|
23
22
|
|
|
24
23
|
const isRequestOpen = (status) => !CLOSED_REQUEST_STATUSES.includes(status);
|
|
25
24
|
|
package/lib/index.d.ts
CHANGED
|
@@ -358,6 +358,16 @@ declare module '@peopl-health/nexus' {
|
|
|
358
358
|
inboundRecovery?: InboundRecoveryOptions;
|
|
359
359
|
reviewDrafts?: ReviewDraftsOptions;
|
|
360
360
|
reviewAlerts?: ReviewAlertsOptions;
|
|
361
|
+
program?: ProgramOptions;
|
|
362
|
+
/** Allowed outbound numbers; unset allows all. */
|
|
363
|
+
outboundAllowlist?: string | string[];
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
export interface ProgramOptions {
|
|
367
|
+
/** The program label in the Symptoms and Monitoreo bases. Defaults to `auna`. */
|
|
368
|
+
source?: string;
|
|
369
|
+
/** The program label in the Config base. Defaults to `auna`. */
|
|
370
|
+
configSource?: string;
|
|
361
371
|
}
|
|
362
372
|
|
|
363
373
|
export interface RecommendationRecoveryOptions {
|
package/lib/index.js
CHANGED
|
@@ -31,6 +31,7 @@ const { configureSafetyNet } = require('./clinical/config/safetyNetConfig');
|
|
|
31
31
|
const { registerSafetyNetRoutes } = require('./clinical/services/pausedSafetyNetService');
|
|
32
32
|
const { ensureOnePledgePerContact, startSafetyNetSweep } = require('./clinical/services/safetyNetPledgeService');
|
|
33
33
|
const { startRecommendationRecoverySweep } = require('./clinical/services/recommendationRecoveryService');
|
|
34
|
+
const { configureProgram } = require('./config/programConfig');
|
|
34
35
|
const { startInboundRecoverySweep } = require('./services/inboundRecoveryService');
|
|
35
36
|
const { startReviewDraftSweep } = require('./services/reviewDraftSweepService');
|
|
36
37
|
const { startReviewAlertSweep } = require('./services/reviewAlertSweepService');
|
|
@@ -159,6 +160,13 @@ class Nexus {
|
|
|
159
160
|
if (options.airtable && options.airtable.apiKey) {
|
|
160
161
|
runtimeConfig.set('AIRTABLE_API_KEY', options.airtable.apiKey);
|
|
161
162
|
}
|
|
163
|
+
|
|
164
|
+
if (options.outboundAllowlist) {
|
|
165
|
+
runtimeConfig.set('OUTBOUND_ALLOWLIST', options.outboundAllowlist);
|
|
166
|
+
}
|
|
167
|
+
if (options.program) {
|
|
168
|
+
configureProgram(options.program);
|
|
169
|
+
}
|
|
162
170
|
} catch (cfgErr) {
|
|
163
171
|
logger.warn('[Nexus] convenience config warning:', cfgErr?.message || cfgErr);
|
|
164
172
|
}
|
|
@@ -144,6 +144,15 @@ class ScheduledMessageJob extends BaseJob {
|
|
|
144
144
|
return { success: false, reason: result.status };
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
+
if (result?.status === 'outbound_blocked') {
|
|
148
|
+
await ScheduledMessage.updateOne(
|
|
149
|
+
{ _id: scheduledMessageId },
|
|
150
|
+
{ $set: { status: 'cancelled', errorCode: result.status, errorMessage: 'The outbound allowlist refused the number' } }
|
|
151
|
+
);
|
|
152
|
+
logger.info('[ScheduledMessageJob] Not sent: the outbound allowlist refused the number', { scheduledMessageId });
|
|
153
|
+
return { success: false, reason: result.status };
|
|
154
|
+
}
|
|
155
|
+
|
|
147
156
|
if (result?.status === 'contact_capped') {
|
|
148
157
|
await ScheduledMessage.updateOne(
|
|
149
158
|
{ _id: scheduledMessageId },
|
|
@@ -303,6 +303,11 @@ class TemplateApprovalJob extends BaseJob {
|
|
|
303
303
|
logger.info('[TemplateApprovalJob] Recovery send already claimed elsewhere', { templateSid, messageId: message._id });
|
|
304
304
|
return { success: false, reason: 'duplicate_suppressed' };
|
|
305
305
|
}
|
|
306
|
+
if (sendResult?.status === 'outbound_blocked') {
|
|
307
|
+
// Keep the claim so the job does not retry a blocked number.
|
|
308
|
+
logger.warn('[TemplateApprovalJob] Recovery send refused by the outbound allowlist', { templateSid, messageId: message._id });
|
|
309
|
+
return { success: false, reason: 'outbound_blocked' };
|
|
310
|
+
}
|
|
306
311
|
if (!sendResult?.messageId) {
|
|
307
312
|
throw new Error('Provider did not return a messageId for the recovery send');
|
|
308
313
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
const { Config_ID, Monitoreo_ID, Historial_Clinico_ID } = require('../config/airtableConfig.js');
|
|
2
2
|
const runtimeConfig = require('../config/runtimeConfig.js');
|
|
3
|
+
const { programConfigSource } = require('../config/programConfig.js');
|
|
3
4
|
|
|
4
5
|
const { logger } = require('../utils/logger');
|
|
5
6
|
|
|
6
7
|
const { Thread } = require('../models/threadModel.js');
|
|
8
|
+
const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper.js');
|
|
7
9
|
const { patientIsDeceased } = require('../helpers/pausedThreadHelper.js');
|
|
8
10
|
|
|
9
11
|
const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService.js');
|
|
@@ -67,9 +69,15 @@ const setThreadPromptId = async (code, promptId) => {
|
|
|
67
69
|
.catch(err => logger.error('[setThreadPromptId] Failed to update message_monitor', { code, error: err.message }));
|
|
68
70
|
};
|
|
69
71
|
|
|
72
|
+
// `status` and `source` are multi-selects, so equality would miss a `prod, dev` row.
|
|
73
|
+
const defaultPromptFormula = () => {
|
|
74
|
+
const status = escapeFormulaValue(runtimeConfig.getServerMode());
|
|
75
|
+
const source = escapeFormulaValue(programConfigSource());
|
|
76
|
+
return `AND({code}="PIPO_ASST", FIND('${status}', ARRAYJOIN({status})), FIND('${source}', ARRAYJOIN({source})))`;
|
|
77
|
+
};
|
|
78
|
+
|
|
70
79
|
const createThread = async (code, { assistantId = null, fallbackName = null }) => {
|
|
71
|
-
const
|
|
72
|
-
const configRecord = await getRecordByFilter(Config_ID, 'responses', `AND({code}="PIPO_ASST", {status}="${assistantStatus}")`, undefined, ['prompt_id']);
|
|
80
|
+
const configRecord = await getRecordByFilter(Config_ID, 'responses', defaultPromptFormula(), undefined, ['prompt_id']);
|
|
73
81
|
const patientRecord = await getRecordByFilter(Historial_Clinico_ID, 'estado_general', `{whatsapp_id} = "${code}"`, undefined, ['name', 'record_id']);
|
|
74
82
|
|
|
75
83
|
const promptId = assistantId || configRecord?.[0]?.['prompt_id'] || null;
|
|
@@ -119,5 +127,6 @@ module.exports = {
|
|
|
119
127
|
setThreadDoNotAlert,
|
|
120
128
|
setThreadPromptId,
|
|
121
129
|
setCheckInsPausedUntil,
|
|
122
|
-
checkInsPausedUntil
|
|
130
|
+
checkInsPausedUntil,
|
|
131
|
+
defaultPromptFormula
|
|
123
132
|
};
|