feat(doctor-report): practice name on cover page (persisted as user preference)

Marc wanted the addressee visible at first glance on the printout —
"Praxis Dr. Müller" should be the first thing the GP sees, so the
report doubles as a polite opening line.

- New optional free-text field "Praxis / clinic name" in the export
  dialog. The dialog pre-fills it with the user's last-used value so
  recurring exports don't require re-typing.
- Persisted as a user preference: new `User.lastReportPracticeName`
  column (migration `0031_user_last_report_practice_name`). The value
  is updated only on a successful POST that supplied a non-empty
  string — passing `null` does NOT clear the stored preference so the
  value sticks across years of follow-ups. Best-effort write: a DB
  failure here MUST NOT break the report (caught + ignored).
- `sanitisePracticeName()` enforces a strict envelope upstream: strips
  ASCII C0 + DEL controls (which jsPDF can't render), collapses
  whitespace, and hard-caps at 120 characters. Defends the PDF layout
  from runaway input + protects the PDF text stream from
  control-character corruption.
- PDF cover prints the line in 11pt bold above the separator when set;
  omitted entirely when `null` so the cover stays compact for
  self-archive use. Both client (`doctor-report-pdf.ts`) and server
  (`doctor-report-pdf-core.ts`) renderers carry the change so the
  visual output matches whichever path the user takes (browser
  download vs iOS Safari fallback).
- `/api/auth/me` now echoes `lastReportPracticeName` so the dialog
  pre-fills without an extra round-trip.
- Audit-log + Wide-Event annotations record `practiceNameProvided:
  boolean` (NOT the value itself — practice names are personal and we
  already store one canonical copy on the user record).

i18n: 6 new keys (`doctorReport.practiceLabel`, `doctorReport.dialog.{practiceLabel,practicePlaceholder}`)
in EN + DE.

Tests: 12 new unit cases covering sanitisation (whitespace, controls,
length cap, type guard), PDF cover rendering (DE label "Praxis:", EN
"Practice:", omission when null), API persistence (prisma.user.update
called with the right shape, audit detail flag set). 965 / 965 unit
pass, 31 / 31 integration pass. Lint 0 errors. Typecheck clean for B6
files (pre-existing dashboard-layout.test.ts errors are A4 territory).
v1.4.15 phase B6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Marc-André BombeckandClaude Opus 4.7 committed 2026-05-09 21:36:47 +02:00
1 parent d692119454
commit 28467b2590
15 files changed
+249 -19

No files matched your search

@@ -3,8 +3,8 @@
/**
* Doctor-report export dialog (v1.4.15 phase B6).
*
* Wraps the trigger button so the user picks a reporting period before the
* PDF is generated.
* Wraps the trigger button so the user picks a reporting period and
* (optionally) a practice / clinic name before the PDF is generated.
*
* Defaults:
* - end = today
@@ -34,16 +34,20 @@ import { useTranslations } from "@/lib/i18n/context";
const ONE_DAY_MS = 86_400_000;
const MAX_RANGE_DAYS = 730;
const PRACTICE_NAME_MAX_LENGTH = 120;
export interface DoctorReportSubmitPayload {
startDate: string;
endDate: string;
practiceName: string | null;
}
interface DoctorReportDialogProps {
/** Controlled open state. */
open: boolean;
onOpenChange: (open: boolean) => void;
/** Last-used practice name from `/api/auth/me`; pre-fills the input. */
defaultPracticeName?: string | null;
/**
* Resolves with the user-confirmed payload. The dialog stays open and
* shows the spinner while the promise is pending; closes on resolve.
@@ -73,25 +77,28 @@ function defaultStartIso(): string {
export function DoctorReportDialog({
open,
onOpenChange,
defaultPracticeName,
onSubmit,
}: DoctorReportDialogProps) {
const { t } = useTranslations();
const [startDate, setStartDate] = useState<string>(defaultStartIso);
const [endDate, setEndDate] = useState<string>(todayIso);
const [practiceName, setPracticeName] = useState<string>("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Reset on open: re-anchor dates to defaults each time the dialog appears
// so a follow-up export doesn't reuse the previous custom range. Using
// the React-recommended "track-the-trigger" pattern (store the last
// observed `open` state and react during render) so the reset happens in
// the render phase rather than a setState-in-effect — that's the cleanest
// way to satisfy the strict `react-hooks/set-state-in-effect` rule.
// Reset on open: re-anchor dates + practice-name to defaults each time
// the dialog appears so a follow-up export doesn't reuse the previous
// custom range. Using the React-recommended "track-the-trigger" pattern
// (store the last observed `open` state and react during render) so the
// reset happens in the render phase rather than a setState-in-effect —
// satisfies the strict `react-hooks/set-state-in-effect` rule.
const [lastOpen, setLastOpen] = useState(false);
if (open && !lastOpen) {
setLastOpen(true);
setStartDate(defaultStartIso());
setEndDate(todayIso());
setPracticeName(defaultPracticeName ?? "");
setError(null);
setSubmitting(false);
} else if (!open && lastOpen) {
@@ -143,7 +150,15 @@ export function DoctorReportDialog({
// captures everything logged on each boundary day.
const startIso = new Date(`${startDate}T00:00:00`).toISOString();
const endIso = new Date(`${endDate}T23:59:59.999`).toISOString();
await onSubmit({ startDate: startIso, endDate: endIso });
const trimmedPractice = practiceName.trim();
await onSubmit({
startDate: startIso,
endDate: endIso,
practiceName:
trimmedPractice.length > 0
? trimmedPractice.slice(0, PRACTICE_NAME_MAX_LENGTH)
: null,
});
} catch (err) {
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
@@ -225,6 +240,21 @@ export function DoctorReportDialog({
</Button>
</div>
<div className="space-y-1.5">
<Label htmlFor="dr-practice">
{t("doctorReport.dialog.practiceLabel")}
</Label>
<Input
id="dr-practice"
type="text"
value={practiceName}
maxLength={PRACTICE_NAME_MAX_LENGTH}
placeholder={t("doctorReport.dialog.practicePlaceholder")}
onChange={(e) => setPracticeName(e.target.value)}
autoComplete="organization"
/>
</div>
{error && (
<p
role="alert"
+28 -1
View File
@@ -1,6 +1,6 @@
"use client";
import { useState } from "react";
import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { AlertTriangle, Download, Loader2, Trash2 } from "lucide-react";
@@ -53,6 +53,28 @@ function ExportCard() {
const [exporting, setExporting] = useState(false);
const [generatingReport, setGeneratingReport] = useState(false);
const [reportDialogOpen, setReportDialogOpen] = useState(false);
const [lastPracticeName, setLastPracticeName] = useState<string | null>(null);
// Fetch the previously-stored practice name so the dialog can pre-fill it.
// `useEffect` is the right place for a one-shot side-effect on mount; the
// ESLint `set-state-in-effect` rule is fine here because we are not
// setting state on every render — we are reacting to a fetch.
useEffect(() => {
let cancelled = false;
fetch("/api/auth/me")
.then((res) => (res.ok ? res.json() : null))
.then((json) => {
if (cancelled || !json) return;
const name = json?.data?.lastReportPracticeName;
if (typeof name === "string") setLastPracticeName(name);
})
.catch(() => {
// Best-effort; the dialog still works without the pre-fill.
});
return () => {
cancelled = true;
};
}, []);
async function handleExport(format: "csv" | "json") {
setExporting(true);
@@ -83,6 +105,7 @@ function ExportCard() {
body: JSON.stringify({
startDate: payload.startDate,
endDate: payload.endDate,
practiceName: payload.practiceName,
}),
});
if (!res.ok) return;
@@ -93,6 +116,9 @@ function ExportCard() {
const doc = generateDoctorReportPDF(json.data, { t, locale });
const fileSlug = locale === "de" ? "gesundheitsbericht" : "health-report";
doc.save(`${fileSlug}-${new Date().toISOString().slice(0, 10)}.pdf`);
// Remember the last-used practice name so the next open of the dialog
// pre-fills it without a roundtrip to /api/auth/me.
if (payload.practiceName) setLastPracticeName(payload.practiceName);
setReportDialogOpen(false);
} finally {
setGeneratingReport(false);
@@ -142,6 +168,7 @@ function ExportCard() {
<DoctorReportDialog
open={reportDialogOpen}
onOpenChange={setReportDialogOpen}
defaultPracticeName={lastPracticeName}
onSubmit={handleDoctorReport}
/>
</div>