From 86995a446648a6600cb3f99254e59711045fa8f5 Mon Sep 17 00:00:00 2001 From: colinislit Date: Sat, 22 Nov 2025 13:58:31 +0100 Subject: [PATCH] feat: implement patient list and new patient form (E2.S1 & E2.S2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Epic 2 - Cliëntenbeheer: Complete implementation of patient list with search/filter functionality and comprehensive new patient form with John Doe crisis admission support. E2.S1 - Cliëntenlijst: - Add client-side search bar with form submission - Implement status filter dropdown (all/screening/active/finished/cancelled) - Create StatusBadge component with color-coded status indicators - Update table columns: Status, Name, BSN, Last Updated - Add status filtering support to FHIR Patient API route - Update FHIR patient transform to include episode-status extension - Sort patients by updated_at descending (newest first) E2.S2 - Nieuwe Cliënt Flow: - Complete rewrite of patient form with all FO-required fields - Implement John Doe checkbox with conditional BSN requirement - Add BSN validation with Dutch Modulo-11 check algorithm - Add comprehensive form fields: * Name fields: prefix, given name, family name * BSN with 9-digit pattern validation * Birth date with max date validation * Gender selection * Address: street, postal code, city * Contact: phone, email * Insurance: company, policy number - Add warning messages for John Doe crisis admissions - Set default episode status to 'planned' for all new patients - Redirect to patient detail page after successful creation - Update FHIR transform bidirectional insurance extension support: * dbPatientToFHIR: serialize insurance to JSON extension * fhirPatientToDB: parse insurance from JSON extension - Pre-populate form fields when editing existing patients Technical changes: - app/api/fhir/Patient/route.ts: Add status query param and sorting - app/epd/patients/actions.ts: Add status filter parameter - app/epd/patients/page.tsx: Pass status searchParam - app/epd/patients/components/patient-list.tsx: Complete UI rewrite - app/epd/patients/components/patient-form.tsx: Complete form rewrite - lib/fhir/transforms/patient.ts: Add insurance extension handling - docs/specs/screening-intake/bouwplan-screening-intake-v1.0.md: Update status 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude --- app/api/fhir/Patient/route.ts | 9 + app/epd/patients/actions.ts | 5 + app/epd/patients/components/patient-form.tsx | 285 +++++++++++++-- app/epd/patients/components/patient-list.tsx | 331 ++++++++++++------ app/epd/patients/page.tsx | 6 +- .../bouwplan-screening-intake-v1.0.md | 28 +- lib/fhir/transforms/patient.ts | 53 +++ 7 files changed, 556 insertions(+), 161 deletions(-) diff --git a/app/api/fhir/Patient/route.ts b/app/api/fhir/Patient/route.ts index 33a7420..17b88b2 100644 --- a/app/api/fhir/Patient/route.ts +++ b/app/api/fhir/Patient/route.ts @@ -46,6 +46,15 @@ export async function GET(request: NextRequest) { query = query.eq('birth_date', birthdate); } + // Filter by status + const status = searchParams.get('status'); + if (status && status !== 'all') { + query = query.eq('status', status); + } + + // Order by updated_at descending (newest first) + query = query.order('updated_at', { ascending: false }); + // Execute query const { data: patients, error } = await query; diff --git a/app/epd/patients/actions.ts b/app/epd/patients/actions.ts index 36a104b..8a4a4f8 100644 --- a/app/epd/patients/actions.ts +++ b/app/epd/patients/actions.ts @@ -16,6 +16,7 @@ const API_BASE_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'; */ export async function getPatients(filters?: { search?: string; + status?: string; }) { try { const url = new URL(`${API_BASE_URL}/api/fhir/Patient`); @@ -24,6 +25,10 @@ export async function getPatients(filters?: { url.searchParams.set('name', filters.search); } + if (filters?.status) { + url.searchParams.set('status', filters.status); + } + const response = await fetch(url.toString(), { cache: 'no-store', }); diff --git a/app/epd/patients/components/patient-form.tsx b/app/epd/patients/components/patient-form.tsx index 82e3348..e47ae78 100644 --- a/app/epd/patients/components/patient-form.tsx +++ b/app/epd/patients/components/patient-form.tsx @@ -1,13 +1,13 @@ 'use client'; /** - * Patient Form Component (FHIR-based) - * Form for creating/editing patients using FHIR format + * Patient Form Component + * E2.S2: Nieuwe Cliënt Flow met John Doe logica */ import { useState } from 'react'; import { useRouter } from 'next/navigation'; -import { Save, Loader2 } from 'lucide-react'; +import { Save, Loader2, AlertCircle } from 'lucide-react'; import { createPatient, updatePatient } from '../actions'; import type { FHIRPatient } from '@/lib/fhir'; @@ -15,10 +15,33 @@ interface PatientFormProps { patient?: FHIRPatient; } +// BSN validation (Modulo-11 check) +function validateBSN(bsn: string): boolean { + if (!bsn || bsn.length !== 9) return false; + + const digits = bsn.split('').map(Number); + if (digits.some(isNaN)) return false; + + // Modulo-11 check + const sum = digits.reduce((acc, digit, index) => { + if (index < 8) { + return acc + digit * (9 - index); + } + return acc - digit; + }, 0); + + return sum % 11 === 0; +} + export function PatientForm({ patient }: PatientFormProps) { const router = useRouter(); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); + const [isJohnDoe, setIsJohnDoe] = useState( + patient?.extension?.find( + (ext) => ext.url === 'http://mini-epd.local/fhir/StructureDefinition/john-doe' + )?.valueBoolean || false + ); const existingName = patient?.name?.[0]; const existingBsn = patient?.identifier?.find( @@ -26,6 +49,20 @@ export function PatientForm({ patient }: PatientFormProps) { )?.value; const existingPhone = patient?.telecom?.find((t) => t.system === 'phone')?.value; const existingEmail = patient?.telecom?.find((t) => t.system === 'email')?.value; + const existingAddress = patient?.address?.[0]; + + // Extract insurance data from extension + const insuranceExtension = patient?.extension?.find( + (ext) => ext.url === 'http://mini-epd.local/fhir/StructureDefinition/insurance' + ); + let existingInsurance: { company?: string; number?: string } = {}; + if (insuranceExtension?.valueString) { + try { + existingInsurance = JSON.parse(insuranceExtension.valueString); + } catch (e) { + console.error('Failed to parse insurance extension:', e); + } + } async function handleSubmit(e: React.FormEvent) { e.preventDefault(); @@ -34,17 +71,27 @@ export function PatientForm({ patient }: PatientFormProps) { try { const formData = new FormData(e.currentTarget); + const bsnValue = formData.get('bsn') as string; + + // Validate BSN if not John Doe + if (!isJohnDoe && bsnValue) { + if (!validateBSN(bsnValue)) { + throw new Error('Ongeldig BSN nummer. Controleer het nummer en probeer opnieuw.'); + } + } // Build FHIR Patient resource const fhirPatient: FHIRPatient = { resourceType: 'Patient', - identifier: [ - { - system: 'http://fhir.nl/fhir/NamingSystem/bsn', - value: formData.get('bsn') as string, - use: 'official' as const, - }, - ], + identifier: bsnValue + ? [ + { + system: 'http://fhir.nl/fhir/NamingSystem/bsn', + value: bsnValue, + use: 'official' as const, + }, + ] + : [], name: [ { use: 'official' as const, @@ -57,6 +104,21 @@ export function PatientForm({ patient }: PatientFormProps) { ], gender: formData.get('gender') as 'male' | 'female' | 'other' | 'unknown', birthDate: formData.get('birthDate') as string, + + // Address + address: formData.get('addressLine') || formData.get('city') || formData.get('postalCode') + ? [ + { + use: 'home', + line: formData.get('addressLine') ? [formData.get('addressLine') as string] : undefined, + city: formData.get('city') as string || undefined, + postalCode: formData.get('postalCode') as string || undefined, + country: 'NL', + }, + ] + : undefined, + + // Contact telecom: [ formData.get('phone') ? { @@ -72,18 +134,50 @@ export function PatientForm({ patient }: PatientFormProps) { } : undefined, ].filter((t): t is NonNullable => t !== undefined), + active: true, + + // Extensions for status and john_doe + extension: [ + { + url: 'http://mini-epd.local/fhir/StructureDefinition/episode-status', + valueCode: 'planned', // Always set to planned for new patients + }, + isJohnDoe + ? { + url: 'http://mini-epd.local/fhir/StructureDefinition/john-doe', + valueBoolean: true, + } + : undefined, + // Insurance extension (custom) + formData.get('insuranceCompany') + ? { + url: 'http://mini-epd.local/fhir/StructureDefinition/insurance', + valueString: JSON.stringify({ + company: formData.get('insuranceCompany'), + number: formData.get('insuranceNumber'), + }), + } + : undefined, + ].filter((ext): ext is NonNullable => ext !== undefined), }; + let createdPatient: FHIRPatient; + if (patient?.id) { // Update existing patient - await updatePatient(patient.id, fhirPatient); + createdPatient = await updatePatient(patient.id, fhirPatient); } else { // Create new patient - await createPatient(fhirPatient); + createdPatient = await createPatient(fhirPatient); } - router.push('/epd/patients'); + // Redirect to patient detail page + if (createdPatient.id) { + router.push(`/epd/patients/${createdPatient.id}`); + } else { + router.push('/epd/patients'); + } router.refresh(); } catch (err) { setError(err instanceof Error ? err.message : 'Er is een fout opgetreden'); @@ -99,6 +193,39 @@ export function PatientForm({ patient }: PatientFormProps) { )} + {/* John Doe Checkbox */} +
+ +
+ + {/* John Doe Warning */} + {isJohnDoe && ( +
+ +
+

John Doe registratie

+

+ Gegevens kunnen later worden aangevuld. Vul BSN aan zodra deze beschikbaar is. +

+
+
+ )} + {/* Name Fields */}
@@ -146,17 +273,20 @@ export function PatientForm({ patient }: PatientFormProps) {
+

9 cijfers, inclusief modulo-11 check

@@ -192,33 +323,115 @@ export function PatientForm({ patient }: PatientFormProps) {
- {/* Contact Information */} -
+ {/* Address Fields */} +
+

Adresgegevens

-
-
- - +
+
+ + +
+
+ + +
+
+
+ + {/* Contact Information */} +
+

Contactgegevens

+
+
+ + +
+
+ + +
+
+
+ + {/* Insurance Information */} +
+

Verzekering

+
+
+ + +
+
+ + +
diff --git a/app/epd/patients/components/patient-list.tsx b/app/epd/patients/components/patient-list.tsx index e7507ea..3333f9c 100644 --- a/app/epd/patients/components/patient-list.tsx +++ b/app/epd/patients/components/patient-list.tsx @@ -1,141 +1,252 @@ 'use client'; /** - * Patient List Component (FHIR-based) - * Displays patients from FHIR API + * Patient List Component + * E2.S1: Cliëntenlijst met zoekfunctie, filters en status badges */ import { useState } from 'react'; import Link from 'next/link'; -import { User, Calendar, Phone, Mail } from 'lucide-react'; +import { useRouter, useSearchParams } from 'next/navigation'; +import { User, Search, Filter } from 'lucide-react'; import type { FHIRPatient } from '@/lib/fhir'; interface PatientListProps { initialPatients: FHIRPatient[]; } +// Status badge component +function StatusBadge({ status }: { status?: string }) { + const badges = { + planned: { label: 'Screening', className: 'bg-amber-100 text-amber-800 border-amber-200' }, + active: { label: 'Actief', className: 'bg-emerald-100 text-emerald-800 border-emerald-200' }, + finished: { label: 'Afgerond', className: 'bg-slate-100 text-slate-800 border-slate-200' }, + cancelled: { label: 'Afgemeld', className: 'bg-red-100 text-red-800 border-red-200' }, + }; + + const badge = status && status in badges ? badges[status as keyof typeof badges] : null; + + if (!badge) { + return -; + } + + return ( + + {badge.label} + + ); +} + export function PatientList({ initialPatients }: PatientListProps) { + const router = useRouter(); + const searchParams = useSearchParams(); + const [searchTerm, setSearchTerm] = useState(searchParams.get('search') || ''); + const [statusFilter, setStatusFilter] = useState(searchParams.get('status') || 'all'); const [patients] = useState(initialPatients); + // Handle search + const handleSearch = (e: React.FormEvent) => { + e.preventDefault(); + const params = new URLSearchParams(); + if (searchTerm) params.set('search', searchTerm); + if (statusFilter !== 'all') params.set('status', statusFilter); + router.push(`/epd/patients?${params.toString()}`); + }; + + // Handle status filter change + const handleStatusFilterChange = (newStatus: string) => { + setStatusFilter(newStatus); + const params = new URLSearchParams(); + if (searchTerm) params.set('search', searchTerm); + if (newStatus !== 'all') params.set('status', newStatus); + router.push(`/epd/patients?${params.toString()}`); + }; + if (patients.length === 0) { return ( -
- -

Geen patiënten gevonden

-

- Begin met het toevoegen van een nieuwe patiënt. -

+
+ {/* Search and Filter Bar */} +
+ {/* Search Bar */} +
+
+ + setSearchTerm(e.target.value)} + className="w-full pl-10 pr-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-teal-500 focus:border-transparent" + /> +
+
+ + {/* Status Filter */} +
+ + +
+
+ + {/* Empty State */} +
+ +

Geen patiënten gevonden

+

+ {searchTerm || statusFilter !== 'all' + ? 'Probeer een andere zoekopdracht of filter.' + : 'Begin met het toevoegen van een nieuwe patiënt.'} +

+
); } return ( -
-
- - - - - - - - - - - - {patients.map((patient) => { - const name = patient.name?.[0]; - const fullName = [ - ...(name?.prefix || []), - ...(name?.given || []), - name?.family, - ] - .filter(Boolean) - .join(' '); +
+ {/* Search and Filter Bar */} +
+ {/* Search Bar */} +
+
+ + setSearchTerm(e.target.value)} + className="w-full pl-10 pr-4 py-2 border border-slate-300 rounded-lg focus:ring-2 focus:ring-teal-500 focus:border-transparent" + /> +
+ - const bsn = patient.identifier?.find( - (id) => id.system === 'http://fhir.nl/fhir/NamingSystem/bsn' - )?.value; + {/* Status Filter */} +
+ + +
+
- const phone = patient.telecom?.find((t) => t.system === 'phone')?.value; - const email = patient.telecom?.find((t) => t.system === 'email')?.value; + {/* Patient Table */} +
+
+
- Patiënt - - BSN - - Geboortedatum - - Contact - - Geslacht -
+ + + + + + + + + + + {patients.map((patient) => { + const name = patient.name?.[0]; + const fullName = [ + ...(name?.prefix || []), + ...(name?.given || []), + name?.family, + ] + .filter(Boolean) + .join(' '); - return ( - - router.push(`/epd/patients/${patient.id}`)} + > + + + - - - - - - ); - })} - -
+ Naam + + BSN + + Geboortedatum + + Status + + Laatst gewijzigd +
- -
- - {name?.given?.[0]?.[0]} - {name?.family?.[0]} - + const bsn = patient.identifier?.find( + (id) => id.system === 'http://fhir.nl/fhir/NamingSystem/bsn' + )?.value; + + // Get status from extension (we'll add this to the FHIR mapping) + const statusExtension = patient.extension?.find( + (ext) => ext.url === 'http://mini-epd.local/fhir/StructureDefinition/episode-status' + ); + const status = statusExtension?.valueCode; + + // Format updated_at date + const updatedAt = patient.meta?.lastUpdated + ? new Date(patient.meta.lastUpdated).toLocaleDateString('nl-NL', { + day: '2-digit', + month: '2-digit', + year: 'numeric', + hour: '2-digit', + minute: '2-digit', + }) + : '-'; + + return ( +
+
+
+ + {name?.given?.[0]?.[0]} + {name?.family?.[0]} + +
+
+
+ {fullName} +
+
-
-
- {fullName} -
-
ID: {patient.id}
+
+
{bsn || '-'}
+
+
+ {patient.birthDate + ? new Date(patient.birthDate).toLocaleDateString('nl-NL') + : '-'}
- -
-
{bsn || '-'}
-
-
- - {patient.birthDate || '-'} -
-
-
- {phone && ( -
- - {phone} -
- )} - {email && ( -
- - {email} -
- )} - {!phone && !email && ( - - - )} -
-
- - {patient.gender === 'male' && 'Man'} - {patient.gender === 'female' && 'Vrouw'} - {patient.gender === 'other' && 'Anders'} - {patient.gender === 'unknown' && 'Onbekend'} - {!patient.gender && '-'} - -
+ + + + + +
{updatedAt}
+ + + ); + })} + + +
); diff --git a/app/epd/patients/page.tsx b/app/epd/patients/page.tsx index 6849f9c..76ddf9c 100644 --- a/app/epd/patients/page.tsx +++ b/app/epd/patients/page.tsx @@ -6,6 +6,7 @@ import Link from 'next/link'; interface SearchParams { search?: string; + status?: string; } export default async function PatientsPage({ @@ -20,9 +21,9 @@ export default async function PatientsPage({
-

Patiënten (FHIR)

+

Patiënten

- FHIR-compliant patiëntenbeheer + Overzicht van alle patiënten met screening en intake status

; diff --git a/docs/specs/screening-intake/bouwplan-screening-intake-v1.0.md b/docs/specs/screening-intake/bouwplan-screening-intake-v1.0.md index f245b19..9f0f8b8 100644 --- a/docs/specs/screening-intake/bouwplan-screening-intake-v1.0.md +++ b/docs/specs/screening-intake/bouwplan-screening-intake-v1.0.md @@ -42,7 +42,7 @@ | Epic ID | Titel | Doel | Status | Stories | |---------|-------|------|--------|---------| | E1 | Database & Types | Datamodel implementeren in Supabase | ✅ Done | 3 | -| E2 | Cliëntenbeheer | Lijstweergave en aanmaken cliënten | ⏳ To Do | 3 | +| E2 | Cliëntenbeheer | Lijstweergave en aanmaken cliënten | 🔨 In Progress | 3 | | E3 | Screening Module | Screening tab en functionaliteit | ⏳ To Do | 4 | | E4 | Intake Core | Intake overzicht en navigatie | ⏳ To Do | 3 | | E5 | Intake Details | Specifieke tabbladen (Contact, Risico, etc.) | ⏳ To Do | 5 | @@ -52,23 +52,25 @@ ## 4. Epics & Stories (Uitwerking) -### Epic 1 — Database & Types +### Epic 1 — Database & Types ✅ **Doel:** Een solide datamodel in Supabase dat voldoet aan de eisen uit het FO. +**Status:** Done - Alle stories voltooid op 22-11-2025 -| Story ID | Beschrijving | Acceptatiecriteria | -|----------|--------------|---------------------| -| E1.S1 | Tabellen aanmaken | ✅ Migration `20251122_screening_intake_schema.sql` aangemaakt met:
- Patient status kolom (`episode_status` enum)
- Screening module (3 tabellen: `screenings`, `screening_activities`, `screening_documents`)
- Intake module (4 tabellen: `intakes`, `anamneses`, `examinations`, `risk_assessments`)
- `encounters` tabel uitgebreid met `intake_id` kolom
- `care_plans` uitgebreid met intake referenties | -| E1.S2 | Migration toepassen | Migration succesvol toegepast op Supabase database met:
- Foreign keys en constraints
- RLS policies voor alle nieuwe tabellen
- Indexes voor performance
- Triggers voor `updated_at` timestamps | -| E1.S3 | TypeScript Types genereren | Types gegenereerd met `supabase gen types` en geëxporteerd naar `lib/supabase/database.types.ts` | +| Story ID | Status | Beschrijving | Acceptatiecriteria | +|----------|--------|--------------|---------------------| +| E1.S1 | ✅ Done | Tabellen aanmaken | Migration `20251122_screening_intake_schema.sql` aangemaakt met:
- Patient status kolom (`episode_status` enum)
- Screening module (3 tabellen: `screenings`, `screening_activities`, `screening_documents`)
- Intake module (4 tabellen: `intakes`, `anamneses`, `examinations`, `risk_assessments`)
- `encounters` tabel uitgebreid met `intake_id` kolom
- `care_plans` uitgebreid met intake referenties | +| E1.S2 | ✅ Done | Migration toepassen | Migration succesvol toegepast op Supabase database met:
- Foreign keys en constraints
- RLS policies voor alle nieuwe tabellen
- Indexes voor performance
- Triggers voor `updated_at` timestamps | +| E1.S3 | ✅ Done | TypeScript Types genereren | Types gegenereerd met `supabase gen types` en geëxporteerd naar `lib/supabase/database.types.ts`
- 2148+ regels TypeScript types
- Alle nieuwe tabellen en enums geëxporteerd | -### Epic 2 — Cliëntenbeheer (Level 1) +### Epic 2 — Cliëntenbeheer (Level 1) 🔨 **Doel:** Behandelaars kunnen cliënten vinden en nieuwe cliënten aanmaken. +**Status:** In Progress - 2 van 3 stories voltooid op 22-11-2025 -| Story ID | Beschrijving | Acceptatiecriteria | -|----------|--------------|---------------------| -| E2.S1 | Cliëntenlijst | Tabel met zoekfunctie, filters en status badges. | -| E2.S2 | Nieuwe Cliënt Flow | Formulier voor aanmaken cliënt (incl. John Doe logica). | -| E2.S3 | Cliënt Header & Nav | Context-aware header en sidebar navigatie (Level 2). | +| Story ID | Status | Beschrijving | Acceptatiecriteria | +|----------|--------|--------------|---------------------| +| E2.S1 | ✅ Done | Cliëntenlijst | Tabel met zoekfunctie, filters en status badges:
- `patient-list.tsx` geüpdatet met client-side search bar
- Status filter dropdown (alle/screening/actief/afgerond/afgemeld)
- StatusBadge component met color-coded badges
- Tabel kolommen: Status, Naam, BSN, Laatst gewijzigd
- API route `/api/fhir/Patient` ondersteunt status filtering
- FHIR transform aangepast voor status extension | +| E2.S2 | ✅ Done | Nieuwe Cliënt Flow | Formulier voor aanmaken cliënt met John Doe logica:
- `patient-form.tsx` compleet herschreven met alle FO velden
- John Doe checkbox met conditional BSN requirement
- BSN validatie met Modulo-11 check
- Alle velden: naam, BSN, geboortedatum, geslacht, adres (straat, postcode, plaats), contact (telefoon, email), verzekering (verzekeraar, polisnummer)
- Warning messages voor John Doe patiënten
- Status altijd 'planned' voor nieuwe patiënten
- Redirect naar patient detail page na aanmaken
- FHIR transform ondersteunt insurance extension (bidirectioneel) | +| E2.S3 | ⏳ To Do | Cliënt Header & Nav | Context-aware header en sidebar navigatie (Level 2). | ### Epic 3 — Screening Module (Level 2) **Doel:** Faciliteren van het screeningsproces. diff --git a/lib/fhir/transforms/patient.ts b/lib/fhir/transforms/patient.ts index 185e57c..5b360ee 100644 --- a/lib/fhir/transforms/patient.ts +++ b/lib/fhir/transforms/patient.ts @@ -131,6 +131,31 @@ export function dbPatientToFHIR(row: PatientRow): FHIRPatient { meta: { lastUpdated: row.updated_at || undefined, }, + + // Extension for episode status (non-standard FHIR, but needed for our workflow) + extension: [ + row.status + ? { + url: 'http://mini-epd.local/fhir/StructureDefinition/episode-status', + valueCode: row.status, + } + : undefined, + row.is_john_doe + ? { + url: 'http://mini-epd.local/fhir/StructureDefinition/john-doe', + valueBoolean: true, + } + : undefined, + row.insurance_company + ? { + url: 'http://mini-epd.local/fhir/StructureDefinition/insurance', + valueString: JSON.stringify({ + company: row.insurance_company, + number: row.insurance_number, + }), + } + : undefined, + ].filter((x): x is NonNullable => x !== undefined), }; } @@ -172,6 +197,30 @@ export function fhirPatientToDB(fhir: FHIRPatient): PatientInsert { const gpName = gp?.display; const gpAgb = gp?.identifier?.value; + // Extract status and john_doe from extensions + const statusExtension = fhir.extension?.find( + (ext) => ext.url === 'http://mini-epd.local/fhir/StructureDefinition/episode-status' + ); + const johnDoeExtension = fhir.extension?.find( + (ext) => ext.url === 'http://mini-epd.local/fhir/StructureDefinition/john-doe' + ); + const insuranceExtension = fhir.extension?.find( + (ext) => ext.url === 'http://mini-epd.local/fhir/StructureDefinition/insurance' + ); + + // Parse insurance data from extension + let insuranceCompany: string | undefined; + let insuranceNumber: string | undefined; + if (insuranceExtension?.valueString) { + try { + const insuranceData = JSON.parse(insuranceExtension.valueString); + insuranceCompany = insuranceData.company; + insuranceNumber = insuranceData.number; + } catch (e) { + console.error('Failed to parse insurance extension:', e); + } + } + return { id: fhir.id, identifier_bsn: bsn || '999999990', // Default placeholder @@ -194,5 +243,9 @@ export function fhirPatientToDB(fhir: FHIRPatient): PatientInsert { general_practitioner_name: gpName || undefined, general_practitioner_agb: gpAgb || undefined, active: fhir.active ?? true, + status: (statusExtension?.valueCode as any) || 'planned', + is_john_doe: johnDoeExtension?.valueBoolean || false, + insurance_company: insuranceCompany || undefined, + insurance_number: insuranceNumber || undefined, }; }