Files
immich-redaktions-plugin/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx
T
Leon TonhäuserandClaude Opus 5.5 9e938e4d07 feat: redesign portal UI with Sakani UI and add release notes
Replace the hand-rolled Tailwind/shadcn look with Sakani UI across the
editorial area, the admin area and all signed-out pages.

- AppShell (Sakani Sidebar + TopBar) for /redaktion and /admin, with a
  mobile drawer, theme toggle, sign-out, legal links and a "Was ist neu"
  button; PublicShell for login, registration, password, 2FA and errors.
- Shared primitives (Button, Card, Input, PageHeader) now render Sakani;
  components/ui/sakani.tsx is the client boundary for Server Components
  (Sakani ships no "use client") and adds FormSelect (native form value)
  and DataTable (element cells from the server).
- Legacy CSS variables map onto Sakani tokens; globals.css shrinks from
  ~2200 to ~700 lines. Geist replaces Inter. recharts/lucide-react dropped
  (charts via Sakani BarChart).
- Release notes popup per area, shown once per version (localStorage) and
  reopenable from the sidebar; native <dialog> for focus trapping.
- Fixes found while testing: TOTP field reused the typed password in
  clear text, modal dialogs sat top-left, invisible unchecked checkboxes
  in dark mode.
- Parallel run: compose.parallel.yaml, AUTO_RULE_SYNC_DISABLED switch and
  docs/operations.md §8 (start, rollback, cutover).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 18:24:05 +01:00

