@peopl-health/nexus 6.0.0-dev.15840 → 6.0.0-dev.15993
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/clinical/providers/BaseLLMProvider.js +4 -3
- package/lib/clinical/tools/schedulePatientReminderTool.js +1 -1
- package/lib/controllers/patientController.js +21 -13
- package/lib/helpers/airtableArchiveHelper.js +7 -1
- package/lib/models/airtableArchiveModel.js +1 -0
- package/lib/services/airtableArchivePlanService.js +12 -5
- package/lib/services/airtableArchiveReadService.js +31 -6
- package/lib/services/airtableArchiveService.js +4 -4
- package/lib/services/escalationReviewService.js +45 -4
- package/lib/services/recommendationCarouselService.js +58 -20
- package/lib/services/teamAlertService.js +13 -7
- package/lib/services/triageHistoryService.js +25 -4
- package/package.json +1 -1
|
@@ -404,6 +404,7 @@ class BaseLLMProvider {
|
|
|
404
404
|
const self = checkIn.reminderId ? `${checkIn.reminderId}${checkIn.dueAt ? `, programado para ${local(checkIn.dueAt)}` : ''}` : null;
|
|
405
405
|
const pending = lines([
|
|
406
406
|
['este check-in', self],
|
|
407
|
+
['tipo', checkIn.type === 'contingencia' ? 'red de contingencia' : 'seguimiento que programaste: esta pregunta todavía no le ha llegado'],
|
|
407
408
|
['lo que querías preguntarle', checkIn.question],
|
|
408
409
|
['por qué quedó abierto', checkIn.concern],
|
|
409
410
|
['qué dato esperabas', checkIn.awaiting],
|
|
@@ -435,9 +436,9 @@ class BaseLLMProvider {
|
|
|
435
436
|
'- Este check-in es el seguimiento que vencía: no cuenta como otro pendiente. Si un seguimiento distinto en la lista de pendientes, o una red activa, ya va a preguntar esto, no programes otro: registra hold con next_check_at null y hold_reason contingency_already_armed.',
|
|
436
437
|
'- Si le escribes, un solo mensaje con una sola pregunta; si otro tema pendiente se responde con esa misma pregunta, intégralo y resuelve las redes que ese mensaje ya cubre. Registra en utility_basis lo que contó o acordó.',
|
|
437
438
|
exchange?.sessionOpen === false
|
|
438
|
-
? 'Si escribes, tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre; entra directo
|
|
439
|
-
: 'Si escribes, le llega como un mensaje normal. Si llevan horas sin hablar, ábrelo con un saludo breve y natural según la hora del día, con el nombre de quien lleva la conversación si lo conoces (a un cuidador cuyo nombre no conoces, sin nombre); luego
|
|
440
|
-
'
|
|
439
|
+
? 'Si escribes, tu texto llega dentro de una plantilla que ya empieza con «Hola {su nombre},»: no saludes ni escribas su nombre; entra directo a lo que quieres saber.'
|
|
440
|
+
: 'Si escribes, le llega como un mensaje normal. Si llevan horas sin hablar, ábrelo con un saludo breve y natural según la hora del día, con el nombre de quien lleva la conversación si lo conoces (a un cuidador cuyo nombre no conoces, sin nombre); luego entra a lo que quieres saber.',
|
|
441
|
+
'En un seguimiento que programaste es la primera vez que se lo preguntas: no digas que ya se lo habías preguntado. En una red, si tu mensaje anterior ya se lo preguntó, dilo en pocas palabras («te había preguntado por…» o «le había preguntado por…», según cómo le hables). Esa única pregunta va por lo que sigue faltando de lo que esperabas saber; si lo que querías preguntarle trae varias, elige la que más importa hoy. Háblale directo a quien lleva la conversación, de tú o de usted, como en la conversación; nunca hables en tercera persona de quien te está leyendo.',
|
|
441
442
|
'No le comentes como novedad algo que no te dijo en el chat: sus respuestas del cuestionario las conoces tú, no son algo que te acaba de contar. No repitas lo que ya le dijiste (por ejemplo, que el equipo ya tiene el aviso) ni des por hecho detalles que no te dio.',
|
|
442
443
|
'Breve, sin listas de señales de alarma y sin mencionar recordatorios, planes ni seguimientos programados.',
|
|
443
444
|
);
|
|
@@ -23,7 +23,7 @@ const definition = {
|
|
|
23
23
|
},
|
|
24
24
|
reminder_description: {
|
|
25
25
|
type: 'string',
|
|
26
|
-
description: 'Short description of what the reminder is for (e.g. \'tomar ondansetrón antes del desayuno\', \'preguntarle cómo amaneció del dolor de cabeza\'). This becomes the WhatsApp message body. For a Programme activity name the format — la charla, tu sesión colectiva, tu sesión individual — never a bare \'tu sesión\': the text stays in the conversation and is what a later turn reads to tell them apart.',
|
|
26
|
+
description: 'Short description of what the reminder is for (e.g. \'tomar ondansetrón antes del desayuno\', \'preguntarle cómo amaneció del dolor de cabeza\'). This becomes the WhatsApp message body. For seguimiento, one question only — the one that matters most on that date — written as asked for the first time (never «te había preguntado»). For a Programme activity name the format — la charla, tu sesión colectiva, tu sesión individual — never a bare \'tu sesión\': the text stays in the conversation and is what a later turn reads to tell them apart.',
|
|
27
27
|
},
|
|
28
28
|
reminder_type: {
|
|
29
29
|
type: 'string',
|
|
@@ -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,
|
|
@@ -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,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
|
|
|
@@ -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 } 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) {
|
|
@@ -52,6 +52,7 @@ const { getEscalationApprover, listEscalationApprovers } = require('./physicianS
|
|
|
52
52
|
const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
|
|
53
53
|
const { effectiveUrgencyOf, patientTimerMinutes, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
|
|
54
54
|
const { caseTaskLive, scheduleCaseSync } = require('./escalationCaseTaskService');
|
|
55
|
+
const { groupConfigured, sendTeamAlert, teamChannelConfigured } = require('./teamAlertService');
|
|
55
56
|
|
|
56
57
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
57
58
|
|
|
@@ -89,6 +90,7 @@ const STAFF_ORIGINS = ['whatsapp_platform', 'instruction', 'system'];
|
|
|
89
90
|
const PRE_DECISION_STATUSES = ['open', 'documenting', 'draft_ready', 'handing_off', 'awaiting_doctor'];
|
|
90
91
|
const ALERT_OPERATOR = 'bot:escalationAlert';
|
|
91
92
|
const AIRTABLE_TRANSPORT = 'airtable';
|
|
93
|
+
const NOT_RECORDED = 'no se registró en Airtable';
|
|
92
94
|
const RECLASSIFIABLE_STATUSES = [...DOCUMENTING_STATUSES, 'awaiting_doctor'];
|
|
93
95
|
const SAME_URGENCY = 'The review is already at that urgency';
|
|
94
96
|
const RECLASSIFY_CHANGED = 'The review changed while you were reclassifying it; read it again before changing the urgency';
|
|
@@ -1251,16 +1253,55 @@ async function fallbackRecipient() {
|
|
|
1251
1253
|
return phone ? { name: null, email: null, phone } : soleApprover();
|
|
1252
1254
|
}
|
|
1253
1255
|
|
|
1254
|
-
|
|
1256
|
+
const oneLine = (value) => inlineOf(value).replace(/\s+/g, ' ');
|
|
1257
|
+
|
|
1258
|
+
// A brief notice for the whole team; a patient record that cannot be read never holds it back.
|
|
1259
|
+
async function teamFallbackNotice(review, urgencyLevel, alarmId) {
|
|
1260
|
+
let identity = { patientName: '', treatingDoctor: '' };
|
|
1261
|
+
try {
|
|
1262
|
+
identity = doctorIdentity(await getPatientInformation(review.patientCode));
|
|
1263
|
+
} catch (error) {
|
|
1264
|
+
logger.error('[EscalationReview] The patient record could not be read for the team notice', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
1265
|
+
}
|
|
1266
|
+
const patient = oneLine(identity.patientName) || 'sin nombre registrado';
|
|
1267
|
+
const doctor = oneLine(identity.treatingDoctor) || 'sin médico registrado';
|
|
1268
|
+
const link = conversationLink(review.patientCode) || 'abrir el chat en la plataforma';
|
|
1269
|
+
const alarm = (alarmId && (review.alarms ?? []).find((raised) => raised.alarmId === alarmId))
|
|
1270
|
+
?? (review.alarms ?? []).findLast((raised) => raised.urgencyLevel === urgencyLevel) ?? review.alarms?.at(-1);
|
|
1271
|
+
const what = [urgencyLevel.toUpperCase(), oneLine(alarm?.symptom), NOT_RECORDED].filter(Boolean).join(' · ');
|
|
1272
|
+
return {
|
|
1273
|
+
body: `⚠️ ${ALERT_MARKS[urgencyLevel]} ${what}\n${patient} (${doctor})\n${link}`,
|
|
1274
|
+
template: { 1: what, 2: patient, 3: doctor, 4: link },
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
async function alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId) {
|
|
1279
|
+
try {
|
|
1280
|
+
const result = await sendTeamAlert({ message: await teamFallbackNotice(review, urgencyLevel, alarmId), operator: ALERT_OPERATOR, notice: true });
|
|
1281
|
+
const missed = result.phones.filter((phone) => !phone.delivered).length + (groupConfigured() && !result.group.delivered ? 1 : 0);
|
|
1282
|
+
if (result.delivered && missed) logger.warn('[EscalationReview] The team notice missed some recipients', { escalationReviewId: String(review._id), delivered: result.delivered, missed });
|
|
1283
|
+
return result.delivered ? { transport: 'team' } : null;
|
|
1284
|
+
} catch (error) {
|
|
1285
|
+
logger.error('[EscalationReview] The team notice failed; falling back to one phone', { escalationReviewId: String(review._id), error: redactedError(error) });
|
|
1286
|
+
return null;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
async function alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId) {
|
|
1291
|
+
const recipient = await fallbackRecipient();
|
|
1292
|
+
const { approver, message } = await prepareDoctorAlert(review, urgencyLevel, { recipient, alarmId });
|
|
1293
|
+
return { physicianEmail: approver.email, ...(await sendDoctorAlert({ message, approver, operator: ALERT_OPERATOR })) };
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1255
1296
|
async function alertWithoutEmergencyRow({ reviewId, alarmId = null, urgencyLevel, now = new Date() }) {
|
|
1256
1297
|
if (escalationApproverAlertLive() || !ALERT_MARKS[urgencyLevel]) return null;
|
|
1257
1298
|
let review;
|
|
1258
1299
|
let delivery;
|
|
1259
1300
|
try {
|
|
1260
1301
|
review = await loadReview(reviewIdOf(reviewId));
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1302
|
+
// Airtable alerts the team only once its emergencies row exists; a team notice that reached no one falls back to one phone.
|
|
1303
|
+
delivery = (teamChannelConfigured() && await alertTeamWithoutEmergencyRow(review, urgencyLevel, alarmId))
|
|
1304
|
+
|| await alertOneWithoutEmergencyRow(review, urgencyLevel, alarmId);
|
|
1264
1305
|
} catch (error) {
|
|
1265
1306
|
delivery = { error: redactedError(error) };
|
|
1266
1307
|
logger.error('[EscalationReview] The alert for a missing emergencies row was not sent', { escalationReviewId: String(reviewId), urgencyLevel, error: delivery.error });
|
|
@@ -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() {
|
|
@@ -9,6 +9,7 @@ const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
|
9
9
|
const WHAPI_MESSAGES_URL = 'https://gate.whapi.cloud/messages/text';
|
|
10
10
|
const REQUEST_TIMEOUT_MS = 15000;
|
|
11
11
|
const ALERT_TEMPLATE_KEY = 'ESCALATION_TEAM_ALERT_CONTENT_SID';
|
|
12
|
+
const NOTICE_TEMPLATE_KEY = 'ESCALATION_TEAM_NOTICE_CONTENT_SID';
|
|
12
13
|
|
|
13
14
|
const getMessaging = () => require('../core/NexusMessaging');
|
|
14
15
|
|
|
@@ -26,10 +27,10 @@ function teamPhones() {
|
|
|
26
27
|
}
|
|
27
28
|
|
|
28
29
|
// Inside the 24-hour window the plain text goes out; outside it, the approved alert template.
|
|
29
|
-
async function sendAlertTo({ code, message, operator }) {
|
|
30
|
+
async function sendAlertTo({ code, message, operator, templateKey }) {
|
|
30
31
|
const inWindow = await isWithin24HourWindow(code);
|
|
31
|
-
const contentSid = inWindow ? null : runtimeConfig.get(
|
|
32
|
-
if (!inWindow && !contentSid) throw new Error(`${
|
|
32
|
+
const contentSid = inWindow ? null : runtimeConfig.get(templateKey);
|
|
33
|
+
if (!inWindow && !contentSid) throw new Error(`${templateKey} is not configured`);
|
|
33
34
|
const outgoing = inWindow
|
|
34
35
|
? { code, body: message.body, triggeredBy: operator }
|
|
35
36
|
: { code, contentSid, variables: message.template, triggeredBy: operator };
|
|
@@ -39,10 +40,14 @@ async function sendAlertTo({ code, message, operator }) {
|
|
|
39
40
|
return { transport: inWindow ? 'text' : 'template', messageId: result?.messageId || null };
|
|
40
41
|
}
|
|
41
42
|
|
|
43
|
+
const groupConfigured = () => Boolean(runtimeConfig.get('WHAPI_TOKEN') && runtimeConfig.get('ESCALATION_TEAM_GROUP_ID'));
|
|
44
|
+
|
|
45
|
+
const teamChannelConfigured = () => groupConfigured() || teamPhones().length > 0;
|
|
46
|
+
|
|
42
47
|
async function sendToGroup(body) {
|
|
48
|
+
if (!groupConfigured()) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
|
|
43
49
|
const token = runtimeConfig.get('WHAPI_TOKEN');
|
|
44
50
|
const group = runtimeConfig.get('ESCALATION_TEAM_GROUP_ID');
|
|
45
|
-
if (!token || !group) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
|
|
46
51
|
try {
|
|
47
52
|
const res = await axios({
|
|
48
53
|
url: WHAPI_MESSAGES_URL,
|
|
@@ -61,12 +66,13 @@ async function sendToGroup(body) {
|
|
|
61
66
|
|
|
62
67
|
// Alerts the team group and every on-call phone. One failed recipient never stops the others,
|
|
63
68
|
// and nothing throws: the caller records what reached whom.
|
|
64
|
-
async function sendTeamAlert({ message, operator }) {
|
|
69
|
+
async function sendTeamAlert({ message, operator, notice = false }) {
|
|
70
|
+
const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
|
|
65
71
|
const group = await sendToGroup(message.body);
|
|
66
72
|
const phones = [];
|
|
67
73
|
for (const code of teamPhones()) {
|
|
68
74
|
try {
|
|
69
|
-
phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator })) });
|
|
75
|
+
phones.push({ code, delivered: true, error: null, ...(await sendAlertTo({ code, message, operator, templateKey })) });
|
|
70
76
|
} catch (error) {
|
|
71
77
|
phones.push({ code, delivered: false, transport: null, messageId: null, error: redacted(error) });
|
|
72
78
|
}
|
|
@@ -76,4 +82,4 @@ async function sendTeamAlert({ message, operator }) {
|
|
|
76
82
|
return { group, phones, delivered };
|
|
77
83
|
}
|
|
78
84
|
|
|
79
|
-
module.exports = { sendTeamAlert, teamPhones };
|
|
85
|
+
module.exports = { groupConfigured, sendTeamAlert, teamChannelConfigured, teamPhones };
|
|
@@ -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(
|