feat: migrate clients module to patients + add docs

This commit is contained in:
colinislit
2025-11-23 10:13:00 +01:00
parent 8e3925ea09
commit 6fcb9a0e7b
277 changed files with 9131 additions and 458 deletions

View File

@@ -0,0 +1,171 @@
'use server';
import { revalidatePath } from 'next/cache';
import { headers, cookies } from 'next/headers';
import type {
ScreeningSummary,
ScreeningWithRelations,
} from '@/lib/types/screening';
function getBaseUrl(): string {
if (process.env.NEXT_PUBLIC_APP_URL) {
return process.env.NEXT_PUBLIC_APP_URL;
}
try {
const headersList = headers();
const host = headersList.get('host');
const protocol = headersList.get('x-forwarded-proto') || 'http';
if (host) {
return `${protocol}://${host}`;
}
} catch {
// ignore
}
return 'http://localhost:3000';
}
async function getCookieHeader(): Promise<string> {
try {
const cookieStore = await cookies();
return cookieStore
.getAll()
.map((cookie) => `${cookie.name}=${cookie.value}`)
.join('; ');
} catch {
return '';
}
}
function normalizeSummary(screening: ScreeningWithRelations): ScreeningSummary {
return {
screening,
activities: screening.screening_activities || [],
documents: screening.screening_documents || [],
};
}
export async function getScreeningSummary(patientId: string): Promise<ScreeningSummary> {
try {
const baseUrl = getBaseUrl();
const cookieHeader = await getCookieHeader();
const response = await fetch(`${baseUrl}/api/screenings?patientId=${patientId}`, {
cache: 'no-store',
headers: {
...(cookieHeader && { Cookie: cookieHeader }),
},
});
if (!response.ok) {
const error = await response.text();
throw new Error(error || 'Kon screening niet ophalen');
}
const data = await response.json();
return normalizeSummary(data.screening);
} catch (error) {
console.error('Error fetching screening summary:', error);
throw error instanceof Error ? error : new Error('Kon screening niet ophalen');
}
}
export async function saveHelpRequest(params: {
patientId: string;
screeningId: string;
request: string;
}) {
try {
const baseUrl = getBaseUrl();
const cookieHeader = await getCookieHeader();
const response = await fetch(`${baseUrl}/api/screenings/${params.screeningId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...(cookieHeader && { Cookie: cookieHeader }),
},
body: JSON.stringify({ request_for_help: params.request }),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || 'Opslaan mislukt');
}
revalidatePath(`/epd/patients/${params.patientId}/screening`);
return true;
} catch (error) {
console.error('Error saving help request:', error);
throw error instanceof Error ? error : new Error('Opslaan mislukt');
}
}
export async function saveScreeningDecision(params: {
patientId: string;
screeningId: string;
decision: 'geschikt' | 'niet_geschikt';
notes?: string;
department?: string;
}) {
try {
const baseUrl = getBaseUrl();
const cookieHeader = await getCookieHeader();
const response = await fetch(`${baseUrl}/api/screenings/${params.screeningId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
...(cookieHeader && { Cookie: cookieHeader }),
},
body: JSON.stringify({
decision: params.decision,
decision_notes: params.notes,
decision_department: params.department,
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || 'Opslaan mislukt');
}
revalidatePath(`/epd/patients/${params.patientId}/screening`);
revalidatePath(`/epd/patients/${params.patientId}`);
return true;
} catch (error) {
console.error('Error saving decision:', error);
throw error instanceof Error ? error : new Error('Opslaan mislukt');
}
}
export async function addScreeningActivity(params: {
patientId: string;
screeningId: string;
text: string;
}) {
try {
const baseUrl = getBaseUrl();
const cookieHeader = await getCookieHeader();
const response = await fetch(`${baseUrl}/api/screenings/${params.screeningId}/activities`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(cookieHeader && { Cookie: cookieHeader }),
},
body: JSON.stringify({ activity_text: params.text }),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || 'Toevoegen mislukt');
}
revalidatePath(`/epd/patients/${params.patientId}/screening`);
return true;
} catch (error) {
console.error('Error adding activity:', error);
throw error instanceof Error ? error : new Error('Toevoegen mislukt');
}
}

View File

