refactor: rename swift → cortex in code and documentation

Complete rename of "swift" terminology to "cortex" across the codebase:

Code Changes:
- Rename directories: lib/swift → lib/cortex, components/swift → components/cortex
- Rename API routes: /api/swift/* → /api/cortex/*
- Rename page routes: /epd/swift → /epd/cortex
- Rename store: swift-store.ts → cortex-store.ts

Type Renames:
- SwiftIntent → CortexIntent
- SwiftStore → CortexStore
- useSwiftStore → useCortexStore
- SwiftContext → CortexContext
- useSwiftVoice → useCortexVoice

Documentation Updates (docs/intent/):
- Safety Net → Nudge (Layer 3 rename)
- SafetySuggestion → NudgeSuggestion
- evaluateSafetyNet → evaluateNudge
- SWIFT_* feature flags → CORTEX_*
- All path references updated to match new structure

Files affected: 47 files, ~700 lines changed

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
colinislit
2025-12-30 09:18:06 +01:00
parent c8aaba657e
commit 2170b23348
62 changed files with 364 additions and 355 deletions

View File

@@ -0,0 +1,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 }
);
}
}