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>
);
}