132 lines
4.1 KiB
TypeScript
132 lines
4.1 KiB
TypeScript
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";
|
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
|
import { emailService } from "@/modules/email/service";
|
|
import { getReportPdf } from "@/modules/billing/reports";
|
|
import { db } from "@/db/client";
|
|
import { editorialAccounts } from "@/db/schema";
|
|
import { eq } from "drizzle-orm";
|
|
|
|
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 {
|
|
assertSameOrigin(request);
|
|
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,
|
|
});
|
|
|
|
// Email dispatch
|
|
try {
|
|
const [editorial] = await db
|
|
.select({ email: editorialAccounts.loginEmail })
|
|
.from(editorialAccounts)
|
|
.where(eq(editorialAccounts.id, editorialId))
|
|
.limit(1);
|
|
|
|
if (editorial?.email) {
|
|
const reportPdf = await getReportPdf(result.reportId);
|
|
if (reportPdf) {
|
|
const periodString = month
|
|
? `${month.toString().padStart(2, "0")}/${year}`
|
|
: `Q${quarter}/${year}`;
|
|
|
|
// Fire and forget (don't await or catch if we want to not block, but awaiting is safer for serverless if not in background)
|
|
await emailService.sendBillingReport(
|
|
editorial.email,
|
|
periodString,
|
|
reportPdf.bytes,
|
|
result.reportNumber
|
|
);
|
|
}
|
|
}
|
|
} catch (emailError) {
|
|
console.error("Failed to send billing email:", emailError);
|
|
// Do not fail the request if email fails
|
|
}
|
|
|
|
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 CrossOriginRequestError) {
|
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
|
}
|
|
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,
|
|
}); |