feat: render billing usage pdf

Add the immutable PDF renderer for "Nutzungsnachweis" billing reports.

- src/modules/billing/types.ts: BillingReportSnapshot self-contained type
  (address, selected positions, repeat downloads, net total in cents,
  report/invoice metadata, period, document ID, legal notice).
- src/modules/pdf/document.ts: pdfmake document definition builder with
  monochrome invoice layout (black logo, sender/recipient blocks, rounded
  black summary panel, repeated black table headers, light-gray rows,
  German dates, cents-derived totals, page numbers, document ID, invoice
  reference, legal separation notice).
- src/modules/pdf/render.ts: renderBillingPdf → { bytes, sha256 } using
  pdfmake 0.3 with IBM Plex Mono (OFL) embedded via the VFS.
- scripts/render-pdf-fixture.ts: stress fixture generator (1 row, 60 rows,
  long address, long fields, umlauts, 3-page case) into tmp/pdfs/.
- tests/fixtures/billing-report.ts: deterministic reportFixture (60,00 EUR).
- tsconfig.json: server-only path alias for tsx script execution.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Leon TonhäuserandClaude committed 2026-08-10 17:54:19 +02:00
1 parent d37affc80f
commit 89d76e2711
13 files changed
+1265 -1

No files matched your search

+385
View File
@@ -0,0 +1,385 @@
import "server-only";
import { readFileSync } from "node:fs";
import path from "node:path";
import { formatCents } from "@/modules/billing/format";
import type { BillingReportSnapshot } from "@/modules/billing/types";
// ---------------------------------------------------------------------------
// Font: IBM Plex Mono (SIL Open Font License 1.1)
// TTF files are vendored under src/modules/pdf/fonts/ — see LICENSE.txt.
// ---------------------------------------------------------------------------
export const FONT_NAME = "IBMPlexMono";
// ---------------------------------------------------------------------------
// Colors (monochrome palette)
// ---------------------------------------------------------------------------
const BLACK = "#000000";
const WHITE = "#FFFFFF";
const LIGHT_GRAY = "#F2F2F2";
const MEDIUM_GRAY = "#888888";
// ---------------------------------------------------------------------------
// Date formatting (Europe/Berlin, German format)
// ---------------------------------------------------------------------------
function formatGermanDate(date: Date): string {
return new Intl.DateTimeFormat("de-DE", {
timeZone: "Europe/Berlin",
day: "2-digit",
month: "2-digit",
year: "numeric",
}).format(date);
}
function formatPeriodRange(fromUtc: Date, toUtcExclusive: Date): string {
return `${formatGermanDate(fromUtc)} – ${formatGermanDate(toUtcExclusive)}`;
}
// ---------------------------------------------------------------------------
// Logo (base64 data URL, read at build time from public/brand/logo-black.png)
// ---------------------------------------------------------------------------
function logoDataUrl(): string {
const logoPath = path.join(process.cwd(), "public", "brand", "logo-black.png");
const buffer = readFileSync(logoPath);
return `data:image/png;base64,${buffer.toString("base64")}`;
}
// ---------------------------------------------------------------------------
// Table builders
// ---------------------------------------------------------------------------
function paidPositionsTable(snapshot: BillingReportSnapshot) {
const headerRow = [
{ text: "Datei", style: "tableHeader" },
{ text: "Album", style: "tableHeader" },
{ text: "Zweck", style: "tableHeader" },
{ text: "Referenz", style: "tableHeader" },
{ text: "Datum", style: "tableHeader", alignment: "right" as const },
{ text: "Betrag", style: "tableHeader", alignment: "right" as const },
];
const body = [headerRow];
for (const pos of snapshot.selectedPositions) {
body.push([
{ text: pos.filename, style: "tableCell" },
{ text: pos.albumName, style: "tableCell" },
{ text: pos.purpose, style: "tableCell" },
{ text: pos.reference ?? "", style: "tableCell" },
{ text: formatGermanDate(pos.createdAt), style: "tableCell", alignment: "right" as const },
{ text: formatCents(pos.priceCents), style: "tableCell", alignment: "right" as const },
]);
}
return {
table: {
headerRows: 1,
widths: ["*", "auto", "auto", "auto", "auto", "auto"],
body,
},
layout: {
fillColor: (rowIndex: number) => {
if (rowIndex === 0) return BLACK;
return rowIndex % 2 === 0 ? LIGHT_GRAY : WHITE;
},
hLineColor: () => MEDIUM_GRAY,
vLineColor: () => MEDIUM_GRAY,
hLineWidth: () => 0.5,
vLineWidth: () => 0.5,
},
margin: [0, 0, 0, 16],
};
}
function repeatDownloadsTable(snapshot: BillingReportSnapshot) {
const headerRow = [
{ text: "Datei", style: "tableHeader" },
{ text: "Nutzung", style: "tableHeader" },
{ text: "Datum", style: "tableHeader", alignment: "right" as const },
{ text: "Hinweis", style: "tableHeader" },
];
const body = [headerRow];
for (const dl of snapshot.repeatDownloads) {
body.push([
{ text: dl.assetId, style: "tableCell" },
{ text: dl.usageId, style: "tableCell" },
{ text: formatGermanDate(dl.authorizedAt), style: "tableCell", alignment: "right" as const },
{ text: dl.repeatDownloadNote ?? "", style: "tableCell" },
]);
}
return {
table: {
headerRows: 1,
widths: ["auto", "auto", "auto", "*"],
body,
},
layout: {
fillColor: (rowIndex: number) => {
if (rowIndex === 0) return BLACK;
return rowIndex % 2 === 0 ? LIGHT_GRAY : WHITE;
},
hLineColor: () => MEDIUM_GRAY,
vLineColor: () => MEDIUM_GRAY,
hLineWidth: () => 0.5,
vLineWidth: () => 0.5,
},
margin: [0, 0, 0, 16],
};
}
// ---------------------------------------------------------------------------
// Document definition
// ---------------------------------------------------------------------------
export function buildDocumentDefinition(snapshot: BillingReportSnapshot) {
const addr = snapshot.address;
const addressLines = [
addr.companyName,
addr.contactName,
addr.addressLine1,
addr.addressLine2,
`${addr.postalCode} ${addr.city}`,
addr.countryCode,
].filter((line): line is string => line !== null && line.length > 0);
const doc = {
pageSize: "A4",
pageMargins: [40, 120, 40, 60],
defaultStyle: {
font: FONT_NAME,
fontSize: 9,
lineHeight: 1.3,
color: BLACK,
},
styles: {
title: {
font: FONT_NAME,
fontSize: 20,
bold: true,
margin: [0, 20, 0, 12],
},
sectionHeading: {
font: FONT_NAME,
fontSize: 11,
bold: true,
margin: [0, 16, 0, 8],
},
tableHeader: {
font: FONT_NAME,
fontSize: 8,
bold: true,
color: WHITE,
},
tableCell: {
font: FONT_NAME,
fontSize: 8,
},
summaryLabel: {
font: FONT_NAME,
fontSize: 11,
bold: true,
color: WHITE,
},
summaryValue: {
font: FONT_NAME,
fontSize: 16,
bold: true,
color: WHITE,
},
small: {
font: FONT_NAME,
fontSize: 7,
color: MEDIUM_GRAY,
},
sender: {
font: FONT_NAME,
fontSize: 7,
color: MEDIUM_GRAY,
},
recipient: {
font: FONT_NAME,
fontSize: 9,
},
legal: {
font: FONT_NAME,
fontSize: 8,
color: MEDIUM_GRAY,
},
},
images: {
logo: logoDataUrl(),
},
header: (_currentPage: number, pageSize: { width: number; height: number }) => ({
margin: [40, 30, 40, 10],
stack: [
{
columns: [
{
image: "logo",
width: 120,
},
{
width: "*",
stack: [
{ text: "Redaktionsportal", style: "sender", alignment: "right" as const },
{ text: "Nutzungsnachweis-Service", style: "sender", alignment: "right" as const },
],
margin: [0, 4, 0, 0],
},
],
},
{
canvas: [
{
type: "line",
x1: 0,
y1: 10,
x2: pageSize.width - 80,
y2: 10,
lineWidth: 1,
lineColor: BLACK,
},
],
margin: [0, 8, 0, 0],
},
],
}),
footer: (currentPage: number, pageCount: number) => ({
margin: [40, 20, 40, 0],
stack: [
{
canvas: [
{
type: "line",
x1: 0,
y1: 0,
x2: 515,
y2: 0,
lineWidth: 0.5,
lineColor: MEDIUM_GRAY,
},
],
},
{
columns: [
{ text: `Dokument-ID: ${snapshot.documentId}`, style: "small" },
{ text: `Rechnung: ${snapshot.invoiceNumber}`, style: "small" },
{
text: `Seite ${currentPage} / ${pageCount}`,
style: "small",
alignment: "right" as const,
},
],
margin: [0, 4, 0, 0],
},
],
}),
content: [
// Recipient block
{
stack: addressLines.map((line) => ({ text: line, style: "recipient" })),
margin: [0, 0, 0, 20],
},
// Title
{ text: "Nutzungsnachweis", style: "title" },
// Metadata block
{
columns: [
{
width: "auto",
stack: [
{ text: "Berichtsnummer", style: "small" },
{ text: String(snapshot.reportNumber), style: "recipient", margin: [0, 0, 0, 6] },
{ text: "Abrechnungszeitraum", style: "small" },
{
text: formatPeriodRange(snapshot.period.fromUtc, snapshot.period.toUtcExclusive),
style: "recipient",
margin: [0, 0, 0, 6],
},
{ text: "Erstellt am", style: "small" },
{ text: formatGermanDate(snapshot.createdAt), style: "recipient" },
],
},
{
width: "*",
stack: [
{ text: "Rechnungsnummer", style: "small" },
{ text: snapshot.invoiceNumber, style: "recipient", margin: [0, 0, 0, 6] },
{ text: "Dokument-ID", style: "small" },
{ text: snapshot.documentId, style: "recipient" },
],
},
],
margin: [0, 0, 0, 16],
},
// Rounded black summary panel
{
canvas: [
{
type: "rect",
x: 0,
y: 0,
w: 515,
h: 60,
r: 8,
lineColor: BLACK,
fillColor: BLACK,
},
],
margin: [0, 0, 0, 4],
},
{
// Overlay text on the summary panel (absolute positioning via column trick)
margin: [16, -52, 16, 0],
columns: [
{
width: "*",
text: "Gesamtbetrag (Netto)",
style: "summaryLabel",
margin: [0, 8, 0, 0],
},
{
width: "auto",
text: formatCents(snapshot.netTotalCents),
style: "summaryValue",
margin: [0, 4, 0, 0],
},
],
},
{ text: "", margin: [0, 0, 0, 16] },
// Paid positions section
{ text: "Berechnete Bildnutzungen", style: "sectionHeading" },
paidPositionsTable(snapshot),
// Repeat downloads section
{ text: "Nicht erneut berechnete Downloads", style: "sectionHeading" },
repeatDownloadsTable(snapshot),
// Legal separation notice
{ text: snapshot.legalSeparationNotice, style: "legal", margin: [0, 20, 0, 0] },
],
info: {
title: `Nutzungsnachweis ${snapshot.invoiceNumber}`,
author: "Redaktionsportal",
subject: `Nutzungsnachweis für den Zeitraum ${formatPeriodRange(
snapshot.period.fromUtc,
snapshot.period.toUtcExclusive,
)}`,
creationDate: snapshot.createdAt,
},
};
return doc;
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
+92
View File
@@ -0,0 +1,92 @@
Copyright © 2017 IBM Corp. with Reserved Font Name "Plex"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+54
View File
@@ -0,0 +1,54 @@
import { createRequire } from "node:module";
import { expect, test } from "vitest";
import { reportFixture } from "../../../tests/fixtures/billing-report";
import { renderBillingPdf } from "./render";
const require = createRequire(import.meta.url);
/**
* Extracts all text content from a PDF buffer using pdfjs-dist. Uses the
* legacy build which does not require browser APIs (DOMMatrix etc.) and
* loads the worker from the filesystem so it works in the Node test env.
*/
async function extractPdfText(bytes: Buffer): Promise<string> {
const pdfjs = await import("pdfjs-dist/legacy/build/pdf.mjs");
const workerPath = require.resolve("pdfjs-dist/legacy/build/pdf.worker.mjs");
pdfjs.GlobalWorkerOptions.workerSrc = workerPath;
const loadingTask = pdfjs.getDocument({
data: new Uint8Array(bytes),
verbosity: 0,
useWorkerFetch: false,
});
const pdf = await loadingTask.promise;
const parts: string[] = [];
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const content = await page.getTextContent();
for (const item of content.items) {
if ("str" in item) {
parts.push(item.str);
}
}
}
await loadingTask.destroy();
return parts.join(" ").replace(/\s+/g, " ").trim();
}
test("renders paid and free-repeat sections with the net total", async () => {
const result = await renderBillingPdf(reportFixture);
const text = await extractPdfText(result.bytes);
expect(text).toContain("Nutzungsnachweis");
expect(text).toContain("Berechnete Bildnutzungen");
expect(text).toContain("Nicht erneut berechnete Downloads");
expect(text).toContain("60,00 EUR");
expect(result.sha256).toMatch(/^[a-f0-9]{64}$/);
});
test("pdf buffer is non-empty and starts with the PDF magic header", async () => {
const result = await renderBillingPdf(reportFixture);
expect(result.bytes.length).toBeGreaterThan(1000);
expect(result.bytes.subarray(0, 5).toString("ascii")).toBe("%PDF-");
});
+76
View File
@@ -0,0 +1,76 @@
import "server-only";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import type { BillingReportSnapshot } from "@/modules/billing/types";
import { buildDocumentDefinition, FONT_NAME } from "./document";
// ---------------------------------------------------------------------------
// Font: IBM Plex Mono — SIL Open Font License 1.1 (see fonts/LICENSE.txt)
// The TTF files are vendored under src/modules/pdf/fonts/ and embedded into
// the PDF via pdfmake's virtual filesystem so the renderer never reads the
// real filesystem at render time.
// ---------------------------------------------------------------------------
const FONTS_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "fonts");
interface PdfMakeInstance {
createPdf(docDefinition: unknown): { getBuffer(): Promise<Buffer> };
setFonts(fonts: Record<string, unknown>): void;
setLocalAccessPolicy(callback: (p: string) => boolean): void;
virtualfs: {
writeFileSync(filename: string, content: Buffer): void;
existsSync(filename: string): boolean;
};
}
// pdfmake exports a CommonJS singleton; use createRequire to preserve the
// `this` context that methods like setFonts rely on.
const require = createRequire(import.meta.url);
const pdfmake = require("pdfmake") as PdfMakeInstance;
function readFont(filename: string): Buffer {
return readFileSync(path.join(FONTS_DIR, filename));
}
// Register fonts once at module load time. Writing to the VFS is idempotent —
// overwriting the same key with the same buffer is a no-op.
pdfmake.virtualfs.writeFileSync("IBMPlexMono-Regular.ttf", readFont("IBMPlexMono-Regular.ttf"));
pdfmake.virtualfs.writeFileSync("IBMPlexMono-Bold.ttf", readFont("IBMPlexMono-Bold.ttf"));
pdfmake.virtualfs.writeFileSync("IBMPlexMono-Italic.ttf", readFont("IBMPlexMono-Italic.ttf"));
pdfmake.setFonts({
[FONT_NAME]: {
normal: "IBMPlexMono-Regular.ttf",
bold: "IBMPlexMono-Bold.ttf",
italics: "IBMPlexMono-Italic.ttf",
bolditalics: "IBMPlexMono-Bold.ttf",
},
});
// Allow pdfmake to read font files from the VFS and the logo from the real
// filesystem (the logo is loaded as a base64 data URL in document.ts, so no
// real file access is needed at render time).
pdfmake.setLocalAccessPolicy(() => true);
// ---------------------------------------------------------------------------
// Renderer
// ---------------------------------------------------------------------------
export type RenderedPdf = {
bytes: Buffer;
sha256: string;
};
export async function renderBillingPdf(snapshot: BillingReportSnapshot): Promise<RenderedPdf> {
const docDefinition = buildDocumentDefinition(snapshot);
const pdf = pdfmake.createPdf(docDefinition);
const bytes = await pdf.getBuffer();
const sha256 = createHash("sha256").update(bytes).digest("hex");
return { bytes, sha256 };
}