Files
immich-redaktions-plugin/src/app/admin/abrechnungen/[editorialId]/BillingSelection.tsx
T
Leon TonhäuserandClaude Opus 5.5 c0c2425dda Merge v2.1-2.2.0 features onto SakaniUI base
Ports calendar, self-service, sorting, image descriptions, logo (2.1),
filename search (2.1.1), statistics page, collab option and bundled
invoice PDF delivery (2.2.0) onto the deployed SakaniUI portal.

Also fixes the statistics daily series, which ended yesterday and so
hid today's activity from the charts, and ignores Playwright
test-results/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 22:19:34 +01:00

635 lines
23 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,
});
}
}
async function handleToggleCollab(position: BillingPosition) {
setActionState({ loading: true, message: null, isError: false });
try {
const response = await fetch(`/api/usages/${encodeURIComponent(position.id)}/collab`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ collab: !position.collab }),
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(body.code ?? "Collab-Kennzeichnung fehlgeschlagen");
}
window.location.reload();
} catch (error) {
setActionState({
loading: false,
message: error instanceof Error ? error.message : "Collab-Kennzeichnung 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="flex flex-col items-end gap-1">
<span className="flex items-center gap-2 tabular-nums">
{formatCents(position.priceCents)}
{position.collab && <Badge variant="neutral">Collab</Badge>}
</span>
{position.selectable && (
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => handleToggleCollab(position)}
disabled={actionState.loading}
>
{position.collab ? "Collab entfernen" : "Als Collab markieren"}
</Button>
)}
</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" />
Nutzungsnachweis herunterladen
</a>
</Button>
)}
</div>
{report.status === "final" && (
<div className="flex flex-col gap-3 rounded-[var(--radius-lg)] border border-[var(--color-border-subtle)] bg-[var(--color-bg-subtle)] p-4">
<p className="text-sm font-medium">
Rechnung:{" "}
{report.invoiceEmailStatus === "sent" ? (
<>
versendet am{" "}
<time
dateTime={report.invoiceEmailSentAt?.toISOString()}
suppressHydrationWarning
>
{report.invoiceEmailSentAt?.toLocaleDateString("de-DE")}
</time>
</>
) : report.hasInvoicePdf ? (
"PDF hinterlegt, Versand fehlgeschlagen"
) : (
"noch keine PDF hinterlegt"
)}
</p>
<InvoiceUploadForm
reportId={report.id}
reportNumber={report.reportNumber}
hasInvoice={report.hasInvoicePdf}
emailFailed={report.hasInvoicePdf && report.invoiceEmailStatus === "failed"}
/>
{report.hasInvoicePdf && (
<Button asChild variant="outline">
<a href={`/api/billing-reports/${encodeURIComponent(report.id)}/invoice`} download>
<IconDownload size={16} aria-hidden="true" />
Rechnungs-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 InvoiceUploadFormProps = {
reportId: string;
reportNumber: number;
hasInvoice: boolean;
emailFailed: boolean;
};
function InvoiceUploadForm({ reportId, reportNumber, hasInvoice, emailFailed }: InvoiceUploadFormProps) {
const [file, setFile] = useState<File | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
async function handleUpload(event: React.FormEvent) {
event.preventDefault();
if (!file || loading) return;
setLoading(true);
setError(null);
try {
const formData = new FormData();
formData.set("invoice", file);
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/invoice`, {
method: "POST",
body: formData,
});
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(invoiceErrorMessage(body.code));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Upload fehlgeschlagen");
setLoading(false);
}
}
async function handleResend() {
if (loading) return;
setLoading(true);
setError(null);
try {
const response = await fetch(
`/api/billing-reports/${encodeURIComponent(reportId)}/invoice/resend`,
{ method: "POST" },
);
if (!response.ok) {
const body = await response.json().catch(() => ({ code: "ERROR" }));
throw new Error(invoiceErrorMessage(body.code));
}
window.location.reload();
} catch (err) {
setError(err instanceof Error ? err.message : "Versand fehlgeschlagen");
setLoading(false);
}
}
return (
<form className="flex flex-col gap-3" onSubmit={handleUpload}>
<label className="flex flex-col gap-1 text-sm font-medium">
<span>
{hasInvoice ? "Rechnungs-PDF ersetzen" : "Rechnungs-PDF hochladen"} (Bericht Nr. {reportNumber})
</span>
<input
type="file"
accept="application/pdf,.pdf"
required
disabled={loading}
onChange={(event) => setFile(event.target.files?.[0] ?? null)}
aria-label={`Rechnungs-PDF für Bericht Nr. ${reportNumber}`}
className="text-sm text-[var(--color-fg-muted)] file:mr-3 file:rounded-[var(--radius-md)] file:border file:border-[var(--color-border-subtle)] file:bg-[var(--color-bg-surface)] file:px-3 file:py-1.5 file:text-sm file:font-medium file:text-[var(--color-fg-default)]"
/>
</label>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={!file || loading}>
{loading ? "Wird gesendet…" : "Hochladen & senden"}
</Button>
{hasInvoice && (
<Button type="button" variant="outline" onClick={handleResend} disabled={loading}>
{emailFailed ? "Erneut senden" : "Nochmal senden"}
</Button>
)}
</div>
<p className="text-xs text-[var(--color-fg-muted)]">
Nach dem Upload geht die Rechnung gebündelt mit dem Nutzungsnachweis automatisch per
E-Mail an die Redaktion.
</p>
{error && <Alert color="danger" description={error} />}
</form>
);
}
function invoiceErrorMessage(code: unknown): string {
switch (code) {
case "INVALID_PDF":
return "Die Datei ist keine gültige PDF (max. 20 MB).";
case "REPORT_NOT_FINAL":
return "Der Bericht ist nicht finalisiert.";
case "INVOICE_NOT_UPLOADED":
return "Es ist noch keine Rechnungs-PDF hinterlegt.";
case "RATE_LIMITED":
return "Zu viele Versuche. Bitte kurz warten.";
default:
return "Der Vorgang ist fehlgeschlagen. Bitte erneut versuchen.";
}
}
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>
);
}