refactor: rename swift → cortex in code and documentation

Complete rename of "swift" terminology to "cortex" across the codebase:

Code Changes:
- Rename directories: lib/swift → lib/cortex, components/swift → components/cortex
- Rename API routes: /api/swift/* → /api/cortex/*
- Rename page routes: /epd/swift → /epd/cortex
- Rename store: swift-store.ts → cortex-store.ts

Type Renames:
- SwiftIntent → CortexIntent
- SwiftStore → CortexStore
- useSwiftStore → useCortexStore
- SwiftContext → CortexContext
- useSwiftVoice → useCortexVoice

Documentation Updates (docs/intent/):
- Safety Net → Nudge (Layer 3 rename)
- SafetySuggestion → NudgeSuggestion
- evaluateSafetyNet → evaluateNudge
- SWIFT_* feature flags → CORTEX_*
- All path references updated to match new structure

Files affected: 47 files, ~700 lines changed

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
colinislit
2025-12-30 09:18:06 +01:00
parent c8aaba657e
commit 2170b23348
62 changed files with 364 additions and 355 deletions

View File

@@ -0,0 +1,113 @@
'use client';
/**
* Block Container
*
* Wrapper for ephemeral blocks with animation, close button, and sizing.
*/
import { ReactNode } from 'react';
import { motion, type Variants } from 'framer-motion';
import { X } from 'lucide-react';
import { useCortexStore } from '@/stores/cortex-store';
import type { BlockSize } from '@/lib/cortex/types';
interface BlockContainerProps {
title: string;
size?: BlockSize;
children: ReactNode;
}
const SIZE_CLASSES: Record<BlockSize, string> = {
sm: 'max-w-sm',
md: 'max-w-md',
lg: 'max-w-2xl',
full: 'max-w-4xl',
};
// Container animations - consistent met CanvasArea slide up/down
// Slide up + fade in bij openen, scale 0.95 → 1.0 (200ms)
const containerVariants: Variants = {
initial: {
scale: 0.95,
opacity: 0,
y: 0, // BlockContainer animatie wordt door CanvasArea gedaan
},
animate: {
scale: 1,
opacity: 1,
y: 0,
transition: {
duration: 0.2,
ease: [0.4, 0, 0.2, 1] as [number, number, number, number],
},
},
};
// Content stagger animation
const contentVariants: Variants = {
initial: { opacity: 0, y: 10 },
animate: {
opacity: 1,
y: 0,
transition: {
delay: 0.1,
duration: 0.2,
ease: [0.4, 0, 0.2, 1] as [number, number, number, number],
},
},
};
// Close button hover animation
const closeButtonVariants = {
rest: { scale: 1, rotate: 0 },
hover: { scale: 1.1, rotate: 90 },
tap: { scale: 0.95 },
};
export function BlockContainer({ title, size = 'md', children }: BlockContainerProps) {
const { closeBlock } = useCortexStore();
return (
<motion.div
variants={containerVariants}
initial="initial"
animate="animate"
className={`w-full ${SIZE_CLASSES[size]} bg-white rounded-xl border border-slate-200 shadow-lg`}
>
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-200">
<motion.h2
initial={{ opacity: 0, x: -10 }}
animate={{ opacity: 1, x: 0 }}
transition={{ delay: 0.05, duration: 0.2 }}
className="text-lg font-medium text-slate-900"
>
{title}
</motion.h2>
<motion.button
onClick={closeBlock}
variants={closeButtonVariants}
initial="rest"
whileHover="hover"
whileTap="tap"
className="p-1 rounded hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors"
title="Sluiten (Esc)"
aria-label="Block sluiten"
>
<X size={20} />
</motion.button>
</div>
{/* Content */}
<motion.div
variants={contentVariants}
initial="initial"
animate="animate"
className="p-4"
>
{children}
</motion.div>
</motion.div>
);
}

View File

