@peopl-health/nexus 5.45.0-dev.7177 → 5.45.0-dev.7187
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/deniedSymptomBoundaryService.js +39 -16
- package/lib/clinical/services/recommendationValidationService.js +10 -0
- package/lib/clinical/services/triageRecommendationService.js +4 -2
- package/lib/controllers/patientController.js +0 -16
- package/lib/routes/index.js +0 -2
- package/lib/utils/sanitizerUtils.js +0 -1
- package/package.json +1 -1
- package/lib/services/escalationContextService.js +0 -81
|
@@ -4,7 +4,11 @@ const {
|
|
|
4
4
|
} = require('../../fhir/helpers/symptomAliasHelper');
|
|
5
5
|
const { str, strList } = require('../../utils/coercionUtils');
|
|
6
6
|
|
|
7
|
-
const
|
|
7
|
+
const URGENT_CARD_NAMES = {
|
|
8
|
+
equipo_tratante_hoy: 'Contacto con tu equipo médico hoy',
|
|
9
|
+
urgencias: 'Atención médica urgente',
|
|
10
|
+
emergencia: 'Atención médica inmediata',
|
|
11
|
+
};
|
|
8
12
|
const SURFACE_MAX = 6;
|
|
9
13
|
|
|
10
14
|
const itemTerm = (catalog, item) => (catalog?.item_index ? termForItem(catalog, item) : null);
|
|
@@ -120,29 +124,45 @@ function stripToReportedTargets(element, boundary) {
|
|
|
120
124
|
return true;
|
|
121
125
|
}
|
|
122
126
|
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
element.
|
|
130
|
-
|
|
127
|
+
const deniedToday = (term, { deniedKeys, deniedAeKeys }) => deniedKeys.has(keyOf(term)) || deniedAeKeys.has(keyOf(term));
|
|
128
|
+
|
|
129
|
+
const ownTargetsOf = (element, boundary) => element.targetedCtcaeTerms.filter((term) => !deniedToday(term, boundary));
|
|
130
|
+
|
|
131
|
+
function keepTargets(element, targets, boundary) {
|
|
132
|
+
if (!targets.length) return false;
|
|
133
|
+
element.targetedCtcaeTerms = targets;
|
|
134
|
+
element.symptoms = element.symptoms.filter((symptom) => !deniedToday(symptom.ctcaeTerm, boundary));
|
|
131
135
|
return true;
|
|
132
136
|
}
|
|
133
137
|
|
|
138
|
+
const urgentCardName = (gate) => URGENT_CARD_NAMES[gate.escalationRoute] || URGENT_CARD_NAMES.urgencias;
|
|
139
|
+
|
|
134
140
|
// El gate urgente viaja en esta tarjeta: se le cambia el rótulo, no se descarta.
|
|
135
141
|
function reframeOnGate(element, boundary) {
|
|
136
142
|
if (boundary.gate?.urgentUnder24h !== true || element.escalation?.urgentUnder24h !== true) return false;
|
|
137
|
-
|
|
138
|
-
|
|
143
|
+
const own = ownTargetsOf(element, boundary);
|
|
144
|
+
const anchors = (boundary.reported || [])
|
|
145
|
+
.filter((symptom) => survives(keyOf(symptom.ctcaeTerm), boundary))
|
|
146
|
+
.slice(0, SURFACE_MAX)
|
|
147
|
+
.map((symptom) => symptom.ctcaeTerm);
|
|
148
|
+
const touchesDenial = [...element.targetedCtcaeTerms, ...element.symptoms.map((symptom) => symptom.ctcaeTerm)]
|
|
149
|
+
.some((term) => deniedToday(term, boundary));
|
|
150
|
+
const catalogLabels = own.map((term) => symptomRecord(boundary.catalog, resolveTerm(boundary.catalog, term))?.es);
|
|
151
|
+
const header = catalogLabels.every(Boolean) || touchesDenial
|
|
152
|
+
? catalogLabels.filter(Boolean)
|
|
153
|
+
: strList(element.recommendation.symptomsPatientFacing);
|
|
154
|
+
if (!keepTargets(element, own.length ? own : anchors, boundary)) return false;
|
|
155
|
+
const name = urgentCardName(boundary.gate);
|
|
156
|
+
element.nameShort = name;
|
|
157
|
+
element.recommendation.symptomsPatientFacing = header.length ? [...new Set(header)].slice(0, SURFACE_MAX) : [name];
|
|
139
158
|
return true;
|
|
140
159
|
}
|
|
141
160
|
|
|
142
161
|
function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = false } = {}) {
|
|
143
|
-
if (!boundary) return { elements, dropped: 0, stripped: 0 };
|
|
162
|
+
if (!boundary) return { elements, dropped: 0, stripped: 0, urgentReframed: [] };
|
|
144
163
|
const kept = [];
|
|
145
164
|
const unanchored = [];
|
|
165
|
+
const urgentReframed = [];
|
|
146
166
|
let dropped = 0;
|
|
147
167
|
let stripped = 0;
|
|
148
168
|
for (const element of elements) {
|
|
@@ -159,8 +179,9 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
|
|
|
159
179
|
continue;
|
|
160
180
|
}
|
|
161
181
|
if (reframeOnGate(element, boundary)) {
|
|
162
|
-
repairs.push(`elemento (rank ${element.rank})
|
|
182
|
+
repairs.push(`elemento (rank ${element.rank}) urgente conservado con un título genérico para mantener el gate: ${breach.why}`);
|
|
163
183
|
stripped += 1;
|
|
184
|
+
urgentReframed.push(element);
|
|
164
185
|
kept.push(element);
|
|
165
186
|
continue;
|
|
166
187
|
}
|
|
@@ -169,10 +190,10 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
|
|
|
169
190
|
dropped += 1;
|
|
170
191
|
}
|
|
171
192
|
const rescued = rescue && !kept.length
|
|
172
|
-
? unanchored.sort((a, b) => a.rank - b.rank).find((element) =>
|
|
193
|
+
? unanchored.sort((a, b) => a.rank - b.rank).find((element) => keepTargets(element, ownTargetsOf(element, boundary), boundary))
|
|
173
194
|
: null;
|
|
174
195
|
if (rescued) {
|
|
175
|
-
repairs.push(`elemento (rank ${rescued.rank})
|
|
196
|
+
repairs.push(`elemento (rank ${rescued.rank}) conservado sobre su propio objetivo en vez de descartar el plan entero`);
|
|
176
197
|
kept.push(rescued);
|
|
177
198
|
stripped += 1;
|
|
178
199
|
dropped -= 1;
|
|
@@ -181,7 +202,9 @@ function applyCardSurfaceBoundary(elements, boundary, repairs = [], { rescue = f
|
|
|
181
202
|
kept.sort((a, b) => a.rank - b.rank);
|
|
182
203
|
kept.forEach((element, index) => { element.rank = index + 1; });
|
|
183
204
|
}
|
|
184
|
-
return {
|
|
205
|
+
return {
|
|
206
|
+
elements: kept, dropped, stripped, urgentReframed,
|
|
207
|
+
};
|
|
185
208
|
}
|
|
186
209
|
|
|
187
210
|
module.exports = {
|
|
@@ -7,6 +7,7 @@ const ESCALATION_ELLIPSIS = /…|\.\.\./;
|
|
|
7
7
|
const ESCALATION_LENGTH_CODE = 'when_to_escalate_length';
|
|
8
8
|
const SENTENCE_COUNT_CODE = 'main_recommendation_sentence_count';
|
|
9
9
|
const ATTRIBUTION_CODE = 'unsourced_care_team_attribution';
|
|
10
|
+
const URGENT_WITHOUT_TODAY_EVIDENCE_CODE = 'urgent_without_today_evidence';
|
|
10
11
|
|
|
11
12
|
const ATTRIBUTIONS = [
|
|
12
13
|
'como lo indico tu equipo', 'tal como lo indico tu equipo', 'como te lo indico tu equipo',
|
|
@@ -138,6 +139,15 @@ function validate(elements, options = {}) {
|
|
|
138
139
|
issues.push({ path: `${path}.recommendation`, problem: 'sin main_recommendation, sin otc_offer y sin followup=team_referral — el paciente no recibe nada' });
|
|
139
140
|
}
|
|
140
141
|
if (isTriagePlan) issues.push(...attributionIssues(patient, path));
|
|
142
|
+
if (isTriagePlan && options.urgentReframed?.includes(element)) {
|
|
143
|
+
issues.push({
|
|
144
|
+
path,
|
|
145
|
+
code: URGENT_WITHOUT_TODAY_EVIDENCE_CODE,
|
|
146
|
+
warning: true,
|
|
147
|
+
problem: 'la tarjeta urgente no nombra ningún síntoma reportado en este triaje; se conservó con un título '
|
|
148
|
+
+ 'genérico para no perder el gate.',
|
|
149
|
+
});
|
|
150
|
+
}
|
|
141
151
|
if (recommendation.otcOffer !== null) {
|
|
142
152
|
for (const field of ['dose', 'frequency', 'duration', 'warnings']) {
|
|
143
153
|
if (!recommendation.otcOffer[field]) {
|
|
@@ -607,7 +607,9 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ri
|
|
|
607
607
|
repairs = [];
|
|
608
608
|
const built = rawElements.map((raw) => buildElement(raw, repairs));
|
|
609
609
|
stripOtcOffers(built, repairs);
|
|
610
|
-
const {
|
|
610
|
+
const {
|
|
611
|
+
elements, dropped, stripped, urgentReframed,
|
|
612
|
+
} = applyCardSurfaceBoundary(built, boundary, repairs, { rescue: last });
|
|
611
613
|
deniedCardsDropped = dropped;
|
|
612
614
|
deniedTargetsStripped = stripped;
|
|
613
615
|
if (!elements.length) {
|
|
@@ -616,7 +618,7 @@ async function runPlan({ provider, presetId, casoBase, gate, boundary = null, ri
|
|
|
616
618
|
return { attempts: attempt, repairs, failure: { status: 'failed', stage: 'validate', reason: 'plan_all_denied', hardRejectIssues: lastIssues } };
|
|
617
619
|
}
|
|
618
620
|
rankReordered = applyRankOrder(elements, gate, repairs);
|
|
619
|
-
const issues = validate(elements, { gate, lane: 'triage' });
|
|
621
|
+
const issues = validate(elements, { gate, lane: 'triage', urgentReframed });
|
|
620
622
|
const blocking = blockingIssues(issues);
|
|
621
623
|
if (blocking.length) {
|
|
622
624
|
lastIssues = blocking;
|
|
@@ -6,7 +6,6 @@ const { isAllowedUrl, redactDirectIdentifiers } = require('../utils/sanitizerUti
|
|
|
6
6
|
const { getPatientInformation, updatePatientInformation, logPatientChange } = require('../services/patientService');
|
|
7
7
|
const { getTriageHistory } = require('../services/triageHistoryService');
|
|
8
8
|
const { getCarePlanHistory } = require('../services/carePlanHistoryService');
|
|
9
|
-
const { getEscalationContext } = require('../services/escalationContextService');
|
|
10
9
|
const { getPatientTasks, updatePatientTask } = require('../services/patientTaskService');
|
|
11
10
|
const {
|
|
12
11
|
getRecommendationCarousels,
|
|
@@ -242,25 +241,10 @@ const logPatientChangeController = async (req, res) => {
|
|
|
242
241
|
}
|
|
243
242
|
};
|
|
244
243
|
|
|
245
|
-
const getPatientEscalationContextController = async (req, res) => {
|
|
246
|
-
try {
|
|
247
|
-
const context = await getEscalationContext({ code: req.params.code });
|
|
248
|
-
res.status(200).json({ success: true, context });
|
|
249
|
-
} catch (error) {
|
|
250
|
-
logger.error('Error fetching patient escalation context:', {
|
|
251
|
-
error: redactDirectIdentifiers(String(error.message || '')),
|
|
252
|
-
stack: redactDirectIdentifiers(String(error.stack || '')),
|
|
253
|
-
code: redactDirectIdentifiers(String(req.params?.code || '')),
|
|
254
|
-
});
|
|
255
|
-
res.status(error.statusCode || 500).json({ success: false, error: error.message });
|
|
256
|
-
}
|
|
257
|
-
};
|
|
258
|
-
|
|
259
244
|
module.exports = {
|
|
260
245
|
getPatientInfoController,
|
|
261
246
|
getPatientTriageInfoController,
|
|
262
247
|
getPatientCarePlanController,
|
|
263
|
-
getPatientEscalationContextController,
|
|
264
248
|
getPatientTasksController,
|
|
265
249
|
getPatientRecommendationCarouselsController,
|
|
266
250
|
getPatientRecommendationCarouselImageController,
|
package/lib/routes/index.js
CHANGED
|
@@ -70,7 +70,6 @@ const patientRouteDefinitions = {
|
|
|
70
70
|
'GET /:code': 'getPatientInfoController',
|
|
71
71
|
'GET /triage/:code': 'getPatientTriageInfoController',
|
|
72
72
|
'GET /careplan/:code': 'getPatientCarePlanController',
|
|
73
|
-
'GET /escalation-context/:code': 'getPatientEscalationContextController',
|
|
74
73
|
'GET /tasks/:code': 'getPatientTasksController',
|
|
75
74
|
'PATCH /:code': 'updatePatientController',
|
|
76
75
|
'PATCH /tasks/:code/:kind/:recordId': 'updatePatientTaskController',
|
|
@@ -215,7 +214,6 @@ const builtInControllers = {
|
|
|
215
214
|
getPatientInfoController: patientController.getPatientInfoController,
|
|
216
215
|
getPatientTriageInfoController: patientController.getPatientTriageInfoController,
|
|
217
216
|
getPatientCarePlanController: patientController.getPatientCarePlanController,
|
|
218
|
-
getPatientEscalationContextController: patientController.getPatientEscalationContextController,
|
|
219
217
|
getPatientTasksController: patientController.getPatientTasksController,
|
|
220
218
|
getPatientRecommendationCarouselsController: patientController.getPatientRecommendationCarouselsController,
|
|
221
219
|
getPatientRecommendationCarouselImageController: patientController.getPatientRecommendationCarouselImageController,
|
package/package.json
CHANGED
|
@@ -1,81 +0,0 @@
|
|
|
1
|
-
const { isoDay } = require('../utils/dateUtils');
|
|
2
|
-
const { logger } = require('../utils/logger');
|
|
3
|
-
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
4
|
-
const { withTimeout } = require('../utils/timeoutUtils');
|
|
5
|
-
const { ensureWhatsAppFormat } = require('../helpers/twilioHelper');
|
|
6
|
-
const { assembleHistory } = require('../clinical/services/patientHistoryService');
|
|
7
|
-
const { DefaultMemoryManager } = require('../clinical/memory/DefaultMemoryManager');
|
|
8
|
-
|
|
9
|
-
const { getCarePlanHistory } = require('./carePlanHistoryService');
|
|
10
|
-
const { getPatientInformation } = require('./patientService');
|
|
11
|
-
const { getTriageHistory } = require('./triageHistoryService');
|
|
12
|
-
|
|
13
|
-
const SECTION_TIMEOUT_MS = 10000;
|
|
14
|
-
const TRIAGE_WINDOW_DAYS = 30;
|
|
15
|
-
const CARE_PLAN_LIMIT = 5;
|
|
16
|
-
const HISTORY_SCOPE = ['closed_cases_90d', 'recurrence_patterns', 'recent_medications', 'patient_reported_procedures'];
|
|
17
|
-
|
|
18
|
-
const httpError = (statusCode, message) => Object.assign(new Error(message), { statusCode });
|
|
19
|
-
|
|
20
|
-
function sectionReaders(code, now) {
|
|
21
|
-
const memoryManager = new DefaultMemoryManager();
|
|
22
|
-
const triageStart = isoDay(new Date(now - TRIAGE_WINDOW_DAYS * 86400000).toISOString());
|
|
23
|
-
return {
|
|
24
|
-
agentContext: () => memoryManager.getClinicalData(code),
|
|
25
|
-
conversation: () => memoryManager.buildContext({ thread: { code } }),
|
|
26
|
-
triages: () => getTriageHistory({ code, startDate: triageStart }),
|
|
27
|
-
carePlan: () => getCarePlanHistory({ code, limit: CARE_PLAN_LIMIT }),
|
|
28
|
-
history: () => assembleHistory(code, { scope: HISTORY_SCOPE }),
|
|
29
|
-
};
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
async function getEscalationContext({ code, now = Date.now(), timeoutMs = SECTION_TIMEOUT_MS } = {}) {
|
|
33
|
-
const patientCode = ensureWhatsAppFormat(String(code ?? '').trim());
|
|
34
|
-
if (!PATIENT_CODE.test(patientCode)) throw httpError(400, 'A valid WhatsApp ID is required');
|
|
35
|
-
|
|
36
|
-
const patient = await withTimeout(getPatientInformation(patientCode), timeoutMs, 'patient lookup');
|
|
37
|
-
if (!patient) throw httpError(404, 'Patient not found');
|
|
38
|
-
|
|
39
|
-
const readers = sectionReaders(patientCode, now);
|
|
40
|
-
const names = Object.keys(readers);
|
|
41
|
-
const outcomes = await Promise.allSettled(names.map((name) => withTimeout(readers[name](), timeoutMs, name)));
|
|
42
|
-
|
|
43
|
-
const context = { patientCode, asOf: new Date(now).toISOString(), degradedSections: [] };
|
|
44
|
-
outcomes.forEach((outcome, index) => {
|
|
45
|
-
const name = names[index];
|
|
46
|
-
if (outcome.status === 'fulfilled' && outcome.value != null) {
|
|
47
|
-
context[name] = outcome.value;
|
|
48
|
-
return;
|
|
49
|
-
}
|
|
50
|
-
context[name] = null;
|
|
51
|
-
context.degradedSections.push(name);
|
|
52
|
-
if (outcome.status === 'rejected') {
|
|
53
|
-
logger.error('[escalationContextService] Section reader failed', {
|
|
54
|
-
code: patientCode,
|
|
55
|
-
section: name,
|
|
56
|
-
error: redactDirectIdentifiers(String(outcome.reason?.message ?? outcome.reason)),
|
|
57
|
-
stack: redactDirectIdentifiers(String(outcome.reason?.stack ?? '')),
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
if (context.conversation) {
|
|
63
|
-
context.conversation = context.conversation
|
|
64
|
-
.filter((item) => item.type === 'message')
|
|
65
|
-
.map(({ role, content }) => ({ role, content }));
|
|
66
|
-
}
|
|
67
|
-
if (context.triages) {
|
|
68
|
-
if (context.triages.pagination?.hasNext) context.degradedSections.push('triages');
|
|
69
|
-
context.triages = context.triages.records;
|
|
70
|
-
}
|
|
71
|
-
if (context.carePlan) {
|
|
72
|
-
const { records, pagination = null, currentState = null } = context.carePlan;
|
|
73
|
-
const { degradedSections: carePlanDegraded = [], ...state } = currentState || {};
|
|
74
|
-
context.carePlan = { records, pagination, currentState: currentState ? state : null };
|
|
75
|
-
for (const section of carePlanDegraded) context.degradedSections.push(`carePlan.${section}`);
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
return context;
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
module.exports = { getEscalationContext };
|