import "server-only"; import { createHash } from "node:crypto"; import { eq } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; import { billingReports, editorialAccounts } from "@/db/schema"; import type * as schema from "@/db/schema"; import { writeAudit } from "@/modules/audit/write"; import { emailService } from "@/modules/email/service"; export const INVOICE_PDF_MAX_BYTES = 20 * 1024 * 1024; export class InvoiceError extends Error { readonly name = "InvoiceError"; constructor( readonly code: | "REPORT_NOT_FOUND" | "REPORT_NOT_FINAL" | "INVALID_PDF" | "INVOICE_NOT_UPLOADED" | "EDITORIAL_NOT_FOUND", ) { super(code); } } export type InvoiceReport = { id: string; status: "draft" | "final" | "cancelled"; editorialAccountId: string; reportNumber: number; invoiceNumber: string | null; periodStartsAt: Date; periodEndsAt: Date; pdf: Buffer | null; invoicePdf: Buffer | null; invoicePdfFilename: string | null; }; export type InvoiceEmailOutcome = "sent" | "failed"; export type InvoiceRepository = { getReport(reportId: string): Promise; getEditorialEmail(editorialId: string): Promise; storeInvoice( reportId: string, input: { bytes: Buffer; sha256: string; filename: string; uploadedAt: Date }, ): Promise; markEmailOutcome( reportId: string, outcome: InvoiceEmailOutcome, error: string | null, ): Promise; }; export type SendInvoiceBundle = (input: { toEmail: string; periodLabel: string; invoicePdf: Buffer; reportPdf: Buffer; invoiceNumber: string; }) => Promise; export function createInvoiceService({ repo, sendEmail, }: { repo: InvoiceRepository; sendEmail: SendInvoiceBundle; }) { async function dispatch(report: InvoiceReport, adminUserId: string): Promise { const invoicePdf = report.invoicePdf; if (!invoicePdf) throw new InvoiceError("INVOICE_NOT_UPLOADED"); const toEmail = await repo.getEditorialEmail(report.editorialAccountId); if (!toEmail) throw new InvoiceError("EDITORIAL_NOT_FOUND"); const periodLabel = formatPeriodLabel(report.periodStartsAt, report.periodEndsAt); const invoiceNumber = report.invoiceNumber ?? String(report.reportNumber); try { await sendEmail({ toEmail, periodLabel, invoicePdf, reportPdf: report.pdf ?? Buffer.alloc(0), invoiceNumber, }); await repo.markEmailOutcome(report.id, "sent", null); await audit("invoice_email_sent", adminUserId, report.id, { toEmail, periodLabel }); return "sent"; } catch (error) { const message = error instanceof Error ? error.message.slice(0, 500) : "unknown"; await repo.markEmailOutcome(report.id, "failed", message); await audit("invoice_email_failed", adminUserId, report.id, { toEmail, error: message }); return "failed"; } } return { /** * Stores the admin-uploaded invoice PDF on a finalized report and sends * the bundled email (invoice + Nutzungsnachweis). A failed send does not * undo the upload; the admin can resend from the report list. */ async uploadInvoice(input: { reportId: string; bytes: Buffer; filename: string; adminUserId: string; }): Promise<{ emailStatus: InvoiceEmailOutcome }> { assertPdfBytes(input.bytes); const report = await repo.getReport(input.reportId); if (!report) throw new InvoiceError("REPORT_NOT_FOUND"); if (report.status !== "final") throw new InvoiceError("REPORT_NOT_FINAL"); const sha256 = createHash("sha256").update(input.bytes).digest("hex"); const filename = sanitizeFilename(input.filename); await repo.storeInvoice(input.reportId, { bytes: input.bytes, sha256, filename, uploadedAt: new Date(), }); await audit("invoice_uploaded", input.adminUserId, input.reportId, { filename, sizeBytes: input.bytes.length, sha256, }); const updated = await repo.getReport(input.reportId); if (!updated) throw new InvoiceError("REPORT_NOT_FOUND"); const emailStatus = await dispatch(updated, input.adminUserId); return { emailStatus }; }, async resendInvoice(input: { reportId: string; adminUserId: string; }): Promise<{ emailStatus: InvoiceEmailOutcome }> { const report = await repo.getReport(input.reportId); if (!report) throw new InvoiceError("REPORT_NOT_FOUND"); if (report.status !== "final") throw new InvoiceError("REPORT_NOT_FINAL"); if (!report.invoicePdf) throw new InvoiceError("INVOICE_NOT_UPLOADED"); const emailStatus = await dispatch(report, input.adminUserId); return { emailStatus }; }, async getInvoicePdf( reportId: string, ): Promise<{ bytes: Buffer; filename: string } | null> { const report = await repo.getReport(reportId); if (!report || report.status !== "final" || !report.invoicePdf) return null; return { bytes: report.invoicePdf, filename: report.invoicePdfFilename ?? `rechnung-${report.reportNumber}.pdf`, }; }, }; } export function assertPdfBytes(bytes: Buffer): void { if ( bytes.length === 0 || bytes.length > INVOICE_PDF_MAX_BYTES || bytes.subarray(0, 5).toString("latin1") !== "%PDF-" ) { throw new InvoiceError("INVALID_PDF"); } } function sanitizeFilename(value: string): string { const cleaned = value.replace(/[\\/\u0000-\u001f\u007f-\u009f]/g, "_").trim().slice(0, 180); return cleaned.toLowerCase().endsWith(".pdf") ? cleaned : `${cleaned || "rechnung"}.pdf`; } /** * Human period label for the invoice email, derived from the stored report * period (Europe/Berlin). Spans longer than 40 days are treated as quarters. */ export function formatPeriodLabel(startsAt: Date, endsAt: Date): string { const spanDays = (endsAt.getTime() - startsAt.getTime()) / 86_400_000; const parts = new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric", timeZone: "Europe/Berlin", }).formatToParts(startsAt); const month = parts.find((part) => part.type === "month")?.value ?? ""; const year = parts.find((part) => part.type === "year")?.value ?? ""; if (spanDays > 40) { const monthIndex = new Intl.DateTimeFormat("en-US", { month: "numeric", timeZone: "Europe/Berlin", }).format(startsAt); const quarter = Math.floor((Number(monthIndex) - 1) / 3) + 1; return `Q${quarter} ${year}`; } return `${month} ${year}`; } async function audit( type: string, adminUserId: string, reportId: string, metadata: Record, ): Promise { try { await writeAudit({ type, actorUserId: adminUserId, actorType: "admin", entityType: "billing_report", entityId: reportId, metadata, }); } catch { // Audit is observability, not a transaction participant. } } // --------------------------------------------------------------------------- // Drizzle repository // --------------------------------------------------------------------------- export function createInvoiceRepository( database: NodePgDatabase, ): InvoiceRepository { return { async getReport(reportId) { const [row] = await database .select({ id: billingReports.id, status: billingReports.status, editorialAccountId: billingReports.editorialAccountId, reportNumber: billingReports.reportNumber, invoiceNumber: billingReports.invoiceNumber, periodStartsAt: billingReports.periodStartsAt, periodEndsAt: billingReports.periodEndsAt, pdf: billingReports.pdf, invoicePdf: billingReports.invoicePdf, invoicePdfFilename: billingReports.invoicePdfFilename, }) .from(billingReports) .where(eq(billingReports.id, reportId)) .limit(1); return (row as InvoiceReport | undefined) ?? null; }, async getEditorialEmail(editorialId) { const [row] = await database .select({ email: editorialAccounts.loginEmail }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)) .limit(1); return row?.email ?? null; }, async storeInvoice(reportId, input) { await database .update(billingReports) .set({ invoicePdf: input.bytes, invoicePdfSha256: input.sha256, invoicePdfFilename: input.filename, invoiceUploadedAt: input.uploadedAt, invoiceEmailStatus: "not_sent", invoiceEmailSentAt: null, invoiceEmailError: null, }) .where(eq(billingReports.id, reportId)); }, async markEmailOutcome(reportId, outcome, error) { await database .update(billingReports) .set({ invoiceEmailStatus: outcome, invoiceEmailSentAt: outcome === "sent" ? new Date() : null, invoiceEmailError: error, }) .where(eq(billingReports.id, reportId)); }, }; } export const invoiceService = createInvoiceService({ repo: createInvoiceRepository(db), sendEmail: async (input) => { await emailService.sendInvoiceBundle( input.toEmail, input.periodLabel, input.invoicePdf, input.reportPdf, input.invoiceNumber, ); }, }); export const uploadInvoice = invoiceService.uploadInvoice; export const resendInvoice = invoiceService.resendInvoice; export const getInvoicePdf = invoiceService.getInvoicePdf;