@peopl-health/nexus 6.0.1 → 6.0.3
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/services/clinicalAirtableService.js +2 -1
- package/lib/clinical/services/patientIdentityService.js +7 -1
- package/lib/config/airtableConfig.js +4 -0
- package/lib/config/programConfig.js +14 -0
- package/lib/services/airtableService.js +7 -2
- package/lib/services/characterizationOutcomeService.js +10 -6
- package/lib/services/recommendationCarouselService.js +9 -4
- package/lib/services/teamAlertService.js +4 -3
- package/lib/services/triageHistoryService.js +5 -3
- package/lib/services/untakenAlertService.js +1 -0
- package/package.json +1 -1
|
@@ -4,6 +4,7 @@ const { decodeUnicodeEscapes } = require('../../utils/sanitizerUtils');
|
|
|
4
4
|
|
|
5
5
|
const { Monitoreo_ID, Estado_General_ID, Symptoms_ID } = require('../../config/airtableConfig');
|
|
6
6
|
const runtimeConfig = require('../../config/runtimeConfig');
|
|
7
|
+
const { programSourceFormula } = require('../../config/programConfig');
|
|
7
8
|
const airtableService = require('../../services/airtableService');
|
|
8
9
|
const { logger } = require('../../utils/logger');
|
|
9
10
|
const { isBenchMode } = require('../../utils/benchModeHelper');
|
|
@@ -97,7 +98,7 @@ async function auditedWrite({ trace, code, table, write, isLive = null, skip = n
|
|
|
97
98
|
}
|
|
98
99
|
|
|
99
100
|
async function findMonitoreoPatientRecordId(code) {
|
|
100
|
-
const patient = await airtableService.getRecordByFilter(Monitoreo_ID, 'estado_general', `{whatsapp_id} = "${code}"`);
|
|
101
|
+
const patient = await airtableService.getRecordByFilter(Monitoreo_ID, 'estado_general', `AND({whatsapp_id} = "${code}", ${programSourceFormula({ allowBlank: true })})`);
|
|
101
102
|
return patient?.[0]?.recordID || null;
|
|
102
103
|
}
|
|
103
104
|
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
const { PROGRAM_TAGGED_BASES } = require('../../config/airtableConfig');
|
|
1
2
|
const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
|
|
3
|
+
const { programSourceFormula } = require('../../config/programConfig');
|
|
2
4
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
3
5
|
|
|
4
6
|
const pendingLookups = new Map();
|
|
@@ -21,8 +23,12 @@ async function resolvePatientIdentity(baseId, code) {
|
|
|
21
23
|
return lookup;
|
|
22
24
|
}
|
|
23
25
|
|
|
26
|
+
const identityFormula = (baseId, code) => (PROGRAM_TAGGED_BASES.has(baseId)
|
|
27
|
+
? `AND(${fieldEquals('whatsapp_id', code)}, ${programSourceFormula({ allowBlank: true })})`
|
|
28
|
+
: fieldEquals('whatsapp_id', code));
|
|
29
|
+
|
|
24
30
|
async function readPatientIdentity(baseId, code) {
|
|
25
|
-
const records = await getRecordByFilter(baseId, 'estado_general',
|
|
31
|
+
const records = await getRecordByFilter(baseId, 'estado_general', identityFormula(baseId, code), null, undefined, true);
|
|
26
32
|
if (!Array.isArray(records)) throw identityError('unavailable');
|
|
27
33
|
if (!records.length) return { kind: 'missing' };
|
|
28
34
|
if (records.length > 1) return { kind: 'ambiguous', candidateCount: records.length };
|
|
@@ -61,7 +61,11 @@ const BASE_MAP = {
|
|
|
61
61
|
estado_general: Estado_General_ID
|
|
62
62
|
};
|
|
63
63
|
|
|
64
|
+
// Bases whose `estado_general` has `source`; Historial Clínico has none.
|
|
65
|
+
const PROGRAM_TAGGED_BASES = new Set([Monitoreo_ID, Symptoms_ID, Estado_General_ID, Follow_Up_ID]);
|
|
66
|
+
|
|
64
67
|
module.exports = {
|
|
68
|
+
PROGRAM_TAGGED_BASES,
|
|
65
69
|
airtable,
|
|
66
70
|
config: airtableConfig,
|
|
67
71
|
getApiKey,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
const { escapeFormulaValue } = require('../helpers/airtableFormulaHelper');
|
|
1
2
|
const runtimeConfig = require('./runtimeConfig');
|
|
2
3
|
|
|
3
4
|
// Symptoms/Monitoreo use `programa AMI`; Config uses `programa_AMI`.
|
|
@@ -12,9 +13,22 @@ function configureProgram({ source, configSource } = {}) {
|
|
|
12
13
|
if (configSource) runtimeConfig.set('PROGRAM_CONFIG_SOURCE', String(configSource));
|
|
13
14
|
}
|
|
14
15
|
|
|
16
|
+
// `allowBlank` keeps rows whose source was never filled, so they read as before.
|
|
17
|
+
function programSourceFormula({ field = 'source', allowBlank = false } = {}) {
|
|
18
|
+
const match = `FIND('${escapeFormulaValue(programSource())}', ARRAYJOIN({${field}}))`;
|
|
19
|
+
return allowBlank ? `OR(${match}, ARRAYJOIN({${field}})='')` : match;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function rowInProgram(row, field = 'source') {
|
|
23
|
+
const sources = [].concat(row?.[field] ?? []).filter(Boolean);
|
|
24
|
+
return !sources.length || sources.some((source) => String(source).includes(programSource()));
|
|
25
|
+
}
|
|
26
|
+
|
|
15
27
|
module.exports = {
|
|
16
28
|
DEFAULT_PROGRAM_SOURCE,
|
|
17
29
|
configureProgram,
|
|
18
30
|
programConfigSource,
|
|
19
31
|
programSource,
|
|
32
|
+
programSourceFormula,
|
|
33
|
+
rowInProgram,
|
|
20
34
|
};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const axios = require('axios');
|
|
2
2
|
|
|
3
|
-
const { airtable, getApiKey, getRequestTimeoutMs } = require('../config/airtableConfig');
|
|
3
|
+
const { PROGRAM_TAGGED_BASES, airtable, getApiKey, getRequestTimeoutMs } = require('../config/airtableConfig');
|
|
4
|
+
const { programSourceFormula } = require('../config/programConfig');
|
|
4
5
|
|
|
5
6
|
const { logger } = require('../utils/logger');
|
|
6
7
|
const { isBenchMode } = require('../utils/benchModeHelper');
|
|
@@ -240,8 +241,12 @@ async function addLinkedRecord(baseID, targetTable, fields, linkConfig, context
|
|
|
240
241
|
try {
|
|
241
242
|
if (linkConfig) {
|
|
242
243
|
const { referenceTable, referenceFilter, linkFieldName } = linkConfig;
|
|
244
|
+
// A number can be a patient of both programs; link only this program's row.
|
|
245
|
+
const filterByFormula = referenceTable === 'estado_general' && PROGRAM_TAGGED_BASES.has(baseID)
|
|
246
|
+
? `AND(${referenceFilter}, ${programSourceFormula({ allowBlank: true })})`
|
|
247
|
+
: referenceFilter;
|
|
243
248
|
const referenceRecords = await withAirtableRetry(
|
|
244
|
-
() => getBase(baseID)(referenceTable).select({ filterByFormula
|
|
249
|
+
() => getBase(baseID)(referenceTable).select({ filterByFormula }).firstPage(),
|
|
245
250
|
'addLinkedRecord'
|
|
246
251
|
);
|
|
247
252
|
|
|
@@ -117,7 +117,9 @@ async function handOff(review, clock, outcome, now) {
|
|
|
117
117
|
return true;
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
+
// Only the first handoff reaches the group; a later update to the doctor shows in the platform.
|
|
120
121
|
async function sendHandoffNotice(review, clock, outcome) {
|
|
122
|
+
if (outcome.update) return;
|
|
121
123
|
try {
|
|
122
124
|
await postHandoffNotice(review, clock, outcome);
|
|
123
125
|
} catch (error) {
|
|
@@ -136,7 +138,8 @@ async function sendGaveUpNotice(review, clock) {
|
|
|
136
138
|
'Qué hacer: revisar el caso y pasarlo al médico a mano',
|
|
137
139
|
link,
|
|
138
140
|
].filter(Boolean).join('\n');
|
|
139
|
-
const
|
|
141
|
+
const threadBody = '⚠️ No pudo pasar solo al médico: pasarlo a mano';
|
|
142
|
+
const sent = await sendGroupNotice(body, await readGroupMessageId(clock.emergencyRecordId, review.patientCode), threadBody);
|
|
140
143
|
await audit(review, { action: 'auto_handoff_gave_up', urgencyLevel: clock.level, delivered: sent.delivered });
|
|
141
144
|
} catch (error) {
|
|
142
145
|
logger.error('[CharacterizationOutcome] The give-up notice was not sent', {
|
|
@@ -145,19 +148,19 @@ async function sendGaveUpNotice(review, clock) {
|
|
|
145
148
|
}
|
|
146
149
|
}
|
|
147
150
|
|
|
148
|
-
async function postHandoffNotice(review, clock, { note
|
|
151
|
+
async function postHandoffNotice(review, clock, { note }) {
|
|
149
152
|
const { patient, doctor, link } = await teamAlertIdentity(review);
|
|
150
153
|
const taken = await takenOf(review, clock);
|
|
151
|
-
const header =
|
|
154
|
+
const header = taken ? '📋 Pasó al médico' : '📋 Pasó al médico · todavía sin tomar';
|
|
152
155
|
const body = [
|
|
153
|
-
|
|
156
|
+
header,
|
|
154
157
|
[`${patient} (${doctor})`, clock.symptom].filter(Boolean).join(' · '),
|
|
155
158
|
note,
|
|
156
159
|
!taken && 'Qué hacer: escribir o llamar a la paciente si nadie lo ha hecho',
|
|
157
160
|
link,
|
|
158
161
|
].filter(Boolean).join('\n');
|
|
159
162
|
const quoted = await readGroupMessageId(clock.emergencyRecordId, review.patientCode);
|
|
160
|
-
const sent = await sendGroupNotice(body, quoted);
|
|
163
|
+
const sent = await sendGroupNotice(body, quoted, [header, note].filter(Boolean).join('\n'));
|
|
161
164
|
await audit(review, { action: 'handoff_notice_sent', urgencyLevel: clock.level, delivered: sent.delivered });
|
|
162
165
|
}
|
|
163
166
|
|
|
@@ -173,6 +176,7 @@ async function graveMessage(review, clock, entries) {
|
|
|
173
176
|
`Qué hacer: ${action}`,
|
|
174
177
|
link,
|
|
175
178
|
].join('\n'),
|
|
179
|
+
threadBody: `❗ Falta dato grave: ${missing}\nQué hacer: ${action}`,
|
|
176
180
|
template: { 1: `${LEVEL_LABELS[clock.level]}, falta dato grave${clock.symptom ? ` (${clock.symptom})` : ''}`, 2: patient, 3: doctor, 4: `Falta: ${missing} · ${action}`, 5: link },
|
|
177
181
|
};
|
|
178
182
|
}
|
|
@@ -205,7 +209,7 @@ async function sendDueGraveAlerts(review, clock, entries, now) {
|
|
|
205
209
|
let delivered = 0;
|
|
206
210
|
try {
|
|
207
211
|
delivered = taken
|
|
208
|
-
? Number((await sendGroupNotice(message.body, quoted)).delivered)
|
|
212
|
+
? Number((await sendGroupNotice(message.body, quoted, message.threadBody)).delivered)
|
|
209
213
|
: (await sendTeamAlert({ message, operator: OPERATOR, quoted })).delivered;
|
|
210
214
|
} catch (error) {
|
|
211
215
|
logger.error('[CharacterizationOutcome] The grave alert was not sent', {
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
const { Symptoms_ID: symptomsId } = require('../config/airtableConfig');
|
|
2
2
|
const runtimeConfig = require('../config/runtimeConfig');
|
|
3
|
+
const { programSourceFormula, rowInProgram } = require('../config/programConfig');
|
|
3
4
|
const { s3 } = require('../config/awsConfig');
|
|
4
5
|
const { logger } = require('../utils/logger');
|
|
5
6
|
const { firstOf } = require('../utils/coercionUtils');
|
|
@@ -41,7 +42,7 @@ const CAROUSEL_STATUS_FIELDS = [
|
|
|
41
42
|
|
|
42
43
|
const RESOLUTION_FIELDS = ['rank', 'element_name_short'];
|
|
43
44
|
// 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)'];
|
|
45
|
+
const VIEW_FIELDS = ['whatsapp_id', 'tipo (from triaje_symptoms)', 'source'];
|
|
45
46
|
const FIRST_RESOLUTION_VARIABLE = '2';
|
|
46
47
|
const UNSUCCESSFUL_SEND_STATUSES = ['failed', 'undelivered'];
|
|
47
48
|
const carouselCache = new MapCache({ maxSize: 30, ttl: CACHE_TTL_MS });
|
|
@@ -170,6 +171,7 @@ async function readArchived(read, params) {
|
|
|
170
171
|
try {
|
|
171
172
|
return await read({ baseId: symptomsId, ...params });
|
|
172
173
|
} catch (error) {
|
|
174
|
+
if (error.code === 'archive_base_unmapped') return [];
|
|
173
175
|
logger.error('[recommendationCarouselService] Archive read failed, serving live rows only', { table: params.tableName, error: error.message });
|
|
174
176
|
return [];
|
|
175
177
|
}
|
|
@@ -177,11 +179,14 @@ async function readArchived(read, params) {
|
|
|
177
179
|
|
|
178
180
|
// Same rule as the live `Grid view`: the patient's own carousels from production triages.
|
|
179
181
|
const inLiveView = (code) => (row) => firstOf(row.whatsapp_id) === code
|
|
180
|
-
&& [].concat(row['tipo (from triaje_symptoms)'] ?? []).includes('prod')
|
|
182
|
+
&& [].concat(row['tipo (from triaje_symptoms)'] ?? []).includes('prod')
|
|
183
|
+
&& rowInProgram(row);
|
|
184
|
+
|
|
185
|
+
const patientCarousels = (code) => `AND(${fieldEquals('whatsapp_id', code)}, ${programSourceFormula({ allowBlank: true })})`;
|
|
181
186
|
|
|
182
187
|
async function readPatientCarouselsWithArchive(code, fields) {
|
|
183
188
|
const [live, archived] = await Promise.all([
|
|
184
|
-
getRecordByFilter(symptomsId, 'cluster_recommendations',
|
|
189
|
+
getRecordByFilter(symptomsId, 'cluster_recommendations', patientCarousels(code), 'Grid view', fields, true),
|
|
185
190
|
readArchived(findArchivedByPatient, { tableName: 'cluster_recommendations', whatsappId: code, fields: [...fields, ...VIEW_FIELDS] }),
|
|
186
191
|
]);
|
|
187
192
|
return mergeArchivedRows(live || [], archived.filter(inLiveView(code)));
|
|
@@ -203,7 +208,7 @@ async function readPatientCarouselRows(code, ids) {
|
|
|
203
208
|
const rows = await getRecordByFilter(
|
|
204
209
|
symptomsId,
|
|
205
210
|
'cluster_recommendations',
|
|
206
|
-
`AND(${
|
|
211
|
+
`AND(${patientCarousels(code)},${recordIdIn(missingIds)})`,
|
|
207
212
|
'Grid view',
|
|
208
213
|
CAROUSEL_FIELDS,
|
|
209
214
|
true,
|
|
@@ -109,10 +109,11 @@ async function postToGroup(body, quoted) {
|
|
|
109
109
|
return { delivered: false, error: `whapi responded ${res.status}` };
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
-
|
|
112
|
+
// A reply in the alarm's thread carries `threadBody`, which leaves out what the quoted alert already says.
|
|
113
|
+
async function sendToGroup(body, quoted = null, threadBody = null) {
|
|
113
114
|
if (!groupConfigured()) return { delivered: false, error: 'WHAPI_TOKEN or ESCALATION_TEAM_GROUP_ID is not configured' };
|
|
114
115
|
try {
|
|
115
|
-
const sent = await postToGroup(body, quoted);
|
|
116
|
+
const sent = await postToGroup(quoted && threadBody ? threadBody : body, quoted);
|
|
116
117
|
// A quoted message Whapi no longer knows must not cost the alert: it goes out unthreaded.
|
|
117
118
|
return sent.delivered || !quoted ? sent : await postToGroup(body, null);
|
|
118
119
|
} catch (error) {
|
|
@@ -123,7 +124,7 @@ async function sendToGroup(body, quoted = null) {
|
|
|
123
124
|
// Alerts the group and the on-call phones for `level` (all without one); one failed recipient never stops the others and nothing throws.
|
|
124
125
|
async function sendTeamAlert({ message, operator, level = null, notice = false, quoted = null }) {
|
|
125
126
|
const templateKey = notice ? NOTICE_TEMPLATE_KEY : ALERT_TEMPLATE_KEY;
|
|
126
|
-
const group = await sendToGroup(message.body, quoted);
|
|
127
|
+
const group = await sendToGroup(message.body, quoted, message.threadBody);
|
|
127
128
|
const phones = [];
|
|
128
129
|
for (const code of await teamPhones(level)) {
|
|
129
130
|
try {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
const { Symptoms_ID } = require('../config/airtableConfig');
|
|
2
|
+
const { programSourceFormula, rowInProgram } = require('../config/programConfig');
|
|
2
3
|
|
|
3
4
|
const { MapCache } = require('../utils/MapCache');
|
|
4
5
|
const { logger } = require('../utils/logger');
|
|
@@ -36,6 +37,7 @@ const readArchived = async (read, params) => {
|
|
|
36
37
|
try {
|
|
37
38
|
return await read({ baseId: Symptoms_ID, ...params });
|
|
38
39
|
} catch (error) {
|
|
40
|
+
if (error.code === 'archive_base_unmapped') return [];
|
|
39
41
|
logger.error('[triageHistoryService] Archive read failed, serving live rows only', { table: params.tableName, error: error.message });
|
|
40
42
|
return [];
|
|
41
43
|
}
|
|
@@ -43,11 +45,11 @@ const readArchived = async (read, params) => {
|
|
|
43
45
|
|
|
44
46
|
const readPatientHistory = async (code) => {
|
|
45
47
|
const [live, archived, archivedSymptoms] = await Promise.all([
|
|
46
|
-
getRecordByFilter(Symptoms_ID, 'triaje_symptoms', fieldEquals('whatsapp_id', code), 'Grid view', TRIAGE_FIELDS, true),
|
|
47
|
-
readArchived(findArchivedByPatient, { tableName: 'triaje_symptoms', whatsappId: code, fields: TRIAGE_FIELDS }),
|
|
48
|
+
getRecordByFilter(Symptoms_ID, 'triaje_symptoms', `AND(${fieldEquals('whatsapp_id', code)}, ${programSourceFormula({ allowBlank: true })})`, 'Grid view', TRIAGE_FIELDS, true),
|
|
49
|
+
readArchived(findArchivedByPatient, { tableName: 'triaje_symptoms', whatsappId: code, fields: [...TRIAGE_FIELDS, 'source'] }),
|
|
48
50
|
readArchived(findArchivedByPatient, { tableName: 'symptoms', whatsappId: code, fields: [...SYMPTOM_FIELDS, SYMPTOM_TRIAGE_FIELD] }),
|
|
49
51
|
]);
|
|
50
|
-
const ownRows = archived.filter((row) => firstOf(row.whatsapp_id) === code);
|
|
52
|
+
const ownRows = archived.filter((row) => firstOf(row.whatsapp_id) === code && rowInProgram(row));
|
|
51
53
|
const archivedSymptomIdsByTriage = new Map();
|
|
52
54
|
[...archivedSymptoms].sort((a, b) => new Date(a._createdTime) - new Date(b._createdTime)).forEach((row) => {
|
|
53
55
|
linkedIdsOf(row[SYMPTOM_TRIAGE_FIELD]).forEach((triageId) => {
|
|
@@ -102,6 +102,7 @@ async function untakenMessage(review, clock, stage, now) {
|
|
|
102
102
|
`Qué hacer: ${action}`,
|
|
103
103
|
link,
|
|
104
104
|
].filter(Boolean).join('\n'),
|
|
105
|
+
threadBody: [`⏰ ${level} sin tomar · ${deadline}`, question && `Falta saber: ${question}`, note].filter(Boolean).join('\n'),
|
|
105
106
|
template: {
|
|
106
107
|
1: `${level}, ${deadline}${clock.symptom ? ` (${clock.symptom})` : ''}`,
|
|
107
108
|
2: patient,
|