454 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { useMemo, useState } from "react";
import Link from "next/link";
import { Alert, Badge, Checkbox, EmptyState, Table, Textarea } from "@sakaniui/react";
import { IconDownload, IconFileText } from "@sakaniui/react/icons";
import { Button } from "@/components/ui/button";
import { Card, FormSelect } from "@/components/ui/sakani";
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
import { formatCents } from "@/modules/billing/format";
import type { FinalizedReportSummary } from "./page-content";
type BillingSelectionProps = {
editorialId: string;
positions: BillingPosition[];
repeatDownloads: RepeatDownloadPosition[];
year: number;
month: number | null;
quarter: number | null;
isQuarter: boolean;
periodLabel: string;
reports: FinalizedReportSummary[];
};
const MONTHS = [
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember",
];
const STATUS_LABELS: Record<BillingPosition["status"], string> = {
open: "Offen",
billed: "Abgerechnet",
reopened: "Wiedereröffnet",
};
const STATUS_BADGES: Record<BillingPosition["status"], "warning" | "success"> = {
open: "warning",
billed: "success",
reopened: "warning",
};
const REPORT_STATUS_LABELS: Record<string, string> = {
draft: "Entwurf",
final: "Erstellt",
cancelled: "Storniert",
};
export function BillingSelection({
editorialId,
positions,
repeatDownloads,
year,
month,
quarter,
isQuarter,
periodLabel,
reports,
}: BillingSelectionProps) {
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [actionState, setActionState] = useState<{
loading: boolean;
message: string | null;
isError: boolean;
}>({ loading: false, message: null, isError: false });
const selectablePositions = useMemo(
() => positions.filter((p) => p.selectable),
[positions],
);
const selectedCount = selectedIds.size;
const selectedTotalCents = useMemo(
() =>
positions.reduce(
(sum, p) => (selectedIds.has(p.id) ? sum + p.priceCents : sum),
0,
),
[positions, selectedIds],
);
function togglePosition(id: string) {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
function selectAllOpen() {
setSelectedIds(new Set(selectablePositions.map((p) => p.id)));
}
function clearSelection() {
setSelectedIds(new Set());
}
const periodPayload = { year, ...(isQuarter ? { quarter: quarter ?? 1 } : { month: month ?? 1 }) };
async function handlePreview() {
if (selectedIds.size === 0) return;
setActionState({ loading: true, message: null, isError: false });
try {
const response = await fetch("/api/billing-reports/preview", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
editorialId,
usageIds: [...selectedIds],
...periodPayload,
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(body.code ?? "Vorschau fehlgeschlagen");
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
window.open(url, "_blank");
URL.revokeObjectURL(url);
setActionState({ loading: false, message: null, isError: false });
} catch (error) {
setActionState({
loading: false,
message: error instanceof Error ? error.message : "Vorschau fehlgeschlagen",
isError: true,
});
}
}
async function handleFinalize() {
if (selectedIds.size === 0) return;
setActionState({ loading: true, message: null, isError: false });
try {
const response = await fetch("/api/billing-reports", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
editorialId,
usageIds: [...selectedIds],
...periodPayload,
}),
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(body.code ?? "Abrechnung konnte nicht erstellt werden");
}
const result = await response.json();
setActionState({
loading: false,
message: `Abrechnung Nr. ${result.reportNumber} wurde erstellt.`,
isError: false,
});
window.location.reload();
} catch (error) {
setActionState({
loading: false,
message: error instanceof Error ? error.message : "Abrechnung fehlgeschlagen",
isError: true,
});
}
}
const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3);
const quarterHref = quarter
? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}`
: `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarterParam}`;
const monthHref = `/admin/abrechnungen/${editorialId}?year=${year}&month=${month ?? (quarter ? (quarter - 1) * 3 + 1 : new Date().getUTCMonth() + 1)}`;
return (
<>
<PeriodSelector year={year} month={month} quarter={quarter} isQuarter={isQuarter} />
<div className="flex flex-wrap items-center gap-3">
<Button type="button" variant="secondary" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
{isQuarter ? "Alle offenen im Quartal" : "Alle offenen im Monat"}
</Button>
<Button asChild variant="outline">
{isQuarter ? <Link href={monthHref}>Monatsansicht</Link> : <Link href={quarterHref}>Ganzes Quartal</Link>}
</Button>
<Button type="button" variant="ghost" onClick={clearSelection} disabled={selectedCount === 0}>
Auswahl aufheben
</Button>
<p className="ml-auto text-sm text-[var(--color-fg-muted)]" aria-live="polite">
Zeitraum: {periodLabel}
</p>
</div>
<section className="flex flex-col gap-3" aria-labelledby="positions-title">
<h2 id="positions-title" className="text-lg font-semibold">Abrechenbare Nutzungen</h2>
{positions.length === 0 ? (
<EmptyState title="Keine abrechenbaren Nutzungen in diesem Zeitraum." description="Wählen Sie oben einen anderen Monat oder ein Quartal." />
) : (
<Table<BillingPosition>
rowKey={(position) => position.id}
rows={positions}
columns={[
{
key: "id",
header: "Auswahl",
render: (position) => (
<Checkbox
aria-label={`${position.filename} auswählen`}
checked={selectedIds.has(position.id)}
disabled={!position.selectable}
onChange={() => togglePosition(position.id)}
/>
),
},
{ key: "filename", header: "Datei" },
{ key: "albumName", header: "Album" },
{ key: "purpose", header: "Zweck" },
{ key: "reference", header: "Referenz", render: (position) => position.reference ?? "—" },
{
key: "priceCents",
header: "Preis",
align: "right",
render: (position) => <span className="tabular-nums">{formatCents(position.priceCents)}</span>,
},
{
key: "status",
header: "Status",
render: (position) => (
<span className="flex flex-wrap items-center gap-2">
<Badge variant={STATUS_BADGES[position.status] ?? "neutral"}>{STATUS_LABELS[position.status]}</Badge>
{position.status === "billed" && position.reportNumber !== null && (
<span className="text-xs text-[var(--color-fg-muted)]">
Bericht Nr. {position.reportNumber}
{position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""}
</span>
)}
</span>
),
},
]}
/>
)}
</section>
{repeatDownloads.length > 0 && (
<section aria-labelledby="repeat-downloads-title" className="flex flex-col gap-3">
<h2 id="repeat-downloads-title" className="text-lg font-semibold">Kostenlose Wiederabrufe</h2>
<p className="text-sm text-[var(--color-fg-muted)]">
Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht
abrechenbar.
</p>
<Table<RepeatDownloadPosition>
rowKey={(download) => download.id}
rows={repeatDownloads}
columns={[
{ key: "assetId", header: "Datei" },
{
key: "authorizedAt",
header: "Datum",
render: (download) => (
<time dateTime={download.authorizedAt.toISOString()} suppressHydrationWarning>
{download.authorizedAt.toLocaleDateString("de-DE")}
</time>
),
},
{ key: "status", header: "Status" },
{ key: "repeatDownloadNote", header: "Notiz", render: (download) => download.repeatDownloadNote ?? "—" },
]}
/>
</section>
)}
<Card>
<div className="flex flex-wrap items-center justify-between gap-4">
<div aria-live="polite" className="billing-summary flex flex-col gap-1">
<p className="text-sm text-[var(--color-fg-muted)]">
<strong className="text-[var(--color-fg-default)]">{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
</p>
<p className="text-2xl font-semibold tabular-nums">
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
</p>
</div>
<div className="flex flex-wrap gap-3">
<Button type="button" variant="outline" onClick={handlePreview} disabled={selectedCount === 0 || actionState.loading}>
Vorschau
</Button>
<Button type="button" onClick={handleFinalize} disabled={selectedCount === 0 || actionState.loading}>
Abrechnung erstellen
</Button>
</div>
</div>
{actionState.message && (
<div role={actionState.isError ? undefined : "status"}>
<Alert color={actionState.isError ? "danger" : "info"} description={actionState.message} />
</div>
)}
</Card>
{reports.length > 0 && (
<section aria-labelledby="reports-title" className="flex flex-col gap-3">
<h2 id="reports-title" className="text-lg font-semibold">Erstellte Abrechnungen</h2>
<ul className="flex flex-col gap-3">
{reports.map((report) => (
<li key={report.id}>
<Card>
<div className="flex flex-wrap items-center gap-x-4 gap-y-2 text-sm">
<span className="inline-flex items-center gap-2 font-semibold">
<IconFileText size={16} aria-hidden="true" />
Bericht Nr. {report.reportNumber}
</span>
{report.invoiceNumber && <span>{report.invoiceNumber}</span>}
<span className="tabular-nums">Summe: {formatCents(report.netTotalCents)}</span>
<Badge variant={report.status === "final" ? "success" : "neutral"}>
{REPORT_STATUS_LABELS[report.status] ?? report.status}
</Badge>
<span className="text-[var(--color-fg-muted)]">
Erstellt am:{" "}
<time dateTime={report.createdAt.toISOString()} suppressHydrationWarning>
{report.createdAt.toLocaleDateString("de-DE")}
</time>
</span>
{report.status === "final" && (
<Button asChild variant="outline">
<a className="ml-auto" href={`/api/billing-reports/${encodeURIComponent(report.id)}`} download>
<IconDownload size={16} aria-hidden="true" />
PDF herunterladen
</a>
</Button>
)}
</div>
{report.status === "final" && (
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
)}
</Card>
</li>
))}
</ul>
</section>
)}
</>
);
}
type PeriodSelectorProps = {
year: number;
month: number | null;
quarter: number | null;
isQuarter: boolean;
};
function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps) {
const years = [2025, 2026, 2027];
return (
<Card>
<form className="flex flex-wrap items-end gap-4" method="get">
<div className="w-32">
<FormSelect name="year" label="Jahr" defaultValue={String(year)} options={years.map((y) => ({ label: String(y), value: String(y) }))} />
</div>
{isQuarter ? (
<div className="w-32">
<FormSelect
name="quarter"
label="Quartal"
defaultValue={String(quarter ?? 1)}
options={[1, 2, 3, 4].map((q) => ({ label: `Q${q}`, value: String(q) }))}
/>
</div>
) : (
<div className="w-40">
<FormSelect
name="month"
label="Monat"
defaultValue={String(month ?? 8)}
options={MONTHS.map((name, index) => ({ label: name, value: String(index + 1) }))}
/>
</div>
)}
<Button type="submit" variant="secondary">Zeitraum laden</Button>
</form>
</Card>
);
}
type CancelReportFormProps = {
reportId: string;
reportNumber: number;
};
function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
const [reason, setReason] = useState("");
const [confirmed, setConfirmed] = useState(false);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const trimmed = reason.trim();
const valid = trimmed.length >= 5 && trimmed.length <= 500 && confirmed;
async function handleSubmit(event: React.FormEvent) {
event.preventDefault();
if (!valid) return;
setLoading(true);
setError(null);
try {
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/cancel`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ reason: trimmed, confirm: true }),
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(body.code ?? "Stornierung fehlgeschlagen");
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Stornierung fehlgeschlagen");
setLoading(false);
}
}
return (
<form className="flex flex-col gap-3 border-t border-[var(--color-border-subtle)] pt-4" onSubmit={handleSubmit}>
<Textarea
aria-label={`Stornierungsgrund für Bericht Nr. ${reportNumber}`}
disabled={loading}
label="Stornierungsgrund (5–500 Zeichen)"
maxLength={500}
onChange={(e) => setReason(e.target.value)}
rows={2}
value={reason}
/>
<div className="flex flex-wrap items-center gap-4">
<Checkbox
checked={confirmed}
disabled={loading}
label="Stornierung bestätigen"
onChange={(e) => setConfirmed(e.target.checked)}
/>
<Button type="submit" variant="destructive" disabled={!valid || loading}>
{loading ? "Wird storniert …" : "Stornieren"}
</Button>
</div>
{error && <Alert color="danger" description={error} />}
</form>
);
}