feat: wrap rapportage split view and add qa plan

This commit is contained in:
colinislit
2025-11-23 21:46:07 +01:00
parent 371021d3c0
commit ce2e08449d
10 changed files with 1026 additions and 281 deletions

View File

@@ -6,12 +6,13 @@
*/
import { Mic } from 'lucide-react';
import { useRouter, usePathname } from 'next/navigation';
import type { FHIRPatient } from '@/lib/fhir';
import { Button } from '@/components/ui/button';
interface ClientHeaderProps {
patient: FHIRPatient;
onNewReport?: () => void;
focusElementId?: string;
}
// Status badge component
@@ -38,7 +39,23 @@ function StatusBadge({ status }: { status?: string }) {
);
}
export function ClientHeader({ patient, onNewReport }: ClientHeaderProps) {
export function ClientHeader({ patient, focusElementId = 'rapportage-composer' }: ClientHeaderProps) {
const router = useRouter();
const pathname = usePathname();
const handleNewReportClick = (patientId?: string) => {
if (!patientId) return;
const rapportagePath = `/epd/patients/${patientId}/rapportage`;
const onRapportagePage = pathname?.startsWith(rapportagePath);
if (onRapportagePage) {
handleScrollToComposer(focusElementId);
return;
}
const hash = focusElementId ? `#${focusElementId}` : '';
router.push(`${rapportagePath}${hash}`);
};
// Extract name
const name = patient.name?.[0];
const fullName = [
@@ -104,13 +121,20 @@ export function ClientHeader({ patient, onNewReport }: ClientHeaderProps) {
<div className="text-xs text-slate-400">
ID: {patient.id}
</div>
{onNewReport && (
<Button type="button" size="sm" onClick={onNewReport}>
<Mic className="mr-2 h-4 w-4" /> Nieuwe rapportage
</Button>
)}
<Button type="button" size="sm" onClick={() => handleNewReportClick(patient.id)}>
<Mic className="mr-2 h-4 w-4" /> Nieuwe rapportage
</Button>
</div>
</div>
</div>
);
}
function handleScrollToComposer(targetId?: string) {
if (!targetId) return;
const element = document.getElementById(targetId);
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'start' });
(element as HTMLElement).focus?.();
}
}

View File

@@ -0,0 +1,75 @@
'use server';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import { authFetch, getBaseUrl } from '@/lib/server/api-client';
import type { Report, ReportListResponse, CreateReportInput } from '@/lib/types/report';
export async function getReports(patientId: string): Promise<Report[]> {
const baseUrl = getBaseUrl();
const url = new URL('/api/reports', baseUrl);
url.searchParams.set('patientId', patientId);
const response = await authFetch(url.toString(), {
cache: 'no-store',
});
if (!response.ok) {
if (response.status === 401) {
redirect('/login');
}
throw new Error('Fout bij ophalen rapportages');
}
const data: ReportListResponse = await response.json();
return data.reports;
}
export async function createReport(
patientId: string,
input: Omit<CreateReportInput, 'patient_id'>
): Promise<Report> {
const baseUrl = getBaseUrl();
const url = `${baseUrl}/api/reports`;
const response = await authFetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
patient_id: patientId,
...input,
}),
});
if (!response.ok) {
if (response.status === 401) {
redirect('/login');
}
const error = await response.json().catch(() => ({}));
throw new Error(error.error || 'Opslaan mislukt');
}
revalidatePath(`/epd/patients/${patientId}/rapportage`);
return response.json();
}
export async function deleteReport(patientId: string, reportId: string) {
const baseUrl = getBaseUrl();
const url = `${baseUrl}/api/reports/${reportId}`;
const response = await authFetch(url, {
method: 'DELETE',
});
if (!response.ok) {
if (response.status === 401) {
redirect('/login');
}
throw new Error('Verwijderen mislukt');
}
revalidatePath(`/epd/patients/${patientId}/rapportage`);
return response.json();
}

View File

