Skip to content

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.

feat: enhance document templates with registration number support (#1024)

Naveen Kashyap3e5fa3909732
diff --git a/.ai/rules/document-template-customizer.md b/.ai/rules/document-template-customizer.md
index 8e7f9ede0d..b0d41b0b98 100644
--- a/.ai/rules/document-template-customizer.md
+++ b/.ai/rules/document-template-customizer.md
@@ -27,9 +27,10 @@ Created by `packages/database/supabase/migrations/20260609143732_document-templa
render), plus audit cols. Realtime-enabled. RLS gated on the **settings** module
(`settings_create/update/delete`).
- **`documentSection`** — company-global reusable rich-text sections. `placement`
- (`body|header|footer`, plain TEXT), `content JSONB`, `config JSONB` (header
- layout: logo, visible company fields). Editing a built-in section **forks** it
- into a row (`upsertDocumentSection`).
+ (`body|header|footer`, plain TEXT), `content JSONB`, `config JSONB` (header:
+ logo + visible company fields; footer: registration line
+ `showRegistrationLine`/`registrationNumber`, merge-field capable). Editing a
+ built-in section **forks** it into a row (`upsertDocumentSection`).
JSON columns are untyped in generated DB types. `toDocumentTemplate(row, type)`
(`template/schema.ts`) is the **one** cast point — callers use it instead of
diff --git a/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx b/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx
index 4f9ef57b79..3f49d302ab 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx
@@ -231,9 +231,9 @@ function TypeBadge({ category }: { category: BlockCategory }) {
}
/**
- * Header & footer are global shared sections — their fields (logo, which
- * company details show) and banner content are edited in a dialog opened right
- * here. The footer also owns its page-number + registration-line settings.
+ * Header & footer are global shared sections — their config (header: logo +
+ * which company details show; footer: registration line) and content are
+ * edited in a dialog opened right here. Page numbers stay per-template below.
*/
function ChromeConfig({ kind }: { kind: "header" | "footer" }) {
const { sections } = useDocumentTemplate();
@@ -287,7 +287,8 @@ function ChromeConfig({ kind }: { kind: "header" | "footer" }) {
);
}
-/** Footer page-number + registration-line settings. */
+/** Footer page-number settings. The registration line is configured on the
+ * shared footer section itself (edit the footer section to change it). */
function FooterSettings() {
const { footerSectionId, settings, setSetting } = useDocumentTemplate();
const hidden = footerSectionId === null;
@@ -329,13 +330,6 @@ function FooterSettings() {
</SelectContent>
</Select>
</div>
- <div className={hidden ? "pointer-events-none opacity-60" : undefined}>
- <ToggleRow
- label="Registration line"
- checked={settings.showRegistrationLine}
- onChange={(v) => setSetting("showRegistrationLine", v)}
- />
- </div>
</div>
);
}
diff --git a/apps/erp/app/components/DocumentTemplateEditor/SectionFormModal.tsx b/apps/erp/app/components/DocumentTemplateEditor/SectionFormModal.tsx
index 7cd47adbe6..887a2aaf6d 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/SectionFormModal.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/SectionFormModal.tsx
@@ -1,11 +1,26 @@
import type {
DocumentSectionPlacement,
- HeaderOptions
+ FooterOptions,
+ HeaderOptions,
+ SectionConfig
+} from "@carbon/documents/template";
+import {
+ COMPANY_MERGE_FIELDS,
+ DEFAULT_FOOTER_OPTIONS,
+ DEFAULT_HEADER_OPTIONS,
+ footerOptionsSchema,
+ getDocumentLabel,
+ headerOptionsSchema,
+ mergeToken,
+ REGISTRATION_LINE_DOCUMENT_TYPES
} from "@carbon/documents/template";
-import { DEFAULT_HEADER_OPTIONS } from "@carbon/documents/template";
import type { JSONContent } from "@carbon/react";
import {
Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
Input,
Label,
Modal,
@@ -31,7 +46,7 @@ export type SectionFormValue = {
name: string;
placement: DocumentSectionPlacement;
content: JSONContent;
- config?: Partial<HeaderOptions>;
+ config?: SectionConfig;
builtIn?: boolean;
};
@@ -62,27 +77,35 @@ export function SectionFormModal({
const [placement, setPlacement] = useState<DocumentSectionPlacement>(
section?.placement ?? "body"
);
- const [config, setConfig] = useState<HeaderOptions>({
+ const [config, setConfig] = useState<HeaderOptions & FooterOptions>({
...DEFAULT_HEADER_OPTIONS,
+ ...DEFAULT_FOOTER_OPTIONS,
...(section?.config ?? {})
});
// Placement is intrinsic once a section exists — don't let it change.
const lockPlacement = Boolean(section);
const isHeader = placement === "header";
+ const isFooter = placement === "footer";
const isSaving = fetcher.state !== "idle";
const submittedRef = useRef(false);
- const setConfigKey = <K extends keyof HeaderOptions>(
+ const setConfigKey = <K extends keyof (HeaderOptions & FooterOptions)>(
key: K,
- value: HeaderOptions[K]
+ value: (HeaderOptions & FooterOptions)[K]
) => setConfig((prev) => ({ ...prev, [key]: value }));
const submit = (form: HTMLFormElement) => {
const data = new FormData(form);
data.set("placement", placement);
data.set("content", JSON.stringify(content));
- if (isHeader) data.set("config", JSON.stringify(config));
+ // Persist only the keys the placement actually uses — parsing through the
+ // placement's schema strips the other group's keys.
+ if (isHeader) {
+ data.set("config", JSON.stringify(headerOptionsSchema.parse(config)));
+ } else if (isFooter) {
+ data.set("config", JSON.stringify(footerOptionsSchema.parse(config)));
+ }
submittedRef.current = true;
fetcher.submit(data, { method: "post", ...(action ? { action } : {}) });
};
@@ -178,6 +201,66 @@ export function SectionFormModal({
</div>
)}
+ {isFooter && (
+ <div className="flex w-full flex-col gap-3 rounded-md border p-3">
+ <ConfigSwitch
+ label="Registration line"
+ checked={config.showRegistrationLine}
+ onChange={(v) => setConfigKey("showRegistrationLine", v)}
+ />
+ {config.showRegistrationLine && (
+ <div className="flex w-full flex-col gap-1.5">
+ <div className="flex items-center justify-between">
+ <Label htmlFor="registrationNumber">
+ Registration number
+ </Label>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ variant="secondary"
+ size="sm"
+ className="shrink-0"
+ >
+ Insert field
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {COMPANY_MERGE_FIELDS.map((field) => (
+ <DropdownMenuItem
+ key={field.token}
+ onClick={() =>
+ setConfigKey(
+ "registrationNumber",
+ config.registrationNumber +
+ mergeToken(field.token)
+ )
+ }
+ >
+ {field.label}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ <Input
+ id="registrationNumber"
+ value={config.registrationNumber}
+ onChange={(e) =>
+ setConfigKey("registrationNumber", e.target.value)
+ }
+ />
+ <p className="text-xs text-muted-foreground">
+ Shown on{" "}
+ {REGISTRATION_LINE_DOCUMENT_TYPES.map(
+ getDocumentLabel
+ ).join(", ")}{" "}
+ documents.
+ </p>
+ </div>
+ )}
+ </div>
+ )}
+
<div className="flex w-full flex-col gap-1.5">
<Label>
{isHeader ? "Banner content (optional)" : "Content"}
diff --git a/apps/erp/app/components/DocumentTemplateEditor/context.tsx b/apps/erp/app/components/DocumentTemplateEditor/context.tsx
index f08f63e562..7f9be20836 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/context.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/context.tsx
@@ -317,6 +317,14 @@ export function DocumentTemplateProvider({
if (!storeRef.current) storeRef.current = createEditorStore(props);
const store = storeRef.current;
+ // Sections are reference data, not draft state: the section modal saves them
+ // through its own action and the route loader revalidates. Resync them into
+ // the store so a reopened modal seeds from the fresh row (e.g. the footer's
+ // registration-line config), leaving the user's draft untouched.
+ useEffect(() => {
+ store.setState({ sections: props.sections });
+ }, [store, props.sections]);
+
const fetcher = useFetcher<{ success?: boolean }>();
const isSaving = fetcher.state !== "idle";
const savedRef = useRef(false);
diff --git a/packages/documents/src/pdf/PackingSlipPDF.tsx b/packages/documents/src/pdf/PackingSlipPDF.tsx
index b08d667bdf..544f6fb17a 100644
--- a/packages/documents/src/pdf/PackingSlipPDF.tsx
+++ b/packages/documents/src/pdf/PackingSlipPDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { PDF } from "../types";
-import { getRegistrationFooter } from "../utils/shared";
+import { resolveRegistrationLine } from "../utils/shared";
import type { PackingSlipData } from "./blocks/packingSlip";
import {
buildPackingSlipVars,
@@ -70,6 +70,14 @@ const PackingSlipPDF = ({
...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})
};
+ const registration = resolveRegistrationLine({
+ company,
+ footerSectionId,
+ sections,
+ settings,
+ vars
+ });
+
const data: PackingSlipData = {
company,
locale,
@@ -119,16 +127,12 @@ const PackingSlipPDF = ({
keywords: meta?.keywords ?? "packing slip",
subject: meta?.subject ?? "Packing Slip"
}}
- footerLabel={getRegistrationFooter(
- company.name,
- company.countryCode,
- company.taxId
- )}
+ footerLabel={registration.label}
footerDocumentId={shipment?.shipmentId}
showFooter={showFooter}
showPageNumbers={settings.showPageNumbers}
pageNumberFormat={settings.pageNumberFormat}
- showRegistrationLine={settings.showRegistrationLine}
+ showRegistrationLine={registration.show}
fontFamily={settings.fontFamily}
headerContent={headerContent}
footerContent={footerContent}
diff --git a/packages/documents/src/pdf/PurchaseOrderPDF.tsx b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
index 048a83ccc8..d068c13ba0 100644
--- a/packages/documents/src/pdf/PurchaseOrderPDF.tsx
+++ b/packages/documents/src/pdf/PurchaseOrderPDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsPayableBillingAddress, PDF } from "../types";
-import { composeRegistrationLine } from "../utils/footer";
+import { resolveRegistrationLine } from "../utils/shared";
import type { PurchaseOrderData } from "./blocks/purchaseOrder";
import {
buildPurchaseOrderVars,
@@ -57,12 +57,6 @@ const PurchaseOrderPDF = ({
maximumFractionDigits: 2
});
- const registrationLine = composeRegistrationLine({
- companyName: company.name,
- country: purchaseOrderLocations.companyCountryName ?? company.countryCode,
- eori: company.eori
- });
-
const headerTitle = purchaseOrder?.purchaseOrderId
? `${title}: ${purchaseOrder.purchaseOrderId}`
: title;
@@ -77,6 +71,14 @@ const PurchaseOrderPDF = ({
currencyCode
});
+ const registration = resolveRegistrationLine({
+ company,
+ footerSectionId,
+ sections,
+ settings,
+ vars
+ });
+
const headerOptions = {
...DEFAULT_HEADER_OPTIONS,
...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})
@@ -130,11 +132,11 @@ const PurchaseOrderPDF = ({
subject: meta?.subject ?? "Purchase Order"
}}
footerDocumentId={purchaseOrder?.purchaseOrderId}
- footerLabel={registrationLine ?? undefined}
+ footerLabel={registration.label}
showFooter={showFooter}
showPageNumbers={settings.showPageNumbers}
pageNumberFormat={settings.pageNumberFormat}
- showRegistrationLine={settings.showRegistrationLine}
+ showRegistrationLine={registration.show}
fontFamily={settings.fontFamily}
headerContent={headerContent}
footerContent={footerContent}
diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsx
index 2045ef0373..1d27beb8b7 100644
--- a/packages/documents/src/pdf/QuotePDF.tsx
+++ b/packages/documents/src/pdf/QuotePDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsReceivableBillingAddress, PDF } from "../types";
-import { composeRegistrationLine } from "../utils/footer";
+import { resolveRegistrationLine } from "../utils/shared";
import type { QuoteCustomerDetails, QuoteData } from "./blocks/quote";
import { buildQuoteVars, quoteBlockRegistry } from "./blocks/quote";
import { Template } from "./components";
@@ -63,12 +63,6 @@ const QuotePDF = ({
maximumFractionDigits: 2
});
- const registrationLine = composeRegistrationLine({
- companyName: company.name,
- country: company.countryCode,
- eori: company.eori
- });
-
const pricesByLine = quoteLinePrices.reduce<Record<string, QuoteLinePrice[]>>(
(acc, price) => {
(acc[price.quoteLineId] ??= []).push(price);
@@ -165,6 +159,14 @@ const QuotePDF = ({
currencyCode
});
+ const registration = resolveRegistrationLine({
+ company,
+ footerSectionId,
+ sections,
+ settings,
+ vars
+ });
+
const headerOptions = {
...DEFAULT_HEADER_OPTIONS,
...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})
@@ -228,11 +230,11 @@ const QuotePDF = ({
subject: meta?.subject ?? "Quote"
}}
footerDocumentId={quote?.quoteId}
- footerLabel={registrationLine ?? undefined}
+ footerLabel={registration.label}
showFooter={showFooter}
showPageNumbers={settings.showPageNumbers}
pageNumberFormat={settings.pageNumberFormat}
- showRegistrationLine={settings.showRegistrationLine}
+ showRegistrationLine={registration.show}
fontFamily={settings.fontFamily}
headerContent={headerContent}
footerContent={footerContent}
diff --git a/packages/documents/src/pdf/SalesInvoicePDF.tsx b/packages/documents/src/pdf/SalesInvoicePDF.tsx
index 4430a92f13..baf013d83d 100644
--- a/packages/documents/src/pdf/SalesInvoicePDF.tsx
+++ b/packages/documents/src/pdf/SalesInvoicePDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsReceivableBillingAddress, PDF } from "../types";
-import { composeRegistrationLine } from "../utils/footer";
+import { resolveRegistrationLine } from "../utils/shared";
import type { SalesInvoiceData, SalesInvoiceLocations } from "./blocks";
import { buildSalesInvoiceVars, salesInvoiceBlockRegistry } from "./blocks";
import { Template } from "./components";
@@ -59,12 +59,6 @@ const SalesInvoicePDF = ({
maximumFractionDigits: 2
});
- const registrationLine = composeRegistrationLine({
- companyName: company.name,
- country: company.countryCode,
- eori: company.eori
- });
-
const { blocks, theme, settings, headerSectionId, footerSectionId } =
resolveTemplate("salesInvoice", template);
@@ -75,6 +69,14 @@ const SalesInvoicePDF = ({
currencyCode
});
+ const registration = resolveRegistrationLine({
+ company,
+ footerSectionId,
+ sections,
+ settings,
+ vars
+ });
+
// Header layout now lives on the global header section's config (not the
// block), so every document shares one header configuration.
const headerOptions = {
@@ -137,11 +139,11 @@ const SalesInvoicePDF = ({
subject: meta?.subject ?? "Invoice"
}}
footerDocumentId={salesInvoice?.invoiceId}
- footerLabel={registrationLine ?? undefined}
+ footerLabel={registration.label}
showFooter={showFooter}
showPageNumbers={settings.showPageNumbers}
pageNumberFormat={settings.pageNumberFormat}
- showRegistrationLine={settings.showRegistrationLine}
+ showRegistrationLine={registration.show}
fontFamily={settings.fontFamily}
headerContent={headerContent}
footerContent={footerContent}
diff --git a/packages/documents/src/pdf/SalesOrderPDF.tsx b/packages/documents/src/pdf/SalesOrderPDF.tsx
index b0e05689a7..5e30c0c7ff 100644
--- a/packages/documents/src/pdf/SalesOrderPDF.tsx
+++ b/packages/documents/src/pdf/SalesOrderPDF.tsx
@@ -8,7 +8,7 @@ import {
resolveTemplate
} from "../template";
import type { AccountsReceivableBillingAddress, PDF } from "../types";
-import { composeRegistrationLine } from "../utils/footer";
+import { resolveRegistrationLine } from "../utils/shared";
import type { SalesOrderData, SalesOrderLocations } from "./blocks/salesOrder";
import {
buildSalesOrderVars,
@@ -58,12 +58,6 @@ const SalesOrderPDF = ({
maximumFractionDigits: 2
});
- const registrationLine = composeRegistrationLine({
- companyName: company.name,
- country: company.countryCode,
- eori: company.eori
- });
-
const { blocks, theme, settings, headerSectionId, footerSectionId } =
resolveTemplate("salesOrder", template);
@@ -74,6 +68,14 @@ const SalesOrderPDF = ({
currencyCode
});
+ const registration = resolveRegistrationLine({
+ company,
+ footerSectionId,
+ sections,
+ settings,
+ vars
+ });
+
const headerOptions = {
...DEFAULT_HEADER_OPTIONS,
...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})
@@ -128,11 +130,11 @@ const SalesOrderPDF = ({
subject: meta?.subject ?? "Sales Order"
}}
footerDocumentId={salesOrder?.salesOrderId}
- footerLabel={registrationLine ?? undefined}
+ footerLabel={registration.label}
showFooter={showFooter}
showPageNumbers={settings.showPageNumbers}
pageNumberFormat={settings.pageNumberFormat}
- showRegistrationLine={settings.showRegistrationLine}
+ showRegistrationLine={registration.show}
fontFamily={settings.fontFamily}
headerContent={headerContent}
footerContent={footerContent}
diff --git a/packages/documents/src/pdf/blocks/packingSlip/vars.ts b/packages/documents/src/pdf/blocks/packingSlip/vars.ts
index 0678dea147..c8f6465af8 100644
--- a/packages/documents/src/pdf/blocks/packingSlip/vars.ts
+++ b/packages/documents/src/pdf/blocks/packingSlip/vars.ts
@@ -20,6 +20,9 @@ export function buildPackingSlipVars(
"customer.country": str(a?.countryCode),
"company.name": str(data.company?.name),
"company.city": str(data.company?.city),
- "company.country": str(data.company?.countryCode)
+ "company.country": str(data.company?.countryCode),
+ "company.taxId": str(data.company?.taxId),
+ "company.eori": str(data.company?.eori),
+ "company.vatNumber": str(data.company?.vatNumber)
};
}
diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/vars.ts b/packages/documents/src/pdf/blocks/purchaseOrder/vars.ts
index 99d64cae56..bbdee5da97 100644
--- a/packages/documents/src/pdf/blocks/purchaseOrder/vars.ts
+++ b/packages/documents/src/pdf/blocks/purchaseOrder/vars.ts
@@ -22,6 +22,9 @@ export function buildPurchaseOrderVars(
"supplier.country": str(loc?.supplierCountryName),
"company.name": str(data.company?.name),
"company.city": str(data.company?.city),
- "company.country": str(data.company?.countryCode)
+ "company.country": str(data.company?.countryCode),
+ "company.taxId": str(data.company?.taxId),
+ "company.eori": str(data.company?.eori),
+ "company.vatNumber": str(data.company?.vatNumber)
};
}
diff --git a/packages/documents/src/pdf/blocks/quote/vars.ts b/packages/documents/src/pdf/blocks/quote/vars.ts
index 6b104be8c5..29cdf54863 100644
--- a/packages/documents/src/pdf/blocks/quote/vars.ts
+++ b/packages/documents/src/pdf/blocks/quote/vars.ts
@@ -22,6 +22,9 @@ export function buildQuoteVars(
"customer.country": str(c?.customerCountryName),
"company.name": str(data.company?.name),
"company.city": str(data.company?.city),
- "company.country": str(data.company?.countryCode)
+ "company.country": str(data.company?.countryCode),
+ "company.taxId": str(data.company?.taxId),
+ "company.eori": str(data.company?.eori),
+ "company.vatNumber": str(data.company?.vatNumber)
};
}
diff --git a/packages/documents/src/pdf/blocks/salesOrder/vars.ts b/packages/documents/src/pdf/blocks/salesOrder/vars.ts
index 7f1bd6a56f..0fa7a417f5 100644
--- a/packages/documents/src/pdf/blocks/salesOrder/vars.ts
+++ b/packages/documents/src/pdf/blocks/salesOrder/vars.ts
@@ -25,6 +25,9 @@ export function buildSalesOrderVars(
"customer.country": str(loc?.customerCountryName),
"company.name": str(data.company?.name),
"company.city": str(data.company?.city),
- "company.country": str(data.company?.countryCode)
+ "company.country": str(data.company?.countryCode),
+ "company.taxId": str(data.company?.taxId),
+ "company.eori": str(data.company?.eori),
+ "company.vatNumber": str(data.company?.vatNumber)
};
}
diff --git a/packages/documents/src/pdf/blocks/vars.ts b/packages/documents/src/pdf/blocks/vars.ts
index cba39921d4..ce5b2dfc09 100644
--- a/packages/documents/src/pdf/blocks/vars.ts
+++ b/packages/documents/src/pdf/blocks/vars.ts
@@ -31,6 +31,9 @@ export function buildSalesInvoiceVars(
),
"company.name": str(data.company?.name),
"company.city": str(data.company?.city),
- "company.country": str(data.company?.countryCode)
+ "company.country": str(data.company?.countryCode),
+ "company.taxId": str(data.company?.taxId),
+ "company.eori": str(data.company?.eori),
+ "company.vatNumber": str(data.company?.vatNumber)
};
}
diff --git a/packages/documents/src/template/merge.ts b/packages/documents/src/template/merge.ts
index 692c2636e7..5bb6411a58 100644
--- a/packages/documents/src/template/merge.ts
+++ b/packages/documents/src/template/merge.ts
@@ -50,6 +50,20 @@ export function mergeToken(token: string): string {
return `{${token}}`;
}
+/**
+ * Company detail fields shared by the customer/supplier-facing documents
+ * (invoice, order, PO, quote, packing slip). Also the field list offered for
+ * the footer registration number, which is company data by definition.
+ */
+export const COMPANY_MERGE_FIELDS: MergeField[] = [
+ { token: "company.name", label: "Company Name", group: "Company" },
+ { token: "company.city", label: "Company City", group: "Company" },
+ { token: "company.country", label: "Company Country", group: "Company" },
+ { token: "company.taxId", label: "Company Tax ID", group: "Company" },
+ { token: "company.eori", label: "Company EORI", group: "Company" },
+ { token: "company.vatNumber", label: "Company VAT Number", group: "Company" }
+];
+
const SALES_INVOICE_MERGE_FIELDS: MergeField[] = [
{ token: "invoice.number", label: "Invoice Number", group: "Invoice" },
{ token: "invoice.dateIssued", label: "Issue Date", group: "Invoice" },
@@ -64,9 +78,7 @@ const SALES_INVOICE_MERGE_FIELDS: MergeField[] = [
{ token: "customer.addressLine1", label: "Address", group: "Customer" },
{ token: "customer.city", label: "City", group: "Customer" },
{ token: "customer.country", label: "Country", group: "Customer" },
- { token: "company.name", label: "Company Name", group: "Company" },
- { token: "company.city", label: "Company City", group: "Company" },
- { token: "company.country", label: "Company Country", group: "Company" }
+ ...COMPANY_MERGE_FIELDS
];
const SALES_ORDER_MERGE_FIELDS: MergeField[] = [
@@ -82,9 +94,7 @@ const SALES_ORDER_MERGE_FIELDS: MergeField[] = [
{ token: "customer.addressLine1", label: "Address", group: "Customer" },
{ token: "customer.city", label: "City", group: "Customer" },
{ token: "customer.country", label: "Country", group: "Customer" },
- { token: "company.name", label: "Company Name", group: "Company" },
- { token: "company.city", label: "Company City", group: "Company" },
- { token: "company.country", label: "Company Country", group: "Company" }
+ ...COMPANY_MERGE_FIELDS
];
const PURCHASE_ORDER_MERGE_FIELDS: MergeField[] = [
@@ -100,9 +110,7 @@ const PURCHASE_ORDER_MERGE_FIELDS: MergeField[] = [
{ token: "supplier.addressLine1", label: "Address", group: "Supplier" },
{ token: "supplier.city", label: "City", group: "Supplier" },
{ token: "supplier.country", label: "Country", group: "Supplier" },
- { token: "company.name", label: "Company Name", group: "Company" },
- { token: "company.city", label: "Company City", group: "Company" },
- { token: "company.country", label: "Company Country", group: "Company" }
+ ...COMPANY_MERGE_FIELDS
];
const QUOTE_MERGE_FIELDS: MergeField[] = [
@@ -118,9 +126,7 @@ const QUOTE_MERGE_FIELDS: MergeField[] = [
{ token: "customer.addressLine1", label: "Address", group: "Customer" },
{ token: "customer.city", label: "City", group: "Customer" },
{ token: "customer.country", label: "Country", group: "Customer" },
- { token: "company.name", label: "Company Name", group: "Company" },
- { token: "company.city", label: "Company City", group: "Company" },
- { token: "company.country", label: "Company Country", group: "Company" }
+ ...COMPANY_MERGE_FIELDS
];
const PACKING_SLIP_MERGE_FIELDS: MergeField[] = [
@@ -134,9 +140,7 @@ const PACKING_SLIP_MERGE_FIELDS: MergeField[] = [
{ token: "customer.addressLine1", label: "Address", group: "Customer" },
{ token: "customer.city", label: "City", group: "Customer" },
{ token: "customer.country", label: "Country", group: "Customer" },
- { token: "company.name", label: "Company Name", group: "Company" },
- { token: "company.city", label: "Company City", group: "Company" },
- { token: "company.country", label: "Company Country", group: "Company" }
+ ...COMPANY_MERGE_FIELDS
];
const STOCK_TRANSFER_MERGE_FIELDS: MergeField[] = [
diff --git a/packages/documents/src/template/schema.ts b/packages/documents/src/template/schema.ts
index c151d0a9aa..f35172e592 100644
--- a/packages/documents/src/template/schema.ts
+++ b/packages/documents/src/template/schema.ts
@@ -267,11 +267,33 @@ export const documentSectionPlacementSchema = z.enum([
"footer"
]);
+/** Default registration number shown in the footer when none is configured. */
+export const DEFAULT_REGISTRATION_NUMBER = "{company.taxId}";
+
+export const DEFAULT_FOOTER_OPTIONS = {
+ showRegistrationLine: true,
+ registrationNumber: DEFAULT_REGISTRATION_NUMBER
+} as const;
+
+/** Registration-line config carried by a footer section. */
+export const footerOptionsSchema = z.object({
+ /** Show the "{company} is registered in {country}" line. */
+ showRegistrationLine: z.boolean().default(true),
+ /**
+ * Free-text registration number appended as "Company Registration Number
+ * {value}". Supports `{token}` merge fields (e.g. `{company.taxId}`).
+ */
+ registrationNumber: z.string().default(DEFAULT_REGISTRATION_NUMBER)
+});
+
/**
- * Layout config carried by a header section — logo + which company fields show.
- * Global: the header is one shared section reused across every document.
+ * Config carried by a shared section. Header sections store layout (logo +
+ * which company fields show); footer sections store the registration line.
+ * Global: sections are reused across every document, so this config is too.
*/
-export const sectionConfigSchema = headerOptionsSchema.partial();
+export const sectionConfigSchema = headerOptionsSchema
+ .partial()
+ .merge(footerOptionsSchema.partial());
export const documentSectionSchema = z.object({
name: z.string().min(1),
@@ -321,7 +343,7 @@ export const DOCUMENT_FONTS = [
export type DocumentFont = (typeof DOCUMENT_FONTS)[number]["value"];
-/** Document-level settings (font + footer page numbers + registration line). */
+/** Document-level settings (font + footer page numbers). */
export const DEFAULT_DOCUMENT_SETTINGS = {
fontFamily: "Inter",
showPageNumbers: true,
@@ -348,6 +370,11 @@ export const documentSettingsSchema = z.object({
showPageNumbers: z.boolean().default(true),
/** "pageOfTotal" → "Page 1 of 3"; "page" → "Page 1". */
pageNumberFormat: z.enum(["pageOfTotal", "page"]).default("pageOfTotal"),
+ /**
+ * Legacy per-template toggle for the footer registration line. The footer
+ * section's config (`sectionConfigSchema.showRegistrationLine`) takes
+ * precedence when set — edit it via the footer section modal.
+ */
showRegistrationLine: z.boolean().default(true)
});
@@ -364,6 +391,19 @@ export const documentTemplateTypeSchema = z.enum([
"trackingLabel"
]);
+/**
+ * Doc types whose PDFs render the footer registration line (via
+ * `resolveRegistrationLine`). Add a type here when its PDF adopts it — the
+ * footer section modal derives its helper text from this list.
+ */
+export const REGISTRATION_LINE_DOCUMENT_TYPES: DocumentTemplateType[] = [
+ "salesInvoice",
+ "salesOrder",
+ "purchaseOrder",
+ "quote",
+ "packingSlip"
+];
+
/**
* Schema version of the stored template JSON. Bump when the block/theme shape
* changes in a non-additive way; `resolveTemplate` migrates older versions
@@ -395,7 +435,7 @@ export interface ResolvedSection {
name: string;
placement: DocumentSectionPlacement;
content: JSONContent;
- /** Header layout config (logo, which fields show). Header sections only. */
+ /** Header layout (logo, which fields show) or footer registration line. */
config?: SectionConfig;
/** True for code-provided system sections — shown read-only in the library. */
builtIn?: boolean;
@@ -445,6 +485,7 @@ export type SpacerBlock = Extract<DocumentBlock, { type: "spacer" }>;
export type TermsBlock = Extract<DocumentBlock, { type: "terms" }>;
export type HeaderBlock = Extract<DocumentBlock, { type: "header" }>;
export type HeaderOptions = z.infer<typeof headerOptionsSchema>;
+export type FooterOptions = z.infer<typeof footerOptionsSchema>;
export type SectionConfig = z.infer<typeof sectionConfigSchema>;
export type LineItemsBlock = Extract<DocumentBlock, { type: "lineItems" }>;
export type LineItemsOptions = z.infer<typeof lineItemsOptionsSchema>;
diff --git a/packages/documents/src/utils/footer.ts b/packages/documents/src/utils/footer.ts
deleted file mode 100644
index a7037472af..0000000000
--- a/packages/documents/src/utils/footer.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Compose the per-page registration line shown on the left side of the PDF
- * footer (across PO, Quote, Sales Order, Sales Invoice).
- *
- * Format: "{companyName} is registered in {country}, Company Number {eori}".
- * - The "Company Number {eori}" suffix is appended only when an EORI exists.
- * - The "Accounts Receivable: {email}" suffix is appended only when provided
- * (sales PDFs pass this; PO does not).
- *
- * Returns null when the minimum data (name + country) is missing — callers can
- * skip rendering when null.
- */
-export function composeRegistrationLine({
- companyName,
- country,
- eori
-}: {
- companyName: string | null | undefined;
- country: string | null | undefined;
- eori?: string | null;
-}): string | null {
- if (!companyName || !country) return null;
- let line = `${companyName} is registered in ${country}`;
- if (eori) line += `, Company Registration Number ${eori}`;
- return line;
-}
diff --git a/packages/documents/src/utils/shared.ts b/packages/documents/src/utils/shared.ts
index abae7e7aa1..7c6ac5d93e 100644
--- a/packages/documents/src/utils/shared.ts
+++ b/packages/documents/src/utils/shared.ts
@@ -1,3 +1,6 @@
+import type { ResolvedSection } from "../template";
+import { DEFAULT_REGISTRATION_NUMBER, interpolateString } from "../template";
+
const regionNames = new Intl.DisplayNames(["en"], { type: "region" });
export const getCountryName = (
@@ -11,15 +14,64 @@ export const getCountryName = (
}
};
+/**
+ * Compose the per-page registration line shown on the left side of the PDF
+ * footer: "{name} is registered in {country}, Company Registration Number
+ * {registrationNumber}". Callers pass the footer section's free-text
+ * `config.registrationNumber` already resolved through `interpolateString`
+ * (so `{company.taxId}` etc. are filled in); the suffix is dropped when it
+ * resolves empty. The country code is mapped to a display name ("GB" →
+ * "United Kingdom").
+ */
export const getRegistrationFooter = (
name: string | null | undefined,
countryCode: string | null | undefined,
- taxId: string | null | undefined
+ registrationNumber: string | null | undefined
): string | undefined => {
if (!name) return undefined;
const country = getCountryName(countryCode);
const base = country ? `${name} is registered in ${country}` : name;
- return taxId ? `${base}, Company Registration Number ${taxId}` : base;
+ return registrationNumber
+ ? `${base}, Company Registration Number ${registrationNumber}`
+ : base;
+};
+
+/**
+ * Resolve the footer registration line for a document. The shared footer
+ * section's config decides the text and visibility, so every document type
+ * using that footer shares one setting; legacy templates without a configured
+ * footer fall back to the per-template `settings.showRegistrationLine`.
+ */
+export const resolveRegistrationLine = ({
+ company,
+ footerSectionId,
+ sections,
+ settings,
+ vars
+}: {
+ company: {
+ name: string | null | undefined;
+ countryCode: string | null | undefined;
+ };
+ footerSectionId: string | null;
+ sections: Record<string, ResolvedSection>;
+ settings: { showRegistrationLine: boolean };
+ vars: Record<string, string>;
+}): { label: string | undefined; show: boolean } => {
+ const config = footerSectionId
+ ? sections[footerSectionId]?.config
+ : undefined;
+ return {
+ label: getRegistrationFooter(
+ company.name,
+ company.countryCode,
+ interpolateString(
+ config?.registrationNumber ?? DEFAULT_REGISTRATION_NUMBER,
+ vars
+ )
+ ),
+ show: config?.showRegistrationLine ?? settings.showRegistrationLine
+ };
};
export const formatTaxPercent = (