@peopl-health/nexus 5.73.0-dev.15250 → 5.73.0-dev.15252

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.
@@ -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: 'weekly_questionnaires',
3
- TRIAGES: 'triaje_symptoms',
4
- SYMPTOMS: 'symptoms',
5
- ADDITIONAL_ANSWERS: 'additional_answers',
6
- RECOMMENDATIONS: 'cluster_recommendations',
7
- RESOLUTIONS: 'cluster_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
- [ARCHIVE_TABLES.QUESTIONNAIRES]: ['triage_symptoms_id', 'additional_answers'],
13
- [ARCHIVE_TABLES.TRIAGES]: ['questionnaire_id', 'symptoms', 'cluster_recommendations'],
14
- [ARCHIVE_TABLES.SYMPTOMS]: ['triaje_id', 'cluster_recommendations'],
15
- [ARCHIVE_TABLES.ADDITIONAL_ANSWERS]: ['questionnaire_id'],
16
- [ARCHIVE_TABLES.RECOMMENDATIONS]: ['triaje_symptoms', 'symptoms', 'cluster_resolutions'],
17
- [ARCHIVE_TABLES.RESOLUTIONS]: ['cluster_recommendations'],
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
- [ARCHIVE_TABLES.TRIAGES]: ['weekly_questionnaires_prev'],
23
- [ARCHIVE_TABLES.SYMPTOMS]: ['weekly_questionnaires'],
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
- [ARCHIVE_TABLES.QUESTIONNAIRES]: ['prev_triaje', 'symptoms_ids_grade1'],
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
- [ARCHIVE_TABLES.QUESTIONNAIRES]: ['physician_report', 'extraction_analysis', 'weekly_first_message'],
34
- [ARCHIVE_TABLES.TRIAGES]: ['seguimiento_dolor'],
35
- [ARCHIVE_TABLES.SYMPTOMS]: ['physician_report'],
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 PATIENT_LINK_FIELD = 'patient_id';
39
- const PATIENT_WHATSAPP_FIELD = 'whatsapp_id';
40
- const QUESTIONNAIRE_TRIAGE_LINK = 'triage_symptoms_id';
41
- const QUESTIONNAIRE_APPROVED_FIELD = 'approved';
42
- const QUESTIONNAIRE_CREATED_FIELD = 'created';
94
+ const LINK_FIELD_TYPE = 'multipleRecordLinks';
95
+ const CHECKBOX_FIELD_TYPE = '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
- PATIENT_LINK_FIELD,
81
- PATIENT_WHATSAPP_FIELD,
82
- QUESTIONNAIRE_TRIAGE_LINK,
83
- QUESTIONNAIRE_APPROVED_FIELD,
84
- QUESTIONNAIRE_CREATED_FIELD,
135
+ PATIENT_FIELDS,
136
+ WHATSAPP_FIELDS,
137
+ LINK_FIELD_TYPE,
138
+ CHECKBOX_FIELD_TYPE,
139
+ DATE_FIELD_TYPES,
85
140
  FIRST_MONTH_DAYS,
86
141
  KEEP_REASONS,
87
142
  };
