feat: add billing period selection

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Leon TonhäuserandClaude committed 2026-08-10 17:31:42 +02:00
1 parent ba673ad732
commit d37affc80f
15 files changed
+1625

No files matched your search

@@ -0,0 +1,204 @@
// @vitest-environment jsdom
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
import { afterEach, expect, test } from "vitest";
import { BillingSelection } from "./BillingSelection";
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
afterEach(cleanup);
const openPosition: BillingPosition = {
id: "u1",
assetId: "asset-1",
filename: "jubel.jpg",
albumName: "Presse 2026",
purpose: "Titelgeschichte",
reference: "Ausgabe 8/26",
priceCents: 6_000,
status: "open",
selectable: true,
createdAt: new Date("2026-08-05T10:00:00.000Z"),
reportNumber: null,
invoiceNumber: null,
};
const billedPosition: BillingPosition = {
id: "u2",
assetId: "asset-2",
filename: "sport.jpg",
albumName: "Presse 2026",
purpose: "Sportbericht",
reference: null,
priceCents: 1_500,
status: "billed",
selectable: false,
createdAt: new Date("2026-08-06T10:00:00.000Z"),
reportNumber: 42,
invoiceNumber: "RE-2026-042",
};
const reopenedPosition: BillingPosition = {
id: "u3",
assetId: "asset-3",
filename: "redaktion.jpg",
albumName: "Presse 2026",
purpose: "Reopened",
reference: null,
priceCents: 1_500,
status: "reopened",
selectable: true,
createdAt: new Date("2026-08-07T10:00:00.000Z"),
reportNumber: null,
invoiceNumber: null,
};
const repeatDownload: RepeatDownloadPosition = {
id: "d1",
assetId: "asset-1",
usageId: "u1",
authorizedAt: new Date("2026-08-10T12:00:00.000Z"),
status: "completed",
repeatDownloadNote: "Zweite Nutzung",
};
const defaultProps = {
editorialId: "e1",
repeatDownloads: [] as RepeatDownloadPosition[],
year: 2026,
month: 8 as number | null,
quarter: null as number | null,
isQuarter: false,
periodLabel: "August 2026",
};
function getCheckbox(filename: string): HTMLInputElement {
return screen.getByRole("checkbox", {
name: `${filename} auswählen`,
}) as HTMLInputElement;
}
test("renders billable positions with individual checkboxes", () => {
render(
<BillingSelection
{...defaultProps}
positions={[openPosition, billedPosition]}
/>,
);
expect(screen.getByText("jubel.jpg")).toBeTruthy();
expect(screen.getByText("sport.jpg")).toBeTruthy();
expect(getCheckbox("jubel.jpg").checked).toBe(false);
});
test("disables the checkbox for billed positions and shows report reference", () => {
render(
<BillingSelection
{...defaultProps}
positions={[billedPosition]}
/>,
);
const checkbox = getCheckbox("sport.jpg");
expect(checkbox.disabled).toBe(true);
expect(screen.getByText(/Bericht Nr\. 42/)).toBeTruthy();
expect(screen.getByText(/RE-2026-042/)).toBeTruthy();
});
test("selects all open positions via Alle offenen im Monat", () => {
render(
<BillingSelection
{...defaultProps}
positions={[openPosition, billedPosition, reopenedPosition]}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i }));
expect(getCheckbox("jubel.jpg").checked).toBe(true);
expect(getCheckbox("redaktion.jpg").checked).toBe(true);
expect(getCheckbox("sport.jpg").checked).toBe(false);
});
test("clears the selection via Auswahl aufheben", () => {
render(
<BillingSelection
{...defaultProps}
positions={[openPosition]}
/>,
);
const checkbox = getCheckbox("jubel.jpg");
fireEvent.click(checkbox);
expect(checkbox.checked).toBe(true);
fireEvent.click(screen.getByRole("button", { name: /Auswahl aufheben/i }));
expect(checkbox.checked).toBe(false);
});
test("displays selected count and cents-derived EUR total", () => {
const { container } = render(
<BillingSelection
{...defaultProps}
positions={[openPosition, reopenedPosition]}
/>,
);
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i }));
const summary = container.querySelector(".billing-summary");
expect(summary?.textContent ?? "").toMatch(/2 Nutzungen ausgewählt/);
expect(summary?.textContent ?? "").toMatch(/75,00 EUR/);
});
test("renders repeat downloads in a separate section", () => {
render(
<BillingSelection
{...defaultProps}
positions={[openPosition]}
repeatDownloads={[repeatDownload]}
/>,
);
expect(screen.getByText(/Kostenlose Wiederabrufe/)).toBeTruthy();
expect(screen.getByText("Zweite Nutzung")).toBeTruthy();
});
test("shows empty state when no billable positions exist", () => {
render(
<BillingSelection
{...defaultProps}
positions={[]}
/>,
);
expect(screen.getByText(/Keine abrechenbaren Nutzungen/)).toBeTruthy();
});
test("links to quarter view from month view", () => {
render(
<BillingSelection
{...defaultProps}
positions={[openPosition]}
/>,
);
const quarterLink = screen.getByRole("link", { name: /Ganzes Quartal/i });
expect(quarterLink.getAttribute("href") ?? "").toContain("quarter=3");
});
test("links to month view from quarter view", () => {
render(
<BillingSelection
{...defaultProps}
positions={[openPosition]}
month={null}
quarter={3}
isQuarter={true}
periodLabel="Q3 2026"
/>,
);
const monthLink = screen.getByRole("link", { name: /Monatsansicht/i });
expect(monthLink.getAttribute("href") ?? "").toContain("month=");
});
@@ -0,0 +1,264 @@
"use client";
import { useMemo, useState } from "react";
import Link from "next/link";
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
import { formatCents } from "@/modules/billing/format";
type BillingSelectionProps = {
editorialId: string;
positions: BillingPosition[];
repeatDownloads: RepeatDownloadPosition[];
year: number;
month: number | null;
quarter: number | null;
isQuarter: boolean;
periodLabel: string;
};
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",
};
export function BillingSelection({
editorialId,
positions,
repeatDownloads,
year,
month,
quarter,
isQuarter,
periodLabel,
}: BillingSelectionProps) {
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
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 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="billing-selection-controls">
<button type="button" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
{isQuarter ? "Alle offenen im Quartal" : "Alle offenen im Monat"}
</button>
{isQuarter ? (
<Link href={monthHref} className="billing-nav-link">
Monatsansicht
</Link>
) : (
<Link href={quarterHref} className="billing-nav-link">
Ganzes Quartal
</Link>
)}
<button type="button" onClick={clearSelection} disabled={selectedCount === 0}>
Auswahl aufheben
</button>
</div>
<p className="billing-period-label" aria-live="polite">
Zeitraum: {periodLabel}
</p>
{positions.length === 0 ? (
<p className="billing-empty">Keine abrechenbaren Nutzungen in diesem Zeitraum.</p>
) : (
<table className="billing-table">
<caption className="billing-caption">
Abrechenbare Nutzungen
</caption>
<thead>
<tr>
<th scope="col">Auswahl</th>
<th scope="col">Datei</th>
<th scope="col">Album</th>
<th scope="col">Zweck</th>
<th scope="col">Referenz</th>
<th scope="col">Preis</th>
<th scope="col">Status</th>
</tr>
</thead>
<tbody>
{positions.map((position) => (
<tr key={position.id} className={position.selectable ? "" : "billing-row-billed"}>
<td>
<input
type="checkbox"
checked={selectedIds.has(position.id)}
onChange={() => togglePosition(position.id)}
disabled={!position.selectable}
aria-label={`${position.filename} auswählen`}
/>
</td>
<td>{position.filename}</td>
<td>{position.albumName}</td>
<td>{position.purpose}</td>
<td>{position.reference ?? "—"}</td>
<td className="billing-price">{formatCents(position.priceCents)}</td>
<td>
<span className="billing-status">
{STATUS_LABELS[position.status]}
{position.status === "billed" && position.reportNumber !== null && (
<span className="billing-report-ref">
{" "}· Bericht Nr. {position.reportNumber}
{position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""}
</span>
)}
</span>
</td>
</tr>
))}
</tbody>
</table>
)}
{repeatDownloads.length > 0 && (
<section aria-labelledby="repeat-downloads-title" className="billing-repeat-section">
<h2 id="repeat-downloads-title">Kostenlose Wiederabrufe</h2>
<p className="form-note">
Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht
abrechenbar.
</p>
<table className="billing-table billing-table-repeat">
<caption className="billing-caption">Wiederabrufe im Zeitraum</caption>
<thead>
<tr>
<th scope="col">Datei</th>
<th scope="col">Datum</th>
<th scope="col">Status</th>
<th scope="col">Notiz</th>
</tr>
</thead>
<tbody>
{repeatDownloads.map((download) => (
<tr key={download.id}>
<td>{download.assetId}</td>
<td>
<time dateTime={download.authorizedAt.toISOString()}>
{download.authorizedAt.toLocaleDateString("de-DE")}
</time>
</td>
<td>{download.status}</td>
<td>{download.repeatDownloadNote ?? "—"}</td>
</tr>
))}
</tbody>
</table>
</section>
)}
<div className="billing-summary" aria-live="polite">
<p>
<strong>{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
</p>
<p className="billing-summary-total">
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
</p>
</div>
</>
);
}
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 (
<form className="billing-period-selector" method="get">
<label>
<span>Jahr</span>
<select name="year" defaultValue={year}>
{years.map((y) => (
<option key={y} value={y}>
{y}
</option>
))}
</select>
</label>
{isQuarter ? (
<label>
<span>Quartal</span>
<select name="quarter" defaultValue={quarter ?? 1}>
{[1, 2, 3, 4].map((q) => (
<option key={q} value={q}>
Q{q}
</option>
))}
</select>
</label>
) : (
<label>
<span>Monat</span>
<select name="month" defaultValue={month ?? 8}>
{MONTHS.map((name, index) => (
<option key={index} value={index + 1}>
{name}
</option>
))}
</select>
</label>
)}
<button type="submit">Zeitraum laden</button>
</form>
);
}
@@ -0,0 +1,121 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { queries } from "@/modules/billing/queries";
import { monthPeriod, quarterPeriod, type BillingPeriod } from "@/modules/billing/period";
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
export type BillingSelectionData = {
editorial: { id: string; name: string };
period: BillingPeriod;
periodLabel: string;
isQuarter: boolean;
year: number;
month: number | null;
quarter: number | null;
positions: BillingPosition[];
repeatDownloads: RepeatDownloadPosition[];
};
export async function loadBillingSelection(
editorialId: string,
searchParams: Record<string, string | string[] | undefined>,
): Promise<BillingSelectionData | null> {
const [editorial] = await db
.select({ id: editorialAccounts.id, name: editorialAccounts.name })
.from(editorialAccounts)
.where(eq(editorialAccounts.id, editorialId))
.limit(1);
if (!editorial) return null;
const { period, isQuarter, year, month, quarter, periodLabel } = resolvePeriod(searchParams);
const [positions, repeatDownloads] = await Promise.all([
queries.listBillablePositions(editorialId, period),
queries.listNonBillableDownloads(editorialId, period),
]);
return {
editorial,
period,
periodLabel,
isQuarter,
year,
month,
quarter,
positions,
repeatDownloads,
};
}
export function resolvePeriod(searchParams: Record<string, string | string[] | undefined>): {
period: BillingPeriod;
isQuarter: boolean;
year: number;
month: number | null;
quarter: number | null;
periodLabel: string;
} {
const now = new Date();
const defaultYear = now.getUTCFullYear();
const defaultMonth = now.getUTCMonth() + 1;
const year = parseNumberParam(searchParams.year, defaultYear);
const quarterParam = firstParam(searchParams.quarter);
if (quarterParam !== undefined) {
const quarter = parseNumberParam(searchParams.quarter, Math.floor((defaultMonth - 1) / 3) + 1);
return {
period: quarterPeriod(year, quarter),
isQuarter: true,
year,
month: null,
quarter,
periodLabel: `Q${quarter} ${year}`,
};
}
const month = parseNumberParam(searchParams.month, defaultMonth);
return {
period: monthPeriod(year, month),
isQuarter: false,
year,
month,
quarter: null,
periodLabel: monthLabel(year, month),
};
}
function monthLabel(year: number, month: number): string {
const names = [
"Januar",
"Februar",
"März",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember",
];
return `${names[month - 1]} ${year}`;
}
function parseNumberParam(
value: string | string[] | undefined,
fallback: number,
): number {
const parsed = Number.parseInt(firstParam(value) ?? "", 10);
return Number.isFinite(parsed) ? parsed : fallback;
}
function firstParam(value: string | string[] | undefined): string | undefined {
if (Array.isArray(value)) return value[0];
return value;
}
@@ -0,0 +1,39 @@
import Link from "next/link";
import { notFound } from "next/navigation";
import { loadBillingSelection } from "./page-content";
import { BillingSelection } from "./BillingSelection";
export default async function BillingSelectionPage({
params,
searchParams,
}: Readonly<{
params: Promise<{ editorialId: string }>;
searchParams: Promise<Record<string, string | string[] | undefined>>;
}>) {
const { editorialId } = await params;
const sp = await searchParams;
const data = await loadBillingSelection(editorialId, sp);
if (!data) notFound();
return (
<section className="content-section" aria-labelledby="billing-selection-title">
<p className="eyebrow">Abrechnungen</p>
<h1 id="billing-selection-title">{data.editorial.name}</h1>
<p>
<Link href="/admin/abrechnungen">Zurück zur Übersicht</Link>
</p>
<BillingSelection
editorialId={data.editorial.id}
positions={data.positions}
repeatDownloads={data.repeatDownloads}
year={data.year}
month={data.month}
quarter={data.quarter}
isQuarter={data.isQuarter}
periodLabel={data.periodLabel}
/>
</section>
);
}
+47
View File
@@ -0,0 +1,47 @@
import { desc } from "drizzle-orm";
import { db } from "@/db/client";
import { editorialAccounts } from "@/db/schema";
import { formatCents } from "@/modules/billing/format";
export default async function BillingOverviewPage() {
const editorials = await db
.select({
id: editorialAccounts.id,
name: editorialAccounts.name,
contactName: editorialAccounts.contactName,
loginEmail: editorialAccounts.loginEmail,
status: editorialAccounts.status,
currentPriceCents: editorialAccounts.currentPriceCents,
})
.from(editorialAccounts)
.orderBy(desc(editorialAccounts.createdAt));
return (
<section className="content-section" aria-labelledby="billing-title">
<p className="eyebrow">Abrechnungen</p>
<h1 id="billing-title">Redaktionen</h1>
<p className="form-note">
Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal
auszuwählen.
</p>
{editorials.length === 0 ? (
<p>Noch keine Redaktionen registriert.</p>
) : (
<ul className="billing-editorial-list">
{editorials.map((editorial) => (
<li key={editorial.id}>
<a href={`/admin/abrechnungen/${editorial.id}`}>{editorial.name}</a>
<p>
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status}
{editorial.currentPriceCents === null
? " · Preis noch nicht festgelegt"
: ` · Netto ${formatCents(editorial.currentPriceCents)}`}
</p>
</li>
))}
</ul>
)}
</section>
);
}
+1
View File
@@ -18,6 +18,7 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea
</header>
<nav aria-label="Administration">
<Link href="/admin/redaktionen">Redaktionen</Link>
<Link href="/admin/abrechnungen">Abrechnungen</Link>
</nav>
{children}
</main>
+298
View File
@@ -961,3 +961,301 @@ a {
flex-direction: column-reverse;
}
}
/* Billing selection */
.content-section {
width: min(100%, 108rem);
margin: 0 auto;
padding: clamp(2rem, 5vw, 5.5rem) clamp(1.25rem, 4vw, 5rem) 5rem;
}
.content-section h1 {
max-width: 15ch;
margin: 0 0 1.5rem;
font-size: clamp(2.5rem, 5vw, 5.5rem);
font-weight: 600;
letter-spacing: -0.065em;
line-height: 0.9;
}
.content-section > p {
max-width: 44rem;
margin: 0 0 2rem;
color: var(--graphite);
font-size: 0.95rem;
line-height: 1.5;
}
.billing-editorial-list {
display: grid;
gap: 1.25rem;
padding: 0;
list-style: none;
}
.billing-editorial-list li {
padding-bottom: 1.25rem;
border-bottom: 1px solid var(--line);
}
.billing-editorial-list a {
font-size: 1.15rem;
font-weight: 650;
text-decoration: none;
}
.billing-editorial-list a:hover {
text-decoration: underline;
text-underline-offset: 0.2em;
}
.billing-editorial-list p {
margin: 0.35rem 0 0;
color: var(--metadata);
font-size: 0.85rem;
}
.billing-period-selector {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: 1rem;
margin-bottom: 2rem;
padding-bottom: 1.25rem;
border-bottom: 1px solid var(--ink);
}
.billing-period-selector label {
display: grid;
gap: 0.35rem;
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.billing-period-selector select {
min-width: 8rem;
min-height: 2.8rem;
border: 1px solid var(--ink);
border-radius: 0;
background: var(--paper);
color: var(--ink);
font: inherit;
font-size: 0.875rem;
padding: 0.4rem 0.6rem;
}
.billing-period-selector button {
min-height: 2.8rem;
border: 1px solid var(--ink);
border-radius: 0;
background: var(--ink);
color: var(--paper);
cursor: pointer;
font: inherit;
font-size: 0.8rem;
font-weight: 700;
padding-inline: 1rem;
}
.billing-period-selector button:hover {
background: var(--graphite);
}
.billing-period-selector a {
align-self: center;
font-size: 0.8125rem;
font-weight: 650;
text-underline-offset: 0.2em;
}
.billing-selection-controls {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
margin-bottom: 1.5rem;
}
.billing-selection-controls button {
min-height: 2.6rem;
border: 1px solid var(--ink);
border-radius: 0;
background: var(--paper);
color: var(--ink);
cursor: pointer;
font: inherit;
font-size: 0.8rem;
font-weight: 700;
padding-inline: 1rem;
}
.billing-selection-controls button:hover:not(:disabled) {
background: var(--ink);
color: var(--paper);
}
.billing-selection-controls button:disabled {
border-color: var(--line);
color: var(--metadata);
cursor: not-allowed;
}
.billing-nav-link {
display: inline-flex;
align-items: center;
min-height: 2.6rem;
border: 1px solid var(--ink);
border-radius: 0;
background: var(--paper);
color: var(--ink);
font: inherit;
font-size: 0.8rem;
font-weight: 700;
padding-inline: 1rem;
text-decoration: none;
}
.billing-nav-link:hover {
background: var(--ink);
color: var(--paper);
}
.billing-period-label {
margin: 0 0 1.5rem;
color: var(--metadata);
font-size: 0.8125rem;
font-weight: 650;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.billing-empty {
max-width: 38rem;
color: var(--graphite);
font-size: 1rem;
line-height: 1.55;
}
.billing-table {
width: 100%;
border-collapse: collapse;
font-size: 0.85rem;
}
.billing-caption {
margin-bottom: 0.75rem;
color: var(--metadata);
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
text-align: left;
caption-side: top;
}
.billing-table thead th {
padding: 0.6rem 0.5rem;
border-bottom: 1px solid var(--ink);
color: var(--metadata);
font-size: 0.65rem;
font-weight: 700;
letter-spacing: 0.08em;
text-align: left;
text-transform: uppercase;
}
.billing-table tbody td {
padding: 0.65rem 0.5rem;
border-bottom: 1px solid var(--line);
vertical-align: top;
}
.billing-table tbody tr.billing-row-billed {
background: var(--soft);
color: var(--metadata);
}
.billing-row-billed td {
color: var(--metadata);
}
.billing-row-billed .billing-status {
font-style: italic;
}
.billing-report-ref {
display: block;
margin-top: 0.15rem;
font-size: 0.7rem;
font-style: normal;
}
.billing-price {
text-align: right;
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.billing-status {
font-size: 0.75rem;
font-weight: 650;
}
.billing-repeat-section {
margin-top: 3rem;
padding-top: 1.5rem;
border-top: 1px solid var(--ink);
}
.billing-repeat-section h2 {
margin: 0 0 0.5rem;
font-size: 1.15rem;
font-weight: 650;
letter-spacing: -0.02em;
}
.billing-table-repeat {
margin-top: 1rem;
}
.billing-summary {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
gap: 1rem;
margin-top: 2rem;
padding: 1rem 0;
border-top: 2px solid var(--ink);
font-size: 0.875rem;
}
.billing-summary p {
margin: 0;
}
.billing-summary-total {
font-size: 1.1rem;
font-variant-numeric: tabular-nums;
}
.billing-summary strong {
font-weight: 700;
}
@media (max-width: 48rem) {
.billing-table {
display: block;
overflow-x: auto;
}
.billing-period-selector {
flex-direction: column;
align-items: stretch;
}
.billing-period-selector a {
align-self: flex-start;
}
}