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,30 @@
'use client';
/**
* Artifact Area (v3.0 + E4)
*
* Displays artifacts using ArtifactContainer with tab support.
* Manages multiple artifacts with lifecycle actions.
*
* Epic: E1 (Foundation), E3 (Chat API), E4 (Artifact Area & Tabs)
* Stories: E1.S3, E3.S6, E4.S1, E4.S2
*/
import { useCortexStore } from '@/stores/cortex-store';
import { ArtifactContainer } from './artifact-container';
export function ArtifactArea() {
const openArtifacts = useCortexStore((s) => s.openArtifacts);
const activeArtifactId = useCortexStore((s) => s.activeArtifactId);
const switchArtifact = useCortexStore((s) => s.switchArtifact);
const closeArtifact = useCortexStore((s) => s.closeArtifact);
return (
<ArtifactContainer
artifacts={openArtifacts}
activeArtifactId={activeArtifactId}
onSelectArtifact={switchArtifact}
onCloseArtifact={closeArtifact}
/>
);
}

View File

@@ -0,0 +1,269 @@
'use client';
/**
* Artifact Container Component
*
* Container die meerdere artifacts kan beheren met tabs.
* Max 3 artifacts tegelijk, tabs alleen zichtbaar bij >1 artifact.
*
* Epic: E4 (Artifact Area & Tabs)
* Story: E4.S1 (ArtifactContainer component)
*/
import { ArtifactTab } from './artifact-tab';
import { AgendaBlock, type AgendaBlockProps } from './blocks/agenda-block';
import { DagnotatieBlock } from '../blocks/dagnotitie-block';
import { ZoekenBlock } from '../blocks/zoeken-block';
import { OverdrachtBlock } from '../blocks/overdracht-block';
import { PatientDashboardBlock } from '../blocks/patient-dashboard-block';
import { FallbackPicker } from '../blocks/fallback-picker';
import { APPOINTMENT_TYPES, type AppointmentTypeCode, type LocationClassCode } from '@/app/epd/agenda/types';
import type { Artifact, BlockType } from '@/stores/cortex-store';
interface ArtifactContainerProps {
artifacts: Artifact[];
activeArtifactId: string | null;
onSelectArtifact: (id: string) => void;
onCloseArtifact: (id: string) => void;
}
type AgendaIntent = 'agenda_query' | 'create_appointment' | 'cancel_appointment' | 'reschedule_appointment';
type AgendaMode = AgendaBlockProps['mode'];
const AGENDA_MODE_MAP: Record<AgendaIntent, AgendaMode> = {
agenda_query: 'list',
create_appointment: 'create',
cancel_appointment: 'cancel',
reschedule_appointment: 'reschedule',
};
const LOCATION_CODE_MAP: Record<string, LocationClassCode> = {
praktijk: 'AMB',
online: 'VR',
thuis: 'HH',
};
function coerceDate(value: unknown): Date | undefined {
if (value instanceof Date) return value;
if (typeof value === 'string' || typeof value === 'number') {
const parsed = new Date(value);
if (!Number.isNaN(parsed.getTime())) {
return parsed;
}
}
return undefined;
}
function coerceDateRange(raw: any): AgendaBlockProps['dateRange'] | undefined {
const start = coerceDate(raw?.start);
const end = coerceDate(raw?.end);
if (!start || !end) return undefined;
return {
start,
end,
label: typeof raw?.label === 'string' ? raw.label : 'custom',
};
}
function resolveAppointmentType(value: unknown): AppointmentTypeCode | undefined {
if (typeof value !== 'string') return undefined;
if (value in APPOINTMENT_TYPES) return value as AppointmentTypeCode;
return undefined;
}
function resolveLocation(value: unknown): LocationClassCode | undefined {
if (typeof value !== 'string') return undefined;
if (value in LOCATION_CODE_MAP) return LOCATION_CODE_MAP[value];
if (value === 'AMB' || value === 'VR' || value === 'HH') return value;
return undefined;
}
function buildAgendaPrefill(prefill: Record<string, any> | undefined): AgendaBlockProps['prefillData'] {
if (!prefill || typeof prefill !== 'object') return undefined;
const patient =
prefill.patient ||
(prefill.patientName || prefill.patientId
? {
id: prefill.patientId || '',
name: prefill.patientName || '',
}
: undefined);
const datetimeDate =
coerceDate(prefill?.datetime?.date) ||
(prefill?.datetime?.time ? new Date() : undefined);
const datetime = datetimeDate
? {
date: datetimeDate,
time: typeof prefill?.datetime?.time === 'string' ? prefill.datetime.time : '',
}
: undefined;
const appointmentType = resolveAppointmentType(prefill?.appointmentType || prefill?.type);
const location = resolveLocation(prefill?.location);
const newDatetimeDate =
coerceDate(prefill?.newDatetime?.date) ||
(prefill?.newDatetime?.time ? new Date() : undefined);
const newDatetime = newDatetimeDate
? {
date: newDatetimeDate,
time: typeof prefill?.newDatetime?.time === 'string' ? prefill.newDatetime.time : '',
}
: undefined;
return {
patient,
datetime,
type: appointmentType,
location,
notes: typeof prefill?.notes === 'string' ? prefill.notes : undefined,
identifier: prefill?.identifier,
newDatetime,
};
}
/**
* Render the appropriate block component based on artifact type
*/
function renderArtifactBlock(artifact: Artifact, onCloseArtifact: (id: string) => void) {
switch (artifact.type) {
case 'dagnotitie':
return <DagnotatieBlock key={artifact.id} prefill={artifact.prefill} />;
case 'zoeken':
return <ZoekenBlock key={artifact.id} prefill={artifact.prefill} />;
case 'overdracht':
return <OverdrachtBlock key={artifact.id} prefill={artifact.prefill} />;
case 'agenda_query':
case 'create_appointment':
case 'cancel_appointment':
case 'reschedule_appointment': {
const agendaType = artifact.type as AgendaIntent;
const rawPrefill = artifact.prefill as Record<string, any>;
const dateRange = coerceDateRange(rawPrefill?.dateRange);
const prefillData = buildAgendaPrefill(rawPrefill);
const appointments = Array.isArray(rawPrefill?.appointments)
? rawPrefill.appointments
: undefined;
const disambiguationOptions = Array.isArray(rawPrefill?.disambiguationOptions)
? rawPrefill.disambiguationOptions
: undefined;
return (
<AgendaBlock
key={artifact.id}
mode={AGENDA_MODE_MAP[agendaType]}
appointments={appointments}
dateRange={dateRange}
prefillData={prefillData}
disambiguationOptions={disambiguationOptions}
onClose={() => onCloseArtifact(artifact.id)}
/>
);
}
case 'patient-dashboard':
return <PatientDashboardBlock key={artifact.id} prefill={artifact.prefill} />;
case 'fallback':
return <FallbackPicker key={artifact.id} originalInput={artifact.prefill?.content} />;
default:
return (
<div className="p-4 text-slate-500">
Onbekend artifact type: {artifact.type}
</div>
);
}
}
/**
* Get user-friendly title for artifact type
*/
export function getArtifactTitle(type: BlockType, prefill?: any): string {
switch (type) {
case 'dagnotitie':
return prefill?.patientName
? `Dagnotitie - ${prefill.patientName}`
: 'Dagnotitie';
case 'zoeken':
return 'Patiënt Zoeken';
case 'overdracht':
return 'Dienst Overdracht';
case 'agenda_query':
return 'Agenda';
case 'create_appointment':
return prefill?.patientName
? `Nieuwe afspraak - ${prefill.patientName}`
: 'Nieuwe afspraak';
case 'cancel_appointment':
return 'Afspraak annuleren';
case 'reschedule_appointment':
return 'Afspraak verzetten';
case 'fallback':
return 'Kies een actie';
case 'patient-dashboard':
return prefill?.patientName
? `Dashboard - ${prefill.patientName}`
: 'Patiëntoverzicht';
default:
return 'Artifact';
}
}
export function ArtifactContainer({
artifacts,
activeArtifactId,
onSelectArtifact,
onCloseArtifact,
}: ArtifactContainerProps) {
// Find active artifact
const activeArtifact = artifacts.find((a) => a.id === activeArtifactId);
// Show placeholder if no artifacts
if (artifacts.length === 0) {
return (
<div className="h-full flex items-center justify-center bg-slate-50 p-6">
<div className="max-w-lg text-center text-slate-500">
<div className="text-5xl mb-4">📋</div>
<h3 className="text-xl font-medium text-slate-700 mb-3">
Artifacts verschijnen hier
</h3>
<p className="text-sm">
Vraag me iets in de chat om te beginnen!
</p>
</div>
</div>
);
}
return (
<div className="h-full flex flex-col bg-slate-50">
{/* Tabs - alleen tonen bij >1 artifact */}
{artifacts.length > 1 && (
<div className="flex bg-white border-b border-slate-200">
{artifacts.map((artifact) => (
<ArtifactTab
key={artifact.id}
artifact={artifact}
isActive={artifact.id === activeArtifactId}
onSelect={onSelectArtifact}
onClose={onCloseArtifact}
/>
))}
</div>
)}
{/* Active artifact content */}
<div className="flex-1 flex items-center justify-center p-6 overflow-y-auto">
{activeArtifact ? (
<div key={activeArtifact.id} className="artifact-enter w-full">
{renderArtifactBlock(activeArtifact, onCloseArtifact)}
</div>
) : (
<div className="text-slate-500">
Selecteer een artifact om te bekijken
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,63 @@
'use client';
/**
* Artifact Tab Component
*
* Tab voor een individueel artifact in de ArtifactContainer.
* Toont titel, close button, en active state.
*
* Epic: E4 (Artifact Area & Tabs)
* Story: E4.S1 (ArtifactContainer component)
*/
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { Artifact } from '@/stores/cortex-store';
interface ArtifactTabProps {
artifact: Artifact;
isActive: boolean;
onSelect: (id: string) => void;
onClose: (id: string) => void;
}
export function ArtifactTab({ artifact, isActive, onSelect, onClose }: ArtifactTabProps) {
return (
<div
className={cn(
'group flex items-center gap-2 px-4 py-2.5 border-r border-slate-200 cursor-pointer transition-colors',
'hover:bg-slate-50 min-w-[140px] max-w-[200px]',
isActive && 'bg-white border-b-2 border-b-amber-500'
)}
onClick={() => onSelect(artifact.id)}
>
{/* Tab title */}
<span
className={cn(
'flex-1 text-sm font-medium truncate',
isActive ? 'text-slate-900' : 'text-slate-600'
)}
title={artifact.title}
>
{artifact.title}
</span>
{/* Close button */}
<button
onClick={(e) => {
e.stopPropagation();
onClose(artifact.id);
}}
className={cn(
'p-0.5 rounded hover:bg-slate-200 text-slate-400 hover:text-slate-700 transition-colors',
'opacity-0 group-hover:opacity-100',
isActive && 'opacity-100'
)}
title="Sluiten"
aria-label={`Sluit ${artifact.title}`}
>
<X size={14} />
</button>
</div>
);
}

View File

@@ -0,0 +1,88 @@
'use client';
import React from 'react';
import { AppointmentTypeCode, LocationClassCode, CalendarEvent } from '@/app/epd/agenda/types';
import { AgendaListView } from './agenda-list-view';
import { AgendaCreateForm } from './agenda-create-form';
import { AgendaCancelView } from './agenda-cancel-view';
import { AgendaRescheduleForm } from './agenda-reschedule-form';
import { motion, AnimatePresence } from 'framer-motion';
export interface AgendaBlockProps {
mode: 'list' | 'create' | 'cancel' | 'reschedule';
appointments?: CalendarEvent[];
dateRange?: { start: Date; end: Date; label: string };
prefillData?: {
patient?: { id: string; name: string };
datetime?: { date: Date; time: string };
type?: AppointmentTypeCode;
location?: LocationClassCode;
notes?: string;
identifier?: { encounterId?: string; encounter?: CalendarEvent };
newDatetime?: { date: Date; time: string };
};
disambiguationOptions?: CalendarEvent[];
onClose?: () => void;
}
export function AgendaBlock({
mode,
appointments,
dateRange,
prefillData,
disambiguationOptions,
onClose,
}: AgendaBlockProps) {
const renderContent = () => {
switch (mode) {
case 'list':
return (
<AgendaListView
key="list"
appointments={appointments}
dateRange={dateRange}
onClose={onClose}
onCancelAppointment={(evt) => console.log('Cancel requested', evt)}
onViewDetails={(evt) => window.location.href = `/epd/agenda?focus=${evt.id}`}
/>
);
case 'create':
return <AgendaCreateForm key="create" prefillData={prefillData} onClose={onClose} />;
case 'cancel':
return (
<AgendaCancelView
key="cancel"
disambiguationOptions={disambiguationOptions}
prefillData={prefillData}
onClose={onClose}
/>
);
case 'reschedule':
return <AgendaRescheduleForm key="reschedule" prefillData={prefillData} onClose={onClose} />;
default:
return <div key="error" className="p-4 text-red-500">Unknown mode: {mode}</div>;
}
};
return (
<motion.div
initial={{ opacity: 0, y: 20, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 10, scale: 0.98 }}
transition={{ type: "spring", stiffness: 350, damping: 25 }}
className="w-full max-w-[600px] max-h-[80vh] h-[600px] overflow-hidden bg-white/95 backdrop-blur-xl border border-black/5 rounded-2xl shadow-2xl flex flex-col"
>
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={mode}
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: -20 }}
transition={{ duration: 0.2 }}
className="flex flex-col h-full overflow-hidden"
>
{renderContent()}
</motion.div>
</AnimatePresence>
</motion.div>
);
}

View File

@@ -0,0 +1,223 @@
'use client';
import React, { useState } from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { AlertTriangle, Calendar, Clock, X, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { cancelEncounter } from '@/app/epd/agenda/actions';
import { CalendarEvent, APPOINTMENT_TYPES, AppointmentTypeCode } from '@/app/epd/agenda/types';
import { motion } from 'framer-motion';
interface AgendaCancelViewProps {
disambiguationOptions?: CalendarEvent[];
prefillData?: {
identifier?: { encounterId?: string };
};
onClose?: () => void;
}
export function AgendaCancelView({ disambiguationOptions, prefillData, onClose }: AgendaCancelViewProps) {
const [selectedEncounterId, setSelectedEncounterId] = useState<string | undefined>(
prefillData?.identifier?.encounterId
);
// If we have disambiguation options and no selection yet, default to first?
// Better to let user choose.
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [error, setError] = useState<string | null>(null);
// If there's only one option provided via disambiguationOptions (and no prefill), select it automatically?
// Logic: if prefill encounterId is set, use that.
// If not, and disambiguationOptions has 1 item, use that.
// If not, wait for user selection.
const effectiveEncounter = disambiguationOptions?.find(e => e.id === selectedEncounterId) ||
(disambiguationOptions?.length === 1 ? disambiguationOptions[0] : undefined);
const handleCancel = async () => {
const idToCancel = selectedEncounterId || effectiveEncounter?.id;
if (!idToCancel) {
setError('Selecteer eerst een afspraak om te annuleren.');
return;
}
setIsSubmitting(true);
setError(null);
try {
const result = await cancelEncounter(idToCancel);
if (result.success) {
setIsSuccess(true);
// Wait a moment before closing or let user close
setTimeout(() => onClose?.(), 2000);
} else {
setError(result.error || 'Kon de afspraak niet annuleren.');
}
} catch (err) {
console.error('Cancel error:', err);
setError('Er is een onverwachte fout opgetreden.');
} finally {
setIsSubmitting(false);
}
};
if (isSuccess) {
return (
<div className="flex flex-col items-center justify-center p-8 text-center h-full">
<div className="bg-green-50 p-3 rounded-full mb-4">
<CheckCircle2 className="h-8 w-8 text-green-600" />
</div>
<h3 className="text-lg font-semibold text-gray-900">Afspraak geannuleerd</h3>
<p className="text-sm text-gray-500 mt-1 mb-6">De afspraak is succesvol verwijderd uit de agenda.</p>
<Button onClick={onClose} variant="outline" className="border-black/5 bg-white/50 hover:bg-white">Sluiten</Button>
</div>
);
}
// Disambiguation Mode
if (!effectiveEncounter && disambiguationOptions && disambiguationOptions.length > 1) {
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="flex flex-col h-full bg-transparent"
>
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-red-700">Afspraak annuleren</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
<div className="flex-1 p-5 overflow-y-auto">
<p className="text-sm text-gray-600 mb-4 font-medium">
Er zijn meerdere afspraken gevonden. Welke wil je annuleren?
</p>
<RadioGroup value={selectedEncounterId} onValueChange={setSelectedEncounterId} className="space-y-3">
{disambiguationOptions.map((evt) => {
const encounter = evt.extendedProps.encounter;
const typeCode = encounter.type_code as AppointmentTypeCode;
const dateStr = format(new Date(evt.start), 'd MMM yyyy', { locale: nl });
const timeStr = format(new Date(evt.start), 'HH:mm');
return (
<div key={evt.id} className="flex items-center space-x-3 border border-black/5 rounded-xl p-4 hover:bg-white/50 cursor-pointer bg-white/40 transition-colors">
<RadioGroupItem value={evt.id} id={evt.id} />
<Label htmlFor={evt.id} className="flex-1 cursor-pointer">
<div className="font-semibold text-gray-900">{evt.title}</div>
<div className="text-sm text-gray-500 mt-0.5">
{dateStr} om {timeStr} {encounter.type_display || APPOINTMENT_TYPES[typeCode]}
</div>
</Label>
</div>
);
})}
</RadioGroup>
</div>
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" onClick={onClose} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">Annuleren</Button>
<Button
onClick={() => { /* State updates automatically via RadioGroup */ }}
disabled={!selectedEncounterId}
className="flex-1 bg-red-600 hover:bg-red-700 text-white shadow-md hover:shadow-lg h-10 rounded-lg"
>
Volgende
</Button>
</div>
</motion.div>
);
}
// Confirmation Mode (Single Match)
if (effectiveEncounter) {
const encounter = effectiveEncounter.extendedProps.encounter;
const typeCode = encounter.type_code as AppointmentTypeCode;
const dateStr = format(new Date(effectiveEncounter.start), 'EEEE d MMMM yyyy', { locale: nl });
const timeStr = format(new Date(effectiveEncounter.start), 'HH:mm');
const endTimeStr = effectiveEncounter.end ? format(new Date(effectiveEncounter.end), 'HH:mm') : '';
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="flex flex-col h-full bg-transparent"
>
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-red-700">Weet je het zeker?</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
<div className="flex-1 p-5">
<div className="bg-red-50/70 border border-red-100/50 rounded-xl p-4 mb-6">
<div className="flex items-start gap-3">
<div className="p-2 bg-red-100 rounded-full mt-0.5">
<AlertTriangle className="h-4 w-4 text-red-600" />
</div>
<div className="text-sm text-red-900">
<p className="font-semibold text-base">Deze actie kan niet ongedaan worden gemaakt.</p>
<p className="mt-1 opacity-90 leading-relaxed">De afspraak met <span className="font-semibold">{effectiveEncounter.title}</span> wordt permanent uit de agenda verwijderd.</p>
</div>
</div>
</div>
<div className="border border-black/5 rounded-xl p-5 bg-white/60 shadow-sm backdrop-blur-sm">
<h4 className="font-semibold text-gray-900 mb-3 text-lg">{effectiveEncounter.title}</h4>
<div className="space-y-3 text-sm text-gray-600">
<div className="flex items-center gap-3">
<Calendar className="h-4 w-4 text-gray-400" />
<span className="capitalize font-medium">{dateStr}</span>
</div>
<div className="flex items-center gap-3">
<Clock className="h-4 w-4 text-gray-400" />
<span className="font-medium">{timeStr} {endTimeStr && `- ${endTimeStr}`}</span>
</div>
<div className="flex items-center gap-3">
<span className="inline-block w-5 text-center text-gray-400"></span>
<span className="font-medium bg-gray-100 px-2 py-0.5 rounded text-gray-700">{encounter.type_display || APPOINTMENT_TYPES[typeCode]}</span>
</div>
</div>
</div>
{error && (
<div className="mt-4 p-4 bg-red-50 text-red-700 text-sm rounded-xl border border-red-100">
{error}
</div>
)}
</div>
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" onClick={onClose} disabled={isSubmitting} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">
Terug
</Button>
<Button
onClick={handleCancel}
disabled={isSubmitting}
className="flex-1 bg-red-600 hover:bg-red-700 text-white shadow-md hover:shadow-lg h-10 rounded-lg"
>
{isSubmitting ? 'Annuleren...' : 'Ja, annuleer afspraak'}
</Button>
</div>
</motion.div>
);
}
// Fallback / Loading
return (
<div className="p-4">
<p>Geen afspraak geselecteerd.</p>
<Button onClick={onClose} variant="link">Sluiten</Button>
</div>
);
}

View File

@@ -0,0 +1,371 @@
'use client';
import React, { useState, useEffect, useRef } from 'react';
import { format, addHours, parseISO } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, Clock, MapPin, User, Check, X, AlertCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { motion } from 'framer-motion';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { createEncounter } from '@/app/epd/agenda/actions';
import {
APPOINTMENT_TYPES,
LOCATION_CLASSES,
AppointmentTypeCode,
LocationClassCode,
APPOINTMENT_TYPE_COLORS
} from '@/app/epd/agenda/types';
import { AgendaErrorAlert } from './agenda-error-state';
interface AgendaCreateFormProps {
prefillData?: {
patient?: { id: string; name: string };
datetime?: { date: Date; time: string };
type?: AppointmentTypeCode;
location?: LocationClassCode;
notes?: string;
};
onClose?: () => void;
}
interface PatientResult {
id: string;
name: string;
bsn?: string;
birthDate?: string;
}
export function AgendaCreateForm({ prefillData, onClose }: AgendaCreateFormProps) {
// Form State
const [patientId, setPatientId] = useState<string>(prefillData?.patient?.id || '');
const [patientName, setPatientName] = useState<string>(prefillData?.patient?.name || '');
const [date, setDate] = useState<string>(
prefillData?.datetime?.date ? format(prefillData.datetime.date, 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd')
);
const [time, setTime] = useState<string>(prefillData?.datetime?.time || '09:00');
const [type, setType] = useState<AppointmentTypeCode>(prefillData?.type || 'behandeling');
const [location, setLocation] = useState<LocationClassCode>(prefillData?.location || 'AMB');
const [notes, setNotes] = useState<string>(prefillData?.notes || '');
// UI State
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Patient Search State
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<PatientResult[]>([]);
const [isSearching, setIsSearching] = useState(false);
const [showResults, setShowResults] = useState(false);
const searchRef = useRef<HTMLDivElement>(null);
// Initialize search query if patient is prefilled but we want to allow editing
useEffect(() => {
if (prefillData?.patient?.name) {
setSearchQuery(prefillData.patient.name);
}
}, [prefillData]);
// Handle outside click to close search results
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (searchRef.current && !searchRef.current.contains(event.target as Node)) {
setShowResults(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// Debounced search
useEffect(() => {
const timer = setTimeout(async () => {
if (searchQuery.length < 2 || patientId) return; // Don't search if too short or if patient already selected
setIsSearching(true);
try {
const res = await fetch(`/api/cortex/patients/search?q=${encodeURIComponent(searchQuery)}`);
if (res.ok) {
const data = await res.json();
setSearchResults(data.patients || []);
setShowResults(true);
}
} catch (err) {
console.error('Failed to search patients', err);
} finally {
setIsSearching(false);
}
}, 300);
return () => clearTimeout(timer);
}, [searchQuery, patientId]);
const handlePatientSelect = (patient: PatientResult) => {
setPatientId(patient.id);
setPatientName(patient.name);
setSearchQuery(patient.name);
setShowResults(false);
};
const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setSearchQuery(e.target.value);
setPatientId(''); // Clear selection on edit
setPatientName('');
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!patientId) {
setError('Selecteer a.u.b. een patiënt.');
return;
}
setIsSubmitting(true);
setError(null);
try {
// Construct Date objects
const startDate = new Date(`${date}T${time}`);
const endDate = addHours(startDate, 1); // Default duration 1 hour
// Map codes to displays
const typeDisplay = APPOINTMENT_TYPES[type];
const locationDisplay = LOCATION_CLASSES[location];
const result = await createEncounter({
patientId,
periodStart: startDate.toISOString(),
periodEnd: endDate.toISOString(),
typeCode: type,
typeDisplay,
classCode: location,
classDisplay: locationDisplay,
notes: notes || undefined,
});
if (result.success) {
onClose?.(); // Close on success
} else {
setError(result.error || 'Er is een fout opgetreden.');
}
} catch (err) {
console.error('Submit error:', err);
setError('Er is een onverwachte fout opgetreden.');
} finally {
setIsSubmitting(false);
}
};
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3, ease: 'easeOut' }}
className="flex flex-col h-full bg-transparent"
>
{/* Header */}
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-gray-900">Nieuwe afspraak inplannen</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 text-gray-500 hover:text-gray-900 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
{/* Form Body */}
<form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-5 space-y-5">
{error && (
<AgendaErrorAlert
error={error}
onDismiss={() => setError(null)}
showFallbackLink={true}
/>
)}
{/* Patient Selection */}
<div className="space-y-2" ref={searchRef}>
<Label htmlFor="patient" className="text-sm font-medium text-gray-700">Patiënt <span className="text-red-500">*</span></Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<User className="h-4 w-4" />
</div>
<Input
id="patient"
value={searchQuery}
onChange={handleSearchChange}
placeholder="Zoek op naam..."
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
autoComplete="off"
/>
{isSearching && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<div className="animate-spin h-3 w-3 border-2 border-teal-500 border-t-transparent rounded-full"></div>
</div>
)}
{showResults && searchResults.length > 0 && (
<div className="absolute z-10 w-full mt-1 bg-white/95 backdrop-blur-xl border border-black/5 rounded-xl shadow-xl max-h-48 overflow-y-auto">
{searchResults.map((p) => (
<button
key={p.id}
type="button"
onClick={() => handlePatientSelect(p)}
className="w-full text-left px-4 py-3 hover:bg-teal-50/50 text-sm flex flex-col border-b last:border-0 border-black/5 transition-colors"
>
<span className="font-medium text-gray-900">{p.name}</span>
<span className="text-xs text-gray-500 mt-0.5">
{p.birthDate && format(new Date(p.birthDate), 'dd-MM-yyyy')}
{p.bsn && ` • BSN: ${p.bsn}`}
</span>
</button>
))}
</div>
)}
</div>
</div>
{/* Date & Time */}
<div className="grid grid-cols-2 gap-5">
<div className="space-y-2">
<Label htmlFor="date" className="text-sm font-medium text-gray-700">Datum <span className="text-red-500">*</span></Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Calendar className="h-4 w-4" />
</div>
<Input
id="date"
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="time" className="text-sm font-medium text-gray-700">Tijd <span className="text-red-500">*</span></Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Clock className="h-4 w-4" />
</div>
<Input
id="time"
type="time"
value={time}
onChange={(e) => setTime(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
</div>
{/* Type Selection */}
<div className="space-y-2">
<Label className="text-sm font-medium text-gray-700">Type afspraak <span className="text-red-500">*</span></Label>
<div className="grid grid-cols-2 gap-2.5">
{(Object.keys(APPOINTMENT_TYPES) as AppointmentTypeCode[]).map((t) => {
const bg = APPOINTMENT_TYPE_COLORS[t].bg;
const text = APPOINTMENT_TYPE_COLORS[t].text;
const border = APPOINTMENT_TYPE_COLORS[t].border;
const isActive = type === t;
return (
<button
key={t}
type="button"
onClick={() => setType(t)}
className={`
px-3 py-2.5 text-xs font-medium rounded-lg border text-left transition-all
${isActive ? 'ring-2 ring-offset-1 ring-teal-500 shadow-sm' : 'hover:bg-black/5 bg-white/40'}
`}
style={{
backgroundColor: isActive ? bg : undefined,
color: isActive ? text : '#374151',
borderColor: isActive ? border : 'rgba(0,0,0,0.1)'
}}
>
<div className="flex items-center justify-between">
<span>{APPOINTMENT_TYPES[t]}</span>
{isActive && <Check className="h-3.5 w-3.5" />}
</div>
</button>
);
})}
</div>
</div>
{/* Location Selection */}
<div className="space-y-2">
<Label className="text-sm font-medium text-gray-700">Locatie <span className="text-red-500">*</span></Label>
<div className="flex gap-2.5">
{(Object.keys(LOCATION_CLASSES) as LocationClassCode[]).map((l) => (
<button
key={l}
type="button"
onClick={() => setLocation(l)}
className={`
flex-1 py-2.5 px-3 text-xs font-medium rounded-lg border flex items-center justify-center gap-2 transition-all
${location === l
? 'bg-teal-50 border-teal-200 text-teal-800 ring-2 ring-teal-500 ring-opacity-20 shadow-sm'
: 'bg-white/40 border-black/10 text-gray-600 hover:bg-black/5'}
`}
>
{l === 'AMB' && <MapPin className="h-3.5 w-3.5" />}
{l === 'VR' && <div className="h-3.5 w-3.5 border rounded-full" />}
{l === 'HH' && <div className="h-3.5 w-3.5 bg-current rounded-sm" />}
{LOCATION_CLASSES[l]}
</button>
))}
</div>
</div>
{/* Notes */}
<div className="space-y-2">
<Label htmlFor="notes" className="text-sm font-medium text-gray-700">Notities (optioneel)</Label>
<Textarea
id="notes"
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="Bijv. bijzonderheden, reden van komst..."
className="h-24 text-sm resize-none bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors rounded-lg"
/>
</div>
<div className="pt-2"></div>
</form>
{/* Footer / Actions */}
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" type="button" onClick={onClose} disabled={isSubmitting} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">
Annuleren
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="flex-1 bg-teal-600 hover:bg-teal-700 text-white shadow-md hover:shadow-lg transition-all h-10 rounded-lg"
>
{isSubmitting ? (
<div className="flex items-center gap-2">
<div className="h-3 w-3 border-2 border-white/50 border-t-white rounded-full animate-spin" />
<span>Bezig...</span>
</div>
) : (
'Afspraak inplannen'
)}
</Button>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,186 @@
'use client';
import React from 'react';
import { AlertCircle, RefreshCw, ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';
/**
* AgendaErrorState Component
*
* Reusable error display for agenda operations.
* Epic 5.S3 - Provides user-friendly error messages with fallback links.
*/
interface AgendaErrorStateProps {
error: string | Error;
onRetry?: () => void;
showFallbackLink?: boolean;
context?: 'query' | 'create' | 'cancel' | 'reschedule';
}
/**
* Get user-friendly error message based on error type and context
*/
function getUserFriendlyMessage(error: string | Error, context?: string): string {
const errorString = error instanceof Error ? error.message : error;
// Check for specific error types
if (errorString.includes('401') || errorString.includes('Niet geautoriseerd')) {
return 'Je sessie is verlopen. Log opnieuw in.';
}
if (errorString.includes('404')) {
return 'De gevraagde afspraak kon niet worden gevonden.';
}
if (errorString.includes('403')) {
return 'Je hebt geen toegang tot deze afspraak.';
}
if (errorString.includes('500') || errorString.includes('server')) {
return 'Er ging iets mis op de server. Probeer het opnieuw.';
}
if (errorString.includes('network') || errorString.includes('Failed to fetch')) {
return 'Geen internetverbinding. Controleer je netwerkverbinding.';
}
if (errorString.includes('timeout')) {
return 'De aanvraag duurde te lang. Probeer het opnieuw.';
}
// Context-specific messages
if (context === 'query') {
return 'Er ging iets mis bij het ophalen van je afspraken.';
}
if (context === 'create') {
return 'Er ging iets mis bij het aanmaken van de afspraak.';
}
if (context === 'cancel') {
return 'Er ging iets mis bij het annuleren van de afspraak.';
}
if (context === 'reschedule') {
return 'Er ging iets mis bij het verzetten van de afspraak.';
}
// Fallback to provided error or generic message
return errorString || 'Er is een onverwachte fout opgetreden.';
}
export function AgendaErrorState({
error,
onRetry,
showFallbackLink = true,
context,
}: AgendaErrorStateProps) {
const userMessage = getUserFriendlyMessage(error, context);
// Check if this is an auth error (should redirect)
const isAuthError = userMessage.includes('sessie') || userMessage.includes('Log opnieuw in');
if (isAuthError) {
// Redirect to login
if (typeof window !== 'undefined') {
window.location.href = '/login';
}
return null;
}
return (
<div className="flex flex-col items-center justify-center p-8 text-center">
<div className="bg-red-50 p-4 rounded-full mb-4">
<AlertCircle className="h-8 w-8 text-red-500" />
</div>
<h3 className="font-semibold text-gray-900 mb-2">Er ging iets mis</h3>
<p className="text-sm text-gray-600 mb-6 max-w-md">
{userMessage}
</p>
<div className="flex flex-col sm:flex-row gap-3">
{onRetry && (
<Button
onClick={onRetry}
variant="outline"
className="gap-2 border-teal-200 text-teal-700 hover:bg-teal-50"
>
<RefreshCw className="h-4 w-4" />
Probeer opnieuw
</Button>
)}
{showFallbackLink && (
<Button
onClick={() => {
window.location.href = '/epd/agenda';
}}
variant={onRetry ? 'ghost' : 'outline'}
className="gap-2 text-teal-700 hover:bg-teal-50"
>
<ExternalLink className="h-4 w-4" />
Open volledige agenda
</Button>
)}
</div>
{/* Technical details (collapsed by default) */}
{process.env.NODE_ENV === 'development' && (
<details className="mt-6 text-left w-full max-w-md">
<summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-700">
Technische details (dev only)
</summary>
<pre className="mt-2 text-xs bg-gray-100 p-3 rounded overflow-auto text-gray-700">
{error instanceof Error ? error.stack : error}
</pre>
</details>
)}
</div>
);
}
/**
* Inline error alert (for forms)
*/
interface AgendaErrorAlertProps {
error: string | Error;
onDismiss?: () => void;
showFallbackLink?: boolean;
}
export function AgendaErrorAlert({
error,
onDismiss,
showFallbackLink = false,
}: AgendaErrorAlertProps) {
const userMessage = getUserFriendlyMessage(error);
return (
<div className="p-3 bg-red-50 border border-red-200 rounded-md flex items-start gap-2 text-sm text-red-700">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
<div className="flex-1">
<p>{userMessage}</p>
{showFallbackLink && (
<a
href="/epd/agenda"
className="text-xs underline hover:no-underline mt-1 inline-block"
>
Open volledige agenda
</a>
)}
</div>
{onDismiss && (
<button
onClick={onDismiss}
className="text-red-400 hover:text-red-600"
aria-label="Sluit melding"
>
×
</button>
)}
</div>
);
}

View File

@@ -0,0 +1,199 @@
'use client';
import React from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, MapPin, Globe, Home, Clock, X, Info, ChevronRight, Ban } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { motion } from 'framer-motion';
import {
CalendarEvent,
APPOINTMENT_TYPE_COLORS,
APPOINTMENT_TYPES,
LOCATION_CLASSES,
LocationClassCode,
AppointmentTypeCode
} from '@/app/epd/agenda/types';
interface AgendaListViewProps {
appointments?: CalendarEvent[];
dateRange?: { start: Date; end: Date; label: string };
onClose?: () => void;
onCancelAppointment?: (encounter: CalendarEvent) => void;
onViewDetails?: (encounter: CalendarEvent) => void;
}
const containerVariants = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: {
staggerChildren: 0.1
}
}
};
const itemVariants = {
hidden: { opacity: 0, y: 10 },
show: { opacity: 1, y: 0 }
};
export function AgendaListView({
appointments = [],
dateRange,
onClose,
onCancelAppointment,
onViewDetails
}: AgendaListViewProps) {
const formatDateLabel = () => {
if (dateRange?.label) {
if (dateRange.label === 'vandaag' || dateRange.label === 'morgen') {
const dateStr = format(dateRange.start, 'd MMMM', { locale: nl });
return `Afspraken ${dateRange.label} - ${dateStr}`;
}
return `Afspraken ${dateRange.label}`;
}
// Fallback if no specific label
if (appointments.length > 0) {
return `Afspraken ${format(new Date(appointments[0].start), 'd MMMM', { locale: nl })}`;
}
return 'Afspraken';
};
const getLocationIcon = (classCode: string) => {
switch (classCode as LocationClassCode) {
case 'AMB': return <MapPin className="h-3 w-3" />;
case 'VR': return <Globe className="h-3 w-3" />;
case 'HH': return <Home className="h-3 w-3" />;
default: return <MapPin className="h-3 w-3" />;
}
};
return (
<div className="flex flex-col h-full bg-transparent">
{/* Header */}
<div className="flex items-center justify-between p-5 border-b border-black/5">
<div className="flex items-center gap-3 text-teal-700">
<div className="p-2 bg-teal-50 rounded-lg">
<Calendar className="h-5 w-5" />
</div>
<h3 className="font-semibold text-lg text-gray-900 capitalize leading-tight">{formatDateLabel()}</h3>
</div>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 text-gray-500 hover:text-gray-900 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
{/* Body */}
<motion.div
className="flex-1 overflow-y-auto p-5 space-y-3"
variants={containerVariants}
initial="hidden"
animate="show"
>
{appointments.length === 0 ? (
<motion.div
variants={itemVariants}
className="flex flex-col items-center justify-center h-full text-center text-gray-500"
>
<div className="bg-gray-50/50 p-4 rounded-full mb-4">
<Calendar className="h-8 w-8 text-gray-400" />
</div>
<p className="font-medium text-gray-900">Geen afspraken gevonden</p>
<p className="text-sm text-gray-500 mt-1 max-w-[200px]">
Er staan geen afspraken gepland voor deze periode.
</p>
<Button variant="outline" className="mt-6 gap-2 text-teal-700 border-teal-200/50 hover:bg-teal-50/50 bg-white/50">
<span className="text-lg leading-none">+</span> Maak nieuwe afspraak
</Button>
</motion.div>
) : (
appointments.map((evt) => {
const encounter = evt.extendedProps.encounter;
const patient = evt.extendedProps.patient;
const typeCode = encounter.type_code as AppointmentTypeCode;
const typeColor = APPOINTMENT_TYPE_COLORS[typeCode] || APPOINTMENT_TYPE_COLORS.overig;
const classCode = encounter.class_code as LocationClassCode;
const startTime = format(new Date(evt.start), 'HH:mm');
const endTime = evt.end ? format(new Date(evt.end), 'HH:mm') : '';
return (
<motion.div
key={evt.id}
variants={itemVariants}
className="group border border-black/5 rounded-2xl p-4 hover:border-teal-200/50 hover:shadow-md transition-all bg-white/60 hover:bg-white/90 backdrop-blur-sm"
>
<div className="flex justify-between items-start mb-3">
<div className="flex flex-col">
<div className="flex items-center gap-2 text-sm font-medium text-gray-500 mb-0.5">
<Clock className="h-3.5 w-3.5" />
<span>{startTime} {endTime && `- ${endTime}`}</span>
</div>
<button
className="text-left text-base font-semibold text-gray-900 hover:text-teal-700 hover:underline transition-colors"
onClick={() => console.log('Open patient context', patient?.id)}
>
{evt.title}
</button>
</div>
<Badge
variant="outline"
style={{
backgroundColor: typeColor.bg,
color: typeColor.text,
borderColor: typeColor.border
}}
className="whitespace-nowrap shadow-none px-2.5 py-0.5 text-xs font-medium rounded-md"
>
{encounter.type_display || APPOINTMENT_TYPES[typeCode] || typeCode}
</Badge>
</div>
<div className="flex items-center gap-4 text-xs text-gray-500 mt-2">
<div className="flex items-center gap-1.5" title={LOCATION_CLASSES[classCode]}>
{getLocationIcon(classCode)}
<span>{encounter.class_display || LOCATION_CLASSES[classCode] || classCode}</span>
</div>
{encounter.status === 'cancelled' && (
<Badge variant="destructive" className="h-5 px-1.5 font-normal rounded-sm">Geannuleerd</Badge>
)}
</div>
<div className="flex items-center justify-end gap-2 mt-4 pt-3 border-t border-black/5 opacity-0 group-hover:opacity-100 transition-opacity">
<Button
variant="ghost"
size="sm"
className="h-8 text-xs font-medium text-gray-500 hover:text-red-600 hover:bg-red-50/50 rounded-lg px-3"
onClick={() => onCancelAppointment?.(evt)}
>
Annuleren
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 text-xs font-medium text-teal-700 hover:bg-teal-50/50 rounded-lg px-3"
onClick={() => onViewDetails?.(evt)}
>
Details <ChevronRight className="ml-1 h-3 w-3" />
</Button>
</div>
</motion.div>
);
})
)}
</motion.div>
{/* Footer */}
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 text-center">
<a
href="/epd/agenda"
className="text-sm font-medium text-teal-700 hover:text-teal-800 hover:underline inline-flex items-center gap-1 transition-colors"
>
Open volledige agenda <ChevronRight className="h-4 w-4" />
</a>
</div>
</div>
);
}

