@peopl-health/nexus 6.0.2 → 6.0.4

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.
@@ -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', fieldEquals('whatsapp_id', code), null, undefined, true);
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: referenceFilter }).firstPage(),
249
+ () => getBase(baseID)(referenceTable).select({ filterByFormula }).firstPage(),
245
250
  'addLinkedRecord'
246
251
  );
247
252
 
@@ -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', fieldEquals('whatsapp_id', code), 'Grid view', fields, true),
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(${fieldEquals('whatsapp_id', code)},${recordIdIn(missingIds)})`,
211
+ `AND(${patientCarousels(code)},${recordIdIn(missingIds)})`,
207
212
  'Grid view',
208
213
  CAROUSEL_FIELDS,
209
214
  true,
@@ -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,7 +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
+ threadBody: [`⏰ ${level} sin tomar · ${deadline}`, question && `Falta saber: ${question}`, note, `Qué hacer: ${action}`].filter(Boolean).join('\n'),
106
106
  template: {
107
107
  1: `${level}, ${deadline}${clock.symptom ? ` (${clock.symptom})` : ''}`,
108
108
  2: patient,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "6.0.2",
3
+ "version": "6.0.4",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",