feat(swift): voeg agenda backend API's toe (E3)

Epic 3 compleet: Backend integratie voor Swift Agenda Planning.

Nieuwe endpoints:
- GET /api/swift/agenda - Query afspraken op datumrange
- POST /api/swift/agenda/create - Nieuwe afspraak aanmaken
- POST /api/swift/agenda/cancel - Afspraak annuleren
- POST /api/swift/agenda/reschedule - Afspraak verzetten
- GET /api/swift/patients/search - Fuzzy patiënt zoeken

Alle endpoints bevatten:
- Supabase authenticatie + resource ownership checks
- Zod validatie met Nederlandse foutmeldingen
- Hergebruik van bestaande agenda server actions

Test documentatie: docs/swift/test-plan-epic3-backend.md

Progress: 3/7 Epics compleet (E0, E1, E2, E3)
Story points: 11 SP (E3.S1: 3, E3.S2: 3, E3.S3: 3, E3.S4: 2)
This commit is contained in:
colinislit
2025-12-27 22:12:01 +01:00
parent 6460b4361f
commit d2ffccc22b
7 changed files with 1093 additions and 9 deletions

View File

@@ -0,0 +1,104 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { cancelEncounter } from '@/app/epd/agenda/actions';
import { z } from 'zod';
/**
* Swift Cancel Appointment API
*
* POST /api/swift/agenda/cancel
*
* Cancels an appointment (soft delete: status → 'cancelled').
*/
// Request body schema
const CancelAppointmentSchema = z.object({
encounterId: z.string().uuid({ message: 'encounterId moet een geldige UUID zijn' }),
});
export async function POST(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate request body
const body = await request.json();
const validation = CancelAppointmentSchema.safeParse(body);
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => `${e.path.join('.')}: ${e.message}`)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
const { encounterId } = validation.data;
// Verify the encounter belongs to the current user (security check)
const { data: encounter, error: fetchError } = await supabase
.from('encounters')
.select('id, practitioner_id, patient_id, period_start, status')
.eq('id', encounterId)
.single();
if (fetchError || !encounter) {
return NextResponse.json(
{ error: 'Afspraak niet gevonden' },
{ status: 404 }
);
}
if (encounter.practitioner_id !== user.id) {
return NextResponse.json(
{ error: 'Je hebt geen toegang tot deze afspraak' },
{ status: 403 }
);
}
if (encounter.status === 'cancelled') {
return NextResponse.json(
{ error: 'Deze afspraak is al geannuleerd' },
{ status: 400 }
);
}
// Cancel the encounter
const result = await cancelEncounter(encounterId);
if (!result.success) {
return NextResponse.json(
{ error: result.error || 'Fout bij het annuleren van de afspraak' },
{ status: 500 }
);
}
return NextResponse.json(
{
success: true,
encounterId,
message: 'Afspraak succesvol geannuleerd',
},
{ status: 200 }
);
} catch (error) {
console.error('Error in cancel appointment API:', error);
return NextResponse.json(
{
error:
'Er ging iets mis bij het annuleren van de afspraak. Probeer het opnieuw.',
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,165 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { createEncounter } from '@/app/epd/agenda/actions';
import { z } from 'zod';
import { addHours } from 'date-fns';
/**
* Swift Create Appointment API
*
* POST /api/swift/agenda/create
*
* Creates a new appointment (encounter).
*/
// Type mappings (appointment type → FHIR encounter type)
const TYPE_MAPPINGS: Record<
string,
{ code: string; display: string }
> = {
intake: { code: 'intake', display: 'Intake' },
behandeling: { code: 'behandeling', display: 'Behandeling' },
'follow-up': { code: 'follow-up', display: 'Follow-up' },
telefonisch: { code: 'telefonisch', display: 'Telefonisch' },
huisbezoek: { code: 'huisbezoek', display: 'Huisbezoek' },
online: { code: 'online', display: 'Online' },
crisis: { code: 'crisis', display: 'Crisis' },
overig: { code: 'overig', display: 'Overig' },
};
// Location mappings (location → FHIR class code)
const LOCATION_MAPPINGS: Record<
string,
{ code: string; display: string }
> = {
praktijk: { code: 'AMB', display: 'Ambulant (praktijk)' },
online: { code: 'VR', display: 'Virtual (online)' },
thuis: { code: 'HH', display: 'Home (thuis)' },
};
// Request body schema
const CreateAppointmentSchema = z.object({
patientId: z.string().uuid({ message: 'patientId moet een geldige UUID zijn' }),
datetime: z.object({
date: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: 'datetime.date moet een geldige datum zijn',
}),
time: z
.string()
.regex(/^\d{2}:\d{2}$/, { message: 'datetime.time moet HH:mm formaat zijn' }),
}),
type: z.enum(
[
'intake',
'behandeling',
'follow-up',
'telefonisch',
'huisbezoek',
'online',
'crisis',
'overig',
],
{ message: 'type moet een geldig afspraaktype zijn' }
),
location: z.enum(['praktijk', 'online', 'thuis'], {
message: 'location moet praktijk, online of thuis zijn',
}),
notes: z.string().max(500, { message: 'Notities mogen maximaal 500 tekens bevatten' }).optional(),
});
export async function POST(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate request body
const body = await request.json();
const validation = CreateAppointmentSchema.safeParse(body);
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => `${e.path.join('.')}: ${e.message}`)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
const { patientId, datetime, type, location, notes } = validation.data;
// Combine date and time into ISO datetime
const [hours, minutes] = datetime.time.split(':').map(Number);
const startDate = new Date(datetime.date);
startDate.setHours(hours, minutes, 0, 0);
// Default duration: 1 hour
const endDate = addHours(startDate, 1);
// Validate date is not in the past
const now = new Date();
if (startDate < now) {
return NextResponse.json(
{ error: 'Kan geen afspraken in het verleden maken' },
{ status: 400 }
);
}
// Map type and location
const typeMapping = TYPE_MAPPINGS[type];
const locationMapping = LOCATION_MAPPINGS[location];
// Create encounter
const result = await createEncounter({
patientId,
practitionerId: user.id,
periodStart: startDate.toISOString(),
periodEnd: endDate.toISOString(),
typeCode: typeMapping.code,
typeDisplay: typeMapping.display,
classCode: locationMapping.code,
classDisplay: locationMapping.display,
notes: notes || undefined,
});
if (!result.success) {
return NextResponse.json(
{ error: result.error || 'Fout bij het aanmaken van de afspraak' },
{ status: 500 }
);
}
return NextResponse.json(
{
success: true,
encounterId: result.data?.id,
appointment: {
id: result.data?.id,
patientId,
periodStart: startDate.toISOString(),
periodEnd: endDate.toISOString(),
type: typeMapping.display,
location: locationMapping.display,
},
},
{ status: 201 }
);
} catch (error) {
console.error('Error in create appointment API:', error);
return NextResponse.json(
{
error:
'Er ging iets mis bij het aanmaken van de afspraak. Probeer het opnieuw.',
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,148 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { rescheduleEncounter } from '@/app/epd/agenda/actions';
import { z } from 'zod';
import { addHours } from 'date-fns';
/**
* Swift Reschedule Appointment API
*
* POST /api/swift/agenda/reschedule
*
* Reschedules an appointment to a new date/time.
*/
// Request body schema
const RescheduleAppointmentSchema = z.object({
encounterId: z.string().uuid({ message: 'encounterId moet een geldige UUID zijn' }),
newDatetime: z.object({
date: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: 'newDatetime.date moet een geldige datum zijn',
}),
time: z
.string()
.regex(/^\d{2}:\d{2}$/, { message: 'newDatetime.time moet HH:mm formaat zijn' }),
}),
});
export async function POST(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate request body
const body = await request.json();
const validation = RescheduleAppointmentSchema.safeParse(body);
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => `${e.path.join('.')}: ${e.message}`)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
const { encounterId, newDatetime } = validation.data;
// Verify the encounter belongs to the current user (security check)
const { data: encounter, error: fetchError } = await supabase
.from('encounters')
.select('id, practitioner_id, patient_id, period_start, period_end, status')
.eq('id', encounterId)
.single();
if (fetchError || !encounter) {
return NextResponse.json(
{ error: 'Afspraak niet gevonden' },
{ status: 404 }
);
}
if (encounter.practitioner_id !== user.id) {
return NextResponse.json(
{ error: 'Je hebt geen toegang tot deze afspraak' },
{ status: 403 }
);
}
if (encounter.status === 'cancelled') {
return NextResponse.json(
{ error: 'Kan een geannuleerde afspraak niet verzetten' },
{ status: 400 }
);
}
// Combine new date and time into ISO datetime
const [hours, minutes] = newDatetime.time.split(':').map(Number);
const newStartDate = new Date(newDatetime.date);
newStartDate.setHours(hours, minutes, 0, 0);
// Validate new date is not in the past
const now = new Date();
if (newStartDate < now) {
return NextResponse.json(
{ error: 'Kan geen afspraken in het verleden verzetten' },
{ status: 400 }
);
}
// Calculate duration from original appointment
let newEndDate: Date;
if (encounter.period_end) {
const originalStart = new Date(encounter.period_start);
const originalEnd = new Date(encounter.period_end);
const durationMs = originalEnd.getTime() - originalStart.getTime();
newEndDate = new Date(newStartDate.getTime() + durationMs);
} else {
// Default: 1 hour
newEndDate = addHours(newStartDate, 1);
}
// Reschedule the encounter
const result = await rescheduleEncounter(
encounterId,
newStartDate.toISOString(),
newEndDate.toISOString()
);
if (!result.success) {
return NextResponse.json(
{ error: result.error || 'Fout bij het verzetten van de afspraak' },
{ status: 500 }
);
}
return NextResponse.json(
{
success: true,
encounterId,
appointment: {
id: encounterId,
periodStart: newStartDate.toISOString(),
periodEnd: newEndDate.toISOString(),
},
message: 'Afspraak succesvol verzet',
},
{ status: 200 }
);
} catch (error) {
console.error('Error in reschedule appointment API:', error);
return NextResponse.json(
{
error:
'Er ging iets mis bij het verzetten van de afspraak. Probeer het opnieuw.',
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { getEncounters } from '@/app/epd/agenda/actions';
import { z } from 'zod';
/**
* Swift Agenda Query API
*
* GET /api/swift/agenda?start=2024-12-27&end=2024-12-27
*
* Returns appointments for the specified date range.
* Automatically filters by current user (practitioner_id).
*/
// Query parameter schema
const QuerySchema = z.object({
start: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: 'start moet een geldige datum zijn',
}),
end: z.string().refine((val) => !isNaN(Date.parse(val)), {
message: 'end moet een geldige datum zijn',
}),
});
export async function GET(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate query parameters
const searchParams = request.nextUrl.searchParams;
const start = searchParams.get('start');
const end = searchParams.get('end');
if (!start || !end) {
return NextResponse.json(
{ error: 'start en end parameters zijn verplicht' },
{ status: 400 }
);
}
const validation = QuerySchema.safeParse({ start, end });
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => e.message)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
// Fetch appointments
const appointments = await getEncounters({
startDate: start,
endDate: end,
practitionerId: user.id,
});
return NextResponse.json(
{
appointments,
count: appointments.length,
dateRange: { start, end },
},
{ status: 200 }
);
} catch (error) {
console.error('Error in agenda query API:', error);
return NextResponse.json(
{
error:
'Er ging iets mis bij het ophalen van afspraken. Probeer het opnieuw.',
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,107 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/auth/server';
import { z } from 'zod';
/**
* Swift Patient Search API
*
* GET /api/swift/patients/search?q=jan
*
* Fuzzy search for patients by name (for disambiguation).
*/
// Query parameter schema
const QuerySchema = z.object({
q: z.string().min(1, { message: 'Zoekterm mag niet leeg zijn' }).max(100),
});
export async function GET(request: NextRequest) {
try {
// Auth check
const supabase = await createClient();
const {
data: { user },
error: authError,
} = await supabase.auth.getUser();
if (authError || !user) {
return NextResponse.json(
{ error: 'Niet geautoriseerd. Log opnieuw in.' },
{ status: 401 }
);
}
// Parse and validate query parameters
const searchParams = request.nextUrl.searchParams;
const q = searchParams.get('q');
if (!q) {
return NextResponse.json(
{ error: 'Query parameter "q" is verplicht' },
{ status: 400 }
);
}
const validation = QuerySchema.safeParse({ q });
if (!validation.success) {
const errorMessage = validation.error.issues
.map((e) => e.message)
.join(', ');
return NextResponse.json({ error: errorMessage }, { status: 400 });
}
const query = validation.data.q.trim();
// Fuzzy search on patient names
// Search in both name_family and name_given fields
const { data: patients, error: searchError } = await supabase
.from('patients')
.select('id, name_family, name_given, birth_date, identifier_bsn')
.or(
`name_family.ilike.%${query}%,name_given.cs.{"${query}"}`
)
.limit(10)
.order('name_family', { ascending: true });
if (searchError) {
console.error('Error searching patients:', searchError);
return NextResponse.json(
{ error: 'Fout bij het zoeken van patiënten' },
{ status: 500 }
);
}
// Format response
const formattedPatients = (patients || []).map((patient) => {
const givenName = Array.isArray(patient.name_given)
? patient.name_given[0]
: patient.name_given;
const fullName = `${givenName || ''} ${patient.name_family || ''}`.trim();
return {
id: patient.id,
name: fullName || 'Onbekende naam',
bsn: patient.identifier_bsn || undefined,
birthDate: patient.birth_date || undefined,
};
});
return NextResponse.json(
{
patients: formattedPatients,
count: formattedPatients.length,
query,
},
{ status: 200 }
);
} catch (error) {
console.error('Error in patient search API:', error);
return NextResponse.json(
{
error:
'Er ging iets mis bij het zoeken van patiënten. Probeer het opnieuw.',
},
{ status: 500 }
);
}
}