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 { writeAudit } from "@/modules/audit/write"; 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; flatrateCentsSnapshot: number | null; 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; getEditorialFlatrate(editorialId: string): Promise<{ flatrateActive: boolean; flatratePriceCents: number | null; flatrateAssetLimit: number | null; } | null>; getSelectedUsages(editorialId: string, usageIds: string[]): Promise; getRepeatDownloads(editorialId: string, period: BillingPeriod): Promise; allocateReportNumber(): Promise; // Atomic finalization (transaction internal to the repo implementation) finalizeInTransaction(input: FinalizeTransactionInput): Promise; // Cancellation getReportWithItemUsageIds( reportId: string, ): Promise<{ status: string; usageIds: string[] } | null>; cancelReportInTransaction( reportId: string, reason: string, adminUserId: string, usageIds: string[], ): Promise; // 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; getReport(reportId: string): Promise; }; // --------------------------------------------------------------------------- // 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 { 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, flatrateCentsSnapshot: input.flatrateCentsSnapshot, 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 { 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, flatrateCentsSnapshot: input.flatrateCentsSnapshot, 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, flatrateCentsSnapshot: input.flatrateCentsSnapshot, pdfBytes: rendered.bytes, pdfSha256: rendered.sha256, documentId, createdAt, legalSeparationNotice: LEGAL_SEPARATION_NOTICE, }); try { await writeAudit({ type: "billing_report_finalized", actorUserId: input.adminUserId, actorType: "admin", entityType: "billing_report", entityId: result.reportId, metadata: { editorialId: input.editorialId, reportNumber: result.reportNumber, invoiceNumber: result.invoiceNumber, netTotalCents, usageCount: selectedUsages.length, }, }); } catch { // Audit is observability, not a transaction participant. } 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 { 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, ); try { await writeAudit({ type: "billing_report_cancelled", actorUserId: input.adminUserId, actorType: "admin", entityType: "billing_report", entityId: input.reportId, metadata: { reason, usageCount: report.usageIds.length }, }); } catch { // Audit is observability, not a transaction participant. } }, /** * 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; flatrateCentsSnapshot: number | null; }> { 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 editorialFlatrate = await repo.getEditorialFlatrate(input.editorialId); let flatrateCentsSnapshot: number | null = null; if (editorialFlatrate && editorialFlatrate.flatrateActive && editorialFlatrate.flatratePriceCents !== null) { flatrateCentsSnapshot = editorialFlatrate.flatratePriceCents; } const repeatDownloads = await repo.getRepeatDownloads(input.editorialId, input.period); let netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0); if (flatrateCentsSnapshot !== null) { netTotalCents += flatrateCentsSnapshot; } return { usages: selectedUsages, address, repeatDownloads, netTotalCents, flatrateCentsSnapshot }; } 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, ): 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 getEditorialFlatrate(editorialId) { const [editorial] = await database .select({ flatrateActive: editorialAccounts.flatrateActive, flatratePriceCents: editorialAccounts.flatratePriceCents, flatrateAssetLimit: editorialAccounts.flatrateAssetLimit, }) .from(editorialAccounts) .where(eq(editorialAccounts.id, editorialId)) .limit(1); return editorial || null; }, 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, flatrateCentsSnapshot: input.flatrateCentsSnapshot, 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;