@@ -0,0 +1,105 @@
'use client';
import { useState, useTransition } from 'react';
import { addScreeningActivity } from '../actions';
import type { ScreeningActivity } from '@/lib/types/screening';
import { Loader2, MessageSquare } from 'lucide-react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
interface ActivityLogProps {
patientId: string;
screeningId: string;
activities: ScreeningActivity[];
}
export function ActivityLog({ patientId, screeningId, activities }: ActivityLogProps) {
const [text, setText] = useState('');
const [error, setError] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const handleSubmit = () => {
if (!text.trim()) {
setError('Vul eerst een activiteit in.');
return;
}
setError(null);
startTransition(async () => {
try {
await addScreeningActivity({
patientId,
screeningId,
text,
});
setText('');
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : 'Toevoegen mislukt');
}
});
};
return (
<section className="bg-white rounded-lg border border-slate-200 p-6 shadow-sm h-full flex flex-col">
<div className="flex items-center gap-3 mb-4">
<div className="p-2 rounded-md bg-blue-50 text-blue-600">
<MessageSquare className="h-5 w-5" />
</div>
<div>
<h3 className="text-lg font-semibold text-slate-900">Activiteitenlog</h3>
<p className="text-sm text-slate-500">Chronologisch overzicht</p>
</div>
</div>
<div className="space-y-4 overflow-y-auto flex-1 pr-1">
{activities.length === 0 && (
<p className="text-sm text-slate-500">
Nog geen activiteiten. Voeg de eerste notitie toe om het dossier te starten.
</p>
)}
{activities.map((activity) => (
<div
key={activity.id}
className="border border-slate-200 rounded-lg p-3 bg-slate-50"
>
<div className="flex items-center justify-between text-xs text-slate-500 mb-1">
<span className="font-medium text-slate-700">
{activity.created_by_name || 'Onbekende gebruiker'}
</span>
{activity.created_at && (
<span>
{format(new Date(activity.created_at), 'd MMM yyyy HH:mm', { locale: nl })}
</span>
)}
</div>
<p className="text-sm text-slate-700 whitespace-pre-line">{activity.activity_text}</p>
</div>
))}
</div>
<div className="mt-4 pt-4 border-t border-slate-100">
<label className="text-sm font-medium text-slate-700 mb-2 block">
Nieuwe activiteit
</label>
<textarea
value={text}
onChange={(event) => setText(event.target.value)}
placeholder="Bijv. Huisarts gesproken, verwijsbrief ontvangen..."
className="w-full rounded-lg border border-slate-200 px-3 py-2 text-sm focus:border-teal-500 focus:ring-2 focus:ring-teal-100"
/>
{error && <p className="text-sm text-red-600 mt-1">{error}</p>}
<button
type="button"
onClick={handleSubmit}
disabled={isPending}
className="mt-3 inline-flex items-center gap-2 rounded-md bg-teal-600 px-4 py-2 text-sm font-medium text-white hover:bg-teal-700 disabled:opacity-60"
>
{isPending && <Loader2 className="h-4 w-4 animate-spin" />}
Toevoegen
</button>
</div>
</section>
);
}

View File