View File

@@ -0,0 +1,220 @@
'use client';
import React, { useState, useEffect } from 'react';
import { format, addHours } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, Clock, X, ArrowRight, AlertCircle, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { rescheduleEncounter } from '@/app/epd/agenda/actions';
import { CalendarEvent } from '@/app/epd/agenda/types';
import { motion } from 'framer-motion';
interface AgendaRescheduleFormProps {
prefillData?: {
identifier?: { encounterId?: string; encounter?: CalendarEvent };
newDatetime?: { date: Date; time: string };
};
onClose?: () => void;
}
export function AgendaRescheduleForm({ prefillData, onClose }: AgendaRescheduleFormProps) {
// Use encounter from prefill if provided directly (we might need to pass it in prefillData from parent)
const encounter = prefillData?.identifier?.encounter;
const encounterId = prefillData?.identifier?.encounterId;
// State for new date/time
const [date, setDate] = useState<string>(
prefillData?.newDatetime?.date
? format(prefillData.newDatetime.date, 'yyyy-MM-dd')
: encounter ? format(new Date(encounter.start), 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd')
);
const [time, setTime] = useState<string>(
prefillData?.newDatetime?.time
? prefillData.newDatetime.time
: encounter ? format(new Date(encounter.start), 'HH:mm') : '09:00'
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSuccess, setIsSuccess] = useState(false);
const [error, setError] = useState<string | null>(null);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!encounterId) {
setError('Geen afspraak ID gevonden.');
return;
}
setIsSubmitting(true);
setError(null);
try {
const startDate = new Date(`${date}T${time}`);
// Keep same duration? For simplicty default to 1 hour or original duration if we knew it.
// API rescheduleEncounter takes start/end.
let endDate = addHours(startDate, 1);
if (encounter && encounter.end) {
const originalDuration = new Date(encounter.end).getTime() - new Date(encounter.start).getTime();
endDate = new Date(startDate.getTime() + originalDuration);
}
// Check if not in past
if (startDate < new Date()) {
setError('Kan niet verplaatsen naar een datum in het verleden.');
setIsSubmitting(false);
return;
}
const result = await rescheduleEncounter(
encounterId,
startDate.toISOString(),
endDate.toISOString()
);
if (result.success) {
setIsSuccess(true);
setTimeout(() => onClose?.(), 2000);
} else {
setError(result.error || 'Kon de afspraak niet verzetten.');
}
} catch (err) {
console.error('Reschedule error:', err);
setError('Er is een onverwachte fout opgetreden.');
} finally {
setIsSubmitting(false);
}
};
if (isSuccess) {
return (
<div className="flex flex-col items-center justify-center p-8 text-center h-full">
<div className="bg-green-50 p-3 rounded-full mb-4">
<CheckCircle2 className="h-8 w-8 text-green-600" />
</div>
<h3 className="text-lg font-semibold text-gray-900">Afspraak verzet</h3>
<p className="text-sm text-gray-500 mt-1 mb-6">
De afspraak is verplaatst naar {format(new Date(`${date}T${time}`), 'd MMMM HH:mm', { locale: nl })}.
</p>
<Button onClick={onClose} variant="outline" className="border-black/5 bg-white/50 hover:bg-white">Sluiten</Button>
</div>
);
}
if (!encounter && !encounterId) {
return (
<div className="p-4 text-center">
<p className="text-red-500">Geen afspraak gevonden om te verzetten.</p>
<Button onClick={onClose} variant="link">Sluiten</Button>
</div>
);
}
// Calculate current date/time for display
const currentStart = encounter ? new Date(encounter.start) : null;
const currentStr = currentStart ? format(currentStart, 'd MMMM yyyy HH:mm', { locale: nl }) : 'Onbekend';
return (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.3 }}
className="flex flex-col h-full bg-transparent"
>
{/* Header */}
<div className="flex items-center justify-between p-5 border-b border-black/5">
<h3 className="font-semibold text-lg text-teal-700">Afspraak verzetten</h3>
<Button variant="ghost" size="icon" onClick={onClose} className="h-9 w-9 hover:bg-black/5 rounded-full">
<X className="h-5 w-5" />
</Button>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="flex-1 p-5 overflow-y-auto space-y-6">
{/* Info Card */}
<div className="bg-blue-50/70 border border-blue-100/50 rounded-xl p-5 shadow-sm">
{encounter && <h4 className="font-semibold text-blue-900 mb-3 text-lg">{encounter.title}</h4>}
<div className="flex items-center gap-3 text-sm text-blue-800/60 decoration-slate-400 mb-2">
<Calendar className="h-4 w-4" />
<span className="line-through decoration-blue-900/30">{currentStr}</span>
</div>
<div className="pl-0.5 my-2">
<div className="h-6 border-l-2 border-blue-200 ml-2 border-dashed"></div>
<ArrowRight className="h-5 w-5 text-blue-500 my-1" />
<div className="h-2 border-l-2 border-blue-200 ml-2 border-dashed"></div>
</div>
<div className="flex items-center gap-3 text-base font-bold text-blue-800 bg-blue-100/50 p-3 rounded-lg border border-blue-200/50">
<Calendar className="h-5 w-5" />
<span>
{date && time ? format(new Date(`${date}T${time}`), 'd MMMM yyyy HH:mm', { locale: nl }) : '...'}
</span>
</div>
</div>
{error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-xl flex items-center gap-3 text-sm text-red-700">
<AlertCircle className="h-5 w-5 shrink-0" />
{error}
</div>
)}
<div className="space-y-5">
<div className="space-y-2">
<Label htmlFor="date" className="text-sm font-medium text-gray-700">Nieuwe datum</Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Calendar className="h-4 w-4" />
</div>
<Input
id="date"
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="time" className="text-sm font-medium text-gray-700">Nieuwe tijd</Label>
<div className="relative">
<div className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">
<Clock className="h-4 w-4" />
</div>
<Input
id="time"
type="time"
value={time}
onChange={(e) => setTime(e.target.value)}
className="pl-10 h-10 bg-white/50 backdrop-blur-sm border-black/10 focus:bg-white transition-colors"
required
/>
</div>
</div>
</div>
</form>
{/* Footer */}
<div className="p-5 bg-gray-50/80 backdrop-blur-sm border-t border-black/5 flex justify-between gap-3">
<Button variant="outline" type="button" onClick={onClose} disabled={isSubmitting} className="flex-1 border-black/10 bg-white/50 hover:bg-white h-10 rounded-lg">
Annuleren
</Button>
<Button
type="button"
onClick={handleSubmit}
disabled={isSubmitting}
className="flex-1 bg-teal-600 hover:bg-teal-700 text-white shadow-md hover:shadow-lg h-10 rounded-lg"
>
{isSubmitting ? 'Verplaatsen...' : 'Bevestig wijziging'}
</Button>
</div>
</motion.div>
);
}

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>
);
}

