@peopl-health/nexus 5.76.0-dev.15841 → 5.76.0
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.
|
@@ -181,19 +181,27 @@ const getPatientRecommendationCarouselImageController = async (req, res) => {
|
|
|
181
181
|
});
|
|
182
182
|
if (!image) return res.status(404).json({ success: false, error: 'Carousel image not found' });
|
|
183
183
|
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
184
|
+
let contentType;
|
|
185
|
+
let body;
|
|
186
|
+
if (image.body) {
|
|
187
|
+
// Archived carousels: the service already read the re-hosted image from the archive bucket.
|
|
188
|
+
contentType = String(image.contentType || '').split(';')[0].trim().toLowerCase();
|
|
189
|
+
body = image.body;
|
|
190
|
+
} else {
|
|
191
|
+
const source = new URL(image.url);
|
|
192
|
+
const allowed = source.protocol === 'https:'
|
|
193
|
+
&& isAllowedUrl(image.url, ['airtableusercontent.com', 'airtable.com']);
|
|
194
|
+
if (!allowed) return res.status(502).json({ success: false, error: 'Unsupported carousel image source' });
|
|
195
|
+
|
|
196
|
+
const response = await axios.get(image.url, {
|
|
197
|
+
responseType: 'arraybuffer',
|
|
198
|
+
timeout: 15000,
|
|
199
|
+
maxContentLength: 10 * 1024 * 1024,
|
|
200
|
+
maxRedirects: 0,
|
|
201
|
+
});
|
|
202
|
+
contentType = String(response.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
|
|
203
|
+
body = Buffer.from(response.data);
|
|
204
|
+
}
|
|
197
205
|
const signatures = {
|
|
198
206
|
'image/png': () => body.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
|
|
199
207
|
'image/jpeg': () => body.length >= 3 && body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff,
|
|
@@ -171,13 +171,20 @@ 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
|
+
};
|
|
174
184
|
eligible.push({
|
|
175
185
|
groupId: groupIdOf(records.map(({ id }) => id)),
|
|
176
|
-
patient
|
|
177
|
-
|
|
178
|
-
whatsappId: firstString(patientEntry?.record.fields?.[schema.whatsappFields[patientEntry.table]]),
|
|
179
|
-
},
|
|
180
|
-
records,
|
|
186
|
+
patient,
|
|
187
|
+
records: records.map((record) => ({ ...record, patient: patientFor(entries.get(record.id)) })),
|
|
181
188
|
});
|
|
182
189
|
}
|
|
183
190
|
|
|
@@ -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 } of batch) {
|
|
240
|
+
for (const { table, record: scanned, group, patient } 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,
|
|
252
|
+
const placement = placementOf(table, group.groupId, 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
|
|
268
|
+
fields: normalized, fieldsHash, sourceHash, 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 }) => ({ table, record: recordsById.get(id), group })));
|
|
340
|
+
const work = plan.eligible.map((group) => group.records.map(({ table, id, patient }) => ({ table, record: recordsById.get(id), group, patient })));
|
|
341
341
|
work.flat().forEach(({ table }) => { counts[table].eligible += 1; });
|
|
342
342
|
|
|
343
343
|
if (mode === 'copy' && work.length) {
|
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
const { Symptoms_ID: symptomsId } = require('../config/airtableConfig');
|
|
2
|
+
const runtimeConfig = require('../config/runtimeConfig');
|
|
3
|
+
const { s3 } = require('../config/awsConfig');
|
|
4
|
+
const { logger } = require('../utils/logger');
|
|
2
5
|
const { firstOf } = require('../utils/coercionUtils');
|
|
3
6
|
const { paginate } = require('../utils/paginationUtils');
|
|
4
7
|
const { MapCache } = require('../utils/MapCache');
|
|
5
8
|
const { DeliveryAttempt, DELIVERY_ATTEMPT_LANDED_STATUSES } = require('../models/deliveryAttemptModel');
|
|
6
9
|
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
7
10
|
const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
|
|
11
|
+
const { mergeArchivedRows } = require('../helpers/airtableArchiveHelper');
|
|
8
12
|
const { getRecordByFilter } = require('./airtableService');
|
|
13
|
+
const { findArchivedByPatient, findArchivedByRecordIds } = require('./airtableArchiveReadService');
|
|
9
14
|
const { getMessages } = require('./messageService');
|
|
10
15
|
|
|
11
16
|
const DEFAULT_LIMIT = 50;
|
|
@@ -35,6 +40,8 @@ const CAROUSEL_STATUS_FIELDS = [
|
|
|
35
40
|
];
|
|
36
41
|
|
|
37
42
|
const RESOLUTION_FIELDS = ['rank', 'element_name_short'];
|
|
43
|
+
// What the live `Grid view` filter reads, so archived rows can be held to the same rule.
|
|
44
|
+
const VIEW_FIELDS = ['whatsapp_id', 'tipo (from triaje_symptoms)'];
|
|
38
45
|
const FIRST_RESOLUTION_VARIABLE = '2';
|
|
39
46
|
const UNSUCCESSFUL_SEND_STATUSES = ['failed', 'undelivered'];
|
|
40
47
|
const carouselCache = new MapCache({ maxSize: 30, ttl: CACHE_TTL_MS });
|
|
@@ -158,15 +165,30 @@ function patientContentOf(recommendation) {
|
|
|
158
165
|
};
|
|
159
166
|
}
|
|
160
167
|
|
|
168
|
+
// Rows deleted from Airtable exist only in the archive; if it cannot be read, live rows are served alone.
|
|
169
|
+
async function readArchived(read, params) {
|
|
170
|
+
try {
|
|
171
|
+
return await read({ baseId: symptomsId, ...params });
|
|
172
|
+
} catch (error) {
|
|
173
|
+
logger.error('[recommendationCarouselService] Archive read failed, serving live rows only', { table: params.tableName, error: error.message });
|
|
174
|
+
return [];
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Same rule as the live `Grid view`: the patient's own carousels from production triages.
|
|
179
|
+
const inLiveView = (code) => (row) => firstOf(row.whatsapp_id) === code
|
|
180
|
+
&& [].concat(row['tipo (from triaje_symptoms)'] ?? []).includes('prod');
|
|
181
|
+
|
|
182
|
+
async function readPatientCarouselsWithArchive(code, fields) {
|
|
183
|
+
const [live, archived] = await Promise.all([
|
|
184
|
+
getRecordByFilter(symptomsId, 'cluster_recommendations', fieldEquals('whatsapp_id', code), 'Grid view', fields, true),
|
|
185
|
+
readArchived(findArchivedByPatient, { tableName: 'cluster_recommendations', whatsappId: code, fields: [...fields, ...VIEW_FIELDS] }),
|
|
186
|
+
]);
|
|
187
|
+
return mergeArchivedRows(live || [], archived.filter(inLiveView(code)));
|
|
188
|
+
}
|
|
189
|
+
|
|
161
190
|
async function readPatientCarouselIndex(code) {
|
|
162
|
-
const rows = await
|
|
163
|
-
symptomsId,
|
|
164
|
-
'cluster_recommendations',
|
|
165
|
-
fieldEquals('whatsapp_id', code),
|
|
166
|
-
'Grid view',
|
|
167
|
-
CAROUSEL_INDEX_FIELDS,
|
|
168
|
-
true,
|
|
169
|
-
) || [];
|
|
191
|
+
const rows = await readPatientCarouselsWithArchive(code, CAROUSEL_INDEX_FIELDS);
|
|
170
192
|
|
|
171
193
|
return rows.sort((a, b) => (
|
|
172
194
|
Date.parse(b.Created || b._createdTime || 0) - Date.parse(a.Created || a._createdTime || 0)
|
|
@@ -186,7 +208,14 @@ async function readPatientCarouselRows(code, ids) {
|
|
|
186
208
|
CAROUSEL_FIELDS,
|
|
187
209
|
true,
|
|
188
210
|
) || [];
|
|
189
|
-
rows.
|
|
211
|
+
const liveIds = new Set(rows.map((row) => row._recordId || row.recordID));
|
|
212
|
+
const archivedIds = missingIds.filter((id) => !liveIds.has(id));
|
|
213
|
+
const archived = archivedIds.length
|
|
214
|
+
? (await readArchived(findArchivedByRecordIds, {
|
|
215
|
+
tableName: 'cluster_recommendations', recordIds: archivedIds, fields: [...CAROUSEL_FIELDS, ...VIEW_FIELDS], withAttachments: true,
|
|
216
|
+
})).filter(inLiveView(code))
|
|
217
|
+
: [];
|
|
218
|
+
[...rows, ...archived].forEach((row) => {
|
|
190
219
|
const id = row._recordId || row.recordID;
|
|
191
220
|
if (id && generation === cacheGeneration) {
|
|
192
221
|
carouselRowCache.set(`${code}:${id}`, row);
|
|
@@ -211,9 +240,21 @@ async function resolutionMapFor(rows) {
|
|
|
211
240
|
true,
|
|
212
241
|
) || []
|
|
213
242
|
: [];
|
|
214
|
-
|
|
243
|
+
const liveIds = new Set(resolutionRows.map((row) => row._recordId));
|
|
244
|
+
const archivedIds = resolutionIds.filter((id) => !liveIds.has(id));
|
|
245
|
+
const archived = archivedIds.length
|
|
246
|
+
? await readArchived(findArchivedByRecordIds, { tableName: 'cluster_resolutions', recordIds: archivedIds, fields: RESOLUTION_FIELDS })
|
|
247
|
+
: [];
|
|
248
|
+
return new Map([...resolutionRows, ...archived].map((row) => [row._recordId, row]));
|
|
215
249
|
}
|
|
216
250
|
|
|
251
|
+
// Airtable attachment URLs are gone once a row is archived; its image was re-hosted to S3.
|
|
252
|
+
const archivedImageKey = (row, attachment) => (
|
|
253
|
+
row?._archived && attachment?.id
|
|
254
|
+
? (row._attachments || []).find((hosted) => hosted.field === 'images' && hosted.id === attachment.id)?.s3Key || null
|
|
255
|
+
: null
|
|
256
|
+
);
|
|
257
|
+
|
|
217
258
|
function projectCarousel(row, resolutionById, sends) {
|
|
218
259
|
const recommendations = parseRecommendations(row.recommendations);
|
|
219
260
|
const images = Array.isArray(row.images) ? row.images : [];
|
|
@@ -235,7 +276,7 @@ function projectCarousel(row, resolutionById, sends) {
|
|
|
235
276
|
recommendationId: recommendationIdOf(recommendation),
|
|
236
277
|
title: titleOf(recommendation, resolution),
|
|
237
278
|
resolutionId: resolution?._recordId || null,
|
|
238
|
-
imageSourceUrl: attachment?.url ||
|
|
279
|
+
imageSourceUrl: attachment?.url || archivedImageKey(row, attachment),
|
|
239
280
|
patientContent: patientContentOf(recommendation),
|
|
240
281
|
};
|
|
241
282
|
});
|
|
@@ -254,14 +295,7 @@ const projectCarouselStatus = (row, sends) => ({
|
|
|
254
295
|
});
|
|
255
296
|
|
|
256
297
|
async function readPatientCarouselStatuses(code) {
|
|
257
|
-
const rows = await
|
|
258
|
-
symptomsId,
|
|
259
|
-
'cluster_recommendations',
|
|
260
|
-
fieldEquals('whatsapp_id', code),
|
|
261
|
-
'Grid view',
|
|
262
|
-
CAROUSEL_STATUS_FIELDS,
|
|
263
|
-
true,
|
|
264
|
-
) || [];
|
|
298
|
+
const rows = await readPatientCarouselsWithArchive(code, CAROUSEL_STATUS_FIELDS);
|
|
265
299
|
const sends = await sendsByFirstResolution(code, rows);
|
|
266
300
|
return rows
|
|
267
301
|
.map((row) => projectCarouselStatus(row, sends))
|
|
@@ -343,7 +377,11 @@ async function getRecommendationCarouselImage({ code, carouselId, cardIndex }) {
|
|
|
343
377
|
const rows = await readPatientCarouselRows(code, [carouselId]);
|
|
344
378
|
const row = rows.find((entry) => (entry._recordId || entry.recordID) === carouselId);
|
|
345
379
|
const attachment = Array.isArray(row?.images) ? row.images[Number(cardIndex)] : null;
|
|
346
|
-
|
|
380
|
+
if (attachment?.url) return { url: attachment.url };
|
|
381
|
+
const key = archivedImageKey(row, attachment);
|
|
382
|
+
if (!key) return null;
|
|
383
|
+
const object = await s3.getObject({ Bucket: runtimeConfig.get('AIRTABLE_ARCHIVE_BUCKET'), Key: key }).promise();
|
|
384
|
+
return { body: Buffer.from(object.Body), contentType: object.ContentType || null };
|
|
347
385
|
}
|
|
348
386
|
|
|
349
387
|
function clearRecommendationCarouselCache() {
|