@peopl-health/nexus 5.59.3 → 5.59.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.
@@ -1,5 +1,5 @@
1
+ const { resolvePatientIdentity } = require('../services/patientIdentityService');
1
2
  const { Follow_Up_ID } = require('../../config/airtableConfig');
2
- const { getRecordByFilter } = require('../../services/airtableService');
3
3
  const { safeParse } = require('../../utils/jsonUtils');
4
4
 
5
5
  const CONTEXT_FIELD = 'clinical-context-json';
@@ -34,15 +34,14 @@ function richestProfile(records) {
34
34
  }
35
35
 
36
36
  async function readClinicalProfile(code) {
37
- const safeCode = String(code).replace(/'/g, '');
38
- let records;
39
37
  try {
40
- records = await getRecordByFilter(Follow_Up_ID, 'estado_general', `{whatsapp_id}='${safeCode}'`);
38
+ const identity = await resolvePatientIdentity(Follow_Up_ID, code);
39
+ if (identity.kind === 'missing') return null;
40
+ if (identity.kind !== 'resolved') return undefined;
41
+ return richestProfile([identity.record]);
41
42
  } catch {
42
43
  return undefined;
43
44
  }
44
- if (!Array.isArray(records)) return undefined;
45
- return richestProfile(records);
46
45
  }
47
46
 
48
47
  module.exports = { readClinicalProfile, richestProfile };
@@ -2,6 +2,7 @@ const { pairTriageSymptoms } = require('../helpers/triageSymptomsHelper');
2
2
  const { handlePendingFunctionCalls: handlePendingFunctionCallsUtil } = require('../providers/OpenAIResponsesProviderTools');
3
3
 
4
4
  const { assembleRiskHeadline } = require('../services/riskHeadlineService');
5
+ const { resolvePatientIdentity, identityError } = require('../services/patientIdentityService');
5
6
  const { Follow_Up_ID } = require('../../config/airtableConfig');
6
7
  const runtimeConfig = require('../../config/runtimeConfig');
7
8
 
@@ -13,6 +14,7 @@ const { getMessageTools, formatMessage } = require('../../helpers/messageHelper'
13
14
  const { safeParse, isPlainObject } = require('../../utils/jsonUtils');
14
15
  const { sanitizeInlineText } = require('../../utils/sanitizerUtils');
15
16
  const { getRecordByFilter } = require('../../services/airtableService');
17
+ const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
16
18
  const { getMessages, countMessages } = require('../../services/messageService');
17
19
  const { getTurnScopedToolNames, getReplayArgsByTool } = require('../../services/toolRegistryService');
18
20
  const { CURRENT_TURN } = require('../promptPlacement');
@@ -238,15 +240,15 @@ class DefaultMemoryManager extends MemoryManager {
238
240
 
239
241
  async _getClinicalContext(whatsappId) {
240
242
  try {
241
- const [clinicalRecords, symptomsRecords] = await Promise.all([
242
- getRecordByFilter(Follow_Up_ID, 'estado_general', `{whatsapp_id}='${whatsappId}'`),
243
- getRecordByFilter(Follow_Up_ID, 'all_triages_last_month', `{whatsapp_id}='${whatsappId}'`)
244
- ]);
243
+ const identity = await resolvePatientIdentity(Follow_Up_ID, whatsappId);
244
+ if (identity.kind === 'ambiguous') throw identityError(identity.kind);
245
+ const record = identity.record || {};
246
+ const symptomsRecords = await getRecordByFilter(Follow_Up_ID, 'all_triages_last_month', fieldEquals('whatsapp_id', whatsappId));
245
247
 
246
- const clinicalContext = clinicalRecords?.[0]?.['clinical-context-json']
247
- ? JSON.parse(clinicalRecords[0]['clinical-context-json'])
248
+ const clinicalContext = record['clinical-context-json']
249
+ ? JSON.parse(record['clinical-context-json'])
248
250
  : null;
249
- const treatingPhysician = sanitizeInlineText(clinicalRecords?.[0]?.doctor || '', Infinity);
251
+ const treatingPhysician = sanitizeInlineText(record.doctor || '', Infinity);
250
252
 
251
253
  const sortedSymptoms = symptomsRecords?.filter(r => r.Date)
252
254
  .sort((a, b) => new Date(b.Date) - new Date(a.Date)).slice(0, 3) || [];
@@ -6,10 +6,12 @@ const { Monitoreo_ID, Estado_General_ID, Symptoms_ID } = require('../../config/a
6
6
  const runtimeConfig = require('../../config/runtimeConfig');
7
7
  const airtableService = require('../../services/airtableService');
8
8
  const { logger } = require('../../utils/logger');
9
+ const { isBenchMode } = require('../../utils/benchModeHelper');
9
10
  const { fieldEquals, recordIdIn } = require('../../helpers/airtableFormulaHelper');
10
11
  const { CLOSED_REQUEST_STATUSES, needsRequestAttention } = require('../../helpers/patientTaskRulesHelper');
11
12
  const { phoneDigits } = require('../../helpers/whatsappHelper');
12
13
  const { WriteClaimStore } = require('./writeClaimStore');
14
+ const { requirePatientIdentity } = require('./patientIdentityService');
13
15
 
14
16
  const MIRROR_ATTEMPTS = 2;
15
17
  const INTAKE_WINDOW_MS = 15 * 60 * 1000;
@@ -56,7 +58,7 @@ const INTAKE_SOURCE_TO_AIRTABLE = {
56
58
 
57
59
  async function auditedWrite({ trace, code, table, write, isLive = null, skip = null, meta = null }) {
58
60
  const entry = { table, at: new Date().toISOString(), ok: false };
59
- if (skip) {
61
+ if (skip && typeof skip !== 'function') {
60
62
  entry.skipped = skip;
61
63
  logger.info('[clinicalAirtableService] Airtable write skipped', { table, code, skip });
62
64
  } else if (isShadowRun()) {
@@ -67,11 +69,18 @@ async function auditedWrite({ trace, code, table, write, isLive = null, skip = n
67
69
  logger.info('[clinicalAirtableService] Airtable write skipped — turn superseded', { table, code });
68
70
  } else {
69
71
  try {
70
- const result = await write();
71
- entry.ok = true;
72
- if (Array.isArray(result) && !result.length) entry.noMatch = true;
73
- const record = Array.isArray(result) ? result[0] : result;
74
- if (record?.id) entry.recordId = record.id;
72
+ const preparedSkip = typeof skip === 'function' ? await skip() : null;
73
+ if (preparedSkip) {
74
+ entry.skipped = preparedSkip;
75
+ } else if (isLive && !isLive()) {
76
+ entry.skipped = 'superseded';
77
+ } else {
78
+ const result = await write();
79
+ entry.ok = true;
80
+ if (Array.isArray(result) && !result.length) entry.noMatch = true;
81
+ const record = Array.isArray(result) ? result[0] : result;
82
+ if (record?.id) entry.recordId = record.id;
83
+ }
75
84
  } catch (err) {
76
85
  entry.error = err?.message || String(err);
77
86
  logger.error('[clinicalAirtableService] Airtable write failed', { table, code, error: entry.error });
@@ -91,8 +100,8 @@ async function findMonitoreoPatientRecordId(code) {
91
100
  }
92
101
 
93
102
  async function findIntakePatientRecordId(code) {
94
- const patient = await airtableService.getRecordByFilter(Estado_General_ID, 'estado_general', `{whatsapp_id} = "${code}"`);
95
- return patient?.[0]?.monitoreo_record_id || null;
103
+ const { recordId } = await requirePatientIdentity(Estado_General_ID, code);
104
+ return recordId;
96
105
  }
97
106
 
98
107
  async function writeUnresolvedRequest({ code, trace, question, details, resolutionAttempted = false, forDoctorOffice = false, category = null, urgency = null, replacesClosedTask = false }) {
@@ -278,23 +287,37 @@ function _clearRecentIntakeCache() {
278
287
  }
279
288
 
280
289
  async function recordClinicalIntake({ code, trace, messageRaw, source = 'self', isLive = null }) {
290
+ if (isBenchMode(code)) {
291
+ return auditedWrite({
292
+ trace, code, isLive, table: 'intake', write: async () => ({ id: 'bench_mock_record' }),
293
+ });
294
+ }
281
295
  const airtableSource = INTAKE_SOURCE_TO_AIRTABLE[source] || 'self';
282
- const fingerprint = createHash('sha1').update(`${code}\n${airtableSource}\n${messageRaw || ''}`).digest('hex');
296
+ let patientId;
297
+ let fingerprint;
283
298
  const written = await auditedWrite({
284
299
  trace,
285
300
  code,
286
301
  isLive,
287
302
  table: 'intake',
288
- skip: await recentIntakeCache.get(code) === fingerprint ? 'duplicate' : null,
303
+ skip: async () => {
304
+ patientId = await findIntakePatientRecordId(code);
305
+ fingerprint = createHash('sha1').update(JSON.stringify([code, patientId, airtableSource, messageRaw || ''])).digest('hex');
306
+ return await recentIntakeCache.get(code) === fingerprint ? 'duplicate' : null;
307
+ },
289
308
  write: async () => {
290
- const patientId = await findIntakePatientRecordId(code);
291
- return airtableService.addRecord(Estado_General_ID, 'intake', [{
309
+ const created = await airtableService.addRecord(Estado_General_ID, 'intake', [{
292
310
  fields: {
293
- patient: patientId ? [patientId] : [],
311
+ patient: [patientId],
294
312
  message_raw: messageRaw || '',
295
313
  source: airtableSource,
296
314
  },
297
315
  }], code);
316
+ const records = Array.isArray(created) ? created : [created];
317
+ if (records.length !== 1 || !records[0]?.id) {
318
+ throw new Error('Clinical intake was not created');
319
+ }
320
+ return created;
298
321
  },
299
322
  });
300
323
  if (written) await recentIntakeCache.set(code, fingerprint);
@@ -0,0 +1,43 @@
1
+ const { fieldEquals } = require('../../helpers/airtableFormulaHelper');
2
+ const { getRecordByFilter } = require('../../services/airtableService');
3
+
4
+ const pendingLookups = new Map();
5
+
6
+ function identityError(kind) {
7
+ const error = new Error(`Patient identity ${kind}`);
8
+ error.code = `PATIENT_IDENTITY_${kind.toUpperCase()}`;
9
+ error.statusCode = kind === 'missing' ? 404 : kind === 'invalid' ? 400 : kind === 'unavailable' ? 502 : 409;
10
+ return error;
11
+ }
12
+
13
+ // A contact locates candidates; it is not a canonical patient identifier. Resolve
14
+ // separately in each base, without a view that could hide duplicate candidates.
15
+ async function resolvePatientIdentity(baseId, code) {
16
+ if (typeof code !== 'string' || !code.trim()) throw identityError('invalid');
17
+ const key = JSON.stringify([baseId, code]);
18
+ if (pendingLookups.has(key)) return pendingLookups.get(key);
19
+ const lookup = readPatientIdentity(baseId, code).finally(() => pendingLookups.delete(key));
20
+ pendingLookups.set(key, lookup);
21
+ return lookup;
22
+ }
23
+
24
+ async function readPatientIdentity(baseId, code) {
25
+ const records = await getRecordByFilter(baseId, 'estado_general', fieldEquals('whatsapp_id', code), null, undefined, true);
26
+ if (!Array.isArray(records)) throw identityError('unavailable');
27
+ if (!records.length) return { kind: 'missing' };
28
+ if (records.length > 1) return { kind: 'ambiguous', candidateCount: records.length };
29
+ const recordId = records[0]?._recordId;
30
+ if (!/^rec[A-Za-z0-9]+$/.test(recordId || '')) throw identityError('unavailable');
31
+ const record = { ...records[0] };
32
+ delete record._recordId;
33
+ delete record._createdTime;
34
+ return { kind: 'resolved', recordId, record };
35
+ }
36
+
37
+ async function requirePatientIdentity(baseId, code) {
38
+ const identity = await resolvePatientIdentity(baseId, code);
39
+ if (identity.kind !== 'resolved') throw identityError(identity.kind);
40
+ return identity;
41
+ }
42
+
43
+ module.exports = { resolvePatientIdentity, requirePatientIdentity, identityError };
@@ -32,7 +32,11 @@ const getPatientInfoController = async (req, res) => {
32
32
  res.status(200).json({ success: true, whatsappId: code, code, clinicalContext, patientInfo });
33
33
  } catch (error) {
34
34
  logger.error('Error fetching patient info:', { error: error.message, code: req.params?.code });
35
- res.status(500).json({ success: false, error: error.message });
35
+ const isIdentityError = typeof error.code === 'string' && error.code.startsWith('PATIENT_IDENTITY_');
36
+ res.status(isIdentityError ? error.statusCode : 502).json({
37
+ success: false,
38
+ error: isIdentityError ? error.message : 'Patient information is unavailable',
39
+ });
36
40
  }
37
41
  };
38
42
 
@@ -5,7 +5,7 @@ const { MapCache } = require('../utils/MapCache');
5
5
 
6
6
  const { Thread } = require('../models/threadModel');
7
7
 
8
- const { getRecordByFilter } = require('../services/airtableService');
8
+ const { resolvePatientIdentity, identityError } = require('../clinical/services/patientIdentityService');
9
9
 
10
10
  const clinicalContextCache = new MapCache({
11
11
  maxSize: 1000,
@@ -13,28 +13,27 @@ const clinicalContextCache = new MapCache({
13
13
  });
14
14
 
15
15
  async function getClinicalContext(whatsappId) {
16
- const cached = clinicalContextCache.get(whatsappId);
17
-
18
- if (cached) {
19
- logger.debug('[getClinicalContext] Returning cached clinical context', { whatsappId });
20
- return cached;
21
- }
22
-
23
16
  try {
24
- const records = await getRecordByFilter(Monitoreo_ID, 'estado_general', `{whatsapp_id}='${whatsappId}'`);
17
+ const identity = await resolvePatientIdentity(Monitoreo_ID, whatsappId);
18
+ if (identity.kind === 'missing') return {airtableName: null, clinicalContext: null, contextAsk: []};
19
+ if (identity.kind !== 'resolved') throw identityError(identity.kind);
20
+ const { record, recordId } = identity;
21
+ const sourceKey = JSON.stringify([record.name, record.context_ask, record['clinical-context-json']]);
22
+ const cached = clinicalContextCache.get(whatsappId);
23
+ if (cached?.recordId === recordId && cached.sourceKey === sourceKey) return cached.value;
25
24
  let clinicalContext = null;
26
- let airtableName = records?.[0]?.['name'] || null;
25
+ const airtableName = record.name || null;
27
26
 
28
- if (records && records.length > 0 && records[0]['clinical-context-json']) {
29
- clinicalContext = JSON.parse(records[0]['clinical-context-json']);
27
+ if (record['clinical-context-json']) {
28
+ clinicalContext = JSON.parse(record['clinical-context-json']);
30
29
  }
31
30
 
32
- const contextAsk = String(records?.[0]?.['context_ask'] || '')
31
+ const contextAsk = String(record.context_ask || '')
33
32
  .split(',')
34
33
  .map((variable) => variable.trim())
35
34
  .filter(Boolean);
36
35
 
37
- clinicalContextCache.set(whatsappId, {airtableName, clinicalContext, contextAsk});
36
+ clinicalContextCache.set(whatsappId, { recordId, sourceKey, value: {airtableName, clinicalContext, contextAsk} });
38
37
 
39
38
  return {airtableName, clinicalContext, contextAsk};
40
39
  } catch (error) {
@@ -106,7 +106,7 @@ async function getRecordByFilter(baseID, tableName, filter, view = 'Grid view',
106
106
  const selectOptions = { filterByFormula: filter };
107
107
  if (view) selectOptions.view = view;
108
108
  if (fields && fields.length) selectOptions.fields = fields;
109
- const mapper = withRecordId ? (r) => ({ _recordId: r.id, _createdTime: r._rawJson?.createdTime, ...r.fields }) : undefined;
109
+ const mapper = withRecordId ? (r) => ({ ...r.fields, _recordId: r.id, _createdTime: r._rawJson?.createdTime }) : undefined;
110
110
  return await withAirtableRetry(
111
111
  () => collectRecords(getBase(baseID)(tableName).select(selectOptions), mapper),
112
112
  'getRecordByFilter'
@@ -5,20 +5,24 @@ const { logger } = require('../utils/logger');
5
5
  const { Thread } = require('../models/threadModel');
6
6
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
7
7
 
8
- const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
8
+ const { fieldEquals, recordIdIn } = require('../helpers/airtableFormulaHelper');
9
+ const { updateRecordByFilter } = require('../services/airtableService');
9
10
 
10
11
  const { updateMessage } = require('../services/messageService');
12
+ const { resolvePatientIdentity, requirePatientIdentity, identityError } = require('../clinical/services/patientIdentityService');
11
13
 
12
14
  const getPatientInformation = async (code) => {
13
- const records = await getRecordByFilter(Estado_General_ID, 'estado_general', `{whatsapp_id}='${code}'`);
14
- if (!records || records.length === 0) return null;
15
-
16
- for (const [key, value] of Object.entries(records[0])) {
17
- if (typeof value === 'object' && value[0] && value.length === 1) {
18
- records[0][key] = value[0];
15
+ const identity = await resolvePatientIdentity(Estado_General_ID, code);
16
+ if (identity.kind === 'missing') return null;
17
+ if (identity.kind !== 'resolved') throw identityError(identity.kind);
18
+ const record = { ...identity.record };
19
+
20
+ for (const [key, value] of Object.entries(record)) {
21
+ if (Array.isArray(value) && value[0] && value.length === 1) {
22
+ record[key] = value[0];
19
23
  }
20
24
  }
21
- return records[0];
25
+ return record;
22
26
  };
23
27
 
24
28
  const logPatientChange = async ({ code, updatedBy, source, requestId, changes, failedFields, status }) => {
@@ -48,7 +52,8 @@ const logPatientChange = async ({ code, updatedBy, source, requestId, changes, f
48
52
  };
49
53
 
50
54
  const updatePatientInformation = async (code, fields, auditContext = {}) => {
51
- const filter = `{whatsapp_id}='${code}'`;
55
+ const { recordId } = await requirePatientIdentity(Estado_General_ID, code);
56
+ const filter = `AND(${recordIdIn([recordId])},${fieldEquals('whatsapp_id', code)})`;
52
57
 
53
58
  const cleanChanges = Object.fromEntries(
54
59
  Object.entries(fields)
@@ -59,20 +64,25 @@ const updatePatientInformation = async (code, fields, auditContext = {}) => {
59
64
  const result = await updateRecordByFilter(Estado_General_ID, 'estado_general', filter, fields, code)
60
65
  .catch(() => undefined);
61
66
 
67
+ if (Array.isArray(result) && result.length === 0) {
68
+ await logPatientChange({ code, changes: {}, status: 'failed', ...auditContext });
69
+ throw identityError('changed');
70
+ }
71
+
62
72
  let failedFields = [];
63
- if (!result) {
73
+ if (!Array.isArray(result) || result.length !== 1) {
64
74
  logger.warn('[updatePatientInformation] Bulk update failed, retrying fields individually', { code });
65
75
  for (const [key, value] of Object.entries(fields)) {
66
76
  const fieldResult = await updateRecordByFilter(Estado_General_ID, 'estado_general', filter, { [key]: value }, code)
67
77
  .catch(() => undefined);
68
- if (!fieldResult) {
78
+ if (!Array.isArray(fieldResult) || fieldResult.length !== 1) {
69
79
  failedFields.push({ key, value });
70
80
  const cleanKey = key.replace(/^updt_/, '');
71
81
  delete cleanChanges[cleanKey];
72
82
  logger.warn('[updatePatientInformation] Field update failed', { field: key, code });
73
83
  }
74
84
  }
75
- if (failedFields.length === Object.keys(fields).length) {
85
+ if (Object.keys(cleanChanges).length === 0) {
76
86
  await logPatientChange({
77
87
  code, changes: cleanChanges, failedFields, status: 'failed', ...auditContext
78
88
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.59.3",
3
+ "version": "5.59.4",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",