View File

@@ -0,0 +1,184 @@
'use client';
/**
* Chat Input Component (v3.0)
*
* Text input onderaan chat panel met Enter to submit en Shift+Enter voor nieuwe regel.
*
* Epic: E2 (Chat Panel & Messages)
* Story: E2.S4 (ChatInput component)
*/
import { useState, useRef, KeyboardEvent, ChangeEvent, forwardRef, useImperativeHandle } from 'react';
import { Send, Mic } from 'lucide-react';
import { useCortexStore } from '@/stores/cortex-store';
import { cn } from '@/lib/utils';
interface ChatInputProps {
placeholder?: string;
onSend?: (message: string) => void;
disabled?: boolean;
}
export interface ChatInputHandle {
focus: () => void;
clear: () => void;
}
export const ChatInput = forwardRef<ChatInputHandle, ChatInputProps>(function ChatInput({
placeholder = 'Typ of spreek wat je wilt doen...',
onSend,
disabled = false,
}, ref) {
const [inputValue, setInputValue] = useState('');
const textareaRef = useRef<HTMLTextAreaElement>(null);
const addChatMessage = useCortexStore((s) => s.addChatMessage);
// Expose focus and clear methods to parent
useImperativeHandle(ref, () => ({
focus: () => {
textareaRef.current?.focus();
},
clear: () => {
setInputValue('');
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
},
}));
// Handle input change and auto-resize
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
setInputValue(e.target.value);
// Auto-resize textarea
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
}
};
// Handle submit
const handleSubmit = () => {
const trimmedValue = inputValue.trim();
if (!trimmedValue || disabled) return;
// Add user message to store
addChatMessage({
type: 'user',
content: trimmedValue,
});
// Call optional onSend callback
onSend?.(trimmedValue);
// Clear input
setInputValue('');
// Reset textarea height
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
// Focus back on textarea
textareaRef.current?.focus();
};
// Handle keyboard shortcuts
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
// Enter to submit (unless Shift is pressed)
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit();
}
// Escape to clear input
if (e.key === 'Escape') {
e.preventDefault();
setInputValue('');
if (textareaRef.current) {
textareaRef.current.style.height = 'auto';
}
}
// Shift+Enter for new line (default behavior, no need to handle)
};
return (
<div className="border-t border-slate-200 p-4 bg-white">
<div className="relative flex items-end gap-2">
{/* Textarea input */}
<textarea
ref={textareaRef}
value={inputValue}
onChange={handleChange}
onKeyDown={handleKeyDown}
placeholder={placeholder}
disabled={disabled}
rows={1}
className={cn(
'flex-1 px-4 py-3 pr-12',
'rounded-lg border border-slate-300',
'focus:border-brand-600 focus:ring-2 focus:ring-brand-600/20',
'outline-none resize-none',
'text-slate-900 placeholder:text-slate-400',
'max-h-32 overflow-y-auto',
'transition-colors',
disabled && 'opacity-50 cursor-not-allowed'
)}
style={{ minHeight: '48px' }}
/>
{/* Voice input button (placeholder for now) */}
<button
type="button"
className={cn(
'absolute right-12 bottom-3',
'text-slate-400 hover:text-slate-600',
'transition-colors p-1.5 rounded-md hover:bg-slate-100',
disabled && 'opacity-50 cursor-not-allowed'
)}
disabled={disabled}
aria-label="Spraak invoer"
title="Spraak invoer (komt in E5.S3)"
>
<Mic className="w-5 h-5" />
</button>
{/* Send button */}
<button
type="button"
onClick={handleSubmit}
disabled={disabled || !inputValue.trim()}
className={cn(
'absolute right-3 bottom-3',
'text-brand-600 hover:text-brand-700',
'transition-all p-1.5 rounded-md',
'hover:bg-brand-50 active:scale-95',
(!inputValue.trim() || disabled) && 'opacity-30 cursor-not-allowed'
)}
aria-label="Verstuur bericht"
title="Verstuur (Enter)"
>
<Send className="w-5 h-5" />
</button>
</div>
{/* Helper text */}
<p className="text-xs text-slate-400 mt-2">
<kbd className="px-1.5 py-0.5 bg-slate-100 border border-slate-300 rounded text-xs">
K
</kbd>{' '}
focus {' '}
<kbd className="px-1.5 py-0.5 bg-slate-100 border border-slate-300 rounded text-xs">
Esc
</kbd>{' '}
clear {' '}
<kbd className="px-1.5 py-0.5 bg-slate-100 border border-slate-300 rounded text-xs">
Enter
</kbd>{' '}
versturen
</p>
</div>
);
});