@@ -0,0 +1,324 @@
'use client';
import type { ReactNode } from 'react';
import { useMemo, useState, useEffect } from 'react';
import { Search, Filter, Sparkles, Timer } from 'lucide-react';
import type { Report } from '@/lib/types/report';
import { ReportTimeline } from './report-timeline';
import { ReportComposer } from './report-composer';
import { useMediaQuery } from '@/hooks/use-media-query';
interface RapportageWorkspaceProps {
patientId: string;
patientName: string;
initialReports: Report[];
}
const TYPE_LABELS: Record<string, string> = {
behandeladvies: 'Behandeladvies',
vrije_notitie: 'Vrije notitie',
};
export function RapportageWorkspace({ patientId, patientName, initialReports }: RapportageWorkspaceProps) {
const [reports, setReports] = useState(initialReports);
const [search, setSearch] = useState('');
const [typeFilter, setTypeFilter] = useState<'all' | keyof typeof TYPE_LABELS>('all');
const [selectedReportId, setSelectedReportId] = useState<string | null>(null);
const [authorFilter, setAuthorFilter] = useState<'all' | string>('all');
const [dateFrom, setDateFrom] = useState('');
const [dateTo, setDateTo] = useState('');
const [aiFilter, setAiFilter] = useState<'all' | 'ai' | 'manual'>('all');
const isMobile = useMediaQuery('(max-width: 1023px)');
const [activeTab, setActiveTab] = useState<'timeline' | 'composer'>('timeline');
useEffect(() => {
if (!isMobile) {
setActiveTab('timeline');
}
}, [isMobile]);
const authorOptions = useMemo(() => {
const unique = Array.from(new Set(reports.map((report) => report.created_by).filter(Boolean)));
return unique as string[];
}, [reports]);
const filteredReports = useMemo(() => {
return reports.filter((report) => {
const matchesType = typeFilter === 'all' || report.type === typeFilter;
const matchesSearch =
!search ||
report.content.toLowerCase().includes(search.toLowerCase()) ||
report.ai_reasoning?.toLowerCase().includes(search.toLowerCase());
const matchesAuthor = authorFilter === 'all' || report.created_by === authorFilter;
const createdAt = report.created_at ? new Date(report.created_at) : null;
const matchesFrom = !dateFrom || (createdAt && createdAt >= new Date(dateFrom));
const matchesTo = !dateTo || (createdAt && createdAt <= new Date(`${dateTo}T23:59:59`));
const matchesAI =
aiFilter === 'all' ||
(aiFilter === 'ai' ? report.ai_confidence !== null : report.ai_confidence === null);
return matchesType && matchesSearch && matchesAuthor && matchesFrom && matchesTo && matchesAI;
});
}, [reports, search, typeFilter, authorFilter, dateFrom, dateTo, aiFilter]);
const selectedReport = useMemo(
() => reports.find((report) => report.id === selectedReportId) ?? null,
[reports, selectedReportId]
);
const totalReports = reports.length;
const aiReports = reports.filter((report) => report.ai_confidence !== null).length;
const latestReport = reports[0];
const latestDate = latestReport?.created_at
? new Date(latestReport.created_at).toLocaleString('nl-NL')
: null;
const handleReportCreated = (report: Report) => {
setReports((prev) => [report, ...prev]);
setSelectedReportId(report.id);
};
const handleDeleteSuccess = (reportId: string) => {
setReports((prev) => prev.filter((report) => report.id !== reportId));
if (selectedReportId === reportId) {
setSelectedReportId(null);
}
};
const resetFilters = () => {
setSearch('');
setTypeFilter('all');
setAuthorFilter('all');
setDateFrom('');
setDateTo('');
setAiFilter('all');
};
return (
<div className="space-y-6 p-6">
<header>
<p className="text-sm uppercase tracking-wide text-slate-500">Universele rapportage</p>
<h1 className="text-2xl font-semibold text-slate-900">Tijdlijn en notities</h1>
<p className="mt-1 text-sm text-slate-600">
Alle behandeladviezen en vrije notities voor {patientName} op één plek.
</p>
</header>
<div className="grid gap-4 md:grid-cols-3">
<StatCard
icon={<Filter className="h-5 w-5" />}
label="Totaal rapportages"
value={totalReports.toString()}
helper={totalReports > 0 ? 'Inclusief AI-notities' : 'Nog geen rapportages'}
/>
<StatCard
icon={<Sparkles className="h-5 w-5" />}
label="AI classificaties"
value={aiReports.toString()}
helper="Aantal rapportages met AI-bijdrage"
/>
<StatCard
icon={<Timer className="h-5 w-5" />}
label="Laatste activiteit"
value={latestDate ?? '—'}
helper={latestDate ? 'Recentste rapportage' : 'Nog geen activiteit'}
/>
</div>
{isMobile && (
<div className="flex rounded-full border border-slate-200 bg-slate-100 p-1 text-sm font-medium text-slate-500">
<button
type="button"
className={`flex-1 rounded-full py-2 ${
activeTab === 'timeline' ? 'bg-white text-slate-900 shadow' : ''
}`}
onClick={() => setActiveTab('timeline')}
>
Timeline
</button>
<button
type="button"
className={`flex-1 rounded-full py-2 ${
activeTab === 'composer' ? 'bg-white text-slate-900 shadow' : ''
}`}
onClick={() => setActiveTab('composer')}
>
Nieuwe rapportage
</button>
</div>
)}
<div className="flex flex-col gap-6 lg:flex-row">
{(!isMobile || activeTab === 'timeline') && (
<aside className="space-y-4 lg:w-2/5">
<div className="rounded-2xl border border-slate-200 bg-white p-4 shadow-sm">
<div className="mb-3 flex items-center gap-2 text-xs uppercase tracking-wide text-slate-500">
<Search className="h-3.5 w-3.5" />
Filters
</div>
<div className="space-y-3">
<label className="text-xs font-medium text-slate-600" htmlFor="rapportage-search">
Zoeken
</label>
<input
id="rapportage-search"
type="search"
value={search}
onChange={(event) => setSearch(event.target.value)}
placeholder="Zoek in rapportages"
className="w-full rounded-lg border border-slate-200 bg-white p-2 text-sm text-slate-900 focus:border-teal-500 focus:outline-none"
/>
<label className="text-xs font-medium text-slate-600" htmlFor="rapportage-type">
Type
</label>
<select
id="rapportage-type"
value={typeFilter}
onChange={(event) =>
setTypeFilter(event.target.value as 'all' | keyof typeof TYPE_LABELS)
}
className="w-full rounded-lg border border-slate-200 bg-white p-2 text-sm text-slate-900"
>
<option value="all">Alle types</option>
{Object.entries(TYPE_LABELS).map(([value, label]) => (
<option key={value} value={value}>
{label}
</option>
))}
</select>
<label className="text-xs font-medium text-slate-600" htmlFor="rapportage-author">
Auteur
</label>
<select
id="rapportage-author"
value={authorFilter}
onChange={(event) => setAuthorFilter(event.target.value as 'all' | string)}
className="w-full rounded-lg border border-slate-200 bg-white p-2 text-sm text-slate-900"
>
<option value="all">Alle auteurs</option>
{authorOptions.map((author) => (
<option key={author} value={author}>
{author || 'Onbekend'}
</option>
))}
</select>
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium text-slate-600" htmlFor="rapportage-date-from">
Datum van
</label>
<input
id="rapportage-date-from"
type="date"
value={dateFrom}
onChange={(event) => setDateFrom(event.target.value)}
className="mt-1 w-full rounded-lg border border-slate-200 bg-white p-2 text-sm text-slate-900"
/>
</div>
<div>
<label className="text-xs font-medium text-slate-600" htmlFor="rapportage-date-to">
Datum t/m
</label>
<input
id="rapportage-date-to"
type="date"
value={dateTo}
onChange={(event) => setDateTo(event.target.value)}
className="mt-1 w-full rounded-lg border border-slate-200 bg-white p-2 text-sm text-slate-900"
/>
</div>
</div>
<div className="space-y-2">
<p className="text-xs font-medium text-slate-600">AI</p>
<div className="flex flex-wrap gap-2">
<FilterChip active={aiFilter === 'all'} onClick={() => setAiFilter('all')}>
Alles
</FilterChip>
<FilterChip active={aiFilter === 'ai'} onClick={() => setAiFilter('ai')}>
Met AI
</FilterChip>
<FilterChip active={aiFilter === 'manual'} onClick={() => setAiFilter('manual')}>
Handmatig
</FilterChip>
</div>
</div>
<button
type="button"
className="w-full rounded-lg border border-slate-200 bg-white py-2 text-sm font-medium text-slate-700 hover:border-teal-200 hover:text-teal-700"
onClick={resetFilters}
>
Reset filters
</button>
</div>
</div>
<ReportTimeline
reports={filteredReports}
patientId={patientId}
selectedReportId={selectedReportId}
onSelect={(report) => setSelectedReportId(report.id)}
onDeleteSuccess={handleDeleteSuccess}
/>
</aside>
)}
{(!isMobile || activeTab === 'composer') && (
<div className="lg:w-3/5">
{isMobile && activeTab === 'composer' && (
<button
type="button"
className="mb-3 inline-flex items-center text-sm font-medium text-teal-600"
onClick={() => setActiveTab('timeline')}
>
Terug naar timeline
</button>
)}
<ReportComposer
patientId={patientId}
patientName={patientName}
selectedReport={selectedReport}
onReportCreated={handleReportCreated}
/>
</div>
)}
</div>
</div>
);
}
function StatCard({
icon,
label,
value,
helper,
}: {
icon: ReactNode;
label: string;
value: string;
helper: string;
}) {
return (
<div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
<div className="flex items-center justify-between text-slate-500">
<span className="text-xs font-medium uppercase tracking-wide">{label}</span>
<div className="text-slate-400">{icon}</div>
</div>
<p className="mt-3 text-2xl font-semibold text-slate-900">{value}</p>
<p className="text-xs text-slate-500">{helper}</p>
</div>
);
}
function FilterChip({ active, onClick, children }: { active: boolean; onClick: () => void; children: ReactNode }) {
return (
<button
type="button"
onClick={onClick}
className={`rounded-full px-3 py-1 text-xs font-medium transition ${
active ? 'bg-teal-100 text-teal-700' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
}`}
>
{children}
</button>
);
}