@@ -0,0 +1,426 @@
'use client';
/**
* Dagnotatie Block
*
* Block voor het maken van een dagnotitie.
* E3.S2: Volledige implementatie met patient selectie, categorie, tekst en opslaan.
*/
import { useState, useEffect, useCallback, useRef } from 'react';
import { useToast } from '@/hooks/use-toast';
import { useCortexStore } from '@/stores/cortex-store';
import { BlockContainer } from './block-container';
import type { BlockPrefillData } from '@/stores/cortex-store';
import { BLOCK_CONFIGS } from '@/lib/cortex/types';
import {
VERPLEEGKUNDIG_CATEGORIES,
CATEGORY_CONFIG,
type VerpleegkundigCategory,
} from '@/lib/types/report';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Button } from '@/components/ui/button';
import { Loader2, Search, User, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import { safeFetch, getErrorInfo, retryFetch } from '@/lib/cortex/error-handler';
interface DagnotitieBlockProps {
prefill?: BlockPrefillData;
}
interface Patient {
id: string;
name_family?: string;
name_given?: string[];
identifier_bsn?: string;
}
export function DagnotatieBlock({ prefill }: DagnotitieBlockProps) {
const config = BLOCK_CONFIGS.dagnotitie;
const { closeBlock } = useCortexStore();
const { toast } = useToast();
// Form state
const [patientId, setPatientId] = useState<string>(prefill?.patientId || '');
const [patientName, setPatientName] = useState<string>(prefill?.patientName || '');
const [category, setCategory] = useState<VerpleegkundigCategory>(
prefill?.category || 'observatie'
);
const [content, setContent] = useState<string>(prefill?.content || '');
const [includeInHandover, setIncludeInHandover] = useState<boolean>(false);
// Patient search state
const [searchQuery, setSearchQuery] = useState<string>(prefill?.patientName || '');
const [patients, setPatients] = useState<Patient[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [showPatientDropdown, setShowPatientDropdown] = useState(false);
const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
const searchTimeoutRef = useRef<NodeJS.Timeout>();
const dropdownRef = useRef<HTMLDivElement>(null);
// Prefill patient if patientId is provided
useEffect(() => {
if (prefill?.patientId && prefill?.patientName) {
setPatientId(prefill.patientId);
setPatientName(prefill.patientName);
setSelectedPatient({
id: prefill.patientId,
name_family: prefill.patientName.split(' ').pop(),
name_given: prefill.patientName.split(' ').slice(0, -1),
});
}
}, [prefill]);
// Patient search with debouncing
const searchPatients = useCallback(async (query: string) => {
if (query.length < 2) {
setPatients([]);
setShowPatientDropdown(false);
return;
}
setIsSearching(true);
try {
const response = await safeFetch(
`/api/fhir/Patient?q=${encodeURIComponent(query)}`,
undefined,
{ operation: 'Patiënt zoeken' }
);
const data = await response.json();
const mappedPatients: Patient[] =
data.entry?.map((e: { resource: any }) => {
const p = e.resource;
return {
id: p.id,
name_family: p.name?.[0]?.family,
name_given: p.name?.[0]?.given || [],
identifier_bsn: p.identifier?.find(
(id: any) => id.system === 'http://fhir.nl/fhir/NamingSystem/bsn'
)?.value,
};
}) || [];
setPatients(mappedPatients);
setShowPatientDropdown(mappedPatients.length > 0);
} catch (error) {
console.error('Failed to search patients:', error);
const errorInfo = getErrorInfo(error, { operation: 'Patiënt zoeken' });
toast({
variant: 'destructive',
title: errorInfo.title,
description: errorInfo.description,
});
setPatients([]);
} finally {
setIsSearching(false);
}
}, [toast]);
// Debounced search
useEffect(() => {
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
if (searchQuery && !selectedPatient) {
searchTimeoutRef.current = setTimeout(() => {
searchPatients(searchQuery);
}, 300);
} else {
setPatients([]);
setShowPatientDropdown(false);
}
return () => {
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
};
}, [searchQuery, selectedPatient, searchPatients]);
// Close dropdown on outside click
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setShowPatientDropdown(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const handleSelectPatient = (patient: Patient) => {
const fullName = `${patient.name_given?.join(' ') || ''} ${patient.name_family || ''}`.trim();
setSelectedPatient(patient);
setPatientId(patient.id);
setPatientName(fullName);
setSearchQuery(fullName);
setShowPatientDropdown(false);
};
const handleClearPatient = () => {
setSelectedPatient(null);
setPatientId('');
setPatientName('');
setSearchQuery('');
};
const [isSubmitting, setIsSubmitting] = useState(false);
const handleSave = useCallback(async () => {
if (!patientId) {
toast({
variant: 'destructive',
title: 'Patiënt vereist',
description: 'Selecteer eerst een patiënt',
});
return;
}
if (!content.trim()) {
toast({
variant: 'destructive',
title: 'Content vereist',
description: 'Voer een notitie in',
});
return;
}
setIsSubmitting(true);
try {
const response = await retryFetch(
() =>
safeFetch(
'/api/reports',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
patient_id: patientId,
type: 'verpleegkundig',
content: content.trim(),
category,
include_in_handover: includeInHandover,
}),
},
{ operation: 'Dagnotitie opslaan' }
),
3,
1000
);
const data = await response.json();
toast({
title: 'Dagnotitie opgeslagen',
description: `Notitie voor ${patientName} is opgeslagen`,
});
// Close block after short delay
setTimeout(() => {
closeBlock();
}, 500);
} catch (error) {
console.error('Failed to save dagnotitie:', error);
const statusCode = (error as any)?.statusCode;
const errorInfo = getErrorInfo(error, {
operation: 'Dagnotitie opslaan',
statusCode,
});
toast({
variant: 'destructive',
title: errorInfo.title,
description: errorInfo.description,
});
} finally {
setIsSubmitting(false);
}
}, [patientId, content, category, includeInHandover, patientName, toast, closeBlock]);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
await handleSave();
};
// Keyboard shortcut: Cmd/Ctrl+Enter to save
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Cmd/Ctrl+Enter: save dagnotitie
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault();
handleSave();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleSave]);
const formatPatientName = (patient: Patient): string => {
const given = patient.name_given?.join(' ') || '';
const family = patient.name_family || '';
return `${given} ${family}`.trim() || 'Naamloos';
};
return (
<BlockContainer title={config.title} size={config.size}>
<form onSubmit={handleSubmit} className="space-y-6">
{/* Patient Selectie */}
<div className="space-y-2">
<Label htmlFor="patient-search">Patiënt *</Label>
<div className="relative" ref={dropdownRef}>
{selectedPatient ? (
<div className="flex items-center gap-2 p-2 rounded-md border border-slate-200 bg-slate-50">
<User className="h-4 w-4 text-slate-500" />
<span className="flex-1 text-sm text-slate-900">{formatPatientName(selectedPatient)}</span>
<Button
type="button"
variant="ghost"
size="sm"
onClick={handleClearPatient}
className="h-6 w-6 p-0 text-slate-400 hover:text-slate-700"
>
×
</Button>
</div>
) : (
<>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
<Input
id="patient-search"
type="text"
placeholder="Zoek patiënt (naam of BSN)..."
value={searchQuery}
onChange={(e) => {
setSearchQuery(e.target.value);
setShowPatientDropdown(true);
}}
onFocus={() => {
if (patients.length > 0) {
setShowPatientDropdown(true);
}
}}
className="pl-9"
/>
{isSearching && (
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400 animate-spin" />
)}
</div>
{showPatientDropdown && patients.length > 0 && (
<div className="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-md shadow-lg max-h-60 overflow-auto">
{patients.map((patient) => (
<button
key={patient.id}
type="button"
onClick={() => handleSelectPatient(patient)}
className="w-full px-3 py-2 text-left text-sm text-slate-700 hover:bg-slate-50 transition-colors"
>
<div className="font-medium">{formatPatientName(patient)}</div>
{patient.identifier_bsn && (
<div className="text-xs text-slate-500">BSN: {patient.identifier_bsn}</div>
)}
</button>
))}
</div>
)}
</>
)}
</div>
</div>
{/* Categorie Selector */}
<div className="space-y-2">
<Label>Categorie *</Label>
<div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
{VERPLEEGKUNDIG_CATEGORIES.map((cat) => {
const catConfig = CATEGORY_CONFIG[cat];
const isSelected = category === cat;
return (
<button
key={cat}
type="button"
onClick={() => setCategory(cat)}
className={cn(
'px-3 py-2 rounded-md text-sm font-medium transition-colors',
isSelected
? 'bg-slate-900 text-white border-2 border-slate-700'
: 'bg-slate-50 text-slate-600 border border-slate-200 hover:bg-slate-100 hover:text-slate-900'
)}
>
{catConfig.label}
</button>
);
})}
</div>
</div>
{/* Content */}
<div className="space-y-2">
<Label htmlFor="content">Notitie *</Label>
<Textarea
id="content"
placeholder="Beschrijf wat er is gebeurd..."
value={content}
onChange={(e) => setContent(e.target.value)}
rows={6}
className="resize-none"
maxLength={500}
/>
<div className="text-xs text-slate-500 text-right">
{content.length}/500 karakters
</div>
</div>
{/* Include in Handover */}
<div className="flex items-center gap-2">
<input
type="checkbox"
id="include-handover"
checked={includeInHandover}
onChange={(e) => setIncludeInHandover(e.target.checked)}
className="h-4 w-4 rounded border-slate-300 bg-white text-blue-600 focus:ring-blue-500"
/>
<Label htmlFor="include-handover" className="cursor-pointer text-sm text-slate-700">
Opnemen in overdracht
</Label>
</div>
{/* Actions */}
<div className="flex gap-2 justify-end">
<Button
type="button"
variant="outline"
onClick={closeBlock}
disabled={isSubmitting}
>
Annuleren
</Button>
<Button
type="submit"
disabled={isSubmitting || !patientId || !content.trim()}
title="Opslaan (⌘Enter)"
>
{isSubmitting ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Opslaan...
</>
) : (
<>
Opslaan
<span className="ml-2 text-xs opacity-70 hidden sm:inline"></span>
</>
)}
</Button>
</div>
</form>
</BlockContainer>
);
}

View File