View File

@@ -0,0 +1,99 @@
'use client';
/**
* Chat Message Component (v3.0)
*
* Displays individual chat messages with styling per message type.
* Supports user, assistant, system, and error message types.
*
* Epic: E2 (Chat Panel & Messages)
* Story: E2.S2 (ChatMessage component)
*/
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { CheckCircle2, Sparkles } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { ChatMessage as ChatMessageType } from '@/stores/cortex-store';
import { getConfidenceLabel } from '@/lib/cortex/action-parser';
// Message styling configuration per type
const MESSAGE_STYLES = {
user: {
container: 'self-end bg-amber-50 border-amber-200 text-slate-900',
borderRadius: 'rounded-2xl rounded-tr-sm',
maxWidth: 'max-w-[80%]',
},
assistant: {
container: 'self-start bg-slate-100 border-slate-200 text-slate-900',
borderRadius: 'rounded-2xl rounded-tl-sm',
maxWidth: 'max-w-[85%]',
},
system: {
container: 'self-center bg-transparent border-transparent text-slate-500 text-sm italic',
borderRadius: 'rounded-lg',
maxWidth: 'max-w-[90%]',
},
error: {
container: 'self-start bg-red-50 border-red-200 text-red-900',
borderRadius: 'rounded-2xl',
maxWidth: 'max-w-[80%]',
},
} as const;
interface ChatMessageProps {
message: ChatMessageType;
showTimestamp?: boolean;
}
export function ChatMessage({ message, showTimestamp = false }: ChatMessageProps) {
const styles = MESSAGE_STYLES[message.type];
// Don't show border for system messages
const showBorder = message.type !== 'system';
return (
<div
className={cn(
'flex flex-col px-4 py-2.5 border transition-all',
styles.container,
styles.borderRadius,
styles.maxWidth,
!showBorder && 'border-none px-0 py-1'
)}
>
{/* Message content */}
<div className="whitespace-pre-wrap break-words leading-relaxed">
{message.content}
</div>
{/* Action badge (E3.S4) - show if action was detected */}
{message.action && message.type === 'assistant' && (
<div className="mt-2 pt-2 border-t border-slate-200">
<div className="flex items-center gap-2 text-xs">
<Sparkles className="w-3.5 h-3.5 text-amber-600" />
<span className="font-medium text-slate-700">
{message.action.intent === 'dagnotitie' && 'Dagnotitie'}
{message.action.intent === 'zoeken' && 'Patiënt zoeken'}
{message.action.intent === 'overdracht' && 'Overdracht'}
{message.action.intent === 'unknown' && 'Onbekend'}
</span>
{message.action.confidence >= 0.7 && (
<CheckCircle2 className="w-3.5 h-3.5 text-green-600" />
)}
<span className="text-slate-500">
{getConfidenceLabel(message.action.confidence)}
</span>
</div>
</div>
)}
{/* Timestamp (optional) */}
{showTimestamp && message.timestamp && (
<div className="text-xs text-slate-400 mt-1.5">
{format(message.timestamp, 'HH:mm', { locale: nl })}
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,215 @@
'use client';
/**
* Chat Panel (v3.0)
*
* Chat interface met scrollable message list, auto-scroll, en scroll-lock detection.
*
* Epic: E2 (Chat Panel & Messages)
* Story: E2.S3 (ChatPanel component - scrolling)
*/
import { useRef, useEffect, useState, useCallback } from 'react';
import { ArrowDown } from 'lucide-react';
import { ChatMessage } from './chat-message';
import { ChatInput, ChatInputHandle } from './chat-input';
import { useCortexStore } from '@/stores/cortex-store';
import { sendChatMessage } from '@/lib/cortex/chat-api';
import { parseActionFromResponse, shouldOpenArtifact } from '@/lib/cortex/action-parser';
import { cn } from '@/lib/utils';
export function ChatPanel() {
const chatMessages = useCortexStore((s) => s.chatMessages);
const addChatMessage = useCortexStore((s) => s.addChatMessage);
const updateLastMessage = useCortexStore((s) => s.updateLastMessage);
const setStreaming = useCortexStore((s) => s.setStreaming);
const isStreaming = useCortexStore((s) => s.isStreaming);
const setPendingAction = useCortexStore((s) => s.setPendingAction);
const activePatient = useCortexStore((s) => s.activePatient);
const shift = useCortexStore((s) => s.shift);
// Refs for scrolling
const scrollContainerRef = useRef<HTMLDivElement>(null);
const messagesEndRef = useRef<HTMLDivElement>(null);
// Ref for chat input (for keyboard shortcuts)
const chatInputRef = useRef<ChatInputHandle>(null);
// Scroll-lock state
const [isScrolledUp, setIsScrolledUp] = useState(false);
const [showScrollButton, setShowScrollButton] = useState(false);
const hasMessages = chatMessages.length > 0;
// Scroll to bottom function
const scrollToBottom = useCallback((behavior: ScrollBehavior = 'smooth') => {
messagesEndRef.current?.scrollIntoView({ behavior });
setIsScrolledUp(false);
setShowScrollButton(false);
}, []);
// Detect scroll position (scroll-lock detection)
const handleScroll = useCallback(() => {
if (!scrollContainerRef.current) return;
const { scrollTop, scrollHeight, clientHeight } = scrollContainerRef.current;
const isNearBottom = scrollHeight - scrollTop - clientHeight < 100; // 100px threshold
setIsScrolledUp(!isNearBottom);
// Show scroll button only if scrolled up AND there are messages
setShowScrollButton(!isNearBottom && hasMessages);
}, [hasMessages]);
// Auto-scroll to latest message when new message arrives (unless user scrolled up)
useEffect(() => {
if (!isScrolledUp && hasMessages) {
scrollToBottom('smooth');
}
}, [chatMessages.length, isScrolledUp, hasMessages, scrollToBottom]);
// Initial scroll to bottom on mount
useEffect(() => {
scrollToBottom('auto');
}, [scrollToBottom]);
// Global keyboard shortcuts
useEffect(() => {
const handleGlobalKeyDown = (e: KeyboardEvent) => {
// ⌘K or Ctrl+K to focus chat input
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
chatInputRef.current?.focus();
}
};
window.addEventListener('keydown', handleGlobalKeyDown);
return () => window.removeEventListener('keydown', handleGlobalKeyDown);
}, []);
return (
<div className="h-full flex flex-col bg-white">
{/* Chat messages area - scrollable */}
<div
ref={scrollContainerRef}
onScroll={handleScroll}
className="flex-1 overflow-y-auto p-6 relative"
>
{hasMessages ? (
<div className="flex flex-col space-y-3">
{chatMessages.map((message) => (
<ChatMessage key={message.id} message={message} showTimestamp />
))}
{/* Invisible element to scroll to */}
<div ref={messagesEndRef} />
</div>
) : (
<div className="flex items-center justify-center h-full">
<div className="max-w-md text-center text-slate-500">
<div className="text-4xl mb-4">💬</div>
<h3 className="text-lg font-medium text-slate-700 mb-2">
Welkom bij Cortex Assistent
</h3>
<p className="text-sm mb-4">
Typ of spreek wat je wilt doen...
</p>
<div className="text-left text-sm space-y-1 bg-slate-50 rounded-lg p-4">
<p className="font-medium text-slate-700 mb-2">Voorbeelden:</p>
<p> &ldquo;Notitie voor Jan: medicatie gegeven&rdquo;</p>
<p> &ldquo;Zoek Marie van den Berg&rdquo;</p>
<p> &ldquo;Maak overdracht voor deze dienst&rdquo;</p>
</div>
</div>
</div>
)}
{/* Scroll to bottom button */}
{showScrollButton && (
<button
onClick={() => scrollToBottom('smooth')}
className={cn(
'absolute bottom-4 right-4 z-10',
'bg-white border border-slate-300 rounded-full p-2',
'shadow-lg hover:shadow-xl',
'transition-all duration-200',
'hover:bg-slate-50 active:scale-95',
'flex items-center gap-2 text-sm text-slate-700 font-medium px-3 py-2'
)}
aria-label="Scroll naar laatste bericht"
>
<ArrowDown className="w-4 h-4" />
<span>Scroll naar beneden</span>
</button>
)}
</div>
{/* Chat input */}
<ChatInput
ref={chatInputRef}
disabled={isStreaming}
onSend={async (message) => {
// E3.S1: Test streaming API with mock response
setStreaming(true);
// Add empty assistant message that will be filled by streaming
addChatMessage({
type: 'assistant',
content: '',
});
let accumulatedContent = '';
await sendChatMessage(
message,
chatMessages,
{
activePatient: activePatient ? {
id: activePatient.id,
first_name: activePatient.name_given?.[0] || '',
last_name: activePatient.name_family || '',
} : null,
shift,
},
(chunk) => {
// On each chunk, append to accumulated content and update last message
accumulatedContent += chunk;
updateLastMessage(accumulatedContent);
},
() => {
// On done - parse action from complete response
setStreaming(false);
// E3.S4: Parse action object from AI response
const parsed = parseActionFromResponse(accumulatedContent);
if (parsed.action) {
console.log('[ChatPanel] Action detected:', parsed.action);
// Update last message with cleaned text content and action
updateLastMessage(parsed.textContent, parsed.action);
// Store action in pendingAction for artifact opening (E3.S6)
if (shouldOpenArtifact(parsed.action.confidence)) {
setPendingAction(parsed.action);
console.log('[ChatPanel] Pending action set (confidence:', parsed.action.confidence, ')');
} else {
console.log('[ChatPanel] Action confidence too low:', parsed.action.confidence);
}
} else {
console.log('[ChatPanel] No action detected in response');
}
},
(error) => {
// On error
setStreaming(false);
addChatMessage({
type: 'error',
content: `Er ging iets mis: ${error}`,
});
}
);
}}
/>
</div>
);
}

View File

@@ -0,0 +1,146 @@
'use client';
/**
* Canvas Area
*
* Central area where blocks appear. Shows empty state when no block is active.
*/
import { AnimatePresence, motion } from 'framer-motion';
import { useCortexStore } from '@/stores/cortex-store';
import type { BlockType, BlockPrefillData } from '@/stores/cortex-store';
import { DagnotatieBlock } from '../blocks/dagnotitie-block';
import { ZoekenBlock } from '../blocks/zoeken-block';
import { OverdrachtBlock } from '../blocks/overdracht-block';
import { PatientContextCard } from '../blocks/patient-context-card';
import { FallbackPicker } from '../blocks/fallback-picker';
export function CanvasArea() {
const { activeBlock, prefillData, activePatient } = useCortexStore();
function renderBlock(blockType: BlockType, prefill: BlockPrefillData) {
switch (blockType) {
case 'dagnotitie':
return <DagnotatieBlock prefill={prefill} />;
case 'zoeken':
return <ZoekenBlock prefill={prefill} />;
case 'overdracht':
return <OverdrachtBlock prefill={prefill} />;
case 'fallback':
return <FallbackPicker originalInput={prefill.content} />;
default:
return null;
}
}
// Block animations volgens UX specificatie (sectie 11.1):
// Openen: Slide up + fade in (200ms), Scale: 0.95 → 1.0
// Sluiten: Slide down + fade out (200ms), Scale: 1.0 → 0.95
const blockAnimations = {
initial: { opacity: 0, y: 20, scale: 0.95 },
animate: {
opacity: 1,
y: 0,
scale: 1,
transition: {
duration: 0.2,
ease: [0.4, 0, 0.2, 1] as [number, number, number, number],
},
},
exit: {
opacity: 0,
y: 20, // Slide down (niet omhoog)
scale: 0.95,
transition: {
duration: 0.2,
ease: [0.4, 0, 0.2, 1] as [number, number, number, number],
},
},
};
return (
<main className="flex-1 flex items-center justify-center p-4 overflow-auto">
<AnimatePresence mode="wait" initial={false}>
{activeBlock ? (
<motion.div
key={activeBlock}
initial={blockAnimations.initial}
animate={blockAnimations.animate}
exit={blockAnimations.exit}
>
{renderBlock(activeBlock, prefillData)}
</motion.div>
) : activePatient ? (
<motion.div
key="patient-context"
initial={blockAnimations.initial}
animate={blockAnimations.animate}
exit={blockAnimations.exit}
>
<PatientContextCard />
</motion.div>
) : (
<motion.div
key="empty"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
>
<EmptyState />
</motion.div>
)}
</AnimatePresence>
</main>
);
}
function EmptyState() {
return (
<div className="text-center max-w-md">
<div className="mb-6">
<div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-white border border-slate-200 shadow-sm flex items-center justify-center">
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="1.5"
strokeLinecap="round"
strokeLinejoin="round"
className="text-slate-400"
>
<path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" />
<path d="M19 10v2a7 7 0 0 1-14 0v-2" />
<line x1="12" x2="12" y1="19" y2="22" />
</svg>
</div>
<h2 className="text-xl font-medium text-slate-700 mb-2">Wat wil je doen?</h2>
<p className="text-sm text-slate-500">
Typ of spreek je intentie
</p>
</div>
<div className="space-y-2 text-left">
<ExampleCommand icon="📝" text="notitie jan medicatie gegeven" />
<ExampleCommand icon="🔍" text="zoek marie" />
<ExampleCommand icon="📋" text="overdracht" />
</div>
<p className="mt-6 text-xs text-slate-500">
<kbd className="px-1.5 py-0.5 rounded bg-white border border-slate-200 text-slate-600 shadow-sm">K</kbd> om te focussen
</p>
</div>
);
}
function ExampleCommand({ icon, text }: { icon: string; text: string }) {
return (
<div className="flex items-center gap-3 px-3 py-2 rounded-lg bg-white border border-slate-200 shadow-sm text-sm">
<span>{icon}</span>
<span className="text-slate-600">&quot;{text}&quot;</span>
</div>
);
}

View File

@@ -0,0 +1,123 @@
'use client';
/**
* Command Center (v3.0)
*
* Main container for the Cortex interface.
* Split-screen layout: Chat Panel (40%) | Artifact Area (60%)
*
* Layout specs:
* - Context Bar: 48px (h-12) - UNCHANGED
* - Split container: flex-1 (fills remaining space)
* - Chat Panel: 40% width (desktop), 100% (mobile)
* - Artifact Area: 60% width (desktop), 100% (mobile)
*
* Epic: E1 (Foundation)
* Stories: E1.S2 (Split-screen layout), E1.S3 (Placeholders), E1.S4 (Responsive)
*/
import { useEffect, useCallback, useRef } from 'react';
import { useCortexStore } from '@/stores/cortex-store';
import { ContextBar } from './context-bar';
import { OfflineBanner } from './offline-banner';
import { ChatPanel } from '../chat/chat-panel';
import { ArtifactArea } from '../artifacts/artifact-area';
import { getArtifactTitle } from '../artifacts/artifact-container';
import { routeIntentToArtifact } from '@/lib/cortex/action-parser';
export function CommandCenter() {
const { closeAllArtifacts, openArtifacts, openArtifact, pendingAction, setPendingAction } = useCortexStore();
const inputRef = useRef<HTMLInputElement>(null);
// Global keyboard shortcuts
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
// Escape: close all artifacts
if (e.key === 'Escape' && openArtifacts.length > 0) {
e.preventDefault();
closeAllArtifacts();
}
// Cmd/Ctrl + K: focus input (chat input in v3.0)
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
inputRef.current?.focus();
}
},
[openArtifacts, closeAllArtifacts]
);
useEffect(() => {
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleKeyDown]);
// E3.S6 + E4.S2: Handle pending actions from chat (artifact opening)
useEffect(() => {
if (!pendingAction) return;
console.log('[CommandCenter] Processing pending action:', pendingAction);
// Check if action has artifact data
if (pendingAction.artifact) {
const { type, prefill } = pendingAction.artifact;
// Generate title for the artifact
const title = getArtifactTitle(type, prefill);
console.log('[CommandCenter] Opening artifact:', type, title);
// Open the artifact (E4.S2 - new artifact system)
openArtifact({
type,
prefill,
title,
});
setPendingAction(null);
return;
}
const routedArtifact = routeIntentToArtifact(
pendingAction.intent,
pendingAction.entities,
pendingAction.confidence
);
if (routedArtifact) {
console.log('[CommandCenter] Routing action to artifact:', routedArtifact.type);
openArtifact({
type: routedArtifact.type,
prefill: routedArtifact.prefill,
title: routedArtifact.title,
});
} else {
console.log('[CommandCenter] Action has no artifact, skipping');
}
setPendingAction(null);
}, [pendingAction, openArtifact, setPendingAction]);
return (
<div className="flex flex-col h-screen overflow-hidden">
{/* Offline Banner */}
<OfflineBanner />
{/* Context Bar - 48px (unchanged) */}
<ContextBar />
{/* Split-screen container - flex-1 */}
<div className="flex-1 flex overflow-hidden">
{/* Chat Panel - 40% (desktop), 100% (mobile) */}
<div className="w-full lg:w-[40%] border-r border-slate-200 flex flex-col">
<ChatPanel />
</div>
{/* Artifact Area - 60% (desktop), hidden on mobile */}
<div className="hidden lg:flex lg:w-[60%] flex-col">
<ArtifactArea />
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,315 @@
'use client';
/**
* Command Input
*
* Bottom input bar for text and voice commands.
* Height: 64px (h-16)
*
* Features:
* - Text input with dynamic placeholder
* - Focus state with ring
* - Send button (appears when input has value)
* - Voice input with Deepgram streaming
* - ⌘K shortcut hint
*/
import { forwardRef, useState, useEffect, useRef } from 'react';
import { useCortexStore } from '@/stores/cortex-store';
import { useCortexVoice } from '@/lib/cortex/use-cortex-voice';
import type { BlockType } from '@/lib/cortex/types';
import { Mic, MicOff, Send, Loader2 } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
import { safeFetch, getErrorInfo } from '@/lib/cortex/error-handler';
import { routeIntentToArtifact } from '@/lib/cortex/action-parser';
export const CommandInput = forwardRef<HTMLInputElement>(function CommandInput(_, ref) {
const {
inputValue,
setInputValue,
clearInput,
activePatient,
activeBlock,
isVoiceActive,
openBlock,
openArtifact,
addRecentAction,
} = useCortexStore();
const { toast } = useToast();
const {
isRecording,
isConnecting,
isConnected,
error: voiceError,
startRecording,
stopRecording,
analyserNode,
isBrowserSupported,
} = useCortexVoice();
const [isProcessing, setIsProcessing] = useState(false);
const waveformRef = useRef<HTMLCanvasElement>(null);
const animationRef = useRef<number | null>(null);
const hasValue = inputValue.trim().length > 0;
// Waveform visualization
useEffect(() => {
if (!analyserNode || !waveformRef.current || !isRecording) {
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
return;
}
const canvas = waveformRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const bufferLength = analyserNode.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
const draw = () => {
if (!isRecording) return;
animationRef.current = requestAnimationFrame(draw);
analyserNode.getByteFrequencyData(dataArray);
ctx.fillStyle = 'rgb(248, 250, 252)'; // slate-50
ctx.fillRect(0, 0, canvas.width, canvas.height);
const barWidth = (canvas.width / bufferLength) * 2.5;
let x = 0;
for (let i = 0; i < bufferLength; i++) {
const barHeight = (dataArray[i] / 255) * canvas.height;
// Gradient from blue to red based on amplitude
const hue = 220 - (dataArray[i] / 255) * 40;
ctx.fillStyle = `hsl(${hue}, 70%, 60%)`;
ctx.fillRect(x, canvas.height - barHeight, barWidth, barHeight);
x += barWidth + 1;
}
};
draw();
return () => {
if (animationRef.current) {
cancelAnimationFrame(animationRef.current);
}
};
}, [analyserNode, isRecording]);
// Dynamic placeholder based on context
const getPlaceholder = () => {
if (isRecording) return 'Luisteren...';
if (isConnecting) return 'Verbinden met spraakherkenning...';
if (activePatient) {
return `Actie voor ${activePatient.name_given[0]}... (bijv. "notitie medicatie")`;
}
return 'Typ of spreek je intentie... (bijv. "notitie jan medicatie")';
};
const handleSubmit = async (e?: React.FormEvent) => {
e?.preventDefault();
if (!hasValue || isProcessing) return;
// Stop recording if active
if (isRecording) {
stopRecording();
}
const inputText = inputValue.trim();
setIsProcessing(true);
try {
// Call intent classification API
const response = await safeFetch(
'/api/intent/classify',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: inputText }),
},
{ operation: 'Intent classificeren' }
);
const result = await response.json();
const { intent, confidence, entities } = result;
// Route intent to artifact using Epic 5.S1 routing logic
const artifactConfig = routeIntentToArtifact(intent, entities, confidence);
if (artifactConfig) {
// Open artifact with routing configuration
openArtifact({
type: artifactConfig.type,
title: artifactConfig.title,
prefill: artifactConfig.prefill,
});
// Add to recent actions
addRecentAction({
intent,
label: inputText.slice(0, 50), // Truncate for display
patientName: entities.patientName,
});
clearInput();
} else {
// Low confidence or missing required entities - show FallbackPicker
openBlock('fallback', { content: inputText });
clearInput();
}
} catch (error) {
console.error('Error processing intent:', error);
const statusCode = (error as any)?.statusCode;
const errorInfo = getErrorInfo(error, {
operation: 'Intent classificeren',
statusCode,
});
// Show error toast
toast({
variant: 'destructive',
title: errorInfo.title,
description: errorInfo.description,
});
// On error, show FallbackPicker so user can choose
// This ensures the user's input is not lost
openBlock('fallback', { content: inputText });
clearInput();
} finally {
setIsProcessing(false);
}
};
const handleVoiceToggle = () => {
if (isRecording) {
stopRecording();
} else {
startRecording();
}
};
// Keyboard shortcut: Cmd/Ctrl+Enter to submit
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
// Cmd/Ctrl+Enter: submit command
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
e.preventDefault();
handleSubmit();
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [handleSubmit]);
const isDisabled = isProcessing || activeBlock !== null;
return (
<footer className="h-16 border-t border-slate-200 flex items-center px-4 shrink-0 bg-white">
<form onSubmit={handleSubmit} className="flex-1 flex items-center gap-2">
{/* Input wrapper with optional waveform */}
<div className="relative flex-1">
{/* Waveform canvas (shown when recording) */}
{isRecording && (
<canvas
ref={waveformRef}
width={200}
height={40}
className="absolute left-2 top-1/2 -translate-y-1/2 rounded opacity-60"
/>
)}
<input
ref={ref}
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder={getPlaceholder()}
disabled={isDisabled}
className={`w-full bg-white border rounded-xl py-3 text-slate-900 placeholder:text-slate-400
focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500
disabled:opacity-50 disabled:cursor-not-allowed
transition-all duration-200
${isRecording ? 'pl-[220px] pr-12 border-red-500/50' : 'pl-4 pr-12 border-slate-300'}`}
autoFocus
/>
{/* Status indicators */}
{!hasValue && !isRecording && !isConnecting && (
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-slate-600 pointer-events-none hidden sm:block">
K
</span>
)}
{isConnecting && (
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-amber-500 flex items-center gap-1">
<Loader2 size={12} className="animate-spin" />
Verbinden
</span>
)}
{voiceError && (
<span className="absolute right-3 top-1/2 -translate-y-1/2 text-xs text-red-400 max-w-[150px] truncate">
{voiceError}
</span>
)}
</div>
{/* Send button - appears when has value */}
{hasValue && (
<button
type="submit"
disabled={isProcessing}
className="p-3 rounded-xl bg-blue-600 hover:bg-blue-500 text-white transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
title="Verstuur (Enter)"
>
{isProcessing ? (
<Loader2 size={20} className="animate-spin" />
) : (
<Send size={20} />
)}
</button>
)}
{/* Voice button */}
{isBrowserSupported ? (
<button
type="button"
onClick={handleVoiceToggle}
disabled={isDisabled || isConnecting}
className={`p-3 rounded-xl transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed ${
isRecording
? 'bg-red-600 hover:bg-red-500 text-white ring-4 ring-red-600/30'
: 'bg-slate-100 hover:bg-slate-200 text-slate-600'
}`}
title={isRecording ? 'Stop opname' : 'Start voice input'}
>
{isConnecting ? (
<Loader2 size={20} className="animate-spin" />
) : isRecording ? (
<MicOff size={20} />
) : (
<Mic size={20} />
)}
</button>
) : (
<button
type="button"
disabled
className="p-3 rounded-xl bg-slate-100 text-slate-400 cursor-not-allowed"
title="Spraakherkenning niet ondersteund in deze browser"
>
<MicOff size={20} />
</button>
)}
</form>
</footer>
);
});

