@peopl-health/nexus 5.78.0-dev.16618 → 5.78.0-dev.16671
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/config/airtableArchiveConfig.js +3 -0
- 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/airtableArchiveService.js +3 -3
- package/lib/services/airtableMirrorService.js +7 -2
- 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}'),`,
|
|
@@ -138,6 +138,8 @@ const ARCHIVE_DELETE_ORDER = Object.freeze([
|
|
|
138
138
|
ARCHIVE_TABLES.RESOLUTIONS, ARCHIVE_TABLES.ADDITIONAL_ANSWERS, ARCHIVE_TABLES.SYMPTOMS,
|
|
139
139
|
]);
|
|
140
140
|
const ARCHIVE_DELETE_SPACING_MS = 250;
|
|
141
|
+
// Airtable deletes at most 10 records per request.
|
|
142
|
+
const ARCHIVE_DELETE_CHUNK_SIZE = 10;
|
|
141
143
|
// The patients table: a mirrored record's patient is its link to it and the WhatsApp id looked up through that link.
|
|
142
144
|
const PATIENT_TABLE = Object.freeze({ ID: 'tblUi9KbsefAbrvK2', WHATSAPP: 'fldMfzbVbAxIJ9345' });
|
|
143
145
|
// Attachments re-hosted per mirror run; the rest wait for the next run, so the first runs over a full base stay bounded.
|
|
@@ -157,6 +159,7 @@ module.exports = {
|
|
|
157
159
|
ARCHIVE_DELETE_MAX_GROUPS,
|
|
158
160
|
ARCHIVE_DELETE_ORDER,
|
|
159
161
|
ARCHIVE_DELETE_SPACING_MS,
|
|
162
|
+
ARCHIVE_DELETE_CHUNK_SIZE,
|
|
160
163
|
PATIENT_TABLE,
|
|
161
164
|
MIRROR_MAX_ATTACHMENTS_PER_RUN,
|
|
162
165
|
MIRROR_GONE_MAX_SHARE,
|
|
@@ -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
|
}
|
|
@@ -5,7 +5,7 @@ const runtimeConfig = require('../config/runtimeConfig');
|
|
|
5
5
|
const { uploadBufferToS3 } = require('../config/awsConfig');
|
|
6
6
|
const {
|
|
7
7
|
ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ARCHIVE_LEASE_RENEW_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS, PATIENT_FIELDS, PLANNER_FIELDS,
|
|
8
|
-
ARCHIVE_DELETE_MAX_GROUPS, ARCHIVE_DELETE_ORDER, ARCHIVE_DELETE_SPACING_MS, LINK_FIELD_TYPES,
|
|
8
|
+
ARCHIVE_DELETE_MAX_GROUPS, ARCHIVE_DELETE_ORDER, ARCHIVE_DELETE_SPACING_MS, ARCHIVE_DELETE_CHUNK_SIZE, LINK_FIELD_TYPES,
|
|
9
9
|
} = require('../config/airtableArchiveConfig');
|
|
10
10
|
const { logger } = require('../utils/logger');
|
|
11
11
|
const { stableStringify } = require('../utils/jsonUtils');
|
|
@@ -430,8 +430,8 @@ async function deleteBatch({ baseId, runId, batch, schema, counts, groups, lease
|
|
|
430
430
|
|
|
431
431
|
for (const tableId of ARCHIVE_DELETE_ORDER) {
|
|
432
432
|
const entries = verified.filter(({ table }) => schema.tableIds[table] === tableId);
|
|
433
|
-
for (let i = 0; i < entries.length; i +=
|
|
434
|
-
const chunk = entries.slice(i, i +
|
|
433
|
+
for (let i = 0; i < entries.length; i += ARCHIVE_DELETE_CHUNK_SIZE) {
|
|
434
|
+
const chunk = entries.slice(i, i + ARCHIVE_DELETE_CHUNK_SIZE);
|
|
435
435
|
// Re-checked right before its request, so an edit made while earlier chunks were deleted stops the run with its copy stamped.
|
|
436
436
|
const changed = await findBlockers({ baseId, entries: chunk, schema, lease, liveIds, cutoff, models });
|
|
437
437
|
if (changed.length) {
|
|
@@ -45,6 +45,12 @@ function patientOf(spec, record) {
|
|
|
45
45
|
|
|
46
46
|
const hasPatient = (patient) => Boolean(patient?.recordId || patient?.whatsappId);
|
|
47
47
|
|
|
48
|
+
// A planned copy keeps the planner's patient, which its delete checks; any other follows its record, unless the record lost its link.
|
|
49
|
+
function patientFor(previous, current) {
|
|
50
|
+
if (previous?.groupId || (!hasPatient(current) && hasPatient(previous?.patient))) return previous.patient;
|
|
51
|
+
return current;
|
|
52
|
+
}
|
|
53
|
+
|
|
48
54
|
// Stamps a mirror set because a scan missed the record; those are undone when it shows up again.
|
|
49
55
|
async function mirrorStampsOf(docs) {
|
|
50
56
|
const stampRunIds = [...new Set(docs.filter((doc) => doc.sourceDeletedAt && doc.deleteRunId).map((doc) => doc.deleteRunId))];
|
|
@@ -110,8 +116,7 @@ async function mirrorPage({ baseId, runId, table, page, Records, names, computed
|
|
|
110
116
|
$set: {
|
|
111
117
|
baseId, tableId: table.id, tableName: table.name, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
112
118
|
fields: normalized, fieldsHash, sourceHash: hashFields(normalized, computed),
|
|
113
|
-
|
|
114
|
-
patient: previous?.groupId || hasPatient(previous?.patient) ? previous.patient : patientOf(patientSpec, record),
|
|
119
|
+
patient: patientFor(previous, patientOf(patientSpec, record)),
|
|
115
120
|
schemaId, attachments: hosted, source: { kind: 'live', baseId }, schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
116
121
|
...(restored ? { sourceDeletedAt: null } : {}),
|
|
117
122
|
},
|
|
@@ -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
|
};
|