feat(cortex): add Intake Blocks MVP for voice/text commands

Adds 4 new intents for intake workflow:
- intake_status: shows completion percentage and section checklist
- intake_navigeer: navigation to specific intake tabs
- risico_query: displays risk assessments with severity indicators
- diagnose_query: shows primary/secondary diagnoses

New components:
- IntakeStatusBlock, RisicoBlock, DiagnoseBlock
- Shared block components (BlockLoading, BlockError, BlockEmpty, BlockSection, BlockItem, BlockFooter)
- useBlockData and useIntakeContext hooks

New API routes:
- GET /api/cortex/intake/status
- GET /api/cortex/intake/risico
- GET /api/cortex/intake/diagnose

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
colinislit
2026-02-03 23:21:18 +01:00
parent 05836c5c6a
commit b095b1e492
22 changed files with 2415 additions and 15 deletions

View File

@@ -0,0 +1,183 @@
/**
* Intake Diagnosis API
*
* GET /api/cortex/intake/diagnose?patientId=xxx&intakeId=xxx
*
* Returns diagnoses for an intake.
* Used by DiagnoseBlock in Cortex Command Center.
*/
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { z } from 'zod';
// Query parameter schema
const QuerySchema = z.object({
patientId: z.string().uuid({ message: 'patientId moet een geldige UUID zijn' }),
intakeId: z.string().uuid({ message: 'intakeId moet een geldige UUID zijn' }).optional(),
});
// Clinical status type
type ClinicalStatus = 'active' | 'recurrence' | 'relapse' | 'inactive' | 'remission' | 'resolved';
export interface DiagnosisItem {
id: string;
code: string;
description: string;
codeSystem: string;
clinicalStatus: ClinicalStatus;
severity: string | null;
isPrimary: boolean;
notes: string | null;
recordedDate: string;
}
export interface IntakeDiagnoseResponse {
intakeId: string;
patientId: string;
diagnoses: DiagnosisItem[];
summary: {
total: number;
primaryDiagnosis: DiagnosisItem | null;
secondaryCount: number;
hasActiveConditions: boolean;
};
lastUpdated: string | null;
}
// Dutch labels for clinical status (not exported - Route files can only export route handlers)
const CLINICAL_STATUS_LABELS: Record<ClinicalStatus, string> = {
active: 'Actief',
recurrence: 'Recidief',
relapse: 'Terugval',
inactive: 'Inactief',
remission: 'Remissie',
resolved: 'Hersteld',
};
export async function GET(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate query parameters
const searchParams = request.nextUrl.searchParams;
const patientId = searchParams.get('patientId');
const intakeId = searchParams.get('intakeId');
if (!patientId) {
return NextResponse.json(
{ error: 'Query parameter "patientId" is verplicht' },
{ status: 400 }
);
}
const validation = QuerySchema.safeParse({ patientId, intakeId });
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => e.message)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
// If no intakeId provided, get the most recent active intake for this patient
let targetIntakeId = validation.data.intakeId;
if (!targetIntakeId) {
const { data: latestIntake, error: intakeError } = await supabase
.from('intakes')
.select('id')
.eq('patient_id', patientId)
.eq('status', 'bezig')
.order('start_date', { ascending: false })
.limit(1)
.maybeSingle();
if (intakeError) {
console.error('Error fetching latest intake:', intakeError);
return NextResponse.json(
{ error: 'Fout bij ophalen intake' },
{ status: 500 }
);
}
if (!latestIntake) {
return NextResponse.json(
{ error: 'Geen actieve intake gevonden voor deze patiënt' },
{ status: 404 }
);
}
targetIntakeId = latestIntake.id;
}
// Fetch diagnoses (conditions linked to intake via encounter_id)
const { data: conditionsData, error: conditionsError } = await supabase
.from('conditions')
.select('*')
.eq('encounter_id', targetIntakeId)
.order('recorded_date', { ascending: false });
if (conditionsError) {
console.error('Error fetching diagnoses:', conditionsError);
return NextResponse.json(
{ error: 'Fout bij ophalen diagnoses' },
{ status: 500 }
);
}
const diagnoses: DiagnosisItem[] = (conditionsData || []).map((condition) => ({
id: condition.id,
code: condition.code_code || '',
description: condition.code_display || 'Onbekende diagnose',
codeSystem: condition.code_system || 'ICD-10',
clinicalStatus: (condition.clinical_status as ClinicalStatus) || 'active',
severity: condition.severity_display,
isPrimary: condition.category === 'primary-diagnosis',
notes: condition.note,
recordedDate: condition.recorded_date || '',
}));
// Build summary
const primaryDiagnosis = diagnoses.find((d) => d.isPrimary) || null;
const secondaryCount = diagnoses.filter((d) => !d.isPrimary).length;
const hasActiveConditions = diagnoses.some(
(d) => d.clinicalStatus === 'active' || d.clinicalStatus === 'recurrence' || d.clinicalStatus === 'relapse'
);
// Get last updated timestamp
const lastUpdated = diagnoses.length > 0 ? diagnoses[0].recordedDate : null;
const response: IntakeDiagnoseResponse = {
intakeId: targetIntakeId,
patientId,
diagnoses,
summary: {
total: diagnoses.length,
primaryDiagnosis,
secondaryCount,
hasActiveConditions,
},
lastUpdated,
};
return NextResponse.json(response, { status: 200 });
} catch (error) {
console.error('Error in intake diagnosis API:', error);
return NextResponse.json(
{ error: 'Er ging iets mis bij het ophalen van de diagnoses.' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,201 @@
/**
* Intake Risk Assessment API
*
* GET /api/cortex/intake/risico?patientId=xxx&intakeId=xxx
*
* Returns risk assessments for an intake.
* Used by RisicoBlock in Cortex Command Center.
*/
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { z } from 'zod';
// Query parameter schema
const QuerySchema = z.object({
patientId: z.string().uuid({ message: 'patientId moet een geldige UUID zijn' }),
intakeId: z.string().uuid({ message: 'intakeId moet een geldige UUID zijn' }).optional(),
});
// Risk level type
type RiskLevel = 'laag' | 'matig' | 'hoog' | 'acuut';
export interface RiskAssessmentItem {
id: string;
type: string;
level: RiskLevel;
rationale: string;
measures: string | null;
assessmentDate: string;
evaluationDate: string | null;
notes: string | null;
}
export interface IntakeRisicoResponse {
intakeId: string;
patientId: string;
risks: RiskAssessmentItem[];
summary: {
total: number;
highestLevel: RiskLevel | null;
hasSuicideRisk: boolean;
hasSelfHarmRisk: boolean;
hasAggressionRisk: boolean;
};
lastUpdated: string | null;
}
// Map risk type to category for summary
function categorizeRiskType(type: string): 'suicide' | 'selfharm' | 'aggression' | 'other' {
const lowerType = type.toLowerCase();
if (lowerType.includes('suïcid') || lowerType.includes('suicide') || lowerType.includes('suicid')) {
return 'suicide';
}
if (lowerType.includes('zelfbeschadig') || lowerType.includes('automutil')) {
return 'selfharm';
}
if (lowerType.includes('agressie') || lowerType.includes('geweld')) {
return 'aggression';
}
return 'other';
}
// Determine highest risk level
function getHighestLevel(levels: RiskLevel[]): RiskLevel | null {
if (levels.length === 0) return null;
const priority: Record<RiskLevel, number> = {
laag: 1,
matig: 2,
hoog: 3,
acuut: 4,
};
return levels.reduce((highest, level) => {
return priority[level] > priority[highest] ? level : highest;
});
}
export async function GET(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate query parameters
const searchParams = request.nextUrl.searchParams;
const patientId = searchParams.get('patientId');
const intakeId = searchParams.get('intakeId');
if (!patientId) {
return NextResponse.json(
{ error: 'Query parameter "patientId" is verplicht' },
{ status: 400 }
);
}
const validation = QuerySchema.safeParse({ patientId, intakeId });
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => e.message)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
// If no intakeId provided, get the most recent active intake for this patient
let targetIntakeId = validation.data.intakeId;
if (!targetIntakeId) {
const { data: latestIntake, error: intakeError } = await supabase
.from('intakes')
.select('id')
.eq('patient_id', patientId)
.eq('status', 'bezig')
.order('start_date', { ascending: false })
.limit(1)
.maybeSingle();
if (intakeError) {
console.error('Error fetching latest intake:', intakeError);
return NextResponse.json(
{ error: 'Fout bij ophalen intake' },
{ status: 500 }
);
}
if (!latestIntake) {
return NextResponse.json(
{ error: 'Geen actieve intake gevonden voor deze patiënt' },
{ status: 404 }
);
}
targetIntakeId = latestIntake.id;
}
// Fetch risk assessments
const { data: riskData, error: riskError } = await supabase
.from('risk_assessments')
.select('*')
.eq('intake_id', targetIntakeId)
.order('assessment_date', { ascending: false });
if (riskError) {
console.error('Error fetching risk assessments:', riskError);
return NextResponse.json(
{ error: 'Fout bij ophalen risicotaxaties' },
{ status: 500 }
);
}
const risks: RiskAssessmentItem[] = (riskData || []).map((risk) => ({
id: risk.id,
type: risk.risk_type,
level: risk.risk_level as RiskLevel,
rationale: risk.rationale,
measures: risk.measures,
assessmentDate: risk.assessment_date,
evaluationDate: risk.evaluation_date,
notes: risk.notes,
}));
// Build summary
const riskCategories = risks.map((r) => categorizeRiskType(r.type));
const riskLevels = risks.map((r) => r.level);
const summary = {
total: risks.length,
highestLevel: getHighestLevel(riskLevels),
hasSuicideRisk: riskCategories.includes('suicide'),
hasSelfHarmRisk: riskCategories.includes('selfharm'),
hasAggressionRisk: riskCategories.includes('aggression'),
};
// Get last updated timestamp
const lastUpdated = risks.length > 0 ? risks[0].assessmentDate : null;
const response: IntakeRisicoResponse = {
intakeId: targetIntakeId,
patientId,
risks,
summary,
lastUpdated,
};
return NextResponse.json(response, { status: 200 });
} catch (error) {
console.error('Error in intake risk API:', error);
return NextResponse.json(
{ error: 'Er ging iets mis bij het ophalen van de risicotaxaties.' },
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,225 @@
/**
* Intake Status API
*
* GET /api/cortex/intake/status?patientId=xxx&intakeId=xxx
*
* Returns intake completion status: percentage, completed/missing sections.
* Used by IntakeStatusBlock in Cortex Command Center.
*/
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { z } from 'zod';
// Query parameter schema
const QuerySchema = z.object({
patientId: z.string().uuid({ message: 'patientId moet een geldige UUID zijn' }),
intakeId: z.string().uuid({ message: 'intakeId moet een geldige UUID zijn' }).optional(),
});
// Section definition
interface IntakeSection {
id: string;
label: string;
required: boolean;
}
const INTAKE_SECTIONS: IntakeSection[] = [
{ id: 'contacts', label: 'Contactmomenten', required: false },
{ id: 'anamnese', label: 'Anamnese', required: true },
{ id: 'risk', label: 'Risicotaxatie', required: true },
{ id: 'kindcheck', label: 'Kindcheck', required: true },
{ id: 'examination', label: 'Onderzoek', required: false },
{ id: 'rom', label: 'Meetinstrumenten (ROM)', required: false },
{ id: 'diagnosis', label: 'Diagnose', required: true },
{ id: 'behandeladvies', label: 'Behandeladvies', required: true },
];
export interface IntakeStatusResponse {
intakeId: string;
patientId: string;
completionPercentage: number;
status: 'bezig' | 'afgerond';
sections: {
id: string;
label: string;
required: boolean;
completed: boolean;
count: number;
}[];
completedCount: number;
totalRequired: number;
lastUpdated: string | null;
}
export async function GET(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate query parameters
const searchParams = request.nextUrl.searchParams;
const patientId = searchParams.get('patientId');
const intakeId = searchParams.get('intakeId');
if (!patientId) {
return NextResponse.json(
{ error: 'Query parameter "patientId" is verplicht' },
{ status: 400 }
);
}
const validation = QuerySchema.safeParse({ patientId, intakeId });
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => e.message)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
// If no intakeId provided, get the most recent active intake for this patient
let targetIntakeId = validation.data.intakeId;
if (!targetIntakeId) {
const { data: latestIntake, error: intakeError } = await supabase
.from('intakes')
.select('id')
.eq('patient_id', patientId)
.eq('status', 'bezig')
.order('start_date', { ascending: false })
.limit(1)
.maybeSingle();
if (intakeError) {
console.error('Error fetching latest intake:', intakeError);
return NextResponse.json(
{ error: 'Fout bij ophalen intake' },
{ status: 500 }
);
}
if (!latestIntake) {
return NextResponse.json(
{ error: 'Geen actieve intake gevonden voor deze patiënt' },
{ status: 404 }
);
}
targetIntakeId = latestIntake.id;
}
// Fetch intake details
const { data: intake, error: intakeDetailError } = await supabase
.from('intakes')
.select('id, patient_id, status, kindcheck_data, treatment_advice, updated_at')
.eq('id', targetIntakeId)
.single();
if (intakeDetailError || !intake) {
return NextResponse.json(
{ error: 'Intake niet gevonden' },
{ status: 404 }
);
}
// Fetch counts for each section in parallel
const [
contactsResult,
anamneseResult,
riskResult,
examinationResult,
romResult,
diagnosisResult,
] = await Promise.all([
// Contacts (encounters)
supabase
.from('encounters')
.select('id', { count: 'exact', head: true })
.eq('intake_id', targetIntakeId),
// Anamnese
supabase
.from('anamneses')
.select('id', { count: 'exact', head: true })
.eq('intake_id', targetIntakeId),
// Risk assessments
supabase
.from('risk_assessments')
.select('id', { count: 'exact', head: true })
.eq('intake_id', targetIntakeId),
// Examinations (non-ROM)
supabase
.from('examinations')
.select('id', { count: 'exact', head: true })
.eq('intake_id', targetIntakeId)
.neq('examination_type', 'ROM'),
// ROM examinations
supabase
.from('examinations')
.select('id', { count: 'exact', head: true })
.eq('intake_id', targetIntakeId)
.eq('examination_type', 'ROM'),
// Diagnoses (conditions linked to intake via encounter_id)
supabase
.from('conditions')
.select('id', { count: 'exact', head: true })
.eq('encounter_id', targetIntakeId),
]);
// Build section status
const sectionCounts: Record<string, number> = {
contacts: contactsResult.count || 0,
anamnese: anamneseResult.count || 0,
risk: riskResult.count || 0,
kindcheck: intake.kindcheck_data && Object.keys(intake.kindcheck_data as object).length > 0 ? 1 : 0,
examination: examinationResult.count || 0,
rom: romResult.count || 0,
diagnosis: diagnosisResult.count || 0,
behandeladvies: intake.treatment_advice && Object.keys(intake.treatment_advice as object).length > 0 ? 1 : 0,
};
const sections = INTAKE_SECTIONS.map((section) => ({
id: section.id,
label: section.label,
required: section.required,
completed: sectionCounts[section.id] > 0,
count: sectionCounts[section.id],
}));
// Calculate completion percentage (based on required sections)
const requiredSections = sections.filter((s) => s.required);
const completedRequired = requiredSections.filter((s) => s.completed).length;
const completionPercentage = Math.round(
(completedRequired / requiredSections.length) * 100
);
const response: IntakeStatusResponse = {
intakeId: targetIntakeId,
patientId: intake.patient_id,
completionPercentage,
status: intake.status as 'bezig' | 'afgerond',
sections,
completedCount: completedRequired,
totalRequired: requiredSections.length,
lastUpdated: intake.updated_at,
};
return NextResponse.json(response, { status: 200 });
} catch (error) {
console.error('Error in intake status API:', error);
return NextResponse.json(
{ error: 'Er ging iets mis bij het ophalen van de intake status.' },
{ status: 500 }
);
}
}