View File

@@ -0,0 +1,85 @@
'use client';
/**
* Context Bar
*
* Top bar showing current context: shift, selected patient, user info.
* Height: 48px (h-12)
*/
import { useCortexStore, type ShiftType } from '@/stores/cortex-store';
import { Sun, Moon, Sunrise, Sunset, X, User, ArrowLeft } from 'lucide-react';
import Link from 'next/link';
import { useOffline } from './offline-banner';
const SHIFT_CONFIG: Record<ShiftType, { icon: typeof Sun; label: string; color: string }> = {
nacht: { icon: Moon, label: 'Nachtdienst', color: 'text-indigo-600' },
ochtend: { icon: Sunrise, label: 'Ochtenddienst', color: 'text-amber-600' },
middag: { icon: Sun, label: 'Middagdienst', color: 'text-yellow-600' },
avond: { icon: Sunset, label: 'Avonddienst', color: 'text-orange-600' },
};
export function ContextBar() {
const { shift, activePatient, setActivePatient } = useCortexStore();
const isOffline = useOffline();
const shiftConfig = SHIFT_CONFIG[shift];
const ShiftIcon = shiftConfig.icon;
return (
<header
className="h-12 border-b border-slate-200 flex items-center px-4 justify-between shrink-0 bg-white"
style={isOffline ? { marginTop: '40px' } : undefined}
>
{/* Left: Logo + Shift */}
<div className="flex items-center gap-4">
<Link
href="/epd/clients"
className="flex items-center gap-2 text-slate-600 hover:text-slate-900 transition-colors"
title="Terug naar EPD"
>
<ArrowLeft size={16} />
<span className="text-sm font-semibold tracking-tight">Terug naar EPD</span>
</Link>
<div className="h-4 w-px bg-slate-200" />
<div className={`flex items-center gap-1.5 ${shiftConfig.color}`}>
<ShiftIcon size={14} />
<span className="text-xs font-medium">{shiftConfig.label}</span>
</div>
</div>
{/* Center: Active Patient */}
<div className="flex items-center">
{activePatient ? (
<div className="flex items-center gap-2 px-3 py-1 rounded-full bg-slate-100 border border-slate-300">
<div className="w-5 h-5 rounded-full bg-blue-600 flex items-center justify-center text-[10px] font-medium text-white">
{activePatient.name_given[0]?.[0]}
{activePatient.name_family[0]}
</div>
<span className="text-sm text-slate-900">
{activePatient.name_given.join(' ')} {activePatient.name_family}
</span>
<button
onClick={() => setActivePatient(null)}
className="p-0.5 rounded hover:bg-slate-200 text-slate-400 hover:text-slate-700 transition-colors"
title="Patiënt deselecteren"
>
<X size={14} />
</button>
</div>
) : (
<span className="text-sm text-slate-500">Geen patiënt geselecteerd</span>
)}
</div>
{/* Right: User */}
<div className="flex items-center gap-3">
<div className="flex items-center gap-2 text-slate-600">
<User size={16} />
<span className="text-xs hidden sm:block">Verpleegkundige</span>
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,9 @@
/**
* Command Center Barrel Export
*/
export { CommandCenter } from './command-center';
export { CommandInput } from './command-input';
export { ContextBar } from './context-bar';
export { CanvasArea } from './canvas-area';
export { RecentStrip } from './recent-strip';

View File

@@ -0,0 +1,71 @@
'use client';
/**
* Offline Banner
*
* Toont een banner wanneer de gebruiker offline is.
* E5.S2: Offline detection en melding.
*/
import { useState, useEffect } from 'react';
import { WifiOff } from 'lucide-react';
import { cn } from '@/lib/utils';
export function OfflineBanner() {
const [isOffline, setIsOffline] = useState(false);
useEffect(() => {
// Initial check
setIsOffline(!navigator.onLine);
// Listen for online/offline events
const handleOnline = () => setIsOffline(false);
const handleOffline = () => setIsOffline(true);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
if (!isOffline) return null;
return (
<div
className={cn(
'fixed top-0 left-0 right-0 z-[100] bg-amber-500 text-white px-4 py-2',
'flex items-center justify-center gap-2 text-sm font-medium',
'shadow-md'
)}
style={{ height: '40px' }}
>
<WifiOff className="h-4 w-4" />
<span>Geen internetverbinding</span>
</div>
);
}
/**
* Hook om te checken of de gebruiker offline is
*/
export function useOffline() {
const [isOffline, setIsOffline] = useState(false);
useEffect(() => {
setIsOffline(!navigator.onLine);
const handleOnline = () => setIsOffline(false);
const handleOffline = () => setIsOffline(true);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOffline;
}

View File

@@ -0,0 +1,115 @@
'use client';
/**
* Recent Strip
*
* Shows last 5 actions as clickable chips for quick repeat.
* Height: 48px (h-12)
*/
import { useCortexStore, type CortexIntent } from '@/stores/cortex-store';
import { FileText, Search, ArrowRightLeft, HelpCircle, Clock, Calendar, Plus, X } from 'lucide-react';
const INTENT_CONFIG: Record<CortexIntent, { icon: typeof FileText; color: string; label: string }> = {
dagnotitie: { icon: FileText, color: 'text-blue-600 bg-blue-50 border border-blue-200', label: 'Notitie' },
zoeken: { icon: Search, color: 'text-emerald-600 bg-emerald-50 border border-emerald-200', label: 'Zoeken' },
overdracht: { icon: ArrowRightLeft, color: 'text-purple-600 bg-purple-50 border border-purple-200', label: 'Overdracht' },
agenda_query: { icon: Calendar, color: 'text-teal-600 bg-teal-50 border border-teal-200', label: 'Agenda' },
create_appointment: { icon: Plus, color: 'text-green-600 bg-green-50 border border-green-200', label: 'Afspraak' },
cancel_appointment: { icon: X, color: 'text-red-600 bg-red-50 border border-red-200', label: 'Annuleren' },
reschedule_appointment: { icon: Clock, color: 'text-amber-600 bg-amber-50 border border-amber-200', label: 'Verzetten' },
unknown: { icon: HelpCircle, color: 'text-slate-600 bg-slate-50 border border-slate-200', label: 'Actie' },
};
function formatRelativeTime(date: Date): string {
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 1) return 'zojuist';
if (diffMins < 60) return `${diffMins}m`;
const diffHours = Math.floor(diffMins / 60);
if (diffHours < 24) return `${diffHours}u`;
return `${Math.floor(diffHours / 24)}d`;
}
export function RecentStrip() {
const { recentActions, setInputValue, openBlock } = useCortexStore();
const handleActionClick = (action: typeof recentActions[0]) => {
// Set the input to repeat the action
setInputValue(action.label);
// If it's a known intent, open the block directly
if (action.intent !== 'unknown') {
openBlock(action.intent, {
patientName: action.patientName,
});
}
};
return (
<div className="h-12 border-t border-slate-200 flex items-center px-4 gap-3 shrink-0 bg-white">
{/* Label */}
<div className="flex items-center gap-1.5 text-slate-500 shrink-0">
<Clock size={12} />
<span className="text-xs font-medium">Recent</span>
</div>
{/* Divider */}
<div className="h-4 w-px bg-slate-200" />
{/* Actions */}
{recentActions.length === 0 ? (
<span className="text-xs text-slate-400 italic">Nog geen acties</span>
) : (
<div className="flex gap-2 overflow-x-auto scrollbar-hide">
{recentActions.map((action) => {
const config = INTENT_CONFIG[action.intent];
const Icon = config.icon;
return (
<button
key={action.id}
onClick={() => handleActionClick(action)}
className={`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium
whitespace-nowrap transition-all duration-200
hover:scale-105 active:scale-95
${config.color} hover:brightness-110`}
title={`Herhaal: ${action.label}${action.patientName ? ` (${action.patientName})` : ''}`}
>
<Icon size={12} />
<span className="max-w-[120px] truncate">{action.label}</span>
{action.patientName && (
<span className="text-[10px] opacity-60"> {action.patientName}</span>
)}
<span className="text-[10px] opacity-40 ml-1">
{formatRelativeTime(action.timestamp)}
</span>
</button>
);
})}
</div>
)}
{/* Quick actions hint (when empty) */}
{recentActions.length === 0 && (
<div className="ml-auto flex items-center gap-2 text-xs text-slate-500">
<span>Probeer:</span>
<button
onClick={() => setInputValue('notitie ')}
className="px-2 py-0.5 rounded bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors"
>
notitie
</button>
<button
onClick={() => setInputValue('zoek ')}
className="px-2 py-0.5 rounded bg-slate-100 hover:bg-slate-200 text-slate-600 transition-colors"
>
zoek
</button>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,6 @@
/**
* Cortex Components Barrel Export
*/
export * from './command-center';
export * from './blocks';

View File

@@ -0,0 +1,160 @@
'use client';
/**
* Linked Evidence Component
*
* Shows source data in a hover popover for overdracht aandachtspunten.
* E5.S2: Provides quick access to original source without leaving context.
*/
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import type { Aandachtspunt } from '@/lib/types/overdracht';
import { ExternalLink, Activity, FileText, AlertTriangle } from 'lucide-react';
import { cn } from '@/lib/utils';
interface LinkedEvidenceProps {
bron: Aandachtspunt['bron'];
sourceData?: Aandachtspunt['sourceData'];
className?: string;
}
export function LinkedEvidence({ bron, sourceData, className }: LinkedEvidenceProps) {
// If no source data, just show label without popover
if (!sourceData) {
return (
<span className={cn('inline-flex items-center gap-1 text-xs text-slate-500', className)}>
{bron.label} {bron.datum}
</span>
);
}
const getBronIcon = () => {
switch (bron.type) {
case 'observatie':
return <Activity className="h-3.5 w-3.5" />;
case 'rapportage':
case 'verpleegkundig':
return <FileText className="h-3.5 w-3.5" />;
case 'risico':
return <AlertTriangle className="h-3.5 w-3.5" />;
}
};
const getInterpretationColor = (code: string | undefined) => {
if (!code) return 'text-slate-600';
switch (code) {
case 'HH':
case 'LL':
return 'text-red-700 font-semibold';
case 'H':
case 'L':
return 'text-amber-700 font-medium';
case 'N':
return 'text-teal-700';
default:
return 'text-slate-600';
}
};
const getRiskLevelColor = (level: string | undefined) => {
if (!level) return 'text-slate-600';
switch (level.toLowerCase()) {
case 'zeer_hoog':
case 'hoog':
return 'text-red-700 font-semibold';
case 'gemiddeld':
return 'text-amber-700';
case 'laag':
return 'text-teal-700';
default:
return 'text-slate-600';
}
};
return (
<Popover>
<PopoverTrigger asChild>
<button
type="button"
className={cn(
'inline-flex items-center gap-1 text-xs text-slate-600 hover:text-slate-900',
'underline decoration-dotted underline-offset-2 cursor-help transition-colors',
className
)}
>
{getBronIcon()}
<span>{bron.label}</span>
<ExternalLink className="h-3 w-3 opacity-50" />
</button>
</PopoverTrigger>
<PopoverContent className="w-96 p-4" side="top" align="start">
<div className="space-y-3">
{/* Header */}
<div className="border-b border-slate-200 pb-2">
<div className="flex items-start justify-between gap-2">
<div className="flex items-center gap-2">
{getBronIcon()}
<div>
<div className="text-sm font-medium text-slate-900">{bron.label}</div>
<div className="text-xs text-slate-500">{bron.datum}</div>
</div>
</div>
</div>
</div>
{/* Content based on type */}
{bron.type === 'observatie' && sourceData.value && (
<div className="space-y-2">
<div className="flex items-baseline gap-2">
<span className="text-2xl font-semibold text-slate-900">
{sourceData.value}
</span>
{sourceData.unit && (
<span className="text-sm text-slate-600">{sourceData.unit}</span>
)}
</div>
{sourceData.interpretation && (
<div className={cn('text-sm', getInterpretationColor(sourceData.interpretation))}>
Interpretatie: {sourceData.interpretation}
{sourceData.interpretation === 'HH' && ' (Kritiek hoog)'}
{sourceData.interpretation === 'H' && ' (Hoog)'}
{sourceData.interpretation === 'LL' && ' (Kritiek laag)'}
{sourceData.interpretation === 'L' && ' (Laag)'}
{sourceData.interpretation === 'N' && ' (Normaal)'}
</div>
)}
</div>
)}
{(bron.type === 'rapportage' || bron.type === 'verpleegkundig') && sourceData.content && (
<div className="space-y-2">
<div className="text-sm text-slate-700 bg-slate-50 rounded p-3 border border-slate-200">
{sourceData.content}
</div>
{sourceData.createdBy && (
<div className="text-xs text-slate-500">
Door: {sourceData.createdBy}
</div>
)}
</div>
)}
{bron.type === 'risico' && (
<div className="space-y-2">
{sourceData.riskLevel && (
<div className={cn('text-sm font-medium', getRiskLevelColor(sourceData.riskLevel))}>
Risiconiveau: {sourceData.riskLevel.replace('_', ' ')}
</div>
)}
{sourceData.rationale && (
<div className="text-sm text-slate-700 bg-slate-50 rounded p-3 border border-slate-200">
{sourceData.rationale}
</div>
)}
</div>
)}
</div>
</PopoverContent>
</Popover>
);
}