View File

@@ -24,9 +24,11 @@ interface ReportCardProps {
report: Report;
onDelete?: () => Promise<void> | void;
isDeleting?: boolean;
onSelect?: () => void;
isSelected?: boolean;
}
export function ReportCard({ report, onDelete, isDeleting }: ReportCardProps) {
export function ReportCard({ report, onDelete, isDeleting, onSelect, isSelected }: ReportCardProps) {
const meta = TYPE_META[report.type as keyof typeof TYPE_META] ?? TYPE_META.vrije_notitie;
const Icon = meta.icon;
const createdAt = report.created_at ? new Date(report.created_at) : null;
@@ -35,7 +37,22 @@ export function ReportCard({ report, onDelete, isDeleting }: ReportCardProps) {
: null;
return (
<article className="rounded-xl border border-slate-200 bg-white p-5 shadow-sm">
<article
className={cn(
'rounded-xl border border-slate-200 bg-white p-5 shadow-sm transition hover:border-teal-200 hover:shadow-md',
onSelect && 'cursor-pointer',
isSelected && 'border-teal-400 ring-2 ring-teal-100'
)}
onClick={() => onSelect?.()}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault();
onSelect?.();
}
}}
role={onSelect ? 'button' : undefined}
tabIndex={onSelect ? 0 : undefined}
>
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3">
<div

View File

@@ -0,0 +1,285 @@
'use client';
import { useMemo, useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { SpeechRecorder } from '@/components/speech-recorder';
import { toast } from '@/hooks/use-toast';
import type { ClassificationResult, Report } from '@/lib/types/report';
import { createReport } from '../actions';
interface ReportComposerProps {
patientId: string;
patientName: string;
selectedReport?: Report | null;
onReportCreated?: (report: Report) => void;
}
export function ReportComposer({
patientId,
patientName,
selectedReport,
onReportCreated,
}: ReportComposerProps) {
const router = useRouter();
const [content, setContent] = useState('');
const [classification, setClassification] = useState<ClassificationResult | null>(null);
const [selectedType, setSelectedType] = useState<'behandeladvies' | 'vrije_notitie'>('vrije_notitie');
const [isAnalyzing, setIsAnalyzing] = useState(false);
const [isSaving, setIsSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [lastAutosave, setLastAutosave] = useState<Date | null>(null);
const draftStorageKey = useMemo(() => `rapportage-draft-${patientId}`, [patientId]);
const characterCount = content.length;
const contentInvalid = characterCount < 20 || characterCount > 5000;
useEffect(() => {
if (typeof window === 'undefined') return;
const stored = window.localStorage.getItem(draftStorageKey);
if (stored) {
try {
const draft = JSON.parse(stored) as {
content?: string;
type?: 'behandeladvies' | 'vrije_notitie';
updatedAt?: string;
};
if (draft.content) {
setContent(draft.content);
}
if (draft.type) {
setSelectedType(draft.type);
}
if (draft.updatedAt) {
setLastAutosave(new Date(draft.updatedAt));
}
} catch (draftError) {
console.error('Failed to parse draft', draftError);
window.localStorage.removeItem(draftStorageKey);
}
}
}, [draftStorageKey]);
useEffect(() => {
if (typeof window === 'undefined') return;
if (!content && selectedType === 'vrije_notitie') {
window.localStorage.removeItem(draftStorageKey);
setLastAutosave(null);
return;
}
const timeout = window.setTimeout(() => {
const payload = {
content,
type: selectedType,
updatedAt: new Date().toISOString(),
};
window.localStorage.setItem(draftStorageKey, JSON.stringify(payload));
setLastAutosave(new Date(payload.updatedAt));
}, 800);
return () => window.clearTimeout(timeout);
}, [content, selectedType, draftStorageKey]);
const referenceSnippet = useMemo(() => {
if (!selectedReport) return null;
const createdAt = selectedReport.created_at ? new Date(selectedReport.created_at) : null;
return {
preview:
selectedReport.content.length > 160
? `${selectedReport.content.slice(0, 160)}`
: selectedReport.content,
meta: createdAt
? `${createdAt.toLocaleDateString('nl-NL')}${createdAt.toLocaleTimeString('nl-NL')}`
: 'Onbekende datum',
type: selectedReport.type,
};
}, [selectedReport]);
const analyzeWithAI = async () => {
if (contentInvalid) return;
setIsAnalyzing(true);
setError(null);
try {
const response = await fetch('/api/reports/classify', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ content }),
});
if (!response.ok) {
throw new Error('AI-analyse mislukt');
}
const result: ClassificationResult = await response.json();
setClassification(result);
setSelectedType(result.type);
} catch (err) {
const message = err instanceof Error ? err.message : 'AI-analyse mislukt';
setClassification(null);
setSelectedType('vrije_notitie');
setError(message);
toast({ variant: 'destructive', title: 'AI-analyse mislukt', description: message });
} finally {
setIsAnalyzing(false);
}
};
const saveReport = async () => {
setIsSaving(true);
setError(null);
try {
const created = await createReport(patientId, {
type: selectedType,
content,
ai_confidence: classification?.confidence,
ai_reasoning: classification?.reasoning,
});
toast({
title: 'Rapportage opgeslagen',
description: `${patientName} heeft nu een nieuwe notitie in de tijdlijn.`,
});
onReportCreated?.(created);
setContent('');
setClassification(null);
setSelectedType('vrije_notitie');
if (typeof window !== 'undefined') {
window.localStorage.removeItem(draftStorageKey);
}
setLastAutosave(null);
router.refresh();
} catch (err) {
const message = err instanceof Error ? err.message : 'Opslaan mislukt';
setError(message);
toast({ variant: 'destructive', title: 'Opslaan mislukt', description: message });
} finally {
setIsSaving(false);
}
};
const insertReference = () => {
if (!selectedReport || !referenceSnippet) return;
const prefix = content ? `${content.trim()}\n\n` : '';
const block = `> ${referenceSnippet.preview}\n(${referenceSnippet.type}${referenceSnippet.meta})`;
setContent(`${prefix}${block}\n\n`);
};
return (
<section
id="rapportage-composer"
tabIndex={-1}
className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm focus:outline-none"
>
<div className="mb-4">
<p className="text-sm uppercase tracking-wide text-slate-500">Nieuwe rapportage</p>
<h2 className="text-xl font-semibold text-slate-900">Voor {patientName}</h2>
<p className="text-sm text-slate-500">
Schrijf vanuit tekst of spraak en gebruik AI voor typebepaling.
</p>
</div>
{referenceSnippet && (
<div className="mb-4 rounded-xl border border-slate-100 bg-slate-50 p-4">
<div className="flex items-center justify-between gap-2 text-xs text-slate-500">
<span className="font-semibold text-slate-700">Geselecteerde rapportage</span>
<span>{referenceSnippet.meta}</span>
</div>
<p className="mt-2 text-sm text-slate-700">{referenceSnippet.preview}</p>
<div className="mt-3 flex items-center justify-between">
<span className="text-xs uppercase tracking-wide text-slate-400">{referenceSnippet.type}</span>
<Button
type="button"
variant="outline"
size="sm"
onClick={insertReference}
disabled={isSaving}
>
Voeg referentie toe
</Button>
</div>
</div>
)}
<div className="flex flex-col gap-4">
<div>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="Beschrijf wat je wilt vastleggen..."
className="w-full min-h-[200px] rounded-xl border border-slate-200 bg-white p-4 text-sm text-slate-900 shadow-inner focus:border-teal-500 focus:outline-none"
/>
<div className="flex justify-between text-xs text-slate-500">
<span>{characterCount} / 5000 karakters</span>
{contentInvalid && <span>Minimaal 20 karakters</span>}
</div>
</div>
<SpeechRecorder
disabled={isSaving || isAnalyzing}
onTranscript={(text) =>
setContent((prev) => (prev ? `${prev}\n${text}` : text))
}
/>
<div className="rounded-xl border border-slate-200 p-4 text-sm">
<div className="flex items-center justify-between">
<div>
<p className="font-medium text-slate-900">Rapportagetype</p>
<p className="text-xs text-slate-500">Stel handmatig in of gebruik het AI-voorstel.</p>
</div>
<span className="text-xs text-slate-500">
{classification
? `AI: ${classification.type} (${Math.round(classification.confidence * 100)}%)`
: 'Nog geen AI-analyse'}
</span>
</div>
{classification?.reasoning && (
<p className="mt-2 text-xs text-slate-500">{classification.reasoning}</p>
)}
<select
value={selectedType}
onChange={(e) => setSelectedType(e.target.value as 'behandeladvies' | 'vrije_notitie')}
className="mt-3 w-full rounded-md border border-slate-200 bg-white p-2 text-sm"
>
<option value="behandeladvies">Behandeladvies</option>
<option value="vrije_notitie">Vrije notitie</option>
</select>
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
</div>
<div className="mt-6 flex flex-wrap items-center justify-between gap-3 border-t border-slate-100 pt-4">
<p className="text-xs text-slate-500">
{isSaving
? 'Opslaan bezig…'
: lastAutosave
? `Automatisch opgeslagen ${lastAutosave.toLocaleTimeString('nl-NL', {
hour: '2-digit',
minute: '2-digit',
})}`
: 'Concept wordt lokaal bijgehouden.'}
</p>
<div className="flex flex-wrap gap-2">
<Button
type="button"
variant="outline"
onClick={analyzeWithAI}
disabled={contentInvalid || isAnalyzing || isSaving}
>
{isAnalyzing ? 'Analyseren…' : 'Analyseer met AI'}
</Button>
<Button
type="button"
onClick={saveReport}
disabled={contentInvalid || isSaving}
>
{isSaving ? 'Opslaan…' : 'Opslaan'}
</Button>
</div>
</div>
</section>
);
}

