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
@@ -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,
|
||||
});
|
||||
Reference in new issue
Block a user