@@ -0,0 +1,186 @@
'use client';
import { useEffect, useState, useTransition } from 'react';
import { saveScreeningDecision } from '../actions';
import { cn } from '@/lib/utils';
import { ShieldCheck, ShieldX } from 'lucide-react';
const departmentOptions = [
'Volwassenen',
'Jeugd (< 18 jaar)',
'Forensisch',
'Verslaving',
'Ouderen (65+)',
'FACT',
];
interface DecisionCardProps {
patientId: string;
screeningId: string;
initialDecision?: string | null;
initialDepartment?: string | null;
initialNotes?: string | null;
hasReferralDocument: boolean;
}
export function DecisionCard({
patientId,
screeningId,
initialDecision,
initialDepartment,
initialNotes,
hasReferralDocument,
}: DecisionCardProps) {
const [decision, setDecision] = useState<'geschikt' | 'niet_geschikt' | ''>(
(initialDecision as 'geschikt' | 'niet_geschikt') || ''
);
const [department, setDepartment] = useState(initialDepartment || '');
const [notes, setNotes] = useState(initialNotes || '');
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [isPending, startTransition] = useTransition();
useEffect(() => {
setDecision((initialDecision as 'geschikt' | 'niet_geschikt') || '');
setDepartment(initialDepartment || '');
setNotes(initialNotes || '');
}, [initialDecision, initialDepartment, initialNotes]);
const handleSave = () => {
if (!decision) {
setError('Kies eerst een besluit.');
return;
}
if (decision === 'geschikt' && !department) {
setError('Kies een afdeling voor intake.');
return;
}
setError(null);
setSuccess(false);
startTransition(async () => {
try {
await saveScreeningDecision({
patientId,
screeningId,
decision,
notes,
department: decision === 'geschikt' ? department : undefined,
});
setSuccess(true);
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : 'Opslaan mislukt');
}
});
};
return (
<section className="bg-white rounded-lg border border-slate-200 p-6 shadow-sm">
<div className="flex items-center gap-3 mb-4">
<div className="p-2 rounded-md bg-slate-100 text-slate-700">
{decision === 'geschikt' ? (
<ShieldCheck className="h-5 w-5 text-emerald-600" />
) : decision === 'niet_geschikt' ? (
<ShieldX className="h-5 w-5 text-red-600" />
) : (
<ShieldCheck className="h-5 w-5" />
)}
</div>
<div>
<h3 className="text-lg font-semibold text-slate-900">Screeningsbesluit</h3>
<p className="text-sm text-slate-500">Alleen zichtbaar voor psychologen</p>
</div>
</div>
{!hasReferralDocument && (
<div className="mb-4 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
<p className="font-medium">Geen verwijsbrief gevonden</p>
<p className="text-amber-800 mt-1">
Voeg een verwijsbrief toe voordat je een definitief besluit neemt, zodat het dossier compleet is.
</p>
</div>
)}
<div className="grid grid-cols-1 gap-4">
<div className="flex flex-wrap gap-3">
{[
{ value: 'geschikt', label: 'Geschikt voor intake' },
{ value: 'niet_geschikt', label: 'Niet geschikt / doorverwijzen' },
].map((option) => (
<button
key={option.value}
type="button"
onClick={() => {
setDecision(option.value as 'geschikt' | 'niet_geschikt');
setSuccess(false);
}}
className={cn(
'px-4 py-2 rounded-full border text-sm font-medium transition',
decision === option.value
? 'border-teal-500 bg-teal-50 text-teal-700'
: 'border-slate-200 text-slate-600 hover:border-slate-300'
)}
>
{option.label}
</button>
))}
</div>
{decision === 'geschikt' && (
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">
Doorgaan bij afdeling
</label>
<select
value={department}
onChange={(event) => {
setDepartment(event.target.value);
setSuccess(false);
}}
className="w-full rounded-md border border-slate-200 px-3 py-2 text-sm focus:border-teal-500 focus:ring-2 focus:ring-teal-100"
>
<option value="">Selecteer afdeling...</option>
{departmentOptions.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</div>
)}
<div className="space-y-2">
<label className="text-sm font-medium text-slate-700">Notities bij besluit</label>
<textarea
value={notes}
onChange={(event) => {
setNotes(event.target.value);
setSuccess(false);
}}
className="w-full rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm text-slate-700 focus:bg-white focus:border-teal-500 focus:ring-2 focus:ring-teal-100"
placeholder="Extra context of afspraken..."
/>
</div>
</div>
<div className="mt-4 flex items-center justify-between text-sm">
<div>
{error && <span className="text-red-600">{error}</span>}
{success && !error && <span className="text-emerald-600">Besluit opgeslagen</span>}
</div>
<button
type="button"
onClick={handleSave}
disabled={isPending}
className="inline-flex items-center gap-2 rounded-md bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-800 disabled:opacity-60"
>
{isPending && <span className="animate-pulse">...</span>}
Opslaan besluit
</button>
</div>
</section>
);
}

View File