@@ -0,0 +1,168 @@
'use client';
/**
* Fallback Picker
*
* Visual intent selector shown when classification confidence is low.
* E4.S4: Grid met block opties, keyboard shortcuts (1-3).
*/
import { useEffect, useCallback } from 'react';
import { motion } from 'framer-motion';
import { FileText, Search, ArrowRightLeft, X } from 'lucide-react';
import { useCortexStore } from '@/stores/cortex-store';
import type { BlockType } from '@/lib/cortex/types';
interface FallbackPickerProps {
originalInput?: string;
}
interface BlockOption {
type: BlockType;
label: string;
description: string;
icon: typeof FileText;
shortcut: string;
color: string;
}
const BLOCK_OPTIONS: BlockOption[] = [
{
type: 'dagnotitie',
label: 'Notitie',
description: 'Schrijf een dagnotitie',
icon: FileText,
shortcut: '1',
color: 'bg-blue-50 text-blue-600 border-blue-200',
},
{
type: 'zoeken',
label: 'Zoeken',
description: 'Zoek een patiënt',
icon: Search,
shortcut: '2',
color: 'bg-emerald-50 text-emerald-600 border-emerald-200',
},
{
type: 'overdracht',
label: 'Overdracht',
description: 'Bekijk overdracht',
icon: ArrowRightLeft,
shortcut: '3',
color: 'bg-amber-50 text-amber-600 border-amber-200',
},
];
export function FallbackPicker({ originalInput }: FallbackPickerProps) {
const { openBlock, closeBlock, addRecentAction } = useCortexStore();
const handleSelect = useCallback(
(option: BlockOption) => {
// Pass original input as content for dagnotitie, or as search query for zoeken
const prefillData =
option.type === 'dagnotitie'
? { content: originalInput }
: option.type === 'zoeken'
? { patientName: originalInput }
: {};
openBlock(option.type, prefillData);
// Only add to recent actions if it's a valid SwiftIntent (not patient-dashboard)
if (option.type !== 'patient-dashboard') {
addRecentAction({
intent: option.type,
label: option.label,
});
}
},
[openBlock, addRecentAction, originalInput]
);
// Keyboard shortcuts
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Don't handle if in input field
if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) {
return;
}
// Number keys 1-3 for quick select
const keyNum = parseInt(e.key);
if (keyNum >= 1 && keyNum <= BLOCK_OPTIONS.length) {
e.preventDefault();
handleSelect(BLOCK_OPTIONS[keyNum - 1]);
}
// Escape to close
if (e.key === 'Escape') {
e.preventDefault();
closeBlock();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleSelect, closeBlock]);
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
transition={{ duration: 0.2, ease: [0.4, 0, 0.2, 1] as [number, number, number, number] }}
className="w-full max-w-md bg-white rounded-xl border border-slate-200 shadow-lg overflow-hidden"
>
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b border-slate-200">
<h2 className="text-lg font-medium text-slate-900">Wat wil je doen?</h2>
<button
onClick={closeBlock}
className="p-1 rounded hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors"
title="Sluiten (Esc)"
aria-label="Sluiten"
>
<X size={20} />
</button>
</div>
{/* Original input display */}
{originalInput && (
<div className="px-4 py-2 bg-slate-50 border-b border-slate-200">
<p className="text-sm text-slate-500">
Je zei: <span className="text-slate-700">&quot;{originalInput}&quot;</span>
</p>
</div>
)}
{/* Options grid */}
<div className="p-4">
<div className="grid grid-cols-3 gap-3">
{BLOCK_OPTIONS.map((option) => (
<motion.button
key={option.type}
onClick={() => handleSelect(option)}
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
className={`flex flex-col items-center gap-2 p-4 rounded-lg border transition-all ${option.color} hover:shadow-md`}
>
<option.icon size={28} />
<span className="font-medium text-sm">{option.label}</span>
<span className="text-xs opacity-70 text-center">{option.description}</span>
<span className="mt-1 px-2 py-0.5 bg-slate-100 rounded text-xs text-slate-500">
[{option.shortcut}]
</span>
</motion.button>
))}
</div>
</div>
{/* Footer hint */}
<div className="px-4 py-2 bg-slate-50 border-t border-slate-200">
<p className="text-xs text-slate-500 text-center">
Druk op [1], [2] of [3] voor snelle selectie
</p>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,11 @@
/**
* Cortex Blocks Barrel Export
*/
export { BlockContainer } from './block-container';
export { DagnotatieBlock } from './dagnotitie-block';
export { ZoekenBlock } from './zoeken-block';
export { OverdrachtBlock } from './overdracht-block';
export { PatientContextCard } from './patient-context-card';
export { PatientDashboardBlock } from './patient-dashboard-block';
export { FallbackPicker } from './fallback-picker';

View File