@@ -24,7 +24,22 @@ 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
+
30
+ // Same shape as airtableService.getRecordByFilter(..., withRecordId = true), flagged as archived.
31
+ const toAirtableRow = (doc) => ({ ...doc.fields, _recordId: doc.recordId, _createdTime: new Date(doc.createdTime).toISOString(), _archived: true });
32
+
33
+ // Union by record id, live row winning; archived rows are appended, so callers sort after merging.
34
+ function mergeArchivedRows(liveRows = [], archivedRows = []) {
35
+ const liveIds = new Set(liveRows.map((row) => row._recordId));
36
+ return [...liveRows, ...archivedRows.filter((row) => !liveIds.has(row._recordId))];
37
+ }
38
+
27
39
  module.exports = {
28
40
  normalizeFields,
29
41
  hashFields,
42
+ schemaSnapshotId,
43
+ toAirtableRow,
44
+ mergeArchivedRows,
30
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, PATIENT_LINK_FIELD, PATIENT_WHATSAPP_FIELD,
5
- QUESTIONNAIRE_TRIAGE_LINK, QUESTIONNAIRE_APPROVED_FIELD, QUESTIONNAIRE_CREATED_FIELD, FIRST_MONTH_DAYS, KEEP_REASONS,
4
+ ARCHIVE_TABLES, ARCHIVE_FIELDS, GROUP_LINKS, CARRY_OVER_LINKS, BACKWARD_LINKS, EXTERNAL_LINKS, PATIENT_FIELDS, WHATSAPP_FIELDS,
5
+ COMPUTED_FIELD_TYPES, LINK_FIELD_TYPE, CHECKBOX_FIELD_TYPE, 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?.[PATIENT_LINK_FIELD]);
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
- // Splits records older than the cutoff into triage groups and returns the ones safe to archive.
59
- function planArchive({ recordsByTable, patientsWithRecent = {} }) {
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, type) => {
65
+ const field = tablesById.get(tableId)?.fields.find((f) => f.id === fieldId);
66
+ if (!field || (type && ![].concat(type).includes(field.type))) missing.push(fieldId);
67
+ return field?.name;
68
+ };
69
+ const byTableName = (map, type) => Object.fromEntries(Object.entries(map).map(([tableId, value]) => [
70
+ tableName(tableId), Array.isArray(value) ? value.map((fieldId) => fieldName(tableId, fieldId, type)) : fieldName(tableId, value, type),
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_TYPE),
79
+ carryOverLinks: byTableName(CARRY_OVER_LINKS, LINK_FIELD_TYPE),
80
+ backwardLinks: byTableName(BACKWARD_LINKS, LINK_FIELD_TYPE),
81
+ externalLinks: byTableName(EXTERNAL_LINKS, LINK_FIELD_TYPE),
82
+ patientFields: byTableName(PATIENT_FIELDS, LINK_FIELD_TYPE),
83
+ whatsappFields: byTableName(WHATSAPP_FIELDS),
84
+ questionnaireTriage: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.TRIAGE, LINK_FIELD_TYPE),
85
+ questionnaireApproved: fieldName(ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_FIELDS.QUESTIONNAIRE.APPROVED, CHECKBOX_FIELD_TYPE),
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 })) })),
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, GROUP_LINKS[table])) {
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, BACKWARD_LINKS[table]).some((linkedId) => !entries.has(linkedId))) touchesNewer.push(id);
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, EXTERNAL_LINKS[table]).length) markKeep(id, KEEP_REASONS.LINKS_OUTSIDE);
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(ARCHIVE_TABLES.QUESTIONNAIRES);
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[ARCHIVE_TABLES.QUESTIONNAIRES]?.has(patientId)) markKeep(newest.record.id, KEEP_REASONS.LATEST_QUESTIONNAIRE);
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(ARCHIVE_TABLES.TRIAGES))) {
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[ARCHIVE_TABLES.TRIAGES]?.has(patientId)) markKeep(newest.record.id, KEEP_REASONS.LATEST_TRIAGE);
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(firstString(entry.record.fields?.[PATIENT_LINK_FIELD]));
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?.[QUESTIONNAIRE_APPROVED_FIELD] !== true && !linkedIds(record, [QUESTIONNAIRE_TRIAGE_LINK]).length) {
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, CARRY_OVER_LINKS[table])) {
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).record).find((r) => firstString(r.fields?.[PATIENT_LINK_FIELD]));
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: firstString(patientEntry?.fields?.[PATIENT_LINK_FIELD]),
138
- whatsappId: firstString(patientEntry?.fields?.[PATIENT_WHATSAPP_FIELD]),
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
  };