@@ -0,0 +1,197 @@
'use client';
import { useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import type { ScreeningDocument } from '@/lib/types/screening';
import { Loader2, Trash2, UploadCloud } from 'lucide-react';
import { cn } from '@/lib/utils';
const DOCUMENT_BUCKET = 'screening-documents';
const BASE_STORAGE_URL = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/${DOCUMENT_BUCKET}`;
const documentTypeOptions = [
'verwijsbrief',
'verhuisbericht',
'indicatie',
'overig',
];
interface DocumentCardProps {
patientId: string;
screeningId: string;
documents: ScreeningDocument[];
}
export function DocumentCard({ patientId, screeningId, documents }: DocumentCardProps) {
const router = useRouter();
const [file, setFile] = useState<File | null>(null);
const [documentType, setDocumentType] = useState('verwijsbrief');
const [error, setError] = useState<string | null>(null);
const [isUploading, startUpload] = useTransition();
const [deletingId, setDeletingId] = useState<string | null>(null);
const handleUpload = () => {
if (!file) {
setError('Selecteer eerst een bestand.');
return;
}
setError(null);
startUpload(async () => {
const formData = new FormData();
formData.append('file', file);
formData.append('documentType', documentType);
try {
const response = await fetch(`/api/screenings/${screeningId}/documents`, {
method: 'POST',
body: formData,
});
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error || 'Upload mislukt');
}
setFile(null);
router.refresh();
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : 'Upload mislukt');
}
});
};
const handleDelete = async (documentId: string) => {
setDeletingId(documentId);
try {
const response = await fetch(
`/api/screenings/${screeningId}/documents/${documentId}`,
{
method: 'DELETE',
}
);
if (!response.ok) {
const data = await response.json().catch(() => ({}));
throw new Error(data.error || 'Verwijderen mislukt');
}
router.refresh();
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : 'Verwijderen mislukt');
} finally {
setDeletingId(null);
}
};
return (
<section className="bg-white rounded-lg border border-slate-200 p-6 shadow-sm">
<div className="flex items-center gap-3 mb-4">
<div className="p-2 rounded-md bg-slate-100 text-slate-600">
<UploadCloud className="h-5 w-5" />
</div>
<div>
<h3 className="text-lg font-semibold text-slate-900">Documenten</h3>
<p className="text-sm text-slate-500">
Upload verwijsbrieven, indicaties en andere stukken.
</p>
</div>
</div>
<div className="space-y-4">
<div className="border border-dashed border-slate-300 rounded-lg p-4">
<div className="flex flex-col gap-3">
<input
type="file"
onChange={(event) => {
const selected = event.target.files?.[0] ?? null;
setFile(selected);
setError(null);
}}
/>
<div className="flex flex-col sm:flex-row sm:items-center gap-3">
<select
value={documentType}
onChange={(event) => setDocumentType(event.target.value)}
className="h-10 rounded-md border border-slate-300 px-3 text-sm"
>
{documentTypeOptions.map((option) => (
<option key={option} value={option}>
{option.charAt(0).toUpperCase() + option.slice(1)}
</option>
))}
</select>
<button
type="button"
onClick={handleUpload}
disabled={isUploading}
className={cn(
'inline-flex items-center justify-center gap-2 rounded-md bg-teal-600 px-4 py-2 text-sm font-medium text-white hover:bg-teal-700 disabled:opacity-60'
)}
>
{isUploading && <Loader2 className="h-4 w-4 animate-spin" />}
Upload document
</button>
</div>
{error && <p className="text-sm text-red-600">{error}</p>}
{file && (
<p className="text-xs text-slate-500">
Geselecteerd: {file.name} {(file.size / 1024).toFixed(1)} KB
</p>
)}
</div>
</div>
<div className="space-y-3">
{documents.length === 0 && (
<p className="text-sm text-slate-500">
Nog geen documenten geregistreerd.
</p>
)}
{documents.map((doc) => {
const publicUrl = `${BASE_STORAGE_URL}/${doc.file_path}`;
return (
<div
key={doc.id}
className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 border border-slate-200 rounded-lg p-3"
>
<div>
<p className="text-sm font-medium text-slate-900">{doc.file_name}</p>
<p className="text-xs text-slate-500">
{doc.document_type} {(doc.file_size / 1024).toFixed(1)} KB {' '}
{doc.uploaded_by_name || 'Onbekend'}
</p>
</div>
<div className="flex items-center gap-3">
<a
href={publicUrl}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-teal-600 hover:text-teal-700"
>
Download
</a>
<button
type="button"
onClick={() => handleDelete(doc.id)}
disabled={deletingId === doc.id}
className="inline-flex items-center gap-1 rounded-md border border-red-200 px-3 py-1.5 text-xs font-medium text-red-600 hover:bg-red-50 disabled:opacity-60"
>
{deletingId === doc.id ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Trash2 className="h-4 w-4" />
)}
Verwijderen
</button>
</div>
</div>
);
})}
</div>
</div>
</section>
);
}

View File

@@ -0,0 +1,84 @@
'use client';
import { useEffect, useState, useTransition } from 'react';
import { Loader2, NotebookPen } from 'lucide-react';
import { saveHelpRequest } from '../actions';
import { cn } from '@/lib/utils';
interface HelpRequestCardProps {
patientId: string;
screeningId: string;
initialValue?: string | null;
}
export function HelpRequestCard({ patientId, screeningId, initialValue }: HelpRequestCardProps) {
const [value, setValue] = useState(initialValue || '');
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);
const [isPending, startTransition] = useTransition();
useEffect(() => {
setValue(initialValue || '');
}, [initialValue]);
const handleSave = () => {
setError(null);
setSuccess(false);
startTransition(async () => {
try {
await saveHelpRequest({
patientId,
screeningId,
request: value,
});
setSuccess(true);
} catch (err) {
console.error(err);
setError(err instanceof Error ? err.message : 'Opslaan mislukt');
}
});
};
return (
<section className="bg-white rounded-lg border border-slate-200 p-6 shadow-sm">
<div className="flex items-center gap-3 mb-4">
<div className="p-2 rounded-md bg-teal-50 text-teal-600">
<NotebookPen className="h-5 w-5" />
</div>
<div>
<h3 className="text-lg font-semibold text-slate-900">Hulpvraag</h3>
<p className="text-sm text-slate-500">Beschrijf de zorgvraag van de cliënt</p>
</div>
</div>
<textarea
className="w-full min-h-[160px] rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700 focus:bg-white focus:border-teal-500 focus:ring-2 focus:ring-teal-100 transition"
placeholder="Beschrijf de hulpvraag van de cliënt..."
value={value}
onChange={(event) => {
setValue(event.target.value);
setSuccess(false);
}}
/>
<div className="mt-4 flex items-center justify-between">
<div className="text-sm">
{error && <span className="text-red-600">{error}</span>}
{success && !error && <span className="text-emerald-600">Opgeslagen</span>}
</div>
<button
type="button"
onClick={handleSave}
disabled={isPending}
className={cn(
'inline-flex items-center gap-2 rounded-md px-4 py-2 text-sm font-medium text-white bg-teal-600 hover:bg-teal-700 transition disabled:opacity-60 disabled:cursor-not-allowed'
)}
>
{isPending && <Loader2 className="h-4 w-4 animate-spin" />}
Opslaan
</button>
</div>
</section>
);
}

View File

@@ -1,9 +1,8 @@
/**
* Screening Page
* E2.S3: Placeholder for screening functionality (to be implemented in Epic 3)
*/
import { ClipboardList } from 'lucide-react';
import { getScreeningSummary } from './actions';
import { HelpRequestCard } from './components/help-request-card';
import { DecisionCard } from './components/decision-card';
import { ActivityLog } from './components/activity-log';
import { DocumentCard } from './components/document-card';
export default async function ScreeningPage({
params,
@@ -11,29 +10,51 @@ export default async function ScreeningPage({
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const summary = await getScreeningSummary(id);
const screening = summary.screening;
const hasReferral = summary.documents.some(
(doc) => doc.document_type === 'verwijsbrief'
);
return (
<div className="p-6">
{/* Page Header */}
<div className="mb-6">
<div className="p-6 space-y-6">
<div>
<h2 className="text-lg font-semibold text-slate-900">Screening</h2>
<p className="text-sm text-slate-600 mt-1">
Activiteitenlog, documenten, hulpvraag en screeningsbesluit
</p>
</div>
{/* Placeholder */}
<div className="bg-white rounded-lg border border-slate-200 p-12 text-center">
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-amber-50 mb-4">
<ClipboardList className="h-8 w-8 text-amber-500" />
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div className="lg:col-span-2 space-y-6">
<HelpRequestCard
patientId={id}
screeningId={screening.id}
initialValue={screening.request_for_help}
/>
<DecisionCard
patientId={id}
screeningId={screening.id}
initialDecision={screening.decision}
initialDepartment={screening.decision_department}
initialNotes={screening.decision_notes}
hasReferralDocument={hasReferral}
/>
<DocumentCard
patientId={id}
screeningId={screening.id}
documents={summary.documents}
/>
</div>
<div className="lg:col-span-1">
<ActivityLog
patientId={id}
screeningId={screening.id}
activities={summary.activities}
/>
</div>
<h3 className="text-lg font-semibold text-slate-900 mb-2">
Screening Module - Coming Soon
</h3>
<p className="text-sm text-slate-600 max-w-md mx-auto">
De screening functionaliteit wordt geïmplementeerd in Epic 3. Dit omvat
activiteitenlog, documentbeheer, hulpvraag registratie en screeningsbesluit.
</p>
</div>
</div>
);