@peopl-health/nexus 5.78.0-dev.16617 → 5.78.0-dev.16670
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 +11 -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/models/airtableArchiveModel.js +8 -2
- package/lib/services/airtableArchiveService.js +10 -1
- package/lib/services/airtableMirrorService.js +228 -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}'),`,
|
|
@@ -138,6 +138,13 @@ 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
|
+
// The patients table: a mirrored record's patient is its link to it and the WhatsApp id looked up through that link.
|
|
142
|
+
const PATIENT_TABLE = Object.freeze({ ID: 'tblUi9KbsefAbrvK2', WHATSAPP: 'fldMfzbVbAxIJ9345' });
|
|
143
|
+
// Attachments re-hosted per mirror run; the rest wait for the next run, so the first runs over a full base stay bounded.
|
|
144
|
+
const MIRROR_MAX_ATTACHMENTS_PER_RUN = 2000;
|
|
145
|
+
// More records missing from a full scan than this is taken for a bad read, not deletions: none are marked gone.
|
|
146
|
+
const MIRROR_GONE_MAX_SHARE = 0.02;
|
|
147
|
+
const MIRROR_GONE_MIN_HELD = 25;
|
|
141
148
|
|
|
142
149
|
module.exports = {
|
|
143
150
|
ARCHIVE_TABLES,
|
|
@@ -150,6 +157,10 @@ module.exports = {
|
|
|
150
157
|
ARCHIVE_DELETE_MAX_GROUPS,
|
|
151
158
|
ARCHIVE_DELETE_ORDER,
|
|
152
159
|
ARCHIVE_DELETE_SPACING_MS,
|
|
160
|
+
PATIENT_TABLE,
|
|
161
|
+
MIRROR_MAX_ATTACHMENTS_PER_RUN,
|
|
162
|
+
MIRROR_GONE_MAX_SHARE,
|
|
163
|
+
MIRROR_GONE_MIN_HELD,
|
|
153
164
|
COMPUTED_FIELD_TYPES,
|
|
154
165
|
GROUP_LINKS,
|
|
155
166
|
CARRY_OVER_LINKS,
|
|
@@ -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
|
}
|
|
@@ -3,7 +3,7 @@ const mongoose = require('mongoose');
|
|
|
3
3
|
const { getDb, getModelDatabase } = require('../config/mongoConfig');
|
|
4
4
|
|
|
5
5
|
const ARCHIVE_SCHEMA_VERSION = 1;
|
|
6
|
-
const ARCHIVE_RUN_MODES = ['plan', 'copy', 'delete'];
|
|
6
|
+
const ARCHIVE_RUN_MODES = ['plan', 'copy', 'delete', 'mirror'];
|
|
7
7
|
const ARCHIVE_RUN_STATUSES = ['running', 'succeeded', 'failed'];
|
|
8
8
|
const ARCHIVE_SOURCE_KINDS = ['live', 'copy', 'export'];
|
|
9
9
|
// Database and collection names: lowercase letters, digits and underscores, as derived by `storeName`.
|
|
@@ -67,6 +67,11 @@ const tableCountsSchema = new mongoose.Schema({
|
|
|
67
67
|
skipped: { type: Number, default: 0 },
|
|
68
68
|
stamped: { type: Number, default: 0 },
|
|
69
69
|
deleted: { type: Number, default: 0 },
|
|
70
|
+
unchanged: { type: Number, default: 0 },
|
|
71
|
+
gone: { type: Number, default: 0 },
|
|
72
|
+
goneHeld: { type: Number, default: 0 },
|
|
73
|
+
restored: { type: Number, default: 0 },
|
|
74
|
+
attachmentsPending: { type: Number, default: 0 },
|
|
70
75
|
}, { _id: false });
|
|
71
76
|
|
|
72
77
|
// One eligible group as the plan saw it, so a later delete can name exactly the groups that were reviewed.
|
|
@@ -83,7 +88,8 @@ const airtableArchiveRunSchema = new mongoose.Schema({
|
|
|
83
88
|
runId: { type: String, required: true },
|
|
84
89
|
baseId: { type: String, required: true },
|
|
85
90
|
mode: { type: String, enum: ARCHIVE_RUN_MODES, required: true },
|
|
86
|
-
|
|
91
|
+
// A mirror copies the base as it is, so it has no cutoff.
|
|
92
|
+
cutoff: { type: Date, default: null },
|
|
87
93
|
status: { type: String, enum: ARCHIVE_RUN_STATUSES, required: true, default: 'running' },
|
|
88
94
|
startedAt: { type: Date, required: true },
|
|
89
95
|
finishedAt: { type: Date, default: null },
|
|
@@ -476,7 +476,7 @@ function groupBatches(groups) {
|
|
|
476
476
|
|
|
477
477
|
function validateRequest({ baseId, cutoff, mode, now, groupIds }) {
|
|
478
478
|
if (!baseId) throw archiveError('archive_base_required');
|
|
479
|
-
if (!ARCHIVE_RUN_MODES.includes(mode)) throw archiveError('archive_mode_invalid');
|
|
479
|
+
if (!ARCHIVE_RUN_MODES.includes(mode) || mode === 'mirror') throw archiveError('archive_mode_invalid');
|
|
480
480
|
if (mode === 'delete') {
|
|
481
481
|
const valid = Array.isArray(groupIds) && groupIds.length > 0 && groupIds.length <= ARCHIVE_DELETE_MAX_GROUPS
|
|
482
482
|
&& groupIds.every((id) => typeof id === 'string' && id) && new Set(groupIds).size === groupIds.length;
|
|
@@ -555,4 +555,13 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date(), gro
|
|
|
555
555
|
|
|
556
556
|
module.exports = {
|
|
557
557
|
runArchive,
|
|
558
|
+
// Shared with the mirror, which runs under the same single-flight lease per base.
|
|
559
|
+
archiveError,
|
|
560
|
+
acquireRun,
|
|
561
|
+
leaseFor,
|
|
562
|
+
renewLease,
|
|
563
|
+
rehostAttachments,
|
|
564
|
+
writeOps,
|
|
565
|
+
storeSchemaSnapshot,
|
|
566
|
+
WRITE_CONCERN,
|
|
558
567
|
};
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
const {
|
|
2
|
+
COMPUTED_FIELD_TYPES, LINK_FIELD_TYPES, PATIENT_FIELDS, WHATSAPP_FIELDS, PATIENT_TABLE,
|
|
3
|
+
MIRROR_MAX_ATTACHMENTS_PER_RUN, MIRROR_GONE_MAX_SHARE, MIRROR_GONE_MIN_HELD,
|
|
4
|
+
} = require('../config/airtableArchiveConfig');
|
|
5
|
+
const { logger } = require('../utils/logger');
|
|
6
|
+
const { firstOf } = require('../utils/coercionUtils');
|
|
7
|
+
const { ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRun, getAirtableTableRecords } = require('../models/airtableArchiveModel');
|
|
8
|
+
const { normalizeFields, hashFields } = require('../helpers/airtableArchiveHelper');
|
|
9
|
+
|
|
10
|
+
const { getBaseSchema, scanRecordPages } = require('./airtableService');
|
|
11
|
+
const {
|
|
12
|
+
archiveError, acquireRun, leaseFor, renewLease, rehostAttachments, writeOps, storeSchemaSnapshot, WRITE_CONCERN,
|
|
13
|
+
} = require('./airtableArchiveService');
|
|
14
|
+
|
|
15
|
+
const emptyCounts = () => ({
|
|
16
|
+
scanned: 0, copied: 0, refreshed: 0, unchanged: 0, skipped: 0, verified: 0, failed: 0, gone: 0, goneHeld: 0, restored: 0, attachmentsPending: 0,
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const snapshotOf = (tables) => tables.map(({ id, name, fields }) => ({
|
|
20
|
+
id, name, fields: fields.map((f) => ({ id: f.id, name: f.name, type: f.type })).sort((a, b) => a.id.localeCompare(b.id)),
|
|
21
|
+
}));
|
|
22
|
+
|
|
23
|
+
const firstText = (value) => {
|
|
24
|
+
const first = firstOf(value);
|
|
25
|
+
return typeof first === 'string' && first ? first : null;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
// The fields naming a table's patient: the planner's own where it has them, so a mirrored copy and an archived one agree.
|
|
29
|
+
function patientFieldsOf(table) {
|
|
30
|
+
if (table.id === PATIENT_TABLE.ID) return { self: true, whatsapp: PATIENT_TABLE.WHATSAPP };
|
|
31
|
+
if (PATIENT_FIELDS[table.id]) return { link: PATIENT_FIELDS[table.id], whatsapp: WHATSAPP_FIELDS[table.id] || null };
|
|
32
|
+
const links = table.fields.filter((f) => LINK_FIELD_TYPES.includes(f.type) && f.options?.linkedTableId === PATIENT_TABLE.ID);
|
|
33
|
+
if (links.length !== 1) return null;
|
|
34
|
+
// With one link to the patients table, a lookup of their WhatsApp id can only go through it.
|
|
35
|
+
const whatsapp = table.fields.find((f) => f.options?.fieldIdInLinkedTable === PATIENT_TABLE.WHATSAPP);
|
|
36
|
+
return { link: links[0].id, whatsapp: whatsapp?.id || null };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Read from the raw record, keyed by field id, so a renamed field cannot lose the patient.
|
|
40
|
+
function patientOf(spec, record) {
|
|
41
|
+
if (!spec) return { recordId: null, whatsappId: null };
|
|
42
|
+
if (spec.self) return { recordId: record.id, whatsappId: firstText(record.fields[spec.whatsapp]) };
|
|
43
|
+
return { recordId: firstText(record.fields[spec.link]), whatsappId: spec.whatsapp ? firstText(record.fields[spec.whatsapp]) : null };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const hasPatient = (patient) => Boolean(patient?.recordId || patient?.whatsappId);
|
|
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
|
+
|
|
54
|
+
// Stamps a mirror set because a scan missed the record; those are undone when it shows up again.
|
|
55
|
+
async function mirrorStampsOf(docs) {
|
|
56
|
+
const stampRunIds = [...new Set(docs.filter((doc) => doc.sourceDeletedAt && doc.deleteRunId).map((doc) => doc.deleteRunId))];
|
|
57
|
+
if (!stampRunIds.length) return new Set();
|
|
58
|
+
const runs = await getAirtableArchiveRun().find({ runId: { $in: stampRunIds }, mode: 'mirror' }, { runId: 1 }).lean();
|
|
59
|
+
return new Set(runs.map((run) => run.runId));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function mirrorPage({ baseId, runId, table, page, Records, names, computed, patientSpec, schemaId, counts, budget, seen, now }) {
|
|
63
|
+
const existing = new Map((await Records.find(
|
|
64
|
+
{ _id: { $in: page.map((record) => record.id) } }, { fieldsHash: 1, tableName: 1, patient: 1, groupId: 1, attachments: 1, sourceDeletedAt: 1, deleteRunId: 1 },
|
|
65
|
+
).lean()).map((doc) => [doc._id, doc]));
|
|
66
|
+
const mirrorStamps = await mirrorStampsOf([...existing.values()]);
|
|
67
|
+
const ops = [];
|
|
68
|
+
const expected = new Map();
|
|
69
|
+
for (const record of page) {
|
|
70
|
+
seen.add(record.id);
|
|
71
|
+
const fields = {};
|
|
72
|
+
for (const [fieldId, value] of Object.entries(record.fields)) {
|
|
73
|
+
if (!names.has(fieldId)) {
|
|
74
|
+
logger.error('[airtableMirror] Scanned a field missing from the run schema', { runId, table: table.name, fieldId });
|
|
75
|
+
throw archiveError('archive_schema_mismatch');
|
|
76
|
+
}
|
|
77
|
+
fields[names.get(fieldId)] = value;
|
|
78
|
+
}
|
|
79
|
+
const previous = existing.get(record.id);
|
|
80
|
+
const restored = Boolean(previous?.sourceDeletedAt) && mirrorStamps.has(previous.deleteRunId);
|
|
81
|
+
// A stamped copy stands in for a record a delete is removing; the delete decides it, not the mirror.
|
|
82
|
+
if (previous?.sourceDeletedAt && !restored) {
|
|
83
|
+
counts.skipped += 1;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const { normalized, attachments } = normalizeFields(fields);
|
|
87
|
+
const fieldsHash = hashFields(normalized);
|
|
88
|
+
const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
|
|
89
|
+
const unhosted = attachments.filter(({ item }) => !alreadyHosted.has(item.id));
|
|
90
|
+
if (previous && !restored && previous.fieldsHash === fieldsHash && previous.tableName === table.name && !unhosted.length) {
|
|
91
|
+
counts.unchanged += 1;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
// Attachments past the run's budget stay unhosted, so the record is rewritten by the next run that has room.
|
|
95
|
+
const hostable = attachments.filter(({ item }) => {
|
|
96
|
+
if (alreadyHosted.has(item.id)) return true;
|
|
97
|
+
if (budget.attachments <= 0) return false;
|
|
98
|
+
budget.attachments -= 1;
|
|
99
|
+
return true;
|
|
100
|
+
});
|
|
101
|
+
counts.attachmentsPending += attachments.length - hostable.length;
|
|
102
|
+
let hosted;
|
|
103
|
+
try {
|
|
104
|
+
hosted = await rehostAttachments({ baseId, tableId: table.id, recordId: record.id, attachments: hostable, alreadyHosted });
|
|
105
|
+
} catch (error) {
|
|
106
|
+
// The fields are copied anyway; the attachments left unhosted are retried by the next run.
|
|
107
|
+
hosted = hostable.filter(({ item }) => alreadyHosted.has(item.id)).map(({ item }) => alreadyHosted.get(item.id));
|
|
108
|
+
counts.attachmentsPending += hostable.length - hosted.length;
|
|
109
|
+
logger.error('[airtableMirror] Attachments not hosted', { runId, table: table.name, recordId: record.id, errorCode: error?.code || 'UNKNOWN' });
|
|
110
|
+
}
|
|
111
|
+
ops.push({
|
|
112
|
+
updateOne: {
|
|
113
|
+
// Only a restore clears a stamp, and only its own: a delete that stamped meanwhile keeps the copy it serves.
|
|
114
|
+
filter: restored ? { _id: record.id, deleteRunId: previous.deleteRunId } : { _id: record.id },
|
|
115
|
+
update: {
|
|
116
|
+
$set: {
|
|
117
|
+
baseId, tableId: table.id, tableName: table.name, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
118
|
+
fields: normalized, fieldsHash, sourceHash: hashFields(normalized, computed),
|
|
119
|
+
patient: patientFor(previous, patientOf(patientSpec, record)),
|
|
120
|
+
schemaId, attachments: hosted, source: { kind: 'live', baseId }, schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
121
|
+
...(restored ? { sourceDeletedAt: null } : {}),
|
|
122
|
+
},
|
|
123
|
+
...(restored ? { $unset: { deleteRunId: '' } } : {}),
|
|
124
|
+
$setOnInsert: { runId, archivedAt: now, groupId: null, ...(restored ? {} : { sourceDeletedAt: null }) },
|
|
125
|
+
},
|
|
126
|
+
upsert: true,
|
|
127
|
+
},
|
|
128
|
+
});
|
|
129
|
+
expected.set(record.id, fieldsHash);
|
|
130
|
+
counts[previous ? 'refreshed' : 'copied'] += 1;
|
|
131
|
+
if (restored) counts.restored += 1;
|
|
132
|
+
// Downloads can outlast the lease, so a record that uploaded any renews it before the next one.
|
|
133
|
+
if (hostable.some(({ item }) => !alreadyHosted.has(item.id))) await renewLease(runId);
|
|
134
|
+
}
|
|
135
|
+
if (!ops.length) return;
|
|
136
|
+
await writeOps(Records, ops, runId);
|
|
137
|
+
const stored = new Map((await Records.find({ _id: { $in: [...expected.keys()] } }, { fields: 1 }).lean()).map((doc) => [doc._id, doc]));
|
|
138
|
+
for (const [recordId, fieldsHash] of expected) {
|
|
139
|
+
if (stored.has(recordId) && hashFields(stored.get(recordId).fields) === fieldsHash) counts.verified += 1;
|
|
140
|
+
else {
|
|
141
|
+
counts.failed += 1;
|
|
142
|
+
logger.error('[airtableMirror] Copy did not verify', { runId, table: table.name, recordId });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Copies the scan missed after a full read were deleted from Airtable; too many at once reads as a bad scan instead.
|
|
148
|
+
async function markGone({ Records, runId, table, seen, counts, now }) {
|
|
149
|
+
const stored = await Records.find({ sourceDeletedAt: null, 'source.kind': 'live' }, { _id: 1 }).lean();
|
|
150
|
+
const gone = stored.map((doc) => doc._id).filter((id) => !seen.has(id));
|
|
151
|
+
if (!gone.length) return;
|
|
152
|
+
if (!seen.size || gone.length > Math.max(MIRROR_GONE_MIN_HELD, Math.ceil(stored.length * MIRROR_GONE_MAX_SHARE))) {
|
|
153
|
+
counts.goneHeld = gone.length;
|
|
154
|
+
logger.error('[airtableMirror] Too many records missing from a full scan, none marked gone', { runId, table: table.name, missing: gone.length, stored: stored.length });
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
await Records.updateMany({ _id: { $in: gone }, sourceDeletedAt: null }, { $set: { sourceDeletedAt: now, deleteRunId: runId } }, { writeConcern: WRITE_CONCERN });
|
|
158
|
+
counts.gone = await Records.countDocuments({ _id: { $in: gone }, deleteRunId: runId });
|
|
159
|
+
if (counts.gone !== gone.length) {
|
|
160
|
+
counts.failed += gone.length - counts.gone;
|
|
161
|
+
logger.error('[airtableMirror] Gone records did not read back stamped', { runId, table: table.name, missing: gone.length, stamped: counts.gone });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function mirrorTable({ baseId, runId, table, schemaId, counts, budget, lease, now }) {
|
|
166
|
+
const Records = await getAirtableTableRecords({ baseId, tableId: table.id, tableName: table.name });
|
|
167
|
+
const names = new Map(table.fields.map((f) => [f.id, f.name]));
|
|
168
|
+
const computed = new Set(table.fields.filter((f) => COMPUTED_FIELD_TYPES.includes(f.type)).map((f) => f.name));
|
|
169
|
+
const patientSpec = patientFieldsOf(table);
|
|
170
|
+
const seen = new Set();
|
|
171
|
+
await scanRecordPages(baseId, table.id, {
|
|
172
|
+
onPage: async (page) => {
|
|
173
|
+
await mirrorPage({ baseId, runId, table, page, Records, names, computed, patientSpec, schemaId, counts, budget, seen, now });
|
|
174
|
+
await lease.renewIfDue();
|
|
175
|
+
},
|
|
176
|
+
// Pages already written are rewritten as unchanged; `seen` only grows, so a restart cannot mark anything gone.
|
|
177
|
+
onRestart: () => {},
|
|
178
|
+
});
|
|
179
|
+
counts.scanned = seen.size;
|
|
180
|
+
await markGone({ Records, runId, table, seen, counts, now });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Copies every table of a base into its collection as it is now and marks copies whose record left Airtable; never writes to Airtable.
|
|
184
|
+
async function runMirror({ baseId, now = new Date(), maxAttachments = MIRROR_MAX_ATTACHMENTS_PER_RUN }) {
|
|
185
|
+
if (!baseId) throw archiveError('archive_base_required');
|
|
186
|
+
const { runId } = await acquireRun({ baseId, mode: 'mirror', cutoff: null, now });
|
|
187
|
+
const counts = {};
|
|
188
|
+
try {
|
|
189
|
+
let tables;
|
|
190
|
+
try {
|
|
191
|
+
tables = await getBaseSchema(baseId);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
throw Object.assign(archiveError('archive_schema_unreadable'), { cause: error });
|
|
194
|
+
}
|
|
195
|
+
const schemaId = await storeSchemaSnapshot(baseId, snapshotOf(tables), now);
|
|
196
|
+
const lease = leaseFor(runId);
|
|
197
|
+
const budget = { attachments: maxAttachments };
|
|
198
|
+
for (const table of tables) {
|
|
199
|
+
counts[table.name] = emptyCounts();
|
|
200
|
+
try {
|
|
201
|
+
await mirrorTable({ baseId, runId, table, schemaId, counts: counts[table.name], budget, lease, now });
|
|
202
|
+
} catch (error) {
|
|
203
|
+
if (error?.code === 'archive_lease_lost') throw error;
|
|
204
|
+
counts[table.name].failed += 1;
|
|
205
|
+
logger.error('[airtableMirror] Table not mirrored', { runId, table: table.name, errorCode: error?.code || 'UNKNOWN' });
|
|
206
|
+
}
|
|
207
|
+
await renewLease(runId);
|
|
208
|
+
}
|
|
209
|
+
const total = (key) => Object.values(counts).reduce((sum, c) => sum + c[key], 0);
|
|
210
|
+
const errorCode = (total('failed') && 'records_failed') || (total('goneHeld') && 'mirror_mass_disappearance') || null;
|
|
211
|
+
const summary = { runId, mode: 'mirror', status: errorCode ? 'failed' : 'succeeded', tables: counts, errorCode };
|
|
212
|
+
const finished = await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, {
|
|
213
|
+
$set: { status: summary.status, finishedAt: new Date(), tables: counts, errorCode },
|
|
214
|
+
});
|
|
215
|
+
if (!finished?.matchedCount) throw archiveError('archive_lease_lost');
|
|
216
|
+
logger.info('[airtableMirror] Run finished', summary);
|
|
217
|
+
return summary;
|
|
218
|
+
} catch (error) {
|
|
219
|
+
const errorCode = [error?.code, error?.error].find((code) => code && typeof code === 'string') || 'UNKNOWN';
|
|
220
|
+
await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, errorCode } });
|
|
221
|
+
logger.error('[airtableMirror] Run failed', { runId, errorCode });
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
module.exports = {
|
|
227
|
+
runMirror,
|
|
228
|
+
};
|
|
@@ -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
|
};
|