@@ -0,0 +1,25 @@
1
+ const { getAirtableArchiveRecord, archiveRecordId } = require('../models/airtableArchiveModel');
2
+ const { toAirtableRow } = require('../helpers/airtableArchiveHelper');
3
+
4
+ const READ_PROJECTION = { recordId: 1, createdTime: 1, fields: 1 };
5
+
6
+ async function findArchivedByPatient({ baseId, tableName, whatsappId, patientRecordId, since }) {
7
+ if (!whatsappId && !patientRecordId) return [];
8
+ const query = { baseId, tableName };
9
+ if (patientRecordId) query['patient.recordId'] = patientRecordId;
10
+ else query['patient.whatsappId'] = whatsappId;
11
+ if (since) query.createdTime = { $gte: since };
12
+ const docs = await getAirtableArchiveRecord().find(query, READ_PROJECTION).sort({ createdTime: -1 }).lean();
13
+ return docs.map(toAirtableRow);
14
+ }
15
+
16
+ async function findArchivedByRecordIds({ baseId, tableName, recordIds }) {
17
+ if (!recordIds?.length) return [];
18
+ const docs = await getAirtableArchiveRecord().find({ _id: { $in: recordIds.map((id) => archiveRecordId(baseId, id)) }, tableName }, READ_PROJECTION).lean();
19
+ return docs.map(toAirtableRow);
20
+ }
21
+
22
+ module.exports = {
23
+ findArchivedByPatient,
24
+ findArchivedByRecordIds,
25
+ };
@@ -4,63 +4,80 @@ 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, PATIENT_LINK_FIELD, COMPUTED_FIELD_TYPES,
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 readComputedFields(baseId) {
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 computed = new Map();
34
- for (const table of Object.values(ARCHIVE_TABLES)) {
35
- const schema = tables?.find((t) => t.name === table);
36
- if (!schema) {
37
- logger.error('[airtableArchive] Archived table missing from the base schema', { table });
38
- throw archiveError('archive_schema_unreadable');
39
- }
40
- computed.set(table, new Set(schema.fields.filter((f) => COMPUTED_FIELD_TYPES.includes(f.type)).map((f) => f.name)));
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
+ if (schemaSnapshotId(baseId, current.snapshot) !== schemaSnapshotId(baseId, schema.snapshot)) {
45
+ logger.error('[airtableArchive] Base schema changed during the scan', { baseId });
46
+ throw archiveError('archive_schema_mismatch');
41
47
  }
42
- return computed;
43
48
  }
44
49
 
45
- async function scanOldRecords(baseId, cutoff, runId) {
50
+ async function scanOldRecords(baseId, cutoff, runId, schema) {
46
51
  const recordsByTable = {};
47
- for (const table of Object.values(ARCHIVE_TABLES)) {
48
- recordsByTable[table] = await getRecordsWithMetadata(baseId, table, createdBefore(cutoff));
52
+ for (const [key, tableId] of Object.entries(ARCHIVE_TABLES)) {
53
+ recordsByTable[schema.tables[key]] = await getRecordsWithMetadata(baseId, tableId, createdBefore(cutoff));
49
54
  await renewLease(runId);
50
55
  }
51
56
  return recordsByTable;
52
57
  }
53
58
 
54
- async function scanPatientsWithRecent(baseId, cutoff, runId) {
59
+ async function scanPatientsWithRecent(baseId, cutoff, runId, schema) {
55
60
  const patientsWithRecent = {};
56
- for (const table of [ARCHIVE_TABLES.QUESTIONNAIRES, ARCHIVE_TABLES.TRIAGES]) {
57
- const records = await getRecordsWithMetadata(baseId, table, createdSince(cutoff), [PATIENT_LINK_FIELD]);
58
- patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields?.[PATIENT_LINK_FIELD] || []));
61
+ for (const key of ['QUESTIONNAIRES', 'TRIAGES']) {
62
+ const table = schema.tables[key];
63
+ const patientField = schema.patientFields[table];
64
+ const records = await getRecordsWithMetadata(baseId, ARCHIVE_TABLES[key], createdSince(cutoff), [patientField]);
65
+ patientsWithRecent[table] = new Set(records.flatMap((r) => r.fields?.[patientField] || []));
59
66
  await renewLease(runId);
60
67
  }
61
68
  return patientsWithRecent;
62
69
  }
63
70
 
71
+ async function storeSchemaSnapshot(baseId, snapshot, now) {
72
+ const _id = schemaSnapshotId(baseId, snapshot);
73
+ await getAirtableArchiveSchema().updateOne(
74
+ { _id },
75
+ { $setOnInsert: { baseId, tables: snapshot, capturedAt: now } },
76
+ { upsert: true, writeConcern: WRITE_CONCERN },
77
+ );
78
+ return _id;
79
+ }
80
+
64
81
  let runIndexesReady = null;
65
82
 
66
83
  // The single-flight guarantee is the partial unique index, so no run starts before it exists.
@@ -100,7 +117,7 @@ async function renewLease(runId) {
100
117
  if (!result?.matchedCount) throw archiveError('archive_lease_lost');
101
118
  }
102
119
 
103
- async function rehostAttachments({ baseId, tableName, recordId, attachments, alreadyHosted }) {
120
+ async function rehostAttachments({ baseId, tableId, recordId, attachments, alreadyHosted }) {
104
121
  if (!attachments.length) return [];
105
122
  const bucket = runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET');
106
123
  if (!bucket) throw archiveError('archive_bucket_missing');
@@ -111,7 +128,7 @@ async function rehostAttachments({ baseId, tableName, recordId, attachments, alr
111
128
  hosted.push(previous);
112
129
  continue;
113
130
  }
114
- const s3Key = `airtable-archive/${baseId}/${tableName}/${recordId}/${item.id}`;
131
+ const s3Key = `airtable-archive/${baseId}/${tableId}/${recordId}/${item.id}`;
115
132
  const response = await axios.get(item.url, { responseType: 'arraybuffer', timeout: ATTACHMENT_DOWNLOAD_TIMEOUT_MS });
116
133
  const bytes = response.data?.byteLength;
117
134
  if (typeof item.size === 'number' ? bytes !== item.size : !bytes) throw archiveError('attachment_size_mismatch');
@@ -141,12 +158,13 @@ async function writeOps(ArchiveRecord, ops, runId) {
141
158
  }
142
159
  }
143
160
 
144
- const placementOf = (groupId, patient, createdTime) => stableStringify({ groupId, patient, createdTime: new Date(createdTime).getTime() });
161
+ // Where readers find a record: a renamed table or a regrouped record is rewritten even when its fields did not change.
162
+ const placementOf = (tableName, groupId, patient, createdTime) => stableStringify({ tableName, groupId, patient, createdTime: new Date(createdTime).getTime() });
145
163
 
146
- async function copyBatch({ baseId, runId, batch, computed, counts, now }) {
164
+ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now }) {
147
165
  const ArchiveRecord = getAirtableArchiveRecord();
148
166
  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())
167
+ 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
168
  .map((doc) => [doc._id, doc]));
151
169
 
152
170
  const expected = new Map();
@@ -155,24 +173,25 @@ async function copyBatch({ baseId, runId, batch, computed, counts, now }) {
155
173
  const _id = archiveRecordId(baseId, record.id);
156
174
  const { normalized, attachments } = normalizeFields(record.fields);
157
175
  const fieldsHash = hashFields(normalized);
158
- const sourceHash = hashFields(normalized, computed.get(table));
159
- const placement = placementOf(group.groupId, group.patient, record.createdTime);
176
+ const sourceHash = hashFields(normalized, schema.computed.get(table));
177
+ const tableId = schema.tableIds[table];
178
+ const placement = placementOf(table, group.groupId, group.patient, record.createdTime);
160
179
  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) {
180
+ const previousIntact = previous?.tableId && previous.schemaId && hashFields(previous.fields) === previous.fieldsHash;
181
+ if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.tableName, previous.groupId, previous.patient, previous.createdTime) === placement) {
163
182
  expected.set(_id, { table, recordId: record.id, fieldsHash: previous.fieldsHash, placement });
164
183
  continue;
165
184
  }
166
185
  try {
167
186
  const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
168
- const hosted = await rehostAttachments({ baseId, tableName: table, recordId: record.id, attachments, alreadyHosted });
187
+ const hosted = await rehostAttachments({ baseId, tableId, recordId: record.id, attachments, alreadyHosted });
169
188
  ops.push({
170
189
  updateOne: {
171
190
  filter: { _id },
172
191
  update: {
173
192
  $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,
193
+ baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
194
+ fields: normalized, fieldsHash, sourceHash, patient: group.patient, groupId: group.groupId, schemaId, attachments: hosted,
176
195
  schemaVersion: ARCHIVE_SCHEMA_VERSION,
177
196
  },
178
197
  $setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
@@ -192,11 +211,11 @@ async function copyBatch({ baseId, runId, batch, computed, counts, now }) {
192
211
 
193
212
  if (ops.length) await writeOps(ArchiveRecord, ops, runId);
194
213
 
195
- const stored = await ArchiveRecord.find({ _id: { $in: [...expected.keys()] } }, { fields: 1, groupId: 1, patient: 1, createdTime: 1 }).lean();
214
+ const stored = await ArchiveRecord.find({ _id: { $in: [...expected.keys()] } }, { fields: 1, tableName: 1, groupId: 1, patient: 1, createdTime: 1 }).lean();
196
215
  const storedById = new Map(stored.map((doc) => [doc._id, doc]));
197
216
  for (const [_id, { table, recordId, fieldsHash, placement }] of expected) {
198
217
  const doc = storedById.get(_id);
199
- if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
218
+ if (doc && hashFields(doc.fields) === fieldsHash && placementOf(doc.tableName, doc.groupId, doc.patient, doc.createdTime) === placement) counts[table].verified += 1;
200
219
  else {
201
220
  counts[table].failed += 1;
202
221
  logger.error('[airtableArchive] Copy did not verify', { runId, table, recordId });
@@ -216,22 +235,25 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
216
235
  validateRequest({ baseId, cutoff, mode, now });
217
236
  const run = await acquireRun({ baseId, mode, cutoff, now });
218
237
  const { runId } = run;
219
- const counts = Object.fromEntries(Object.values(ARCHIVE_TABLES).map((table) => [table, emptyCounts()]));
238
+ let counts = {};
220
239
 
221
240
  try {
222
- const computed = await readComputedFields(baseId);
223
- const recordsByTable = await scanOldRecords(baseId, cutoff, runId);
224
- const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, runId);
225
- const plan = planArchive({ recordsByTable, patientsWithRecent });
241
+ const schema = await readArchiveSchema(baseId);
242
+ counts = Object.fromEntries(Object.values(schema.tables).map((table) => [table, emptyCounts()]));
243
+ const recordsByTable = await scanOldRecords(baseId, cutoff, runId, schema);
244
+ const patientsWithRecent = await scanPatientsWithRecent(baseId, cutoff, runId, schema);
245
+ await assertSchemaUnchanged(baseId, schema);
246
+ const plan = planArchive({ recordsByTable, patientsWithRecent, schema });
226
247
 
227
248
  Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
228
249
  const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
229
250
  const work = plan.eligible.flatMap((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
230
251
  work.forEach(({ table }) => { counts[table].eligible += 1; });
231
252
 
232
- if (mode === 'copy') {
253
+ if (mode === 'copy' && work.length) {
254
+ const schemaId = await storeSchemaSnapshot(baseId, schema.snapshot, now);
233
255
  for (let i = 0; i < work.length; i += ARCHIVE_BATCH_SIZE) {
234
- await copyBatch({ baseId, runId, batch: work.slice(i, i + ARCHIVE_BATCH_SIZE), computed, counts, now });
256
+ await copyBatch({ baseId, runId, batch: work.slice(i, i + ARCHIVE_BATCH_SIZE), schema, schemaId, counts, now });
235
257
  await renewLease(runId);
236
258
  }
237
259
  }
@@ -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');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.73.0-dev.15250",
3
+ "version": "5.73.0-dev.15252",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",