@peopl-health/nexus 5.78.0-dev.16570 → 5.78.0-dev.16618

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.
@@ -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,
@@ -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
- cutoff: { type: Date, required: true },
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,223 @@
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
+ // Stamps a mirror set because a scan missed the record; those are undone when it shows up again.
49
+ async function mirrorStampsOf(docs) {
50
+ const stampRunIds = [...new Set(docs.filter((doc) => doc.sourceDeletedAt && doc.deleteRunId).map((doc) => doc.deleteRunId))];
51
+ if (!stampRunIds.length) return new Set();
52
+ const runs = await getAirtableArchiveRun().find({ runId: { $in: stampRunIds }, mode: 'mirror' }, { runId: 1 }).lean();
53
+ return new Set(runs.map((run) => run.runId));
54
+ }
55
+
56
+ async function mirrorPage({ baseId, runId, table, page, Records, names, computed, patientSpec, schemaId, counts, budget, seen, now }) {
57
+ const existing = new Map((await Records.find(
58
+ { _id: { $in: page.map((record) => record.id) } }, { fieldsHash: 1, tableName: 1, patient: 1, groupId: 1, attachments: 1, sourceDeletedAt: 1, deleteRunId: 1 },
59
+ ).lean()).map((doc) => [doc._id, doc]));
60
+ const mirrorStamps = await mirrorStampsOf([...existing.values()]);
61
+ const ops = [];
62
+ const expected = new Map();
63
+ for (const record of page) {
64
+ seen.add(record.id);
65
+ const fields = {};
66
+ for (const [fieldId, value] of Object.entries(record.fields)) {
67
+ if (!names.has(fieldId)) {
68
+ logger.error('[airtableMirror] Scanned a field missing from the run schema', { runId, table: table.name, fieldId });
69
+ throw archiveError('archive_schema_mismatch');
70
+ }
71
+ fields[names.get(fieldId)] = value;
72
+ }
73
+ const previous = existing.get(record.id);
74
+ const restored = Boolean(previous?.sourceDeletedAt) && mirrorStamps.has(previous.deleteRunId);
75
+ // A stamped copy stands in for a record a delete is removing; the delete decides it, not the mirror.
76
+ if (previous?.sourceDeletedAt && !restored) {
77
+ counts.skipped += 1;
78
+ continue;
79
+ }
80
+ const { normalized, attachments } = normalizeFields(fields);
81
+ const fieldsHash = hashFields(normalized);
82
+ const alreadyHosted = new Map((previous?.attachments || []).map((a) => [a.id, a]));
83
+ const unhosted = attachments.filter(({ item }) => !alreadyHosted.has(item.id));
84
+ if (previous && !restored && previous.fieldsHash === fieldsHash && previous.tableName === table.name && !unhosted.length) {
85
+ counts.unchanged += 1;
86
+ continue;
87
+ }
88
+ // Attachments past the run's budget stay unhosted, so the record is rewritten by the next run that has room.
89
+ const hostable = attachments.filter(({ item }) => {
90
+ if (alreadyHosted.has(item.id)) return true;
91
+ if (budget.attachments <= 0) return false;
92
+ budget.attachments -= 1;
93
+ return true;
94
+ });
95
+ counts.attachmentsPending += attachments.length - hostable.length;
96
+ let hosted;
97
+ try {
98
+ hosted = await rehostAttachments({ baseId, tableId: table.id, recordId: record.id, attachments: hostable, alreadyHosted });
99
+ } catch (error) {
100
+ // The fields are copied anyway; the attachments left unhosted are retried by the next run.
101
+ hosted = hostable.filter(({ item }) => alreadyHosted.has(item.id)).map(({ item }) => alreadyHosted.get(item.id));
102
+ counts.attachmentsPending += hostable.length - hosted.length;
103
+ logger.error('[airtableMirror] Attachments not hosted', { runId, table: table.name, recordId: record.id, errorCode: error?.code || 'UNKNOWN' });
104
+ }
105
+ ops.push({
106
+ updateOne: {
107
+ // Only a restore clears a stamp, and only its own: a delete that stamped meanwhile keeps the copy it serves.
108
+ filter: restored ? { _id: record.id, deleteRunId: previous.deleteRunId } : { _id: record.id },
109
+ update: {
110
+ $set: {
111
+ baseId, tableId: table.id, tableName: table.name, recordId: record.id, createdTime: new Date(record.createdTime),
112
+ fields: normalized, fieldsHash, sourceHash: hashFields(normalized, computed),
113
+ // A patient already stored came from the planner, which can name it through the triage group; it is kept.
114
+ patient: previous?.groupId || hasPatient(previous?.patient) ? previous.patient : patientOf(patientSpec, record),
115
+ schemaId, attachments: hosted, source: { kind: 'live', baseId }, schemaVersion: ARCHIVE_SCHEMA_VERSION,
116
+ ...(restored ? { sourceDeletedAt: null } : {}),
117
+ },
118
+ ...(restored ? { $unset: { deleteRunId: '' } } : {}),
119
+ $setOnInsert: { runId, archivedAt: now, groupId: null, ...(restored ? {} : { sourceDeletedAt: null }) },
120
+ },
121
+ upsert: true,
122
+ },
123
+ });
124
+ expected.set(record.id, fieldsHash);
125
+ counts[previous ? 'refreshed' : 'copied'] += 1;
126
+ if (restored) counts.restored += 1;
127
+ // Downloads can outlast the lease, so a record that uploaded any renews it before the next one.
128
+ if (hostable.some(({ item }) => !alreadyHosted.has(item.id))) await renewLease(runId);
129
+ }
130
+ if (!ops.length) return;
131
+ await writeOps(Records, ops, runId);
132
+ const stored = new Map((await Records.find({ _id: { $in: [...expected.keys()] } }, { fields: 1 }).lean()).map((doc) => [doc._id, doc]));
133
+ for (const [recordId, fieldsHash] of expected) {
134
+ if (stored.has(recordId) && hashFields(stored.get(recordId).fields) === fieldsHash) counts.verified += 1;
135
+ else {
136
+ counts.failed += 1;
137
+ logger.error('[airtableMirror] Copy did not verify', { runId, table: table.name, recordId });
138
+ }
139
+ }
140
+ }
141
+
142
+ // Copies the scan missed after a full read were deleted from Airtable; too many at once reads as a bad scan instead.
143
+ async function markGone({ Records, runId, table, seen, counts, now }) {
144
+ const stored = await Records.find({ sourceDeletedAt: null, 'source.kind': 'live' }, { _id: 1 }).lean();
145
+ const gone = stored.map((doc) => doc._id).filter((id) => !seen.has(id));
146
+ if (!gone.length) return;
147
+ if (!seen.size || gone.length > Math.max(MIRROR_GONE_MIN_HELD, Math.ceil(stored.length * MIRROR_GONE_MAX_SHARE))) {
148
+ counts.goneHeld = gone.length;
149
+ logger.error('[airtableMirror] Too many records missing from a full scan, none marked gone', { runId, table: table.name, missing: gone.length, stored: stored.length });
150
+ return;
151
+ }
152
+ await Records.updateMany({ _id: { $in: gone }, sourceDeletedAt: null }, { $set: { sourceDeletedAt: now, deleteRunId: runId } }, { writeConcern: WRITE_CONCERN });
153
+ counts.gone = await Records.countDocuments({ _id: { $in: gone }, deleteRunId: runId });
154
+ if (counts.gone !== gone.length) {
155
+ counts.failed += gone.length - counts.gone;
156
+ logger.error('[airtableMirror] Gone records did not read back stamped', { runId, table: table.name, missing: gone.length, stamped: counts.gone });
157
+ }
158
+ }
159
+
160
+ async function mirrorTable({ baseId, runId, table, schemaId, counts, budget, lease, now }) {
161
+ const Records = await getAirtableTableRecords({ baseId, tableId: table.id, tableName: table.name });
162
+ const names = new Map(table.fields.map((f) => [f.id, f.name]));
163
+ const computed = new Set(table.fields.filter((f) => COMPUTED_FIELD_TYPES.includes(f.type)).map((f) => f.name));
164
+ const patientSpec = patientFieldsOf(table);
165
+ const seen = new Set();
166
+ await scanRecordPages(baseId, table.id, {
167
+ onPage: async (page) => {
168
+ await mirrorPage({ baseId, runId, table, page, Records, names, computed, patientSpec, schemaId, counts, budget, seen, now });
169
+ await lease.renewIfDue();
170
+ },
171
+ // Pages already written are rewritten as unchanged; `seen` only grows, so a restart cannot mark anything gone.
172
+ onRestart: () => {},
173
+ });
174
+ counts.scanned = seen.size;
175
+ await markGone({ Records, runId, table, seen, counts, now });
176
+ }
177
+
178
+ // Copies every table of a base into its collection as it is now and marks copies whose record left Airtable; never writes to Airtable.
179
+ async function runMirror({ baseId, now = new Date(), maxAttachments = MIRROR_MAX_ATTACHMENTS_PER_RUN }) {
180
+ if (!baseId) throw archiveError('archive_base_required');
181
+ const { runId } = await acquireRun({ baseId, mode: 'mirror', cutoff: null, now });
182
+ const counts = {};
183
+ try {
184
+ let tables;
185
+ try {
186
+ tables = await getBaseSchema(baseId);
187
+ } catch (error) {
188
+ throw Object.assign(archiveError('archive_schema_unreadable'), { cause: error });
189
+ }
190
+ const schemaId = await storeSchemaSnapshot(baseId, snapshotOf(tables), now);
191
+ const lease = leaseFor(runId);
192
+ const budget = { attachments: maxAttachments };
193
+ for (const table of tables) {
194
+ counts[table.name] = emptyCounts();
195
+ try {
196
+ await mirrorTable({ baseId, runId, table, schemaId, counts: counts[table.name], budget, lease, now });
197
+ } catch (error) {
198
+ if (error?.code === 'archive_lease_lost') throw error;
199
+ counts[table.name].failed += 1;
200
+ logger.error('[airtableMirror] Table not mirrored', { runId, table: table.name, errorCode: error?.code || 'UNKNOWN' });
201
+ }
202
+ await renewLease(runId);
203
+ }
204
+ const total = (key) => Object.values(counts).reduce((sum, c) => sum + c[key], 0);
205
+ const errorCode = (total('failed') && 'records_failed') || (total('goneHeld') && 'mirror_mass_disappearance') || null;
206
+ const summary = { runId, mode: 'mirror', status: errorCode ? 'failed' : 'succeeded', tables: counts, errorCode };
207
+ const finished = await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, {
208
+ $set: { status: summary.status, finishedAt: new Date(), tables: counts, errorCode },
209
+ });
210
+ if (!finished?.matchedCount) throw archiveError('archive_lease_lost');
211
+ logger.info('[airtableMirror] Run finished', summary);
212
+ return summary;
213
+ } catch (error) {
214
+ const errorCode = [error?.code, error?.error].find((code) => code && typeof code === 'string') || 'UNKNOWN';
215
+ await getAirtableArchiveRun().updateOne({ runId, status: 'running' }, { $set: { status: 'failed', finishedAt: new Date(), tables: counts, errorCode } });
216
+ logger.error('[airtableMirror] Run failed', { runId, errorCode });
217
+ throw error;
218
+ }
219
+ }
220
+
221
+ module.exports = {
222
+ runMirror,
223
+ };
@@ -28,6 +28,9 @@ const withinRange = (row, fromDate, toDate) => {
28
28
 
29
29
  const linkedIdsOf = (value) => (Array.isArray(value) ? value.filter(Boolean) : []);
30
30
 
31
+ // The symptom's own link to its triage: Airtable unlinks a deleted symptom from the triage but its copy keeps this side.
32
+ const SYMPTOM_TRIAGE_FIELD = 'triaje_id';
33
+
31
34
  // Rows deleted from Airtable exist only in the archive; if it cannot be read, the page shows live rows only.
32
35
  const readArchived = async (read, params) => {
33
36
  try {
@@ -39,12 +42,24 @@ const readArchived = async (read, params) => {
39
42
  };
40
43
 
41
44
  const readPatientHistory = async (code) => {
42
- const [live, archived] = await Promise.all([
45
+ const [live, archived, archivedSymptoms] = await Promise.all([
43
46
  getRecordByFilter(Symptoms_ID, 'triaje_symptoms', fieldEquals('whatsapp_id', code), 'Grid view', TRIAGE_FIELDS, true),
44
47
  readArchived(findArchivedByPatient, { tableName: 'triaje_symptoms', whatsappId: code, fields: TRIAGE_FIELDS }),
48
+ readArchived(findArchivedByPatient, { tableName: 'symptoms', whatsappId: code, fields: [...SYMPTOM_FIELDS, SYMPTOM_TRIAGE_FIELD] }),
45
49
  ]);
46
50
  const ownRows = archived.filter((row) => firstOf(row.whatsapp_id) === code);
47
- return { rows: mergeArchivedRows(live || [], ownRows), symptomsById: new Map() };
51
+ const archivedSymptomIdsByTriage = new Map();
52
+ [...archivedSymptoms].sort((a, b) => new Date(a._createdTime) - new Date(b._createdTime)).forEach((row) => {
53
+ linkedIdsOf(row[SYMPTOM_TRIAGE_FIELD]).forEach((triageId) => {
54
+ archivedSymptomIdsByTriage.set(triageId, [...(archivedSymptomIdsByTriage.get(triageId) || []), row._recordId]);
55
+ });
56
+ });
57
+ return {
58
+ rows: mergeArchivedRows(live || [], ownRows),
59
+ symptomsById: new Map(),
60
+ archivedSymptomsById: new Map(archivedSymptoms.map((row) => [row._recordId, row])),
61
+ archivedSymptomIdsByTriage,
62
+ };
48
63
  };
49
64
 
50
65
  const getPatientHistory = (code) => {
@@ -67,7 +82,8 @@ const getPatientHistory = (code) => {
67
82
 
68
83
  // The `… (from symptoms)` lookups are not used: Airtable omits empty values, shifting every later grade onto the wrong symptom.
69
84
  const getTriageHistory = async ({ code, startDate, endDate, limit, page } = {}) => {
70
- const { rows, symptomsById } = await getPatientHistory(code);
85
+ const { rows, symptomsById, archivedSymptomsById, archivedSymptomIdsByTriage } = await getPatientHistory(code);
86
+ const symptomIdsOf = (row) => [...new Set([...linkedIdsOf(row.symptoms), ...(archivedSymptomIdsByTriage.get(row._recordId || row.recordID) || [])])];
71
87
 
72
88
  const fromDate = startDate ? new Date(`${startDate}T00:00:00.000Z`) : null;
73
89
  const toDate = endDate ? new Date(`${endDate}T23:59:59.999Z`) : null;
@@ -76,23 +92,25 @@ const getTriageHistory = async ({ code, startDate, endDate, limit, page } = {})
76
92
  const sorted = [...filtered].sort((a, b) => new Date(b?.Created || 0) - new Date(a?.Created || 0));
77
93
  const { records: pageRows, pagination } = paginate(sorted, { limit, page, defaultLimit: DEFAULT_LIMIT });
78
94
 
79
- const symptomIds = [...new Set(pageRows.flatMap((row) => linkedIdsOf(row.symptoms)))];
80
- const missingIds = symptomIds.filter((id) => !symptomsById.has(id));
81
- if (missingIds.length) {
95
+ // Linked symptoms are read live first, so a live symptom always wins over an archived copy of it.
96
+ const linkedMissing = [...new Set(pageRows.flatMap((row) => linkedIdsOf(row.symptoms)))].filter((id) => !symptomsById.has(id));
97
+ if (linkedMissing.length) {
82
98
  const symptomRows = await getRecordByFilter(
83
- Symptoms_ID, 'symptoms', recordIdIn(missingIds), null, SYMPTOM_FIELDS, true,
99
+ Symptoms_ID, 'symptoms', recordIdIn(linkedMissing), null, SYMPTOM_FIELDS, true,
84
100
  ) || [];
85
101
  for (const symptomRow of symptomRows) symptomsById.set(symptomRow._recordId, symptomRow);
86
- const archivedIds = missingIds.filter((id) => !symptomsById.has(id));
87
- if (archivedIds.length) {
88
- const archivedRows = await readArchived(findArchivedByRecordIds, { tableName: 'symptoms', recordIds: archivedIds, fields: SYMPTOM_FIELDS });
89
- for (const symptomRow of archivedRows) symptomsById.set(symptomRow._recordId, symptomRow);
90
- }
102
+ }
103
+ const symptomIds = [...new Set(pageRows.flatMap(symptomIdsOf))];
104
+ for (const id of symptomIds) if (!symptomsById.has(id) && archivedSymptomsById.has(id)) symptomsById.set(id, archivedSymptomsById.get(id));
105
+ const archivedIds = symptomIds.filter((id) => !symptomsById.has(id));
106
+ if (archivedIds.length) {
107
+ const archivedRows = await readArchived(findArchivedByRecordIds, { tableName: 'symptoms', recordIds: archivedIds, fields: SYMPTOM_FIELDS });
108
+ for (const symptomRow of archivedRows) symptomsById.set(symptomRow._recordId, symptomRow);
91
109
  }
92
110
 
93
111
  const records = pageRows.map((row) => buildTriageRecord(
94
112
  row,
95
- linkedIdsOf(row.symptoms).map((id) => symptomsById.get(id)).filter(Boolean),
113
+ symptomIdsOf(row).map((id) => symptomsById.get(id)).filter(Boolean),
96
114
  ));
97
115
 
98
116
  return { records, pagination };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.78.0-dev.16570",
3
+ "version": "5.78.0-dev.16618",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",