@@ -0,0 +1,495 @@
'use client';
/**
* Overdracht Block
*
* Block voor het genereren van overdracht samenvattingen per patiënt.
* E3.S6: Volledige implementatie met AI samenvatting per patiënt.
*/
import { useState, useEffect, useCallback } from 'react';
import { useToast } from '@/hooks/use-toast';
import { useCortexStore } from '@/stores/cortex-store';
import { BlockContainer } from './block-container';
import type { BlockPrefillData } from '@/stores/cortex-store';
import { BLOCK_CONFIGS } from '@/lib/cortex/types';
import type { PatientOverzicht, AISamenvatting } from '@/lib/types/overdracht';
import {
Sparkles,
Loader2,
AlertTriangle,
CheckCircle2,
Clock,
RefreshCw,
Calendar,
Users,
} from 'lucide-react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale/nl';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { safeFetch, getErrorInfo, retryFetch } from '@/lib/cortex/error-handler';
import { LinkedEvidence } from '@/components/cortex/shared/linked-evidence';
interface OverdrachtBlockProps {
prefill?: BlockPrefillData;
}
type PeriodValue = '1d' | '3d' | '7d' | '14d';
const PERIOD_OPTIONS: { value: PeriodValue; label: string; description: string }[] = [
{ value: '1d', label: 'Vandaag', description: 'Laatste 24 uur' },
{ value: '3d', label: '3 dagen', description: 'Afgelopen 3 dagen' },
{ value: '7d', label: '1 week', description: 'Afgelopen 7 dagen' },
{ value: '14d', label: '2 weken', description: 'Afgelopen 14 dagen' },
];
interface PatientSummary {
patient: PatientOverzicht;
summary: AISamenvatting | null;
loading: boolean;
error: string | null;
}
export function OverdrachtBlock({ prefill }: OverdrachtBlockProps) {
const config = BLOCK_CONFIGS.overdracht;
const { activePatient } = useCortexStore();
const { toast } = useToast();
const [period, setPeriod] = useState<PeriodValue>('1d');
const [filterRole, setFilterRole] = useState<'verpleegkundige' | 'psychiater'>('verpleegkundige');
const [patients, setPatients] = useState<PatientOverzicht[]>([]);
const [isLoadingPatients, setIsLoadingPatients] = useState(true);
const [patientSummaries, setPatientSummaries] = useState<Map<string, PatientSummary>>(new Map());
// Load patients list
useEffect(() => {
const fetchPatients = async () => {
setIsLoadingPatients(true);
try {
const response = await safeFetch(
'/api/overdracht/patients',
undefined,
{ operation: 'Patiëntenlijst laden' }
);
const data = await response.json();
setPatients(data.patients || []);
// Initialize summaries map
const summaries = new Map<string, PatientSummary>();
(data.patients || []).forEach((patient: PatientOverzicht) => {
summaries.set(patient.id, {
patient,
summary: null,
loading: false,
error: null,
});
});
setPatientSummaries(summaries);
} catch (error) {
console.error('Failed to fetch patients:', error);
const statusCode = (error as any)?.statusCode;
const errorInfo = getErrorInfo(error, {
operation: 'Patiëntenlijst laden',
statusCode,
});
toast({
variant: 'destructive',
title: errorInfo.title,
description: errorInfo.description,
});
} finally {
setIsLoadingPatients(false);
}
};
fetchPatients();
}, [toast]);
// Auto-generate summary for activePatient if set (only once when block opens)
useEffect(() => {
if (activePatient && patients.length > 0 && patientSummaries.size > 0) {
const summaryData = patientSummaries.get(activePatient.id);
// Only auto-generate if no summary exists and not already loading
if (summaryData && !summaryData.summary && !summaryData.loading) {
generateSummary(activePatient.id);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activePatient?.id, patients.length, patientSummaries.size]);
// Generate summary for a patient
const generateSummary = useCallback(async (patientId: string) => {
setPatientSummaries((prev) => {
const updated = new Map(prev);
const existing = updated.get(patientId);
if (existing) {
updated.set(patientId, {
...existing,
loading: true,
error: null,
});
}
return updated;
});
try {
const response = await retryFetch(
() =>
safeFetch(
'/api/overdracht/generate',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ patientId, period, filterForRole: filterRole }),
},
{ operation: 'Overdracht genereren' }
),
3,
1000
);
const summary: AISamenvatting = await response.json();
setPatientSummaries((prev) => {
const updated = new Map(prev);
const existing = updated.get(patientId);
if (existing) {
updated.set(patientId, {
...existing,
summary,
loading: false,
error: null,
});
}
return updated;
});
} catch (error) {
console.error('Failed to generate summary:', error);
const statusCode = (error as any)?.statusCode;
const errorInfo = getErrorInfo(error, {
operation: 'Overdracht genereren',
statusCode,
});
setPatientSummaries((prev) => {
const updated = new Map(prev);
const existing = updated.get(patientId);
if (existing) {
updated.set(patientId, {
...existing,
loading: false,
error: errorInfo.description,
});
}
return updated;
});
}
}, [period, filterRole]);
// Filter patients: if activePatient is set, only show that one
const displayPatients = activePatient
? patients.filter((p) => p.id === activePatient.id)
: patients;
const formatPatientName = (patient: PatientOverzicht): string => {
return `${patient.name_given?.join(' ') || ''} ${patient.name_family || ''}`.trim();
};
const formatDuration = (ms: number): string => {
if (ms < 1000) return `${ms}ms`;
return `${(ms / 1000).toFixed(1)}s`;
};
const formatTime = (datetime: string): string => {
return format(new Date(datetime), 'HH:mm', { locale: nl });
};
return (
<BlockContainer title={config.title} size={config.size}>
<div className="space-y-6">
{/* Period Selector */}
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">Periode</label>
<div className="grid grid-cols-4 gap-2">
{PERIOD_OPTIONS.map((option) => (
<button
key={option.value}
type="button"
onClick={() => setPeriod(option.value)}
className={cn(
'px-3 py-2 rounded-lg text-sm font-medium transition-colors',
period === option.value
? 'bg-slate-900 text-white border-2 border-slate-700'
: 'bg-slate-50 text-slate-600 border border-slate-200 hover:bg-slate-100 hover:text-slate-900'
)}
>
{option.label}
</button>
))}
</div>
<p className="text-xs text-slate-500">
{PERIOD_OPTIONS.find((o) => o.value === period)?.description}
</p>
</div>
{/* Role Filter Toggle */}
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">Doelgroep</label>
<div className="grid grid-cols-2 gap-2">
<button
type="button"
onClick={() => setFilterRole('verpleegkundige')}
className={cn(
'px-3 py-2.5 rounded-lg text-sm font-medium transition-colors text-left',
filterRole === 'verpleegkundige'
? 'bg-slate-900 text-white border-2 border-slate-700'
: 'bg-slate-50 text-slate-600 border border-slate-200 hover:bg-slate-100 hover:text-slate-900'
)}
>
<div className="font-semibold">Verpleegkundige</div>
<div className="text-xs opacity-80 mt-0.5">Alle gemarkeerde items</div>
</button>
<button
type="button"
onClick={() => setFilterRole('psychiater')}
className={cn(
'px-3 py-2.5 rounded-lg text-sm font-medium transition-colors text-left',
filterRole === 'psychiater'
? 'bg-slate-900 text-white border-2 border-slate-700'
: 'bg-slate-50 text-slate-600 border border-slate-200 hover:bg-slate-100 hover:text-slate-900'
)}
>
<div className="font-semibold">Psychiater</div>
<div className="text-xs opacity-80 mt-0.5">Behandelrelevante items</div>
</button>
</div>
<p className="text-xs text-slate-500">
{filterRole === 'psychiater'
? 'AI filtert op behandelrelevantie voor psychiater'
: 'Toont alle door verpleegkundige gemarkeerde items'}
</p>
</div>
{/* Patients List */}
{isLoadingPatients ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-slate-400 mr-2" />
<span className="text-sm text-slate-500">Patiënten laden...</span>
</div>
) : displayPatients.length === 0 ? (
<div className="text-center py-8 text-slate-400">
<Users className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Geen patiënten gevonden voor deze periode</p>
</div>
) : (
<div className="space-y-4">
{displayPatients.map((patient) => {
const summaryData = patientSummaries.get(patient.id);
const summary = summaryData?.summary;
const loading = summaryData?.loading || false;
const error = summaryData?.error;
return (
<div
key={patient.id}
className="p-4 rounded-lg bg-slate-50 border border-slate-200"
>
{/* Patient Header */}
<div className="flex items-center justify-between mb-4">
<div>
<h3 className="text-base font-medium text-slate-900">
{formatPatientName(patient)}
</h3>
{patient.alerts.total > 0 && (
<div className="flex items-center gap-2 mt-1">
<span className="text-xs text-slate-500">
{patient.alerts.total} alert{patient.alerts.total > 1 ? 's' : ''}
</span>
{patient.alerts.high_risk_count > 0 && (
<span className="text-xs px-1.5 py-0.5 rounded bg-red-100 text-red-700 border border-red-200">
{patient.alerts.high_risk_count} risico
</span>
)}
</div>
)}
</div>
{!summary && !loading && (
<Button
size="sm"
onClick={() => generateSummary(patient.id)}
className="bg-violet-600 hover:bg-violet-700"
>
<Sparkles className="h-4 w-4 mr-1.5" />
Genereer
</Button>
)}
</div>
{/* Loading State */}
{loading && (
<div className="py-6 text-center">
<Loader2 className="h-6 w-6 text-violet-600 mx-auto mb-2 animate-spin" />
<p className="text-sm text-slate-500">Samenvatting wordt gegenereerd...</p>
</div>
)}
{/* Error State */}
{error && (
<div className="py-4">
<div className="p-3 bg-red-50 rounded-lg border border-red-200 mb-3">
<div className="flex items-start gap-2">
<AlertTriangle className="h-4 w-4 text-red-500 flex-shrink-0 mt-0.5" />
<p className="text-sm text-red-700">{error}</p>
</div>
</div>
<Button
size="sm"
variant="outline"
onClick={() => generateSummary(patient.id)}
className="w-full"
>
<RefreshCw className="h-4 w-4 mr-1.5" />
Opnieuw proberen
</Button>
</div>
)}
{/* Summary Content */}
{summary && (
<div className="space-y-4 pt-4 border-t border-slate-200">
{/* Samenvatting */}
<div>
<h4 className="text-sm font-medium text-slate-700 mb-2">Samenvatting</h4>
<p className="text-sm text-slate-600 leading-relaxed bg-white p-3 rounded-lg border border-slate-200">
{summary.samenvatting}
</p>
</div>
{/* Aandachtspunten */}
{summary.aandachtspunten.length > 0 && (
<div>
<h4 className="text-sm font-medium text-slate-700 mb-2">
Aandachtspunten ({summary.aandachtspunten.length})
</h4>
<div className="space-y-2">
{summary.aandachtspunten.map((punt, index) => (
<AandachtspuntItem key={index} punt={punt} />
))}
</div>
</div>
)}
{/* Actiepunten */}
{summary.actiepunten.length > 0 && (
<div>
<h4 className="text-sm font-medium text-slate-700 mb-2">
Actiepunten ({summary.actiepunten.length})
</h4>
<ul className="space-y-2">
{summary.actiepunten.map((actie, index) => (
<li
key={index}
className="flex items-start gap-2 text-sm text-slate-600"
>
<CheckCircle2 className="h-4 w-4 text-teal-600 flex-shrink-0 mt-0.5" />
<span>{actie}</span>
</li>
))}
</ul>
</div>
)}
{/* Footer */}
<div className="pt-3 border-t border-slate-200 flex items-center justify-between">
<div className="flex items-center gap-2 text-xs text-slate-500">
<Clock className="h-3.5 w-3.5" />
<span>
{formatTime(summary.generatedAt)} ({formatDuration(summary.durationMs)})
</span>
</div>
<Button
size="sm"
variant="ghost"
onClick={() => generateSummary(patient.id)}
disabled={loading}
className="text-xs h-7"
>
<RefreshCw className="h-3.5 w-3.5 mr-1" />
Vernieuwen
</Button>
</div>
</div>
)}
</div>
);
})}
</div>
)}
</div>
</BlockContainer>
);
}
function AandachtspuntItem({ punt }: { punt: AISamenvatting['aandachtspunten'][0] }) {
const getBronTypeLabel = (type: string): string => {
const labels: Record<string, string> = {
observatie: 'Vitale functie',
rapportage: 'Rapportage',
verpleegkundig: 'Verpleegkundig',
risico: 'Risicobeoordeling',
};
return labels[type] || type;
};
const getBronTypeStyle = (type: string): { bg: string; text: string } => {
switch (type) {
case 'observatie':
return { bg: 'bg-teal-50', text: 'text-teal-700' };
case 'rapportage':
return { bg: 'bg-indigo-50', text: 'text-indigo-700' };
case 'verpleegkundig':
return { bg: 'bg-amber-50', text: 'text-amber-700' };
case 'risico':
return { bg: 'bg-red-50', text: 'text-red-700' };
default:
return { bg: 'bg-slate-100', text: 'text-slate-600' };
}
};
const bronStyle = getBronTypeStyle(punt.bron.type);
return (
<div
className={cn(
'p-3 rounded-lg border-l-4',
punt.urgent
? 'bg-red-50 border-red-500'
: 'bg-white border border-slate-200 border-l-slate-400'
)}
>
<div className="flex items-start gap-2 mb-2">
{punt.urgent && <AlertTriangle className="h-4 w-4 text-red-500 flex-shrink-0 mt-0.5" />}
<p
className={cn(
'text-sm flex-1',
punt.urgent ? 'text-red-700 font-medium' : 'text-slate-700'
)}
>
{punt.tekst}
</p>
</div>
<div className="flex items-center gap-2">
<span
className={cn(
'inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-xs',
bronStyle.bg,
bronStyle.text
)}
>
{getBronTypeLabel(punt.bron.type)}
</span>
<LinkedEvidence bron={punt.bron} sourceData={punt.sourceData} />
</div>
</div>
);
}

