"use client"; /** * v1.7.0 — Settings → Export → Health Record export panel. * * One surface that drives `POST /api/export/health-record`: a format * toggle (PDF / FHIR / package) that drives the visible options below it * (per the "dropdown drives the form, no top/bottom split" preference), * a date-range picker, grouped data-section toggles, and the generate * action that streams the artefact as a download. * * Mood stays default-OFF everywhere (privacy). PDF-only fields (practice * name, charts) hide when the format is FHIR. The ePA-compat note shows * for the FHIR + package formats. */ import { useState } from "react"; import { Download, FileText, Loader2 } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Label } from "@/components/ui/label"; import { Input } from "@/components/ui/input"; import { NativeSelect } from "@/components/ui/native-select"; import { Switch } from "@/components/ui/switch"; import { useRovingRadioGroup } from "@/hooks/use-roving-radio-group"; import { useTranslations } from "@/lib/i18n/context"; type ExportFormat = "pdf" | "fhir" | "package"; const EXPORT_FORMATS: readonly ExportFormat[] = ["pdf", "fhir", "package"]; interface SectionState { weight: boolean; bp: boolean; pulse: boolean; oxygenSaturation: boolean; bodyFat: boolean; bodyComposition: boolean; restingHeartRate: boolean; hrv: boolean; vo2max: boolean; steps: boolean; distance: boolean; sleep: boolean; glucose: boolean; medList: boolean; compliance: boolean; mood: boolean; bmi: boolean; } const DEFAULT_SECTIONS: SectionState = { weight: true, bp: true, pulse: true, oxygenSaturation: true, bodyFat: true, bodyComposition: false, restingHeartRate: false, hrv: false, vo2max: false, steps: false, distance: false, sleep: false, glucose: true, medList: true, compliance: true, mood: false, // privacy default bmi: true, }; function buildSelectionSections(s: SectionState) { return { vitals: { weight: s.weight, bp: s.bp, pulse: s.pulse, oxygenSaturation: s.oxygenSaturation, bodyFat: s.bodyFat, bodyComposition: s.bodyComposition, }, cardioFitness: { restingHeartRate: s.restingHeartRate, hrv: s.hrv, vo2max: s.vo2max, }, activity: { steps: s.steps, distance: s.distance, sleep: s.sleep, }, glucose: s.glucose, medications: { list: s.medList, compliance: s.compliance }, mood: s.mood, bmi: s.bmi, }; } export function HealthRecordExportPanel() { const { t, locale } = useTranslations(); const [format, setFormat] = useState("pdf"); const [days, setDays] = useState(90); const [practiceName, setPracticeName] = useState(""); const [includeCharts, setIncludeCharts] = useState(true); const [includeAiSummary, setIncludeAiSummary] = useState(false); const [sections, setSections] = useState(DEFAULT_SECTIONS); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const isPdfLike = format === "pdf" || format === "package"; const isFhirLike = format === "fhir" || format === "package"; const { getRadioProps: getFormatRadioProps } = useRovingRadioGroup({ count: EXPORT_FORMATS.length, selectedIndex: EXPORT_FORMATS.indexOf(format), onSelect: (index) => setFormat(EXPORT_FORMATS[index]!), }); function toggle(key: keyof SectionState) { setSections((prev) => ({ ...prev, [key]: !prev[key] })); } // The single "Medikamente" control gates the whole medication block // (list + compliance) so unchecking it actually excludes all medication // data from the export — matching the iOS five-section model. function toggleMedications() { setSections((prev) => { const next = !(prev.medList && prev.compliance); return { ...prev, medList: next, compliance: next }; }); } async function handleGenerate() { setBusy(true); setError(null); try { const res = await fetch("/api/export/health-record", { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ format, // Carry the active in-app locale so the generated artefact matches // the UI language instead of falling back to the browser's // Accept-Language header on the server. locale, range: { days }, practiceName: practiceName.trim() || undefined, includeCharts, includeAiSummary, sections: buildSelectionSections(sections), }), }); if (!res.ok) { setError(`${res.status}`); return; } const blob = await res.blob(); const ext = format === "pdf" ? "pdf" : format === "fhir" ? "json" : "zip"; const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = `healthlog-health-record-${new Date() .toISOString() .slice(0, 10)}.${ext}`; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setBusy(false); } } return (

{t("settings.healthRecord.description")}

{/* Format toggle */}
{t("settings.healthRecord.format")}
{EXPORT_FORMATS.map((f, index) => ( ))}
{/* Date range */}
setDays(Number(e.target.value))} >
{/* Practice name — PDF only */} {isPdfLike && (
setPracticeName(e.target.value)} maxLength={120} placeholder={t("settings.healthRecord.practiceNamePlaceholder")} />
)} {/* Section groups */}
{t("settings.healthRecord.includedData")}

{t("settings.healthRecord.groupVitals")}

toggle("weight")} /> toggle("bp")} /> toggle("pulse")} /> toggle("oxygenSaturation")} /> toggle("bodyFat")} /> toggle("bodyComposition")} />

{t("settings.healthRecord.groupCardio")}

toggle("restingHeartRate")} /> toggle("hrv")} /> toggle("vo2max")} />

{t("settings.healthRecord.groupActivity")}

toggle("steps")} /> toggle("distance")} /> toggle("sleep")} />
toggle("glucose")} /> toggle("bmi")} /> toggle("mood")} />
{isPdfLike && ( setIncludeCharts((v) => !v)} /> )} {isPdfLike && ( setIncludeAiSummary((v) => !v)} /> )}
{isFhirLike && (

{t("settings.healthRecord.fhirNote")}

)}
{error && (

{t("settings.healthRecord.error", { code: error })}

)}
); } function ToggleRow({ label, checked, onToggle, }: { label: string; checked: boolean; onToggle: () => void; }) { return ( ); }