Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(documents): show the invoice contact on sales invoice PDFs and render Latin Ext letters (#2078)
Brad Barbinb5d5226fa7e0
diff --git a/.claude/rules/pdf-generation-patterns.md b/.claude/rules/pdf-generation-patterns.mdindex a7f2aab04a..11ec99177f 100644--- a/.claude/rules/pdf-generation-patterns.md+++ b/.claude/rules/pdf-generation-patterns.md@@ -107,7 +107,7 @@ Times-Roman / Courier are PDF built-ins (no registration).`Offset is outside the bounds of the DataView` at embed. woff (zlib) is stateless.Also avoid OpenType **variable** fonts — react-pdf can't subset them (PDF 2.0).- `pdf/fonts.data.ts` — **generated, gitignored** `BUNDLED_FONTS` (base64 woff,- ~720 KiB). Produced by `scripts/generate-fonts.mjs` from the `@fontsource/*`+ ~1.4 MiB). Produced by `scripts/generate-fonts.mjs` from the `@fontsource/*`devDeps (static, numeric-weight instances — NOT the variable packages). The`@carbon/documents` **`build`** script is the single entry point; it runs:- on the **root `postinstall`** (`pnpm --filter @carbon/documents build`) — so the@@ -124,8 +124,18 @@ Times-Roman / Courier are PDF built-ins (no registration).`getSafeFontFamily` — no crash.- `ensureFont(family)` — back-compat async wrapper (routes still `await` it); justcalls `registerDocumentFonts()`. The `family` arg is ignored (all registered up front).-- `getSafeFontFamily(family)` — returns the family if built-in/registered, else- `"Helvetica"`. **Every render path must route the settings font through this**+- **Two subsets per face.** Fontsource splits a face by unicode range and react-pdf+ has no unicode-range, so each family is registered twice: `Inter` (`latin`) and+ `Inter Latin Ext` (`latin-ext`: ś, ł, ő, č, ș…). With `latin` alone "Przemyśl"+ printed as "Przemy[" (react-pdf fell back to Helvetica, which cannot encode ś).+ The generator renames each Latin Ext face's PostScript name (`-LatinExt`,+ `renamePostScript`): pdfkit reuses an embedded font by that name, so two faces+ sharing one drew Latin Ext glyph ids from the latin subset — wrong letters.+- `getSafeFontFamily(family)` — returns a font **stack** (`string[]`): the family if+ built-in/registered (else `"Helvetica"`), then its Latin Ext face, `Inter` and+ `Inter Latin Ext`, registered names only. react-pdf picks the first font with a+ glyph per character, so built-ins and Lato (whose `latin-ext` is nearly empty)+ borrow Inter's letters. Pinned by `pdf/fonts.test.ts`. **Every render path must route the settings font through this**(both `Template` and the hand-built job traveler, `renderJobTravelerPdf` in`apps/erp/app/modules/production/production.pdf.tsx`, which both traveler routes call)so an unregistered family can never throw.diff --git a/packages/documents/AGENTS.md b/packages/documents/AGENTS.mdindex 81303b836f..b3ffd22fa0 100644--- a/packages/documents/AGENTS.md+++ b/packages/documents/AGENTS.md@@ -7,7 +7,7 @@ PDF generation, email templates, ZPL labels, and QR/barcode utilities.- **Style PDFs with `useTw()` (react-pdf-tailwind), not raw `StyleSheet`** — semantic grays (`gray-600` = heading, `gray-800` = body) keep themes consistent across all blocks- **Resolve async work before render** — QR codes, barcodes, images, and fonts must be resolved to data URLs / registered before the synchronous component tree renders- **Use `@bwip-js/node` for QR/barcodes** — there is no `qrcode` dependency; call `generateQRCode()` or `generateBarcode()` from `src/qr/`-- **Route fonts through `getSafeFontFamily()`** — every render path must use this (falls back to Helvetica) so unregistered families never throw+- **Route fonts through `getSafeFontFamily()`** — every render path must use this: it returns the font stack (family, its Latin Ext face, Inter) so Central European letters render, and falls back to Helvetica so unregistered families never throw- **Register new block-driven docs in `pdf/preview-documents.tsx`** — `DOCUMENT_PDFS[type] = { Component, sample }` is required for the template preview route## Ask First@@ -34,7 +34,7 @@ pnpm --filter @carbon/documents build # generates fonts.data.ts- **Two PDF styles**: block-registry driven (customizable) vs hand-built (fixed layout labels)- **Block shape**: `({ block, data }) => JSX.Element | null`, keyed in per-doc `registry.tsx`-- **Fonts**: bundled as base64 woff in gitignored `pdf/fonts.data.ts`, generated by `scripts/generate-fonts.mjs`+- **Fonts**: bundled as base64 woff in gitignored `pdf/fonts.data.ts`, generated by `scripts/generate-fonts.mjs` — `latin` and `latin-ext` subsets as two families, the Latin Ext face's PostScript name suffixed `-LatinExt` (pdfkit dedupes embedded fonts by that name)- **Email previews**: `src/email/previews/` holds **one fixture per shipped email** — every `NotificationEvent` that sends mail (except `Digest`, which is in-app only), plus the transactional and lifecycle templates. Fixtures are not shipped (not exported from `index.ts`). `pnpm email:previews` is the only way to view them — it serves the react-email dev server over that folder on `EMAIL_DEV_PORT`, and is what `crbn up`'s Email app runs. Point `email-dev.mjs` at `./src/email` by hand if you ever need the bare templates, but the four document emails error there (their props are DB view rows). The per-event `NotificationEmail` fixtures are generated: edit the `previews` array in `scripts/generate-notification-previews.mjs`, re-run it, then `biome check --write` the folder (the generator emits raw JSON indentation)- **Exports**: `./pdf`, `./email`, `./template`, `./zpl`, `./qr`, `./labels`, `./utils`- **`./utils` is the CLIENT-SAFE entry point** — pure display helpers with type-only deps: `withRevisionSuffix(readableId, revisionId)` is the one place the `PO000123-1` format is defined, and `getPurchaseOrderDisplayId` / `getQuoteDisplayId` are the entity-shaped wrappers that delegate to it. Browser code (ERP UI, the `/share/**` pages) must import from here, NOT from `./pdf`, which pulls the whole react-pdf graph into the bundle. `src/utils/index.ts` is deliberately an explicit re-export list, not `export *`: the per-document util files each define their own `getLineDescription`diff --git a/packages/documents/scripts/generate-fonts.mjs b/packages/documents/scripts/generate-fonts.mjsindex 44e8bc149c..de2163366a 100644--- a/packages/documents/scripts/generate-fonts.mjs+++ b/packages/documents/scripts/generate-fonts.mjs@@ -10,17 +10,29 @@// woff2/brotli decoder corrupts shared state across many decodes → DataView range// errors at embed. woff (zlib) is stateless.import { createRequire } from "node:module";-import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import { existsSync, readFileSync, writeFileSync } from "node:fs";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";+import { deflateSync, inflateSync } from "node:zlib";const require = createRequire(import.meta.url);const here = dirname(fileURLToPath(import.meta.url));const OUT = join(here, "..", "src", "pdf", "fonts.data.ts");-// "latin" subset = Western European, keeps the bundle small. Mirrors the bundled-// fonts in DOCUMENT_FONTS (template/schema.ts).-const SUBSET = "latin";+// Mirrors the bundled fonts in DOCUMENT_FONTS (template/schema.ts). Fontsource+// splits each face by unicode range, and react-pdf has no unicode-range, so each+// subset is registered as its own family: "Inter" holds "latin" (Western European)+// and "Inter Latin Ext" holds "latin-ext" (Central European: ś, ł, ő, č…). fonts.ts+// stacks them, and react-pdf picks per glyph. Without latin-ext a Polish city like+// "Przemyśl" printed as "Przemy[".+//+// Both subsets of a face carry the same PostScript name, and pdfkit reuses an+// embedded font by that name, so a Latin Ext glyph id was drawn from the latin+// subset (wrong letters). `psSuffix` renames the Latin Ext face (renamePostScript).+const SUBSETS = [+ { subset: "latin", suffix: "", psSuffix: "" },+ { subset: "latin-ext", suffix: " Latin Ext", psSuffix: "-LatinExt" },+];const FAMILIES = [{ family: "Inter", pkg: "@fontsource/inter", weights: [300, 400, 500, 700, 900] },{ family: "Roboto", pkg: "@fontsource/roboto", weights: [400, 700] },@@ -46,13 +58,111 @@ function filesDir(pkg) {return join(dirname(pkgJson), "files");}-function findWoff(dir, id, weight) {- const exact = join(dir, `${id}-${SUBSET}-${weight}-normal.woff`);- if (existsSync(exact)) return exact;- const all = readdirSync(dir);- const re = new RegExp(`^${id}-${SUBSET}.*-${weight}-normal\\.woff$`);- const hit = all.find((f) => re.test(f)) ?? all.find((f) => f.includes(`-${SUBSET}-`) && f.endsWith(`-${weight}-normal.woff`));- return hit ? join(dir, hit) : null;+function findWoff(dir, id, subset, weight) {+ const exact = join(dir, `${id}-${subset}-${weight}-normal.woff`);+ return existsSync(exact) ? exact : null;+}++const align4 = (n) => (n + 3) & ~3;++function sfntChecksum(buf) {+ const padded = Buffer.alloc(align4(buf.length));+ buf.copy(padded);+ let sum = 0;+ for (let i = 0; i < padded.length; i += 4) sum = (sum + padded.readUInt32BE(i)) >>> 0;+ return sum;+}++// Appends `suffix` to every PostScript name record (nameID 6) of an sfnt `name`+// table. The new strings go at the end of the string storage and the records are+// repointed, so no other offset moves.+function renameNameTable(table, suffix) {+ const count = table.readUInt16BE(2);+ const storage = table.readUInt16BE(4);+ const out = Buffer.from(table);+ const added = [];+ let end = table.length - storage;+ for (let i = 0; i < count; i++) {+ const rec = 6 + i * 12;+ if (out.readUInt16BE(rec + 6) !== 6) continue;+ const platform = out.readUInt16BE(rec);+ const length = out.readUInt16BE(rec + 8);+ const offset = storage + out.readUInt16BE(rec + 10);+ const old = table.subarray(offset, offset + length);+ // Windows/Unicode names are UTF-16BE; Macintosh names are one byte per char.+ const name =+ platform === 1 ? Buffer.from(old.toString("latin1") + suffix, "latin1") : utf16be(utf16beString(old) + suffix);+ out.writeUInt16BE(name.length, rec + 8);+ out.writeUInt16BE(end, rec + 10);+ added.push(name);+ end += name.length;+ }+ if (!added.length) throw new Error("font has no PostScript name to rename");+ return Buffer.concat([out, ...added]);+}++function utf16beString(buf) {+ let s = "";+ for (let i = 0; i + 1 < buf.length; i += 2) s += String.fromCharCode(buf.readUInt16BE(i));+ return s;+}++function utf16be(s) {+ const buf = Buffer.alloc(s.length * 2);+ for (let i = 0; i < s.length; i++) buf.writeUInt16BE(s.charCodeAt(i), i * 2);+ return buf;+}++// Rewrites a WOFF 1.0 file with its PostScript name suffixed. Every table is kept+// byte for byte except `name`; metadata and private blocks are dropped.+function renamePostScript(woff, suffix) {+ if (woff.toString("latin1", 0, 4) !== "wOFF") throw new Error("not a WOFF 1.0 file");+ const numTables = woff.readUInt16BE(12);+ const tables = [];+ for (let i = 0; i < numTables; i++) {+ const dir = 44 + i * 20;+ const tag = woff.toString("latin1", dir, dir + 4);+ const offset = woff.readUInt32BE(dir + 4);+ const compLength = woff.readUInt32BE(dir + 8);+ const origLength = woff.readUInt32BE(dir + 12);+ let data = woff.subarray(offset, offset + compLength);+ let checksum = woff.readUInt32BE(dir + 16);+ if (tag === "name") {+ const raw = compLength < origLength ? inflateSync(data) : data;+ const renamed = renameNameTable(raw, suffix);+ checksum = sfntChecksum(renamed);+ const packed = deflateSync(renamed);+ tables.push({ tag, data: packed.length < renamed.length ? packed : renamed, origLength: renamed.length, checksum });+ continue;+ }+ tables.push({ tag, data, origLength, checksum });+ }++ let offset = 44 + numTables * 20;+ let sfntSize = 12 + numTables * 16;+ const placed = tables.map((t) => {+ const at = offset;+ offset += align4(t.data.length);+ sfntSize += align4(t.origLength);+ return { ...t, at };+ });++ const out = Buffer.alloc(offset);+ woff.copy(out, 0, 0, 12); // signature, flavor, (length rewritten below)+ out.writeUInt32BE(offset, 8);+ out.writeUInt16BE(numTables, 12);+ out.writeUInt32BE(sfntSize, 16);+ woff.copy(out, 20, 20, 24); // font version+ placed.forEach((t, i) => {+ const dir = 44 + i * 20;+ out.write(t.tag, dir, "latin1");+ out.writeUInt32BE(t.at, dir + 4);+ out.writeUInt32BE(t.data.length, dir + 8);+ out.writeUInt32BE(t.origLength, dir + 12);+ out.writeUInt32BE(t.checksum, dir + 16);+ t.data.copy(out, t.at);+ });+ return out;}const entries = [];@@ -67,18 +177,21 @@ for (const { family, pkg, weights } of FAMILIES) {warnings.push(`MISSING package ${pkg} — run pnpm install. Skipped ${family}.`);continue;}- const fonts = [];- for (const weight of weights) {- const file = findWoff(dir, pkg.split("/")[1], weight);- if (!file) {- warnings.push(`No woff for ${family} ${weight} (${SUBSET}) in ${dir}`);- continue;+ for (const { subset, suffix, psSuffix } of SUBSETS) {+ const fonts = [];+ for (const weight of weights) {+ const file = findWoff(dir, pkg.split("/")[1], subset, weight);+ if (!file) {+ warnings.push(`No woff for ${family} ${weight} (${subset}) in ${dir}`);+ continue;+ }+ const raw = readFileSync(file);+ const buf = psSuffix ? renamePostScript(raw, psSuffix) : raw;+ totalBytes += buf.length;+ fonts.push({ src: `data:font/woff;base64,${buf.toString("base64")}`, fontWeight: weight });}- const buf = readFileSync(file);- totalBytes += buf.length;- fonts.push({ src: `data:font/woff;base64,${buf.toString("base64")}`, fontWeight: weight });+ if (fonts.length) entries.push({ family: `${family}${suffix}`, fonts });}- if (fonts.length) entries.push({ family, fonts });}const body = entriesdiff --git a/packages/documents/src/pdf/blocks/PartiesBlock.tsx b/packages/documents/src/pdf/blocks/PartiesBlock.tsxindex a46c3f5202..16d6a29676 100644--- a/packages/documents/src/pdf/blocks/PartiesBlock.tsx+++ b/packages/documents/src/pdf/blocks/PartiesBlock.tsx@@ -44,7 +44,9 @@ export function PartiesBlock({ data }: { data: SalesInvoiceData }) {shipmentCity,shipmentStateProvince,shipmentPostalCode,- shipmentCountryName+ shipmentCountryName,+ contactName,+ contactEmail} = salesInvoiceLocations;const paymentTerm = paymentTerms?.find(@@ -80,6 +82,8 @@ export function PartiesBlock({ data }: { data: SalesInvoiceData }) {) : null}{customerVatNumber ? <Text>VAT: {customerVatNumber}</Text> : null}{customerEori ? <Text>EORI: {customerEori}</Text> : null}+ {contactName ? <Text>Contact: {contactName}</Text> : null}+ {contactEmail ? <Text>Email: {contactEmail}</Text> : null}</View></View>diff --git a/packages/documents/src/pdf/blocks/types.ts b/packages/documents/src/pdf/blocks/types.tsindex 3e08d0cc4d..5e25bf7b8d 100644--- a/packages/documents/src/pdf/blocks/types.ts+++ b/packages/documents/src/pdf/blocks/types.ts@@ -20,6 +20,9 @@ export type SalesInvoiceLocations =Database["public"]["Views"]["salesInvoiceLocations"]["Row"] & {customerTaxId?: string | null;customerVatNumber?: string | null;+ /** The invoice's contact (`invoiceCustomerContactId`), resolved by the loader. */+ contactName?: string | null;+ contactEmail?: string | null;};/**diff --git a/packages/documents/src/pdf/fonts.test.ts b/packages/documents/src/pdf/fonts.test.tsnew file mode 100644index 0000000000..a3abb9dfee--- /dev/null+++ b/packages/documents/src/pdf/fonts.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { Font, renderToBuffer, Text } from "@react-pdf/renderer";+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import { documentSettingsSchema } from "../template/schema";+import Template from "./components/Template";+import { BUILT_IN_FONTS, getSafeFontFamily } from "./fonts";++// Letters outside the "latin" subset that real addresses carry: Polish,+// Czech, Hungarian, Romanian, Turkish. "Przemyśl" printed as "Przemy[".+const CENTRAL_EUROPEAN = "śłąęźżćńőűčřšžďťğışț";++const BODY_FONTS =+ documentSettingsSchema.shape.fontFamily.removeDefault().options;++function loadFaces(stack: string[], fontWeight: number) {+ return Promise.all(+ stack+ .filter((family) => !BUILT_IN_FONTS.includes(family))+ .map(async (fontFamily) => {+ const font = Font.getFont({ fontFamily, fontWeight });+ await font.load();+ if (!font.data) throw new Error(`${fontFamily} did not load`);+ return font.data;+ })+ );+}++async function drawsEveryLetter(stack: string[], fontWeight: number) {+ const faces = await loadFaces(stack, fontWeight);+ return [...CENTRAL_EUROPEAN].filter(+ (letter) =>+ !faces.some((face) => face.hasGlyphForCodePoint(letter.codePointAt(0)))+ );+}++describe("getSafeFontFamily", () => {+ it.each(BODY_FONTS)("%s draws Central European letters", async (family) => {+ const stack = getSafeFontFamily(family);+ expect(stack[0]).toBe(family);+ expect(await drawsEveryLetter(stack, 400)).toEqual([]);+ expect(await drawsEveryLetter(stack, 700)).toEqual([]);+ });++ // pdfkit reuses an embedded font by PostScript name, so two faces sharing one+ // draw the second face's glyph ids from the first: the wrong letters.+ it.each(BODY_FONTS)(+ "%s stacks faces with distinct PostScript names",+ async (family) => {+ const faces = await loadFaces(getSafeFontFamily(family), 400);+ const names = faces.map((face) => face.postscriptName);+ expect(new Set(names).size).toBe(names.length);+ }+ );++ it("falls back to Helvetica for an unregistered family", () => {+ expect(getSafeFontFamily("Comic Sans")[0]).toBe("Helvetica");+ });++ it("renders a document with Central European text", async () => {+ const pdf = await renderToBuffer(+ createElement(+ Template,+ { title: "Invoice", meta: {} as never, fontFamily: "Inter" },+ createElement(Text, null, `Przemyśl ${CENTRAL_EUROPEAN}`)+ ) as never+ );+ expect(pdf.subarray(0, 4).toString()).toBe("%PDF");+ });+});diff --git a/packages/documents/src/pdf/fonts.ts b/packages/documents/src/pdf/fonts.tsindex e0adc19779..663b037a31 100644--- a/packages/documents/src/pdf/fonts.ts+++ b/packages/documents/src/pdf/fonts.ts@@ -30,13 +30,27 @@ export async function ensureFont(_family?: string): Promise<void> {registerDocumentFonts();}-// Falls back to Helvetica for an unregistered family so react-pdf never throws+// Each bundled family's Central European glyphs (ś, ł, ő, č…) live in a separate+// "<family> Latin Ext" face (see scripts/generate-fonts.mjs).+const LATIN_EXT_SUFFIX = " Latin Ext";++// The font stack for a body font: react-pdf picks the first font with a glyph for+// each character, so "Przemyśl" draws "ś" from the Latin Ext face. Inter closes+// the stack because not every face covers Latin Ext (the built-in PDF fonts have+// none of it, Lato only a few letters). Only registered names enter the stack,+// and an unregistered family falls back to Helvetica, so react-pdf never throws// "Font family not registered".-export function getSafeFontFamily(family: string | undefined | null): string {+export function getSafeFontFamily(family: string | undefined | null): string[] {registerDocumentFonts();- if (!family) return "Helvetica";- if (BUILT_IN_FONTS.includes(family)) return family;- return Font.getRegisteredFontFamilies().includes(family)- ? family- : "Helvetica";+ const registered = Font.getRegisteredFontFamilies();+ const base =+ family && (BUILT_IN_FONTS.includes(family) || registered.includes(family))+ ? family+ : "Helvetica";+ const fallbacks = [+ `${base}${LATIN_EXT_SUFFIX}`,+ "Inter",+ `Inter${LATIN_EXT_SUFFIX}`+ ].filter((name) => name !== base && registered.includes(name));+ return [base, ...new Set(fallbacks)];}diff --git a/packages/documents/src/pdf/samples.ts b/packages/documents/src/pdf/samples.tsindex 6751a75edb..366ed11f9d 100644--- a/packages/documents/src/pdf/samples.ts+++ b/packages/documents/src/pdf/samples.ts@@ -86,7 +86,9 @@ export const SAMPLE_SALES_INVOICE = {invoiceCity: "Chicago",invoiceStateProvince: "IL",invoicePostalCode: "60601",- invoiceCountryName: "United States"+ invoiceCountryName: "United States",+ contactName: "Hank Scorpio",+ contactEmail: "[email protected]"},salesInvoiceShipment: {shippingCost: 0,diff --git a/packages/lib/src/sales-invoice-document.server.tsx b/packages/lib/src/sales-invoice-document.server.tsxindex 7d8927f13d..91dc471250 100644--- a/packages/lib/src/sales-invoice-document.server.tsx+++ b/packages/lib/src/sales-invoice-document.server.tsx@@ -307,15 +307,35 @@ export async function loadSalesInvoiceDocument(args: {// Settlement decimals from the document currency's row (authoritative over// CLDR); null keeps the PDF's historical 2dp fallback.- const currencyRow = salesInvoice.data.currencyCode- ? await client- .from("currencies")- .select("*")- .eq("code", salesInvoice.data.currencyCode)- .eq("companyGroupId", companyGroupId)- .single()- : null;+ const [currencyRow, invoiceContact] = await Promise.all([+ salesInvoice.data.currencyCode+ ? client+ .from("currencies")+ .select("*")+ .eq("code", salesInvoice.data.currencyCode)+ .eq("companyGroupId", companyGroupId)+ .single()+ : null,+ salesInvoice.data.invoiceCustomerContactId+ ? client+ .from("customerContact")+ .select("contact(fullName, email)")+ .eq("id", salesInvoice.data.invoiceCustomerContactId)+ .eq("companyId", companyId)+ .maybeSingle()+ : null+ ]);const currencyDecimals = currencyRow?.data?.decimalPlaces ?? null;+ if (invoiceContact?.error) {+ logger.error("Failed to load invoice contact", {+ error: invoiceContact.error+ });+ }+ const locations = {+ ...salesInvoiceLocations.data,+ contactName: invoiceContact?.data?.contact?.fullName ?? null,+ contactEmail: invoiceContact?.data?.contact?.email ?? null+ };// `company` (table, logos rewritten to public URLs) stands in for the// `companies` view row the documents type against, as the routes always did.@@ -335,7 +355,7 @@ export async function loadSalesInvoiceDocument(args: {salesInvoice: salesInvoice.data,salesInvoiceLines: lines,salesOrderIds,- salesInvoiceLocations: salesInvoiceLocations.data,+ salesInvoiceLocations: locations,salesInvoiceShipment: salesInvoiceShipment.data,accountsReceivableBillingAddress: companySettings.data?.accountsReceivableAddress