feat: finalize immutable billing reports

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Leon TonhäuserandClaude committed 2026-08-10 18:19:13 +02:00
1 parent a384c4c35e
commit 7f1ecd9322
15 files changed
+1697 -3

No files matched your search

@@ -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;
+3
View File
@@ -0,0 +1,3 @@
import { finalizeHandler } from "./finalize-handler";
export const POST = finalizeHandler;