feat: finalize immutable billing reports
Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
a384c4c35e
commit
7f1ecd9322
15 files changed
+1697
-3
No files matched your search
@@ -4,6 +4,7 @@ import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
|
||||
import { BillingSelection } from "./BillingSelection";
|
||||
import type { FinalizedReportSummary } from "./page-content";
|
||||
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
|
||||
|
||||
afterEach(cleanup);
|
||||
@@ -70,6 +71,7 @@ const defaultProps = {
|
||||
quarter: null as number | null,
|
||||
isQuarter: false,
|
||||
periodLabel: "August 2026",
|
||||
reports: [] as FinalizedReportSummary[],
|
||||
};
|
||||
|
||||
function getCheckbox(filename: string): HTMLInputElement {
|
||||
|
||||
@@ -5,6 +5,7 @@ import Link from "next/link";
|
||||
|
||||
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
|
||||
import { formatCents } from "@/modules/billing/format";
|
||||
import type { FinalizedReportSummary } from "./page-content";
|
||||
|
||||
type BillingSelectionProps = {
|
||||
editorialId: string;
|
||||
@@ -15,6 +16,7 @@ type BillingSelectionProps = {
|
||||
quarter: number | null;
|
||||
isQuarter: boolean;
|
||||
periodLabel: string;
|
||||
reports: FinalizedReportSummary[];
|
||||
};
|
||||
|
||||
const MONTHS = [
|
||||
@@ -38,6 +40,12 @@ const STATUS_LABELS: Record<BillingPosition["status"], string> = {
|
||||
reopened: "Wiedereröffnet",
|
||||
};
|
||||
|
||||
const REPORT_STATUS_LABELS: Record<string, string> = {
|
||||
draft: "Entwurf",
|
||||
final: "Erstellt",
|
||||
cancelled: "Storniert",
|
||||
};
|
||||
|
||||
export function BillingSelection({
|
||||
editorialId,
|
||||
positions,
|
||||
@@ -47,8 +55,14 @@ export function BillingSelection({
|
||||
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),
|
||||
@@ -82,6 +96,72 @@ export function BillingSelection({
|
||||
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}`
|
||||
@@ -209,6 +289,57 @@ export function BillingSelection({
|
||||
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="billing-actions">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handlePreview}
|
||||
disabled={selectedCount === 0 || actionState.loading}
|
||||
>
|
||||
Vorschau
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="billing-action-primary"
|
||||
onClick={handleFinalize}
|
||||
disabled={selectedCount === 0 || actionState.loading}
|
||||
>
|
||||
Abrechnung erstellen
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{actionState.message && (
|
||||
<p className="billing-status-message" role={actionState.isError ? "alert" : "status"}>
|
||||
{actionState.message}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{reports.length > 0 && (
|
||||
<section aria-labelledby="reports-title" className="billing-reports-section">
|
||||
<h2 id="reports-title">Erstellte Abrechnungen</h2>
|
||||
<ul className="billing-reports-list">
|
||||
{reports.map((report) => (
|
||||
<li key={report.id}>
|
||||
<div className="billing-report-meta">
|
||||
<span>Bericht Nr. {report.reportNumber}</span>
|
||||
{report.invoiceNumber && <span>{report.invoiceNumber}</span>}
|
||||
<span>Summe: {formatCents(report.netTotalCents)}</span>
|
||||
<span>Status: {REPORT_STATUS_LABELS[report.status] ?? report.status}</span>
|
||||
<span>
|
||||
Erstellt am:{" "}
|
||||
<time dateTime={report.createdAt.toISOString()}>
|
||||
{report.createdAt.toLocaleDateString("de-DE")}
|
||||
</time>
|
||||
</span>
|
||||
</div>
|
||||
{report.status === "final" && (
|
||||
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -261,4 +392,77 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
|
||||
<button type="submit">Zeitraum laden</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
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="billing-cancel-form" onSubmit={handleSubmit}>
|
||||
<label>
|
||||
<span>Stornierungsgrund (5–500 Zeichen)</span>
|
||||
<textarea
|
||||
value={reason}
|
||||
onChange={(e) => setReason(e.target.value)}
|
||||
rows={2}
|
||||
maxLength={500}
|
||||
aria-label={`Stornierungsgrund für Bericht Nr. ${reportNumber}`}
|
||||
disabled={loading}
|
||||
/>
|
||||
</label>
|
||||
<div className="billing-cancel-controls">
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={confirmed}
|
||||
onChange={(e) => setConfirmed(e.target.checked)}
|
||||
disabled={loading}
|
||||
aria-label="Stornierung bestätigen"
|
||||
/>
|
||||
<span>Stornierung bestätigen</span>
|
||||
</label>
|
||||
<button type="submit" disabled={!valid || loading}>
|
||||
{loading ? "Wird storniert…" : "Stornieren"}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="billing-status-message" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,22 @@
|
||||
import "server-only";
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { editorialAccounts } from "@/db/schema";
|
||||
import { billingReports, 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 FinalizedReportSummary = {
|
||||
id: string;
|
||||
reportNumber: number;
|
||||
invoiceNumber: string | null;
|
||||
netTotalCents: number;
|
||||
status: string;
|
||||
createdAt: Date;
|
||||
};
|
||||
|
||||
export type BillingSelectionData = {
|
||||
editorial: { id: string; name: string };
|
||||
period: BillingPeriod;
|
||||
@@ -18,6 +27,7 @@ export type BillingSelectionData = {
|
||||
quarter: number | null;
|
||||
positions: BillingPosition[];
|
||||
repeatDownloads: RepeatDownloadPosition[];
|
||||
reports: FinalizedReportSummary[];
|
||||
};
|
||||
|
||||
export async function loadBillingSelection(
|
||||
@@ -33,9 +43,21 @@ export async function loadBillingSelection(
|
||||
|
||||
const { period, isQuarter, year, month, quarter, periodLabel } = resolvePeriod(searchParams);
|
||||
|
||||
const [positions, repeatDownloads] = await Promise.all([
|
||||
const [positions, repeatDownloads, reportRows] = await Promise.all([
|
||||
queries.listBillablePositions(editorialId, period),
|
||||
queries.listNonBillableDownloads(editorialId, period),
|
||||
db
|
||||
.select({
|
||||
id: billingReports.id,
|
||||
reportNumber: billingReports.reportNumber,
|
||||
invoiceNumber: billingReports.invoiceNumber,
|
||||
netTotalCents: billingReports.netTotalCents,
|
||||
status: billingReports.status,
|
||||
createdAt: billingReports.createdAt,
|
||||
})
|
||||
.from(billingReports)
|
||||
.where(eq(billingReports.editorialAccountId, editorialId))
|
||||
.orderBy(desc(billingReports.createdAt)),
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -48,6 +70,14 @@ export async function loadBillingSelection(
|
||||
quarter,
|
||||
positions,
|
||||
repeatDownloads,
|
||||
reports: reportRows.map((row) => ({
|
||||
id: row.id,
|
||||
reportNumber: row.reportNumber,
|
||||
invoiceNumber: row.invoiceNumber,
|
||||
netTotalCents: row.netTotalCents,
|
||||
status: row.status,
|
||||
createdAt: row.createdAt,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ export default async function BillingSelectionPage({
|
||||
quarter={data.quarter}
|
||||
isQuarter={data.isQuarter}
|
||||
periodLabel={data.periodLabel}
|
||||
reports={data.reports}
|
||||
/>
|
||||
</section>
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user