View File

@@ -1,6 +1,6 @@
'use client';
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { FilePlus2 } from 'lucide-react';
import type { Report } from '@/lib/types/report';
import { deleteReport } from '../actions';
@@ -10,21 +10,34 @@ import { toast } from '@/hooks/use-toast';
interface ReportTimelineProps {
reports: Report[];
patientId: string;
selectedReportId?: string | null;
onSelect?: (report: Report) => void;
onDeleteSuccess?: (reportId: string) => void;
}
export function ReportTimeline({ reports, patientId }: ReportTimelineProps) {
const [items, setItems] = useState(reports);
const INITIAL_VISIBLE = 20;
export function ReportTimeline({
reports,
patientId,
selectedReportId,
onSelect,
onDeleteSuccess,
}: ReportTimelineProps) {
const [deletingId, setDeletingId] = useState<string | null>(null);
const [visibleCount, setVisibleCount] = useState(INITIAL_VISIBLE);
useEffect(() => {
setItems(reports);
setVisibleCount(INITIAL_VISIBLE);
}, [reports]);
const visibleReports = useMemo(() => reports.slice(0, visibleCount), [reports, visibleCount]);
const handleDelete = async (reportId: string) => {
setDeletingId(reportId);
try {
await deleteReport(patientId, reportId);
setItems((prev) => prev.filter((report) => report.id !== reportId));
onDeleteSuccess?.(reportId);
toast({
title: 'Rapportage verwijderd',
description: 'De rapportage is verwijderd uit de tijdlijn.',
@@ -42,7 +55,7 @@ export function ReportTimeline({ reports, patientId }: ReportTimelineProps) {
}
};
if (items.length === 0) {
if (reports.length === 0) {
return (
<div className="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-10 text-center">
<div className="mx-auto mb-4 flex h-16 w-16 items-center justify-center rounded-full bg-white text-slate-400">
@@ -56,16 +69,29 @@ export function ReportTimeline({ reports, patientId }: ReportTimelineProps) {
);
}
const hasMore = reports.length > visibleCount;
return (
<div className="space-y-4">
{items.map((report) => (
{visibleReports.map((report) => (
<ReportCard
key={report.id}
report={report}
onDelete={() => handleDelete(report.id)}
isDeleting={deletingId === report.id}
onSelect={() => onSelect?.(report)}
isSelected={selectedReportId === report.id}
/>
))}
{hasMore && (
<button
type="button"
className="w-full rounded-lg border border-slate-200 bg-white py-2 text-sm font-medium text-slate-700 hover:border-teal-200 hover:text-teal-700"
onClick={() => setVisibleCount((prev) => prev + INITIAL_VISIBLE)}
>
Meer rapportages laden
</button>
)}
</div>
);
}

View File

@@ -1,9 +1,6 @@
import type { ReactNode } from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { ClipboardList, Sparkles, Timer } from 'lucide-react';
import { getReports } from './actions';
import { ReportTimeline } from './components/report-timeline';
import { RapportageWorkspace } from './components/rapportage-workspace';
import { getPatient } from '../../actions';
export default async function RapportagePage({
params,
@@ -11,68 +8,26 @@ export default async function RapportagePage({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const reports = await getReports(id);
const totalReports = reports.length;
const latestReport = reports[0];
const latestDate = latestReport?.created_at
? format(new Date(latestReport.created_at), "d MMM yyyy 'om' HH:mm", { locale: nl })
: null;
const [reports, patient] = await Promise.all([getReports(id), getPatient(id)]);
const patientName = formatPatientName(patient);
return (
<div className="space-y-6 p-6">
<div>
<p className="text-sm uppercase tracking-wide text-slate-500">Universele rapportage</p>
<h1 className="text-2xl font-semibold text-slate-900">Tijdlijn en notities</h1>
<p className="mt-1 text-sm text-slate-600">
Alle behandeladviezen en vrije notities voor deze cliënt op één plek.
</p>
</div>
<div className="grid gap-4 md:grid-cols-3">
<StatCard
icon={<ClipboardList className="h-5 w-5" />}
label="Totaal rapportages"
value={totalReports.toString()}
helper={totalReports > 0 ? 'Inclusief soft-deletes' : 'Nog geen rapportages'}
/>
<StatCard
icon={<Sparkles className="h-5 w-5" />}
label="AI classificaties"
value={`${reports.filter((r) => r.ai_confidence !== null).length}`}
helper="AI helpt bij type bepaling"
/>
<StatCard
icon={<Timer className="h-5 w-5" />}
label="Laatste activiteit"
value={latestDate ?? '—'}
helper={latestDate ? 'Recentste rapportage' : 'Nog geen activiteit'}
/>
</div>
<ReportTimeline reports={reports} patientId={id} />
</div>
<RapportageWorkspace
patientId={id}
patientName={patientName}
initialReports={reports}
/>
);
}
function StatCard({
icon,
label,
value,
helper,
}: {
icon: ReactNode;
label: string;
value: string;
helper: string;
}) {
return (
<div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
<div className="flex items-center justify-between text-slate-500">
<span className="text-xs font-medium uppercase tracking-wide">{label}</span>
<div className="text-slate-400">{icon}</div>
</div>
<p className="mt-3 text-2xl font-semibold text-slate-900">{value}</p>
<p className="text-xs text-slate-500">{helper}</p>
</div>
);
function formatPatientName(patient: Awaited<ReturnType<typeof getPatient>>) {
const name = patient?.name?.[0];
if (!name) return 'deze patiënt';
return [
...(name.prefix || []),
...(name.given || []),
name.family,
]
.filter(Boolean)
.join(' ');
}