@peopl-health/nexus 5.75.8 → 5.76.0-dev.15841
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/helpers/airtableArchiveHelper.js +7 -1
- package/lib/models/airtableArchiveModel.js +1 -0
- package/lib/services/airtableArchivePlanService.js +5 -12
- package/lib/services/airtableArchiveReadService.js +31 -6
- package/lib/services/airtableArchiveService.js +4 -4
- package/lib/services/triageHistoryService.js +25 -4
- package/package.json +1 -1
|
@@ -28,7 +28,13 @@ const hashFields = (fields, skip = new Set()) => crypto.createHash('sha256')
|
|
|
28
28
|
const schemaSnapshotId = (baseId, snapshot) => `${baseId}:${crypto.createHash('sha256').update(stableStringify(snapshot)).digest('hex').slice(0, 24)}`;
|
|
29
29
|
|
|
30
30
|
// Same shape as airtableService.getRecordByFilter(..., withRecordId = true), flagged as archived.
|
|
31
|
-
const toAirtableRow = (doc) => ({
|
|
31
|
+
const toAirtableRow = (doc) => ({
|
|
32
|
+
...doc.fields,
|
|
33
|
+
_recordId: doc.recordId,
|
|
34
|
+
_createdTime: new Date(doc.createdTime).toISOString(),
|
|
35
|
+
_archived: true,
|
|
36
|
+
...(doc.attachments ? { _attachments: doc.attachments } : {}),
|
|
37
|
+
});
|
|
32
38
|
|
|
33
39
|
// Union by record id, live row winning; archived rows are appended, so callers sort after merging.
|
|
34
40
|
function mergeArchivedRows(liveRows = [], archivedRows = []) {
|
|
@@ -42,6 +42,7 @@ const airtableArchiveRecordSchema = new mongoose.Schema({
|
|
|
42
42
|
|
|
43
43
|
airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.whatsappId': 1, createdTime: -1 });
|
|
44
44
|
airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, 'patient.recordId': 1, createdTime: -1 });
|
|
45
|
+
airtableArchiveRecordSchema.index({ baseId: 1, tableName: 1, createdTime: -1 });
|
|
45
46
|
airtableArchiveRecordSchema.index({ baseId: 1, groupId: 1 });
|
|
46
47
|
airtableArchiveRecordSchema.index({ runId: 1 });
|
|
47
48
|
|
|
@@ -171,20 +171,13 @@ function planArchive({ recordsByTable, patientsWithRecent = {}, schema }) {
|
|
|
171
171
|
continue;
|
|
172
172
|
}
|
|
173
173
|
const patientEntry = records.map(({ id }) => entries.get(id)).find(patientOf);
|
|
174
|
-
const patient = {
|
|
175
|
-
recordId: patientEntry ? patientOf(patientEntry) : null,
|
|
176
|
-
whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
|
|
177
|
-
};
|
|
178
|
-
// A group can join two patients' records through a shared questionnaire; each record keeps its own patient.
|
|
179
|
-
const patientFor = (entry) => {
|
|
180
|
-
const own = patientOf(entry);
|
|
181
|
-
if (!own || own === patient.recordId) return patient;
|
|
182
|
-
return { recordId: own, whatsappId: firstString(entry.record.fields?.[schema.whatsappFields[entry.table]]) };
|
|
183
|
-
};
|
|
184
174
|
eligible.push({
|
|
185
175
|
groupId: groupIdOf(records.map(({ id }) => id)),
|
|
186
|
-
patient
|
|
187
|
-
|
|
176
|
+
patient: {
|
|
177
|
+
recordId: patientEntry ? patientOf(patientEntry) : null,
|
|
178
|
+
whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
|
|
179
|
+
},
|
|
180
|
+
records,
|
|
188
181
|
});
|
|
189
182
|
}
|
|
190
183
|
|
|
@@ -1,25 +1,50 @@
|
|
|
1
|
+
const { getModelDatabase } = require('../config/mongoConfig');
|
|
1
2
|
const { getAirtableArchiveRecord, archiveRecordId } = require('../models/airtableArchiveModel');
|
|
2
3
|
const { toAirtableRow } = require('../helpers/airtableArchiveHelper');
|
|
3
4
|
|
|
4
|
-
|
|
5
|
+
// Only rows already deleted from Airtable: a copy whose source is still live must never reach a reader.
|
|
6
|
+
const DELETED_FROM_SOURCE = { sourceDeletedAt: { $ne: null } };
|
|
5
7
|
|
|
6
|
-
|
|
8
|
+
// Unmapped, the model would fall back to the default database and every read would come back empty.
|
|
9
|
+
function archiveRecords() {
|
|
10
|
+
if (!getModelDatabase('AirtableArchiveRecord')) throw new Error('AirtableArchiveRecord db not mapped (setModelDatabases)');
|
|
11
|
+
return getAirtableArchiveRecord();
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function readProjection({ fields, withAttachments = false } = {}) {
|
|
15
|
+
const projection = { recordId: 1, createdTime: 1 };
|
|
16
|
+
if (fields?.length) fields.forEach((name) => { projection[`fields.${name}`] = 1; });
|
|
17
|
+
else projection.fields = 1;
|
|
18
|
+
if (withAttachments) projection.attachments = 1;
|
|
19
|
+
return projection;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function findArchivedByPatient({ baseId, tableName, whatsappId, patientRecordId, since, fields, withAttachments }) {
|
|
7
23
|
if (!whatsappId && !patientRecordId) return [];
|
|
8
|
-
const query = { baseId, tableName };
|
|
24
|
+
const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
|
|
9
25
|
if (patientRecordId) query['patient.recordId'] = patientRecordId;
|
|
10
26
|
else query['patient.whatsappId'] = whatsappId;
|
|
11
27
|
if (since) query.createdTime = { $gte: since };
|
|
12
|
-
const docs = await
|
|
28
|
+
const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).sort({ createdTime: -1 }).lean();
|
|
13
29
|
return docs.map(toAirtableRow);
|
|
14
30
|
}
|
|
15
31
|
|
|
16
|
-
async function findArchivedByRecordIds({ baseId, tableName, recordIds }) {
|
|
32
|
+
async function findArchivedByRecordIds({ baseId, tableName, recordIds, fields, withAttachments }) {
|
|
17
33
|
if (!recordIds?.length) return [];
|
|
18
|
-
const
|
|
34
|
+
const query = { _id: { $in: recordIds.map((id) => archiveRecordId(baseId, id)) }, tableName, ...DELETED_FROM_SOURCE };
|
|
35
|
+
const docs = await archiveRecords().find(query, readProjection({ fields, withAttachments })).lean();
|
|
36
|
+
return docs.map(toAirtableRow);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function findArchivedByTable({ baseId, tableName, since, fields }) {
|
|
40
|
+
const query = { baseId, tableName, ...DELETED_FROM_SOURCE };
|
|
41
|
+
if (since) query.createdTime = { $gte: since };
|
|
42
|
+
const docs = await archiveRecords().find(query, readProjection({ fields })).sort({ createdTime: -1 }).lean();
|
|
19
43
|
return docs.map(toAirtableRow);
|
|
20
44
|
}
|
|
21
45
|
|
|
22
46
|
module.exports = {
|
|
23
47
|
findArchivedByPatient,
|
|
24
48
|
findArchivedByRecordIds,
|
|
49
|
+
findArchivedByTable,
|
|
25
50
|
};
|
|
@@ -237,7 +237,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
237
237
|
|
|
238
238
|
const expected = new Map();
|
|
239
239
|
const ops = [];
|
|
240
|
-
for (const { table, record: scanned, group
|
|
240
|
+
for (const { table, record: scanned, group } of batch) {
|
|
241
241
|
if (changedGroups.has(group.groupId)) {
|
|
242
242
|
counts[table].failed += 1;
|
|
243
243
|
logger.error('[airtableArchive] Group changed or gone since the scan', { runId, table, recordId: scanned.id, groupId: group.groupId });
|
|
@@ -249,7 +249,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
249
249
|
const fieldsHash = hashFields(normalized);
|
|
250
250
|
const sourceHash = hashFields(normalized, schema.computed.get(table));
|
|
251
251
|
const tableId = schema.tableIds[table];
|
|
252
|
-
const placement = placementOf(table, group.groupId, patient, record.createdTime);
|
|
252
|
+
const placement = placementOf(table, group.groupId, group.patient, record.createdTime);
|
|
253
253
|
const previous = existing.get(_id);
|
|
254
254
|
const previousIntact = previous?.tableId && previous.schemaId && hashFields(previous.fields) === previous.fieldsHash;
|
|
255
255
|
if (previousIntact && previous.sourceHash === sourceHash && placementOf(previous.tableName, previous.groupId, previous.patient, previous.createdTime) === placement) {
|
|
@@ -265,7 +265,7 @@ async function copyBatch({ baseId, runId, batch, schema, schemaId, counts, now,
|
|
|
265
265
|
update: {
|
|
266
266
|
$set: {
|
|
267
267
|
baseId, tableId, tableName: table, recordId: record.id, createdTime: new Date(record.createdTime),
|
|
268
|
-
fields: normalized, fieldsHash, sourceHash, patient, groupId: group.groupId, schemaId, attachments: hosted,
|
|
268
|
+
fields: normalized, fieldsHash, sourceHash, patient: group.patient, groupId: group.groupId, schemaId, attachments: hosted,
|
|
269
269
|
schemaVersion: ARCHIVE_SCHEMA_VERSION,
|
|
270
270
|
},
|
|
271
271
|
$setOnInsert: { runId, archivedAt: now, sourceDeletedAt: null },
|
|
@@ -337,7 +337,7 @@ async function runArchive({ baseId, cutoff, mode = 'plan', now = new Date() }) {
|
|
|
337
337
|
|
|
338
338
|
Object.entries(recordsByTable).forEach(([table, records]) => { counts[table].scanned = records.length; });
|
|
339
339
|
const recordsById = new Map(Object.values(recordsByTable).flat().map((record) => [record.id, record]));
|
|
340
|
-
const work = plan.eligible.map((group) => group.records.map(({ table, id
|
|
340
|
+
const work = plan.eligible.map((group) => group.records.map(({ table, id }) => ({ table, record: recordsById.get(id), group })));
|
|
341
341
|
work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
|
|
342
342
|
|
|
343
343
|
if (mode === 'copy' && work.length) {
|
|
@@ -1,11 +1,15 @@
|
|
|
1
1
|
const { Symptoms_ID } = require('../config/airtableConfig');
|
|
2
2
|
|
|
3
3
|
const { MapCache } = require('../utils/MapCache');
|
|
4
|
+
const { logger } = require('../utils/logger');
|
|
4
5
|
const { paginate } = require('../utils/paginationUtils');
|
|
6
|
+
const { firstOf } = require('../utils/coercionUtils');
|
|
5
7
|
const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
8
|
+
const { mergeArchivedRows } = require('../helpers/airtableArchiveHelper');
|
|
6
9
|
const { TRIAGE_FIELDS, SYMPTOM_FIELDS, buildTriageRecord } = require('../helpers/triageRecordHelper');
|
|
7
10
|
|
|
8
11
|
const { getRecordByFilter } = require('./airtableService');
|
|
12
|
+
const { findArchivedByPatient, findArchivedByRecordIds } = require('./airtableArchiveReadService');
|
|
9
13
|
|
|
10
14
|
const DEFAULT_LIMIT = 50;
|
|
11
15
|
const HISTORY_TTL_MS = 60 * 1000;
|
|
@@ -24,11 +28,23 @@ const withinRange = (row, fromDate, toDate) => {
|
|
|
24
28
|
|
|
25
29
|
const linkedIdsOf = (value) => (Array.isArray(value) ? value.filter(Boolean) : []);
|
|
26
30
|
|
|
31
|
+
// Rows deleted from Airtable exist only in the archive; if it cannot be read, the page shows live rows only.
|
|
32
|
+
const readArchived = async (read, params) => {
|
|
33
|
+
try {
|
|
34
|
+
return await read({ baseId: Symptoms_ID, ...params });
|
|
35
|
+
} catch (error) {
|
|
36
|
+
logger.error('[triageHistoryService] Archive read failed, serving live rows only', { table: params.tableName, error: error.message });
|
|
37
|
+
return [];
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
|
|
27
41
|
const readPatientHistory = async (code) => {
|
|
28
|
-
const
|
|
29
|
-
Symptoms_ID, 'triaje_symptoms', fieldEquals('whatsapp_id', code), 'Grid view', TRIAGE_FIELDS,
|
|
30
|
-
|
|
31
|
-
|
|
42
|
+
const [live, archived] = await Promise.all([
|
|
43
|
+
getRecordByFilter(Symptoms_ID, 'triaje_symptoms', fieldEquals('whatsapp_id', code), 'Grid view', TRIAGE_FIELDS, true),
|
|
44
|
+
readArchived(findArchivedByPatient, { tableName: 'triaje_symptoms', whatsappId: code, fields: TRIAGE_FIELDS }),
|
|
45
|
+
]);
|
|
46
|
+
const ownRows = archived.filter((row) => firstOf(row.whatsapp_id) === code);
|
|
47
|
+
return { rows: mergeArchivedRows(live || [], ownRows), symptomsById: new Map() };
|
|
32
48
|
};
|
|
33
49
|
|
|
34
50
|
const getPatientHistory = (code) => {
|
|
@@ -67,6 +83,11 @@ const getTriageHistory = async ({ code, startDate, endDate, limit, page } = {})
|
|
|
67
83
|
Symptoms_ID, 'symptoms', recordIdIn(missingIds), null, SYMPTOM_FIELDS, true,
|
|
68
84
|
) || [];
|
|
69
85
|
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
|
+
}
|
|
70
91
|
}
|
|
71
92
|
|
|
72
93
|
const records = pageRows.map((row) => buildTriageRecord(
|