View File

@@ -0,0 +1,261 @@
'use client';
/**
* Patient Context Card
*
* Toont patiënt context na selectie: notities, vitals, diagnoses.
* E3.S5: Volledige implementatie met auto-open na patient selectie.
*/
import { useEffect, useState } from 'react';
import { useCortexStore } from '@/stores/cortex-store';
import { BlockContainer } from './block-container';
import { BLOCK_CONFIGS } from '@/lib/cortex/types';
import type { PatientDetail, Report, VitalSign, Condition, RiskAssessment } from '@/lib/types/overdracht';
import { Loader2, FileText, Activity, Stethoscope, AlertTriangle, Calendar } from 'lucide-react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale/nl';
import { cn } from '@/lib/utils';
export function PatientContextCard() {
const { activePatient, closeBlock } = useCortexStore();
const [data, setData] = useState<PatientDetail | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!activePatient?.id) {
return;
}
const fetchContext = async () => {
setIsLoading(true);
setError(null);
try {
const response = await fetch(`/api/overdracht/${activePatient.id}`);
if (!response.ok) {
throw new Error('Kon patiënt context niet laden');
}
const result = await response.json();
setData(result);
} catch (err) {
console.error('Failed to fetch patient context:', err);
setError(err instanceof Error ? err.message : 'Onbekende fout');
} finally {
setIsLoading(false);
}
};
fetchContext();
}, [activePatient?.id]);
if (!activePatient) {
return null;
}
const patientName = `${activePatient.name_given?.join(' ') || ''} ${activePatient.name_family || ''}`.trim();
return (
<BlockContainer title={`Patiënt: ${patientName}`} size="lg">
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-slate-400 mr-2" />
<span className="text-sm text-slate-500">Context laden...</span>
</div>
) : error ? (
<div className="text-center py-8">
<AlertTriangle className="h-8 w-8 text-red-500 mx-auto mb-2" />
<p className="text-sm text-red-700">{error}</p>
</div>
) : data ? (
<div className="space-y-6">
{/* Notities (Reports) */}
{data.reports && data.reports.length > 0 && (
<section>
<div className="flex items-center gap-2 mb-3">
<FileText className="h-4 w-4 text-slate-500" />
<h3 className="text-sm font-medium text-slate-700">Recente notities</h3>
<span className="text-xs text-slate-500">({data.reports.length})</span>
</div>
<div className="space-y-2">
{data.reports.slice(0, 5).map((report) => (
<ReportItem key={report.id} report={report} />
))}
{data.reports.length > 5 && (
<p className="text-xs text-slate-500 text-center pt-2">
+ {data.reports.length - 5} meer notities
</p>
)}
</div>
</section>
)}
{/* Vitals */}
{data.vitals && data.vitals.length > 0 && (
<section>
<div className="flex items-center gap-2 mb-3">
<Activity className="h-4 w-4 text-slate-500" />
<h3 className="text-sm font-medium text-slate-700">Vitale functies (vandaag)</h3>
<span className="text-xs text-slate-500">({data.vitals.length})</span>
</div>
<div className="grid grid-cols-2 gap-2">
{data.vitals.slice(0, 6).map((vital) => (
<VitalItem key={vital.id} vital={vital} />
))}
</div>
</section>
)}
{/* Diagnoses */}
{data.conditions && data.conditions.length > 0 && (
<section>
<div className="flex items-center gap-2 mb-3">
<Stethoscope className="h-4 w-4 text-slate-500" />
<h3 className="text-sm font-medium text-slate-700">Actieve diagnoses</h3>
<span className="text-xs text-slate-500">({data.conditions.length})</span>
</div>
<div className="space-y-2">
{data.conditions.map((condition) => (
<ConditionItem key={condition.id} condition={condition} />
))}
</div>
</section>
)}
{/* Risico's */}
{data.risks && data.risks.length > 0 && (
<section>
<div className="flex items-center gap-2 mb-3">
<AlertTriangle className="h-4 w-4 text-amber-500" />
<h3 className="text-sm font-medium text-slate-700">Risico&apos;s</h3>
<span className="text-xs text-slate-500">({data.risks.length})</span>
</div>
<div className="flex flex-wrap gap-2">
{data.risks.map((risk) => (
<RiskBadge key={risk.id} risk={risk} />
))}
</div>
</section>
)}
{/* Empty state */}
{(!data.reports || data.reports.length === 0) &&
(!data.vitals || data.vitals.length === 0) &&
(!data.conditions || data.conditions.length === 0) &&
(!data.risks || data.risks.length === 0) && (
<div className="text-center py-8 text-slate-400">
<p className="text-sm">Geen context beschikbaar voor deze patiënt</p>
</div>
)}
</div>
) : null}
</BlockContainer>
);
}
function ReportItem({ report }: { report: Report }) {
const date = report.created_at ? new Date(report.created_at) : null;
const formattedDate = date ? format(date, 'd MMM HH:mm', { locale: nl }) : 'Onbekend';
return (
<div className="p-3 rounded-lg bg-slate-50 border border-slate-200">
<div className="flex items-start justify-between gap-2 mb-1">
<div className="flex items-center gap-2 flex-1 min-w-0">
<span className="text-xs font-medium text-slate-500 uppercase">{report.type}</span>
{report.include_in_handover && (
<span className="text-xs px-1.5 py-0.5 rounded bg-blue-50 text-blue-700 border border-blue-200">
Overdracht
</span>
)}
</div>
<div className="flex items-center gap-1 text-xs text-slate-500">
<Calendar className="h-3 w-3" />
{formattedDate}
</div>
</div>
<p className="text-sm text-slate-700 line-clamp-2">{report.content}</p>
</div>
);
}
function VitalItem({ vital }: { vital: VitalSign }) {
const isAbnormal = vital.interpretation_code === 'H' || vital.interpretation_code === 'L';
const date = vital.effective_datetime ? new Date(vital.effective_datetime) : null;
const formattedTime = date ? format(date, 'HH:mm', { locale: nl }) : '';
return (
<div
className={cn(
'p-2 rounded-lg border',
isAbnormal
? 'bg-amber-50 border-amber-200 text-amber-700'
: 'bg-slate-50 border-slate-200 text-slate-700'
)}
>
<div className="text-xs font-medium mb-0.5">{vital.code_display}</div>
<div className="text-sm font-semibold">
{vital.value_quantity_value}
{vital.value_quantity_unit && <span className="text-xs ml-1">{vital.value_quantity_unit}</span>}
</div>
{formattedTime && <div className="text-xs text-slate-500 mt-0.5">{formattedTime}</div>}
</div>
);
}
function ConditionItem({ condition }: { condition: Condition }) {
const date = condition.onset_datetime ? new Date(condition.onset_datetime) : null;
const formattedDate = date ? format(date, 'd MMM yyyy', { locale: nl }) : null;
return (
<div className="flex items-center gap-3 p-2 rounded-lg bg-slate-50 border border-slate-200">
<div className="w-1.5 h-1.5 rounded-full bg-blue-500" />
<div className="flex-1 min-w-0">
<p className="text-sm text-slate-700">{condition.code_display}</p>
{formattedDate && (
<p className="text-xs text-slate-500">Sinds {formattedDate}</p>
)}
</div>
</div>
);
}
function RiskBadge({ risk }: { risk: RiskAssessment }) {
const RISK_TYPE_LABELS: Record<string, string> = {
suiciderisico: 'Suicide',
agressie: 'Agressie',
terugval: 'Terugval',
automutilatie: 'Automutilatie',
verwaarlozing: 'Verwaarlozing',
weglopen: 'Weglopen',
};
const RISK_LEVEL_STYLES: Record<string, { bg: string; text: string; dot: string; border: string }> = {
zeer_hoog: { bg: 'bg-red-50', text: 'text-red-700', dot: 'bg-red-500', border: 'border-red-200' },
hoog: { bg: 'bg-red-50', text: 'text-red-600', dot: 'bg-red-500', border: 'border-red-200' },
gemiddeld: { bg: 'bg-amber-50', text: 'text-amber-700', dot: 'bg-amber-500', border: 'border-amber-200' },
laag: { bg: 'bg-green-50', text: 'text-green-700', dot: 'bg-green-500', border: 'border-green-200' },
};
const styles = RISK_LEVEL_STYLES[risk.risk_level] || RISK_LEVEL_STYLES.laag;
const label = RISK_TYPE_LABELS[risk.risk_type] || risk.risk_type;
const levelLabel =
risk.risk_level === 'zeer_hoog'
? 'Zeer hoog'
: risk.risk_level.charAt(0).toUpperCase() + risk.risk_level.slice(1);
return (
<span
className={cn(
'inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-xs font-medium border',
styles.bg,
styles.text,
styles.border
)}
>
<span className={cn('w-1.5 h-1.5 rounded-full', styles.dot)} />
{label}: {levelLabel}
</span>
);
}

