@peopl-health/nexus 5.73.0-dev.15251 → 5.73.0-dev.15253
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/config/airtableArchiveConfig.js +83 -28
- package/lib/helpers/airtableArchiveHelper.js +4 -0
- package/lib/models/airtableArchiveModel.js +16 -0
- package/lib/services/airtableArchivePlanService.js +62 -22
- package/lib/services/airtableArchiveService.js +65 -42
- package/lib/services/airtableService.js +1 -1
- package/package.json +1 -1
|
@@ -1,45 +1,99 @@
|
|
|
1
|
+
// Tables and fields are configured by Airtable id, so renaming them in Airtable cannot change what the archive does.
|
|
1
2
|
const ARCHIVE_TABLES = Object.freeze({
|
|
2
|
-
QUESTIONNAIRES: '
|
|
3
|
-
TRIAGES: '
|
|
4
|
-
SYMPTOMS: '
|
|
5
|
-
ADDITIONAL_ANSWERS: '
|
|
6
|
-
RECOMMENDATIONS: '
|
|
7
|
-
RESOLUTIONS: '
|
|
3
|
+
QUESTIONNAIRES: 'tbl5VjUMEdPQJ8oR6',
|
|
4
|
+
TRIAGES: 'tblC1fwHpWEfDBovf',
|
|
5
|
+
SYMPTOMS: 'tblNHfup9y1s77vdN',
|
|
6
|
+
ADDITIONAL_ANSWERS: 'tblFeHmI5JDACsOBd',
|
|
7
|
+
RECOMMENDATIONS: 'tblwDv3v5wcFKnPrE',
|
|
8
|
+
RESOLUTIONS: 'tbly4e90Xcp19a6VA',
|
|
8
9
|
});
|
|
9
10
|
|
|
11
|
+
const ARCHIVE_FIELDS = Object.freeze({
|
|
12
|
+
QUESTIONNAIRE: Object.freeze({
|
|
13
|
+
TRIAGE: 'fldFIcRnYXr6HbGEr',
|
|
14
|
+
ADDITIONAL_ANSWERS: 'fldCD4MvSjJ6GGYeQ',
|
|
15
|
+
PREVIOUS_TRIAGE: 'fldekZghYN1Zv7U5j',
|
|
16
|
+
PREVIOUS_SYMPTOMS: 'flduGxzHejCy7FfTr',
|
|
17
|
+
PHYSICIAN_REPORT: 'fld3w7Zfuc8BChDOL',
|
|
18
|
+
EXTRACTION_ANALYSIS: 'fldcrm4xZuG2hHzW2',
|
|
19
|
+
FIRST_MESSAGE: 'fld3GmmdKLCnJuKzL',
|
|
20
|
+
PATIENT: 'fldMIxWgaGiF7IvYr',
|
|
21
|
+
WHATSAPP: 'fld5XXqDfLgT8JQS4',
|
|
22
|
+
CREATED: 'fld1rLI32ITUtgfdJ',
|
|
23
|
+
APPROVED: 'fldTgcHGvR6Dy64US',
|
|
24
|
+
}),
|
|
25
|
+
TRIAGE: Object.freeze({
|
|
26
|
+
QUESTIONNAIRE: 'fldPSXnnwABCVlJYa',
|
|
27
|
+
SYMPTOMS: 'fld6mNLRqEjNqh6lc',
|
|
28
|
+
RECOMMENDATIONS: 'fldfIkWJNHmbzYWyk',
|
|
29
|
+
NEXT_QUESTIONNAIRE: 'fldjFFoiNFQfEJaTd',
|
|
30
|
+
PAIN_FOLLOW_UP: 'fldkWqBcTY8Y4nB3r',
|
|
31
|
+
PATIENT: 'fld13AeMleGR4Ar2S',
|
|
32
|
+
WHATSAPP: 'fldSPX9JIe1vS8fFQ',
|
|
33
|
+
}),
|
|
34
|
+
SYMPTOM: Object.freeze({
|
|
35
|
+
TRIAGE: 'fldmam6VjxqsDhIOc',
|
|
36
|
+
RECOMMENDATIONS: 'fldKWnRpBOw1bDgvE',
|
|
37
|
+
NEXT_QUESTIONNAIRE: 'fldRgZqXn4W5zYxIV',
|
|
38
|
+
PHYSICIAN_REPORT: 'fldE1RJpWMq9J7kye',
|
|
39
|
+
PATIENT: 'fld1HwByMBq3sPLf3',
|
|
40
|
+
WHATSAPP: 'fldN5yrbmRQlt35II',
|
|
41
|
+
}),
|
|
42
|
+
ADDITIONAL_ANSWER: Object.freeze({ QUESTIONNAIRE: 'fldWeXx3CalMGphYb' }),
|
|
43
|
+
RECOMMENDATION: Object.freeze({
|
|
44
|
+
TRIAGE: 'fldgY1c0T9MJhxtno',
|
|
45
|
+
SYMPTOMS: 'fldPnsR2JgEOWbdKi',
|
|
46
|
+
RESOLUTIONS: 'fld3vY8ATExN85r9U',
|
|
47
|
+
}),
|
|
48
|
+
RESOLUTION: Object.freeze({ RECOMMENDATION: 'fldOotQhruyC1tPuW' }),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
const TABLE = ARCHIVE_TABLES;
|
|
52
|
+
const FIELD = ARCHIVE_FIELDS;
|
|
53
|
+
|
|
10
54
|
// Links inside one triage group: their records are archived together or not at all.
|
|
11
55
|
const GROUP_LINKS = Object.freeze({
|
|
12
|
-
[
|
|
13
|
-
[
|
|
14
|
-
[
|
|
15
|
-
[
|
|
16
|
-
[
|
|
17
|
-
[
|
|
56
|
+
[TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.TRIAGE, FIELD.QUESTIONNAIRE.ADDITIONAL_ANSWERS],
|
|
57
|
+
[TABLE.TRIAGES]: [FIELD.TRIAGE.QUESTIONNAIRE, FIELD.TRIAGE.SYMPTOMS, FIELD.TRIAGE.RECOMMENDATIONS],
|
|
58
|
+
[TABLE.SYMPTOMS]: [FIELD.SYMPTOM.TRIAGE, FIELD.SYMPTOM.RECOMMENDATIONS],
|
|
59
|
+
[TABLE.ADDITIONAL_ANSWERS]: [FIELD.ADDITIONAL_ANSWER.QUESTIONNAIRE],
|
|
60
|
+
[TABLE.RECOMMENDATIONS]: [FIELD.RECOMMENDATION.TRIAGE, FIELD.RECOMMENDATION.SYMPTOMS, FIELD.RECOMMENDATION.RESOLUTIONS],
|
|
61
|
+
[TABLE.RESOLUTIONS]: [FIELD.RESOLUTION.RECOMMENDATION],
|
|
18
62
|
});
|
|
19
63
|
|
|
20
64
|
// Links from an older group to the newer questionnaire generated from it.
|
|
21
65
|
const CARRY_OVER_LINKS = Object.freeze({
|
|
22
|
-
[
|
|
23
|
-
[
|
|
66
|
+
[TABLE.TRIAGES]: [FIELD.TRIAGE.NEXT_QUESTIONNAIRE],
|
|
67
|
+
[TABLE.SYMPTOMS]: [FIELD.SYMPTOM.NEXT_QUESTIONNAIRE],
|
|
24
68
|
});
|
|
25
69
|
|
|
26
70
|
// Questionnaire links back to the group it continues: they keep a group only when they reach outside the scan.
|
|
27
71
|
const BACKWARD_LINKS = Object.freeze({
|
|
28
|
-
[
|
|
72
|
+
[TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.PREVIOUS_TRIAGE, FIELD.QUESTIONNAIRE.PREVIOUS_SYMPTOMS],
|
|
29
73
|
});
|
|
30
74
|
|
|
31
75
|
// Links to non-catalog tables that are never archived: a linked group stays in Airtable.
|
|
32
76
|
const EXTERNAL_LINKS = Object.freeze({
|
|
33
|
-
[
|
|
34
|
-
[
|
|
35
|
-
[
|
|
77
|
+
[TABLE.QUESTIONNAIRES]: [FIELD.QUESTIONNAIRE.PHYSICIAN_REPORT, FIELD.QUESTIONNAIRE.EXTRACTION_ANALYSIS, FIELD.QUESTIONNAIRE.FIRST_MESSAGE],
|
|
78
|
+
[TABLE.TRIAGES]: [FIELD.TRIAGE.PAIN_FOLLOW_UP],
|
|
79
|
+
[TABLE.SYMPTOMS]: [FIELD.SYMPTOM.PHYSICIAN_REPORT],
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
const PATIENT_FIELDS = Object.freeze({
|
|
83
|
+
[TABLE.QUESTIONNAIRES]: FIELD.QUESTIONNAIRE.PATIENT,
|
|
84
|
+
[TABLE.TRIAGES]: FIELD.TRIAGE.PATIENT,
|
|
85
|
+
[TABLE.SYMPTOMS]: FIELD.SYMPTOM.PATIENT,
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
const WHATSAPP_FIELDS = Object.freeze({
|
|
89
|
+
[TABLE.QUESTIONNAIRES]: FIELD.QUESTIONNAIRE.WHATSAPP,
|
|
90
|
+
[TABLE.TRIAGES]: FIELD.TRIAGE.WHATSAPP,
|
|
91
|
+
[TABLE.SYMPTOMS]: FIELD.SYMPTOM.WHATSAPP,
|
|
36
92
|
});
|
|
37
93
|
|
|
38
|
-
const
|
|
39
|
-
const
|
|
40
|
-
const
|
|
41
|
-
const QUESTIONNAIRE_APPROVED_FIELD = 'approved';
|
|
42
|
-
const QUESTIONNAIRE_CREATED_FIELD = 'created';
|
|
94
|
+
const LINK_FIELD_TYPES = Object.freeze(['multipleRecordLinks']);
|
|
95
|
+
const CHECKBOX_FIELD_TYPES = Object.freeze(['checkbox']);
|
|
96
|
+
const DATE_FIELD_TYPES = Object.freeze(['dateTime', 'date']);
|
|
43
97
|
const FIRST_MONTH_DAYS = 30;
|
|
44
98
|
|
|
45
99
|
const KEEP_REASONS = Object.freeze({
|
|
@@ -68,6 +122,7 @@ const ATTACHMENT_DOWNLOAD_TIMEOUT_MS = 30000;
|
|
|
68
122
|
|
|
69
123
|
module.exports = {
|
|
70
124
|
ARCHIVE_TABLES,
|
|
125
|
+
ARCHIVE_FIELDS,
|
|
71
126
|
MIN_ARCHIVE_AGE_DAYS,
|
|
72
127
|
ARCHIVE_BATCH_SIZE,
|
|
73
128
|
ARCHIVE_LEASE_MS,
|
|
@@ -77,11 +132,11 @@ module.exports = {
|
|
|
77
132
|
CARRY_OVER_LINKS,
|
|
78
133
|
BACKWARD_LINKS,
|
|
79
134
|
EXTERNAL_LINKS,
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
135
|
+
PATIENT_FIELDS,
|
|
136
|
+
WHATSAPP_FIELDS,
|
|
137
|
+
LINK_FIELD_TYPES,
|
|
138
|
+
CHECKBOX_FIELD_TYPES,
|
|
139
|
+
DATE_FIELD_TYPES,
|
|
85
140
|
FIRST_MONTH_DAYS,
|
|
86
141
|
KEEP_REASONS,
|
|
87
142
|
};
|
|
@@ -24,6 +24,9 @@ const hashFields = (fields, skip = new Set()) => crypto.createHash('sha256')
|
|
|
24
24
|
.update(stableStringify(Object.fromEntries(Object.entries(fields).filter(([name]) => !skip.has(name)))))
|
|
25
25
|
.digest('hex');
|
|
26
26
|
|
|
27
|
+
// Same schema snapshot, same id: a record points at the snapshot that names its fields.
|
|
28
|
+
const schemaSnapshotId = (baseId, snapshot) => `${baseId}:${crypto.createHash('sha256').update(stableStringify(snapshot)).digest('hex').slice(0, 24)}`;
|
|
29
|
+
|
|
27
30
|
// Same shape as airtableService.getRecordByFilter(..., withRecordId = true), flagged as archived.
|
|
28
31
|
const toAirtableRow = (doc) => ({ ...doc.fields, _recordId: doc.recordId, _createdTime: new Date(doc.createdTime).toISOString(), _archived: true });
|
|
29
32
|
|
|
@@ -36,6 +39,7 @@ function mergeArchivedRows(liveRows = [], archivedRows = []) {
|
|
|
36
39
|
module.exports = {
|
|
37
40
|
normalizeFields,
|
|
38
41
|
hashFields,
|
|
42
|
+
schemaSnapshotId,
|
|
39
43
|
toAirtableRow,
|
|
40
44
|
mergeArchivedRows,
|
|
41
45
|
};
|
|
@@ -18,6 +18,7 @@ const archivedAttachmentSchema = new mongoose.Schema({
|
|
|
18
18
|
const airtableArchiveRecordSchema = new mongoose.Schema({
|
|
19
19
|
_id: { type: String, required: true },
|
|
20
20
|
baseId: { type: String, required: true },
|
|
21
|
+
tableId: { type: String, required: true },
|
|
21
22
|
tableName: { type: String, required: true },
|
|
22
23
|
recordId: { type: String, required: true },
|
|
23
24
|
createdTime: { type: Date, required: true },
|
|
@@ -30,6 +31,8 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
|
|
|
30
31
|
whatsappId: { type: String, default: null },
|
|
31
32
|
},
|
|
32
33
|
groupId: { type: String, required: true },
|
|
34
|
+
// The schema snapshot whose field names key `fields`, so a later rename can be mapped back by field id.
|
|
35
|
+
schemaId: { type: String, required: true },
|
|
33
36
|
attachments: { type: [archivedAttachmentSchema], default: [] },
|
|
34
37
|
runId: { type: String, required: true },
|
|
35
38
|
archivedAt: { type: Date, required: true },
|
|
@@ -72,6 +75,13 @@ airtableArchiveRunSchema.index({ runId: 1 }, { unique: true });
|
|
|
72
75
|
// At most one running run per base: a second run fails to insert instead of racing the first.
|
|
73
76
|
airtableArchiveRunSchema.index({ baseId: 1 }, { unique: true, partialFilterExpression: { status: 'running' } });
|
|
74
77
|
|
|
78
|
+
const airtableArchiveSchemaSchema = new mongoose.Schema({
|
|
79
|
+
_id: { type: String, required: true },
|
|
80
|
+
baseId: { type: String, required: true },
|
|
81
|
+
tables: { type: mongoose.Schema.Types.Mixed, required: true },
|
|
82
|
+
capturedAt: { type: Date, required: true },
|
|
83
|
+
}, { collection: 'airtable_archive_schemas', minimize: false, versionKey: false });
|
|
84
|
+
|
|
75
85
|
const getDatabase = (modelName) => {
|
|
76
86
|
const dbName = getModelDatabase(modelName);
|
|
77
87
|
return dbName ? getDb(dbName) : mongoose;
|
|
@@ -87,6 +97,11 @@ const getAirtableArchiveRun = () => {
|
|
|
87
97
|
return db.models.AirtableArchiveRun || db.model('AirtableArchiveRun', airtableArchiveRunSchema);
|
|
88
98
|
};
|
|
89
99
|
|
|
100
|
+
const getAirtableArchiveSchema = () => {
|
|
101
|
+
const db = getDatabase('AirtableArchiveSchema');
|
|
102
|
+
return db.models.AirtableArchiveSchema || db.model('AirtableArchiveSchema', airtableArchiveSchemaSchema);
|
|
103
|
+
};
|
|
104
|
+
|
|
90
105
|
const archiveRecordId = (baseId, recordId) => `${baseId}:${recordId}`;
|
|
91
106
|
|
|
92
107
|
module.exports = {
|
|
@@ -95,5 +110,6 @@ module.exports = {
|
|
|
95
110
|
airtableArchiveRecordSchema,
|
|
96
111
|
getAirtableArchiveRecord,
|
|
97
112
|
getAirtableArchiveRun,
|
|
113
|
+
getAirtableArchiveSchema,
|
|
98
114
|
archiveRecordId,
|
|
99
115
|
};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
const crypto = require('crypto');
|
|
2
2
|
|
|
3
3
|
const {
|
|
4
|
-
ARCHIVE_TABLES, GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS,
|
|
5
|
-
|
|
4
|
+
ARCHIVE_TABLES, ARCHIVE_FIELDS, GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS, PATIENT_FIELDS, WHATSAPP_FIELDS,
|
|
5
|
+
COMPUTED_FIELD_TYPES, LINK_FIELD_TYPES, CHECKBOX_FIELD_TYPES, DATE_FIELD_TYPES, FIRST_MONTH_DAYS, KEEP_REASONS,
|
|
6
6
|
} = require('../config/airtableArchiveConfig');
|
|
7
7
|
|
|
8
8
|
const linkedIds = (record, fieldNames = []) => fieldNames.flatMap((name) => {
|
|
@@ -35,14 +35,12 @@ function createUnionFind(ids) {
|
|
|
35
35
|
|
|
36
36
|
const groupIdOf = (recordIds) => crypto.createHash('sha256').update([...recordIds].sort().join(',')).digest('hex').slice(0, 24);
|
|
37
37
|
|
|
38
|
-
// The patient rollups read the questionnaire's own `created` date, which can differ from the record's createdTime.
|
|
39
|
-
const createdMs = (entry) => Date.parse(entry.record.fields?.[QUESTIONNAIRE_CREATED_FIELD] || entry.record.createdTime);
|
|
40
38
|
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
41
39
|
|
|
42
|
-
function oldestAndNewestByPatient(entries) {
|
|
40
|
+
function oldestAndNewestByPatient(entries, patientField, createdMs) {
|
|
43
41
|
const byPatient = new Map();
|
|
44
42
|
for (const entry of entries) {
|
|
45
|
-
const patientId = firstString(entry.record.fields?.[
|
|
43
|
+
const patientId = firstString(entry.record.fields?.[patientField]);
|
|
46
44
|
if (!patientId) continue;
|
|
47
45
|
const current = byPatient.get(patientId);
|
|
48
46
|
if (!current) {
|
|
@@ -55,8 +53,49 @@ function oldestAndNewestByPatient(entries) {
|
|
|
55
53
|
return byPatient;
|
|
56
54
|
}
|
|
57
55
|
|
|
58
|
-
//
|
|
59
|
-
function
|
|
56
|
+
// Translates the configured table and field ids to their current names; `missing` lists every id the base no longer has as configured.
|
|
57
|
+
function resolveArchiveSchema(baseTables = []) {
|
|
58
|
+
const tablesById = new Map(baseTables.map((table) => [table.id, table]));
|
|
59
|
+
const missing = [];
|
|
60
|
+
const tableName = (tableId) => {
|
|
61
|
+
if (!tablesById.has(tableId)) missing.push(tableId);
|
|
62
|
+
return tablesById.get(tableId)?.name;
|
|
63
|
+
};
|
|
64
|
+
const fieldName = (tableId, fieldId, types) => {
|
|
65
|
+
const field = tablesById.get(tableId)?.fields.find((f) => f.id === fieldId);
|
|
66
|
+
if (!field || (types && !types.includes(field.type))) missing.push(fieldId);
|
|
67
|
+
return field?.name;
|
|
68
|
+
};
|
|
69
|
+
const byTableName = (map, types) => Object.fromEntries(Object.entries(map).map(([tableId, value]) => [
|
|
70
|
+
tableName(tableId), Array.isArray(value) ? value.map((fieldId) => fieldName(tableId, fieldId, types)) : fieldName(tableId, value, types),
|
|
71
|
+
]));
|
|
72
|
+
|
|
73
|
+
const tables = Object.fromEntries(Object.entries(ARCHIVE_TABLES).map(([key, tableId]) => [key, tableName(tableId)]));
|
|
74
|
+
const archived = Object.values(ARCHIVE_TABLES).filter((tableId) => tablesById.has(tableId)).map((tableId) => tablesById.get(tableId));
|
|
75
|
+
const schema = {
|
|
76
|
+
tables,
|
|
77
|
+
tableIds: Object.fromEntries(archived.map((table) => [table.name, table.id])),
|
|
78
|
+
groupLinks: byTableName(GROUP_LINKS, LINK_FIELD_TYPES),
|
|
79
|
+
carryOverLinks: byTableName(CARRY_OVER_LINKS, LINK_FIELD_TYPES),
|
|
80
|
+
backwardLinks: byTableName(BACKWARD_LINKS, LINK_FIELD_TYPES),
|
|
81
|
+
externalLinks: byTableName(EXTERNAL_LINKS, LINK_FIELD_TYPES),
|
|
82
|
+
patientFields: byTableName(PATIENT_FIELDS, LINK_FIELD_TYPES),
|
|
83
|
+
whatsappFields: byTableName(WHATSAPP_FIELDS),
|
|
84
|
+
questionnaireTriage: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.TRIAGE, LINK_FIELD_TYPES),
|
|
85
|
+
questionnaireApproved: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.APPROVED, CHECKBOX_FIELD_TYPES),
|
|
86
|
+
questionnaireCreated: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.CREATED, DATE_FIELD_TYPES),
|
|
87
|
+
computed: new Map(archived.map((table) => [table.name, new Set(table.fields.filter((f) => COMPUTED_FIELD_TYPES.includes(f.type)).map((f) => f.name))])),
|
|
88
|
+
snapshot: archived.map(({ id, name, fields }) => ({ id, name, fields: fields.map((f) => ({ id: f.id, name: f.name, type: f.type })).sort((a, b) => a.id.localeCompare(b.id)) })),
|
|
89
|
+
};
|
|
90
|
+
return { schema, missing: [...new Set(missing)] };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Splits records older than the cutoff into triage groups and returns the ones safe to archive; `schema` holds the current field names.
|
|
94
|
+
function planArchive({ recordsByTable, patientsWithRecent = {}, schema }) {
|
|
95
|
+
const { tables } = schema;
|
|
96
|
+
const patientOf = (entry) => firstString(entry.record.fields?.[schema.patientFields[entry.table]]);
|
|
97
|
+
// The patient rollups read the questionnaire's own `created` date, which can differ from the record's createdTime.
|
|
98
|
+
const createdMs = (entry) => Date.parse((entry.table === tables.QUESTIONNAIRES && entry.record.fields?.[schema.questionnaireCreated]) || entry.record.createdTime);
|
|
60
99
|
const entries = new Map();
|
|
61
100
|
for (const [table, records] of Object.entries(recordsByTable)) {
|
|
62
101
|
for (const record of records || []) entries.set(record.id, { table, record });
|
|
@@ -71,37 +110,37 @@ function planArchive({ recordsByTable, patientsWithRecent = {} }) {
|
|
|
71
110
|
|
|
72
111
|
const touchesNewer = [];
|
|
73
112
|
for (const [id, { table, record }] of entries) {
|
|
74
|
-
for (const linkedId of linkedIds(record,
|
|
113
|
+
for (const linkedId of linkedIds(record, schema.groupLinks[table])) {
|
|
75
114
|
if (entries.has(linkedId)) union(id, linkedId);
|
|
76
115
|
else touchesNewer.push(id);
|
|
77
116
|
}
|
|
78
117
|
}
|
|
79
118
|
for (const [id, { table, record }] of entries) {
|
|
80
|
-
if (linkedIds(record,
|
|
119
|
+
if (linkedIds(record, schema.backwardLinks[table]).some((linkedId) => !entries.has(linkedId))) touchesNewer.push(id);
|
|
81
120
|
}
|
|
82
121
|
touchesNewer.forEach((id) => markKeep(id, KEEP_REASONS.LINKS_NEWER));
|
|
83
122
|
for (const [id, { table, record }] of entries) {
|
|
84
|
-
if (linkedIds(record,
|
|
123
|
+
if (linkedIds(record, schema.externalLinks[table]).length) markKeep(id, KEEP_REASONS.LINKS_OUTSIDE);
|
|
85
124
|
}
|
|
86
125
|
|
|
87
126
|
const byTable = (table) => [...entries.values()].filter((entry) => entry.table === table);
|
|
88
|
-
const questionnaires = byTable(
|
|
127
|
+
const questionnaires = byTable(tables.QUESTIONNAIRES);
|
|
89
128
|
|
|
90
|
-
const questionnaireAnchors = oldestAndNewestByPatient(questionnaires);
|
|
129
|
+
const questionnaireAnchors = oldestAndNewestByPatient(questionnaires, schema.patientFields[tables.QUESTIONNAIRES], createdMs);
|
|
91
130
|
for (const [patientId, { oldest, newest }] of questionnaireAnchors) {
|
|
92
131
|
markKeep(oldest.record.id, KEEP_REASONS.FIRST_QUESTIONNAIRE);
|
|
93
|
-
if (!patientsWithRecent[
|
|
132
|
+
if (!patientsWithRecent[tables.QUESTIONNAIRES]?.has(patientId)) markKeep(newest.record.id, KEEP_REASONS.LATEST_QUESTIONNAIRE);
|
|
94
133
|
}
|
|
95
|
-
for (const [patientId, { oldest, newest }] of oldestAndNewestByPatient(byTable(
|
|
134
|
+
for (const [patientId, { oldest, newest }] of oldestAndNewestByPatient(byTable(tables.TRIAGES), schema.patientFields[tables.TRIAGES], createdMs)) {
|
|
96
135
|
markKeep(oldest.record.id, KEEP_REASONS.FIRST_TRIAGE);
|
|
97
|
-
if (!patientsWithRecent[
|
|
136
|
+
if (!patientsWithRecent[tables.TRIAGES]?.has(patientId)) markKeep(newest.record.id, KEEP_REASONS.LATEST_TRIAGE);
|
|
98
137
|
}
|
|
99
138
|
for (const entry of questionnaires) {
|
|
100
|
-
const anchor = questionnaireAnchors.get(
|
|
139
|
+
const anchor = questionnaireAnchors.get(patientOf(entry));
|
|
101
140
|
if (anchor && createdMs(entry) - createdMs(anchor.oldest) < FIRST_MONTH_DAYS * DAY_MS) markKeep(entry.record.id, KEEP_REASONS.FIRST_MONTH);
|
|
102
141
|
}
|
|
103
142
|
for (const { record } of questionnaires) {
|
|
104
|
-
if (record.fields?.[
|
|
143
|
+
if (record.fields?.[schema.questionnaireApproved] !== true && !linkedIds(record, [schema.questionnaireTriage]).length) {
|
|
105
144
|
markKeep(record.id, KEEP_REASONS.UNAPPROVED_QUESTIONNAIRE);
|
|
106
145
|
}
|
|
107
146
|
}
|
|
@@ -109,7 +148,7 @@ function planArchive({ recordsByTable, patientsWithRecent = {} }) {
|
|
|
109
148
|
// One hop only: a kept group protects the group it was generated from, never that group's own predecessor.
|
|
110
149
|
const keptBeforeCarryOver = new Set(keepReasons.keys());
|
|
111
150
|
for (const [id, { table, record }] of entries) {
|
|
112
|
-
for (const linkedId of linkedIds(record,
|
|
151
|
+
for (const linkedId of linkedIds(record, schema.carryOverLinks[table])) {
|
|
113
152
|
if (!entries.has(linkedId)) markKeep(id, KEEP_REASONS.CARRIED_INTO_NEWER);
|
|
114
153
|
else if (keptBeforeCarryOver.has(find(linkedId)) && find(linkedId) !== find(id)) markKeep(id, KEEP_REASONS.CARRIED_INTO_KEPT);
|
|
115
154
|
}
|
|
@@ -130,12 +169,12 @@ function planArchive({ recordsByTable, patientsWithRecent = {} }) {
|
|
|
130
169
|
keptByReason[reason] = (keptByReason[reason] || 0) + 1;
|
|
131
170
|
continue;
|
|
132
171
|
}
|
|
133
|
-
const patientEntry = records.map(({ id }) => entries.get(id)
|
|
172
|
+
const patientEntry = records.map(({ id }) => entries.get(id)).find(patientOf);
|
|
134
173
|
eligible.push({
|
|
135
174
|
groupId: groupIdOf(records.map(({ id }) => id)),
|
|
136
175
|
patient: {
|
|
137
|
-
recordId:
|
|
138
|
-
whatsappId: firstString(patientEntry?.fields?.[
|
|
176
|
+
recordId: patientEntry ? patientOf(patientEntry) : null,
|
|
177
|
+
whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
|
|
139
178
|
},
|
|
140
179
|
records,
|
|
141
180
|
});
|
|
@@ -145,5 +184,6 @@ function planArchive({ recordsByTable, patientsWithRecent = {} }) {
|
|
|
145
184
|
}
|
|
146
185
|
|
|
147
186
|
module.exports = {
|
|
187
|
+
resolveArchiveSchema,
|
|
148
188
|
planArchive,
|
|
149
189
|
};
|
|
@@ -4,63 +4,81 @@ const { v4: uuidv4 } = require('uuid');
|
|
|
4
4
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
5
5
|
const { uploadBufferToS3 } = require('../config/awsConfig');
|
|
6
6
|
const {
|
|
7
|
-
ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
|
|
7
|
+
ARCHIVE_TABLES, MIN_ARCHIVE_AGE_DAYS, ARCHIVE_BATCH_SIZE, ARCHIVE_LEASE_MS, ATTACHMENT_DOWNLOAD_TIMEOUT_MS,
|
|
8
8
|
} = require('../config/airtableArchiveConfig');
|
|
9
9
|
const { logger } = require('../utils/logger');
|
|
10
10
|
const { stableStringify } = require('../utils/jsonUtils');
|
|
11
11
|
const { daysSince } = require('../utils/dateUtils');
|
|
12
12
|
const {
|
|
13
|
-
ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRecord, getAirtableArchiveRun, archiveRecordId,
|
|
13
|
+
ARCHIVE_RUN_MODES, ARCHIVE_SCHEMA_VERSION, getAirtableArchiveRecord, getAirtableArchiveRun, getAirtableArchiveSchema, archiveRecordId,
|
|
14
14
|
} = require('../models/airtableArchiveModel');
|
|
15
15
|
const { createdBefore, createdSince } = require('../helpers/airtableFormulaHelper');
|
|
16
|
-
const { normalizeFields, hashFields } = require('../helpers/airtableArchiveHelper');
|
|
16
|
+
const { normalizeFields, hashFields, schemaSnapshotId } = require('../helpers/airtableArchiveHelper');
|
|
17
17
|
|
|
18
18
|
const { getRecordsWithMetadata, getBaseSchema } = require('./airtableService');
|
|
19
|
-
const { planArchive } = require('./airtableArchivePlanService');
|
|
19
|
+
const { planArchive, resolveArchiveSchema } = require('./airtableArchivePlanService');
|
|
20
20
|
|
|
21
21
|
const DUPLICATE_KEY_ERROR = 11000;
|
|
22
22
|
const WRITE_CONCERN = { w: 'majority', j: true };
|
|
23
23
|
|
|
24
24
|
const archiveError = (code) => Object.assign(new Error(code), { code });
|
|
25
25
|
|
|
26
|
-
async function
|
|
26
|
+
async function readArchiveSchema(baseId) {
|
|
27
27
|
let tables;
|
|
28
28
|
try {
|
|
29
29
|
tables = await getBaseSchema(baseId);
|
|
30
30
|
} catch (error) {
|
|
31
31
|
throw Object.assign(archiveError('archive_schema_unreadable'), { cause: error });
|
|
32
32
|
}
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
33
|
+
const { schema, missing } = resolveArchiveSchema(tables || []);
|
|
34
|
+
if (missing.length) {
|
|
35
|
+
logger.error('[airtableArchive] Configured tables or fields are missing or changed type in the base schema', { missing });
|
|
36
|
+
throw archiveError('archive_schema_mismatch');
|
|
37
|
+
}
|
|
38
|
+
return schema;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Records come back keyed by name, so a rename during the scans would hide links from the planner.
|
|
42
|
+
async function assertSchemaUnchanged(baseId, schema) {
|
|
43
|
+
const current = await readArchiveSchema(baseId);
|
|
44
|
+
const changed = schema.snapshot.filter((table, i) => stableStringify(table) !== stableStringify(current.snapshot[i])).map((table) => table.id);
|
|
45
|
+
if (changed.length) {
|
|
46
|
+
logger.error('[airtableArchive] Base schema changed during the scan', { baseId, tables: changed });
|
|
47
|
+
throw archiveError('archive_schema_mismatch');
|
|
41
48
|
}
|
|
42
|
-
return computed;
|
|
43
49
|
}
|
|
44
50
|
|
|
45
|
-
async function scanOldRecords(baseId, cutoff, runId) {
|
|
51
|
+
async function scanOldRecords(baseId, cutoff, runId, schema) {
|
|
46
52
|
const recordsByTable = {};
|
|
47
|
-
for (const
|
|
48
|
-
recordsByTable[
|
|
53
|
+
for (const [key, tableId] of Object.entries(ARCHIVE_TABLES)) {
|
|
54
|
+
recordsByTable[schema.tables[key]] = await getRecordsWithMetadata(baseId, tableId, createdBefore(cutoff));
|
|
49
55
|
await renewLease(runId);
|
|
50
56
|
}
|
|
51
57
|
return recordsByTable;
|
|
52
58
|
}
|
|
53
59
|
|
|
54
|
-
async function scanPatientsWithRecent(baseId, cutoff, runId) {
|
|
60
|
+
async function scanPatientsWithRecent(baseId, cutoff, runId, schema) {
|
|
55
61
|
const patientsWithRecent = {};
|
|
56
|
-
for (const
|
|
57
|
-
const
|
|
58
|
-
|
|
62
|
+
for (const key of ['QUESTIONNAIRES', 'TRIAGES']) {
|
|
63
|
+
const table = schema.tables[key];
|
|
64
|
+
const patientField = schema.patientFields[table];
|
|
65
|
+
const records = await getRecordsWithMetadata(baseId, ARCHIVE_TABLES[key], createdSince(cutoff), [patientField]);
|
|
66
|
+
patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields?.[patientField] || []));
|
|
59
67
|
await renewLease(runId);
|
|
60
68
|
}
|
|
61
69
|
return patientsWithRecent;
|
|
62
70
|
}
|
|
63
71
|
|
|
72
|
+
async function storeSchemaSnapshot(baseId, snapshot, now) {
|
|
73
|
+
const _id = schemaSnapshotId(baseId, snapshot);
|
|
74
|
+
await getAirtableArchiveSchema().updateOne(
|
|
75
|
+
{ _id },
|
|
76
|
+
{ $setOnInsert: { baseId, tables: snapshot, capturedAt: now } },
|
|
77
|
+
{ upsert: true, writeConcern: WRITE_CONCERN },
|
|
78
|
+
);
|
|
79
|
+
return _id;
|
|
80
|
+
}
|
|
81
|
+
|
|
64
82
|
let runIndexesReady = null;
|
|
65
83
|
|
|
66
84
|
// The single-flight guarantee is the partial unique index, so no run starts before it exists.
|
|
@@ -100,7 +118,7 @@ async function renewLease(runId) {
|
|
|
100
118
|
if (!result?.matchedCount) throw archiveError('archive_lease_lost');
|
|
101
119
|
}
|
|
102
120
|
|
|
103
|
-
async function rehostAttachments({ baseId,
|
|
121
|
+
async function rehostAttachments({ baseId, tableId, recordId, attachments, alreadyHosted }) {
|
|
104
122
|
if (!attachments.length) return [];
|
|
105
123
|
const bucket = runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET');
|
|
106
124
|
if (!bucket) throw archiveError('archive_bucket_missing');
|
|
@@ -111,7 +129,7 @@ async function rehostAttachments({ baseId, tableName, recordId, attachments, alr
|
|
|
111
129
|
hosted.push(previous);
|
|
112
130
|
continue;
|
|
113
131
|
}
|
|
114
|
-
const s3Key = `airtable-archive/${baseId}/${
|
|
132
|
+
const s3Key = `airtable-archive/${baseId}/${tableId}/${recordId}/${item.id}`;
|
|
115
133
|
const response = await axios.get(item.url, { responseType: 'arraybuffer', timeout: ATTACHMENT_DOWNLOAD_TIMEOUT_MS });
|
|
116
134
|
const bytes = response.data?.byteLength;
|
|
117
135
|
if (typeof item.size === 'number' ? bytes !== item.size : !bytes) throw archiveError('attachment_size_mismatch');
|
|
@@ -141,12 +159,13 @@ async function writeOps(ArchiveRecord, ops, runId) {
|
|
|
141
159
|
}
|
|
142
160
|
}
|
|
143
161
|
|
|
144
|
-
|
|
162
|
+
// Where readers find a record: a renamed table or a regrouped record is rewritten even when its fields did not change.
|
|
163
|
+
const placementOf = (tableName, groupId, patient, createdTime) => stableStringify({ tableName, groupId, patient, createdTime: new Date(createdTime).getTime() });
|
|
145
164
|
|
|
146
|
-
async function copyBatch({ baseId, runId, batch,
|
|
165
|
+
async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now }) {
|
|
147
166
|
const ArchiveRecord = getAirtableArchiveRecord();
|
|
148
167
|
const ids = batch.map(({ record }) => archiveRecordId(baseId, record.id));
|
|
149
|
-
const existing = new Map((await ArchiveRecord.find({ _id: { $in: ids } }, { fields: 1, fieldsHash: 1, sourceHash: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 }).lean())
|
|
168
|
+
const existing = new Map((await ArchiveRecord.find({ _id: { $in: ids } }, { fields: 1, fieldsHash: 1, sourceHash: 1, tableId: 1, schemaId: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1, attachments: 1 }).lean())
|
|
150
169
|
.map((doc) => [doc._id, doc]));
|
|
151
170
|
|
|
152
171
|
const expected = new Map();
|
|
@@ -155,24 +174,25 @@ async function copyBatch({ baseId, runId, batch, computed, counts, now }) {
|
|
|
155
174
|
const _id = archiveRecordId(baseId, record.id);
|
|
156
175
|
const { normalized, attachments } = normalizeFields(record.fields);
|
|
157
176
|
const fieldsHash = hashFields(normalized);
|
|
158
|
-
const sourceHash = hashFields(normalized, computed.get(table));
|
|
159
|
-
const
|
|
177
|
+
const sourceHash = hashFields(normalized, schema.computed.get(table));
|
|
178
|
+
const tableId = schema.tableIds[table];
|
|
179
|
+
const placement = placementOf(table, group.groupId, group.patient, record.createdTime);
|
|
160
180
|
const previous = existing.get(_id);
|
|
161
|
-
const previousIntact = previous && hashFields(previous.fields) === previous.fieldsHash;
|
|
162
|
-
if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.groupId, previous.patient, previous.createdTime) === placement) {
|
|
181
|
+
const previousIntact = previous?.tableId && previous.schemaId && hashFields(previous.fields) === previous.fieldsHash;
|
|
182
|
+
if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.tableName, previous.groupId, previous.patient, previous.createdTime) === placement) {
|
|
163
183
|
expected.set(_id, { table, recordId: record.id, fieldsHash: previous.fieldsHash, placement });
|
|
164
184
|
continue;
|
|
165
185
|
}
|
|
166
186
|
try {
|
|
167
187
|
const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
|
|
168
|
-
const hosted = await rehostAttachments({ baseId,
|
|
188
|
+
const hosted = await rehostAttachments({ baseId, tableId, recordId: record.id, attachments, alreadyHosted });
|
|
169
189
|
ops.push({
|
|
170
190
|
updateOne: {
|
|
171
191
|
filter: { _id },
|
|
172
192
|
update: {
|
|
173
193
|
$set: {
|
|
174
|
-
baseId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
175
|
-
fields: normalized, fieldsHash, sourceHash, patient: group.patient, groupId: group.groupId, attachments: hosted,
|
|
194
|
+
baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
195
|
+
fields: normalized, fieldsHash, sourceHash, patient: group.patient, groupId: group.groupId, schemaId, attachments: hosted,
|
|
176
196
|
schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
177
197
|
},
|
|
178
198
|
$setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
|
|
@@ -192,11 +212,11 @@ async function copyBatch({ baseId, runId, batch, computed, counts, now }) {
|
|
|
192
212
|
|
|
193
213
|
if (ops.length) await writeOps(ArchiveRecord, ops, runId);
|
|
194
214
|
|
|
195
|
-
const stored = await ArchiveRecord.find({ _id: { $in: [...expected.keys()] } }, { fields: 1, groupId: 1, patient: 1, createdTime: 1 }).lean();
|
|
215
|
+
const stored = await ArchiveRecord.find({ _id: { $in: [...expected.keys()] } }, { fields: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1 }).lean();
|
|
196
216
|
const storedById = new Map(stored.map((doc) => [doc._id, doc]));
|
|
197
217
|
for (const [_id, { table, recordId, fieldsHash, placement }] of expected) {
|
|
198
218
|
const doc = storedById.get(_id);
|
|
199
|
-
if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
|
|
219
|
+
if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
|
|
200
220
|
else {
|
|
201
221
|
counts[table].failed += 1;
|
|
202
222
|
logger.error('[airtableArchive] Copy did not verify', { runId, table, recordId });
|
|
@@ -216,22 +236,25 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
|
|
|
216
236
|
validateRequest({ baseId, cutoff, mode, now });
|
|
217
237
|
const run = await acquireRun({ baseId, mode, cutoff, now });
|
|
218
238
|
const { runId } = run;
|
|
219
|
-
|
|
239
|
+
let counts = {};
|
|
220
240
|
|
|
221
241
|
try {
|
|
222
|
-
const
|
|
223
|
-
|
|
224
|
-
const
|
|
225
|
-
const
|
|
242
|
+
const schema = await readArchiveSchema(baseId);
|
|
243
|
+
counts = Object.fromEntries(Object.values(schema.tables).map((table) => [table, emptyCounts()]));
|
|
244
|
+
const recordsByTable = await scanOldRecords(baseId, cutoff, runId, schema);
|
|
245
|
+
const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, runId, schema);
|
|
246
|
+
await assertSchemaUnchanged(baseId, schema);
|
|
247
|
+
const plan = planArchive({ recordsByTable, patientsWithRecent, schema });
|
|
226
248
|
|
|
227
249
|
Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
|
|
228
250
|
const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
|
|
229
251
|
const work = plan.eligible.flatMap((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
|
|
230
252
|
work.forEach(({ table }) => { counts[table].eligible += 1; });
|
|
231
253
|
|
|
232
|
-
if (mode === 'copy') {
|
|
254
|
+
if (mode === 'copy' && work.length) {
|
|
255
|
+
const schemaId = await storeSchemaSnapshot(baseId, schema.snapshot, now);
|
|
233
256
|
for (let i = 0; i < work.length; i += ARCHIVE_BATCH_SIZE) {
|
|
234
|
-
await copyBatch({ baseId, runId, batch: work.slice(i, i + ARCHIVE_BATCH_SIZE),
|
|
257
|
+
await copyBatch({ baseId, runId, batch: work.slice(i, i + ARCHIVE_BATCH_SIZE), schema, schemaId, counts, now });
|
|
235
258
|
await renewLease(runId);
|
|
236
259
|
}
|
|
237
260
|
}
|
|
@@ -141,7 +141,7 @@ async function getRecordsWithMetadata(baseID, tableName, filter, fields) {
|
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
// Needs the schema.bases:read scope; returns [{ name, fields: [{ name, type }] }] per table.
|
|
144
|
+
// Needs the schema.bases:read scope; returns [{ id, name, fields: [{ id, name, type }] }] per table.
|
|
145
145
|
async function getBaseSchema(baseID) {
|
|
146
146
|
const apiKey = getApiKey();
|
|
147
147
|
if (!apiKey) throw new Error('Airtable not configured. Set AIRTABLE_API_KEY');
|