@peopl-health/nexus 5.59.3 → 5.59.5
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/helpers/clinicalProfileHelper.js +5 -6
- package/lib/clinical/helpers/triageCaseBaseHelper.js +11 -0
- package/lib/clinical/memory/DefaultMemoryManager.js +9 -7
- package/lib/clinical/services/clinicalAirtableService.js +36 -13
- package/lib/clinical/services/deniedSymptomBoundaryService.js +7 -6
- package/lib/clinical/services/patientIdentityService.js +43 -0
- package/lib/clinical/services/recommendationRankService.js +2 -1
- package/lib/clinical/services/triageRecommendationService.js +23 -7
- package/lib/controllers/patientController.js +5 -1
- package/lib/helpers/patientInformationHelper.js +13 -14
- package/lib/services/airtableService.js +1 -1
- package/lib/services/patientService.js +22 -12
- package/package.json +1 -1
|
@@ -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
|
-
|
|
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 };
|
|
@@ -139,6 +139,7 @@ function buildSymptomsMetadata({
|
|
|
139
139
|
declined = [],
|
|
140
140
|
additionalSymptoms = [],
|
|
141
141
|
freeTextDerivedSymptoms = [],
|
|
142
|
+
freeTextUnmatchedSymptoms = [],
|
|
142
143
|
nonIdentifiedSymptoms = null,
|
|
143
144
|
stage = 'gate',
|
|
144
145
|
catalog = null,
|
|
@@ -177,6 +178,14 @@ function buildSymptomsMetadata({
|
|
|
177
178
|
+ 'clasificador y puede no ser el correcto: verifícalo con el paciente antes de darlo por confirmado.',
|
|
178
179
|
);
|
|
179
180
|
}
|
|
181
|
+
if (freeTextUnmatchedSymptoms.length) {
|
|
182
|
+
parts.push(
|
|
183
|
+
'Síntomas que el paciente escribió en el TEXTO LIBRE y que no tienen ítem PRO-CTCAE: '
|
|
184
|
+
+ freeTextUnmatchedSymptoms.join(', ')
|
|
185
|
+
+ '. Están PRESENTES, sin grado, y son material válido de recomendación. No los traduzcas a un '
|
|
186
|
+
+ 'ítem PRO-CTCAE parecido: si les haces una tarjeta, pon exactamente esa etiqueta en targeted_ctcae_terms.',
|
|
187
|
+
);
|
|
188
|
+
}
|
|
180
189
|
if (denied.length) {
|
|
181
190
|
parts.push(
|
|
182
191
|
'Síntomas NEGADOS explícitamente en la ventana de reporte del triaje (respuesta grado 0 a preguntas del triaje): '
|
|
@@ -370,6 +379,7 @@ function buildCasoBase({
|
|
|
370
379
|
freeText = null,
|
|
371
380
|
additionalSymptoms = [],
|
|
372
381
|
freeTextDerivedSymptoms = [],
|
|
382
|
+
freeTextUnmatchedSymptoms = [],
|
|
373
383
|
nonIdentifiedSymptoms = null,
|
|
374
384
|
stage = 'gate',
|
|
375
385
|
catalog = null,
|
|
@@ -396,6 +406,7 @@ function buildCasoBase({
|
|
|
396
406
|
declined,
|
|
397
407
|
additionalSymptoms,
|
|
398
408
|
freeTextDerivedSymptoms,
|
|
409
|
+
freeTextUnmatchedSymptoms,
|
|
399
410
|
nonIdentifiedSymptoms,
|
|
400
411
|
stage,
|
|
401
412
|
catalog,
|
|
@@ -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
|
|
242
|
-
|
|
243
|
-
|
|
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 =
|
|
247
|
-
? JSON.parse(
|
|
248
|
+
const clinicalContext = record['clinical-context-json']
|
|
249
|
+
? JSON.parse(record['clinical-context-json'])
|
|
248
250
|
: null;
|
|
249
|
-
const treatingPhysician = sanitizeInlineText(
|
|
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
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
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
|
|
95
|
-
return
|
|
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
|
-
|
|
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:
|
|
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
|
|
291
|
-
return airtableService.addRecord(Estado_General_ID, 'intake', [{
|
|
309
|
+
const created = await airtableService.addRecord(Estado_General_ID, 'intake', [{
|
|
292
310
|
fields: {
|
|
293
|
-
patient:
|
|
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);
|
|
@@ -51,12 +51,13 @@ function canonicalCtcaeTerm(catalog, term) {
|
|
|
51
51
|
return resolved ? spellingOf(catalog.symptoms[resolved], resolved) || term : term;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
)
|
|
54
|
+
// A free-text complaint the classifier could not code keeps the patient's label: a fuzzy
|
|
55
|
+
// alias match would rename it to a catalog term she never reported, and drop the card.
|
|
56
|
+
function canonicaliseTerms(element, catalog, uncodedKeys = new Set()) {
|
|
57
|
+
const canonical = (term) => (uncodedKeys.has(keyOf(term)) ? term : canonicalCtcaeTerm(catalog, term));
|
|
58
|
+
element.targetedCtcaeTerms = [...new Set(element.targetedCtcaeTerms.map(canonical))];
|
|
58
59
|
for (const symptom of element.symptoms) {
|
|
59
|
-
symptom.ctcaeTerm =
|
|
60
|
+
symptom.ctcaeTerm = canonical(symptom.ctcaeTerm);
|
|
60
61
|
}
|
|
61
62
|
}
|
|
62
63
|
|
|
@@ -166,7 +167,7 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
|
|
|
166
167
|
let dropped = 0;
|
|
167
168
|
let stripped = 0;
|
|
168
169
|
for (const element of elements) {
|
|
169
|
-
canonicaliseTerms(element, boundary.catalog);
|
|
170
|
+
canonicaliseTerms(element, boundary.catalog, boundary.uncodedKeys);
|
|
170
171
|
const breach = breachOf(element, boundary);
|
|
171
172
|
if (!breach) {
|
|
172
173
|
kept.push(element);
|
|
@@ -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 };
|
|
@@ -89,7 +89,7 @@ function buildRankContext({ catalog, graded = [], reportedTerms = [], priorResol
|
|
|
89
89
|
|
|
90
90
|
function buildSymptomSignals({
|
|
91
91
|
catalog, graded = [], ungradedTerms = [], additionalSymptoms = [], freeTextDerivedSymptoms = [],
|
|
92
|
-
priorResolutions = [], openCases = [],
|
|
92
|
+
freeTextUnmatchedSymptoms = [], priorResolutions = [], openCases = [],
|
|
93
93
|
}) {
|
|
94
94
|
const gradeByKey = new Map();
|
|
95
95
|
for (const symptom of graded) keepHighest(gradeByKey, aliasKeysOf(catalog, symptom.term), symptom.grade);
|
|
@@ -109,6 +109,7 @@ function buildSymptomSignals({
|
|
|
109
109
|
ungradedTerms.forEach((term) => add(term, 'cuestionario'));
|
|
110
110
|
additionalSymptoms.forEach((symptom) => add(symptom.label, 'checkbox', symptom));
|
|
111
111
|
freeTextDerivedSymptoms.forEach((term) => add(term, 'texto libre'));
|
|
112
|
+
freeTextUnmatchedSymptoms.forEach((label) => add(label, 'texto libre'));
|
|
112
113
|
|
|
113
114
|
return signals.map(({ keys, ...signal }) => ({
|
|
114
115
|
...signal,
|
|
@@ -38,6 +38,7 @@ const {
|
|
|
38
38
|
const { gradeComposites, PAIN_TERM } = require('../../fhir/helpers/compositeHelper');
|
|
39
39
|
const { affirmative } = require('../../fhir/helpers/terminologyHelper');
|
|
40
40
|
const { buildTriageResponse } = require('../../fhir/helpers/triagePayloadHelper');
|
|
41
|
+
const { keyOf } = require('../../fhir/helpers/symptomAliasHelper');
|
|
41
42
|
const { getCatalog } = require('../../fhir/services/terminologyService');
|
|
42
43
|
const { getRecordByFilter } = require('../../services/airtableService');
|
|
43
44
|
const { RecommendationPlan } = require('../../shared/dtos/RecommendationPlan');
|
|
@@ -262,11 +263,12 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
262
263
|
return { ...settle, status: 'failed', stage: 'assemble', reason: 'triage_patient_mismatch' };
|
|
263
264
|
}
|
|
264
265
|
const freeTextDerivedSymptoms = classifier.terms;
|
|
266
|
+
const freeTextUnmatchedSymptoms = classifier.unmatched || [];
|
|
265
267
|
settle.classifierPending = classifier.pending;
|
|
266
268
|
settle.classifierOutcome = classifier.outcome;
|
|
267
269
|
settle.classifierWaitMs = classifier.waitMs;
|
|
268
270
|
|
|
269
|
-
let supportContext = { triage: triageResponse, freeTextDerivedSymptoms };
|
|
271
|
+
let supportContext = { triage: triageResponse, freeTextDerivedSymptoms, freeTextUnmatchedSymptoms };
|
|
270
272
|
let supportPromise;
|
|
271
273
|
let existingClinicalMirrorId = null;
|
|
272
274
|
const startSupport = () => {
|
|
@@ -527,6 +529,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
527
529
|
freeText: freeTextLabelled.join(' · ') || null,
|
|
528
530
|
additionalSymptoms,
|
|
529
531
|
freeTextDerivedSymptoms,
|
|
532
|
+
freeTextUnmatchedSymptoms,
|
|
530
533
|
nonIdentifiedSymptoms: triageResponse.nonIdentifiedSymptoms,
|
|
531
534
|
stage,
|
|
532
535
|
catalog,
|
|
@@ -539,6 +542,7 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
539
542
|
...reported.map((symptom) => symptom.term),
|
|
540
543
|
...additionalSymptoms.map((symptom) => symptom.term).filter(Boolean),
|
|
541
544
|
...freeTextDerivedSymptoms,
|
|
545
|
+
...freeTextUnmatchedSymptoms,
|
|
542
546
|
];
|
|
543
547
|
const reportedKeys = symptomKeySet(catalog, reportedTerms);
|
|
544
548
|
const floorConfig = await getRedFlagMinRoutes()
|
|
@@ -581,12 +585,14 @@ async function generateTriageRecommendations({ payload, provider, runId = null,
|
|
|
581
585
|
gate,
|
|
582
586
|
deniedKeys,
|
|
583
587
|
reportedKeys,
|
|
588
|
+
uncodedKeys: new Set(freeTextUnmatchedSymptoms.map(keyOf).filter(Boolean)),
|
|
584
589
|
deniedAeKeys: deniedAeKeySet(catalog, gate),
|
|
585
590
|
reported: reportedSymptoms(catalog, reportedTerms),
|
|
586
591
|
};
|
|
587
592
|
const rankContext = buildRankContext({ catalog, graded, reportedTerms, priorResolutions, openCases });
|
|
588
593
|
const symptomSignals = buildSymptomSignals({
|
|
589
|
-
catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms,
|
|
594
|
+
catalog, graded, ungradedTerms, additionalSymptoms, freeTextDerivedSymptoms, freeTextUnmatchedSymptoms,
|
|
595
|
+
priorResolutions, openCases,
|
|
590
596
|
});
|
|
591
597
|
const planOutcome = await runPlan({
|
|
592
598
|
provider, presetId: planPresetId, casoBase: casoBaseFor('plan', symptomSignals),
|
|
@@ -1022,18 +1028,19 @@ async function awaitFreeTextClassifier(triageRecordId, code, { hasFreeText }) {
|
|
|
1022
1028
|
|
|
1023
1029
|
function classifierSettled(read) {
|
|
1024
1030
|
if (read.pending !== false) return false;
|
|
1025
|
-
|
|
1031
|
+
// The classifier writes the complaints it could not code too, so an all-NO MATCH run is done, not empty.
|
|
1032
|
+
if (read.derived > 0 || read.unmatched.length > 0) return true;
|
|
1026
1033
|
const createdMs = Date.parse(read.createdAt || '');
|
|
1027
1034
|
return !Number.isFinite(createdMs) || Date.now() - createdMs >= CLASSIFIER_WINDOW_MS;
|
|
1028
1035
|
}
|
|
1029
1036
|
|
|
1030
1037
|
async function readFreeTextDerivedSymptoms(triageRecordId, code) {
|
|
1031
|
-
if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], pending: null, derived: 0, createdAt: null };
|
|
1038
|
+
if (!/^rec[A-Za-z0-9]+$/.test(triageRecordId || '')) return { terms: [], unmatched: [], pending: null, derived: 0, createdAt: null };
|
|
1032
1039
|
const rows = await getRecordByFilter(Symptoms_ID, 'triaje_symptoms', `RECORD_ID()='${triageRecordId}'`);
|
|
1033
1040
|
const row = Array.isArray(rows) ? rows[0] : rows;
|
|
1034
1041
|
if (!row) {
|
|
1035
1042
|
logger.warn('[triageRecommendation] triage row unreadable; no classifier anchors', { code, triageRecordId });
|
|
1036
|
-
return { terms: [], pending: null, derived: 0, createdAt: null };
|
|
1043
|
+
return { terms: [], unmatched: [], pending: null, derived: 0, createdAt: null };
|
|
1037
1044
|
}
|
|
1038
1045
|
const owner = Array.isArray(row.whatsapp_id) ? row.whatsapp_id[0] : row.whatsapp_id;
|
|
1039
1046
|
if (owner && owner !== code) {
|
|
@@ -1043,8 +1050,9 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
|
|
|
1043
1050
|
// The classifier writes its rows ~96 s after the triage: an unfinished one is not an empty one.
|
|
1044
1051
|
const pending = row.symptoms_processed !== true;
|
|
1045
1052
|
const createdAt = row.Created || null;
|
|
1053
|
+
const unmatched = unmatchedMentionsOf(row.freetext_unmatched);
|
|
1046
1054
|
const ids = (Array.isArray(row.symptoms) ? row.symptoms : []).filter((id) => /^rec[A-Za-z0-9]+$/.test(id || ''));
|
|
1047
|
-
if (!ids.length) return { terms: [], pending, derived: 0, createdAt };
|
|
1055
|
+
if (!ids.length) return { terms: [], unmatched, pending, derived: 0, createdAt };
|
|
1048
1056
|
const formula = `OR(${ids.map((id) => `RECORD_ID()='${id}'`).join(',')})`;
|
|
1049
1057
|
const symptoms = await getRecordByFilter(Symptoms_ID, 'symptoms', formula, null, FREE_TEXT_SYMPTOM_FIELDS, true);
|
|
1050
1058
|
const derived = (Array.isArray(symptoms) ? symptoms : []).filter((symptom) => symptom.freetext_derived === true);
|
|
@@ -1053,7 +1061,15 @@ async function readFreeTextDerivedSymptoms(triageRecordId, code) {
|
|
|
1053
1061
|
.map((symptom) => (Array.isArray(symptom.corresponding_CTCAE) ? symptom.corresponding_CTCAE[0] : symptom.corresponding_CTCAE))
|
|
1054
1062
|
.map((term) => String(term ?? '').trim())
|
|
1055
1063
|
.filter(Boolean);
|
|
1056
|
-
return { terms, pending, derived: derived.length, createdAt };
|
|
1064
|
+
return { terms, unmatched, pending, derived: derived.length, createdAt };
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// One complaint per line, `mención — "cita literal"`: only the mention names the symptom.
|
|
1068
|
+
function unmatchedMentionsOf(value) {
|
|
1069
|
+
const mentions = String(value || '').split('\n')
|
|
1070
|
+
.map((line) => line.split(' — ')[0].trim())
|
|
1071
|
+
.filter(Boolean);
|
|
1072
|
+
return [...new Set(mentions)];
|
|
1057
1073
|
}
|
|
1058
1074
|
|
|
1059
1075
|
async function readPriorResolutions(adherence = [], patientRecordId = null) {
|
|
@@ -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
|
-
|
|
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 {
|
|
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
|
|
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
|
-
|
|
25
|
+
const airtableName = record.name || null;
|
|
27
26
|
|
|
28
|
-
if (
|
|
29
|
-
clinicalContext = JSON.parse(
|
|
27
|
+
if (record['clinical-context-json']) {
|
|
28
|
+
clinicalContext = JSON.parse(record['clinical-context-json']);
|
|
30
29
|
}
|
|
31
30
|
|
|
32
|
-
const contextAsk = String(
|
|
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
|
|
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 {
|
|
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
|
|
14
|
-
if (
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
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
|
|
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
|
|
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 (
|
|
85
|
+
if (Object.keys(cleanChanges).length === 0) {
|
|
76
86
|
await logPatientChange({
|
|
77
87
|
code, changes: cleanChanges, failedFields, status: 'failed', ...auditContext
|
|
78
88
|
});
|