View File

@@ -0,0 +1,369 @@
'use client';
/**
* Patient Dashboard Block
*
* Swift artifact that shows patient properties and dashboard summary.
*/
import { useEffect, useMemo, useState } from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import {
AlertCircle,
Calendar,
ClipboardList,
Clock,
FileText,
Loader2,
User,
} from 'lucide-react';
import { BlockContainer } from './block-container';
import { safeFetch, getErrorInfo } from '@/lib/cortex/error-handler';
import { useToast } from '@/hooks/use-toast';
import { BLOCK_CONFIGS } from '@/lib/cortex/types';
import type { BlockPrefillData } from '@/stores/cortex-store';
import type { FHIRPatient } from '@/lib/fhir';
import type { Intake } from '@/lib/types/intake';
import { cn } from '@/lib/utils';
interface PatientDashboardBlockProps {
prefill?: BlockPrefillData;
}
interface EncounterSummary {
id: string;
period_start: string;
period_end?: string | null;
type_display?: string | null;
status: string;
}
interface CarePlanSummary {
id?: string;
title?: string | null;
status?: string | null;
based_on_intake_id?: string | null;
behandelstructuur?: unknown;
goals?: unknown;
activities?: unknown;
evaluatiemomenten?: unknown;
}
interface PatientDashboardResponse {
patient: FHIRPatient;
intakes: Intake[];
encounters: EncounterSummary[];
carePlan: CarePlanSummary | null;
hulpvraag?: string | null;
}
const STATUS_LABELS: Record<string, string> = {
planned: 'Screening',
active: 'Actief',
finished: 'Afgerond',
cancelled: 'Afgemeld',
};
const GENDER_LABELS: Record<string, string> = {
male: 'Man',
female: 'Vrouw',
other: 'Anders',
unknown: 'Onbekend',
};
function extractEpisodeStatus(patient?: FHIRPatient): string | null {
if (!patient) return null;
const statusExtension = (patient as any)?.extension?.find(
(ext: any) => ext.url === 'http://mini-epd.local/fhir/StructureDefinition/episode-status'
);
return statusExtension?.valueCode || null;
}
function getPatientName(patient?: FHIRPatient): string {
const name = patient?.name?.[0];
if (!name) return 'Onbekende patiënt';
return [
...(name.prefix || []),
...(name.given || []),
name.family,
]
.filter(Boolean)
.join(' ');
}
function getPatientBsn(patient?: FHIRPatient): string | null {
if (!patient?.identifier) return null;
return (
patient.identifier.find(
(id) => id.system === 'http://fhir.nl/fhir/NamingSystem/bsn'
)?.value || null
);
}
export function PatientDashboardBlock({ prefill }: PatientDashboardBlockProps) {
const config = BLOCK_CONFIGS['patient-dashboard'];
const patientId = prefill?.patientId;
const { toast } = useToast();
const [data, setData] = useState<PatientDashboardResponse | null>(null);
const [isLoading, setIsLoading] = useState(Boolean(patientId));
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!patientId) {
setError('Geen patiënt geselecteerd');
setIsLoading(false);
return;
}
const fetchDashboard = async () => {
setIsLoading(true);
setError(null);
try {
const response = await safeFetch(
`/api/patients/${patientId}/dashboard`,
undefined,
{ operation: 'Patiëntdashboard laden' }
);
const result = (await response.json()) as PatientDashboardResponse;
setData(result);
} catch (err) {
const statusCode = (err as any)?.statusCode;
const errorInfo = getErrorInfo(err, {
operation: 'Patiëntdashboard laden',
statusCode,
});
setError(errorInfo.description);
toast({
variant: 'destructive',
title: errorInfo.title,
description: errorInfo.description,
});
} finally {
setIsLoading(false);
}
};
fetchDashboard();
}, [patientId, toast]);
const patient = data?.patient;
const patientName = useMemo(() => getPatientName(patient), [patient]);
const patientStatus = extractEpisodeStatus(patient);
const patientStatusLabel = patientStatus ? STATUS_LABELS[patientStatus] || patientStatus : null;
const patientBirthDate = patient?.birthDate
? format(new Date(patient.birthDate), 'd MMM yyyy', { locale: nl })
: 'Onbekend';
const patientGender = patient?.gender ? GENDER_LABELS[patient.gender] || patient.gender : 'Onbekend';
const patientBsn = getPatientBsn(patient) || 'Onbekend';
const recentIntakes = data?.intakes?.slice(0, 3) || [];
const encounters = data?.encounters || [];
const encounterGroups = useMemo(() => {
const now = new Date();
const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const upcoming = encounters.filter((e) => new Date(e.period_start) >= todayStart);
const recent = encounters.filter((e) => new Date(e.period_start) < todayStart);
const displayEncounters = [...upcoming, ...recent].slice(0, 5);
return displayEncounters;
}, [encounters]);
const goalsCount = Array.isArray(data?.carePlan?.goals) ? data?.carePlan?.goals.length : 0;
const interventionsCount = Array.isArray(data?.carePlan?.activities)
? data?.carePlan?.activities.length
: 0;
const title = prefill?.patientName
? `${config.title} - ${prefill.patientName}`
: config.title;
return (
<BlockContainer title={title} size={config.size}>
{isLoading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-6 w-6 animate-spin text-slate-400 mr-2" />
<span className="text-sm text-slate-500">Dashboard laden...</span>
</div>
) : error ? (
<div className="text-center py-8">
<AlertCircle className="h-8 w-8 text-red-500 mx-auto mb-2" />
<p className="text-sm text-red-700">{error}</p>
</div>
) : data ? (
<div className="space-y-6">
{/* Basisgegevens */}
<section className="bg-white rounded-lg border border-slate-200 p-4">
<div className="flex items-center gap-2 mb-3">
<User className="h-4 w-4 text-blue-600" />
<h3 className="text-sm font-medium text-slate-700">Basisgegevens</h3>
{patientStatusLabel && (
<span className="text-xs px-2 py-0.5 rounded-full bg-slate-100 text-slate-700 border border-slate-200">
{patientStatusLabel}
</span>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
<div>
<p className="text-xs text-slate-500">Naam</p>
<p className="text-slate-900 font-medium">{patientName}</p>
</div>
<div>
<p className="text-xs text-slate-500">Geboortedatum</p>
<p className="text-slate-900">{patientBirthDate}</p>
</div>
<div>
<p className="text-xs text-slate-500">BSN</p>
<p className="text-slate-900">{patientBsn}</p>
</div>
<div>
<p className="text-xs text-slate-500">Geslacht</p>
<p className="text-slate-900">{patientGender}</p>
</div>
</div>
</section>
{/* Recente intakes */}
<section className="bg-white rounded-lg border border-slate-200 p-4">
<div className="flex items-center gap-2 mb-3">
<FileText className="h-4 w-4 text-teal-600" />
<h3 className="text-sm font-medium text-slate-700">Recente intakes</h3>
<span className="text-xs text-slate-500">({data.intakes.length})</span>
</div>
{recentIntakes.length === 0 ? (
<p className="text-sm text-slate-500">Geen intakes gevonden</p>
) : (
<div className="space-y-2">
{recentIntakes.map((intake) => (
<div
key={intake.id}
className="flex items-center justify-between p-3 rounded-lg bg-slate-50 border border-slate-200"
>
<div>
<p className="text-sm font-medium text-slate-900">{intake.title}</p>
<div className="flex items-center gap-2 text-xs text-slate-500 mt-0.5">
<span>{intake.department}</span>
<span></span>
<span>
{format(new Date(intake.start_date), 'd MMM yyyy', { locale: nl })}
</span>
</div>
</div>
<span className={cn(
'px-2 py-0.5 rounded-full text-xs font-medium',
intake.status === 'Open'
? 'bg-blue-50 text-blue-700'
: 'bg-green-50 text-green-700'
)}>
{intake.status}
</span>
</div>
))}
</div>
)}
</section>
{/* Agenda afspraken */}
<section className="bg-white rounded-lg border border-slate-200 p-4">
<div className="flex items-center gap-2 mb-3">
<Calendar className="h-4 w-4 text-amber-600" />
<h3 className="text-sm font-medium text-slate-700">Agenda afspraken</h3>
<span className="text-xs text-slate-500">({encounters.length})</span>
</div>
{encounterGroups.length === 0 ? (
<p className="text-sm text-slate-500">Geen afspraken gevonden</p>
) : (
<div className="space-y-2">
{encounterGroups.map((encounter) => {
const encounterDate = new Date(encounter.period_start);
const isPast = encounterDate < new Date();
return (
<div
key={encounter.id}
className="flex items-center justify-between p-3 rounded-lg bg-slate-50 border border-slate-200"
>
<div>
<p className="text-sm font-medium text-slate-900">
{encounter.type_display || 'Afspraak'}
</p>
<div className="flex items-center gap-2 text-xs text-slate-500 mt-0.5">
<Clock className="h-3 w-3" />
<span>
{format(encounterDate, 'd MMM yyyy HH:mm', { locale: nl })}
</span>
{encounter.period_end && (
<>
<span></span>
<span>
{format(new Date(encounter.period_end), 'HH:mm', { locale: nl })}
</span>
</>
)}
</div>
</div>
<span className={cn(
'px-2 py-0.5 rounded-full text-xs font-medium',
encounter.status === 'planned' || encounter.status === 'arrived'
? 'bg-blue-50 text-blue-700'
: encounter.status === 'finished'
? 'bg-green-50 text-green-700'
: isPast
? 'bg-slate-100 text-slate-700'
: 'bg-slate-50 text-slate-700'
)}>
{encounter.status === 'planned'
? 'Gepland'
: encounter.status === 'arrived'
? 'Aangekomen'
: encounter.status === 'finished'
? 'Afgerond'
: encounter.status}
</span>
</div>
);
})}
</div>
)}
</section>
{/* Behandelplan */}
<section className="bg-white rounded-lg border border-slate-200 p-4">
<div className="flex items-center gap-2 mb-3">
<ClipboardList className="h-4 w-4 text-purple-600" />
<h3 className="text-sm font-medium text-slate-700">Actief behandelplan</h3>
</div>
{data.carePlan ? (
<div className="space-y-3">
{data.hulpvraag && (
<div className="bg-slate-50 rounded-lg p-3 text-sm text-slate-700">
<p className="text-xs font-medium text-slate-500 mb-1">Hulpvraag</p>
<p className="italic">&ldquo;{data.hulpvraag}&rdquo;</p>
</div>
)}
<div className="grid grid-cols-2 gap-3 text-sm">
<div className="bg-teal-50 border border-teal-200 rounded-lg p-3">
<p className="text-xs text-teal-700 mb-1">Doelen</p>
<p className="text-base font-semibold text-teal-900">{goalsCount}</p>
</div>
<div className="bg-purple-50 border border-purple-200 rounded-lg p-3">
<p className="text-xs text-purple-700 mb-1">Interventies</p>
<p className="text-base font-semibold text-purple-900">{interventionsCount}</p>
</div>
</div>
</div>
) : (
<p className="text-sm text-slate-500">Geen actief behandelplan</p>
)}
</section>
</div>
) : (
<div className="text-sm text-slate-500">Geen gegevens beschikbaar</div>
)}
</BlockContainer>
);
}

