feat(agenda): Epic 4 - EPD Koppeling (appointment-report integration)

Implements bidirectional linking between appointments and reports:
- E4.S1: Create report from appointment modal with encounter pre-linked
- E4.S2: Link existing reports to appointments via EncounterSelector
- E4.S3: Show linked reports in appointment modal edit view
- E4.S4: Navigation between appointments and reports with deep linking

Also includes bug fixes for patient search:
- Fix FHIR to internal format mapping for patient data
- Fix debounced search interference after patient selection
- Fix UUID handling for optional practitioner_id

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

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
colinislit
2025-12-02 19:34:07 +01:00
parent e661c97491
commit b7b5a0888b
18 changed files with 1612 additions and 61 deletions

View File

@@ -26,20 +26,44 @@ export async function GET(request: NextRequest) {
// Build query
let query = supabaseAdmin.from('patients').select('*');
// Search by name (family or given)
// General search (searches name, BSN, and client number)
const q = searchParams.get('q');
if (q) {
// Check if input looks like a number (BSN or client number)
const isNumeric = /^\d+$/.test(q.trim());
if (isNumeric) {
// Search BSN and client number
query = query.or(
`identifier_bsn.ilike.%${q}%,identifier_client_number.ilike.%${q}%`
);
} else {
// Search name fields
query = query.or(
`name_family.ilike.%${q}%,name_given.cs.{${q}}`
);
}
}
// Search by name (family or given) - legacy support
const name = searchParams.get('name');
if (name) {
if (name && !q) {
query = query.or(
`name_family.ilike.%${name}%,name_given.cs.{${name}}`
);
}
// Search by identifier (BSN)
// Search by identifier (BSN) - legacy support
const identifier = searchParams.get('identifier');
if (identifier) {
if (identifier && !q) {
query = query.eq('identifier_bsn', identifier);
}
// Search by client number
const clientNumber = searchParams.get('clientNumber');
if (clientNumber && !q) {
query = query.ilike('identifier_client_number', `%${clientNumber}%`);
}
// Search by birth date
const birthdate = searchParams.get('birthdate');
if (birthdate) {
@@ -55,6 +79,15 @@ export async function GET(request: NextRequest) {
// Order by updated_at descending (newest first)
query = query.order('updated_at', { ascending: false });
// Limit results (_count parameter)
const count = searchParams.get('_count');
if (count) {
const limit = parseInt(count, 10);
if (!isNaN(limit) && limit > 0) {
query = query.limit(limit);
}
}
// Execute query
const { data: patients, error } = await query;

View File

@@ -81,7 +81,7 @@ export async function POST(request: NextRequest) {
);
}
const { patient_id, type, content, ai_confidence, ai_reasoning } = result.data;
const { patient_id, type, content, ai_confidence, ai_reasoning, encounter_id, intake_id } = result.data;
const { data, error } = await supabase
.from('reports')
.insert({
@@ -90,6 +90,8 @@ export async function POST(request: NextRequest) {
content,
ai_confidence,
ai_reasoning,
encounter_id,
intake_id,
created_by: authData.user.id,
})
.select('*')

View File

@@ -70,7 +70,7 @@ export async function getEncounters({
} | null;
const patientName = patient
? `${patient.name_given?.[0] || ''} ${patient.name_family}`.trim()
? `${patient.name_given?.[0] || ''} ${patient.name_family || ''}`.trim() || 'Onbekende patiënt'
: 'Onbekende patiënt';
const typeCode = encounter.type_code as AppointmentTypeCode;
@@ -94,7 +94,7 @@ export async function getEncounters({
interface CreateEncounterParams {
patientId: string;
practitionerId: string;
practitionerId?: string;
periodStart: string;
periodEnd?: string;
typeCode: string;
@@ -111,7 +111,7 @@ export async function createEncounter(params: CreateEncounterParams) {
.from('encounters')
.insert({
patient_id: params.patientId,
practitioner_id: params.practitionerId,
practitioner_id: params.practitionerId || null,
period_start: params.periodStart,
period_end: params.periodEnd,
type_code: params.typeCode,
@@ -137,18 +137,26 @@ export async function updateEncounter(
encounterId: string,
updates: {
periodStart?: string;
periodEnd?: string;
periodEnd?: string | null;
status?: string;
notes?: string;
typeCode?: string;
typeDisplay?: string;
classCode?: string;
classDisplay?: string;
}
) {
const supabase = await createClient();
const updateData: Record<string, unknown> = {};
if (updates.periodStart) updateData.period_start = updates.periodStart;
if (updates.periodEnd) updateData.period_end = updates.periodEnd;
if (updates.periodEnd !== undefined) updateData.period_end = updates.periodEnd;
if (updates.status) updateData.status = updates.status;
if (updates.notes !== undefined) updateData.notes = updates.notes;
if (updates.typeCode) updateData.type_code = updates.typeCode;
if (updates.typeDisplay) updateData.type_display = updates.typeDisplay;
if (updates.classCode) updateData.class_code = updates.classCode;
if (updates.classDisplay) updateData.class_display = updates.classDisplay;
const { data, error } = await supabase
.from('encounters')
@@ -180,3 +188,66 @@ export async function rescheduleEncounter(
periodEnd: newEnd || undefined,
});
}
/**
* Get encounters for a specific patient (for linking reports to appointments)
*/
export async function getPatientEncounters(patientId: string) {
const supabase = await createClient();
const { data, error } = await supabase
.from('encounters')
.select('id, period_start, period_end, type_code, type_display, status, notes')
.eq('patient_id', patientId)
.neq('status', 'cancelled')
.order('period_start', { ascending: false })
.limit(50);
if (error) {
console.error('Error fetching patient encounters:', error);
return [];
}
return data || [];
}
/**
* Get reports linked to a specific encounter
*/
export async function getEncounterReports(encounterId: string) {
const supabase = await createClient();
const { data, error } = await supabase
.from('reports')
.select('id, type, content, created_at')
.eq('encounter_id', encounterId)
.is('deleted_at', null)
.order('created_at', { ascending: false });
if (error) {
console.error('Error fetching encounter reports:', error);
return [];
}
return data || [];
}
/**
* Get a single encounter by ID (for navigation from report to appointment)
*/
export async function getEncounterById(encounterId: string) {
const supabase = await createClient();
const { data, error } = await supabase
.from('encounters')
.select('id, period_start, period_end, type_code, type_display, status')
.eq('id', encounterId)
.single();
if (error) {
console.error('Error fetching encounter:', error);
return null;
}
return data;
}

View File

@@ -6,28 +6,59 @@
* Client-side wrapper managing calendar state, view switching, and interactions.
*/
import { useState, useCallback, useRef, useEffect, useTransition } from 'react';
import { useState, useCallback, useRef, useTransition, useEffect } from 'react';
import { startOfWeek, endOfWeek, addDays, format } from 'date-fns';
import { toast } from '@/hooks/use-toast';
import { AgendaCalendar } from './agenda-calendar';
import { AgendaToolbar } from './agenda-toolbar';
import { AppointmentModal } from './appointment-modal';
import { RescheduleDialog } from './reschedule-dialog';
import { getEncounters, rescheduleEncounter } from '../actions';
import type { CalendarEvent, CalendarView } from '../types';
interface PendingReschedule {
event: CalendarEvent;
newStart: Date;
newEnd: Date | null;
}
interface AgendaViewProps {
initialEvents: CalendarEvent[];
initialDate?: Date;
highlightEncounterId?: string;
}
export function AgendaView({ initialEvents, initialDate }: AgendaViewProps) {
export function AgendaView({ initialEvents, initialDate, highlightEncounterId }: AgendaViewProps) {
const [events, setEvents] = useState<CalendarEvent[]>(initialEvents);
const [currentDate, setCurrentDate] = useState(initialDate || new Date());
const [currentView, setCurrentView] = useState<CalendarView>('timeGridWeek');
const [isPending, startTransition] = useTransition();
// Modal state
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalInitialDate, setModalInitialDate] = useState<Date | undefined>();
const [modalInitialStartTime, setModalInitialStartTime] = useState<string | undefined>();
const [modalInitialEndTime, setModalInitialEndTime] = useState<string | undefined>();
const [editingEvent, setEditingEvent] = useState<CalendarEvent | undefined>();
// Reschedule dialog state
const [pendingReschedule, setPendingReschedule] = useState<PendingReschedule | null>(null);
const [isRescheduling, setIsRescheduling] = useState(false);
const calendarRef = useRef<{ getApi: () => { prev: () => void; next: () => void; today: () => void; changeView: (view: string) => void; getDate: () => Date } } | null>(null);
// Auto-open appointment modal when navigating from a report
useEffect(() => {
if (highlightEncounterId && initialEvents.length > 0) {
const eventToOpen = initialEvents.find((e) => e.id === highlightEncounterId);
if (eventToOpen) {
setEditingEvent(eventToOpen);
setIsModalOpen(true);
}
}
}, [highlightEncounterId, initialEvents]);
// Fetch events when date range changes
const fetchEvents = useCallback(async (start: Date, end: Date) => {
startTransition(async () => {
@@ -75,42 +106,52 @@ export function AgendaView({ initialEvents, initialDate }: AgendaViewProps) {
fetchEvents(start, end);
}, [fetchEvents]);
// Handle event click
// Handle event click - open edit modal
const handleEventClick = useCallback((event: CalendarEvent) => {
// TODO: Open appointment details modal
toast({
title: `Afspraak: ${event.title}`,
description: event.extendedProps.encounter.type_display,
});
setEditingEvent(event);
setIsModalOpen(true);
}, []);
// Handle date selection (for creating new appointment)
const handleDateSelect = useCallback((start: Date, end: Date) => {
// TODO: Open new appointment modal with pre-filled dates
toast({
title: 'Nieuwe afspraak',
description: `${format(start, 'HH:mm')} - ${format(end, 'HH:mm')}`,
});
setEditingEvent(undefined);
setModalInitialDate(start);
setModalInitialStartTime(format(start, 'HH:mm'));
setModalInitialEndTime(format(end, 'HH:mm'));
setIsModalOpen(true);
}, []);
// Handle event drag-and-drop
const handleEventDrop = useCallback(async (
// Handle event drag-and-drop - show confirmation dialog
const handleEventDrop = useCallback((
eventId: string,
newStart: Date,
newEnd: Date | null
) => {
const event = events.find((e) => e.id === eventId);
if (event) {
setPendingReschedule({ event, newStart, newEnd });
}
}, [events]);
// Confirm reschedule
const confirmReschedule = useCallback(async () => {
if (!pendingReschedule) return;
setIsRescheduling(true);
const { event, newStart, newEnd } = pendingReschedule;
const result = await rescheduleEncounter(
eventId,
event.id,
newStart.toISOString(),
newEnd?.toISOString() || null
);
if (result.success) {
toast({ title: 'Afspraak verzet' });
// Update local state optimistically
// Update local state
setEvents((prev) =>
prev.map((e) =>
e.id === eventId
e.id === event.id
? { ...e, start: newStart, end: newEnd || undefined }
: e
)
@@ -126,13 +167,39 @@ export function AgendaView({ initialEvents, initialDate }: AgendaViewProps) {
const end = endOfWeek(currentDate, { weekStartsOn: 1 });
fetchEvents(start, end);
}
setIsRescheduling(false);
setPendingReschedule(null);
}, [pendingReschedule, currentDate, fetchEvents]);
// Cancel reschedule - revert the visual change
const cancelReschedule = useCallback(() => {
// Refresh events to revert the visual drag
const start = startOfWeek(currentDate, { weekStartsOn: 1 });
const end = endOfWeek(currentDate, { weekStartsOn: 1 });
fetchEvents(start, end);
setPendingReschedule(null);
}, [currentDate, fetchEvents]);
// Handle new appointment button
const handleNewAppointment = useCallback(() => {
// TODO: Open new appointment modal
toast({ title: 'Nieuwe afspraak modal (nog te implementeren)' });
}, []);
setEditingEvent(undefined);
setModalInitialDate(currentDate);
setModalInitialStartTime('09:00');
setModalInitialEndTime('10:00');
setIsModalOpen(true);
}, [currentDate]);
// Handle modal success (refresh events)
const handleModalSuccess = useCallback(() => {
const start = currentView === 'timeGridDay'
? currentDate
: startOfWeek(currentDate, { weekStartsOn: 1 });
const end = currentView === 'timeGridDay'
? addDays(currentDate, 1)
: endOfWeek(currentDate, { weekStartsOn: 1 });
fetchEvents(start, end);
}, [currentDate, currentView, fetchEvents]);
return (
<div className="flex flex-col h-[calc(100vh-8rem)]">
@@ -159,6 +226,35 @@ export function AgendaView({ initialEvents, initialDate }: AgendaViewProps) {
onDateChange={handleDateChange}
/>
</div>
{/* Appointment Modal */}
<AppointmentModal
open={isModalOpen}
onOpenChange={setIsModalOpen}
initialDate={modalInitialDate}
initialStartTime={modalInitialStartTime}
initialEndTime={modalInitialEndTime}
editingEvent={editingEvent}
onSuccess={handleModalSuccess}
/>
{/* Reschedule Confirmation Dialog */}
{pendingReschedule && (
<RescheduleDialog
open={!!pendingReschedule}
onOpenChange={(open) => {
if (!open) cancelReschedule();
}}
patientName={pendingReschedule.event.title}
appointmentType={pendingReschedule.event.extendedProps.encounter.type_display}
oldStart={new Date(pendingReschedule.event.start)}
oldEnd={pendingReschedule.event.end ? new Date(pendingReschedule.event.end) : null}
newStart={pendingReschedule.newStart}
newEnd={pendingReschedule.newEnd}
onConfirm={confirmReschedule}
isLoading={isRescheduling}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,777 @@
'use client';
/**
* Appointment Modal Component
*
* Modal for creating and editing appointments (encounters).
*/
import { useState, useEffect, useCallback } from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, Clock, User, MapPin, FileText, Search, X, Trash2, PenLine } from 'lucide-react';
import Link from 'next/link';
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { toast } from '@/hooks/use-toast';
import { createEncounter, updateEncounter, cancelEncounter, getEncounterReports } from '../actions';
import { CancelDialog } from './cancel-dialog';
import {
APPOINTMENT_TYPES,
LOCATION_CLASSES,
type AppointmentTypeCode,
type LocationClassCode,
type CalendarEvent,
} from '../types';
interface Patient {
id: string;
name_family: string;
name_given: string[];
birth_date: string;
identifier_bsn?: string;
identifier_client_number?: string;
}
interface LinkedReport {
id: string;
type: string;
content: string;
created_at: string;
}
interface AppointmentModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
initialDate?: Date;
initialStartTime?: string;
initialEndTime?: string;
editingEvent?: CalendarEvent;
onSuccess?: () => void;
}
const inputClassName = "w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-teal-500 focus:border-transparent text-sm";
const selectClassName = "w-full px-3 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-teal-500 focus:border-transparent text-sm bg-white";
const labelClassName = "block text-sm font-medium text-slate-700 mb-1";
export function AppointmentModal({
open,
onOpenChange,
initialDate,
initialStartTime,
initialEndTime,
editingEvent,
onSuccess,
}: AppointmentModalProps) {
const [isSubmitting, setIsSubmitting] = useState(false);
const [patientSearch, setPatientSearch] = useState('');
const [patients, setPatients] = useState<Patient[]>([]);
const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [showPatientDropdown, setShowPatientDropdown] = useState(false);
// Recent patients
const [recentPatients, setRecentPatients] = useState<Patient[]>([]);
const [isInputFocused, setIsInputFocused] = useState(false);
// Cancel dialog state
const [showCancelDialog, setShowCancelDialog] = useState(false);
const [isCancelling, setIsCancelling] = useState(false);
// Linked reports state
const [linkedReports, setLinkedReports] = useState<LinkedReport[]>([]);
const [isLoadingReports, setIsLoadingReports] = useState(false);
// Form state
const [date, setDate] = useState<string>(
initialDate ? format(initialDate, 'yyyy-MM-dd') : format(new Date(), 'yyyy-MM-dd')
);
const [startTime, setStartTime] = useState<string>(initialStartTime || '09:00');
const [endTime, setEndTime] = useState<string>(initialEndTime || '10:00');
const [typeCode, setTypeCode] = useState<AppointmentTypeCode>('behandeling');
const [classCode, setClassCode] = useState<LocationClassCode>('AMB');
const [notes, setNotes] = useState<string>('');
// Determine if we're in edit mode
const isEditMode = !!editingEvent;
// Reset form when modal opens/closes
useEffect(() => {
if (open) {
if (editingEvent) {
// Edit mode: pre-fill from existing event
const encounter = editingEvent.extendedProps.encounter;
const patient = editingEvent.extendedProps.patient;
// Set patient
if (patient) {
setSelectedPatient(patient as Patient);
setPatientSearch(`${patient.name_given?.[0] || ''} ${patient.name_family || ''}`.trim());
}
// Set date/time
const startDate = new Date(encounter.period_start);
setDate(format(startDate, 'yyyy-MM-dd'));
setStartTime(format(startDate, 'HH:mm'));
if (encounter.period_end) {
const endDate = new Date(encounter.period_end);
setEndTime(format(endDate, 'HH:mm'));
} else {
setEndTime('');
}
// Set type and location
setTypeCode((encounter.type_code as AppointmentTypeCode) || 'behandeling');
setClassCode((encounter.class_code as LocationClassCode) || 'AMB');
setNotes(encounter.notes || '');
} else {
// Create mode: use initial values
if (initialDate) {
setDate(format(initialDate, 'yyyy-MM-dd'));
}
if (initialStartTime) {
setStartTime(initialStartTime);
}
if (initialEndTime) {
setEndTime(initialEndTime);
}
}
} else {
// Reset on close
setSelectedPatient(null);
setPatientSearch('');
setNotes('');
setTypeCode('behandeling');
setClassCode('AMB');
setLinkedReports([]);
}
}, [open, initialDate, initialStartTime, initialEndTime, editingEvent]);
// Fetch linked reports when editing an appointment
useEffect(() => {
if (open && editingEvent) {
setIsLoadingReports(true);
getEncounterReports(editingEvent.id)
.then((reports) => {
setLinkedReports(reports);
})
.catch((error) => {
console.error('Failed to fetch linked reports:', error);
})
.finally(() => {
setIsLoadingReports(false);
});
}
}, [open, editingEvent]);
// Fetch recent patients (last 5 by updated_at)
const fetchRecentPatients = useCallback(async () => {
try {
const response = await fetch('/api/fhir/Patient?_count=5');
if (response.ok) {
const data = await response.json();
const mappedPatients = data.entry?.map((e: { resource: unknown }) =>
mapFhirPatient(e.resource as Parameters<typeof mapFhirPatient>[0])
) || [];
setRecentPatients(mappedPatients);
}
} catch (error) {
console.error('Failed to fetch recent patients:', error);
}
}, []);
// Fetch recent patients when modal opens (for new appointments)
useEffect(() => {
if (open && !editingEvent) {
fetchRecentPatients();
}
}, [open, editingEvent, fetchRecentPatients]);
// Map FHIR Patient to internal format
const mapFhirPatient = (fhirPatient: {
id: string;
name?: Array<{ family?: string; given?: string[] }>;
birthDate?: string;
identifier?: Array<{ system?: string; value?: string }>;
}): Patient => {
const bsnIdentifier = fhirPatient.identifier?.find(
(id) => id.system === 'http://fhir.nl/fhir/NamingSystem/bsn'
);
const clientNumberIdentifier = fhirPatient.identifier?.find(
(id) => id.system?.includes('client') || id.system?.includes('999.7.6')
);
return {
id: fhirPatient.id,
name_family: fhirPatient.name?.[0]?.family || '',
name_given: fhirPatient.name?.[0]?.given || [],
birth_date: fhirPatient.birthDate || '',
identifier_bsn: bsnIdentifier?.value,
identifier_client_number: clientNumberIdentifier?.value,
};
};
// Search patients
const searchPatients = useCallback(async (query: string) => {
if (query.length < 2) {
setPatients([]);
return;
}
setIsSearching(true);
try {
// Use general search parameter that searches name, BSN, and client number
const response = await fetch(`/api/fhir/Patient?q=${encodeURIComponent(query)}`);
if (response.ok) {
const data = await response.json();
const mappedPatients = data.entry?.map((e: { resource: unknown }) =>
mapFhirPatient(e.resource as Parameters<typeof mapFhirPatient>[0])
) || [];
setPatients(mappedPatients);
}
} catch (error) {
console.error('Failed to search patients:', error);
} finally {
setIsSearching(false);
}
}, []);
// Debounced search - only search when no patient is selected
useEffect(() => {
// Skip search if patient is already selected
if (selectedPatient) {
setShowPatientDropdown(false);
return;
}
const timer = setTimeout(() => {
if (patientSearch.length >= 2) {
searchPatients(patientSearch);
setShowPatientDropdown(true);
} else {
setPatients([]);
setShowPatientDropdown(false);
}
}, 300);
return () => clearTimeout(timer);
}, [patientSearch, searchPatients, selectedPatient]);
// Handle patient selection
const handleSelectPatient = (patient: Patient) => {
setSelectedPatient(patient);
setPatientSearch(`${patient.name_given?.[0] || ''} ${patient.name_family || ''}`.trim());
setShowPatientDropdown(false);
};
// Handle form submission
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedPatient && !isEditMode) {
toast({
variant: 'destructive',
title: 'Selecteer een patiënt',
description: 'Kies een patiënt uit de zoekresultaten.',
});
return;
}
setIsSubmitting(true);
try {
const periodStart = `${date}T${startTime}:00`;
const periodEnd = endTime ? `${date}T${endTime}:00` : null;
if (isEditMode && editingEvent) {
// Update existing encounter
const result = await updateEncounter(editingEvent.id, {
periodStart,
periodEnd,
typeCode,
typeDisplay: APPOINTMENT_TYPES[typeCode],
classCode,
classDisplay: LOCATION_CLASSES[classCode],
notes: notes || '',
});
if (result.success) {
toast({
title: 'Afspraak bijgewerkt',
description: `${APPOINTMENT_TYPES[typeCode]} is aangepast.`,
});
onOpenChange(false);
onSuccess?.();
} else {
toast({
variant: 'destructive',
title: 'Bewerken mislukt',
description: result.error,
});
}
} else {
// Create new encounter
const result = await createEncounter({
patientId: selectedPatient!.id,
practitionerId: '', // TODO: Get current practitioner
periodStart,
periodEnd: periodEnd || undefined,
typeCode,
typeDisplay: APPOINTMENT_TYPES[typeCode],
classCode,
classDisplay: LOCATION_CLASSES[classCode],
notes: notes || undefined,
});
if (result.success) {
toast({
title: 'Afspraak aangemaakt',
description: `${APPOINTMENT_TYPES[typeCode]} met ${selectedPatient!.name_given?.[0] || ''} ${selectedPatient!.name_family || ''}`.trim(),
});
onOpenChange(false);
onSuccess?.();
} else {
toast({
variant: 'destructive',
title: 'Afspraak aanmaken mislukt',
description: result.error,
});
}
}
} catch (error) {
toast({
variant: 'destructive',
title: 'Er ging iets mis',
description: 'Probeer het opnieuw.',
});
} finally {
setIsSubmitting(false);
}
};
// Handle cancel appointment
const handleCancelAppointment = async () => {
if (!editingEvent) return;
setIsCancelling(true);
try {
const result = await cancelEncounter(editingEvent.id);
if (result.success) {
toast({
title: 'Afspraak geannuleerd',
description: 'De afspraak is succesvol geannuleerd.',
});
setShowCancelDialog(false);
onOpenChange(false);
onSuccess?.();
} else {
toast({
variant: 'destructive',
title: 'Annuleren mislukt',
description: result.error,
});
}
} catch {
toast({
variant: 'destructive',
title: 'Er ging iets mis',
description: 'Probeer het opnieuw.',
});
} finally {
setIsCancelling(false);
}
};
const formatPatientName = (patient: Patient) => {
const name = `${patient.name_given?.[0] || ''} ${patient.name_family || ''}`.trim();
const birthDate = patient.birth_date
? format(new Date(patient.birth_date), 'd MMM yyyy', { locale: nl })
: '';
// Show client number or BSN (prefer client number)
const identifier = patient.identifier_client_number
? `#${patient.identifier_client_number}`
: patient.identifier_bsn
? `BSN ${patient.identifier_bsn.slice(-4)}`
: '';
return { name, birthDate, identifier };
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px]">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Calendar className="h-5 w-5 text-teal-600" />
{editingEvent ? 'Afspraak bewerken' : 'Nieuwe Afspraak'}
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 mt-2">
{/* Patient Search */}
<div className="relative">
<label className={labelClassName}>
<User className="h-4 w-4 inline mr-1" />
Patiënt *
</label>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
<input
type="text"
value={patientSearch}
onChange={(e) => {
setPatientSearch(e.target.value);
if (selectedPatient) {
setSelectedPatient(null);
}
}}
onFocus={() => setIsInputFocused(true)}
onBlur={() => {
// Delay to allow click on dropdown items
setTimeout(() => setIsInputFocused(false), 200);
}}
placeholder="Zoek op naam, BSN of clientnummer..."
className={`${inputClassName} pl-9`}
required
/>
{selectedPatient && (
<button
type="button"
onClick={() => {
setSelectedPatient(null);
setPatientSearch('');
}}
className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
<X className="h-4 w-4" />
</button>
)}
</div>
{/* Patient Dropdown */}
{showPatientDropdown && patients.length > 0 && (
<div className="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg max-h-48 overflow-auto">
{patients.map((patient) => {
const { name, birthDate, identifier } = formatPatientName(patient);
return (
<button
key={patient.id}
type="button"
onClick={() => handleSelectPatient(patient)}
className="w-full px-3 py-2 text-left hover:bg-slate-50"
>
<div className="flex justify-between items-center">
<span className="font-medium text-sm">{name}</span>
<span className="text-xs text-slate-500">{birthDate}</span>
</div>
{identifier && (
<div className="text-xs text-slate-400">{identifier}</div>
)}
</button>
);
})}
</div>
)}
{isSearching && (
<div className="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg p-3 text-center text-sm text-slate-500">
Zoeken...
</div>
)}
{showPatientDropdown && patients.length === 0 && patientSearch.length >= 2 && !isSearching && (
<div className="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg p-3 text-center text-sm text-slate-500">
Geen patiënten gevonden
</div>
)}
{/* Recent Patients Dropdown - shown when focused but no search query */}
{isInputFocused && !selectedPatient && patientSearch.length < 2 && recentPatients.length > 0 && !isEditMode && (
<div className="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg max-h-48 overflow-auto">
<div className="px-3 py-2 border-b border-slate-100 text-xs font-medium text-slate-500 uppercase tracking-wide">
Recente patiënten
</div>
{recentPatients.map((patient) => {
const { name, birthDate, identifier } = formatPatientName(patient);
return (
<button
key={patient.id}
type="button"
onClick={() => handleSelectPatient(patient)}
className="w-full px-3 py-2 text-left hover:bg-slate-50"
>
<div className="flex justify-between items-center">
<span className="font-medium text-sm">{name}</span>
<span className="text-xs text-slate-500">{birthDate}</span>
</div>
{identifier && (
<div className="text-xs text-slate-400">{identifier}</div>
)}
</button>
);
})}
</div>
)}
</div>
{/* Quick Patient Info Card - shown when patient is selected */}
{selectedPatient && (
<div className="mt-2 p-3 bg-teal-50 rounded-lg border border-teal-100">
<div className="flex items-start justify-between">
<div>
<div className="font-medium text-slate-900">
{selectedPatient.name_given?.[0]} {selectedPatient.name_family}
</div>
<div className="text-sm text-slate-600 mt-0.5">
Geb. {selectedPatient.birth_date
? format(new Date(selectedPatient.birth_date), 'd MMMM yyyy', { locale: nl })
: 'Onbekend'}
</div>
{selectedPatient.identifier_client_number && (
<div className="text-xs text-slate-500 mt-0.5">
Clientnr: {selectedPatient.identifier_client_number}
</div>
)}
{selectedPatient.identifier_bsn && !selectedPatient.identifier_client_number && (
<div className="text-xs text-slate-500 mt-0.5">
BSN: ***{selectedPatient.identifier_bsn.slice(-4)}
</div>
)}
</div>
<button
type="button"
onClick={() => {
setSelectedPatient(null);
setPatientSearch('');
}}
className="text-slate-400 hover:text-slate-600 p-1"
>
<X className="h-4 w-4" />
</button>
</div>
</div>
)}
{/* Date and Time */}
<div className="grid grid-cols-3 gap-3">
<div>
<label className={labelClassName}>
<Calendar className="h-4 w-4 inline mr-1" />
Datum *
</label>
<input
type="date"
value={date}
onChange={(e) => setDate(e.target.value)}
className={inputClassName}
required
/>
</div>
<div>
<label className={labelClassName}>
<Clock className="h-4 w-4 inline mr-1" />
Van *
</label>
<input
type="time"
value={startTime}
onChange={(e) => setStartTime(e.target.value)}
className={inputClassName}
required
/>
</div>
<div>
<label className={labelClassName}>
<Clock className="h-4 w-4 inline mr-1" />
Tot
</label>
<input
type="time"
value={endTime}
onChange={(e) => setEndTime(e.target.value)}
className={inputClassName}
/>
</div>
</div>
{/* Type and Location */}
<div className="grid grid-cols-2 gap-3">
<div>
<label className={labelClassName}>Type afspraak *</label>
<select
value={typeCode}
onChange={(e) => setTypeCode(e.target.value as AppointmentTypeCode)}
className={selectClassName}
required
>
{Object.entries(APPOINTMENT_TYPES).map(([code, label]) => (
<option key={code} value={code}>
{label}
</option>
))}
</select>
</div>
<div>
<label className={labelClassName}>
<MapPin className="h-4 w-4 inline mr-1" />
Locatie
</label>
<select
value={classCode}
onChange={(e) => setClassCode(e.target.value as LocationClassCode)}
className={selectClassName}
>
{Object.entries(LOCATION_CLASSES).map(([code, label]) => (
<option key={code} value={code}>
{label}
</option>
))}
</select>
</div>
</div>
{/* Notes */}
<div>
<label className={labelClassName}>
<FileText className="h-4 w-4 inline mr-1" />
Notities
</label>
<textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
placeholder="Optionele notities voor deze afspraak..."
rows={3}
className={`${inputClassName} resize-none`}
/>
</div>
{/* Linked Reports Section - only shown in edit mode */}
{isEditMode && (
<div className="border-t border-slate-200 pt-4">
<label className={labelClassName}>
<FileText className="h-4 w-4 inline mr-1" />
Gekoppelde verslagen
</label>
{isLoadingReports ? (
<div className="text-sm text-slate-500 py-2">Verslagen laden...</div>
) : linkedReports.length === 0 ? (
<div className="text-sm text-slate-400 py-2 italic">
Geen verslagen gekoppeld aan deze afspraak
</div>
) : (
<div className="space-y-2 mt-2">
{linkedReports.map((report) => {
const reportDate = new Date(report.created_at);
const TYPE_LABELS: Record<string, string> = {
behandeladvies: 'Behandeladvies',
vrije_notitie: 'Vrije notitie',
intake: 'Intake verslag',
voortgang: 'Voortgangsverslag',
crisis: 'Crisis notitie',
contact: 'Contactnotitie',
};
return (
<Link
key={report.id}
href={`/epd/patients/${editingEvent?.extendedProps.patient?.id}/rapportage?reportId=${report.id}`}
className="block p-3 bg-slate-50 hover:bg-slate-100 rounded-lg border border-slate-200 transition-colors"
>
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-slate-700">
{TYPE_LABELS[report.type] || report.type}
</span>
<span className="text-xs text-slate-500">
{format(reportDate, 'd MMM yyyy', { locale: nl })}
</span>
</div>
<p className="text-xs text-slate-500 mt-1 line-clamp-2">
{report.content.substring(0, 100)}
{report.content.length > 100 ? '...' : ''}
</p>
</Link>
);
})}
</div>
)}
</div>
)}
<DialogFooter className="flex justify-between sm:justify-between gap-2">
{isEditMode && editingEvent?.extendedProps.patient && (
<div className="flex gap-2 mr-auto">
<Button
type="button"
variant="destructive"
onClick={() => setShowCancelDialog(true)}
disabled={isSubmitting}
>
<Trash2 className="h-4 w-4 mr-1" />
Annuleren
</Button>
<Button
type="button"
variant="outline"
asChild
>
<Link
href={`/epd/patients/${editingEvent.extendedProps.patient.id}/rapportage?encounterId=${editingEvent.id}`}
>
<PenLine className="h-4 w-4 mr-1" />
Maak verslag
</Link>
</Button>
</div>
)}
{isEditMode && !editingEvent?.extendedProps.patient && (
<Button
type="button"
variant="destructive"
onClick={() => setShowCancelDialog(true)}
disabled={isSubmitting}
className="mr-auto"
>
<Trash2 className="h-4 w-4 mr-1" />
Annuleren
</Button>
)}
<div className="flex gap-2">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSubmitting}
>
Sluiten
</Button>
<Button type="submit" disabled={isSubmitting || (!selectedPatient && !isEditMode)}>
{isSubmitting ? 'Opslaan...' : isEditMode ? 'Wijzigingen opslaan' : 'Afspraak maken'}
</Button>
</div>
</DialogFooter>
</form>
{/* Cancel Confirmation Dialog */}
{editingEvent && (
<CancelDialog
open={showCancelDialog}
onOpenChange={setShowCancelDialog}
patientName={editingEvent.title}
appointmentType={editingEvent.extendedProps.encounter.type_display}
appointmentDate={new Date(editingEvent.start)}
onConfirm={handleCancelAppointment}
isLoading={isCancelling}
/>
)}
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,95 @@
'use client';
/**
* Cancel Appointment Confirmation Dialog
*
* Confirms appointment cancellation (soft delete).
*/
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { AlertTriangle, Calendar } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface CancelDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
patientName: string;
appointmentType: string;
appointmentDate: Date;
onConfirm: () => void;
isLoading?: boolean;
}
export function CancelDialog({
open,
onOpenChange,
patientName,
appointmentType,
appointmentDate,
onConfirm,
isLoading,
}: CancelDialogProps) {
const formatDateTime = (date: Date) => {
return format(date, "EEEE d MMMM 'om' HH:mm", { locale: nl });
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2 text-red-600">
<AlertTriangle className="h-5 w-5" />
Afspraak annuleren
</DialogTitle>
<DialogDescription asChild>
<div className="space-y-4 pt-2">
<p>
Weet je zeker dat je deze afspraak wilt annuleren? Deze actie kan
niet ongedaan worden gemaakt.
</p>
<div className="bg-red-50 rounded-lg p-4 border border-red-100">
<div className="flex items-start gap-3">
<Calendar className="h-5 w-5 text-red-600 mt-0.5" />
<div>
<div className="font-medium text-slate-900">{patientName}</div>
<div className="text-sm text-slate-600">{appointmentType}</div>
<div className="text-sm text-slate-500 mt-1">
{formatDateTime(appointmentDate)}
</div>
</div>
</div>
</div>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
Terug
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isLoading}
>
{isLoading ? 'Annuleren...' : 'Afspraak annuleren'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,118 @@
'use client';
/**
* Reschedule Confirmation Dialog
*
* Confirms appointment rescheduling after drag-and-drop.
*/
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, Clock, ArrowRight } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface RescheduleDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
patientName: string;
appointmentType: string;
oldStart: Date;
oldEnd: Date | null;
newStart: Date;
newEnd: Date | null;
onConfirm: () => void;
isLoading?: boolean;
}
export function RescheduleDialog({
open,
onOpenChange,
patientName,
appointmentType,
oldStart,
oldEnd,
newStart,
newEnd,
onConfirm,
isLoading,
}: RescheduleDialogProps) {
const formatDateTime = (date: Date) => {
return format(date, "EEEE d MMMM 'om' HH:mm", { locale: nl });
};
const formatTime = (date: Date) => {
return format(date, 'HH:mm');
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Calendar className="h-5 w-5 text-teal-600" />
Afspraak verzetten
</DialogTitle>
<DialogDescription asChild>
<div className="space-y-4 pt-2">
<p>
Weet je zeker dat je de afspraak van <strong>{patientName}</strong>{' '}
({appointmentType}) wilt verzetten?
</p>
<div className="bg-slate-50 rounded-lg p-4 space-y-3">
<div className="flex items-center gap-3">
<div className="flex-1 text-center">
<div className="text-xs text-slate-500 mb-1">Van</div>
<div className="text-sm font-medium text-slate-700">
{formatDateTime(oldStart)}
</div>
{oldEnd && (
<div className="text-xs text-slate-500">
<Clock className="h-3 w-3 inline mr-1" />
{formatTime(oldStart)} - {formatTime(oldEnd)}
</div>
)}
</div>
<ArrowRight className="h-5 w-5 text-teal-600 flex-shrink-0" />
<div className="flex-1 text-center">
<div className="text-xs text-slate-500 mb-1">Naar</div>
<div className="text-sm font-medium text-teal-700">
{formatDateTime(newStart)}
</div>
{newEnd && (
<div className="text-xs text-slate-500">
<Clock className="h-3 w-3 inline mr-1" />
{formatTime(newStart)} - {formatTime(newEnd)}
</div>
)}
</div>
</div>
</div>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2 sm:gap-0">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isLoading}
>
Annuleren
</Button>
<Button onClick={onConfirm} disabled={isLoading}>
{isLoading ? 'Verzetten...' : 'Verzetten'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View File

@@ -5,15 +5,29 @@
* Supports day, week, and workweek views.
*/
import { startOfWeek, endOfWeek } from 'date-fns';
import { startOfWeek, endOfWeek, parseISO, isValid } from 'date-fns';
import { AgendaView } from './components/agenda-view';
import { getEncounters } from './actions';
export default async function AgendaPage() {
// Get initial date range (current week)
const now = new Date();
const start = startOfWeek(now, { weekStartsOn: 1 });
const end = endOfWeek(now, { weekStartsOn: 1 });
interface AgendaPageProps {
searchParams: Promise<{ date?: string; encounterId?: string }>;
}
export default async function AgendaPage({ searchParams }: AgendaPageProps) {
const { date: dateParam, encounterId } = await searchParams;
// Parse date from URL or use current date
let targetDate = new Date();
if (dateParam) {
const parsedDate = parseISO(dateParam);
if (isValid(parsedDate)) {
targetDate = parsedDate;
}
}
// Get initial date range (week of target date)
const start = startOfWeek(targetDate, { weekStartsOn: 1 });
const end = endOfWeek(targetDate, { weekStartsOn: 1 });
// Fetch initial events
const initialEvents = await getEncounters({
@@ -24,7 +38,8 @@ export default async function AgendaPage() {
return (
<AgendaView
initialEvents={initialEvents}
initialDate={now}
initialDate={targetDate}
highlightEncounterId={encounterId}
/>
);
}

View File

@@ -58,7 +58,7 @@ export async function createReport(
export async function updateReport(
patientId: string,
reportId: string,
input: { content: string }
input: { content?: string; encounter_id?: string | null }
): Promise<Report> {
const baseUrl = getBaseUrl();
const url = `${baseUrl}/api/reports/${reportId}`;

View File

@@ -0,0 +1,208 @@
'use client';
import { useState, useEffect } from 'react';
import { format } from 'date-fns';
import { nl } from 'date-fns/locale';
import { Calendar, Link2, Link2Off, ChevronDown, Loader2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { getPatientEncounters } from '@/app/epd/agenda/actions';
interface Encounter {
id: string;
period_start: string;
period_end: string | null;
type_code: string;
type_display: string;
status: string;
notes: string | null;
}
interface EncounterSelectorProps {
patientId: string;
value?: string | null;
onChange: (encounterId: string | null) => void;
disabled?: boolean;
}
const TYPE_LABELS: Record<string, string> = {
intake: 'Intake',
behandeling: 'Behandeling',
'follow-up': 'Follow-up',
telefonisch: 'Telefonisch',
huisbezoek: 'Huisbezoek',
online: 'Online consult',
crisis: 'Crisis',
overig: 'Overig',
};
export function EncounterSelector({
patientId,
value,
onChange,
disabled = false,
}: EncounterSelectorProps) {
const [encounters, setEncounters] = useState<Encounter[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isOpen, setIsOpen] = useState(false);
const [hasLoaded, setHasLoaded] = useState(false);
// Load encounters when dropdown opens
useEffect(() => {
if (isOpen && !hasLoaded) {
setIsLoading(true);
getPatientEncounters(patientId)
.then((data) => {
setEncounters(data);
setHasLoaded(true);
})
.catch((error) => {
console.error('Failed to load encounters:', error);
})
.finally(() => {
setIsLoading(false);
});
}
}, [isOpen, hasLoaded, patientId]);
const selectedEncounter = encounters.find((e) => e.id === value);
const formatEncounterDate = (dateStr: string) => {
const date = new Date(dateStr);
return format(date, "d MMM yyyy 'om' HH:mm", { locale: nl });
};
const handleSelect = (encounterId: string | null) => {
onChange(encounterId);
setIsOpen(false);
};
return (
<div className="relative">
<button
type="button"
onClick={() => !disabled && setIsOpen(!isOpen)}
disabled={disabled}
className={cn(
'w-full flex items-center justify-between gap-2 px-3 py-2 text-left',
'border rounded-lg text-sm transition-colors',
disabled
? 'bg-slate-100 text-slate-400 cursor-not-allowed'
: 'bg-white hover:bg-slate-50',
value
? 'border-teal-300 bg-teal-50'
: 'border-slate-200'
)}
>
<div className="flex items-center gap-2 flex-1 min-w-0">
{value ? (
<Link2 className="h-4 w-4 text-teal-600 shrink-0" />
) : (
<Calendar className="h-4 w-4 text-slate-400 shrink-0" />
)}
<span className={cn('truncate', value ? 'text-teal-700' : 'text-slate-500')}>
{selectedEncounter
? `${TYPE_LABELS[selectedEncounter.type_code] || selectedEncounter.type_display} - ${formatEncounterDate(selectedEncounter.period_start)}`
: 'Koppel aan afspraak...'}
</span>
</div>
<ChevronDown
className={cn(
'h-4 w-4 shrink-0 transition-transform',
isOpen && 'rotate-180',
value ? 'text-teal-600' : 'text-slate-400'
)}
/>
</button>
{/* Dropdown */}
{isOpen && (
<>
{/* Backdrop */}
<div
className="fixed inset-0 z-40"
onClick={() => setIsOpen(false)}
/>
{/* Menu */}
<div className="absolute z-50 w-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg max-h-64 overflow-auto">
{isLoading ? (
<div className="flex items-center justify-center gap-2 py-4 text-sm text-slate-500">
<Loader2 className="h-4 w-4 animate-spin" />
Afspraken laden...
</div>
) : encounters.length === 0 ? (
<div className="py-4 px-3 text-sm text-slate-500 text-center">
Geen afspraken gevonden
</div>
) : (
<>
{/* Option to unlink */}
{value && (
<button
type="button"
onClick={() => handleSelect(null)}
className="w-full px-3 py-2 text-left hover:bg-red-50 flex items-center gap-2 text-red-600 border-b border-slate-100"
>
<Link2Off className="h-4 w-4" />
<span className="text-sm">Koppeling verwijderen</span>
</button>
)}
{/* Encounters list */}
{encounters.map((encounter) => {
const isSelected = encounter.id === value;
return (
<button
key={encounter.id}
type="button"
onClick={() => handleSelect(encounter.id)}
className={cn(
'w-full px-3 py-2 text-left hover:bg-slate-50',
isSelected && 'bg-teal-50'
)}
>
<div className="flex items-center justify-between">
<span
className={cn(
'text-sm font-medium',
isSelected ? 'text-teal-700' : 'text-slate-900'
)}
>
{TYPE_LABELS[encounter.type_code] || encounter.type_display}
</span>
<span
className={cn(
'text-xs px-1.5 py-0.5 rounded',
encounter.status === 'completed'
? 'bg-emerald-100 text-emerald-700'
: encounter.status === 'planned'
? 'bg-blue-100 text-blue-700'
: 'bg-slate-100 text-slate-600'
)}
>
{encounter.status === 'completed'
? 'Afgerond'
: encounter.status === 'planned'
? 'Gepland'
: encounter.status}
</span>
</div>
<div className="text-xs text-slate-500 mt-0.5">
{formatEncounterDate(encounter.period_start)}
</div>
{encounter.notes && (
<div className="text-xs text-slate-400 mt-0.5 truncate">
{encounter.notes}
</div>
)}
</button>
);
})}
</>
)}
</div>
</>
)}
</div>
);
}

View File

@@ -2,7 +2,7 @@
import { useState, useCallback, useEffect } from 'react'
import dynamic from 'next/dynamic'
import { ChevronRight, ChevronLeft } from 'lucide-react'
import { ChevronRight, ChevronLeft, Calendar } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { Report } from '@/lib/types/report'
import { ReportComposer } from './report-composer'
@@ -33,6 +33,7 @@ interface RapportageWorkspaceV2Props {
patientId: string
patientName: string
initialReports: Report[]
linkedEncounterId?: string
}
type PanelsModule = typeof import('react-resizable-panels')
@@ -45,6 +46,7 @@ export function RapportageWorkspaceV2({
patientId,
patientName,
initialReports,
linkedEncounterId,
}: RapportageWorkspaceV2Props) {
const [reports, setReports] = useState(initialReports)
const [selectedType, setSelectedType] = useState<ReportType>('vrije_notitie')
@@ -137,6 +139,13 @@ export function RapportageWorkspaceV2({
)}
</div>
{linkedEncounterId && (
<div className="mb-3 p-2 bg-teal-50 border border-teal-200 rounded-lg flex items-center gap-2 text-sm text-teal-700">
<Calendar className="h-4 w-4" />
<span>Dit verslag wordt gekoppeld aan de afspraak</span>
</div>
)}
<QuickActions onSelectType={handleTypeSelect} selectedType={selectedType} />
</div>
@@ -150,6 +159,7 @@ export function RapportageWorkspaceV2({
onReportCreated={handleReportCreated}
initialContent={duplicateContent}
onInitialContentConsumed={() => setDuplicateContent(null)}
linkedEncounterId={linkedEncounterId}
/>
</div>
</div>

View File

@@ -43,6 +43,8 @@ interface ReportComposerProps {
initialContent?: string | null;
/** Callback wanneer initialContent is verwerkt */
onInitialContentConsumed?: () => void;
/** Linked encounter ID for linking report to appointment */
linkedEncounterId?: string;
}
// ─────────────────────────────────────────────────────────────────────────────
@@ -58,6 +60,7 @@ export function ReportComposer({
onReportCreated,
initialContent,
onInitialContentConsumed,
linkedEncounterId,
}: ReportComposerProps) {
const router = useRouter();
const [editorRef, setEditorRef] = useState<Editor | null>(null);
@@ -221,6 +224,7 @@ export function ReportComposer({
content: textContent, // Save plain text for now
ai_confidence: classification?.confidence,
ai_reasoning: classification?.reasoning,
encounter_id: linkedEncounterId,
});
toast({
title: 'Rapportage opgeslagen',

View File

@@ -1,7 +1,8 @@
'use client'
import { useState, useEffect, useCallback, useRef } from 'react'
import { X, Pencil, Copy, Trash2, Save, Loader2 } from 'lucide-react'
import Link from 'next/link'
import { X, Pencil, Copy, Trash2, Save, Loader2, Calendar, ExternalLink } from 'lucide-react'
import { format, formatDistanceToNow } from 'date-fns'
import { nl } from 'date-fns/locale'
import { cn } from '@/lib/utils'
@@ -9,6 +10,17 @@ import type { Report } from '@/lib/types/report'
import { SpeechRecorderStreaming } from '@/components/speech-recorder-streaming'
import { toast } from '@/hooks/use-toast'
import { updateReport, deleteReport } from '../actions'
import { EncounterSelector } from './encounter-selector'
import { getEncounterById } from '@/app/epd/agenda/actions'
interface LinkedEncounter {
id: string
period_start: string
period_end: string | null
type_code: string
type_display: string
status: string
}
// ─────────────────────────────────────────────────────────────────────────────
// Types
@@ -179,12 +191,15 @@ export function ReportViewEditModal({
const [mode, setMode] = useState<ModalMode>('read')
const [content, setContent] = useState('')
const [originalContent, setOriginalContent] = useState('')
const [encounterId, setEncounterId] = useState<string | null>(null)
const [originalEncounterId, setOriginalEncounterId] = useState<string | null>(null)
const [linkedEncounter, setLinkedEncounter] = useState<LinkedEncounter | null>(null)
const [isSaving, setIsSaving] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [showUnsavedDialog, setShowUnsavedDialog] = useState(false)
const [showDeleteDialog, setShowDeleteDialog] = useState(false)
const [isStreaming, setIsStreaming] = useState(false)
const textareaRef = useRef<HTMLTextAreaElement>(null)
// Sync content met report
@@ -192,10 +207,23 @@ export function ReportViewEditModal({
if (report) {
setContent(report.content)
setOriginalContent(report.content)
setEncounterId(report.encounter_id || null)
setOriginalEncounterId(report.encounter_id || null)
setMode('read')
}
}, [report])
// Fetch linked encounter details for navigation
useEffect(() => {
if (encounterId) {
getEncounterById(encounterId).then((encounter) => {
setLinkedEncounter(encounter)
})
} else {
setLinkedEncounter(null)
}
}, [encounterId])
// Reset bij sluiten
useEffect(() => {
if (!isOpen) {
@@ -206,7 +234,7 @@ export function ReportViewEditModal({
}, [isOpen])
// Check for unsaved changes
const hasUnsavedChanges = content !== originalContent
const hasUnsavedChanges = content !== originalContent || encounterId !== originalEncounterId
// Keyboard handler (Escape)
// Handlers
@@ -254,8 +282,12 @@ export function ReportViewEditModal({
setIsSaving(true)
try {
const updated = await updateReport(patientId, report.id, { content })
const updated = await updateReport(patientId, report.id, {
content,
encounter_id: encounterId,
})
setOriginalContent(content)
setOriginalEncounterId(encounterId)
onReportUpdated?.(updated)
toast({
title: 'Wijzigingen opgeslagen',
@@ -271,7 +303,7 @@ export function ReportViewEditModal({
} finally {
setIsSaving(false)
}
}, [report, patientId, content, onReportUpdated])
}, [report, patientId, content, encounterId, onReportUpdated])
const handleSaveAndClose = useCallback(async () => {
await handleSave()
@@ -281,9 +313,10 @@ export function ReportViewEditModal({
const handleDiscardAndClose = useCallback(() => {
setContent(originalContent)
setEncounterId(originalEncounterId)
setShowUnsavedDialog(false)
onClose()
}, [originalContent, onClose])
}, [originalContent, originalEncounterId, onClose])
const handleDelete = useCallback(async () => {
if (!report) return
@@ -500,6 +533,58 @@ export function ReportViewEditModal({
)}
</div>
{/* Encounter linking */}
<div className="px-6 pb-4">
<div className="flex items-center gap-2 mb-2">
<Calendar className="h-4 w-4 text-slate-500" />
<span className="text-sm font-medium text-slate-700">Gekoppelde afspraak</span>
</div>
{mode === 'read' && linkedEncounter ? (
// Read mode with linked encounter - show clickable card
<Link
href={`/epd/agenda?date=${format(new Date(linkedEncounter.period_start), 'yyyy-MM-dd')}&encounterId=${linkedEncounter.id}`}
className="block p-3 bg-teal-50 hover:bg-teal-100 rounded-lg border border-teal-200 transition-colors group"
>
<div className="flex items-center justify-between">
<span className="text-sm font-medium text-teal-700">
{linkedEncounter.type_display || linkedEncounter.type_code}
</span>
<ExternalLink className="h-4 w-4 text-teal-500 opacity-0 group-hover:opacity-100 transition-opacity" />
</div>
<div className="text-xs text-teal-600 mt-0.5">
{format(new Date(linkedEncounter.period_start), "EEEE d MMMM yyyy 'om' HH:mm", { locale: nl })}
</div>
<div className="text-xs text-teal-500 mt-1 flex items-center gap-1">
<span className={cn(
'px-1.5 py-0.5 rounded text-xs',
linkedEncounter.status === 'completed' ? 'bg-emerald-100 text-emerald-700' :
linkedEncounter.status === 'planned' ? 'bg-blue-100 text-blue-700' :
'bg-slate-100 text-slate-600'
)}>
{linkedEncounter.status === 'completed' ? 'Afgerond' :
linkedEncounter.status === 'planned' ? 'Gepland' :
linkedEncounter.status}
</span>
<span className="text-teal-400"></span>
<span>Klik om naar agenda te gaan</span>
</div>
</Link>
) : mode === 'read' ? (
// Read mode without linked encounter
<div className="text-sm text-slate-400 py-2 italic">
Geen afspraak gekoppeld. Bewerk om een afspraak te koppelen.
</div>
) : (
// Edit mode - show selector
<EncounterSelector
patientId={patientId}
value={encounterId}
onChange={setEncounterId}
/>
)}
</div>
{/* Footer with metadata */}
{report.ai_reasoning && (
<div className="px-6 pb-6">

View File

@@ -4,10 +4,13 @@ import { getPatient } from '../../actions';
export default async function RapportagePage({
params,
searchParams,
}: {
params: Promise<{ id: string }>;
searchParams: Promise<{ encounterId?: string }>;
}) {
const { id } = await params;
const { encounterId } = await searchParams;
const [reports, patient] = await Promise.all([getReports(id), getPatient(id)]);
const patientName = formatPatientName(patient);
@@ -16,6 +19,7 @@ export default async function RapportagePage({
patientId={id}
patientName={patientName}
initialReports={reports}
linkedEncounterId={encounterId}
/>
);
}