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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -262,3 +393,76 @@ function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps
|
||||
</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>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import {
|
||||
cancelReport,
|
||||
ReportValidationError,
|
||||
ReportConflictError,
|
||||
} from "@/modules/billing/reports";
|
||||
|
||||
const cancelPayload = z
|
||||
.object({
|
||||
reason: z.string().trim().min(5).max(500),
|
||||
confirm: z.literal(true),
|
||||
})
|
||||
.strict();
|
||||
|
||||
type CancelReportRouteContext = Readonly<{ params: Promise<{ reportId: string }> }>;
|
||||
|
||||
type CancelHandlerDependencies = {
|
||||
requireAdmin: typeof requireAdmin;
|
||||
cancelReport: typeof cancelReport;
|
||||
};
|
||||
|
||||
export function createCancelReportHandler(dependencies: CancelHandlerDependencies) {
|
||||
return async function POST(
|
||||
request: Request,
|
||||
context: CancelReportRouteContext,
|
||||
): Promise<Response> {
|
||||
try {
|
||||
const principal = await dependencies.requireAdmin(request.headers);
|
||||
const { reportId } = await context.params;
|
||||
const payload = cancelPayload.safeParse(await readJson(request));
|
||||
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
|
||||
|
||||
await dependencies.cancelReport({
|
||||
reportId,
|
||||
reason: payload.data.reason,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{ status: "cancelled" },
|
||||
{ status: 200, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson(request: Request): Promise<unknown> {
|
||||
try {
|
||||
return await request.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mappedError(error: unknown): Response {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof ReportValidationError) {
|
||||
return jsonError(400, error.code);
|
||||
}
|
||||
if (error instanceof ReportConflictError) {
|
||||
if (error.code === "REPORT_NOT_FOUND") return jsonError(404, error.code);
|
||||
return jsonError(409, error.code);
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const cancelReportHandler = createCancelReportHandler({
|
||||
requireAdmin,
|
||||
cancelReport,
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { cancelReportHandler } from "./cancel-handler";
|
||||
|
||||
export const POST = cancelReportHandler;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { getReportPdf } from "@/modules/billing/reports";
|
||||
|
||||
type GetReportRouteContext = Readonly<{ params: Promise<{ reportId: string }> }>;
|
||||
|
||||
type GetHandlerDependencies = {
|
||||
requireAdmin: typeof requireAdmin;
|
||||
getReportPdf: typeof getReportPdf;
|
||||
};
|
||||
|
||||
export function createGetReportHandler(dependencies: GetHandlerDependencies) {
|
||||
return async function GET(
|
||||
request: Request,
|
||||
context: GetReportRouteContext,
|
||||
): Promise<Response> {
|
||||
try {
|
||||
await dependencies.requireAdmin(request.headers);
|
||||
const { reportId } = await context.params;
|
||||
|
||||
const report = await dependencies.getReportPdf(reportId);
|
||||
if (!report) return notFound();
|
||||
|
||||
const filename = buildFilename(report.invoiceNumber);
|
||||
return new Response(new Uint8Array(report.bytes), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/pdf",
|
||||
"cache-control": "private, no-store",
|
||||
"content-disposition": `attachment; filename="${filename}"`,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function buildFilename(invoiceNumber: string): string {
|
||||
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
|
||||
return `${safe || "nutzungsnachweis"}.pdf`;
|
||||
}
|
||||
|
||||
function notFound(): Response {
|
||||
return new Response(null, {
|
||||
status: 404,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
});
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const getReportHandler = createGetReportHandler({
|
||||
requireAdmin,
|
||||
getReportPdf,
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { getReportHandler } from "./get-handler";
|
||||
|
||||
export const GET = getReportHandler;
|
||||
@@ -0,0 +1,93 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import {
|
||||
finalizeReport,
|
||||
ReportValidationError,
|
||||
ReportConflictError,
|
||||
} from "@/modules/billing/reports";
|
||||
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
||||
|
||||
const finalizePayload = z
|
||||
.object({
|
||||
editorialId: z.string().uuid(),
|
||||
usageIds: z.array(z.string().uuid()).min(1),
|
||||
year: z.number().int().min(2020).max(2100),
|
||||
month: z.number().int().min(1).max(12).optional(),
|
||||
quarter: z.number().int().min(1).max(4).optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine((data) => (data.month !== undefined) !== (data.quarter !== undefined), {
|
||||
message: "Exactly one of month or quarter must be provided",
|
||||
});
|
||||
|
||||
type FinalizeHandlerDependencies = {
|
||||
requireAdmin: typeof requireAdmin;
|
||||
finalizeReport: typeof finalizeReport;
|
||||
};
|
||||
|
||||
export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
try {
|
||||
const principal = await dependencies.requireAdmin(request.headers);
|
||||
const payload = finalizePayload.safeParse(await readJson(request));
|
||||
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
|
||||
|
||||
const { editorialId, usageIds, year, month, quarter } = payload.data;
|
||||
const period = month ? monthPeriod(year, month) : quarterPeriod(year, quarter!);
|
||||
|
||||
const result = await dependencies.finalizeReport({
|
||||
editorialId,
|
||||
usageIds,
|
||||
period,
|
||||
adminUserId: principal.userId,
|
||||
});
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
reportId: result.reportId,
|
||||
reportNumber: result.reportNumber,
|
||||
},
|
||||
{
|
||||
status: 201,
|
||||
headers: { "cache-control": "private, no-store" },
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson(request: Request): Promise<unknown> {
|
||||
try {
|
||||
return await request.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mappedError(error: unknown): Response {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof ReportValidationError) {
|
||||
return jsonError(400, error.code);
|
||||
}
|
||||
if (error instanceof ReportConflictError) {
|
||||
return jsonError(409, error.code);
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const finalizeHandler = createFinalizeHandler({
|
||||
requireAdmin,
|
||||
finalizeReport,
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||
import { previewReport, ReportValidationError, ReportConflictError } from "@/modules/billing/reports";
|
||||
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
||||
|
||||
const previewPayload = z
|
||||
.object({
|
||||
editorialId: z.string().uuid(),
|
||||
usageIds: z.array(z.string().uuid()).min(1),
|
||||
year: z.number().int().min(2020).max(2100),
|
||||
month: z.number().int().min(1).max(12).optional(),
|
||||
quarter: z.number().int().min(1).max(4).optional(),
|
||||
})
|
||||
.strict()
|
||||
.refine((data) => (data.month !== undefined) !== (data.quarter !== undefined), {
|
||||
message: "Exactly one of month or quarter must be provided",
|
||||
});
|
||||
|
||||
type PreviewHandlerDependencies = {
|
||||
requireAdmin: typeof requireAdmin;
|
||||
previewReport: typeof previewReport;
|
||||
};
|
||||
|
||||
export function createPreviewHandler(dependencies: PreviewHandlerDependencies) {
|
||||
return async function POST(request: Request): Promise<Response> {
|
||||
try {
|
||||
await dependencies.requireAdmin(request.headers);
|
||||
const payload = previewPayload.safeParse(await readJson(request));
|
||||
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
|
||||
|
||||
const { editorialId, usageIds, year, month, quarter } = payload.data;
|
||||
const period = month ? monthPeriod(year, month) : quarterPeriod(year, quarter!);
|
||||
|
||||
const bytes = await dependencies.previewReport({ editorialId, usageIds, period });
|
||||
|
||||
return new Response(new Uint8Array(bytes), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "application/pdf",
|
||||
"cache-control": "private, no-store",
|
||||
"content-disposition": 'inline; filename="nutzungsnachweis-vorschau.pdf"',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return mappedError(error);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async function readJson(request: Request): Promise<unknown> {
|
||||
try {
|
||||
return await request.json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function mappedError(error: unknown): Response {
|
||||
if (error instanceof PrincipalAuthorizationError) {
|
||||
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||
}
|
||||
if (error instanceof ReportValidationError) {
|
||||
return jsonError(400, error.code);
|
||||
}
|
||||
if (error instanceof ReportConflictError) {
|
||||
return jsonError(409, error.code);
|
||||
}
|
||||
return jsonError(500, "REQUEST_FAILED");
|
||||
}
|
||||
|
||||
function jsonError(status: number, code: string): Response {
|
||||
return Response.json(
|
||||
{ code },
|
||||
{ status, headers: { "cache-control": "private, no-store" } },
|
||||
);
|
||||
}
|
||||
|
||||
export const previewHandler = createPreviewHandler({
|
||||
requireAdmin,
|
||||
previewReport,
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { previewHandler } from "./preview-handler";
|
||||
|
||||
export const POST = previewHandler;
|
||||
@@ -0,0 +1,3 @@
|
||||
import { finalizeHandler } from "./finalize-handler";
|
||||
|
||||
export const POST = finalizeHandler;
|
||||
@@ -1244,6 +1244,156 @@ a {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.billing-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.billing-actions button {
|
||||
font: inherit;
|
||||
font-size: 0.875rem;
|
||||
padding: 0.5rem 1.25rem;
|
||||
border: 2px solid var(--ink);
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
border-radius: 0;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.billing-actions button:hover:not(:disabled) {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.billing-actions button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.billing-actions .billing-action-primary {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.billing-actions .billing-action-primary:hover:not(:disabled) {
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.billing-status-message {
|
||||
margin-top: 0.75rem;
|
||||
padding: 0.5rem 0.75rem;
|
||||
font-size: 0.8125rem;
|
||||
border: 2px solid var(--ink);
|
||||
}
|
||||
|
||||
.billing-status-message[role="alert"] {
|
||||
border-color: var(--ink);
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.billing-reports-section {
|
||||
margin-top: 2.5rem;
|
||||
padding-top: 1.5rem;
|
||||
border-top: 2px solid var(--ink);
|
||||
}
|
||||
|
||||
.billing-reports-section h2 {
|
||||
font-size: 1.05rem;
|
||||
margin: 0 0 0.75rem;
|
||||
}
|
||||
|
||||
.billing-reports-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.billing-reports-list li {
|
||||
padding: 0.75rem;
|
||||
border: 1px solid var(--ink);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.billing-reports-list .billing-report-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem 1.5rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.billing-reports-list .billing-report-meta span {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.billing-cancel-form {
|
||||
margin-top: 0.5rem;
|
||||
padding-top: 0.5rem;
|
||||
border-top: 1px solid var(--muted-ink, #ccc);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.billing-cancel-form label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.8125rem;
|
||||
}
|
||||
|
||||
.billing-cancel-form textarea {
|
||||
font: inherit;
|
||||
font-size: 0.875rem;
|
||||
padding: 0.375rem 0.5rem;
|
||||
border: 1px solid var(--ink);
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
resize: vertical;
|
||||
min-height: 3rem;
|
||||
}
|
||||
|
||||
.billing-cancel-form .billing-cancel-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.billing-cancel-form .billing-cancel-controls label {
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.billing-cancel-form button {
|
||||
font: inherit;
|
||||
font-size: 0.8125rem;
|
||||
padding: 0.375rem 0.875rem;
|
||||
border: 2px solid var(--ink);
|
||||
background: var(--paper);
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.billing-cancel-form button:hover:not(:disabled) {
|
||||
background: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
|
||||
.billing-cancel-form button:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
@media (max-width: 48rem) {
|
||||
.billing-table {
|
||||
display: block;
|
||||
@@ -1258,4 +1408,9 @@ a {
|
||||
.billing-period-selector a {
|
||||
align-self: flex-start;
|
||||
}
|
||||
|
||||
.billing-actions {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createReportService,
|
||||
type ReportRepository,
|
||||
type SelectedUsage,
|
||||
type StoredReport,
|
||||
ReportConflictError,
|
||||
} from "./reports";
|
||||
import type { BillingReportAddress, BillingReportRepeatDownload } from "./types";
|
||||
import type { BillingPeriod } from "./period";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Fixtures
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const period: BillingPeriod = {
|
||||
fromUtc: new Date("2026-08-01T22:00:00.000Z"),
|
||||
toUtcExclusive: new Date("2026-09-01T22:00:00.000Z"),
|
||||
};
|
||||
|
||||
const validSelection = {
|
||||
editorialId: "e1",
|
||||
usageIds: ["u1", "u2"],
|
||||
period,
|
||||
adminUserId: "a1",
|
||||
};
|
||||
|
||||
const address: BillingReportAddress = {
|
||||
companyName: "Redaktion Beispiel GmbH",
|
||||
contactName: "Anna Schmidt",
|
||||
addressLine1: "Musterstraße 12",
|
||||
addressLine2: null,
|
||||
postalCode: "10115",
|
||||
city: "Berlin",
|
||||
countryCode: "DE",
|
||||
};
|
||||
|
||||
function selectedUsage(id: string, status: "open" | "reopened" = "open"): SelectedUsage {
|
||||
return {
|
||||
id,
|
||||
immichAssetId: `asset-${id}`,
|
||||
filenameSnapshot: `file-${id}.jpg`,
|
||||
albumNameSnapshot: "Presse 2026",
|
||||
purpose: "Titelgeschichte",
|
||||
internalReference: null,
|
||||
priceCents: 3_000,
|
||||
billingStatus: status,
|
||||
createdAt: new Date("2026-08-05T10:00:00.000Z"),
|
||||
editorialAccountId: "e1",
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// In-memory mock repository
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createMockRepo() {
|
||||
const usageStatuses = new Map<string, string>([
|
||||
["u1", "open"],
|
||||
["u2", "open"],
|
||||
]);
|
||||
const reports = new Map<string, StoredReport & { pdf?: Buffer; pdfSha256?: string }>();
|
||||
const reportItems = new Map<string, string[]>();
|
||||
let nextReportNumber = 1;
|
||||
|
||||
const repo: ReportRepository = {
|
||||
async getCurrentAddress() {
|
||||
return address;
|
||||
},
|
||||
|
||||
async getSelectedUsages(_editorialId, usageIds) {
|
||||
return usageIds.map((id) => selectedUsage(id, usageStatuses.get(id) as "open" | "reopened"));
|
||||
},
|
||||
|
||||
async getRepeatDownloads() {
|
||||
return [] as BillingReportRepeatDownload[];
|
||||
},
|
||||
|
||||
async allocateReportNumber() {
|
||||
return nextReportNumber++;
|
||||
},
|
||||
|
||||
async finalizeInTransaction(input) {
|
||||
// Re-check eligibility inside the "transaction"
|
||||
for (const usage of input.selectedUsages) {
|
||||
const status = usageStatuses.get(usage.id);
|
||||
if (status !== "open" && status !== "reopened") {
|
||||
throw new ReportConflictError("USAGE_NOT_ELIGIBLE");
|
||||
}
|
||||
}
|
||||
// Check report number collision
|
||||
for (const report of reports.values()) {
|
||||
if (report.reportNumber === input.reportNumber) {
|
||||
throw new ReportConflictError("REPORT_NUMBER_COLLISION");
|
||||
}
|
||||
}
|
||||
|
||||
const reportId = `r${reports.size + 1}`;
|
||||
reports.set(reportId, {
|
||||
id: reportId,
|
||||
reportNumber: input.reportNumber,
|
||||
invoiceNumber: input.invoiceNumber,
|
||||
status: "final",
|
||||
editorialAccountId: input.editorialId,
|
||||
netTotalCents: input.netTotalCents,
|
||||
cancellationReason: null,
|
||||
});
|
||||
reportItems.set(reportId, input.selectedUsages.map((u) => u.id));
|
||||
for (const usage of input.selectedUsages) {
|
||||
usageStatuses.set(usage.id, "billed");
|
||||
}
|
||||
return {
|
||||
reportId,
|
||||
reportNumber: input.reportNumber,
|
||||
invoiceNumber: input.invoiceNumber,
|
||||
};
|
||||
},
|
||||
|
||||
async getReportWithItemUsageIds(reportId) {
|
||||
const report = reports.get(reportId);
|
||||
if (!report) return null;
|
||||
return { status: report.status, usageIds: reportItems.get(reportId) ?? [] };
|
||||
},
|
||||
|
||||
async cancelReportInTransaction(reportId, reason, adminUserId, usageIds) {
|
||||
const report = reports.get(reportId);
|
||||
if (!report) throw new Error("Report not found");
|
||||
reports.set(reportId, {
|
||||
...report,
|
||||
status: "cancelled",
|
||||
cancellationReason: reason,
|
||||
cancelledByUserId: adminUserId,
|
||||
} as StoredReport & { pdf?: Buffer; pdfSha256?: string; cancelledByUserId?: string });
|
||||
for (const id of usageIds) {
|
||||
usageStatuses.set(id, "reopened");
|
||||
}
|
||||
},
|
||||
|
||||
async getFinalReportPdf(reportId) {
|
||||
const report = reports.get(reportId);
|
||||
if (!report || report.status !== "final") return null;
|
||||
return {
|
||||
bytes: report.pdf ?? Buffer.from("pdf"),
|
||||
reportNumber: report.reportNumber,
|
||||
invoiceNumber: report.invoiceNumber ?? "",
|
||||
};
|
||||
},
|
||||
|
||||
async getUsageStatuses(usageIds) {
|
||||
return usageIds.map((id) => usageStatuses.get(id) ?? "open");
|
||||
},
|
||||
|
||||
async getReport(reportId) {
|
||||
const report = reports.get(reportId);
|
||||
if (!report) return null;
|
||||
const { pdf, pdfSha256, ...rest } = report;
|
||||
return rest;
|
||||
},
|
||||
};
|
||||
|
||||
return { repo, usageStatuses, reports, reportItems };
|
||||
}
|
||||
|
||||
function createService(repo: ReportRepository) {
|
||||
const render = vi.fn().mockResolvedValue({
|
||||
bytes: Buffer.from("mock-pdf"),
|
||||
sha256: "a".repeat(64),
|
||||
});
|
||||
const service = createReportService({ repo, render });
|
||||
return { service, render };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests (from the brief — exact assertions)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("does not bill positions when PDF rendering fails", async () => {
|
||||
const { repo } = createMockRepo();
|
||||
const { service, render } = createService(repo);
|
||||
render.mockRejectedValue(new Error("render failed"));
|
||||
|
||||
await expect(service.finalizeReport(validSelection)).rejects.toThrow("render failed");
|
||||
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["open", "open"]);
|
||||
});
|
||||
|
||||
test("cancellation reopens positions and preserves the cancelled report", async () => {
|
||||
const mock = createMockRepo();
|
||||
const { repo, reports, reportItems } = mock;
|
||||
|
||||
// Set up a finalized report with one billed usage
|
||||
reports.set("r1", {
|
||||
id: "r1",
|
||||
reportNumber: 1,
|
||||
invoiceNumber: "NN-2026-0001",
|
||||
status: "final",
|
||||
editorialAccountId: "e1",
|
||||
netTotalCents: 3_000,
|
||||
cancellationReason: null,
|
||||
});
|
||||
reportItems.set("r1", ["u1"]);
|
||||
mock.usageStatuses.set("u1", "billed");
|
||||
|
||||
const { service } = createService(repo);
|
||||
|
||||
await service.cancelReport({ reportId: "r1", reason: "Falscher Zeitraum", adminUserId: "a1" });
|
||||
await expect(repo.getReport("r1")).resolves.toMatchObject({ status: "cancelled" });
|
||||
await expect(repo.getUsageStatuses(["u1"])).resolves.toEqual(["reopened"]);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Additional tests for preview, happy-path finalize, and conflict behavior
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("finalizeReport creates a final report and marks usages billed", async () => {
|
||||
const { repo, reports } = createMockRepo();
|
||||
const { service } = createService(repo);
|
||||
|
||||
const result = await service.finalizeReport(validSelection);
|
||||
|
||||
expect(result.reportNumber).toBe("1");
|
||||
expect(result.reportId).toBeTruthy();
|
||||
const report = await repo.getReport(result.reportId);
|
||||
expect(report).toMatchObject({ status: "final", netTotalCents: 6_000 });
|
||||
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["billed", "billed"]);
|
||||
});
|
||||
|
||||
test("previewReport returns PDF bytes without persisting or billing", async () => {
|
||||
const { repo, reports } = createMockRepo();
|
||||
const { service, render } = createService(repo);
|
||||
|
||||
const bytes = await service.previewReport({
|
||||
editorialId: validSelection.editorialId,
|
||||
usageIds: validSelection.usageIds,
|
||||
period: validSelection.period,
|
||||
});
|
||||
|
||||
expect(bytes).toBeInstanceOf(Buffer);
|
||||
expect(render).toHaveBeenCalledTimes(1);
|
||||
expect(reports.size).toBe(0);
|
||||
await expect(repo.getUsageStatuses(validSelection.usageIds)).resolves.toEqual(["open", "open"]);
|
||||
});
|
||||
|
||||
test("finalizeReport rejects when a selected usage is already billed", async () => {
|
||||
const mock = createMockRepo();
|
||||
const { repo } = mock;
|
||||
mock.usageStatuses.set("u1", "billed");
|
||||
const { service } = createService(repo);
|
||||
|
||||
await expect(service.finalizeReport(validSelection)).rejects.toBeInstanceOf(ReportConflictError);
|
||||
await expect(repo.getUsageStatuses(["u2"])).resolves.toEqual(["open"]);
|
||||
});
|
||||
|
||||
test("cancelReport rejects a reason shorter than 5 characters", async () => {
|
||||
const { repo } = createMockRepo();
|
||||
const { service } = createService(repo);
|
||||
|
||||
await expect(
|
||||
service.cancelReport({ reportId: "r1", reason: "abc", adminUserId: "a1" }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
test("cancelReport rejects a reason longer than 500 characters", async () => {
|
||||
const { repo } = createMockRepo();
|
||||
const { service } = createService(repo);
|
||||
|
||||
await expect(
|
||||
service.cancelReport({ reportId: "r1", reason: "x".repeat(501), adminUserId: "a1" }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
@@ -0,0 +1,699 @@
|
||||
import "server-only";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import {
|
||||
billingAddressVersions,
|
||||
billingReportItems,
|
||||
billingReports,
|
||||
downloadEvents,
|
||||
editorialAccounts,
|
||||
usages,
|
||||
} from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
import { renderBillingPdf } from "@/modules/pdf/render";
|
||||
import type { BillingReportSnapshot } from "@/modules/billing/types";
|
||||
|
||||
import type { BillingPeriod } from "./period";
|
||||
import type {
|
||||
BillingReportAddress,
|
||||
BillingReportPosition,
|
||||
BillingReportRepeatDownload,
|
||||
} from "./types";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Legal notice — clarifies that the document is NOT a VAT invoice.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const LEGAL_SEPARATION_NOTICE =
|
||||
"Dieser Nutzungsnachweis ist keine Rechnung im Sinne des Umsatzsteuerrechts.";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Invoice number format: NN-{periodYear}-{paddedReportNumber}
|
||||
// e.g. NN-2026-0001. The periodYear is derived from toUtcExclusive so that
|
||||
// January periods (whose fromUtc falls in the previous UTC year due to the
|
||||
// Europe/Berlin offset) are attributed to the correct calendar year. The
|
||||
// reportNumber is UNIQUE in billing_reports, so the derived invoiceNumber is
|
||||
// also unique — there is no separate collision surface.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildInvoiceNumber(reportNumber: number, period: BillingPeriod): string {
|
||||
const year = period.toUtcExclusive.getUTCFullYear();
|
||||
return `NN-${year}-${String(reportNumber).padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Domain types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type ReportSelection = {
|
||||
editorialId: string;
|
||||
usageIds: string[];
|
||||
period: BillingPeriod;
|
||||
};
|
||||
|
||||
export type FinalizeReportInput = ReportSelection & {
|
||||
adminUserId: string;
|
||||
};
|
||||
|
||||
export type PreviewReportInput = ReportSelection;
|
||||
|
||||
export type CancelReportInput = {
|
||||
reportId: string;
|
||||
reason: string;
|
||||
adminUserId: string;
|
||||
};
|
||||
|
||||
export type FinalizeResult = {
|
||||
reportId: string;
|
||||
reportNumber: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A usage selected for billing, as read from the database. Contains all the
|
||||
* fields needed for eligibility validation and snapshot building.
|
||||
*/
|
||||
export type SelectedUsage = {
|
||||
id: string;
|
||||
immichAssetId: string;
|
||||
filenameSnapshot: string;
|
||||
albumNameSnapshot: string;
|
||||
purpose: string;
|
||||
internalReference: string | null;
|
||||
priceCents: number;
|
||||
billingStatus: "open" | "billed" | "reopened" | "voided";
|
||||
createdAt: Date;
|
||||
editorialAccountId: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* A stored billing report as read back from the database.
|
||||
*/
|
||||
export type StoredReport = {
|
||||
id: string;
|
||||
reportNumber: number;
|
||||
invoiceNumber: string | null;
|
||||
status: "draft" | "final" | "cancelled";
|
||||
editorialAccountId: string;
|
||||
netTotalCents: number;
|
||||
cancellationReason: string | null;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Typed errors
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Stable conflict error returned when a concurrent finalize has already billed
|
||||
* one of the selected usages, or when the allocated report number collides with
|
||||
* a concurrent insert. The API route maps this to HTTP 409.
|
||||
*/
|
||||
export class ReportConflictError extends Error {
|
||||
readonly name = "ReportConflictError";
|
||||
constructor(
|
||||
readonly code:
|
||||
| "USAGE_NOT_ELIGIBLE"
|
||||
| "USAGE_NOT_FOUND"
|
||||
| "REPORT_NUMBER_COLLISION"
|
||||
| "REPORT_NOT_FINAL"
|
||||
| "REPORT_NOT_FOUND",
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
export class ReportValidationError extends Error {
|
||||
readonly name = "ReportValidationError";
|
||||
constructor(
|
||||
readonly code:
|
||||
| "NO_USAGES_SELECTED"
|
||||
| "USAGE_NOT_ELIGIBLE"
|
||||
| "USAGE_NOT_FOUND"
|
||||
| "ADDRESS_NOT_FOUND"
|
||||
| "INVALID_CANCELLATION_REASON",
|
||||
) {
|
||||
super(code);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repository interface
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type FinalizeTransactionInput = {
|
||||
editorialId: string;
|
||||
period: BillingPeriod;
|
||||
adminUserId: string;
|
||||
reportNumber: number;
|
||||
invoiceNumber: string;
|
||||
selectedUsages: SelectedUsage[];
|
||||
address: BillingReportAddress;
|
||||
repeatDownloads: BillingReportRepeatDownload[];
|
||||
netTotalCents: number;
|
||||
pdfBytes: Buffer;
|
||||
pdfSha256: string;
|
||||
documentId: string;
|
||||
createdAt: Date;
|
||||
legalSeparationNotice: string;
|
||||
};
|
||||
|
||||
export type FinalizeTransactionResult = {
|
||||
reportId: string;
|
||||
reportNumber: number;
|
||||
invoiceNumber: string;
|
||||
};
|
||||
|
||||
export type ReportRepository = {
|
||||
// Snapshot building (pre-transaction)
|
||||
getCurrentAddress(editorialId: string): Promise<BillingReportAddress | null>;
|
||||
getSelectedUsages(editorialId: string, usageIds: string[]): Promise<SelectedUsage[]>;
|
||||
getRepeatDownloads(editorialId: string, period: BillingPeriod): Promise<BillingReportRepeatDownload[]>;
|
||||
allocateReportNumber(): Promise<number>;
|
||||
|
||||
// Atomic finalization (transaction internal to the repo implementation)
|
||||
finalizeInTransaction(input: FinalizeTransactionInput): Promise<FinalizeTransactionResult>;
|
||||
|
||||
// Cancellation
|
||||
getReportWithItemUsageIds(
|
||||
reportId: string,
|
||||
): Promise<{ status: string; usageIds: string[] } | null>;
|
||||
cancelReportInTransaction(
|
||||
reportId: string,
|
||||
reason: string,
|
||||
adminUserId: string,
|
||||
usageIds: string[],
|
||||
): Promise<void>;
|
||||
|
||||
// Retrieval
|
||||
getFinalReportPdf(
|
||||
reportId: string,
|
||||
): Promise<{ bytes: Buffer; reportNumber: number; invoiceNumber: string } | null>;
|
||||
|
||||
// Verification helpers (used by tests; also available to the service)
|
||||
getUsageStatuses(usageIds: string[]): Promise<string[]>;
|
||||
getReport(reportId: string): Promise<StoredReport | null>;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Render function type (matches renderBillingPdf from @/modules/pdf/render)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type RenderBillingPdf = (
|
||||
snapshot: BillingReportSnapshot,
|
||||
) => Promise<{ bytes: Buffer; sha256: string }>;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Service factory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createReportService({
|
||||
repo,
|
||||
render,
|
||||
}: {
|
||||
repo: ReportRepository;
|
||||
render: RenderBillingPdf;
|
||||
}) {
|
||||
return {
|
||||
/**
|
||||
* Builds a snapshot from the selection, renders the PDF, and returns the
|
||||
* bytes. No database writes are performed — the preview is not persisted.
|
||||
*/
|
||||
async previewReport(input: PreviewReportInput): Promise<Buffer> {
|
||||
const { usages: selectedUsages, address, repeatDownloads, netTotalCents } =
|
||||
await buildSnapshot(repo, input);
|
||||
|
||||
// Preview uses report number 0 and a "VORSCHAU" invoice number — the
|
||||
// preview is not persisted, so these placeholder values never collide
|
||||
// with real allocations.
|
||||
const snapshot = {
|
||||
address,
|
||||
selectedPositions: selectedUsages.map(toReportPosition),
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
reportNumber: 0,
|
||||
invoiceNumber: "VORSCHAU",
|
||||
period: input.period,
|
||||
documentId: randomUUID(),
|
||||
createdAt: new Date(),
|
||||
legalSeparationNotice: LEGAL_SEPARATION_NOTICE,
|
||||
};
|
||||
const rendered = await render(snapshot);
|
||||
return rendered.bytes;
|
||||
},
|
||||
|
||||
/**
|
||||
* Finalizes a billing report atomically.
|
||||
*
|
||||
* Flow:
|
||||
* 1. Pre-check eligibility (fast fail before rendering).
|
||||
* 2. Allocate a report number (read-only SELECT MAX+1 — not a DB write).
|
||||
* 3. Build the immutable snapshot and render the PDF.
|
||||
* 4. Open a transaction: re-check eligibility with row locks, insert the
|
||||
* report/items/PDF, and mark usages billed. If the report number
|
||||
* collides with a concurrent insert, abort → ReportConflictError.
|
||||
*
|
||||
* If the render fails, nothing is written.
|
||||
*/
|
||||
async finalizeReport(input: FinalizeReportInput): Promise<FinalizeResult> {
|
||||
const { usages: selectedUsages, address, repeatDownloads, netTotalCents } =
|
||||
await buildSnapshot(repo, input);
|
||||
|
||||
const reportNumber = await repo.allocateReportNumber();
|
||||
const invoiceNumber = buildInvoiceNumber(reportNumber, input.period);
|
||||
const documentId = randomUUID();
|
||||
const createdAt = new Date();
|
||||
|
||||
const snapshot = {
|
||||
address,
|
||||
selectedPositions: selectedUsages.map(toReportPosition),
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
reportNumber,
|
||||
invoiceNumber,
|
||||
period: input.period,
|
||||
documentId,
|
||||
createdAt,
|
||||
legalSeparationNotice: LEGAL_SEPARATION_NOTICE,
|
||||
};
|
||||
|
||||
// Render the PDF FIRST — no DB writes yet. If this fails, nothing is
|
||||
// persisted and usages stay in their original status.
|
||||
const rendered = await render(snapshot);
|
||||
|
||||
// Open the transaction: re-check eligibility, insert, and mark billed.
|
||||
// If a concurrent finalize has billed any usage or taken the same report
|
||||
// number, the transaction aborts with a stable ReportConflictError.
|
||||
const result = await repo.finalizeInTransaction({
|
||||
editorialId: input.editorialId,
|
||||
period: input.period,
|
||||
adminUserId: input.adminUserId,
|
||||
reportNumber,
|
||||
invoiceNumber,
|
||||
selectedUsages,
|
||||
address,
|
||||
repeatDownloads,
|
||||
netTotalCents,
|
||||
pdfBytes: rendered.bytes,
|
||||
pdfSha256: rendered.sha256,
|
||||
documentId,
|
||||
createdAt,
|
||||
legalSeparationNotice: LEGAL_SEPARATION_NOTICE,
|
||||
});
|
||||
|
||||
return {
|
||||
reportId: result.reportId,
|
||||
reportNumber: String(result.reportNumber),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Cancels a finalized report: sets status to 'cancelled', records the
|
||||
* reason and cancelling admin, and reopens all linked usages. The
|
||||
* cancelled report row, items, and PDF are preserved (not deleted).
|
||||
*/
|
||||
async cancelReport(input: CancelReportInput): Promise<void> {
|
||||
const reason = input.reason.trim();
|
||||
if (reason.length < 5 || reason.length > 500) {
|
||||
throw new ReportValidationError("INVALID_CANCELLATION_REASON");
|
||||
}
|
||||
|
||||
const report = await repo.getReportWithItemUsageIds(input.reportId);
|
||||
if (!report) {
|
||||
throw new ReportConflictError("REPORT_NOT_FOUND");
|
||||
}
|
||||
if (report.status !== "final") {
|
||||
throw new ReportConflictError("REPORT_NOT_FINAL");
|
||||
}
|
||||
|
||||
await repo.cancelReportInTransaction(
|
||||
input.reportId,
|
||||
reason,
|
||||
input.adminUserId,
|
||||
report.usageIds,
|
||||
);
|
||||
},
|
||||
|
||||
/**
|
||||
* Retrieves the stored PDF bytes for a finalized report. Returns null if
|
||||
* the report does not exist or is not in 'final' status.
|
||||
*/
|
||||
async getReportPdf(
|
||||
reportId: string,
|
||||
): Promise<{ bytes: Buffer; reportNumber: number; invoiceNumber: string } | null> {
|
||||
return repo.getFinalReportPdf(reportId);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Snapshot building (shared by preview and finalize)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function buildSnapshot(
|
||||
repo: ReportRepository,
|
||||
input: ReportSelection,
|
||||
): Promise<{
|
||||
usages: SelectedUsage[];
|
||||
address: BillingReportAddress;
|
||||
repeatDownloads: BillingReportRepeatDownload[];
|
||||
netTotalCents: number;
|
||||
}> {
|
||||
if (input.usageIds.length === 0) {
|
||||
throw new ReportValidationError("NO_USAGES_SELECTED");
|
||||
}
|
||||
|
||||
// Pre-check: fetch usages and validate eligibility before rendering.
|
||||
const selectedUsages = await repo.getSelectedUsages(input.editorialId, input.usageIds);
|
||||
|
||||
if (selectedUsages.length !== input.usageIds.length) {
|
||||
throw new ReportValidationError("USAGE_NOT_FOUND");
|
||||
}
|
||||
|
||||
for (const usage of selectedUsages) {
|
||||
if (usage.editorialAccountId !== input.editorialId) {
|
||||
throw new ReportValidationError("USAGE_NOT_FOUND");
|
||||
}
|
||||
if (usage.billingStatus !== "open" && usage.billingStatus !== "reopened") {
|
||||
throw new ReportConflictError("USAGE_NOT_ELIGIBLE");
|
||||
}
|
||||
if (
|
||||
usage.createdAt < input.period.fromUtc ||
|
||||
usage.createdAt >= input.period.toUtcExclusive
|
||||
) {
|
||||
throw new ReportValidationError("USAGE_NOT_FOUND");
|
||||
}
|
||||
}
|
||||
|
||||
const address = await repo.getCurrentAddress(input.editorialId);
|
||||
if (!address) {
|
||||
throw new ReportValidationError("ADDRESS_NOT_FOUND");
|
||||
}
|
||||
|
||||
const repeatDownloads = await repo.getRepeatDownloads(input.editorialId, input.period);
|
||||
|
||||
const netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0);
|
||||
|
||||
return { usages: selectedUsages, address, repeatDownloads, netTotalCents };
|
||||
}
|
||||
|
||||
function toReportPosition(usage: SelectedUsage): BillingReportPosition {
|
||||
return {
|
||||
id: usage.id,
|
||||
assetId: usage.immichAssetId,
|
||||
filename: usage.filenameSnapshot,
|
||||
albumName: usage.albumNameSnapshot,
|
||||
purpose: usage.purpose,
|
||||
reference: usage.internalReference,
|
||||
priceCents: usage.priceCents,
|
||||
createdAt: usage.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Drizzle repository implementation
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// PostgreSQL unique-constraint violation error code.
|
||||
const PG_UNIQUE_VIOLATION = "23505";
|
||||
|
||||
export function createReportRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): ReportRepository {
|
||||
return {
|
||||
async getCurrentAddress(editorialId) {
|
||||
const [editorial] = await database
|
||||
.select({
|
||||
versionId: editorialAccounts.currentBillingAddressVersionId,
|
||||
})
|
||||
.from(editorialAccounts)
|
||||
.where(eq(editorialAccounts.id, editorialId))
|
||||
.limit(1);
|
||||
if (!editorial || !editorial.versionId) return null;
|
||||
|
||||
const [version] = await database
|
||||
.select({
|
||||
companyName: billingAddressVersions.companyName,
|
||||
contactName: billingAddressVersions.contactName,
|
||||
addressLine1: billingAddressVersions.addressLine1,
|
||||
addressLine2: billingAddressVersions.addressLine2,
|
||||
postalCode: billingAddressVersions.postalCode,
|
||||
city: billingAddressVersions.city,
|
||||
countryCode: billingAddressVersions.countryCode,
|
||||
})
|
||||
.from(billingAddressVersions)
|
||||
.where(eq(billingAddressVersions.id, editorial.versionId))
|
||||
.limit(1);
|
||||
if (!version) return null;
|
||||
return version;
|
||||
},
|
||||
|
||||
async getSelectedUsages(editorialId, usageIds) {
|
||||
const rows = await database
|
||||
.select({
|
||||
id: usages.id,
|
||||
immichAssetId: usages.immichAssetId,
|
||||
filenameSnapshot: usages.filenameSnapshot,
|
||||
albumNameSnapshot: usages.albumNameSnapshot,
|
||||
purpose: usages.purpose,
|
||||
internalReference: usages.internalReference,
|
||||
priceCents: usages.priceCents,
|
||||
billingStatus: usages.billingStatus,
|
||||
createdAt: usages.createdAt,
|
||||
editorialAccountId: usages.editorialAccountId,
|
||||
})
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
eq(usages.editorialAccountId, editorialId),
|
||||
inArray(usages.id, usageIds),
|
||||
),
|
||||
);
|
||||
return rows as SelectedUsage[];
|
||||
},
|
||||
|
||||
async getRepeatDownloads(editorialId, period) {
|
||||
const rows = await database
|
||||
.select({
|
||||
id: downloadEvents.id,
|
||||
assetId: downloadEvents.immichAssetId,
|
||||
usageId: downloadEvents.usageId,
|
||||
authorizedAt: downloadEvents.authorizedAt,
|
||||
repeatDownloadNote: downloadEvents.repeatDownloadNote,
|
||||
})
|
||||
.from(downloadEvents)
|
||||
.where(
|
||||
and(
|
||||
eq(downloadEvents.editorialAccountId, editorialId),
|
||||
sql`${downloadEvents.authorizedAt} >= ${period.fromUtc}`,
|
||||
sql`${downloadEvents.authorizedAt} < ${period.toUtcExclusive}`,
|
||||
eq(downloadEvents.intentKind, "repeat_download"),
|
||||
inArray(downloadEvents.status, ["completed", "interrupted"]),
|
||||
),
|
||||
);
|
||||
return rows as BillingReportRepeatDownload[];
|
||||
},
|
||||
|
||||
async allocateReportNumber() {
|
||||
const result = await database.execute(
|
||||
sql`SELECT COALESCE(MAX(report_number), 0) + 1 AS next_number FROM billing_reports`,
|
||||
);
|
||||
const row = (result as unknown as { rows: { next_number: number }[] }).rows[0];
|
||||
return Number(row?.next_number ?? 1);
|
||||
},
|
||||
|
||||
async finalizeInTransaction(input) {
|
||||
try {
|
||||
return await database.transaction(async (tx) => {
|
||||
// Serializable isolation ensures that if a concurrent transaction
|
||||
// has already inserted a report or billed a usage, this transaction
|
||||
// detects the conflict and aborts. We use SELECT ... FOR UPDATE on
|
||||
// the selected usages to prevent double-billing.
|
||||
await tx.execute(sql`SET TRANSACTION ISOLATION LEVEL SERIALIZABLE`);
|
||||
|
||||
const lockedRows = await tx
|
||||
.select({
|
||||
id: usages.id,
|
||||
billingStatus: usages.billingStatus,
|
||||
editorialAccountId: usages.editorialAccountId,
|
||||
})
|
||||
.from(usages)
|
||||
.where(
|
||||
and(
|
||||
eq(usages.editorialAccountId, input.editorialId),
|
||||
inArray(usages.id, input.selectedUsages.map((u) => u.id)),
|
||||
),
|
||||
)
|
||||
.for("update");
|
||||
|
||||
if (lockedRows.length !== input.selectedUsages.length) {
|
||||
throw new ReportConflictError("USAGE_NOT_FOUND");
|
||||
}
|
||||
for (const row of lockedRows) {
|
||||
if (row.billingStatus !== "open" && row.billingStatus !== "reopened") {
|
||||
throw new ReportConflictError("USAGE_NOT_ELIGIBLE");
|
||||
}
|
||||
}
|
||||
|
||||
const [report] = await tx
|
||||
.insert(billingReports)
|
||||
.values({
|
||||
reportNumber: input.reportNumber,
|
||||
editorialAccountId: input.editorialId,
|
||||
periodStartsAt: input.period.fromUtc,
|
||||
periodEndsAt: input.period.toUtcExclusive,
|
||||
billingAddressSnapshot: input.address,
|
||||
invoiceNumber: input.invoiceNumber,
|
||||
netTotalCents: input.netTotalCents,
|
||||
status: "final",
|
||||
pdf: input.pdfBytes,
|
||||
pdfSha256: input.pdfSha256,
|
||||
createdByUserId: input.adminUserId,
|
||||
finalizedAt: input.createdAt,
|
||||
})
|
||||
.returning({ id: billingReports.id });
|
||||
|
||||
await tx.insert(billingReportItems).values(
|
||||
input.selectedUsages.map((u) => ({
|
||||
billingReportId: report.id,
|
||||
usageId: u.id,
|
||||
immichAssetIdSnapshot: u.immichAssetId,
|
||||
filenameSnapshot: u.filenameSnapshot,
|
||||
albumNameSnapshot: u.albumNameSnapshot,
|
||||
purposeSnapshot: u.purpose,
|
||||
internalReferenceSnapshot: u.internalReference,
|
||||
priceCents: u.priceCents,
|
||||
})),
|
||||
);
|
||||
|
||||
await tx
|
||||
.update(usages)
|
||||
.set({ billingStatus: "billed", billingReportId: report.id })
|
||||
.where(inArray(usages.id, input.selectedUsages.map((u) => u.id)));
|
||||
|
||||
return {
|
||||
reportId: report.id,
|
||||
reportNumber: input.reportNumber,
|
||||
invoiceNumber: input.invoiceNumber,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
// Map PostgreSQL unique-constraint violation to a stable conflict error.
|
||||
if (isPgUniqueViolation(error)) {
|
||||
throw new ReportConflictError("REPORT_NUMBER_COLLISION");
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async getReportWithItemUsageIds(reportId) {
|
||||
const [report] = await database
|
||||
.select({ id: billingReports.id, status: billingReports.status })
|
||||
.from(billingReports)
|
||||
.where(eq(billingReports.id, reportId))
|
||||
.limit(1);
|
||||
if (!report) return null;
|
||||
|
||||
const items = await database
|
||||
.select({ usageId: billingReportItems.usageId })
|
||||
.from(billingReportItems)
|
||||
.where(eq(billingReportItems.billingReportId, reportId));
|
||||
return { status: report.status, usageIds: items.map((i) => i.usageId) };
|
||||
},
|
||||
|
||||
async cancelReportInTransaction(reportId, reason, adminUserId, usageIds) {
|
||||
await database.transaction(async (tx) => {
|
||||
await tx
|
||||
.update(billingReports)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
cancelledAt: new Date(),
|
||||
cancellationReason: reason,
|
||||
cancelledByUserId: adminUserId,
|
||||
})
|
||||
.where(eq(billingReports.id, reportId));
|
||||
|
||||
if (usageIds.length > 0) {
|
||||
await tx
|
||||
.update(usages)
|
||||
.set({ billingStatus: "reopened", billingReportId: null })
|
||||
.where(inArray(usages.id, usageIds));
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
async getFinalReportPdf(reportId) {
|
||||
const [report] = await database
|
||||
.select({
|
||||
id: billingReports.id,
|
||||
status: billingReports.status,
|
||||
pdf: billingReports.pdf,
|
||||
reportNumber: billingReports.reportNumber,
|
||||
invoiceNumber: billingReports.invoiceNumber,
|
||||
})
|
||||
.from(billingReports)
|
||||
.where(eq(billingReports.id, reportId))
|
||||
.limit(1);
|
||||
if (!report || report.status !== "final" || !report.pdf) return null;
|
||||
return {
|
||||
bytes: report.pdf,
|
||||
reportNumber: report.reportNumber,
|
||||
invoiceNumber: report.invoiceNumber ?? "",
|
||||
};
|
||||
},
|
||||
|
||||
async getUsageStatuses(usageIds) {
|
||||
if (usageIds.length === 0) return [];
|
||||
const rows = await database
|
||||
.select({ id: usages.id, status: usages.billingStatus })
|
||||
.from(usages)
|
||||
.where(inArray(usages.id, usageIds));
|
||||
const map = new Map(rows.map((r) => [r.id, r.status]));
|
||||
return usageIds.map((id) => map.get(id) ?? "open");
|
||||
},
|
||||
|
||||
async getReport(reportId) {
|
||||
const [row] = await database
|
||||
.select({
|
||||
id: billingReports.id,
|
||||
reportNumber: billingReports.reportNumber,
|
||||
invoiceNumber: billingReports.invoiceNumber,
|
||||
status: billingReports.status,
|
||||
editorialAccountId: billingReports.editorialAccountId,
|
||||
netTotalCents: billingReports.netTotalCents,
|
||||
cancellationReason: billingReports.cancellationReason,
|
||||
})
|
||||
.from(billingReports)
|
||||
.where(eq(billingReports.id, reportId))
|
||||
.limit(1);
|
||||
if (!row) return null;
|
||||
return row as StoredReport;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function isPgUniqueViolation(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
(error as { code: string }).code === PG_UNIQUE_VIOLATION
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default singleton wired to the real database + real PDF renderer
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const reportService = createReportService({
|
||||
repo: createReportRepository(db),
|
||||
render: renderBillingPdf,
|
||||
});
|
||||
|
||||
export const previewReport = reportService.previewReport;
|
||||
export const finalizeReport = reportService.finalizeReport;
|
||||
export const cancelReport = reportService.cancelReport;
|
||||
export const getReportPdf = reportService.getReportPdf;
|
||||
Reference in new issue
Block a user