"use client"; /** * v1.4.16 phase B7 — Settings → Export. * * Single surface that consolidates every "give me my data out" path in * HealthLog. Replaces the old `` inside `` * (CSV/JSON/Doctor-report buttons crammed onto one row) with one card * per export type, each with its own filter inputs and a clear * "Download" / "Generate" button. * * 1. Doctor Report (PDF) — date range + practice name dialog * 2. Measurements CSV — optional `since`/`until` * 3. Medications CSV — optional intake-history toggle * 4. Mood CSV — optional `since`/`until` * 5. Full JSON Backup — single-file user-scoped dump * * Mobile-first: cards stack on `=md`. */ import { useEffect, useState } from "react"; import { Download, FileJson, FileSpreadsheet, FileText, Loader2, Pill, Stethoscope, Waves, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { DoctorReportDialog, type DoctorReportSubmitPayload, } from "@/components/doctor-report/doctor-report-dialog"; import { useTranslations } from "@/lib/i18n/context"; type ExportFormat = "PDF" | "CSV" | "JSON"; /** * Trigger a browser download for a given URL by spinning up an anchor * element. Used by every CSV/JSON card so the implementation stays in * one place. */ async function downloadFromUrl(url: string, filename: string): Promise { const res = await fetch(url, { credentials: "include" }); if (!res.ok) { throw new Error(`Download failed (${res.status})`); } const blob = await res.blob(); const objectUrl = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = objectUrl; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(objectUrl); } export function ExportSection() { const { t } = useTranslations(); return (

{t("settings.sections.export.title")}

{t("settings.sections.export.description")}

{/* Mobile: single column. Desktop (md+): 2-column grid. */}
); } // ─────────────────────────── Card primitives ─────────────────────────── interface ExportCardShellProps { testId: string; icon: React.ComponentType<{ className?: string }>; title: string; description: string; format: ExportFormat; children?: React.ReactNode; /** Footer slot — typically the "Download" button + status text. */ footer: React.ReactNode; } function ExportCardShell({ testId, icon: Icon, title, description, format, children, footer, }: ExportCardShellProps) { return (

{title}

{format}

{description}

{children &&
{children}
}
{footer}
); } // ─────────────────────────── Doctor Report ─────────────────────────── function DoctorReportCard() { const { t, locale } = useTranslations(); const [open, setOpen] = useState(false); const [busy, setBusy] = useState(false); const [defaultPracticeName, setDefaultPracticeName] = useState( null, ); const [error, setError] = useState(null); // Pre-fill the practice name from the user profile so the dialog opens // ready-to-submit. Best-effort: if the request fails, the dialog still // works without a pre-fill. useEffect(() => { let cancelled = false; fetch("/api/auth/me", { credentials: "include" }) .then((res) => (res.ok ? res.json() : null)) .then((json) => { if (cancelled || !json) return; const name = json?.data?.lastReportPracticeName; if (typeof name === "string") setDefaultPracticeName(name); }) .catch(() => { // ignore — pre-fill is a UX nicety }); return () => { cancelled = true; }; }, []); async function handleSubmit(payload: DoctorReportSubmitPayload) { setBusy(true); setError(null); try { const res = await fetch("/api/doctor-report", { method: "POST", headers: { "Content-Type": "application/json" }, credentials: "include", body: JSON.stringify({ startDate: payload.startDate, endDate: payload.endDate, practiceName: payload.practiceName, }), }); if (!res.ok) { setError(`${res.status}`); return; } const json = await res.json(); const { generateDoctorReportPDF } = await import("@/lib/doctor-report-pdf"); const doc = generateDoctorReportPDF(json.data, { t, locale }); const fileSlug = locale === "de" ? "gesundheitsbericht" : "health-report"; doc.save(`${fileSlug}-${new Date().toISOString().slice(0, 10)}.pdf`); if (payload.practiceName) setDefaultPracticeName(payload.practiceName); setOpen(false); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setBusy(false); } } return ( setOpen(true)} disabled={busy} > {busy && } {t("settings.sections.export.cards.doctorReport.action")} } > {error && (

{error}

)}
); } // ─────────────────────────── CSV cards ─────────────────────────── interface DateRangeFieldsProps { since: string; until: string; setSince: (v: string) => void; setUntil: (v: string) => void; idPrefix: string; } function DateRangeFields({ since, until, setSince, setUntil, idPrefix, }: DateRangeFieldsProps) { const { t, locale } = useTranslations(); return (
setSince(e.target.value)} max={until || undefined} />
setUntil(e.target.value)} min={since || undefined} />
); } function buildQueryString(base: Record): string { const params = new URLSearchParams(); for (const [k, v] of Object.entries(base)) { if (v) params.set(k, v); } const q = params.toString(); return q ? `?${q}` : ""; } interface CsvCardProps { testId: string; actionTestId: string; icon: React.ComponentType<{ className?: string }>; titleKey: string; descriptionKey: string; endpoint: string; filenamePrefix: string; } function CsvCard({ testId, actionTestId, icon, titleKey, descriptionKey, endpoint, filenamePrefix, }: CsvCardProps) { const { t } = useTranslations(); const [since, setSince] = useState(""); const [until, setUntil] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); async function handleDownload() { setBusy(true); setError(null); try { const query = buildQueryString({ since: since || undefined, until: until || undefined, }); const stamp = new Date().toISOString().slice(0, 10); const filename = `${filenamePrefix}-${stamp}.csv`; await downloadFromUrl(`${endpoint}${query}`, filename); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setBusy(false); } } return ( {busy ? ( ) : ( )} {t("settings.sections.export.actions.download")} } > {error && (

{error}

)}
); } function MeasurementsCsvCard() { return ( ); } function MedicationsCsvCard() { // The intake-history toggle is local state on this card — we read it // when the user clicks Download and append `&intake=true` to the URL. const { t } = useTranslations(); const [since, setSince] = useState(""); const [until, setUntil] = useState(""); const [includeIntake, setIncludeIntake] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); async function handleDownload() { setBusy(true); setError(null); try { const query = buildQueryString({ since: since || undefined, until: until || undefined, intake: includeIntake ? "true" : "false", }); const stamp = new Date().toISOString().slice(0, 10); await downloadFromUrl( `/api/export/medications${query}`, `healthlog-medications-${stamp}.csv`, ); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setBusy(false); } } return ( {busy ? ( ) : ( )} {t("settings.sections.export.actions.download")} } > {error && (

{error}

)}
); } function MoodCsvCard() { return ( ); } function FullBackupCard() { const { t } = useTranslations(); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); async function handleDownload() { setBusy(true); setError(null); try { const stamp = new Date().toISOString().slice(0, 10); await downloadFromUrl( "/api/export/full-backup", `healthlog-backup-${stamp}.json`, ); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setBusy(false); } } return ( {busy ? ( ) : ( )} {t("settings.sections.export.actions.download")} } > {error && (

{error}

)}
); }