@peopl-health/nexus 5.51.0-dev.7633 → 5.51.0-dev.7637
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/README.md +21 -0
- package/lib/clinical/AssistantProcessor.js +156 -12
- package/lib/clinical/context/ToolRuntimeContext.js +39 -1
- package/lib/clinical/context/turnContext.js +10 -0
- package/lib/clinical/models/supportCandidateModel.js +90 -0
- package/lib/clinical/models/triageRecommendationEventModel.js +28 -0
- package/lib/clinical/providers/BaseLLMProvider.js +45 -5
- package/lib/clinical/services/clinicalAirtableService.js +8 -5
- package/lib/clinical/services/deliverySettlementService.js +39 -0
- package/lib/clinical/services/divergenceService.js +9 -2
- package/lib/clinical/services/supportActionService.js +129 -0
- package/lib/clinical/services/supportCandidateService.js +532 -0
- package/lib/clinical/services/supportRoutingAgentService.js +118 -0
- package/lib/clinical/services/triageRecommendationService.js +453 -251
- package/lib/clinical/tools/deliverPatientMessageTool.js +82 -23
- package/lib/clinical/tools/registerClinicalTools.js +2 -0
- package/lib/clinical/tools/submitNutritionSafetyDecisionTool.js +200 -0
- package/lib/clinical/tools/submitSupportRoutingRecommendationTool.js +142 -0
- package/lib/controllers/dashboardController.js +5 -2
- package/lib/controllers/escalationReviewController.js +0 -12
- package/lib/core/BatchingManager.js +20 -9
- package/lib/core/NexusMessaging.js +25 -6
- package/lib/core/ProcessingPipeline.js +32 -3
- package/lib/core/runtimeToolPolicy.js +3 -0
- package/lib/index.d.ts +334 -6
- package/lib/index.js +22 -0
- package/lib/models/escalationReviewModel.js +0 -4
- package/lib/routes/index.js +0 -2
- package/lib/services/airtableService.js +8 -1
- package/lib/services/dashboard-provider-registry.js +38 -0
- package/lib/services/dashboardService.js +30 -3
- package/lib/services/escalationReviewService.js +4 -36
- package/lib/shared/dtos/NutritionSafetyDecision.js +128 -0
- package/lib/shared/dtos/SupportAction.js +28 -0
- package/lib/shared/dtos/SupportRoutingRecommendation.js +124 -0
- package/package.json +1 -1
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const { withTimeout } = require('../utils/timeoutUtils');
|
|
2
|
+
|
|
3
|
+
const providers = new Map();
|
|
4
|
+
const SOURCE = 'auna.support.v1';
|
|
5
|
+
|
|
6
|
+
function registerDashboardProvider(source, provider) {
|
|
7
|
+
if (source !== SOURCE || typeof provider !== 'function' || providers.has(source)) {
|
|
8
|
+
throw new Error('Invalid or duplicate dashboard provider');
|
|
9
|
+
}
|
|
10
|
+
providers.set(source, provider);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function validateDashboardSource(config) {
|
|
14
|
+
if (config?.source !== SOURCE || config.metric !== 'exceptions' || !providers.has(config.source)) {
|
|
15
|
+
throw new Error('Dashboard provider unavailable');
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async function readDashboardProvider(config, now) {
|
|
20
|
+
validateDashboardSource(config);
|
|
21
|
+
try {
|
|
22
|
+
const snapshot = await withTimeout(Promise.resolve().then(() => providers.get(config.source)({ now })), 15000, 'Dashboard provider');
|
|
23
|
+
const metric = snapshot?.metrics?.exceptions;
|
|
24
|
+
if (snapshot?.generatedAt !== now.toISOString() || Object.keys(snapshot.metrics).length !== 1
|
|
25
|
+
|| !Array.isArray(metric?.records) || metric.records.length > 2000 || !Array.isArray(metric.struct)
|
|
26
|
+
|| metric.records.some(row => !row || typeof row !== 'object' || Array.isArray(row))
|
|
27
|
+
|| metric.struct.some(column => typeof column !== 'string')
|
|
28
|
+
|| !['indicator', 'sample', 'total'].every(key => metric[key] === metric.records.length)) {
|
|
29
|
+
throw new Error('Invalid dashboard snapshot');
|
|
30
|
+
}
|
|
31
|
+
const { indicator, sample, total, struct, records } = metric;
|
|
32
|
+
return { generatedAt: snapshot.generatedAt, indicator, sample, total, struct, records };
|
|
33
|
+
} catch {
|
|
34
|
+
throw new Error('Dashboard provider unavailable');
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { registerDashboardProvider, validateDashboardSource, readDashboardProvider };
|
|
@@ -5,6 +5,7 @@ const { fetchBoxesFromAirtable, fetchDetailsFromAirtable, attachPreview } = requ
|
|
|
5
5
|
const { getMexicoDateRange, buildPatientMessagesPipeline, buildToolDistributionPipeline, mergeTrendData } = require('../helpers/trendHelper');
|
|
6
6
|
|
|
7
7
|
const { aggregateMessages } = require('./messageService');
|
|
8
|
+
const { validateDashboardSource, readDashboardProvider } = require('./dashboard-provider-registry');
|
|
8
9
|
|
|
9
10
|
const boxCache = new MapCache({ maxSize: 100 });
|
|
10
11
|
const detailCache = new MapCache({ maxSize: 100 });
|
|
@@ -16,7 +17,7 @@ async function seedCaches() {
|
|
|
16
17
|
const boxes = await fetchBoxesFromAirtable();
|
|
17
18
|
boxes.forEach(box => boxCache.set(box.id, box));
|
|
18
19
|
|
|
19
|
-
const details = await fetchDetailsFromAirtable(boxes);
|
|
20
|
+
const details = await fetchDetailsFromAirtable(boxes.filter(box => box.config?.source === undefined));
|
|
20
21
|
details.forEach(({ id, records }) => {
|
|
21
22
|
detailCache.set(id, records);
|
|
22
23
|
const box = boxCache.get(id);
|
|
@@ -40,10 +41,23 @@ async function ensureSeeded(force) {
|
|
|
40
41
|
|
|
41
42
|
async function getAllBoxes(force) {
|
|
42
43
|
await ensureSeeded(force);
|
|
43
|
-
|
|
44
|
+
const snapshots = new Map();
|
|
45
|
+
const now = new Date();
|
|
46
|
+
return Promise.all(Array.from(boxCache.entries()).map(async ([id, { config, ...data }]) => {
|
|
47
|
+
if (config?.source === undefined) return { id, ...data };
|
|
48
|
+
validateDashboardSource(config);
|
|
49
|
+
if (!snapshots.has(config.source)) snapshots.set(config.source, readDashboardProvider(config, now));
|
|
50
|
+
const { records, struct: _struct, ...metric } = await snapshots.get(config.source);
|
|
51
|
+
const box = { id, ...data, ...metric };
|
|
52
|
+
attachPreview(box, records);
|
|
53
|
+
return box;
|
|
54
|
+
}));
|
|
44
55
|
}
|
|
45
56
|
|
|
46
57
|
async function getStatsById(cacheId) {
|
|
58
|
+
await ensureSeeded(false);
|
|
59
|
+
const config = boxCache.get(cacheId)?.config;
|
|
60
|
+
if (config?.source !== undefined) return { id: cacheId, ...await readDashboardProvider(config, new Date()) };
|
|
47
61
|
const detail = detailCache.get(cacheId);
|
|
48
62
|
if (!detail) return null;
|
|
49
63
|
const struct = boxCache.get(cacheId)?.config?.columns || [];
|
|
@@ -51,11 +65,24 @@ async function getStatsById(cacheId) {
|
|
|
51
65
|
}
|
|
52
66
|
|
|
53
67
|
async function updateBox(id, data) {
|
|
68
|
+
if (!data.config || Object.keys(data.config).length === 0) {
|
|
69
|
+
await ensureSeeded(false);
|
|
70
|
+
data = { ...data, config: boxCache.get(id)?.config };
|
|
71
|
+
}
|
|
72
|
+
if (data.config?.source !== undefined) {
|
|
73
|
+
validateDashboardSource(data.config);
|
|
74
|
+
data = Object.fromEntries(Object.entries(data).filter(([key]) => ['id', 'title', 'type', 'metadata', 'config'].includes(key)));
|
|
75
|
+
if (data.metadata) {
|
|
76
|
+
const { preview: _preview, ...metadata } = data.metadata;
|
|
77
|
+
data.metadata = metadata;
|
|
78
|
+
}
|
|
79
|
+
detailCache.delete(id);
|
|
80
|
+
}
|
|
54
81
|
boxCache.set(id, data);
|
|
55
82
|
logger.info('[DashboardService] Box cache updated', { id });
|
|
56
83
|
|
|
57
84
|
const box = boxCache.get(id);
|
|
58
|
-
if (box?.config?.table) {
|
|
85
|
+
if (box?.config?.source === undefined && box?.config?.table) {
|
|
59
86
|
const [detail] = await fetchDetailsFromAirtable([box]);
|
|
60
87
|
if (detail) {
|
|
61
88
|
detailCache.set(detail.id, detail.records);
|
|
@@ -6,7 +6,6 @@ const { logger } = require('../utils/logger');
|
|
|
6
6
|
const { PATIENT_CODE, redactDirectIdentifiers } = require('../utils/sanitizerUtils');
|
|
7
7
|
const {
|
|
8
8
|
CALL_OUTCOMES,
|
|
9
|
-
CANCELLABLE_STATUSES,
|
|
10
9
|
DECISION_SOURCES,
|
|
11
10
|
DOCTOR_DECISIONS,
|
|
12
11
|
HANDOFF_MODES,
|
|
@@ -249,24 +248,6 @@ const deliveryTransport = (message, result) => {
|
|
|
249
248
|
return result.deferred ? 'template_recovery' : 'text';
|
|
250
249
|
};
|
|
251
250
|
|
|
252
|
-
let indexesReady = new WeakMap();
|
|
253
|
-
|
|
254
|
-
function ensureActiveReviewIndex(EscalationReview) {
|
|
255
|
-
const pending = indexesReady.get(EscalationReview);
|
|
256
|
-
if (pending) return pending;
|
|
257
|
-
|
|
258
|
-
const building = EscalationReview.ensureIndexes().catch((error) => {
|
|
259
|
-
indexesReady.delete(EscalationReview);
|
|
260
|
-
if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
|
|
261
|
-
logger.error('[EscalationReview] A uniqueness index could not be built', { error: redactedError(error) });
|
|
262
|
-
throw httpError(409, 'Escalation reviews cannot be opened: a uniqueness index could not be built. The server log names the index and the conflict; resolve it and retry.');
|
|
263
|
-
});
|
|
264
|
-
indexesReady.set(EscalationReview, building);
|
|
265
|
-
return building;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
const _resetEscalationReviewIndexes = () => { indexesReady = new WeakMap(); };
|
|
269
|
-
|
|
270
251
|
async function openEscalationReview({ code, patientCaseRecordId = null, openedBy, requestId = null } = {}) {
|
|
271
252
|
const patientCode = patientCodeOf(code);
|
|
272
253
|
const operator = requiredText(openedBy, 'openedBy');
|
|
@@ -283,14 +264,14 @@ async function openEscalationReview({ code, patientCaseRecordId = null, openedBy
|
|
|
283
264
|
}
|
|
284
265
|
|
|
285
266
|
const EscalationReview = getEscalationReview();
|
|
286
|
-
await
|
|
267
|
+
await EscalationReview.init();
|
|
287
268
|
let review;
|
|
288
269
|
try {
|
|
289
270
|
review = (await EscalationReview.create(fields)).toObject();
|
|
290
271
|
} catch (error) {
|
|
291
|
-
if (error?.code !== DUPLICATE_KEY_ERROR) throw error;
|
|
292
|
-
const existing = await EscalationReview.findOne({
|
|
293
|
-
if (!existing) throw httpError(409, '
|
|
272
|
+
if (error?.code !== DUPLICATE_KEY_ERROR || !fields.activeCaseKey) throw error;
|
|
273
|
+
const existing = await EscalationReview.findOne({ activeCaseKey: fields.activeCaseKey }).lean();
|
|
274
|
+
if (!existing) throw httpError(409, 'The patient case review changed while opening; try again');
|
|
294
275
|
return { review: existing, created: false };
|
|
295
276
|
}
|
|
296
277
|
await audit(review, operator, requestId, { action: 'opened', patientCaseRecordId });
|
|
@@ -543,17 +524,6 @@ async function closeEscalationReview({ id, closedBy, deliveryConfirmed = false,
|
|
|
543
524
|
return syncCase(review, operator, requestId);
|
|
544
525
|
}
|
|
545
526
|
|
|
546
|
-
async function cancelEscalationReview({ id, cancelledBy, reason = null, requestId = null } = {}) {
|
|
547
|
-
const reviewId = reviewIdOf(id);
|
|
548
|
-
const operator = requiredText(cancelledBy, 'cancelledBy');
|
|
549
|
-
const review = await updateReview(reviewId, CANCELLABLE_STATUSES, {
|
|
550
|
-
$set: { status: 'cancelled', closedBy: operator, closedAt: new Date() },
|
|
551
|
-
$unset: { activeCaseKey: '' },
|
|
552
|
-
});
|
|
553
|
-
await audit(review, operator, requestId, { action: 'cancelled', reason: optionalText(reason) });
|
|
554
|
-
return review;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
527
|
async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {}) {
|
|
558
528
|
const reviewId = reviewIdOf(id);
|
|
559
529
|
const operator = requiredText(syncedBy, 'syncedBy');
|
|
@@ -561,10 +531,8 @@ async function syncEscalationReviewCase({ id, syncedBy, requestId = null } = {})
|
|
|
561
531
|
}
|
|
562
532
|
|
|
563
533
|
module.exports = {
|
|
564
|
-
_resetEscalationReviewIndexes,
|
|
565
534
|
addCallLog,
|
|
566
535
|
addDraft,
|
|
567
|
-
cancelEscalationReview,
|
|
568
536
|
closeEscalationReview,
|
|
569
537
|
getEscalationReviewById,
|
|
570
538
|
handOffToDoctor,
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
const { z } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { BaseDto } = require('./BaseDto');
|
|
4
|
+
|
|
5
|
+
const FINDING_CODES = [
|
|
6
|
+
'cannot_eat',
|
|
7
|
+
'cannot_keep_fluids',
|
|
8
|
+
'bleeding',
|
|
9
|
+
'severe_abdominal_pain',
|
|
10
|
+
];
|
|
11
|
+
const FINDING_VALUES = ['yes', 'no', 'unknown'];
|
|
12
|
+
const FINDING_TO_QUESTION = Object.freeze({
|
|
13
|
+
cannot_eat: 'can_eat',
|
|
14
|
+
cannot_keep_fluids: 'can_keep_fluids',
|
|
15
|
+
bleeding: 'bleeding',
|
|
16
|
+
severe_abdominal_pain: 'severe_abdominal_pain',
|
|
17
|
+
});
|
|
18
|
+
const QUESTION_CODES = Object.freeze(FINDING_CODES.map(code => FINDING_TO_QUESTION[code]));
|
|
19
|
+
const EVIDENCE_SOURCE_TYPES = ['chat', 'flow', 'historical', 'forecast'];
|
|
20
|
+
const CURRENT_EVIDENCE_SOURCE_TYPES = new Set(['chat', 'flow']);
|
|
21
|
+
const DISPOSITIONS = ['clear', 'clarify', 'escalate', 'review_required'];
|
|
22
|
+
|
|
23
|
+
const findingsSchema = z.strictObject(Object.fromEntries(
|
|
24
|
+
FINDING_CODES.map(code => [code, z.enum(FINDING_VALUES)]),
|
|
25
|
+
));
|
|
26
|
+
|
|
27
|
+
const evidenceRefSchema = z.strictObject({
|
|
28
|
+
finding: z.enum(FINDING_CODES),
|
|
29
|
+
source_type: z.enum(EVIDENCE_SOURCE_TYPES),
|
|
30
|
+
source_id: z.string().min(1),
|
|
31
|
+
observed_at: z.string().datetime({ offset: true }),
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
const schema = z.strictObject({
|
|
35
|
+
submission_revision: z.number().int().positive(),
|
|
36
|
+
screen_revision: z.number().int().nonnegative(),
|
|
37
|
+
findings: findingsSchema,
|
|
38
|
+
evidence_refs: z.array(evidenceRefSchema).min(FINDING_CODES.length),
|
|
39
|
+
questions_needed: z.array(z.enum(QUESTION_CODES)).max(QUESTION_CODES.length)
|
|
40
|
+
.refine(values => new Set(values).size === values.length, 'question codes must be unique'),
|
|
41
|
+
disposition: z.enum(DISPOSITIONS),
|
|
42
|
+
}).superRefine((value, ctx) => {
|
|
43
|
+
const unknown = FINDING_CODES.filter(code => value.findings[code] === 'unknown');
|
|
44
|
+
const yes = FINDING_CODES.filter(code => value.findings[code] === 'yes');
|
|
45
|
+
const questions = new Set(value.questions_needed);
|
|
46
|
+
for (const finding of FINDING_CODES) {
|
|
47
|
+
const references = value.evidence_refs.filter(reference => reference.finding === finding);
|
|
48
|
+
if (references.length === 0) {
|
|
49
|
+
ctx.addIssue({
|
|
50
|
+
code: 'custom',
|
|
51
|
+
path: ['evidence_refs'],
|
|
52
|
+
message: `evidence is required for ${finding}`,
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
if (value.findings[finding] !== 'unknown'
|
|
56
|
+
&& !references.some(reference => CURRENT_EVIDENCE_SOURCE_TYPES.has(reference.source_type))) {
|
|
57
|
+
ctx.addIssue({
|
|
58
|
+
code: 'custom',
|
|
59
|
+
path: ['evidence_refs'],
|
|
60
|
+
message: `${finding} requires current Flow or active chat evidence`,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
if (value.findings[finding] !== 'unknown'
|
|
64
|
+
&& references.some(reference => !CURRENT_EVIDENCE_SOURCE_TYPES.has(reference.source_type))) {
|
|
65
|
+
ctx.addIssue({
|
|
66
|
+
code: 'custom',
|
|
67
|
+
path: ['evidence_refs'],
|
|
68
|
+
message: 'historical and forecast evidence may only support unknown findings',
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (value.disposition === 'clear') {
|
|
73
|
+
if (FINDING_CODES.some(code => value.findings[code] !== 'no')) {
|
|
74
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'clear requires every finding to be no' });
|
|
75
|
+
}
|
|
76
|
+
if (value.questions_needed.length > 0) {
|
|
77
|
+
ctx.addIssue({ code: 'custom', path: ['questions_needed'], message: 'clear cannot request questions' });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
if (value.disposition === 'clarify') {
|
|
81
|
+
const expectedQuestions = unknown.map(code => FINDING_TO_QUESTION[code]);
|
|
82
|
+
if (unknown.length === 0
|
|
83
|
+
|| expectedQuestions.some(code => !questions.has(code))
|
|
84
|
+
|| questions.size !== expectedQuestions.length) {
|
|
85
|
+
ctx.addIssue({ code: 'custom', path: ['questions_needed'], message: 'clarify must request every and only unknown finding' });
|
|
86
|
+
}
|
|
87
|
+
if (yes.length > 0) {
|
|
88
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'a confirmed warning requires escalation' });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (value.disposition === 'review_required' && yes.length > 0) {
|
|
92
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'a confirmed warning requires escalation' });
|
|
93
|
+
}
|
|
94
|
+
if (value.disposition === 'escalate') {
|
|
95
|
+
if (yes.length === 0) {
|
|
96
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'escalate requires a confirmed warning finding' });
|
|
97
|
+
}
|
|
98
|
+
if (value.questions_needed.length > 0) {
|
|
99
|
+
ctx.addIssue({ code: 'custom', path: ['questions_needed'], message: 'escalate cannot request questions' });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}).transform(value => ({
|
|
103
|
+
submissionRevision: value.submission_revision,
|
|
104
|
+
screenRevision: value.screen_revision,
|
|
105
|
+
findings: value.findings,
|
|
106
|
+
evidenceRefs: value.evidence_refs.map(reference => ({
|
|
107
|
+
finding: reference.finding,
|
|
108
|
+
sourceType: reference.source_type,
|
|
109
|
+
sourceId: reference.source_id,
|
|
110
|
+
observedAt: reference.observed_at,
|
|
111
|
+
})),
|
|
112
|
+
questionsNeeded: value.questions_needed,
|
|
113
|
+
disposition: value.disposition,
|
|
114
|
+
}));
|
|
115
|
+
|
|
116
|
+
class NutritionSafetyDecision extends BaseDto {}
|
|
117
|
+
|
|
118
|
+
NutritionSafetyDecision.schema = schema;
|
|
119
|
+
|
|
120
|
+
module.exports = {
|
|
121
|
+
NutritionSafetyDecision,
|
|
122
|
+
FINDING_CODES,
|
|
123
|
+
FINDING_VALUES,
|
|
124
|
+
FINDING_TO_QUESTION,
|
|
125
|
+
QUESTION_CODES,
|
|
126
|
+
EVIDENCE_SOURCE_TYPES,
|
|
127
|
+
DISPOSITIONS,
|
|
128
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const { z } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { BaseDto } = require('./BaseDto');
|
|
4
|
+
|
|
5
|
+
const actionSchema = z.strictObject({
|
|
6
|
+
candidateId: z.string().min(1),
|
|
7
|
+
service: z.enum(['nutrition', 'psychology']),
|
|
8
|
+
type: z.enum(['group_registration', 'urgent_nutrition_intake']),
|
|
9
|
+
invitationClass: z.enum(['first', 'followup']).nullable().default(null),
|
|
10
|
+
idempotencyKey: z.string().min(1).nullable().optional(),
|
|
11
|
+
targetKey: z.string().min(1),
|
|
12
|
+
priority: z.enum(['routine', 'soon', 'urgent']),
|
|
13
|
+
}).refine((action) => action.type !== 'group_registration' || Boolean(action.idempotencyKey), {
|
|
14
|
+
path: ['idempotencyKey'], message: 'group registration requires idempotencyKey',
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const supportActionSchema = z.strictObject({
|
|
18
|
+
schemaVersion: z.literal('1'),
|
|
19
|
+
patientId: z.string().min(1),
|
|
20
|
+
sourceId: z.string().min(1),
|
|
21
|
+
actions: z.array(actionSchema).min(1).max(3),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
class SupportAction extends BaseDto {}
|
|
25
|
+
|
|
26
|
+
SupportAction.schema = supportActionSchema;
|
|
27
|
+
|
|
28
|
+
module.exports = { SupportAction };
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
const { z } = require('zod');
|
|
2
|
+
|
|
3
|
+
const { BaseDto } = require('./BaseDto');
|
|
4
|
+
|
|
5
|
+
const dateTime = z.iso.datetime({ offset: true });
|
|
6
|
+
const PRIORITIES = ['routine', 'soon', 'urgent'];
|
|
7
|
+
const DISPOSITIONS = ['group', 'individual', 'escalated', 'reviewRequired', 'none'];
|
|
8
|
+
|
|
9
|
+
const evidenceSchema = z.strictObject({
|
|
10
|
+
source: z.enum(['triage', 'chat', 'fhir', 'airtable']),
|
|
11
|
+
sourceId: z.string().min(1),
|
|
12
|
+
code: z.string().min(1),
|
|
13
|
+
summary: z.string().max(300).nullable().default(null),
|
|
14
|
+
confidence: z.number().min(0).max(1).nullable().default(null),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const safetySchema = z.strictObject({
|
|
18
|
+
suicidalIdeation: z.boolean().default(false),
|
|
19
|
+
immediateRisk: z.boolean().default(false),
|
|
20
|
+
urgentMedicalRisk: z.boolean().default(false),
|
|
21
|
+
needsHumanConfirmation: z.boolean().default(false),
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const decisionBase = {
|
|
25
|
+
disposition: z.enum(DISPOSITIONS),
|
|
26
|
+
groupEligible: z.boolean(),
|
|
27
|
+
priority: z.enum(PRIORITIES).default('routine'),
|
|
28
|
+
confidence: z.number().min(0).max(1),
|
|
29
|
+
reasonCodes: z.array(z.string().min(1)).max(20).default([]),
|
|
30
|
+
evidence: z.array(evidenceSchema).min(1).max(20),
|
|
31
|
+
safety: safetySchema,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const nutritionDecisionSchema = z.strictObject({
|
|
35
|
+
service: z.literal('nutrition'),
|
|
36
|
+
nutritionRisk: z.enum(['green', 'yellow', 'red', 'unknown']),
|
|
37
|
+
urgentIntakeEligible: z.boolean(),
|
|
38
|
+
...decisionBase,
|
|
39
|
+
}).superRefine((decision, ctx) => {
|
|
40
|
+
const expected = {
|
|
41
|
+
green: { eligible: true, urgentIntakeEligible: false, dispositions: ['group'] },
|
|
42
|
+
yellow: { eligible: null, urgentIntakeEligible: true, dispositions: ['individual'] },
|
|
43
|
+
red: { eligible: false, urgentIntakeEligible: false, dispositions: ['escalated'] },
|
|
44
|
+
unknown: { eligible: false, urgentIntakeEligible: false, dispositions: ['reviewRequired'] },
|
|
45
|
+
}[decision.nutritionRisk];
|
|
46
|
+
if (expected.eligible !== null && decision.groupEligible !== expected.eligible) {
|
|
47
|
+
ctx.addIssue({ code: 'custom', path: ['groupEligible'], message: `nutrition ${decision.nutritionRisk} has invalid group eligibility` });
|
|
48
|
+
}
|
|
49
|
+
if (decision.urgentIntakeEligible !== expected.urgentIntakeEligible) {
|
|
50
|
+
ctx.addIssue({ code: 'custom', path: ['urgentIntakeEligible'], message: `nutrition ${decision.nutritionRisk} has invalid urgent intake eligibility` });
|
|
51
|
+
}
|
|
52
|
+
if (!expected.dispositions.includes(decision.disposition)) {
|
|
53
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: `nutrition ${decision.nutritionRisk} has invalid disposition` });
|
|
54
|
+
}
|
|
55
|
+
if (!decision.safety.urgentMedicalRisk) {
|
|
56
|
+
if (decision.disposition === 'escalated') {
|
|
57
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'nutrition escalation requires urgent medical risk' });
|
|
58
|
+
}
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (decision.disposition !== 'escalated') {
|
|
62
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'urgent medical risk permits escalation only' });
|
|
63
|
+
}
|
|
64
|
+
if (decision.groupEligible) {
|
|
65
|
+
ctx.addIssue({ code: 'custom', path: ['groupEligible'], message: 'urgent medical risk cannot be group eligible' });
|
|
66
|
+
}
|
|
67
|
+
if (decision.urgentIntakeEligible) {
|
|
68
|
+
ctx.addIssue({ code: 'custom', path: ['urgentIntakeEligible'], message: 'urgent medical risk cannot be urgent intake eligible' });
|
|
69
|
+
}
|
|
70
|
+
if (decision.priority !== 'urgent') {
|
|
71
|
+
ctx.addIssue({ code: 'custom', path: ['priority'], message: 'urgent medical risk requires urgent priority' });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
const psychologyDecisionSchema = z.strictObject({
|
|
76
|
+
service: z.literal('psychology'),
|
|
77
|
+
psychologyRisk: z.enum(['green', 'orange', 'red', 'unknown']),
|
|
78
|
+
...decisionBase,
|
|
79
|
+
}).superRefine((decision, ctx) => {
|
|
80
|
+
const expected = {
|
|
81
|
+
green: { eligible: true, dispositions: ['group'] },
|
|
82
|
+
orange: { eligible: false, dispositions: ['individual'] },
|
|
83
|
+
red: { eligible: false, dispositions: ['escalated'] },
|
|
84
|
+
unknown: { eligible: false, dispositions: ['reviewRequired'] },
|
|
85
|
+
}[decision.psychologyRisk];
|
|
86
|
+
if (decision.groupEligible !== expected.eligible) {
|
|
87
|
+
ctx.addIssue({ code: 'custom', path: ['groupEligible'], message: `psychology ${decision.psychologyRisk} has invalid group eligibility` });
|
|
88
|
+
}
|
|
89
|
+
if (!expected.dispositions.includes(decision.disposition)) {
|
|
90
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: `psychology ${decision.psychologyRisk} has invalid disposition` });
|
|
91
|
+
}
|
|
92
|
+
if ((decision.safety.suicidalIdeation || decision.safety.immediateRisk) && decision.psychologyRisk !== 'red') {
|
|
93
|
+
ctx.addIssue({ code: 'custom', path: ['psychologyRisk'], message: 'immediate or suicidal risk must be red' });
|
|
94
|
+
}
|
|
95
|
+
if ((decision.safety.suicidalIdeation || decision.safety.immediateRisk) && decision.priority !== 'urgent') {
|
|
96
|
+
ctx.addIssue({ code: 'custom', path: ['priority'], message: 'immediate or suicidal risk requires urgent priority' });
|
|
97
|
+
}
|
|
98
|
+
if ((decision.safety.suicidalIdeation || decision.safety.immediateRisk) && decision.disposition !== 'escalated') {
|
|
99
|
+
ctx.addIssue({ code: 'custom', path: ['disposition'], message: 'immediate or suicidal risk requires escalation' });
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const schema = z.strictObject({
|
|
104
|
+
schemaVersion: z.string().default('1'),
|
|
105
|
+
decisionVersion: z.string().default('support-routing-v1'),
|
|
106
|
+
patientId: z.string().trim().min(1),
|
|
107
|
+
origin: z.enum(['triage', 'chat', 'fhir']),
|
|
108
|
+
sourceId: z.string().min(1),
|
|
109
|
+
createdAt: dateTime,
|
|
110
|
+
decisions: z.array(z.union([nutritionDecisionSchema, psychologyDecisionSchema])).max(2),
|
|
111
|
+
}).superRefine((recommendation, ctx) => {
|
|
112
|
+
const services = recommendation.decisions.map((decision) => decision.service);
|
|
113
|
+
if (new Set(services).size !== services.length) {
|
|
114
|
+
ctx.addIssue({ code: 'custom', path: ['decisions'], message: 'only one decision per service is allowed' });
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
class SupportRoutingRecommendation extends BaseDto {}
|
|
119
|
+
|
|
120
|
+
SupportRoutingRecommendation.schema = schema;
|
|
121
|
+
|
|
122
|
+
module.exports = {
|
|
123
|
+
SupportRoutingRecommendation,
|
|
124
|
+
};
|