View File

@@ -0,0 +1,348 @@
'use client';
/**
* Zoeken Block
*
* Block voor het zoeken naar patiënten.
* E3.S4: Volledige implementatie met input, resultaten en selectie naar store.
*/
import { useState, useEffect, useCallback, useRef } from 'react';
import { useToast } from '@/hooks/use-toast';
import { useCortexStore } from '@/stores/cortex-store';
import { BlockContainer } from './block-container';
import type { BlockPrefillData } from '@/stores/cortex-store';
import { BLOCK_CONFIGS } from '@/lib/cortex/types';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Loader2, Search, User, Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import { safeFetch, getErrorInfo } from '@/lib/cortex/error-handler';
interface ZoekenBlockProps {
prefill?: BlockPrefillData;
}
interface PatientSearchResult {
id: string;
name: string;
birthDate: string;
identifier_bsn?: string;
identifier_client_number?: string;
matchScore: number;
}
export function ZoekenBlock({ prefill }: ZoekenBlockProps) {
const config = BLOCK_CONFIGS.zoeken;
const { closeBlock, setActivePatient, addRecentAction, openArtifact } = useCortexStore();
const { toast } = useToast();
const prefillQuery = prefill?.patientName || prefill?.query || '';
// Search state
const [searchQuery, setSearchQuery] = useState<string>(prefillQuery);
const [patients, setPatients] = useState<PatientSearchResult[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [selectedPatientId, setSelectedPatientId] = useState<string | null>(null);
const searchTimeoutRef = useRef<NodeJS.Timeout>();
const dropdownRef = useRef<HTMLDivElement>(null);
// Patient search function
const searchPatients = useCallback(async (query: string) => {
if (query.length < 2) {
setPatients([]);
return;
}
setIsSearching(true);
try {
const response = await safeFetch(
`/api/patients/search?q=${encodeURIComponent(query)}&limit=10`,
undefined,
{ operation: 'Patiënt zoeken' }
);
const data = await response.json();
setPatients(data.patients || []);
} catch (error) {
console.error('Failed to search patients:', error);
const statusCode = (error as any)?.statusCode;
const errorInfo = getErrorInfo(error, {
operation: 'Patiënt zoeken',
statusCode,
});
toast({
variant: 'destructive',
title: errorInfo.title,
description: errorInfo.description,
});
setPatients([]);
} finally {
setIsSearching(false);
}
}, [toast]);
// Prefill search query
useEffect(() => {
if (prefillQuery) {
setSearchQuery(prefillQuery);
// Auto-search if prefill is provided
if (prefillQuery.length >= 2) {
searchPatients(prefillQuery);
}
}
}, [prefillQuery, searchPatients]);
// Debounced search
useEffect(() => {
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
if (searchQuery.length >= 2) {
searchTimeoutRef.current = setTimeout(() => {
searchPatients(searchQuery);
}, 300);
} else {
setPatients([]);
}
return () => {
if (searchTimeoutRef.current) {
clearTimeout(searchTimeoutRef.current);
}
};
}, [searchQuery, searchPatients]);
// Close dropdown on outside click
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
// Don't close if clicking on input
const target = event.target as HTMLElement;
if (!target.closest('input')) {
// Dropdown will close naturally when input loses focus
}
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// Handle patient selection
const handleSelectPatient = async (patient: PatientSearchResult) => {
setSelectedPatientId(patient.id);
try {
// Fetch full patient data from FHIR API
const response = await safeFetch(
`/api/fhir/Patient/${patient.id}`,
undefined,
{ operation: 'Patiënt data ophalen' }
);
const fhirPatient = await response.json();
// Map FHIR Patient to database Patient format
// Map gender to enum type
const genderMap: Record<string, 'male' | 'female' | 'other' | 'unknown'> = {
male: 'male',
female: 'female',
other: 'other',
unknown: 'unknown',
};
const mappedGender = genderMap[fhirPatient.gender?.toLowerCase() || 'unknown'] || 'unknown';
const dbPatient = {
id: fhirPatient.id,
name_family: fhirPatient.name?.[0]?.family || '',
name_given: fhirPatient.name?.[0]?.given || [],
birth_date: fhirPatient.birthDate || '',
identifier_bsn: fhirPatient.identifier?.find(
(id: any) => id.system === 'http://fhir.nl/fhir/NamingSystem/bsn'
)?.value || null,
identifier_client_number: fhirPatient.identifier?.find(
(id: any) => id.system?.includes('client') || id.system?.includes('999.7.6')
)?.value || null,
gender: mappedGender as 'male' | 'female' | 'other' | 'unknown',
active: fhirPatient.active !== false,
status: null,
created_at: null,
updated_at: null,
address_line: null,
address_city: null,
address_postal_code: null,
address_country: null,
telecom_email: null,
telecom_phone: null,
name_prefix: null,
name_use: null,
emergency_contact_name: null,
emergency_contact_phone: null,
emergency_contact_relationship: null,
general_practitioner_name: null,
general_practitioner_agb: null,
insurance_company: null,
insurance_number: null,
is_john_doe: null,
};
// Set active patient in store
setActivePatient(dbPatient);
// Add to recent actions
addRecentAction({
intent: 'zoeken',
label: `Patiënt geselecteerd: ${patient.name}`,
patientName: patient.name,
});
// Show success toast
toast({
title: 'Patiënt geselecteerd',
description: `${patient.name} is nu actief`,
});
// Close legacy block (v2) and open dashboard artifact (v3)
closeBlock();
openArtifact({
type: 'patient-dashboard',
title: `Dashboard - ${patient.name}`,
prefill: {
patientId: patient.id,
patientName: patient.name,
},
});
} catch (error) {
console.error('Failed to select patient:', error);
const statusCode = (error as any)?.statusCode;
const errorInfo = getErrorInfo(error, {
operation: 'Patiënt selecteren',
statusCode,
});
toast({
variant: 'destructive',
title: errorInfo.title,
description: errorInfo.description,
});
setSelectedPatientId(null);
}
};
const formatPatientDisplay = (patient: PatientSearchResult): string => {
let display = patient.name;
if (patient.birthDate) {
const birthYear = new Date(patient.birthDate).getFullYear();
const currentYear = new Date().getFullYear();
const age = currentYear - birthYear;
display += ` (${age} jaar)`;
}
return display;
};
return (
<BlockContainer title={config.title} size={config.size}>
<div className="space-y-4">
{/* Search Input */}
<div className="space-y-2">
<Label htmlFor="patient-search">Zoek patiënt</Label>
<div className="relative" ref={dropdownRef}>
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
<Input
id="patient-search"
type="text"
placeholder="Typ naam, BSN of clientnummer..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9"
autoFocus
/>
{isSearching && (
<Loader2 className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400 animate-spin" />
)}
</div>
</div>
{/* Search Results */}
{searchQuery.length >= 2 && (
<div className="space-y-2">
{isSearching ? (
<div className="flex items-center justify-center py-8 text-slate-500">
<Loader2 className="h-5 w-5 animate-spin mr-2" />
<span className="text-sm">Zoeken...</span>
</div>
) : patients.length > 0 ? (
<div className="space-y-1 max-h-96 overflow-y-auto">
{patients.map((patient) => {
const isSelected = selectedPatientId === patient.id;
return (
<button
key={patient.id}
type="button"
onClick={() => handleSelectPatient(patient)}
disabled={isSelected}
className={cn(
'w-full px-3 py-2.5 rounded-lg border text-left transition-colors',
isSelected
? 'bg-slate-100 border-slate-300 cursor-wait'
: 'bg-slate-50 border-slate-200 hover:bg-slate-100 hover:border-slate-300 cursor-pointer'
)}
>
<div className="flex items-center justify-between">
<div className="flex items-center gap-3 flex-1 min-w-0">
<div className="w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-xs font-medium text-white shrink-0">
{patient.name
.split(' ')
.map((n) => n[0])
.join('')
.slice(0, 2)
.toUpperCase()}
</div>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-slate-900 truncate">
{formatPatientDisplay(patient)}
</div>
<div className="flex items-center gap-3 mt-0.5">
{patient.identifier_bsn && (
<span className="text-xs text-slate-500">
BSN: {patient.identifier_bsn}
</span>
)}
{patient.identifier_client_number && (
<span className="text-xs text-slate-500">
Client: {patient.identifier_client_number}
</span>
)}
</div>
</div>
</div>
{isSelected ? (
<Loader2 className="h-4 w-4 animate-spin text-blue-600 shrink-0" />
) : (
<Check className="h-4 w-4 text-slate-400 shrink-0" />
)}
</div>
</button>
);
})}
</div>
) : (
<div className="flex flex-col items-center justify-center py-8 text-slate-400">
<User className="h-8 w-8 mb-2 opacity-50" />
<p className="text-sm">Geen patiënten gevonden</p>
<p className="text-xs mt-1">Probeer een andere zoekterm</p>
</div>
)}
</div>
)}
{/* Empty State */}
{searchQuery.length < 2 && (
<div className="flex flex-col items-center justify-center py-8 text-slate-400">
<Search className="h-8 w-8 mb-2 opacity-50" />
<p className="text-sm">Typ minimaal 2 karakters om te zoeken</p>
</div>
)}
</div>
</BlockContainer>
);
}