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
feat: document template customiser (#880)
Sid6bbe2b4032bf
diff --git a/.gitignore b/.gitignoreindex 62001e9f1a..38fd74935a 100644--- a/.gitignore+++ b/.gitignore@@ -21,6 +21,7 @@ vite.config.ts.timestamp*.mcp.jsonopencode.json.windsurf+llm/tasks/todo.md# Lingui compiled catalogspackages/locale/locales/**/*.mjsdiff --git a/apps/erp/app/components/ColorPicker.tsx b/apps/erp/app/components/ColorPicker.tsxnew file mode 100644index 0000000000..c081ff83ed--- /dev/null+++ b/apps/erp/app/components/ColorPicker.tsx@@ -0,0 +1,89 @@+import { cn, Popover, PopoverContent, PopoverTrigger } from "@carbon/react";+import { HexColorInput, HexColorPicker } from "react-colorful";++/** Preset swatches shown under the picker, Mantine ColorInput style. */+const SWATCHES = [+ "#1f2937",+ "#111827",+ "#374151",+ "#0f172a",+ "#000000",+ "#ffffff",+ "#1e3a8a",+ "#1d4ed8",+ "#2563eb",+ "#0891b2",+ "#059669",+ "#16a34a",+ "#ca8a04",+ "#ea580c",+ "#dc2626",+ "#db2777",+ "#7c3aed",+ "#475569"+];++export function ColorPicker({+ value,+ onChange+}: {+ value: string;+ onChange: (value: string) => void;+}) {+ return (+ <Popover>+ <PopoverTrigger asChild>+ <button+ type="button"+ className="flex h-9 w-full items-center gap-2 rounded-md border border-input bg-background px-2 text-sm outline-none transition-colors focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"+ >+ <span+ className="size-5 shrink-0 rounded ring-1 ring-inset ring-black/10"+ style={{ backgroundColor: value }}+ />+ <span className="font-mono text-xs uppercase text-foreground">+ {value}+ </span>+ </button>+ </PopoverTrigger>+ <PopoverContent align="start" className="w-[232px] p-3">+ <div className="flex flex-col gap-3">+ <HexColorPicker+ color={value}+ onChange={onChange}+ style={{ width: "100%", height: 150 }}+ />++ <div className="flex items-center gap-2">+ <span+ className="size-5 shrink-0 rounded ring-1 ring-inset ring-black/10"+ style={{ backgroundColor: value }}+ />+ <HexColorInput+ prefixed+ color={value}+ onChange={onChange}+ className="h-8 w-full rounded-md border border-input bg-background px-2 font-mono text-xs uppercase outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50"+ />+ </div>++ <div className="grid grid-cols-9 gap-1.5">+ {SWATCHES.map((swatch) => (+ <button+ key={swatch}+ type="button"+ aria-label={swatch}+ onClick={() => onChange(swatch)}+ className={cn(+ "size-5 rounded ring-1 ring-inset ring-black/10 transition-transform hover:scale-110",+ value.toLowerCase() === swatch && "ring-2 ring-primary"+ )}+ style={{ backgroundColor: swatch }}+ />+ ))}+ </div>+ </div>+ </PopoverContent>+ </Popover>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx b/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsxnew file mode 100644index 0000000000..89576dca78--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/BlockConfig.tsx@@ -0,0 +1,691 @@+import type {+ CustomFieldBlock,+ DocumentBlockType,+ KeyValueBlock,+ LineItemsBlock,+ OperationsBlock,+ RichTextBlock,+ SpacerBlock,+ SummaryBlock,+ TermsBlock,+ WatermarkBlock+} from "@carbon/documents/template";+import {+ BLOCK_META,+ BUILT_IN_SECTION_IDS,+ DEFAULT_LINE_ITEMS_OPTIONS,+ DEFAULT_SUMMARY_OPTIONS,+ getMergeFields+} from "@carbon/documents/template";+import type { JSONContent } from "@carbon/react";+import {+ Badge,+ Button,+ IconButton,+ Input,+ Label,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@carbon/react";+import { Editor } from "@carbon/react/Editor";+import { useState } from "react";+import {+ LuExternalLink,+ LuPencil,+ LuPlus,+ LuSlidersHorizontal,+ LuTrash2+} from "react-icons/lu";+import { Link } from "react-router";+import { path } from "~/utils/path";+import { ToggleRow } from "./configHelpers";+import { FOOTER_BLOCK_ID, useDocumentTemplate } from "./context";+import {+ FieldConfig,+ HeaderLogoConfig,+ LabelBarcodeConfig,+ LabelEntityIdConfig,+ LabelFieldNameConfig,+ LabelLogoConfig+} from "./labelConfigs";+import { MergeFieldMenu } from "./MergeFieldMenu";+import { NumberRow } from "./NumberRow";+import { SectionFormModal } from "./SectionFormModal";+import { HEADER_LOGO_ID } from "./useHeaderConfig";++/** Append a `{{token}}` snippet to the end of a tiptap doc (inline if possible). */+function appendText(content: JSONContent, text: string): JSONContent {+ const doc =+ content && content.type === "doc"+ ? content+ : ({ type: "doc", content: [] } as JSONContent);+ const nodes = Array.isArray(doc.content) ? [...doc.content] : [];+ const last = nodes[nodes.length - 1];+ if (last && last.type === "paragraph") {+ const inline = Array.isArray(last.content) ? [...last.content] : [];+ inline.push({ type: "text", text: inline.length ? ` ${text}` : text });+ nodes[nodes.length - 1] = { ...last, content: inline };+ } else {+ nodes.push({ type: "paragraph", content: [{ type: "text", text }] });+ }+ return { ...doc, type: "doc", content: nodes };+}++export function BlockConfig() {+ const { blocks, sections, selectedId } = useDocumentTemplate();++ if (selectedId === HEADER_LOGO_ID) {+ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-sm font-medium">Logo</h3>+ <TypeBadge category="page" />+ </div>+ <p className="text-xs text-muted-foreground">+ Shown in the header of every document.+ </p>+ </div>+ <HeaderLogoConfig />+ </div>+ );+ }++ if (selectedId === FOOTER_BLOCK_ID) {+ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-sm font-medium">Footer</h3>+ <TypeBadge category="page" />+ </div>+ <p className="text-xs text-muted-foreground">+ Shown at the bottom of every page.+ </p>+ </div>+ <ChromeConfig kind="footer" />+ </div>+ );+ }++ const block = blocks.find((b) => b.id === selectedId);++ if (!block) {+ return (+ <div className="flex flex-col items-center gap-2 rounded-md border border-dashed px-4 py-8 text-center">+ <LuSlidersHorizontal className="size-5 text-muted-foreground/60" />+ <p className="text-sm text-muted-foreground">+ Select a block to configure it+ </p>+ </div>+ );+ }++ const meta = BLOCK_META[block.type];+ const sharedName =+ block.type === "shared"+ ? (sections.find((s) => s.id === block.sectionId)?.name ?? null)+ : null;+ // Built-in blocks that now expose real options shouldn't show the generic+ // "reorder / toggle" placeholder.+ const hasOwnConfig =+ block.type === "watermark" ||+ block.type === "header" ||+ block.type === "lineItems" ||+ block.type === "summary" ||+ block.type === "terms" ||+ block.type === "labelRevision" ||+ block.type === "labelQuantity" ||+ block.type === "labelTracking" ||+ block.type === "labelBarcode" ||+ block.type === "labelLogo" ||+ block.type === "labelEntityId" ||+ block.type === "operations";++ return (+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-sm font-medium">+ {block.type === "shared"+ ? (sharedName ?? "Shared Section")+ : meta.label}+ </h3>+ <TypeBadge category={categoryOf(block.type)} />+ </div>+ {meta.isBuiltIn && !hasOwnConfig && (+ <p className="text-xs text-muted-foreground">+ Reorder or show/hide it from the list.+ </p>+ )}+ </div>++ {block.type === "header" && <ChromeConfig kind="header" />}+ {block.type === "watermark" && <WatermarkConfig block={block} />}+ {block.type === "lineItems" && <LineItemsConfig block={block} />}+ {block.type === "operations" && <OperationsConfig block={block} />}+ {block.type === "summary" && <SummaryConfig block={block} />}+ {block.type === "terms" && <TermsConfig block={block} />}+ {(block.type === "labelRevision" ||+ block.type === "labelQuantity" ||+ block.type === "labelTracking") && (+ <LabelFieldNameConfig block={block} />+ )}+ {block.type === "richText" && <RichTextConfig block={block} />}+ {block.type === "keyValue" && <KeyValueConfig block={block} />}+ {block.type === "spacer" && <SpacerConfig block={block} />}+ {block.type === "field" && <FieldConfig block={block} />}+ {block.type === "labelBarcode" && <LabelBarcodeConfig block={block} />}+ {block.type === "labelLogo" && <LabelLogoConfig block={block} />}+ {block.type === "labelEntityId" && <LabelEntityIdConfig block={block} />}+ {block.type === "customField" && <CustomFieldConfig block={block} />}+ {block.type === "shared" && (+ <div className="flex flex-col gap-2">+ <p className="text-xs text-muted-foreground">+ {sharedName+ ? "Linked to a shared section. Edit it in the library to update it everywhere."+ : "This shared section no longer exists. Remove the block or recreate the section."}+ </p>+ <Link+ to={path.to.documentSections}+ className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"+ >+ <LuExternalLink className="size-3" />+ Manage shared sections+ </Link>+ </div>+ )}+ </div>+ );+}++type BlockCategory = "page" | "built-in" | "custom" | "shared";++const CATEGORY_LABEL: Record<BlockCategory, string> = {+ page: "Page",+ "built-in": "Built-in",+ custom: "Custom",+ shared: "Shared"+};++function categoryOf(type: DocumentBlockType): BlockCategory {+ if (type === "header") return "page";+ if (type === "shared") return "shared";+ if (+ type === "richText" ||+ type === "keyValue" ||+ type === "spacer" ||+ type === "field" ||+ type === "customField"+ ) {+ return "custom";+ }+ return "built-in";+}++function TypeBadge({ category }: { category: BlockCategory }) {+ return <Badge variant="secondary">{CATEGORY_LABEL[category]}</Badge>;+}++/**+ * 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.+ */+function ChromeConfig({ kind }: { kind: "header" | "footer" }) {+ const { sections } = useDocumentTemplate();+ const [open, setOpen] = useState(false);+ const targetId =+ kind === "header"+ ? BUILT_IN_SECTION_IDS.header+ : BUILT_IN_SECTION_IDS.footer;+ const section = sections.find((s) => s.id === targetId);++ return (+ <div className="flex flex-col gap-3">+ <p className="text-xs text-muted-foreground">+ {kind === "header"+ ? "The header is shared by every document — same logo, fields, and banner everywhere."+ : "The footer is shared by every document."}+ </p>+ <Button+ variant="secondary"+ leftIcon={<LuPencil />}+ onClick={() => setOpen(true)}+ isDisabled={!section}+ >+ Edit {kind} section+ </Button>++ {kind === "footer" && <FooterSettings />}++ <Link+ to={path.to.documentSections}+ className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground"+ >+ <LuExternalLink className="size-3" />+ Open section library+ </Link>++ {open && section && (+ <SectionFormModal+ action={path.to.documentSections}+ onClose={() => setOpen(false)}+ section={{+ id: section.id,+ name: section.name,+ placement: section.placement,+ content: section.content ?? { type: "doc", content: [] },+ config: section.config+ }}+ />+ )}+ </div>+ );+}++/** Footer page-number + registration-line settings. */+function FooterSettings() {+ const { footerSectionId, settings, setSetting } = useDocumentTemplate();+ const hidden = footerSectionId === null;+ const pageNumbersValue = settings.showPageNumbers+ ? settings.pageNumberFormat+ : "none";++ return (+ <div className="flex flex-col gap-3 border-t pt-3">+ {hidden && (+ <p className="text-xs text-muted-foreground">+ Footer is hidden — turn it on with the eye toggle to apply these.+ </p>+ )}+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm">Page numbers</span>+ <Select+ disabled={hidden}+ value={pageNumbersValue}+ onValueChange={(v) => {+ if (v === "none") {+ setSetting("showPageNumbers", false);+ } else {+ setSetting("showPageNumbers", true);+ setSetting(+ "pageNumberFormat",+ v as typeof settings.pageNumberFormat+ );+ }+ }}+ >+ <SelectTrigger className="h-7 w-32">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="none">None</SelectItem>+ <SelectItem value="pageOfTotal">Page 1 of 3</SelectItem>+ <SelectItem value="page">Page 1</SelectItem>+ </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>+ );+}++function CustomFieldConfig({ block }: { block: CustomFieldBlock }) {+ const { updateBlock, customFields } = useDocumentTemplate();+ const field = customFields.find((f) => f.id === block.fieldId);++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="cf-label">Label</Label>+ <Input+ id="cf-label"+ value={block.label}+ placeholder={field?.name ?? ""}+ onChange={(e) => updateBlock(block.id, { label: e.target.value })}+ />+ </div>+ <p className="text-xs text-muted-foreground">+ {field+ ? `Value comes from the “${field.name}” custom field.`+ : "This custom field no longer exists. Remove the block."}+ </p>+ </div>+ );+}++function SummaryConfig({ block }: { block: SummaryBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const opts = { ...DEFAULT_SUMMARY_OPTIONS, ...block.options };++ return (+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="tax-label">Tax label</Label>+ <Input+ id="tax-label"+ value={opts.taxLabel}+ placeholder="Taxes"+ onChange={(e) =>+ updateBlock(block.id, {+ options: { ...opts, taxLabel: e.target.value }+ })+ }+ />+ <p className="text-xs text-muted-foreground">+ Shown on the tax row, e.g. "VAT 15%".+ </p>+ </div>+ );+}++function WatermarkConfig({ block }: { block: WatermarkBlock }) {+ const { updateBlock, hasWatermark } = useDocumentTemplate();+ return (+ <div className="flex flex-col gap-3">+ <NumberRow+ label="Opacity (%)"+ minValue={1}+ maxValue={100}+ value={Math.round((block.opacity ?? 0.07) * 100)}+ onChange={(v) => updateBlock(block.id, { opacity: v / 100 })}+ />+ <NumberRow+ label="Size (% of width)"+ minValue={10}+ maxValue={100}+ value={block.size ?? 50}+ onChange={(v) => updateBlock(block.id, { size: v })}+ />+ <div className="flex flex-col gap-1.5">+ <Label>Placement</Label>+ <Select+ value={block.placement ?? "center"}+ onValueChange={(v) =>+ updateBlock(block.id, {+ placement: v as WatermarkBlock["placement"]+ })+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="top">Top</SelectItem>+ <SelectItem value="center">Center</SelectItem>+ <SelectItem value="bottom">Bottom</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <p className="text-xs text-muted-foreground">+ {hasWatermark+ ? "Your watermark logo (set in Logos), faint behind the document."+ : "Upload a watermark logo in Logos to see it."}+ </p>+ </div>+ );+}++function OperationsConfig({ block }: { block: OperationsBlock }) {+ const { updateBlock } = useDocumentTemplate();+ return (+ <ToggleRow+ label="Show work instructions"+ checked={block.showWorkInstructions ?? false}+ onChange={(v) => updateBlock(block.id, { showWorkInstructions: v })}+ />+ );+}++function LineItemsConfig({ block }: { block: LineItemsBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };+ const set = <K extends keyof typeof opts>(key: K, value: (typeof opts)[K]) =>+ updateBlock(block.id, { options: { ...opts, [key]: value } });++ return (+ <div className="flex flex-col gap-3">+ <ToggleRow+ label="Show thumbnails"+ checked={opts.showThumbnails}+ onChange={(v) => set("showThumbnails", v)}+ />+ <ToggleRow+ label="Striped rows"+ checked={opts.zebra}+ onChange={(v) => set("zebra", v)}+ />+ <div className="flex flex-col gap-1.5">+ <Label>Item text</Label>+ <Select+ value={opts.textOverflow}+ onValueChange={(v) =>+ set("textOverflow", v as typeof opts.textOverflow)+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="wrap">Wrap to new lines</SelectItem>+ <SelectItem value="truncate">Truncate to one line</SelectItem>+ </SelectContent>+ </Select>+ </div>+ </div>+ );+}++function RichTextConfig({ block }: { block: RichTextBlock }) {+ const { updateBlock, documentType } = useDocumentTemplate();+ // Bumped on insert to remount the Editor so the appended token shows (Tiptap+ // only reads `initialValue` on mount).+ const [nonce, setNonce] = useState(0);+ const knownTokens = getMergeFields(documentType).map((f) => f.token);++ const insertField = (snippet: string) => {+ updateBlock(block.id, { content: appendText(block.content, snippet) });+ setNonce((n) => n + 1);+ };++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="rt-title">Heading (optional)</Label>+ <Input+ id="rt-title"+ value={block.title ?? ""}+ onChange={(e) => updateBlock(block.id, { title: e.target.value })}+ />+ </div>+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <Label>Content</Label>+ <MergeFieldMenu onInsert={insertField} label="Insert field" />+ </div>+ <Editor+ key={`${block.id}-${nonce}`}+ className="min-h-[140px] w-full rounded-md border bg-background p-3"+ initialValue={block.content}+ onChange={(content) => updateBlock(block.id, { content })}+ highlightTokens={knownTokens}+ disableFileUpload+ />+ </div>+ </div>+ );+}++function hasDocContent(content?: JSONContent | null): boolean {+ return Boolean(+ content && Array.isArray(content.content) && content.content.length > 0+ );+}++/**+ * Per-document Terms & Conditions. The block stores its own content; when left+ * empty it falls back to the company terms setting at render. The editor seeds+ * the field with that setting (`termsSeed`) so the current value is the starting+ * point.+ */+function TermsConfig({ block }: { block: TermsBlock }) {+ const { updateBlock, termsSeed, documentType } = useDocumentTemplate();+ const [nonce, setNonce] = useState(0);+ const knownTokens = getMergeFields(documentType).map((f) => f.token);++ const initialValue: JSONContent = (hasDocContent(block.content)+ ? block.content+ : termsSeed) ?? {+ type: "doc",+ content: []+ };++ const insertField = (snippet: string) => {+ updateBlock(block.id, { content: appendText(initialValue, snippet) });+ setNonce((n) => n + 1);+ };++ return (+ <div className="flex flex-col gap-3">+ <p className="text-xs text-muted-foreground">+ Starts from your company's default terms. Edits apply to this document+ only.+ </p>+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <Label>Content</Label>+ <MergeFieldMenu onInsert={insertField} label="Insert field" />+ </div>+ <Editor+ key={`${block.id}-${nonce}`}+ className="min-h-[160px] w-full rounded-md border bg-background p-3"+ initialValue={initialValue}+ onChange={(content) => updateBlock(block.id, { content })}+ highlightTokens={knownTokens}+ disableFileUpload+ />+ </div>+ </div>+ );+}++function KeyValueConfig({ block }: { block: KeyValueBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const rows = block.rows ?? [];++ const setRows = (next: KeyValueBlock["rows"]) =>+ updateBlock(block.id, { rows: next });++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="kv-title">Heading (optional)</Label>+ <Input+ id="kv-title"+ value={block.title ?? ""}+ onChange={(e) => updateBlock(block.id, { title: e.target.value })}+ />+ </div>++ <div className="flex flex-col gap-2">+ {rows.map((row, index) => (+ <div key={index} className="flex items-center gap-2">+ <Input+ placeholder="Label"+ value={row.label}+ onChange={(e) =>+ setRows(+ rows.map((r, i) =>+ i === index ? { ...r, label: e.target.value } : r+ )+ )+ }+ />+ <Input+ placeholder="Value"+ value={row.value}+ onChange={(e) =>+ setRows(+ rows.map((r, i) =>+ i === index ? { ...r, value: e.target.value } : r+ )+ )+ }+ />+ <MergeFieldMenu+ label=""+ onInsert={(snippet) =>+ setRows(+ rows.map((r, i) =>+ i === index ? { ...r, value: r.value + snippet } : r+ )+ )+ }+ />+ <IconButton+ size="sm"+ variant="ghost"+ aria-label="Remove row"+ icon={<LuTrash2 />}+ onClick={() => setRows(rows.filter((_, i) => i !== index))}+ />+ </div>+ ))}+ <Button+ variant="secondary"+ leftIcon={<LuPlus />}+ onClick={() => setRows([...rows, { label: "", value: "" }])}+ >+ Add row+ </Button>+ </div>+ </div>+ );+}++function SpacerConfig({ block }: { block: SpacerBlock }) {+ const { updateBlock } = useDocumentTemplate();+ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label>Style</Label>+ <Select+ value={block.variant}+ onValueChange={(variant) =>+ updateBlock(block.id, {+ variant: variant as SpacerBlock["variant"]+ })+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="space">Empty space</SelectItem>+ <SelectItem value="divider">Divider line</SelectItem>+ <SelectItem value="pageBreak">Page break</SelectItem>+ </SelectContent>+ </Select>+ </div>++ {block.variant === "space" && (+ <NumberRow+ label="Height (pt)"+ minValue={0}+ maxValue={200}+ value={block.size ?? 16}+ onChange={(v) => updateBlock(block.id, { size: v })}+ />+ )}+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx b/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsxnew file mode 100644index 0000000000..b80ba14550--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx@@ -0,0 +1,676 @@+import type { DocumentBlockType } from "@carbon/documents/template";+import {+ BLOCK_META,+ BUILT_IN_SECTION_IDS,+ extensionSupport+} from "@carbon/documents/template";+import {+ Button,+ cn,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from "@carbon/react";+import {+ closestCenter,+ DndContext,+ type DragEndEvent,+ KeyboardSensor,+ PointerSensor,+ useSensor,+ useSensors+} from "@dnd-kit/core";+import {+ SortableContext,+ useSortable,+ verticalListSortingStrategy+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import { Fragment, type ReactNode } from "react";+import {+ LuEye,+ LuEyeOff,+ LuFileText,+ LuGripVertical,+ LuHash,+ LuImage,+ LuInfo,+ LuLibrary,+ LuLock,+ LuPanelBottom,+ LuPanelTop,+ LuPlus,+ LuQrCode,+ LuReceipt,+ LuSeparatorHorizontal,+ LuStamp,+ LuStickyNote,+ LuTable,+ LuTag,+ LuTrash2,+ LuType,+ LuUsers+} from "react-icons/lu";+import { Link } from "react-router";+import { path } from "~/utils/path";+import {+ type AddableBlockType,+ FOOTER_BLOCK_ID,+ useDocumentTemplate+} from "./context";+import { HEADER_LOGO_ID, useHeaderConfig } from "./useHeaderConfig";++const ADD_OPTIONS: {+ type: AddableBlockType;+ icon: ReactNode;+ description: string;+}[] = [+ {+ type: "richText",+ icon: <LuType className="size-4" />,+ description: "Formatted text with merge fields"+ },+ {+ type: "keyValue",+ icon: <LuTable className="size-4" />,+ description: "Label / value rows"+ },+ {+ type: "spacer",+ icon: <LuSeparatorHorizontal className="size-4" />,+ description: "Space, divider, or page break"+ }+];++/** A consistent leading icon per block type, so every row reads the same. */+const BLOCK_ICON: Partial<Record<DocumentBlockType, ReactNode>> = {+ header: <LuPanelTop className="size-4" />,+ watermark: <LuStamp className="size-4" />,+ parties: <LuUsers className="size-4" />,+ details: <LuInfo className="size-4" />,+ lineItems: <LuTable className="size-4" />,+ summary: <LuReceipt className="size-4" />,+ terms: <LuFileText className="size-4" />,+ notes: <LuStickyNote className="size-4" />,+ richText: <LuType className="size-4" />,+ keyValue: <LuTable className="size-4" />,+ spacer: <LuSeparatorHorizontal className="size-4" />,+ shared: <LuLibrary className="size-4" />,+ field: <LuType className="size-4" />,+ customField: <LuTag className="size-4" />,+ labelLogo: <LuImage className="size-4" />,+ labelBarcode: <LuQrCode className="size-4" />,+ labelEntityId: <LuHash className="size-4" />+};++function blockIcon(type: DocumentBlockType): ReactNode {+ return BLOCK_ICON[type] ?? <LuType className="size-4" />;+}++export function BlockList() {+ const {+ documentType,+ blocks,+ reorder,+ addBlock,+ addSharedBlock,+ addCustomFieldBlock,+ addField,+ sections,+ customFields+ } = useDocumentTemplate();+ // "text" docs (labels) only allow single-line fields, so every block also+ // renders as one ZPL `^FD` line — no rich text, key-value lists, spacers, or+ // shared sections.+ const isTextOnly = extensionSupport(documentType) === "text";+ const bodySections = sections.filter((s) => s.placement === "body");+ // Header & footer are page chrome — pinned (not reorderable). Only the body+ // blocks between them are sortable.+ const headerBlock = blocks.find((b) => b.type === "header");+ const bodyBlocks = blocks.filter((b) => b.type !== "header");+ // The Summary (totals) belongs to the Line Items table, so it's shown nested+ // under it in the tree rather than as a separate sortable row. Only nest when+ // a Line Items block is actually present.+ const hasLineItems = bodyBlocks.some((b) => b.type === "lineItems");+ const summaryBlock = hasLineItems+ ? bodyBlocks.find((b) => b.type === "summary")+ : undefined;+ const sortableBlocks = summaryBlock+ ? bodyBlocks.filter((b) => b.id !== summaryBlock.id)+ : bodyBlocks;+ const sensors = useSensors(+ useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),+ useSensor(KeyboardSensor)+ );++ const handleDragEnd = (event: DragEndEvent) => {+ const { active, over } = event;+ if (over && active.id !== over.id) {+ reorder(String(active.id), String(over.id));+ }+ };++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1">+ {headerBlock && <HeaderRow id={headerBlock.id} />}+ {headerBlock && <HeaderLogoRow />}+ </div>+ <DndContext+ sensors={sensors}+ collisionDetection={closestCenter}+ onDragEnd={handleDragEnd}+ >+ <SortableContext+ items={sortableBlocks.map((b) => b.id)}+ strategy={verticalListSortingStrategy}+ >+ <div className="flex flex-col gap-1">+ {sortableBlocks.map((block) => (+ <Fragment key={block.id}>+ <BlockRow id={block.id} />+ {block.type === "lineItems" && summaryBlock && (+ <NestedBlockRow id={summaryBlock.id} />+ )}+ </Fragment>+ ))}+ <FooterRow />+ </div>+ </SortableContext>+ </DndContext>++ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="secondary"+ leftIcon={<LuPlus />}+ className="w-full border-dashed"+ >+ Add block+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ align="start"+ className="w-[--radix-popper-anchor-width] min-w-64"+ >+ {isTextOnly ? (+ <AddMenuItem+ icon={<LuType className="size-4" />}+ title="Text field"+ description="A label and a value"+ onClick={() => addField(true)}+ />+ ) : (+ <>+ <AddMenuItem+ icon={<LuType className="size-4" />}+ title="Text field"+ description="A label and a value"+ onClick={() => addField(true)}+ />+ {ADD_OPTIONS.map(({ type, icon, description }) => (+ <AddMenuItem+ key={type}+ icon={icon}+ title={BLOCK_META[type].label}+ description={description}+ onClick={() => addBlock(type)}+ />+ ))}+ </>+ )}+ {!isTextOnly && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuLabel>Shared sections</DropdownMenuLabel>+ {bodySections.map((section) => (+ <DropdownMenuItem+ key={section.id}+ onClick={() => addSharedBlock(section.id)}+ className="flex items-center gap-2.5"+ >+ <LuLibrary className="size-4 text-muted-foreground" />+ <span className="text-sm">{section.name}</span>+ </DropdownMenuItem>+ ))}+ <DropdownMenuItem asChild className="flex items-center gap-2.5">+ <Link to={path.to.documentSections}>+ <LuPlus className="size-4 text-muted-foreground" />+ <span className="text-sm">+ {bodySections.length > 0+ ? "New shared section"+ : "Create a shared section"}+ </span>+ </Link>+ </DropdownMenuItem>+ </>+ )}++ <DropdownMenuSeparator />+ <DropdownMenuLabel>Custom fields</DropdownMenuLabel>+ {customFields.map((field) => (+ <DropdownMenuItem+ key={field.id}+ onClick={() => addCustomFieldBlock(field.id, field.name)}+ className="flex items-center gap-2.5"+ >+ <LuTag className="size-4 text-muted-foreground" />+ <span className="text-sm">{field.name}</span>+ </DropdownMenuItem>+ ))}+ <DropdownMenuItem asChild className="flex items-center gap-2.5">+ <Link to={path.to.customFields}>+ <LuPlus className="size-4 text-muted-foreground" />+ <span className="text-sm">+ {customFields.length > 0+ ? "Manage custom fields"+ : "Create a custom field"}+ </span>+ </Link>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ );+}++function AddMenuItem({+ icon,+ title,+ description,+ onClick+}: {+ icon: ReactNode;+ title: string;+ description: string;+ onClick: () => void;+}) {+ return (+ <DropdownMenuItem+ onClick={onClick}+ className="flex items-start gap-2.5 py-2"+ >+ <span className="mt-0.5 text-muted-foreground">{icon}</span>+ <span className="flex flex-col">+ <span className="text-sm font-medium">{title}</span>+ <span className="text-xs text-muted-foreground">{description}</span>+ </span>+ </DropdownMenuItem>+ );+}++function BlockRow({ id }: { id: string }) {+ const { blocks, sections, selectedId, select, toggleVisible, removeBlock } =+ useDocumentTemplate();+ const block = blocks.find((b) => b.id === id);+ const {+ attributes,+ listeners,+ setNodeRef,+ transform,+ transition,+ isDragging+ } = useSortable({ id });++ if (!block) return null;+ const meta = BLOCK_META[block.type];+ const isSelected = selectedId === id;+ const shown = block.visible;+ const onToggle = () => toggleVisible(id);+ const label =+ block.type === "shared"+ ? (sections.find((s) => s.id === block.sectionId)?.name ??+ "Shared Section (deleted)")+ : block.type === "customField"+ ? block.label || meta.label+ : block.type === "field"+ ? block.label || block.value || meta.label+ : meta.label;++ return (+ <div+ ref={setNodeRef}+ style={{+ transform: CSS.Translate.toString(transform),+ transition: transition ?? undefined+ }}+ onClick={() => select(isSelected ? null : id)}+ className={cn(+ "group flex cursor-pointer items-center gap-1.5 rounded-md border px-1.5 py-2",+ "transition-colors duration-150",+ isSelected+ ? "border-primary bg-accent/50"+ : "border-transparent hover:border-border hover:bg-accent/30",+ isDragging && "opacity-50 shadow-sm",+ !shown && !isSelected && "opacity-60"+ )}+ >+ <button+ type="button"+ aria-label="Drag to reorder"+ onClick={(e) => e.stopPropagation()}+ className="relative cursor-grab text-muted-foreground/60 active:cursor-grabbing"+ {...attributes}+ {...listeners}+ >+ {/* Type icon normally; grip on hover to signal draggability. */}+ <span className="group-hover:opacity-0">{blockIcon(block.type)}</span>+ <span className="absolute inset-0 opacity-0 group-hover:opacity-100">+ <LuGripVertical className="size-4" />+ </span>+ </button>++ <span className="flex flex-1 items-center gap-2 truncate text-sm">+ <span className="truncate">{label}</span>+ {block.type === "shared" ? (+ <span className="rounded bg-muted px-1.5 py-px text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ Shared+ </span>+ ) : (+ !meta.isBuiltIn && (+ <span className="rounded bg-muted px-1.5 py-px text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ Custom+ </span>+ )+ )}+ </span>++ {meta.removable && (+ <button+ type="button"+ aria-label="Remove block"+ onClick={(e) => {+ e.stopPropagation();+ removeBlock(id);+ }}+ className="rounded p-1 text-muted-foreground opacity-0 transition-[opacity,color] hover:text-destructive group-hover:opacity-100"+ >+ <LuTrash2 className="size-4" />+ </button>+ )}++ {meta.hideable ? (+ <button+ type="button"+ aria-label={shown ? "Hide block" : "Show block"}+ aria-pressed={shown}+ onClick={(e) => {+ e.stopPropagation();+ onToggle();+ }}+ className={cn(+ "rounded p-1 transition-colors",+ shown+ ? "text-foreground hover:bg-muted"+ : "text-muted-foreground hover:bg-muted"+ )}+ >+ {shown ? (+ <LuEye className="size-4" />+ ) : (+ <LuEyeOff className="size-4" />+ )}+ </button>+ ) : (+ <span+ title="Required — always shown"+ className="p-1 text-muted-foreground/50"+ >+ <LuLock className="size-3.5" />+ </span>+ )}+ </div>+ );+}++/**+ * A non-draggable, indented block row — used for blocks shown nested under a+ * parent (e.g. Summary under Line Items). Same selection / visibility / remove+ * behavior as `BlockRow`, just without the drag handle.+ */+function NestedBlockRow({ id }: { id: string }) {+ const { blocks, sections, selectedId, select, toggleVisible, removeBlock } =+ useDocumentTemplate();+ const block = blocks.find((b) => b.id === id);+ if (!block) return null;+ const meta = BLOCK_META[block.type];+ const isSelected = selectedId === id;+ const shown = block.visible;+ const label =+ block.type === "shared"+ ? (sections.find((s) => s.id === block.sectionId)?.name ??+ "Shared Section (deleted)")+ : block.type === "customField"+ ? block.label || meta.label+ : block.type === "field"+ ? block.label || block.value || meta.label+ : meta.label;++ return (+ <div className="ml-3 border-l border-border/60 pl-2">+ <div+ onClick={() => select(isSelected ? null : id)}+ className={cn(+ "group flex cursor-pointer items-center gap-1.5 rounded-md border px-1.5 py-2",+ "transition-colors duration-150",+ isSelected+ ? "border-primary bg-accent/50"+ : "border-transparent hover:border-border hover:bg-accent/30",+ !shown && !isSelected && "opacity-60"+ )}+ >+ <span className="p-1 text-muted-foreground/60">+ {blockIcon(block.type)}+ </span>+ <span className="flex-1 truncate text-sm">{label}</span>+ {meta.removable && (+ <button+ type="button"+ aria-label="Remove block"+ onClick={(e) => {+ e.stopPropagation();+ removeBlock(id);+ }}+ className="rounded p-1 text-muted-foreground opacity-0 transition-[opacity,color] hover:text-destructive group-hover:opacity-100"+ >+ <LuTrash2 className="size-4" />+ </button>+ )}+ {meta.hideable ? (+ <button+ type="button"+ aria-label={shown ? "Hide block" : "Show block"}+ aria-pressed={shown}+ onClick={(e) => {+ e.stopPropagation();+ toggleVisible(id);+ }}+ className={cn(+ "rounded p-1 transition-colors",+ shown+ ? "text-foreground hover:bg-muted"+ : "text-muted-foreground hover:bg-muted"+ )}+ >+ {shown ? (+ <LuEye className="size-4" />+ ) : (+ <LuEyeOff className="size-4" />+ )}+ </button>+ ) : (+ <span+ title="Required — always shown"+ className="p-1 text-muted-foreground/50"+ >+ <LuLock className="size-3.5" />+ </span>+ )}+ </div>+ </div>+ );+}++/**+ * The page Header — pinned (not reorderable). Eye toggles it on/off; selecting+ * it opens the header config (a link to its global shared section).+ */+function HeaderRow({ id }: { id: string }) {+ const { selectedId, select, headerSectionId, setHeaderSection } =+ useDocumentTemplate();+ const isSelected = selectedId === id;+ const shown = headerSectionId !== null;++ return (+ <ChromeRow+ icon={<LuPanelTop className="size-4" />}+ label="Header"+ isSelected={isSelected}+ shown={shown}+ onSelect={() => select(isSelected ? null : id)}+ onToggle={() =>+ setHeaderSection(shown ? null : BUILT_IN_SECTION_IDS.header)+ }+ />+ );+}++/**+ * The Logo — a child of the Header, shown indented in the tree so it can be+ * configured inline (variant, crop, height) instead of via the header dialog.+ * Only rendered while the header is shown. Eye toggles `showLogo`.+ */+function HeaderLogoRow() {+ const { selectedId, select, headerSectionId } = useDocumentTemplate();+ const { section, config, patch } = useHeaderConfig();+ // Hide the node when the header is off or its section isn't available.+ if (!section || headerSectionId === null) return null;+ const isSelected = selectedId === HEADER_LOGO_ID;+ const shown = config.showLogo;++ return (+ <div className="ml-3 border-l border-border/60 pl-2">+ <div+ onClick={() => select(isSelected ? null : HEADER_LOGO_ID)}+ className={cn(+ "group flex cursor-pointer items-center gap-1.5 rounded-md border px-1.5 py-2",+ "transition-colors duration-150",+ isSelected+ ? "border-primary bg-accent/50"+ : "border-transparent hover:border-border hover:bg-accent/30",+ !shown && !isSelected && "opacity-60"+ )}+ >+ <span className="p-1 text-muted-foreground/40">+ <LuImage className="size-4" />+ </span>+ <span className="flex-1 truncate text-sm">Logo</span>+ <button+ type="button"+ aria-label={shown ? "Hide logo" : "Show logo"}+ aria-pressed={shown}+ onClick={(e) => {+ e.stopPropagation();+ patch({ showLogo: !shown });+ }}+ className={cn(+ "rounded p-1 transition-colors",+ shown+ ? "text-foreground hover:bg-muted"+ : "text-muted-foreground hover:bg-muted"+ )}+ >+ {shown ? (+ <LuEye className="size-4" />+ ) : (+ <LuEyeOff className="size-4" />+ )}+ </button>+ </div>+ </div>+ );+}++/**+ * The page Footer — chrome, not a flow block, so it's a static row pinned below+ * the sortable blocks. Eye toggles the footer on/off; selecting it opens the+ * footer config (page numbers, registration line).+ */+function FooterRow() {+ const { footerSectionId, setFooterSection, selectedId, select } =+ useDocumentTemplate();+ const isSelected = selectedId === FOOTER_BLOCK_ID;+ const shown = footerSectionId !== null;++ return (+ <ChromeRow+ icon={<LuPanelBottom className="size-4" />}+ label="Footer"+ isSelected={isSelected}+ shown={shown}+ onSelect={() => select(isSelected ? null : FOOTER_BLOCK_ID)}+ onToggle={() =>+ setFooterSection(shown ? null : BUILT_IN_SECTION_IDS.footer)+ }+ />+ );+}++/** Shared presentation for the pinned, non-draggable Header & Footer rows. */+function ChromeRow({+ icon,+ label,+ isSelected,+ shown,+ onSelect,+ onToggle+}: {+ icon: ReactNode;+ label: string;+ isSelected: boolean;+ shown: boolean;+ onSelect: () => void;+ onToggle: () => void;+}) {+ return (+ <div+ onClick={onSelect}+ className={cn(+ "group flex cursor-pointer items-center gap-1.5 rounded-md border px-1.5 py-2",+ "transition-colors duration-150",+ isSelected+ ? "border-primary bg-accent/50"+ : "border-transparent hover:border-border hover:bg-accent/30",+ !shown && !isSelected && "opacity-60"+ )}+ >+ <span className="p-1 text-muted-foreground/40">{icon}</span>+ <span className="flex flex-1 items-center gap-2 truncate text-sm">+ <span className="truncate">{label}</span>+ <span className="rounded bg-muted px-1.5 py-px text-[10px] font-medium uppercase tracking-wide text-muted-foreground">+ Page+ </span>+ </span>+ <button+ type="button"+ aria-label={shown ? `Hide ${label}` : `Show ${label}`}+ aria-pressed={shown}+ onClick={(e) => {+ e.stopPropagation();+ onToggle();+ }}+ className={cn(+ "rounded p-1 transition-colors",+ shown+ ? "text-foreground hover:bg-muted"+ : "text-muted-foreground hover:bg-muted"+ )}+ >+ {shown ? <LuEye className="size-4" /> : <LuEyeOff className="size-4" />}+ </button>+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/FontConfig.tsx b/apps/erp/app/components/DocumentTemplateEditor/FontConfig.tsxnew file mode 100644index 0000000000..1a1cbee57f--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/FontConfig.tsx@@ -0,0 +1,44 @@+import { DOCUMENT_FONTS } from "@carbon/documents/template";+import {+ Label,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@carbon/react";+import { useDocumentTemplate } from "./context";++/** Document body font selector (applies to the whole document). */+export function FontConfig() {+ const { settings, setSetting } = useDocumentTemplate();++ return (+ <div className="flex flex-col gap-1.5">+ <Label>Body font</Label>+ <Select+ value={settings.fontFamily}+ onValueChange={(v) =>+ setSetting("fontFamily", v as typeof settings.fontFamily)+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {DOCUMENT_FONTS.map((f) => (+ <SelectItem key={f.value} value={f.value}>+ <span className="flex w-full items-center justify-between gap-3">+ <span>{f.label}</span>+ <span className="text-xs text-muted-foreground">{f.kind}</span>+ </span>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <p className="text-xs text-muted-foreground">+ Applies to the whole document.+ </p>+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/LogoCropper.tsx b/apps/erp/app/components/DocumentTemplateEditor/LogoCropper.tsxnew file mode 100644index 0000000000..5ae02f2079--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/LogoCropper.tsx@@ -0,0 +1,222 @@+import type { LabelLogoBlock } from "@carbon/documents/template";+import {+ Button,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalTitle+} from "@carbon/react";+import { useCallback, useRef, useState } from "react";++type Crop = NonNullable<LabelLogoBlock["crop"]>;++const FULL: Crop = { x: 0, y: 0, width: 1, height: 1, aspect: 1 };+const clamp01 = (n: number) => Math.min(1, Math.max(0, n));++/**+ * Logo crop field: a compact preview + buttons. The actual drag-to-crop canvas+ * lives in a dialog (kept out of the cramped config panels) so the source logo+ * never blows the surrounding form open. Emits a crop rectangle normalized to+ * the source image (0..1) plus the cropped region's pixel aspect ratio, so the+ * PDF/ZPL renderers can size a clip box without loading the image.+ */+export function LogoCropper({+ src,+ crop,+ onChange+}: {+ src: string;+ crop?: Crop;+ onChange: (crop: Crop | undefined) => void;+}) {+ const [open, setOpen] = useState(false);+ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <span className="text-xs text-muted-foreground">Crop</span>+ <div className="flex items-center gap-1">+ {crop && (+ <Button+ variant="ghost"+ size="sm"+ className="h-6 px-2 text-xs"+ onClick={() => onChange(undefined)}+ >+ Reset+ </Button>+ )}+ <Button+ variant="secondary"+ size="sm"+ className="h-6 px-2 text-xs"+ onClick={() => setOpen(true)}+ >+ {crop ? "Edit crop" : "Crop"}+ </Button>+ </div>+ </div>+ <button+ type="button"+ onClick={() => setOpen(true)}+ className="flex h-16 items-center justify-center overflow-hidden rounded-md border bg-white p-1"+ >+ <img src={src} alt="" className="max-h-full w-auto" />+ </button>+ {open && (+ <CropDialog+ src={src}+ crop={crop}+ onChange={onChange}+ onClose={() => setOpen(false)}+ />+ )}+ </div>+ );+}++/** The drag-to-crop canvas, in a dialog. Live-updates the crop as you drag. */+function CropDialog({+ src,+ crop,+ onChange,+ onClose+}: {+ src: string;+ crop?: Crop;+ onChange: (crop: Crop | undefined) => void;+ onClose: () => void;+}) {+ const boxRef = useRef<HTMLDivElement>(null);+ const natural = useRef<{ w: number; h: number }>({ w: 1, h: 1 });+ const drag = useRef<{+ mode: "move" | "resize";+ startX: number;+ startY: number;+ start: Crop;+ } | null>(null);+ const [active, setActive] = useState(false);++ const c = crop ?? FULL;++ const aspectOf = useCallback((width: number, height: number) => {+ const { w, h } = natural.current;+ return (width * w) / (height * h) || 1;+ }, []);++ const onPointerMove = useCallback(+ (e: PointerEvent) => {+ const d = drag.current;+ const rect = boxRef.current?.getBoundingClientRect();+ if (!d || !rect) return;+ const dx = (e.clientX - d.startX) / rect.width;+ const dy = (e.clientY - d.startY) / rect.height;+ let next: Crop;+ if (d.mode === "move") {+ const x = clamp01(d.start.x + dx);+ const y = clamp01(d.start.y + dy);+ next = {+ ...d.start,+ x: Math.min(x, 1 - d.start.width),+ y: Math.min(y, 1 - d.start.height)+ };+ } else {+ const width = clamp01(d.start.width + dx) || 0.05;+ const height = clamp01(d.start.height + dy) || 0.05;+ const w = Math.max(0.05, Math.min(width, 1 - d.start.x));+ const h = Math.max(0.05, Math.min(height, 1 - d.start.y));+ next = { ...d.start, width: w, height: h, aspect: aspectOf(w, h) };+ }+ onChange(next);+ },+ [aspectOf, onChange]+ );++ const endDrag = useCallback(() => {+ drag.current = null;+ setActive(false);+ window.removeEventListener("pointermove", onPointerMove);+ window.removeEventListener("pointerup", endDrag);+ }, [onPointerMove]);++ const startDrag = useCallback(+ (mode: "move" | "resize") => (e: React.PointerEvent) => {+ e.preventDefault();+ e.stopPropagation();+ drag.current = {+ mode,+ startX: e.clientX,+ startY: e.clientY,+ start: crop ?? { ...FULL, aspect: aspectOf(1, 1) }+ };+ setActive(true);+ window.addEventListener("pointermove", onPointerMove);+ window.addEventListener("pointerup", endDrag);+ },+ [aspectOf, crop, endDrag, onPointerMove]+ );++ return (+ <Modal open onOpenChange={(o) => !o && onClose()}>+ <ModalContent>+ <ModalHeader>+ <ModalTitle>Crop logo</ModalTitle>+ </ModalHeader>+ <ModalBody>+ <p className="mb-3 text-sm text-muted-foreground">+ Drag the box to move it, drag the bottom-right handle to resize.+ </p>+ <div className="flex justify-center">+ <div+ ref={boxRef}+ className="relative inline-block max-h-[55vh] select-none overflow-hidden rounded-md border bg-white"+ style={{ touchAction: "none" }}+ >+ <img+ src={src}+ alt=""+ draggable={false}+ className="pointer-events-none block max-h-[55vh] w-auto"+ onLoad={(e) => {+ natural.current = {+ w: e.currentTarget.naturalWidth || 1,+ h: e.currentTarget.naturalHeight || 1+ };+ }}+ />+ <div+ onPointerDown={startDrag("move")}+ className="absolute cursor-move border-2 border-white"+ style={{+ left: `${c.x * 100}%`,+ top: `${c.y * 100}%`,+ width: `${c.width * 100}%`,+ height: `${c.height * 100}%`,+ boxShadow: "0 0 0 9999px rgba(0,0,0,0.4)",+ outline: active ? "1px solid #fff" : undefined+ }}+ >+ <div+ onPointerDown={startDrag("resize")}+ className="absolute -bottom-1.5 -right-1.5 h-3 w-3 cursor-se-resize rounded-sm border-2 border-white bg-foreground"+ />+ </div>+ </div>+ </div>+ </ModalBody>+ <ModalFooter>+ <Button+ variant="secondary"+ onClick={() => {+ onChange(undefined);+ }}+ >+ Reset+ </Button>+ <Button onClick={onClose}>Done</Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/MergeFieldMenu.tsx b/apps/erp/app/components/DocumentTemplateEditor/MergeFieldMenu.tsxnew file mode 100644index 0000000000..7d80e21d6c--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/MergeFieldMenu.tsx@@ -0,0 +1,63 @@+import { getMergeFields, mergeToken } from "@carbon/documents/template";+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuTrigger+} from "@carbon/react";+import { Fragment } from "react";+import { LuBraces } from "react-icons/lu";+import { useDocumentTemplate } from "./context";++/**+ * Dropdown of the document's merge fields. Inserting one hands the caller the+ * `{token}` snippet to splice into whatever it's editing (a key-value cell,+ * rich text, etc.).+ */+export function MergeFieldMenu({+ onInsert,+ label = "Field"+}: {+ onInsert: (snippet: string) => void;+ label?: string;+}) {+ const { documentType } = useDocumentTemplate();+ const fields = getMergeFields(documentType);+ if (fields.length === 0) return null;++ const groups = [...new Set(fields.map((f) => f.group))];++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="sm"+ leftIcon={<LuBraces />}+ className="shrink-0 text-muted-foreground"+ >+ {label}+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="max-h-72 overflow-y-auto">+ {groups.map((group) => (+ <Fragment key={group}>+ <DropdownMenuLabel>{group}</DropdownMenuLabel>+ {fields+ .filter((f) => f.group === group)+ .map((field) => (+ <DropdownMenuItem+ key={field.token}+ onClick={() => onInsert(mergeToken(field.token))}+ >+ {field.label}+ </DropdownMenuItem>+ ))}+ </Fragment>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/NumberRow.tsx b/apps/erp/app/components/DocumentTemplateEditor/NumberRow.tsxnew file mode 100644index 0000000000..481ebfe82a--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/NumberRow.tsx@@ -0,0 +1,54 @@+import {+ Label,+ NumberDecrementStepper,+ NumberField,+ NumberIncrementStepper,+ NumberInput,+ NumberInputGroup,+ NumberInputStepper+} from "@carbon/react";+import { LuChevronDown, LuChevronUp } from "react-icons/lu";++/**+ * A labeled numeric input. `NumberField` (react-aria) is a container — it needs+ * a composed `NumberInputGroup` child to render an actual input — so callers+ * can't just pass a `label` prop. This wraps the boilerplate.+ */+export function NumberRow({+ label,+ value,+ onChange,+ minValue,+ maxValue+}: {+ label: string;+ value: number;+ onChange: (value: number) => void;+ minValue?: number;+ maxValue?: number;+}) {+ return (+ <div className="flex flex-col gap-1.5">+ <Label>{label}</Label>+ <NumberField+ value={value}+ onChange={(v) => onChange(Number.isNaN(v) ? 0 : v)}+ minValue={minValue}+ maxValue={maxValue}+ aria-label={label}+ >+ <NumberInputGroup className="relative">+ <NumberInput />+ <NumberInputStepper>+ <NumberIncrementStepper>+ <LuChevronUp size="1em" strokeWidth="3" />+ </NumberIncrementStepper>+ <NumberDecrementStepper>+ <LuChevronDown size="1em" strokeWidth="3" />+ </NumberDecrementStepper>+ </NumberInputStepper>+ </NumberInputGroup>+ </NumberField>+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/SectionFormModal.tsx b/apps/erp/app/components/DocumentTemplateEditor/SectionFormModal.tsxnew file mode 100644index 0000000000..7cd47adbe6--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/SectionFormModal.tsx@@ -0,0 +1,227 @@+import type {+ DocumentSectionPlacement,+ HeaderOptions+} from "@carbon/documents/template";+import { DEFAULT_HEADER_OPTIONS } from "@carbon/documents/template";+import type { JSONContent } from "@carbon/react";+import {+ Button,+ Input,+ Label,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalTitle,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ Switch,+ VStack+} from "@carbon/react";+import { Editor } from "@carbon/react/Editor";+import { useEffect, useRef, useState } from "react";+import { useFetcher } from "react-router";++export type SectionFormValue = {+ id: string;+ name: string;+ placement: DocumentSectionPlacement;+ content: JSONContent;+ config?: Partial<HeaderOptions>;+ builtIn?: boolean;+};++const PLACEMENT_LABELS: Record<DocumentSectionPlacement, string> = {+ body: "Body section",+ header: "Page header",+ footer: "Page footer"+};++/**+ * Create/edit a shared document section. Reused by the section library and the+ * template editor — pass `action` to post to the sections route when rendered+ * outside it.+ */+export function SectionFormModal({+ section,+ onClose,+ action+}: {+ section: SectionFormValue | null;+ onClose: () => void;+ action?: string;+}) {+ const fetcher = useFetcher<{ success?: boolean }>();+ const [content, setContent] = useState<JSONContent>(+ section?.content ?? { type: "doc", content: [] }+ );+ const [placement, setPlacement] = useState<DocumentSectionPlacement>(+ section?.placement ?? "body"+ );+ const [config, setConfig] = useState<HeaderOptions>({+ ...DEFAULT_HEADER_OPTIONS,+ ...(section?.config ?? {})+ });+ // Placement is intrinsic once a section exists — don't let it change.+ const lockPlacement = Boolean(section);+ const isHeader = placement === "header";++ const isSaving = fetcher.state !== "idle";+ const submittedRef = useRef(false);++ const setConfigKey = <K extends keyof HeaderOptions>(+ key: K,+ value: HeaderOptions[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));+ submittedRef.current = true;+ fetcher.submit(data, { method: "post", ...(action ? { action } : {}) });+ };++ // Close once our save resolves successfully.+ useEffect(() => {+ if (+ submittedRef.current &&+ fetcher.state === "idle" &&+ fetcher.data?.success+ ) {+ submittedRef.current = false;+ onClose();+ }+ }, [fetcher.state, fetcher.data, onClose]);++ return (+ <Modal open onOpenChange={(open) => !open && onClose()}>+ <ModalContent>+ <fetcher.Form+ method="post"+ onSubmit={(e) => {+ e.preventDefault();+ submit(e.currentTarget);+ }}+ >+ {section && <input type="hidden" name="id" value={section.id} />}+ <ModalHeader>+ <ModalTitle>+ {section ? "Edit section" : "New shared section"}+ </ModalTitle>+ </ModalHeader>+ <ModalBody>+ <VStack spacing={4}>+ <div className="flex w-full flex-col gap-1.5">+ <Label htmlFor="name">Name</Label>+ <Input+ id="name"+ name="name"+ defaultValue={section?.name ?? ""}+ autoFocus+ required+ />+ </div>+ <div className="flex w-full flex-col gap-1.5">+ <Label>Placement</Label>+ {lockPlacement ? (+ <div className="rounded-md border bg-muted/40 px-3 py-2 text-sm">+ {PLACEMENT_LABELS[placement]}+ </div>+ ) : (+ <Select+ value={placement}+ onValueChange={(v) =>+ setPlacement(v as DocumentSectionPlacement)+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="body">Body section</SelectItem>+ <SelectItem value="header">Page header</SelectItem>+ <SelectItem value="footer">Page footer</SelectItem>+ </SelectContent>+ </Select>+ )}+ </div>++ {isHeader && (+ <div className="flex w-full flex-col gap-3 rounded-md border bg-muted/30 p-3">+ <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">+ Header layout+ </p>+ <p className="text-xs text-muted-foreground">+ Set the logo from the Logo item under Header.+ </p>+ <ConfigSwitch+ label="Show company address"+ checked={config.showCompanyDetails}+ onChange={(v) => setConfigKey("showCompanyDetails", v)}+ />+ <ConfigSwitch+ label="Show document title"+ checked={config.showDocumentTitle}+ onChange={(v) => setConfigKey("showDocumentTitle", v)}+ />+ <ConfigSwitch+ label="Show document number"+ checked={config.showDocumentId}+ onChange={(v) => setConfigKey("showDocumentId", v)}+ />+ </div>+ )}++ <div className="flex w-full flex-col gap-1.5">+ <Label>+ {isHeader ? "Banner content (optional)" : "Content"}+ </Label>+ <Editor+ className="min-h-[160px] w-full rounded-md border bg-background p-3"+ initialValue={content}+ onChange={setContent}+ disableFileUpload+ />+ </div>+ </VStack>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" type="button" onClick={onClose}>+ Cancel+ </Button>+ <Button type="submit" isLoading={isSaving} isDisabled={isSaving}>+ Save+ </Button>+ </ModalFooter>+ </fetcher.Form>+ </ModalContent>+ </Modal>+ );+}++function ConfigSwitch({+ label,+ checked,+ onChange+}: {+ label: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+}) {+ return (+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm">{label}</span>+ <Switch+ variant="small"+ checked={checked}+ onCheckedChange={(v) => onChange(Boolean(v))}+ />+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/TemplatePreview.tsx b/apps/erp/app/components/DocumentTemplateEditor/TemplatePreview.tsxnew file mode 100644index 0000000000..971206898f--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/TemplatePreview.tsx@@ -0,0 +1,100 @@+import { Spinner } from "@carbon/react";+import { useEffect, useRef, useState } from "react";+import { useDocumentTemplate } from "./context";++const PREVIEW_DEBOUNCE_MS = 500;++/**+ * Server-rendered preview. The PDF is generated by the `.preview` route (Node,+ * where @react-pdf/renderer's Buffer/stream deps exist) and shown in the+ * browser's native PDF viewer via an iframe. No client-side react-pdf, no+ * polyfills, and the preview is byte-identical to the real document route.+ */+export function TemplatePreview({ previewPath }: { previewPath: string }) {+ const {+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ sections,+ previewId+ } = useDocumentTemplate();+ const [url, setUrl] = useState<string | null>(null);+ const [isLoading, setIsLoading] = useState(true);+ const urlRef = useRef<string | null>(null);++ // biome-ignore lint/correctness/useExhaustiveDependencies: `sections` is intentionally a dep so editing a header/footer section re-renders the preview.+ useEffect(() => {+ const controller = new AbortController();+ const handle = setTimeout(async () => {+ setIsLoading(true);+ try {+ const formData = new FormData();+ formData.append("blocks", JSON.stringify(blocks));+ formData.append("theme", JSON.stringify(theme));+ formData.append("settings", JSON.stringify(settings));+ formData.append("headerSectionId", headerSectionId ?? "");+ formData.append("footerSectionId", footerSectionId ?? "");+ if (previewId) formData.append("previewId", previewId);+ const response = await fetch(previewPath, {+ method: "post",+ body: formData,+ signal: controller.signal+ });+ if (!response.ok) return;+ const blob = await response.blob();+ const nextUrl = URL.createObjectURL(blob);+ if (urlRef.current) URL.revokeObjectURL(urlRef.current);+ urlRef.current = nextUrl;+ setUrl(nextUrl);+ } catch (error) {+ if (!controller.signal.aborted) console.error(error);+ } finally {+ if (!controller.signal.aborted) setIsLoading(false);+ }+ }, PREVIEW_DEBOUNCE_MS);++ return () => {+ controller.abort();+ clearTimeout(handle);+ };+ // `sections` is included so editing a header/footer section (which the+ // preview route resolves server-side) retriggers a fresh render.+ }, [+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ sections,+ previewId,+ previewPath+ ]);++ // Revoke the last object URL on unmount.+ useEffect(+ () => () => {+ if (urlRef.current) URL.revokeObjectURL(urlRef.current);+ },+ []+ );++ return (+ <div className="relative mx-auto flex h-full w-full max-w-3xl flex-col overflow-hidden rounded-lg border bg-card shadow-sm">+ {url && (+ <iframe+ key={url}+ src={url}+ title="Document preview"+ className="block h-full w-full grow border-none"+ />+ )}+ {isLoading && (+ <div className="absolute inset-0 flex items-center justify-center bg-background/60 backdrop-blur-[1px]">+ <Spinner className="size-6" />+ </div>+ )}+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/ThemeConfig.tsx b/apps/erp/app/components/DocumentTemplateEditor/ThemeConfig.tsxnew file mode 100644index 0000000000..50720c4c25--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/ThemeConfig.tsx@@ -0,0 +1,29 @@+import type { DocumentTheme } from "@carbon/documents/template";+import { ColorPicker } from "~/components/ColorPicker";+import { useDocumentTemplate } from "./context";++const SWATCHES: { key: keyof DocumentTheme; label: string; hint: string }[] = [+ { key: "accent", label: "Accent", hint: "Table header bar, headings" },+ { key: "accentForeground", label: "Accent text", hint: "Text on the accent" }+];++export function ThemeConfig() {+ const { theme, setThemeColor } = useDocumentTemplate();++ return (+ <div className="flex flex-col gap-3">+ {SWATCHES.map(({ key, label, hint }) => (+ <div key={key} className="flex flex-col gap-1.5">+ <div className="flex flex-col">+ <span className="text-sm">{label}</span>+ <span className="text-xs text-muted-foreground">{hint}</span>+ </div>+ <ColorPicker+ value={theme[key]}+ onChange={(value) => setThemeColor(key, value)}+ />+ </div>+ ))}+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/configHelpers.tsx b/apps/erp/app/components/DocumentTemplateEditor/configHelpers.tsxnew file mode 100644index 0000000000..9a4fa2a207--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/configHelpers.tsx@@ -0,0 +1,23 @@+import { Switch } from "@carbon/react";++/** A label + small switch row, shared across the block config panels. */+export function ToggleRow({+ label,+ checked,+ onChange+}: {+ label: string;+ checked: boolean;+ onChange: (checked: boolean) => void;+}) {+ return (+ <div className="flex items-center justify-between gap-2">+ <span className="text-sm">{label}</span>+ <Switch+ variant="small"+ checked={checked}+ onCheckedChange={(value) => onChange(Boolean(value))}+ />+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/context.tsx b/apps/erp/app/components/DocumentTemplateEditor/context.tsxnew file mode 100644index 0000000000..1b38f2c24b--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/context.tsx@@ -0,0 +1,405 @@+import type {+ DocumentBlock,+ DocumentBlockType,+ DocumentSettings,+ DocumentTemplateType,+ DocumentTheme,+ HeaderOptions+} from "@carbon/documents/template";+import type { JSONContent } from "@carbon/react";+import { arrayMove } from "@dnd-kit/sortable";+import { nanoid } from "nanoid";+import {+ createContext,+ type PropsWithChildren,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState+} from "react";+import { useFetcher } from "react-router";++type AddableBlockType = Extract<+ DocumentBlockType,+ "richText" | "keyValue" | "spacer"+>;++export interface SectionRef {+ id: string;+ name: string;+ placement: "body" | "header" | "footer";+ /** Present for header/footer so the editor can open the edit dialog inline. */+ content?: JSONContent;+ config?: Partial<HeaderOptions>;+}++/**+ * Synthetic selection id for the page Footer. The footer is page chrome, not a+ * flow block, so it isn't in `blocks` — but it gets a row in the list and a+ * config panel keyed off this id.+ */+export const FOOTER_BLOCK_ID = "__footer__";++/** A custom field available to insert (id + display name). */+export interface CustomFieldRef {+ id: string;+ name: string;+}++/** A real record the preview can render against (id + readable label). */+export interface PreviewEntity {+ id: string;+ label: string;+}++/**+ * Generic editor interface: state + actions + meta. The provider is the only+ * place that knows blocks live in React state and persist via a fetcher;+ * consumers depend on this shape, not the implementation.+ */+interface DocumentTemplateContextValue {+ // state+ documentType: DocumentTemplateType;+ blocks: DocumentBlock[];+ theme: DocumentTheme;+ settings: DocumentSettings;+ headerSectionId: string | null;+ footerSectionId: string | null;+ /** All shared sections available to reference (id, name, placement). */+ sections: SectionRef[];+ /** Custom fields available to insert as blocks. */+ customFields: CustomFieldRef[];+ /** Company terms setting — seeds the Terms block when it has no content. */+ termsSeed?: JSONContent;+ /** Real records the preview can render against. */+ previewEntities: PreviewEntity[];+ /** Whether the company has a watermark logo set (gates the watermark toggle). */+ hasWatermark: boolean;+ /** Selected record id for live-data preview (null = sample data). */+ previewId: string | null;+ setPreviewId: (id: string | null) => void;+ selectedId: string | null;+ // actions+ select: (id: string | null) => void;+ addBlock: (type: AddableBlockType) => void;+ addSharedBlock: (sectionId: string) => void;+ addCustomFieldBlock: (fieldId: string, label: string) => void;+ /** Add a single-line field. `withLabel` seeds an empty label (key-value). */+ addField: (withLabel: boolean) => void;+ removeBlock: (id: string) => void;+ toggleVisible: (id: string) => void;+ reorder: (activeId: string, overId: string) => void;+ updateBlock: (id: string, patch: Partial<DocumentBlock>) => void;+ setThemeColor: (key: keyof DocumentTheme, value: string) => void;+ setSetting: <K extends keyof DocumentSettings>(+ key: K,+ value: DocumentSettings[K]+ ) => void;+ setHeaderSection: (sectionId: string | null) => void;+ setFooterSection: (sectionId: string | null) => void;+ reset: () => void;+ save: () => void;+ // meta+ isDirty: boolean;+ isSaving: boolean;+}++const DocumentTemplateContext =+ createContext<DocumentTemplateContextValue | null>(null);++export function useDocumentTemplate() {+ const ctx = useContext(DocumentTemplateContext);+ if (!ctx) {+ throw new Error(+ "useDocumentTemplate must be used within a DocumentTemplateProvider"+ );+ }+ return ctx;+}++function createBlock(type: AddableBlockType): DocumentBlock {+ const id = nanoid();+ switch (type) {+ case "richText":+ return { id, type, visible: true, content: { type: "doc", content: [] } };+ case "keyValue":+ return { id, type, visible: true, rows: [] };+ case "spacer":+ return { id, type, visible: true, variant: "space" };+ }+}++export function DocumentTemplateProvider({+ documentType,+ actionPath,+ initialBlocks,+ initialTheme,+ initialSettings,+ initialHeaderSectionId,+ initialFooterSectionId,+ sections,+ customFields,+ previewEntities,+ termsSeed,+ hasWatermark,+ children+}: PropsWithChildren<{+ documentType: DocumentTemplateType;+ actionPath: string;+ initialBlocks: DocumentBlock[];+ initialTheme: DocumentTheme;+ initialSettings: DocumentSettings;+ initialHeaderSectionId: string | null;+ initialFooterSectionId: string | null;+ sections: SectionRef[];+ customFields: CustomFieldRef[];+ previewEntities: PreviewEntity[];+ termsSeed?: JSONContent;+ hasWatermark: boolean;+}>) {+ const fetcher = useFetcher<{ success?: boolean }>();+ const [blocks, setBlocks] = useState<DocumentBlock[]>(initialBlocks);+ const [theme, setTheme] = useState<DocumentTheme>(initialTheme);+ const [settings, setSettings] = useState<DocumentSettings>(initialSettings);+ const [headerSectionId, setHeaderSectionId] = useState<string | null>(+ initialHeaderSectionId+ );+ const [footerSectionId, setFooterSectionId] = useState<string | null>(+ initialFooterSectionId+ );+ const [selectedId, setSelectedId] = useState<string | null>(null);+ const [previewId, setPreviewId] = useState<string | null>(null);+ const submittedRef = useRef(false);++ const isSaving = fetcher.state !== "idle";++ const isDirty = useMemo(+ () =>+ JSON.stringify(blocks) !== JSON.stringify(initialBlocks) ||+ JSON.stringify(theme) !== JSON.stringify(initialTheme) ||+ JSON.stringify(settings) !== JSON.stringify(initialSettings) ||+ headerSectionId !== initialHeaderSectionId ||+ footerSectionId !== initialFooterSectionId,+ [+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ initialBlocks,+ initialTheme,+ initialSettings,+ initialHeaderSectionId,+ initialFooterSectionId+ ]+ );++ const addBlock = useCallback((type: AddableBlockType) => {+ const block = createBlock(type);+ setBlocks((prev) => [...prev, block]);+ setSelectedId(block.id);+ }, []);++ const addSharedBlock = useCallback((sectionId: string) => {+ const block: DocumentBlock = {+ id: nanoid(),+ type: "shared",+ visible: true,+ sectionId+ };+ setBlocks((prev) => [...prev, block]);+ setSelectedId(block.id);+ }, []);++ const addCustomFieldBlock = useCallback((fieldId: string, label: string) => {+ const block: DocumentBlock = {+ id: nanoid(),+ type: "customField",+ visible: true,+ fieldId,+ label+ };+ setBlocks((prev) => [...prev, block]);+ setSelectedId(block.id);+ }, []);++ const addField = useCallback((withLabel: boolean) => {+ const block: DocumentBlock = {+ id: nanoid(),+ type: "field",+ visible: true,+ value: "",+ ...(withLabel ? { label: "" } : {})+ };+ setBlocks((prev) => [...prev, block]);+ setSelectedId(block.id);+ }, []);++ const removeBlock = useCallback((id: string) => {+ setBlocks((prev) => prev.filter((b) => b.id !== id));+ setSelectedId((current) => (current === id ? null : current));+ }, []);++ const toggleVisible = useCallback((id: string) => {+ setBlocks((prev) =>+ prev.map((b) => (b.id === id ? { ...b, visible: !b.visible } : b))+ );+ }, []);++ const reorder = useCallback((activeId: string, overId: string) => {+ setBlocks((prev) => {+ const from = prev.findIndex((b) => b.id === activeId);+ const to = prev.findIndex((b) => b.id === overId);+ if (from === -1 || to === -1) return prev;+ return arrayMove(prev, from, to);+ });+ }, []);++ const updateBlock = useCallback(+ (id: string, patch: Partial<DocumentBlock>) => {+ setBlocks((prev) =>+ prev.map((b) =>+ b.id === id ? ({ ...b, ...patch } as DocumentBlock) : b+ )+ );+ },+ []+ );++ const setThemeColor = useCallback(+ (key: keyof DocumentTheme, value: string) => {+ setTheme((prev) => ({ ...prev, [key]: value }));+ },+ []+ );++ const setSetting = useCallback(+ <K extends keyof DocumentSettings>(key: K, value: DocumentSettings[K]) => {+ setSettings((prev) => ({ ...prev, [key]: value }));+ },+ []+ );++ const reset = useCallback(() => {+ setBlocks(initialBlocks);+ setTheme(initialTheme);+ setSettings(initialSettings);+ setHeaderSectionId(initialHeaderSectionId);+ setFooterSectionId(initialFooterSectionId);+ setSelectedId(null);+ }, [+ initialBlocks,+ initialTheme,+ initialSettings,+ initialHeaderSectionId,+ initialFooterSectionId+ ]);++ const save = useCallback(() => {+ const formData = new FormData();+ formData.append("documentType", documentType);+ formData.append("blocks", JSON.stringify(blocks));+ formData.append("theme", JSON.stringify(theme));+ formData.append("settings", JSON.stringify(settings));+ formData.append("headerSectionId", headerSectionId ?? "");+ formData.append("footerSectionId", footerSectionId ?? "");+ submittedRef.current = true;+ fetcher.submit(formData, { method: "post", action: actionPath });+ }, [+ actionPath,+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ documentType,+ fetcher+ ]);++ // Clear the dirty baseline once our save resolves: react-router revalidates+ // the loader, so `initialBlocks` updates and isDirty falls back to false.+ useEffect(() => {+ if (+ submittedRef.current &&+ fetcher.state === "idle" &&+ fetcher.data?.success+ ) {+ submittedRef.current = false;+ }+ }, [fetcher.data, fetcher.state]);++ const value = useMemo<DocumentTemplateContextValue>(+ () => ({+ documentType,+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ sections,+ customFields,+ termsSeed,+ previewEntities,+ hasWatermark,+ previewId,+ setPreviewId,+ selectedId,+ select: setSelectedId,+ addBlock,+ addSharedBlock,+ addCustomFieldBlock,+ addField,+ removeBlock,+ toggleVisible,+ reorder,+ updateBlock,+ setThemeColor,+ setSetting,+ setHeaderSection: setHeaderSectionId,+ setFooterSection: setFooterSectionId,+ reset,+ save,+ isDirty,+ isSaving+ }),+ [+ documentType,+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ sections,+ customFields,+ termsSeed,+ previewEntities,+ hasWatermark,+ previewId,+ selectedId,+ addBlock,+ addSharedBlock,+ addCustomFieldBlock,+ addField,+ removeBlock,+ toggleVisible,+ reorder,+ updateBlock,+ setThemeColor,+ setSetting,+ reset,+ save,+ isDirty,+ isSaving+ ]+ );++ return (+ <DocumentTemplateContext.Provider value={value}>+ {children}+ </DocumentTemplateContext.Provider>+ );+}++export type { AddableBlockType };diff --git a/apps/erp/app/components/DocumentTemplateEditor/index.tsx b/apps/erp/app/components/DocumentTemplateEditor/index.tsxnew file mode 100644index 0000000000..c114baaa27--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/index.tsx@@ -0,0 +1,258 @@+import type {+ DocumentBlock,+ DocumentSettings,+ DocumentTemplateType,+ DocumentTheme+} from "@carbon/documents/template";+import { getDocumentLabel } from "@carbon/documents/template";+import type { JSONContent } from "@carbon/react";+import {+ Button,+ Combobox,+ Heading,+ ResizableHandle,+ ResizablePanel,+ ResizablePanelGroup,+ ScrollArea,+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger+} from "@carbon/react";+import { type ReactNode, useState } from "react";+import { LuArrowLeft, LuPalette } from "react-icons/lu";+import { Link } from "react-router";+import { path } from "~/utils/path";+import { BlockConfig } from "./BlockConfig";+import { BlockList } from "./BlockList";+import type { CustomFieldRef, PreviewEntity, SectionRef } from "./context";+import { DocumentTemplateProvider, useDocumentTemplate } from "./context";+import { FontConfig } from "./FontConfig";+import { TemplatePreview } from "./TemplatePreview";+import { ThemeConfig } from "./ThemeConfig";++export function DocumentTemplateEditor({+ documentType,+ actionPath,+ initialBlocks,+ initialTheme,+ initialSettings,+ initialHeaderSectionId,+ initialFooterSectionId,+ sections,+ customFields,+ previewEntities,+ termsSeed,+ hasWatermark,+ canEdit+}: {+ documentType: DocumentTemplateType;+ actionPath: string;+ initialBlocks: DocumentBlock[];+ initialTheme: DocumentTheme;+ initialSettings: DocumentSettings;+ initialHeaderSectionId: string | null;+ initialFooterSectionId: string | null;+ sections: SectionRef[];+ customFields: CustomFieldRef[];+ previewEntities: PreviewEntity[];+ termsSeed?: JSONContent;+ hasWatermark: boolean;+ canEdit: boolean;+}) {+ return (+ <DocumentTemplateProvider+ documentType={documentType}+ actionPath={actionPath}+ initialBlocks={initialBlocks}+ initialTheme={initialTheme}+ initialSettings={initialSettings}+ initialHeaderSectionId={initialHeaderSectionId}+ initialFooterSectionId={initialFooterSectionId}+ sections={sections}+ customFields={customFields}+ previewEntities={previewEntities}+ termsSeed={termsSeed}+ hasWatermark={hasWatermark}+ >+ <div className="flex h-full w-full min-w-0 flex-col bg-background">+ <EditorToolbar+ title={getDocumentLabel(documentType)}+ canEdit={canEdit}+ />+ <ResizablePanelGroup+ direction="horizontal"+ autoSaveId="document-template-editor"+ className="flex-1 overflow-hidden"+ >+ {/* LEFT — blocks + theme */}+ <ResizablePanel+ id="rail"+ order={1}+ defaultSize={22}+ minSize={16}+ maxSize={34}+ >+ <ControlRail />+ </ResizablePanel>++ <ResizableHandle withHandle />++ {/* CENTER — canvas */}+ <ResizablePanel id="canvas" order={2} defaultSize={56} minSize={30}>+ <div className="flex h-full min-w-0 flex-col bg-muted/40 p-6">+ <TemplatePreview previewPath={`${actionPath}/preview`} />+ </div>+ </ResizablePanel>++ <ResizableHandle withHandle />++ {/* RIGHT — contextual config, always present */}+ <ResizablePanel+ id="config"+ order={3}+ defaultSize={22}+ minSize={16}+ maxSize={34}+ >+ <ScrollArea className="h-full bg-card">+ <div className="flex flex-col gap-1.5 p-3">+ <h2 className={RAIL_HEADING}>Configure</h2>+ <BlockConfig />+ </div>+ </ScrollArea>+ </ResizablePanel>+ </ResizablePanelGroup>+ </div>+ </DocumentTemplateProvider>+ );+}++const RAIL_HEADING =+ "text-[11px] font-semibold uppercase tracking-wide text-muted-foreground";++/**+ * Left rail: block layers (incl. the Header block + Footer row) and a Page /+ * Theme tab group for document-wide settings. The contextual Configure panel+ * lives in its own right rail.+ */+function ControlRail() {+ const [tab, setTab] = useState<"style">("style");++ return (+ <ScrollArea className="h-full bg-card">+ <div className="flex flex-col gap-4 p-3">+ <section className="flex flex-col gap-1.5">+ <h2 className={RAIL_HEADING}>Blocks</h2>+ <BlockList />+ </section>++ <Tabs+ value={tab}+ onValueChange={(v) => setTab(v as "style")}+ className="border-t pt-1"+ >+ <TabsList className="h-auto w-full justify-start gap-1 rounded-none border-b bg-transparent p-0 shadow-none">+ <UnderlineTab value="style" icon={<LuPalette />} label="Style" />+ </TabsList>+ <TabsContent value="style" className="flex flex-col gap-5 pt-4">+ <section className="flex flex-col gap-3">+ <h3 className={RAIL_HEADING}>Typography</h3>+ <FontConfig />+ </section>+ <section className="flex flex-col gap-2">+ <h3 className={RAIL_HEADING}>Theme colors</h3>+ <ThemeConfig />+ </section>+ </TabsContent>+ </Tabs>+ </div>+ </ScrollArea>+ );+}++/** Clean underline-style tab trigger with a generous hit area. */+function UnderlineTab({+ value,+ icon,+ label+}: {+ value: string;+ icon: ReactNode;+ label: string;+}) {+ return (+ <TabsTrigger+ value={value}+ className="-mb-px gap-1.5 rounded-none border-0 border-b-2 border-transparent bg-transparent px-3 py-2 text-xs text-muted-foreground shadow-none data-[state=active]:border-foreground data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none"+ >+ <span className="[&>svg]:size-3.5">{icon}</span>+ {label}+ </TabsTrigger>+ );+}++function EditorToolbar({+ title,+ canEdit+}: {+ title: string;+ canEdit: boolean;+}) {+ const {+ isDirty,+ isSaving,+ reset,+ save,+ previewEntities,+ previewId,+ setPreviewId+ } = useDocumentTemplate();++ return (+ <div className="flex items-center justify-between gap-3 border-b bg-card px-4 py-3">+ <div className="flex items-center gap-3">+ <Link+ to={path.to.documentTemplates}+ aria-label="Back to documents"+ className="flex size-8 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ >+ <LuArrowLeft className="size-4" />+ </Link>+ <div className="flex flex-col">+ <Heading size="h4">Document Layout</Heading>+ <p className="text-xs text-muted-foreground">{title}</p>+ </div>+ </div>+ {previewEntities.length > 0 && (+ <div className="flex min-w-0 max-w-[280px] flex-1 justify-center">+ <Combobox+ size="sm"+ className="w-full"+ value={previewId ?? ""}+ options={previewEntities.map((e) => ({+ label: e.label,+ value: e.id+ }))}+ onChange={(value) => setPreviewId(value || null)}+ placeholder="Sample data"+ />+ </div>+ )}+ {canEdit && (+ <div className="flex items-center gap-2">+ <Button+ variant="secondary"+ onClick={reset}+ isDisabled={!isDirty || isSaving}+ >+ Discard+ </Button>+ <Button onClick={save} isLoading={isSaving} isDisabled={!isDirty}>+ Save layout+ </Button>+ </div>+ )}+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/labelConfigs.tsx b/apps/erp/app/components/DocumentTemplateEditor/labelConfigs.tsxnew file mode 100644index 0000000000..22011389ec--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/labelConfigs.tsx@@ -0,0 +1,338 @@+import type {+ FieldBlock,+ LabelBarcodeBlock,+ LabelEntityIdBlock,+ LabelLogoBlock,+ LabelNamedBlock+} from "@carbon/documents/template";+import { DEFAULT_HEADER_OPTIONS } from "@carbon/documents/template";+import {+ Input,+ Label,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue+} from "@carbon/react";+import { useEffect, useState } from "react";+import { useUser } from "~/hooks";+import { ToggleRow } from "./configHelpers";+import { useDocumentTemplate } from "./context";+import { LogoCropper } from "./LogoCropper";+import { MergeFieldMenu } from "./MergeFieldMenu";+import { NumberRow } from "./NumberRow";+import { useHeaderConfig } from "./useHeaderConfig";++/**+ * A single authored line. With a `label` it's a key-value; without, plain text.+ * The value is a single-line string (ZPL-safe) and supports merge fields.+ */+export function FieldConfig({ block }: { block: FieldBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const insertField = (snippet: string) =>+ updateBlock(block.id, { value: (block.value ?? "") + snippet });++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="field-label">Label (optional)</Label>+ <Input+ id="field-label"+ value={block.label ?? ""}+ onChange={(e) => updateBlock(block.id, { label: e.target.value })}+ />+ </div>+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <Label htmlFor="field-value">Value</Label>+ <MergeFieldMenu onInsert={insertField} label="Insert field" />+ </div>+ <Input+ id="field-value"+ value={block.value ?? ""}+ onChange={(e) => updateBlock(block.id, { value: e.target.value })}+ />+ </div>+ </div>+ );+}++const BARCODE_SYMBOLOGIES: { value: string; label: string }[] = [+ { value: "pdf417", label: "PDF417" },+ { value: "code128", label: "Code 128" },+ { value: "datamatrix", label: "Data Matrix" },+ { value: "qrcode", label: "QR Code" }+];++/** Symbology + value + height for a barcode block. */+export function LabelBarcodeConfig({ block }: { block: LabelBarcodeBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const insertField = (snippet: string) =>+ updateBlock(block.id, { value: (block.value ?? "") + snippet });++ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label>Type</Label>+ <Select+ value={block.symbology}+ onValueChange={(value) =>+ updateBlock(block.id, {+ symbology: value as LabelBarcodeBlock["symbology"]+ })+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {BARCODE_SYMBOLOGIES.map((s) => (+ <SelectItem key={s.value} value={s.value}>+ {s.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <Label htmlFor="barcode-value">Value</Label>+ <MergeFieldMenu onInsert={insertField} label="Insert field" />+ </div>+ <Input+ id="barcode-value"+ value={block.value ?? ""}+ onChange={(e) => updateBlock(block.id, { value: e.target.value })}+ />+ </div>+ <div className="flex flex-col gap-1.5">+ <Label>Placement</Label>+ <Select+ value={block.placement}+ onValueChange={(value) =>+ updateBlock(block.id, {+ placement: value as LabelBarcodeBlock["placement"]+ })+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="right">Top-right</SelectItem>+ <SelectItem value="center">Centered</SelectItem>+ <SelectItem value="full">Full width</SelectItem>+ </SelectContent>+ </Select>+ </div>+ <NumberRow+ label="Height (pt)"+ minValue={16}+ maxValue={300}+ value={block.height ?? 56}+ onChange={(v) => updateBlock(block.id, { height: v })}+ />+ </div>+ );+}++/**+ * The document header logo, edited inline (no dialog). Local draft for snappy+ * UI; persists to the header section (debounced) so the crop drag doesn't spam+ * the server. The preview refreshes once the section save revalidates.+ */+export function HeaderLogoConfig() {+ const { company } = useUser();+ const { section, config, submit } = useHeaderConfig();+ const [draft, setDraft] = useState(config);++ // Re-seed when the persisted config changes (revalidation / external edit).+ // biome-ignore lint/correctness/useExhaustiveDependencies: seed on server value only+ useEffect(() => {+ setDraft(config);+ }, [JSON.stringify(config)]);++ // Debounced persist — only when the draft actually diverges from the server+ // value, so re-seeding after a save can't loop back into another submit.+ useEffect(() => {+ if (JSON.stringify(draft) === JSON.stringify(config)) return;+ const t = setTimeout(() => submit(draft), 400);+ return () => clearTimeout(t);+ }, [draft, config, submit]);++ if (!section) {+ return (+ <p className="text-xs text-muted-foreground">+ The header section isn't available yet — save the template first.+ </p>+ );+ }++ const variant = draft.logoVariant ?? "mark";+ const src =+ variant === "icon"+ ? (company?.logoLightIcon ?? company?.logoLight)+ : (company?.logoLight ?? company?.logoLightIcon);+ const set = (patch: Partial<typeof draft>) =>+ setDraft((prev) => ({ ...prev, ...patch }));++ return (+ <div className="flex flex-col gap-3">+ {!draft.showLogo && (+ <p className="text-xs text-muted-foreground">+ Logo is hidden — turn it on with the eye toggle in the list.+ </p>+ )}+ <div className="flex flex-col gap-1.5">+ <Label>Logo</Label>+ <Select+ value={variant}+ onValueChange={(value) =>+ // Switching source invalidates the crop aspect.+ set({+ logoVariant: value as typeof draft.logoVariant,+ logoCrop: undefined+ })+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="mark">Wordmark</SelectItem>+ <SelectItem value="icon">Mark</SelectItem>+ </SelectContent>+ </Select>+ </div>+ {src ? (+ <LogoCropper+ src={src}+ crop={draft.logoCrop}+ onChange={(crop) => set({ logoCrop: crop })}+ />+ ) : (+ <p className="text-xs text-muted-foreground">+ No company logo set — upload one in company settings to crop it.+ </p>+ )}+ <NumberRow+ label="Height (pt)"+ minValue={16}+ maxValue={120}+ value={draft.logoHeight ?? DEFAULT_HEADER_OPTIONS.logoHeight}+ onChange={(v) => set({ logoHeight: v })}+ />+ </div>+ );+}++/** Company logo: B&W toggle + height. */+export function LabelLogoConfig({ block }: { block: LabelLogoBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const { company } = useUser();+ const variant = block.variant ?? "mark";+ const src =+ variant === "icon"+ ? (company?.logoLightIcon ?? company?.logoLight)+ : (company?.logoLight ?? company?.logoLightIcon);+ return (+ <div className="flex flex-col gap-3">+ <div className="flex flex-col gap-1.5">+ <Label>Logo</Label>+ <Select+ value={variant}+ onValueChange={(value) =>+ // Switching source invalidates the old crop's aspect.+ updateBlock(block.id, {+ variant: value as LabelLogoBlock["variant"],+ crop: undefined+ })+ }+ >+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="mark">Wordmark</SelectItem>+ <SelectItem value="icon">Mark</SelectItem>+ </SelectContent>+ </Select>+ </div>+ {src ? (+ <LogoCropper+ src={src}+ crop={block.crop}+ onChange={(crop) => updateBlock(block.id, { crop })}+ />+ ) : (+ <p className="text-xs text-muted-foreground">+ No company logo set — upload one in company settings to crop it.+ </p>+ )}+ <ToggleRow+ label="Print in black & white"+ checked={block.monochrome ?? false}+ onChange={(v) => updateBlock(block.id, { monochrome: v })}+ />+ <NumberRow+ label="Height (pt)"+ minValue={16}+ maxValue={160}+ value={block.height ?? 50}+ onChange={(v) => updateBlock(block.id, { height: v })}+ />+ <p className="text-xs text-muted-foreground">+ Label printers always print the logo in black & white.+ </p>+ </div>+ );+}++/** The identifier line: a single interpolated value (merge fields supported). */+export function LabelEntityIdConfig({ block }: { block: LabelEntityIdBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const insertField = (snippet: string) =>+ updateBlock(block.id, { value: (block.value ?? "") + snippet });++ return (+ <div className="flex flex-col gap-1.5">+ <div className="flex items-center justify-between">+ <Label htmlFor="identifier-value">Value</Label>+ <MergeFieldMenu onInsert={insertField} label="Insert field" />+ </div>+ <Input+ id="identifier-value"+ value={block.value ?? ""}+ onChange={(e) => updateBlock(block.id, { value: e.target.value })}+ />+ </div>+ );+}++const LABEL_FIELD_DEFAULT_NAME: Record<LabelNamedBlock["type"], string> = {+ labelRevision: "Rev",+ labelQuantity: "Qty",+ labelTracking: "S/N"+};++/** Edit the printed name (prefix before the value) of a built-in label field. */+export function LabelFieldNameConfig({ block }: { block: LabelNamedBlock }) {+ const { updateBlock } = useDocumentTemplate();+ const placeholder = LABEL_FIELD_DEFAULT_NAME[block.type];++ return (+ <div className="flex flex-col gap-1.5">+ <Label htmlFor="label-field-name">Field name</Label>+ <Input+ id="label-field-name"+ value={block.label ?? ""}+ placeholder={placeholder}+ onChange={(e) => updateBlock(block.id, { label: e.target.value })}+ />+ <p className="text-xs text-muted-foreground">+ Printed before the value, e.g. “{block.label || placeholder}: …”.+ </p>+ </div>+ );+}diff --git a/apps/erp/app/components/DocumentTemplateEditor/useHeaderConfig.tsx b/apps/erp/app/components/DocumentTemplateEditor/useHeaderConfig.tsxnew file mode 100644index 0000000000..3e2d7ee56f--- /dev/null+++ b/apps/erp/app/components/DocumentTemplateEditor/useHeaderConfig.tsx@@ -0,0 +1,57 @@+import {+ BUILT_IN_SECTION_IDS,+ DEFAULT_HEADER_OPTIONS,+ type HeaderOptions+} from "@carbon/documents/template";+import { useCallback, useMemo } from "react";+import { useFetcher } from "react-router";+import { path } from "~/utils/path";+import { useDocumentTemplate } from "./context";++/** Synthetic selection id for the header's Logo child node in the block tree. */+export const HEADER_LOGO_ID = "__header_logo__";++/**+ * Read + persist the document header's layout config (logo + which fields+ * show). The header is a global shared section, so its config is saved through+ * the `documentSections` action (same as the edit dialog) — the loader then+ * revalidates and the preview re-renders. `patch` merges into the current+ * config so independent fields (logo vs. address toggles) don't clobber.+ */+export function useHeaderConfig() {+ const { sections } = useDocumentTemplate();+ const fetcher = useFetcher();+ const section = sections.find((s) => s.id === BUILT_IN_SECTION_IDS.header);+ const config = useMemo<HeaderOptions>(+ () => ({ ...DEFAULT_HEADER_OPTIONS, ...(section?.config ?? {}) }),+ [section?.config]+ );++ const submit = useCallback(+ (next: HeaderOptions) => {+ if (!section) return;+ const data = new FormData();+ if (section.id) data.set("id", section.id);+ data.set("name", section.name);+ data.set("placement", section.placement);+ data.set(+ "content",+ JSON.stringify(section.content ?? { type: "doc", content: [] })+ );+ data.set("config", JSON.stringify(next));+ fetcher.submit(data, {+ method: "post",+ action: path.to.documentSections+ });+ },+ [section, fetcher]+ );++ /** Merge a partial change into the current config and persist (one-shot). */+ const patch = useCallback(+ (partial: Partial<HeaderOptions>) => submit({ ...config, ...partial }),+ [submit, config]+ );++ return { section, config, submit, patch };+}diff --git a/apps/erp/app/components/Form/Color.tsx b/apps/erp/app/components/Form/Color.tsxindex 4f55e40daa..b0346f8b6d 100644--- a/apps/erp/app/components/Form/Color.tsx+++ b/apps/erp/app/components/Form/Color.tsx@@ -1,58 +1,24 @@import { useControlField, useField } from "@carbon/form";-import {- FormControl,- FormErrorMessage,- FormLabel,- HStack,- useDisclosure,- useOutsideClick-} from "@carbon/react";-import { useRef } from "react";-import { HexColorInput, HexColorPicker } from "react-colorful";+import { FormControl, FormErrorMessage, FormLabel } from "@carbon/react";+import { ColorPicker } from "~/components/ColorPicker";type ColorFieldProps = {name: string;label: string;};-const ColorPicker = ({ name, label }: ColorFieldProps) => {+const Color = ({ name, label }: ColorFieldProps) => {const { error, isOptional: fieldIsOptional } = useField(name);const [value, setValue] = useControlField<string>(name);- const disclosure = useDisclosure();- const containerRef = useRef<HTMLDivElement>(null);-- useOutsideClick({- ref: containerRef,- handler: () => disclosure.onClose()- });return (<FormControl><FormLabel isOptional={fieldIsOptional}>{label}</FormLabel>- <input type="hidden" name={name} value={value} />- <div className="relative" ref={containerRef}>- <HStack>- <button- className="inline-flex items-center justify-center whitespace-nowrap rounded-md font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 h-8 w-8 border border-border"- style={{ background: value }}- onClick={disclosure.onToggle}- type="button"- />- <HexColorInput- color={value}- onChange={setValue}- className="py-0 px-2 h-9 rounded-md outline-2 outline-offset-2 outline-transparent border border-border bg-background text-foreground focus:ring-ring focus:ring-offset-background focus:ring-2 focus:outline-none disabled:pointer-events-none disabled:opacity-50"- />- </HStack>- {disclosure.isOpen && (- <div className="absolute mt-1 top-10 z-50">- <HexColorPicker color={value} onChange={setValue} />- </div>- )}- </div>+ <input type="hidden" name={name} value={value ?? ""} />+ <ColorPicker value={value ?? "#000000"} onChange={setValue} />{error && <FormErrorMessage>{error}</FormErrorMessage>}</FormControl>);};-export default ColorPicker;+export default Color;diff --git a/apps/erp/app/modules/settings/documentPreview.server.ts b/apps/erp/app/modules/settings/documentPreview.server.tsnew file mode 100644index 0000000000..5a4f39f67b--- /dev/null+++ b/apps/erp/app/modules/settings/documentPreview.server.ts@@ -0,0 +1,263 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import type { SupabaseClient } from "@supabase/supabase-js";+import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";+import {+ getShippingMethodsList,+ getStockTransfer,+ getStockTransferLines+} from "~/modules/inventory";+import {+ getSalesInvoice,+ getSalesInvoiceCustomerDetails,+ getSalesInvoiceLines,+ getSalesInvoiceShipment+} from "~/modules/invoicing";+import {+ getPurchaseOrder,+ getPurchaseOrderLines,+ getPurchaseOrderLocations,+ getPurchasingTerms+} from "~/modules/purchasing";+import {+ getQuote,+ getQuoteCustomerDetails,+ getQuoteLinePricesByQuoteId,+ getQuoteLines,+ getQuotePayment,+ getQuoteShipment,+ getSalesOrder,+ getSalesOrderCustomerDetails,+ getSalesOrderLines,+ getSalesTerms+} from "~/modules/sales";+import {+ getAccountsPayableBillingAddress,+ getAccountsReceivableBillingAddress,+ getCompany,+ getCompanySettings+} from "~/modules/settings";++type Client = SupabaseClient<Database>;++export interface PreviewEntity {+ id: string;+ label: string;+}++/** Document types that support previewing against a real record. */+const LIST_CONFIG: Record<+ string,+ { view: string; idColumn: string } | undefined+> = {+ salesInvoice: { view: "salesInvoices", idColumn: "invoiceId" },+ salesOrder: { view: "salesOrders", idColumn: "salesOrderId" },+ purchaseOrder: { view: "purchaseOrders", idColumn: "purchaseOrderId" },+ quote: { view: "quotes", idColumn: "quoteId" },+ stockTransfer: { view: "stockTransfer", idColumn: "stockTransferId" }+};++/** Recent records of a document type, to populate the preview record picker. */+export async function listPreviewEntities(+ client: Client,+ companyId: string,+ documentType: string+): Promise<PreviewEntity[]> {+ const cfg = LIST_CONFIG[documentType];+ if (!cfg) return [];++ const { data } = await client+ .from(cfg.view as never)+ .select(`id, ${cfg.idColumn}`)+ .eq("companyId", companyId)+ .order("createdAt", { ascending: false })+ // Just the latest handful — the picker is for sampling, not browsing.+ .limit(6);++ return ((data ?? []) as Record<string, string>[])+ .filter((row) => row.id)+ .map((row) => ({ id: row.id, label: row[cfg.idColumn] ?? row.id }));+}++const emptyThumbnails: Record<string, string | null> = {};++/**+ * Fetch the real data props a document's PDF needs for a record id, mirroring+ * the live PDF route loaders. Returns null when unsupported / not found, so the+ * preview falls back to sample data.+ */+export async function buildPreviewProps(+ client: Client,+ companyId: string,+ companyGroupId: string,+ documentType: string,+ id: string,+ locale: string+): Promise<Record<string, unknown> | null> {+ const [company, companySettings] = await Promise.all([+ getCompany(client, companyId),+ getCompanySettings(client, companyId)+ ]);+ if (!company.data) return null;+ const base = {+ company: company.data,+ companySettings: companySettings.data,+ locale,+ thumbnails: emptyThumbnails+ };++ switch (documentType) {+ case "salesInvoice": {+ const [+ invoice,+ lines,+ locations,+ shipment,+ terms,+ payment,+ shipping,+ ar+ ] = await Promise.all([+ getSalesInvoice(client, id),+ getSalesInvoiceLines(client, id),+ getSalesInvoiceCustomerDetails(client, id),+ getSalesInvoiceShipment(client, id),+ getSalesTerms(client, companyId),+ getPaymentTermsList(client, companyId),+ getShippingMethodsList(client, companyId),+ getAccountsReceivableBillingAddress(client, companyId)+ ]);+ if (!invoice.data) return null;+ return {+ ...base,+ salesInvoice: invoice.data,+ salesInvoiceLines: lines.data ?? [],+ salesInvoiceLocations: locations.data,+ salesInvoiceShipment: shipment.data,+ accountsReceivableBillingAddress: companySettings.data+ ?.accountsReceivableAddress+ ? ar.data+ : null,+ terms: (terms?.data?.salesTerms ?? {}) as JSONContent,+ paymentTerms: payment.data ?? [],+ shippingMethods: shipping.data ?? []+ };+ }+ case "salesOrder": {+ const [order, lines, locations, terms, payment, shipping, ar] =+ await Promise.all([+ getSalesOrder(client, id),+ getSalesOrderLines(client, id),+ getSalesOrderCustomerDetails(client, id),+ getSalesTerms(client, companyId),+ getPaymentTermsList(client, companyId),+ getShippingMethodsList(client, companyId),+ getAccountsReceivableBillingAddress(client, companyId)+ ]);+ if (!order.data) return null;+ return {+ ...base,+ salesOrder: order.data,+ salesOrderLines: lines.data ?? [],+ salesOrderLocations: locations.data,+ accountsReceivableBillingAddress: companySettings.data+ ?.accountsReceivableAddress+ ? ar.data+ : null,+ terms: (terms?.data?.salesTerms ?? {}) as JSONContent,+ paymentTerms: payment.data ?? [],+ shippingMethods: shipping.data ?? []+ };+ }+ case "purchaseOrder": {+ const [order, lines, locations, terms, payment, ap] = await Promise.all([+ getPurchaseOrder(client, id),+ getPurchaseOrderLines(client, id),+ getPurchaseOrderLocations(client, id),+ getPurchasingTerms(client, companyId),+ getPaymentTermsList(client, companyId),+ getAccountsPayableBillingAddress(client, companyId)+ ]);+ if (!order.data) return null;+ return {+ ...base,+ purchaseOrder: order.data,+ purchaseOrderLines: lines.data ?? [],+ purchaseOrderLocations: locations.data,+ accountsPayableBillingAddress: companySettings.data+ ?.accountsPayableAddress+ ? ap.data+ : null,+ terms: (terms?.data?.purchasingTerms ?? {}) as JSONContent,+ paymentTerms: payment.data ?? []+ };+ }+ case "quote": {+ const [+ quote,+ lines,+ prices,+ locations,+ payment,+ shipment,+ terms,+ paymentTerms,+ shipping+ ] = await Promise.all([+ getQuote(client, id),+ getQuoteLines(client, id),+ getQuoteLinePricesByQuoteId(client, id),+ getQuoteCustomerDetails(client, id),+ getQuotePayment(client, id),+ getQuoteShipment(client, id),+ getSalesTerms(client, companyId),+ getPaymentTermsList(client, companyId),+ getShippingMethodsList(client, companyId)+ ]);+ if (!quote.data) return null;+ let exchangeRate = 1;+ if (quote.data.currencyCode) {+ const currency = await getCurrencyByCode(+ client,+ companyGroupId,+ quote.data.currencyCode+ );+ if (currency.data?.exchangeRate)+ exchangeRate = currency.data.exchangeRate;+ }+ return {+ ...base,+ exchangeRate,+ quote: quote.data,+ quoteLines: lines.data ?? [],+ quoteLinePrices: prices.data ?? [],+ quoteCustomerDetails: locations.data,+ payment: payment?.data,+ shipment: shipment?.data,+ terms: (terms?.data?.salesTerms ?? {}) as JSONContent,+ paymentTerms: paymentTerms.data ?? [],+ shippingMethods: shipping.data ?? []+ };+ }+ case "stockTransfer": {+ const [transfer, lines] = await Promise.all([+ getStockTransfer(client, id),+ getStockTransferLines(client, id)+ ]);+ if (!transfer.data) return null;+ const location = await client+ .from("location")+ .select("*")+ .eq("id", transfer.data.locationId)+ .single();+ return {+ ...base,+ stockTransfer: transfer.data,+ stockTransferLines: lines.data ?? [],+ location: location.data+ };+ }+ default:+ return null;+ }+}diff --git a/apps/erp/app/modules/settings/labelLogo.server.ts b/apps/erp/app/modules/settings/labelLogo.server.tsnew file mode 100644index 0000000000..92f20fd4c3--- /dev/null+++ b/apps/erp/app/modules/settings/labelLogo.server.ts@@ -0,0 +1,20 @@+import { SUPABASE_URL } from "@carbon/auth";+import {+ type ResolvedLabelLogo,+ resolveLabelLogo as resolve+} from "@carbon/documents/labels";+import type { DocumentTemplate } from "@carbon/documents/template";+import type { LabelSize } from "@carbon/utils";++export type { ResolvedLabelLogo };++/** Binds the shared label-logo resolver to this app's Supabase URL. */+export function resolveLabelLogo(+ company: { logoLight?: string | null; logoLightIcon?: string | null } | null,+ template: DocumentTemplate | null,+ labelSize: LabelSize+): Promise<ResolvedLabelLogo | null> {+ return resolve(company, template, labelSize, {+ supabaseUrl: SUPABASE_URL ?? ""+ });+}diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.tsindex 4aac79fa18..678dac7e93 100644--- a/apps/erp/app/modules/settings/settings.models.ts+++ b/apps/erp/app/modules/settings/settings.models.ts@@ -1,3 +1,11 @@+import {+ blockSchema,+ documentSectionPlacementSchema,+ documentSettingsSchema,+ documentTemplateTypeSchema,+ sectionConfigSchema,+ themeSchema+} from "@carbon/documents/template";import { labelSizes } from "@carbon/utils";import { z } from "zod";import { zfd } from "zod-form-data";@@ -198,14 +206,6 @@ export const productLabelSizeValidator = z.object({)});-export const includeThumbnailsOnPurchasingPdfsValidator = z.object({- includeThumbnailsOnPurchasingPdfs: zfd.checkbox()-});--export const includeThumbnailsOnSalesPdfsValidator = z.object({- includeThumbnailsOnSalesPdfs: zfd.checkbox()-});-export const rfqReadyValidator = z.object({rfqReadyNotificationGroup: z.array(z.string().min(1, { message: "Invalid selection" }))@@ -311,10 +311,6 @@ export const webhookValidator = z});-export const jobTravelerSettingsValidator = z.object({- jobTravelerIncludeWorkInstructions: zfd.checkbox()-});-export const consoleSettingsValidator = z.object({consoleEnabled: zfd.checkbox()});@@ -350,3 +346,34 @@ export const accountsReceivableBillingAddressValidator =export const timeCardSettingsValidator = z.object({timeCardEnabled: zfd.checkbox()});++// The editor submits the block list as a JSON string in a hidden field; we+// parse it and validate every block against the shared schema.+const jsonField = <T>(schema: z.ZodType<T>, message: string) =>+ zfd.text(+ z.string().transform((value, ctx) => {+ try {+ return schema.parse(JSON.parse(value));+ } catch {+ ctx.addIssue({ code: z.ZodIssueCode.custom, message });+ return z.NEVER;+ }+ })+ );++export const documentTemplateValidator = zfd.formData({+ documentType: zfd.text(documentTemplateTypeSchema),+ blocks: jsonField(z.array(blockSchema), "Invalid document template blocks"),+ theme: jsonField(themeSchema, "Invalid document theme"),+ settings: jsonField(documentSettingsSchema, "Invalid document settings"),+ headerSectionId: zfd.text(z.string().optional()),+ footerSectionId: zfd.text(z.string().optional())+});++export const documentSectionValidator = zfd.formData({+ id: zfd.text(z.string().optional()),+ name: zfd.text(z.string().min(1)),+ placement: zfd.text(documentSectionPlacementSchema),+ content: jsonField(z.any(), "Invalid section content"),+ config: jsonField(sectionConfigSchema, "Invalid section config").optional()+});diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 3de80fc478..abbcc0cd6c 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -1,5 +1,21 @@import { SUPABASE_URL } from "@carbon/auth";-import type { Database } from "@carbon/database";+import type { Database, Json } from "@carbon/database";+import type {+ DocumentBlock,+ DocumentSectionPlacement,+ DocumentSettings,+ DocumentTemplate,+ DocumentTemplateType,+ DocumentTheme,+ ResolvedSection+} from "@carbon/documents/template";+import {+ CURRENT_TEMPLATE_FORMAT_VERSION,+ getBuiltInSection,+ isBuiltInSectionId,+ toDocumentTemplate+} from "@carbon/documents/template";+import type { JSONContent } from "@carbon/react";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import type { GenericQueryFilters } from "~/utils/query";@@ -463,6 +479,198 @@ export async function getTerms(return client.from("terms").select("*").eq("id", companyId).single();}+export async function getDocumentTemplate(+ client: SupabaseClient<Database>,+ companyId: string,+ documentType: DocumentTemplateType+) {+ return client+ .from("documentTemplate")+ .select("*")+ .eq("companyId", companyId)+ .eq("documentType", documentType)+ .maybeSingle();+}++/**+ * Load a stored document template as a `DocumentTemplate | null` ready to pass+ * to a PDF (which runs it through `resolveTemplate`). Returns null when no row+ * is stored, so the PDF falls back to the type's default.+ */+export async function getDocumentTemplateConfig(+ client: SupabaseClient<Database>,+ companyId: string,+ documentType: DocumentTemplateType+): Promise<DocumentTemplate | null> {+ const stored = await getDocumentTemplate(client, companyId, documentType);+ return toDocumentTemplate(stored.data, documentType);+}++export async function upsertDocumentTemplate(+ client: SupabaseClient<Database>,+ documentTemplate: {+ companyId: string;+ documentType: DocumentTemplateType;+ blocks: DocumentBlock[];+ theme: DocumentTheme;+ settings: DocumentSettings;+ headerSectionId: string | null;+ footerSectionId: string | null;+ createdBy: string;+ updatedBy: string;+ }+) {+ return client.from("documentTemplate").upsert(+ {+ ...documentTemplate,+ // Always persist the current schema version of the JSON we're writing.+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ updatedAt: new Date().toISOString()+ },+ { onConflict: "companyId,documentType" }+ );+}++export async function getDocumentSections(+ client: SupabaseClient<Database>,+ companyId: string+) {+ return client+ .from("documentSection")+ .select("*")+ .eq("companyId", companyId)+ .order("name");+}++export async function getDocumentSection(+ client: SupabaseClient<Database>,+ id: string,+ companyId: string+) {+ return client+ .from("documentSection")+ .select("*")+ .eq("id", id)+ .eq("companyId", companyId)+ .maybeSingle();+}++export async function getDocumentSectionsByIds(+ client: SupabaseClient<Database>,+ companyId: string,+ ids: string[]+) {+ return client+ .from("documentSection")+ .select("*")+ .eq("companyId", companyId)+ .in("id", ids);+}++export async function upsertDocumentSection(+ client: SupabaseClient<Database>,+ documentSection: {+ id?: string;+ companyId: string;+ name: string;+ placement: DocumentSectionPlacement;+ content: JSONContent;+ config?: Record<string, unknown>;+ } & ({ createdBy: string } | { updatedBy: string })+) {+ // Editing a system default forks it into a real row keyed by the same id, so+ // it overrides the built-in everywhere it's referenced. Upsert keeps repeat+ // edits idempotent (the row may or may not exist yet).+ if (documentSection.id && isBuiltInSectionId(documentSection.id)) {+ const actor =+ "createdBy" in documentSection+ ? documentSection.createdBy+ : documentSection.updatedBy;+ return client+ .from("documentSection")+ .upsert(+ {+ id: documentSection.id,+ companyId: documentSection.companyId,+ name: documentSection.name,+ placement: documentSection.placement,+ content: documentSection.content as Json,+ config: (documentSection.config ?? {}) as Json,+ createdBy: actor,+ updatedBy: actor,+ updatedAt: new Date().toISOString()+ },+ { onConflict: "id,companyId" }+ )+ .select("id");+ }++ if ("createdBy" in documentSection) {+ return client+ .from("documentSection")+ .insert({+ ...documentSection,+ content: documentSection.content as Json,+ config: (documentSection.config ?? {}) as Json+ })+ .select("id");+ }+ const { id, companyId, ...update } = documentSection;+ return client+ .from("documentSection")+ .update({+ ...update,+ content: update.content as Json,+ config: (update.config ?? {}) as Json,+ updatedAt: new Date().toISOString()+ })+ .eq("id", id ?? "")+ .eq("companyId", companyId)+ .select("id");+}++export async function deleteDocumentSection(+ client: SupabaseClient<Database>,+ id: string,+ companyId: string+) {+ return client+ .from("documentSection")+ .delete()+ .eq("id", id)+ .eq("companyId", companyId);+}++/** Fetch the given section ids and return them keyed by id for rendering. */+export async function resolveSections(+ client: SupabaseClient<Database>,+ companyId: string,+ ids: string[]+): Promise<Record<string, ResolvedSection>> {+ if (ids.length === 0) return {};+ const map: Record<string, ResolvedSection> = {};++ // System sections live in code, not the DB. Seed them first so a stored row+ // with the same id (a customized/forked default) overrides below.+ for (const id of ids) {+ const builtIn = getBuiltInSection(id);+ if (builtIn) map[id] = builtIn;+ }++ const dbIds = ids.filter((id) => !map[id] || map[id]?.builtIn);+ const { data } = await getDocumentSectionsByIds(client, companyId, dbIds);+ for (const row of (data ?? []) as ResolvedSection[]) {+ map[row.id] = {+ id: row.id,+ name: row.name,+ placement: row.placement,+ content: row.content,+ config: row.config+ };+ }+ return map;+}+export async function getWebhook(client: SupabaseClient<Database>, id: string) {return client.from("webhook").select("*").eq("id", id).single();}@@ -649,17 +857,6 @@ export async function updateIntegrationMetadata(.eq("id", integrationId);}-export async function updateJobTravelerWorkInstructions(- client: SupabaseClient<Database>,- companyId: string,- jobTravelerIncludeWorkInstructions: boolean-) {- return client- .from("companySettings")- .update(sanitize({ jobTravelerIncludeWorkInstructions }))- .eq("id", companyId);-}-export async function updateAccountingEnabledSetting(client: SupabaseClient<Database>,companyId: string,@@ -893,17 +1090,6 @@ export async function updateQuoteLineCategoryMarkups(.eq("id", companyId);}-export async function updatePurchasingPdfThumbnails(- client: SupabaseClient<Database>,- companyId: string,- includeThumbnailsOnPurchasingPdfs: boolean-) {- return client- .from("companySettings")- .update(sanitize({ includeThumbnailsOnPurchasingPdfs }))- .eq("id", companyId);-}-export async function updateRfqReadySetting(client: SupabaseClient<Database>,companyId: string,@@ -915,17 +1101,6 @@ export async function updateRfqReadySetting(.eq("id", companyId);}-export async function updateSalesPdfThumbnails(- client: SupabaseClient<Database>,- companyId: string,- includeThumbnailsOnSalesPdfs: boolean-) {- return client- .from("companySettings")- .update(sanitize({ includeThumbnailsOnSalesPdfs }))- .eq("id", companyId);-}-export async function updateSequence(client: SupabaseClient<Database>,table: string,diff --git a/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx b/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsxindex 6e0e086c8d..cd57a73422 100644--- a/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx+++ b/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx@@ -53,7 +53,11 @@ const CompanyLogoForm = ({ company, target }: CompanyLogoFormProps) => {const isIcon = target === "logoLightIcon" || target === "logoDarkIcon";const isDark = target === "logoDark" || target === "logoDarkIcon";- const shouldResize = target !== "logoWatermark";+ // The watermark is drawn at ~50% page width, so keep it large; everything+ // else is a small inline logo. Either way the resizer re-encodes to PNG,+ // which is the only raster format @react-pdf/renderer can decode (a raw+ // webp/gif upload renders blank in the PDF).+ const resizeHeight = target === "logoWatermark" ? 512 : 128;const getLogoPath = (file: File) => {return `${company.id}/logos/${ROLE_BY_TARGET[target]}/${nanoid()}/${@@ -90,10 +94,10 @@ const CompanyLogoForm = ({ company, target }: CompanyLogoFormProps) => {return;}- if (shouldResize) {+ {const formData = new FormData();formData.append("file", logo);- formData.append("height", "128");+ formData.append("height", String(resizeHeight));formData.append("contained", "true");try {diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsxindex f5ab991a7d..a3d6246981 100644--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx@@ -7,6 +7,7 @@ import {LuCreditCard,LuCrown,LuFactory,+ LuFileText,LuHistory,LuImage,LuKey,@@ -62,6 +63,12 @@ export default function useSettingsSubmodules() {role: "employee",icon: <LuNetwork />},+ {+ name: t`Document Templates`,+ to: path.to.documentTemplates,+ role: "employee",+ icon: <LuFileText />+ },{name: t`Logos`,to: path.to.logos,diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex 492267dbbd..db0f8562af 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json@@ -1,6 +1,6 @@{- "generated": "2026-06-11T15:16:25.602Z",- "totalTools": 1181,+ "generated": "2026-06-12T08:34:31.151Z",+ "totalTools": 1187,"modules": 15,"tools": [{@@ -33064,6 +33064,267 @@"properties": {}}},+ {+ "name": "settings_getDocumentTemplate",+ "module": "settings",+ "classification": "READ",+ "description": "get document template",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "documentType"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "documentType": {}+ },+ "required": [+ "documentType"+ ]+ }+ },+ {+ "name": "settings_getDocumentTemplateConfig",+ "module": "settings",+ "classification": "READ",+ "description": "get document template config",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "documentType"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "documentType": {}+ },+ "required": [+ "documentType"+ ]+ }+ },+ {+ "name": "settings_upsertDocumentTemplate",+ "module": "settings",+ "classification": "WRITE",+ "description": "upsert document template",+ "paramCount": 6,+ "serviceParams": [+ "client",+ "documentTemplate"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "documentType": {},+ "blocks": {+ "type": "array",+ "items": {}+ },+ "theme": {},+ "settings": {},+ "headerSectionId": {+ "type": [+ "string",+ "null"+ ]+ },+ "footerSectionId": {+ "type": [+ "string",+ "null"+ ]+ }+ },+ "required": [+ "documentType",+ "blocks",+ "theme",+ "settings",+ "headerSectionId",+ "footerSectionId"+ ]+ }+ },+ {+ "name": "settings_getDocumentSections",+ "module": "settings",+ "classification": "READ",+ "description": "get document sections",+ "paramCount": 0,+ "serviceParams": [+ "client",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {}+ }+ },+ {+ "name": "settings_getDocumentSection",+ "module": "settings",+ "classification": "READ",+ "description": "get document section",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "settings_getDocumentSectionsByIds",+ "module": "settings",+ "classification": "READ",+ "description": "get document sections by ids",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "ids"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "ids"+ ]+ }+ },+ {+ "name": "settings_upsertDocumentSection",+ "module": "settings",+ "classification": "WRITE",+ "description": "upsert document section",+ "paramCount": 6,+ "serviceParams": [+ "client",+ "documentSection"+ ],+ "injectAuth": [+ "companyId",+ "createdBy",+ "updatedBy"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "placement": {},+ "content": {},+ "config": {},+ "} & ({ createdBy": {}+ },+ "required": [+ "name",+ "placement",+ "content",+ "} & ({ createdBy"+ ]+ }+ },+ {+ "name": "settings_deleteDocumentSection",+ "module": "settings",+ "classification": "DESTRUCTIVE",+ "description": "delete document section",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "id",+ "companyId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ }+ },+ "required": [+ "id"+ ]+ }+ },+ {+ "name": "settings_resolveSections",+ "module": "settings",+ "classification": "WRITE",+ "description": "resolve sections",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "companyId",+ "ids"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ },+ "required": [+ "ids"+ ]+ }+ },{"name": "settings_getWebhook","module": "settings",@@ -33437,33 +33698,6 @@]}},- {- "name": "settings_updateJobTravelerWorkInstructions",- "module": "settings",- "classification": "WRITE",- "description": "update job traveler work instructions",- "paramCount": 1,- "serviceParams": [- "client",- "companyId",- "jobTravelerIncludeWorkInstructions"- ],- "injectAuth": [- "companyId",- "updatedBy"- ],- "schema": {- "type": "object",- "properties": {- "jobTravelerIncludeWorkInstructions": {- "type": "boolean"- }- },- "required": [- "jobTravelerIncludeWorkInstructions"- ]- }- },{"name": "settings_updateAccountingEnabledSetting","module": "settings",@@ -34038,33 +34272,6 @@]}},- {- "name": "settings_updatePurchasingPdfThumbnails",- "module": "settings",- "classification": "WRITE",- "description": "update purchasing pdf thumbnails",- "paramCount": 1,- "serviceParams": [- "client",- "companyId",- "includeThumbnailsOnPurchasingPdfs"- ],- "injectAuth": [- "companyId",- "updatedBy"- ],- "schema": {- "type": "object",- "properties": {- "includeThumbnailsOnPurchasingPdfs": {- "type": "boolean"- }- },- "required": [- "includeThumbnailsOnPurchasingPdfs"- ]- }- },{"name": "settings_updateRfqReadySetting","module": "settings",@@ -34095,33 +34302,6 @@]}},- {- "name": "settings_updateSalesPdfThumbnails",- "module": "settings",- "classification": "WRITE",- "description": "update sales pdf thumbnails",- "paramCount": 1,- "serviceParams": [- "client",- "companyId",- "includeThumbnailsOnSalesPdfs"- ],- "injectAuth": [- "companyId",- "updatedBy"- ],- "schema": {- "type": "object",- "properties": {- "includeThumbnailsOnSalesPdfs": {- "type": "boolean"- }- },- "required": [- "includeThumbnailsOnSalesPdfs"- ]- }- },{"name": "settings_updateSequence","module": "settings",diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsxindex fa7251b9be..0e3827b0e5 100644--- a/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx@@ -3,7 +3,10 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";import { labelSizes } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";-import { getCompany } from "~/modules/settings";+import { redirect } from "react-router";+import { getCompany, getDocumentTemplateConfig } from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";+import { path } from "~/utils/path";import { getEntityLabelData } from "./labels.server";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -29,7 +32,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const labelParam = url.searchParams.get("labelSize");const labelSizeId =- labelParam || companySettings?.data?.productLabelSize || "avery5163";+ labelParam || companySettings?.data?.productLabelSize || "avery5160";const labelSize = labelSizes.find((size) => size.id === labelSizeId);@@ -37,8 +40,27 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Invalid label size");}+ if (labelSize.zpl) {+ throw redirect(+ path.to.file.trackedEntityLabelZpl(id, { labelSize: labelSize.id })+ );+ }++ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );+ const logo = await resolveLabelLogo(company.data, template, labelSize);+const stream = await renderToStream(- <ProductLabelPDF items={[labelItem!]} labelSize={labelSize} />+ <ProductLabelPDF+ items={[labelItem!]}+ labelSize={labelSize}+ template={template}+ company={company.data as any}+ logo={logo}+ />);const body: Buffer = await new Promise((resolve, reject) => {diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsxindex f73a553d37..df708b57eb 100644--- a/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx@@ -3,6 +3,8 @@ import { generateProductLabelZPL } from "@carbon/documents/zpl";import { labelSizes } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";+import { getCompany, getDocumentTemplateConfig } from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";import { path } from "~/utils/path";import { getEntityLabelData } from "./labels.server";@@ -37,7 +39,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const zplOutput = generateProductLabelZPL(labelItem!, labelSize);+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);++ const zplOutput = generateProductLabelZPL(+ labelItem!,+ labelSize,+ template,+ logo+ );const headers = new Headers({"Content-Type": "application/zpl",diff --git a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsxindex d7e155eba7..69458abccb 100644--- a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx@@ -1,5 +1,10 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { IssuePDF } from "@carbon/documents/pdf";+import { ensureFont, IssuePDF } from "@carbon/documents/pdf";+import {+ collectSectionIds,+ resolveTemplate,+ toDocumentTemplate+} from "@carbon/documents/template";import { getPreferenceHeaders } from "@carbon/react";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";@@ -13,7 +18,11 @@ import {getIssueTypes,getRequiredActionsList} from "~/modules/quality";-import { getCompany } from "~/modules/settings";+import {+ getCompany,+ getDocumentTemplate,+ resolveSections+} from "~/modules/settings";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -157,6 +166,20 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { locale } = getPreferenceHeaders(request);+ const documentTemplate = await getDocumentTemplate(+ client,+ companyId,+ "issue"+ );+ const templateConfig = toDocumentTemplate(documentTemplate.data, "issue");+ const resolved = resolveTemplate("issue", templateConfig);+ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolved)+ );+ await ensureFont(resolved.settings.fontFamily);+const stream = await renderToStream(<IssuePDFcompany={company.data as any}@@ -171,6 +194,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {assignees={userNames}jobOperationStepRecords={jobOperationStepRecords.data ?? []}operationToJobId={operationToJobId}+ template={templateConfig}+ sections={sections}/>);diff --git a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsxindex e6ec71e161..e7be575f46 100644--- a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx+++ b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx@@ -1,6 +1,16 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { Footer, JobTravelerPageContent } from "@carbon/documents/pdf";+import {+ ensureFont,+ Footer,+ JobTravelerPageContent+} from "@carbon/documents/pdf";+import {+ collectSectionIds,+ interpolateContent,+ resolveTemplate,+ toDocumentTemplate+} from "@carbon/documents/template";import type { JSONContent } from "@carbon/react";import { getPreferenceHeaders } from "@carbon/react";import { flattenTree, generateBomIds } from "@carbon/utils";@@ -18,7 +28,11 @@ import {getJobOperationsByMethodId,getTrackedEntityByJobId} from "~/modules/production/production.service";-import { getCompany, getCompanySettings } from "~/modules/settings";+import {+ getCompany,+ getDocumentTemplate,+ resolveSections+} from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -54,18 +68,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Failed to load job make methods");}- const [company, companySettings] = await Promise.all([- getCompany(serviceRole, job.data.companyId ?? ""),- getCompanySettings(serviceRole, job.data.companyId ?? "")- ]);+ const company = await getCompany(serviceRole, job.data.companyId ?? "");if (company.error) {console.error(company.error);throw new Error("Failed to load company");}- if (companySettings.error) {- console.error(companySettings.error);- throw new Error("Failed to load company settings");- }const customer = await serviceRole.from("customer")@@ -146,6 +153,36 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}));+ // Resolve the customizable template (block order / visibility / font /+ // footer) and the shared header/footer sections.+ const documentTemplate = await getDocumentTemplate(+ serviceRole,+ companyId,+ "jobTraveler"+ );+ const templateConfig = toDocumentTemplate(+ documentTemplate.data,+ "jobTraveler"+ );+ const resolved = resolveTemplate("jobTraveler", templateConfig);+ const sections = await resolveSections(+ serviceRole,+ companyId,+ collectSectionIds(resolved)+ );+ await ensureFont(resolved.settings.fontFamily);++ const footerSectionContent = resolved.footerSectionId+ ? sections[resolved.footerSectionId]?.content+ : undefined;+ const footerContent = footerSectionContent+ ? interpolateContent(footerSectionContent, {+ "job.number": job.data.jobId ?? "",+ "company.name": company.data.name ?? ""+ })+ : undefined;+ const showFooter = resolved.footerSectionId !== null;+// Register fonts (same as Template component)Font.register({family: "Inter",@@ -174,7 +211,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const styles = StyleSheet.create({body: {- fontFamily: "Inter",+ fontFamily: resolved.settings.fontFamily,padding: "20px 40px 50px 40px",color: "#000000",backgroundColor: "#FFFFFF"@@ -203,11 +240,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {notes={index === 0 ? jobNotes : undefined}thumbnail={data.thumbnail}methodRevision={data.makeMethod.version?.toString()}- includeWorkInstructions={- companySettings.data?.jobTravelerIncludeWorkInstructions ?? false- }+ template={templateConfig}+ sections={sections}/>- <Footer />+ {showFooter && (+ <Footer+ documentId={job.data.jobId}+ content={footerContent}+ showPageNumbers={resolved.settings.showPageNumbers}+ pageNumberFormat={resolved.settings.pageNumberFormat}+ showRegistrationLine={resolved.settings.showRegistrationLine}+ />+ )}</Page>))}</Document>diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsxindex 47e67f3a31..0bb894b558 100644--- a/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx@@ -4,7 +4,8 @@ import { labelSizes } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";import { getTrackedEntitiesByMakeMethodId } from "~/modules/inventory";-import { getCompany } from "~/modules/settings";+import { getCompany, getDocumentTemplateConfig } from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";import { getCompanySettings } from "~/modules/settings/settings.service";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -75,8 +76,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const logo = await resolveLabelLogo(company.data, template, labelSize);+const stream = await renderToStream(- <ProductLabelPDF items={items ?? []} labelSize={labelSize} />+ <ProductLabelPDF+ items={items ?? []}+ labelSize={labelSize}+ template={template}+ company={company.data as any}+ logo={logo}+ />);const body: Buffer = await new Promise((resolve, reject) => {diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsxindex 7a6ac8e980..5fdae101e9 100644--- a/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx@@ -4,7 +4,12 @@ import { labelSizes } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";import { getTrackedEntitiesByMakeMethodId } from "~/modules/inventory";-import { getCompanySettings } from "~/modules/settings";+import {+ getCompany,+ getCompanySettings,+ getDocumentTemplateConfig+} from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";import { path } from "~/utils/path";@@ -82,9 +87,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Invalid label size or missing ZPL configuration");}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);+// Generate ZPL for each itemconst zplCommands = items.map((item) =>- generateProductLabelZPL(item, labelSize)+ generateProductLabelZPL(item, labelSize, template, logo));const zplOutput = zplCommands.join("\n");diff --git a/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx b/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsxindex 73d2fefef9..da59ab8c54 100644--- a/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx+++ b/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx@@ -1,5 +1,11 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { PurchaseOrderPDF } from "@carbon/documents/pdf";+import { ensureFont, PurchaseOrderPDF } from "@carbon/documents/pdf";+import {+ collectSectionIds,+ resolveTemplate,+ templateShowsThumbnails,+ toDocumentTemplate+} from "@carbon/documents/template";import type { JSONContent } from "@carbon/react";import { getPreferenceHeaders } from "@carbon/react";import { renderToStream } from "@react-pdf/renderer";@@ -14,7 +20,9 @@ import {import {getAccountsPayableBillingAddress,getCompany,- getCompanySettings+ getCompanySettings,+ getDocumentTemplate,+ resolveSections} from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";@@ -34,7 +42,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {purchaseOrderLines,purchaseOrderLocations,terms,- paymentTerms+ paymentTerms,+ documentTemplate] = await Promise.all([getCompany(client, companyId),getCompanySettings(client, companyId),@@ -43,7 +52,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getPurchaseOrderLines(client, orderId),getPurchaseOrderLocations(client, orderId),getPurchasingTerms(client, companyId),- getPaymentTermsList(client, companyId)+ getPaymentTermsList(client, companyId),+ getDocumentTemplate(client, companyId, "purchaseOrder")]);if (company.error) {@@ -76,8 +86,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Failed to load purchase order");}- const showThumbnails =- companySettings.data?.includeThumbnailsOnPurchasingPdfs ?? true;+ const templateConfig = toDocumentTemplate(+ documentTemplate.data,+ "purchaseOrder"+ );+ const showThumbnails = templateShowsThumbnails(+ templateConfig,+ "purchaseOrder"+ );let thumbnails: Record<string, string | null> = {};@@ -115,6 +131,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { locale } = getPreferenceHeaders(request);+ const resolved = resolveTemplate("purchaseOrder", templateConfig);+ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolved)+ );+ await ensureFont(resolved.settings.fontFamily);+const stream = await renderToStream(<PurchaseOrderPDFcompany={company.data as any}@@ -131,6 +155,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {purchaseOrderLocations={purchaseOrderLocations.data}terms={(terms?.data?.purchasingTerms || {}) as JSONContent}thumbnails={thumbnails}+ template={templateConfig}+ sections={sections}/>);diff --git a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsxindex 3a928a9a04..ba9ca1fe62 100644--- a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx@@ -1,5 +1,11 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { QuotePDF } from "@carbon/documents/pdf";+import { ensureFont, QuotePDF } from "@carbon/documents/pdf";+import {+ collectSectionIds,+ resolveTemplate,+ templateShowsThumbnails,+ toDocumentTemplate+} from "@carbon/documents/template";import type { JSONContent } from "@carbon/react";import { getPreferenceHeaders } from "@carbon/react";import { renderToStream } from "@react-pdf/renderer";@@ -18,7 +24,9 @@ import {import {getAccountsReceivableBillingAddress,getCompany,- getCompanySettings+ getCompanySettings,+ getDocumentTemplate,+ resolveSections} from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";@@ -47,7 +55,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {quoteShipment,paymentTerms,terms,- shippingMethods+ shippingMethods,+ documentTemplate] = await Promise.all([getCompany(client, companyId),getCompanySettings(client, companyId),@@ -60,7 +69,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getQuoteShipment(client, id),getPaymentTermsList(client, companyId),getSalesTerms(client, companyId),- getShippingMethodsList(client, companyId)+ getShippingMethodsList(client, companyId),+ getDocumentTemplate(client, companyId, "quote")]);if (company.error) {@@ -87,8 +97,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Failed to load quote");}- const showThumbnails =- companySettings.data?.includeThumbnailsOnSalesPdfs ?? true;+ const templateConfig = toDocumentTemplate(documentTemplate.data, "quote");+ const showThumbnails = templateShowsThumbnails(templateConfig, "quote");let thumbnails: Record<string, string | null> = {};@@ -136,6 +146,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}+ const resolved = resolveTemplate("quote", templateConfig);+ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolved)+ );+ await ensureFont(resolved.settings.fontFamily);+const stream = await renderToStream(<QuotePDFcompany={company.data as any}@@ -157,6 +175,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {shippingMethods={shippingMethods.data ?? []}terms={(terms?.data?.salesTerms ?? {}) as JSONContent}thumbnails={thumbnails}+ template={templateConfig}+ sections={sections}/>);diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsxindex 137f1e01b5..da93208404 100644--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx@@ -5,7 +5,8 @@ import { labelSizes } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";import { getReceiptTracking } from "~/modules/inventory";-import { getCompany } from "~/modules/settings";+import { getCompany, getDocumentTemplateConfig } from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";import { getCompanySettings } from "~/modules/settings/settings.service";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -79,8 +80,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const logo = await resolveLabelLogo(company.data, template, labelSize);+const stream = await renderToStream(- <ProductLabelPDF items={items ?? []} labelSize={labelSize} />+ <ProductLabelPDF+ items={items ?? []}+ labelSize={labelSize}+ template={template}+ company={company.data as any}+ logo={logo}+ />);const body: Buffer = await new Promise((resolve, reject) => {diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsxindex 69a12e3b88..73bd7b7dfc 100644--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx@@ -5,6 +5,8 @@ import { labelSizes } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";import { getReceiptTracking } from "~/modules/inventory/inventory.service";+import { getCompany, getDocumentTemplateConfig } from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";import { getCompanySettings } from "~/modules/settings/settings.service";import { path } from "~/utils/path";@@ -85,9 +87,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Invalid label size or missing ZPL configuration");}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);+// Generate ZPL for each itemconst zplCommands = items.map((item) =>- generateProductLabelZPL(item, labelSize)+ generateProductLabelZPL(item, labelSize, template, logo));const zplOutput = zplCommands.join("\n");diff --git a/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsxindex f92f23d091..825f68b41b 100644--- a/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx@@ -1,5 +1,11 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { SalesInvoicePDF } from "@carbon/documents/pdf";+import { ensureFont, SalesInvoicePDF } from "@carbon/documents/pdf";+import {+ collectSectionIds,+ resolveTemplate,+ templateShowsThumbnails,+ toDocumentTemplate+} from "@carbon/documents/template";import type { JSONContent } from "@carbon/react";import { getPreferenceHeaders } from "@carbon/react";import { renderToStream } from "@react-pdf/renderer";@@ -16,7 +22,9 @@ import { getSalesOrdersByIds, getSalesTerms } from "~/modules/sales";import {getAccountsReceivableBillingAddress,getCompany,- getCompanySettings+ getCompanySettings,+ getDocumentTemplate,+ resolveSections} from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";@@ -38,7 +46,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {salesInvoiceShipment,terms,paymentTerms,- shippingMethods+ shippingMethods,+ documentTemplate] = await Promise.all([getCompany(client, companyId),getCompanySettings(client, companyId),@@ -49,7 +58,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getSalesInvoiceShipment(client, id),getSalesTerms(client, companyId),getPaymentTermsList(client, companyId),- getShippingMethodsList(client, companyId)+ getShippingMethodsList(client, companyId),+ getDocumentTemplate(client, companyId, "salesInvoice")]);if (company.error) {@@ -87,8 +97,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Failed to load sales order");}- const showThumbnails =- companySettings.data?.includeThumbnailsOnSalesPdfs ?? true;+ const templateConfig = toDocumentTemplate(+ documentTemplate.data,+ "salesInvoice"+ );+ const showThumbnails = templateShowsThumbnails(+ templateConfig,+ "salesInvoice"+ );let thumbnails: Record<string, string | null> = {};@@ -148,6 +164,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { locale } = getPreferenceHeaders(request);+ // Resolve against the effective template (default when nothing is stored) so+ // built-in / forked header & footer sections render even before a company+ // saves a custom layout.+ const resolved = resolveTemplate("salesInvoice", templateConfig);+ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolved)+ );++ // Register the chosen Google font (no-op for built-ins / Inter) before render.+ await ensureFont(resolved.settings.fontFamily);+const stream = await renderToStream(<SalesInvoicePDFcompany={company.data as any}@@ -173,6 +202,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {shippingMethods={shippingMethods.data ?? []}title="Sales Invoice"thumbnails={thumbnails}+ template={templateConfig}+ sections={sections}/>);diff --git a/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsxindex 27c2e3892c..3042888ac0 100644--- a/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx@@ -1,5 +1,11 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { SalesOrderPDF } from "@carbon/documents/pdf";+import { ensureFont, SalesOrderPDF } from "@carbon/documents/pdf";+import {+ collectSectionIds,+ resolveTemplate,+ templateShowsThumbnails,+ toDocumentTemplate+} from "@carbon/documents/template";import type { JSONContent } from "@carbon/react";import { getPreferenceHeaders } from "@carbon/react";import { renderToStream } from "@react-pdf/renderer";@@ -15,7 +21,9 @@ import {import {getAccountsReceivableBillingAddress,getCompany,- getCompanySettings+ getCompanySettings,+ getDocumentTemplate,+ resolveSections} from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";@@ -36,7 +44,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {salesOrderLocations,terms,paymentTerms,- shippingMethods+ shippingMethods,+ documentTemplate] = await Promise.all([getCompany(client, companyId),getCompanySettings(client, companyId),@@ -46,7 +55,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getSalesOrderCustomerDetails(client, id),getSalesTerms(client, companyId),getPaymentTermsList(client, companyId),- getShippingMethodsList(client, companyId)+ getShippingMethodsList(client, companyId),+ getDocumentTemplate(client, companyId, "salesOrder")]);if (company.error) {@@ -79,8 +89,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Failed to load sales order");}- const showThumbnails =- companySettings.data?.includeThumbnailsOnSalesPdfs ?? true;+ const templateConfig = toDocumentTemplate(+ documentTemplate.data,+ "salesOrder"+ );+ const showThumbnails = templateShowsThumbnails(templateConfig, "salesOrder");let thumbnails: Record<string, string | null> = {};@@ -118,6 +131,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { locale } = getPreferenceHeaders(request);+ const resolved = resolveTemplate("salesOrder", templateConfig);+ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolved)+ );+ await ensureFont(resolved.settings.fontFamily);+const stream = await renderToStream(<SalesOrderPDFcompany={company.data as any}@@ -141,6 +162,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {shippingMethods={shippingMethods.data ?? []}title="Sales Order"thumbnails={thumbnails}+ template={templateConfig}+ sections={sections}/>);diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsxindex 972078000a..1c913c2507 100644--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx@@ -5,7 +5,8 @@ import { labelSizes } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";import { getShipmentTracking } from "~/modules/inventory";-import { getCompany } from "~/modules/settings";+import { getCompany, getDocumentTemplateConfig } from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";import { getCompanySettings } from "~/modules/settings/settings.service";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -116,8 +117,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const logo = await resolveLabelLogo(company.data, template, labelSize);+const stream = await renderToStream(- <ProductLabelPDF items={items ?? []} labelSize={labelSize} />+ <ProductLabelPDF+ items={items ?? []}+ labelSize={labelSize}+ template={template}+ company={company.data as any}+ logo={logo}+ />);const body: Buffer = await new Promise((resolve, reject) => {diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsxindex 3b4b480df0..13f7d46f42 100644--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx@@ -5,6 +5,8 @@ import { labelSizes } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";import { getShipmentTracking } from "~/modules/inventory/inventory.service";+import { getCompany, getDocumentTemplateConfig } from "~/modules/settings";+import { resolveLabelLogo } from "~/modules/settings/labelLogo.server";import { getCompanySettings } from "~/modules/settings/settings.service";import { path } from "~/utils/path";@@ -122,9 +124,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Invalid label size or missing ZPL configuration");}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);+// Generate ZPL for each itemconst zplCommands = items.map((item) =>- generateProductLabelZPL(item, labelSize)+ generateProductLabelZPL(item, labelSize, template, logo));const zplOutput = zplCommands.join("\n");diff --git a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsxindex 02f3a71e50..168939f9c4 100644--- a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx@@ -1,6 +1,12 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { PackingSlipPDF } from "@carbon/documents/pdf";+import { ensureFont, PackingSlipPDF } from "@carbon/documents/pdf";+import {+ collectSectionIds,+ resolveTemplate,+ templateShowsThumbnails,+ toDocumentTemplate+} from "@carbon/documents/template";import type { JSONContent } from "@carbon/react";import { getPreferenceHeaders } from "@carbon/react";import { renderToStream } from "@react-pdf/renderer";@@ -23,7 +29,11 @@ import {getSalesOrderShipment,getSalesTerms} from "~/modules/sales";-import { getCompany, getCompanySettings } from "~/modules/settings";+import {+ getCompany,+ getDocumentTemplate,+ resolveSections+} from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -34,14 +44,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { id } = params;if (!id) throw new Error("Could not find id");- const [company, companySettings, shipment, shipmentLines] = await Promise.all(- [- getCompany(client, companyId),- getCompanySettings(client, companyId),- getShipment(client, id),- getShipmentLinesWithDetails(client, id)- ]- );+ const [company, shipment, shipmentLines] = await Promise.all([+ getCompany(client, companyId),+ getShipment(client, id),+ getShipmentLinesWithDetails(client, id)+ ]);if (company.error) {console.error(company.error);@@ -74,6 +81,24 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { locale } = getPreferenceHeaders(request);+ const documentTemplate = await getDocumentTemplate(+ client,+ companyId,+ "packingSlip"+ );+ const templateConfig = toDocumentTemplate(+ documentTemplate.data,+ "packingSlip"+ );+ const resolvedTemplate = resolveTemplate("packingSlip", templateConfig);+ const showThumbnails = templateShowsThumbnails(templateConfig, "packingSlip");+ const templateSections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolvedTemplate)+ );+ await ensureFont(resolvedTemplate.settings.fontFamily);+switch (shipment.data.sourceDocument) {case "Sales Order": {const [salesOrder, salesOrderShipment] = await Promise.all([@@ -114,7 +139,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {let thumbnails: Record<string, string | null> = {};- if (companySettings.data?.includeThumbnailsOnSalesPdfs ?? true) {+ if (showThumbnails) {const thumbnailPaths = shipmentLines.data?.reduce<Record<string, string | null>>((acc, line) => {@@ -171,6 +196,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {trackedEntities={shipmentTracking.data ?? []}title="Packing Slip"thumbnails={thumbnails}+ template={templateConfig}+ sections={templateSections}/>);@@ -233,7 +260,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {let thumbnails: Record<string, string | null> = {};- if (companySettings.data?.includeThumbnailsOnSalesPdfs ?? true) {+ if (showThumbnails) {const thumbnailPaths = shipmentLines.data?.reduce<Record<string, string | null>>((acc, line) => {@@ -290,6 +317,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {trackedEntities={shipmentTracking.data ?? []}title="Packing Slip"thumbnails={thumbnails}+ template={templateConfig}+ sections={templateSections}/>);@@ -347,7 +376,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {let poThumbnails: Record<string, string | null> = {};- if (companySettings.data?.includeThumbnailsOnPurchasingPdfs ?? true) {+ if (showThumbnails) {const poThumbnailPaths = shipmentLines.data?.reduce<Record<string, string | null>>((acc, line) => {@@ -404,6 +433,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {trackedEntities={poShipmentTracking.data ?? []}title="Packing Slip"thumbnails={poThumbnails}+ template={templateConfig}+ sections={templateSections}/>);diff --git a/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsxindex a03654ef1c..6b1769e83b 100644--- a/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx@@ -1,10 +1,19 @@import { requirePermissions } from "@carbon/auth/auth.server";-import { StockTransferPDF } from "@carbon/documents/pdf";+import { ensureFont, StockTransferPDF } from "@carbon/documents/pdf";+import {+ collectSectionIds,+ resolveTemplate,+ toDocumentTemplate+} from "@carbon/documents/template";import { getPreferenceHeaders } from "@carbon/react";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";import { getStockTransfer, getStockTransferLines } from "~/modules/inventory";-import { getCompany } from "~/modules/settings";+import {+ getCompany,+ getDocumentTemplate,+ resolveSections+} from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -56,6 +65,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { locale } = getPreferenceHeaders(request);+ const documentTemplate = await getDocumentTemplate(+ client,+ companyId,+ "stockTransfer"+ );+ const templateConfig = toDocumentTemplate(+ documentTemplate.data,+ "stockTransfer"+ );+ const resolved = resolveTemplate("stockTransfer", templateConfig);+ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds(resolved)+ );+ await ensureFont(resolved.settings.fontFamily);+// Get thumbnails for itemsconst thumbnailPaths = stockTransferLines.data?.reduce<Record<string, string | null>@@ -101,6 +127,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}title="Stock Transfer"thumbnails={thumbnails}+ template={templateConfig}+ sections={sections}/>);diff --git a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsxindex 590994b239..2e1f53f13f 100644--- a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx+++ b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx@@ -13,7 +13,7 @@ import {getJobOperationsByMethodId,getTrackedEntityByJobId} from "~/modules/production/production.service";-import { getCompany, getCompanySettings } from "~/modules/settings";+import { getCompany } from "~/modules/settings";import { getBase64ImageFromSupabase } from "~/modules/shared";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -32,10 +32,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Failed to load job make method");}- const [company, job, companySettings] = await Promise.all([+ const [company, job] = await Promise.all([getCompany(serviceRole, jobMakeMethod.data?.companyId ?? ""),- getJob(serviceRole, jobMakeMethod.data?.jobId ?? ""),- getCompanySettings(serviceRole, jobMakeMethod.data?.companyId ?? "")+ getJob(serviceRole, jobMakeMethod.data?.jobId ?? "")]);if (company.error) {@@ -48,11 +47,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Failed to load job");}- if (companySettings.error) {- console.error(companySettings.error);- throw new Error("Failed to load company settings");- }-const [jobOperations, customer, item] = await Promise.all([getJobOperationsByMethodId(serviceRole, id),serviceRole@@ -138,9 +132,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {notes={jobNotes}thumbnail={thumbnail}title="Job Traveler"- includeWorkInstructions={- companySettings.data?.jobTravelerIncludeWorkInstructions ?? false- }/>);diff --git a/apps/erp/app/routes/x+/settings+/production.tsx b/apps/erp/app/routes/x+/settings+/production.tsxindex f1880a4a53..ad30244cad 100644--- a/apps/erp/app/routes/x+/settings+/production.tsx+++ b/apps/erp/app/routes/x+/settings+/production.tsx@@ -10,24 +10,18 @@ import {CardHeader,CardTitle,Heading,- HStack,Label,ScrollArea,- Switch,toast,VStack} from "@carbon/react";import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useEffect } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useFetcher, useLoaderData } from "react-router";import { Users } from "~/components/Form";-import {- getCompanySettings,- jobCompletedValidator,- updateJobTravelerWorkInstructions-} from "~/modules/settings";+import { getCompanySettings, jobCompletedValidator } from "~/modules/settings";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";@@ -86,19 +80,6 @@ export async function action({ request }: ActionFunctionArgs) {return { success: true, message: "Job notification settings updated" };}- if (intent === "jobTraveler") {- const enabled = formData.get("enabled") === "true";- const update = await updateJobTravelerWorkInstructions(- client,- companyId,- enabled- );-- if (update.error) return { success: false, message: update.error.message };-- return { success: true, message: "Job traveler settings updated" };- }-return { success: false, message: "Unknown intent" };}@@ -106,7 +87,6 @@ export default function ProductionSettingsRoute() {const { t } = useLingui();const { companySettings } = useLoaderData<typeof loader>();const fetcher = useFetcher<typeof action>();- const toggleFetcher = useFetcher<typeof action>();useEffect(() => {if (fetcher.data?.success === true && fetcher?.data?.message) {@@ -118,25 +98,6 @@ export default function ProductionSettingsRoute() {}}, [fetcher.data?.message, fetcher.data?.success]);- useEffect(() => {- if (toggleFetcher.data?.success === true && toggleFetcher?.data?.message) {- toast.success(toggleFetcher.data.message);- }- if (toggleFetcher.data?.success === false && toggleFetcher?.data?.message) {- toast.error(toggleFetcher.data.message);- }- }, [toggleFetcher.data?.message, toggleFetcher.data?.success]);-- const handleJobTravelerToggle = useCallback(- (checked: boolean) => {- toggleFetcher.submit(- { intent: "jobTraveler", enabled: String(checked) },- { method: "POST" }- );- },- [toggleFetcher]- );-return (<ScrollArea className="w-full h-[calc(100dvh-49px)]"><VStack@@ -204,48 +165,6 @@ export default function ProductionSettingsRoute() {</CardFooter></ValidatedForm></Card>-- <Card>- <CardHeader>- <CardTitle>- <Trans>Job Traveler</Trans>- </CardTitle>- <CardDescription>- <Trans>- Configure the content displayed on job traveler PDFs.- </Trans>- </CardDescription>- </CardHeader>- <CardContent>- <HStack className="justify-between items-center">- <VStack className="items-start" spacing={1}>- <span className="font-medium">- {companySettings.jobTravelerIncludeWorkInstructions ? (- <Trans>Work instructions are included</Trans>- ) : (- <Trans>Work instructions are not included</Trans>- )}- </span>- <span className="text-sm text-muted-foreground">- {companySettings.jobTravelerIncludeWorkInstructions ? (- <Trans>Job traveler PDFs include work instructions.</Trans>- ) : (- <Trans>- Enable to include work instructions on job traveler PDFs.- </Trans>- )}- </span>- </VStack>- <Switch- checked={- companySettings.jobTravelerIncludeWorkInstructions ?? false- }- onCheckedChange={handleJobTravelerToggle}- disabled={toggleFetcher.state !== "idle"}- />- </HStack>- </CardContent>- </Card></VStack></ScrollArea>);diff --git a/apps/erp/app/routes/x+/settings+/purchasing.tsx b/apps/erp/app/routes/x+/settings+/purchasing.tsxindex b66afd28c7..a65735d52c 100644--- a/apps/erp/app/routes/x+/settings+/purchasing.tsx+++ b/apps/erp/app/routes/x+/settings+/purchasing.tsx@@ -1,4 +1,4 @@-import { error, useCarbon } from "@carbon/auth";+import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import {@@ -9,44 +9,34 @@ import {ValidatedForm,validator} from "@carbon/form";-import type { JSONContent } from "@carbon/react";import {- Badge,Card,- CardAction,CardContent,CardDescription,CardFooter,CardHeader,CardTitle,- generateHTML,Heading,HStack,Label,ScrollArea,Switch,toast,- useDebounce,VStack} from "@carbon/react";-import { Editor } from "@carbon/react/Editor";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect, useState } from "react";-import { LuCircleCheck } from "react-icons/lu";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useFetcher, useLoaderData } from "react-router";import CompanyDefaultAttachmentsCard from "~/components/CompanyDefaultAttachmentsCard";import { EmailRecipients, Users } from "~/components/Form";import Country from "~/components/Form/Country";-import { usePermissions, useUser } from "~/hooks";import {accountsPayableBillingAddressValidator,defaultSupplierCcValidator,getAccountsPayableBillingAddress,getCompanySettings,- getTerms,purchasePriceUpdateTimingTypes,purchasePriceUpdateTimingValidator,supplierQuoteNotificationValidator,@@ -55,7 +45,6 @@ import {updateDefaultSupplierCc,updateLeadTimesOnReceiptSetting,updatePurchasePriceUpdateTimingSetting,- updatePurchasingPdfThumbnails,updateShowSupplierReadableIdSetting,updateSupplierQuoteNotificationSetting} from "~/modules/settings";@@ -72,10 +61,9 @@ export async function loader({ request }: LoaderFunctionArgs) {view: "settings"});- const [companySettings, terms, apBillingAddress, defaultAttachmentsResult] =+ const [companySettings, apBillingAddress, defaultAttachmentsResult] =await Promise.all([getCompanySettings(client, companyId),- getTerms(client, companyId),getAccountsPayableBillingAddress(client, companyId),client.storage.from("private")@@ -92,16 +80,8 @@ export async function loader({ request }: LoaderFunctionArgs) {);}- if (terms.error) {- throw redirect(- path.to.settings,- await flash(request, error(terms.error, "Failed to load terms"))- );- }-return {companySettings: companySettings.data,- terms: terms.data,apBillingAddress: apBillingAddress.data,defaultAttachments: defaultAttachmentsResult.data ?? []};@@ -249,23 +229,6 @@ export async function action({ request }: ActionFunctionArgs) {message: "Supplier quote notification setting updated"};- case "pdfs": {- const pdfEnabled = formData.get("enabled") === "true";- const thumbnailsResult = await updatePurchasingPdfThumbnails(- client,- companyId,- pdfEnabled- );-- if (thumbnailsResult.error)- return {- success: false,- message: thumbnailsResult.error.message- };-- return { success: true, message: "PDF settings updated" };- }-case "accountsPayableBillingAddress":const apBillingValidation = await validator(accountsPayableBillingAddressValidator@@ -335,15 +298,9 @@ export async function action({ request }: ActionFunctionArgs) {export default function PurchasingSettingsRoute() {const { t } = useLingui();- const { companySettings, terms, apBillingAddress, defaultAttachments } =+ const { companySettings, apBillingAddress, defaultAttachments } =useLoaderData<typeof loader>();const fetcher = useFetcher<typeof action>();- const permissions = usePermissions();- const { carbon } = useCarbon();- const {- id: userId,- company: { id: companyId }- } = useUser();useEffect(() => {if (fetcher.data?.success === true && fetcher?.data?.message) {@@ -414,38 +371,6 @@ export default function PurchasingSettingsRoute() {}}, [toggleFetcher.data?.message, toggleFetcher.data?.success]);- const [purchasingTermsStatus, setPurchasingTermsStatus] = useState<- "saved" | "draft"- >("saved");-- const handleUpdatePurchasingTerms = (content: JSONContent) => {- setPurchasingTermsStatus("draft");- onUpdatePurchasingTerms(content);- };- const onUpdatePurchasingTerms = useDebounce(- async (content: JSONContent) => {- if (!carbon) return;- const { error } = await carbon- .from("terms")- .update({- purchasingTerms: content,- updatedAt: today(getLocalTimeZone()).toString(),- updatedBy: userId- })- .eq("id", companyId);- if (!error) setPurchasingTermsStatus("saved");- },- 2500,- true- );-- const onUploadImage = async (file: File) => {- // Implement image upload logic here- // This is a placeholder function- console.error("Image upload not implemented", file);- return "";- };-return (<ScrollArea className="w-full h-[calc(100dvh-49px)]"><VStack@@ -460,45 +385,6 @@ export default function PurchasingSettingsRoute() {<Trans>Documents</Trans></p>- <Card>- <HStack className="justify-between items-start">- <CardHeader>- <CardTitle>- <Trans>Purchasing Terms & Conditions</Trans>- </CardTitle>- <CardDescription>- <Trans>- Define the terms and conditions for purchase orders- </Trans>- </CardDescription>- </CardHeader>- <CardAction className="py-6">- {purchasingTermsStatus === "draft" ? (- <Badge variant="secondary">- <Trans>Draft</Trans>- </Badge>- ) : (- <LuCircleCheck className="w-4 h-4 text-emerald-500" />- )}- </CardAction>- </HStack>- <CardContent>- {permissions.can("update", "settings") ? (- <Editor- initialValue={(terms.purchasingTerms ?? {}) as JSONContent}- onUpload={onUploadImage}- onChange={handleUpdatePurchasingTerms}- />- ) : (- <div- className="prose dark:prose-invert"- dangerouslySetInnerHTML={{- __html: generateHTML(terms.purchasingTerms as JSONContent)- }}- />- )}- </CardContent>- </Card><CompanyDefaultAttachmentsCardfiles={(defaultAttachments ?? []) as any}/>@@ -626,33 +512,6 @@ export default function PurchasingSettingsRoute() {</Card>)}- <Card>- <CardHeader>- <HStack className="justify-between items-center">- <div>- <CardTitle>- <Trans>Include Thumbnails on Purchasing Documents</Trans>- </CardTitle>- <CardDescription>- <Trans>Show part thumbnails on purchase order PDFs.</Trans>- </CardDescription>- </div>- <Switch- checked={- companySettings.includeThumbnailsOnPurchasingPdfs ?? true- }- onCheckedChange={(checked) => {- toggleFetcher.submit(- { intent: "pdfs", enabled: String(checked) },- { method: "POST" }- );- }}- disabled={toggleFetcher.state !== "idle"}- />- </HStack>- </CardHeader>- </Card>-<p className="mt-4 text-xxs text-foreground/70 uppercase font-light tracking-wide"><Trans>Automatic Updates</Trans></p>diff --git a/apps/erp/app/routes/x+/settings+/sales.tsx b/apps/erp/app/routes/x+/settings+/sales.tsxindex 07f379f39b..c477ae2d73 100644--- a/apps/erp/app/routes/x+/settings+/sales.tsx+++ b/apps/erp/app/routes/x+/settings+/sales.tsx@@ -1,4 +1,4 @@-import { error, useCarbon } from "@carbon/auth";+import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import {@@ -10,45 +10,35 @@ import {ValidatedForm,validator} from "@carbon/form";-import type { JSONContent } from "@carbon/react";import {- Badge,Card,- CardAction,CardContent,CardDescription,CardFooter,CardHeader,CardTitle,cn,- generateHTML,Heading,HStack,Label,ScrollArea,Switch,toast,- useDebounce,VStack} from "@carbon/react";-import { Editor } from "@carbon/react/Editor";-import { getLocalTimeZone, today } from "@internationalized/date";import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect, useState } from "react";-import { LuCircleCheck } from "react-icons/lu";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useFetcher, useLoaderData } from "react-router";import { EmailRecipients, Users } from "~/components/Form";import Country from "~/components/Form/Country";-import { usePermissions, useUser } from "~/hooks";import {accountsReceivableBillingAddressValidator,defaultCustomerCcValidator,digitalQuoteValidator,getAccountsReceivableBillingAddress,getCompanySettings,- getTerms,quoteLineCategoryMarkupsSettingsValidator,rfqReadyValidator,updateAccountsReceivableAddressSetting,@@ -57,7 +47,6 @@ import {updateDigitalQuoteSetting,updateQuoteLineCategoryMarkups,updateRfqReadySetting,- updateSalesPdfThumbnails,updateShowCustomerReadableIdSetting} from "~/modules/settings";import type { Handle } from "~/utils/handle";@@ -73,9 +62,8 @@ export async function loader({ request }: LoaderFunctionArgs) {view: "settings"});- const [companySettings, terms, arBillingAddress] = await Promise.all([+ const [companySettings, arBillingAddress] = await Promise.all([getCompanySettings(client, companyId),- getTerms(client, companyId),getAccountsReceivableBillingAddress(client, companyId)]);if (!companySettings.data)@@ -88,7 +76,6 @@ export async function loader({ request }: LoaderFunctionArgs) {);return {companySettings: companySettings.data,- terms: terms.data,arBillingAddress: arBillingAddress.data};}@@ -157,20 +144,6 @@ export async function action({ request }: ActionFunctionArgs) {return { success: true, message: "Digital quote setting updated" };- case "pdfs": {- const pdfEnabled = formData.get("enabled") === "true";- const thumbnailsResult = await updateSalesPdfThumbnails(- client,- companyId,- pdfEnabled- );-- if (thumbnailsResult.error)- return { success: false, message: thumbnailsResult.error.message };-- return { success: true, message: "PDF settings updated" };- }-case "rfq":const rfqValidation =await validator(rfqReadyValidator).validate(formData);@@ -274,8 +247,7 @@ export async function action({ request }: ActionFunctionArgs) {export default function SalesSettingsRoute() {const { t } = useLingui();- const { companySettings, terms, arBillingAddress } =- useLoaderData<typeof loader>();+ const { companySettings, arBillingAddress } = useLoaderData<typeof loader>();const fetcher = useFetcher<typeof action>();const toggleFetcher = useFetcher<typeof action>();const [arAddressEnabled, setArAddressEnabled] = useState(@@ -333,46 +305,6 @@ export default function SalesSettingsRoute() {}}, [toggleFetcher.data?.message, toggleFetcher.data?.success]);- const permissions = usePermissions();- const { carbon } = useCarbon();- const {- id: userId,- company: { id: companyId }- } = useUser();-- const [salesTermsStatus, setSalesTermsStatus] = useState<"saved" | "draft">(- "saved"- );-- const handleUpdateSalesTerms = (content: JSONContent) => {- setSalesTermsStatus("draft");- onUpdateSalesTerms(content);- };-- const onUpdateSalesTerms = useDebounce(- async (content: JSONContent) => {- setSalesTermsStatus("draft");- await carbon- ?.from("terms")- .update({- salesTerms: content,- updatedAt: today(getLocalTimeZone()).toString(),- updatedBy: userId- })- .eq("id", companyId);- setSalesTermsStatus("saved");- },- 2500,- true- );-- const onUploadImage = async (file: File) => {- // Implement image upload logic here- // This is a placeholder function- console.error("Image upload not implemented", file);- return "";- };-return (<ScrollArea className="w-full h-[calc(100dvh-49px)]"><VStack@@ -387,46 +319,6 @@ export default function SalesSettingsRoute() {<Trans>Documents</Trans></p>- <Card>- <HStack className="justify-between items-start">- <CardHeader>- <CardTitle>- <Trans>Sales Terms & Conditions</Trans>- </CardTitle>- <CardDescription>- <Trans>- Define the terms and conditions for quotes and sales orders- </Trans>- </CardDescription>- </CardHeader>- <CardAction className="py-6">- {salesTermsStatus === "draft" ? (- <Badge variant="secondary">- <Trans>Draft</Trans>- </Badge>- ) : (- <LuCircleCheck className="w-4 h-4 text-emerald-500" />- )}- </CardAction>- </HStack>- <CardContent>- {permissions.can("update", "settings") ? (- <Editor- initialValue={(terms?.salesTerms ?? {}) as JSONContent}- onUpload={onUploadImage}- onChange={handleUpdateSalesTerms}- />- ) : (- <div- className="prose dark:prose-invert"- dangerouslySetInnerHTML={{- __html: generateHTML(terms?.salesTerms as JSONContent)- }}- />- )}- </CardContent>- </Card>-<Card><ValidatedFormmethod="post"@@ -549,34 +441,6 @@ export default function SalesSettingsRoute() {</ValidatedForm></Card>)}- <Card>- <CardHeader>- <HStack className="justify-between items-center">- <div>- <CardTitle>- <Trans>Include Thumbnails on Sales Documents</Trans>- </CardTitle>- <CardDescription>- <Trans>- Show part thumbnails on quotes, sales orders, invoices, and- shipments.- </Trans>- </CardDescription>- </div>- <Switch- checked={companySettings.includeThumbnailsOnSalesPdfs ?? true}- onCheckedChange={(checked) => {- toggleFetcher.submit(- { intent: "pdfs", enabled: String(checked) },- { method: "POST" }- );- }}- disabled={toggleFetcher.state !== "idle"}- />- </HStack>- </CardHeader>- </Card>-<p className="mt-4 text-xxs text-foreground/70 uppercase font-light tracking-wide"><Trans>Customers</Trans></p>diff --git a/apps/erp/app/routes/x+/templates+/$type.preview.tsx b/apps/erp/app/routes/x+/templates+/$type.preview.tsxnew file mode 100644index 0000000000..f3fed96ffc--- /dev/null+++ b/apps/erp/app/routes/x+/templates+/$type.preview.tsx@@ -0,0 +1,118 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { DOCUMENT_PDFS, ensureFont } from "@carbon/documents/pdf";+import {+ blockSchema,+ CURRENT_TEMPLATE_FORMAT_VERSION,+ collectSectionIds,+ DEFAULT_DOCUMENT_SETTINGS,+ documentSettingsSchema,+ documentTemplateTypeSchema,+ themeSchema+} from "@carbon/documents/template";+import { getPreferenceHeaders } from "@carbon/react";+import { renderToStream } from "@react-pdf/renderer";+import type { ActionFunctionArgs } from "react-router";+import { z } from "zod";+import { getCompany, resolveSections } from "~/modules/settings";+import { buildPreviewProps } from "~/modules/settings/documentPreview.server";++/**+ * Renders a sample of the document with the draft block layout, server-side.+ * Keeps @react-pdf/renderer off the client entirely (it relies on Node's+ * Buffer/streams) and guarantees the preview matches the real PDF route.+ */+export async function action({ request, params }: ActionFunctionArgs) {+ const { client, companyId, companyGroupId } = await requirePermissions(+ request,+ {+ view: "settings"+ }+ );++ const documentType = documentTemplateTypeSchema.parse(params.type);++ const formData = await request.formData();+ const parsed = z+ .array(blockSchema)+ .safeParse(JSON.parse(String(formData.get("blocks") ?? "[]")));+ const theme = themeSchema.safeParse(+ JSON.parse(String(formData.get("theme") ?? "{}"))+ );+ const settingsParsed = documentSettingsSchema.safeParse(+ JSON.parse(String(formData.get("settings") ?? "{}"))+ );+ const settings = settingsParsed.success+ ? settingsParsed.data+ : { ...DEFAULT_DOCUMENT_SETTINGS };++ if (!parsed.success || !theme.success) {+ return new Response("Invalid template", { status: 400 });+ }++ const headerSectionId = String(formData.get("headerSectionId") ?? "") || null;+ const footerSectionId = String(formData.get("footerSectionId") ?? "") || null;++ const sections = await resolveSections(+ client,+ companyId,+ collectSectionIds({ blocks: parsed.data, headerSectionId, footerSectionId })+ );++ const { locale } = getPreferenceHeaders(request);++ await ensureFont(settings.fontFamily);++ const { Component, sample } = DOCUMENT_PDFS[documentType];++ // When a record is picked, render the draft layout against its live data.+ // Otherwise fall back to sample data with the real company branding.+ const previewId = String(formData.get("previewId") ?? "") || null;+ const real = previewId+ ? await buildPreviewProps(+ client,+ companyId,+ companyGroupId,+ documentType,+ previewId,+ locale+ )+ : null;++ let baseProps: Record<string, unknown>;+ if (real) {+ baseProps = real;+ } else {+ // Use the real company so the preview shows the actual logo / branding;+ // everything else (line items, totals) stays sample data.+ const company = await getCompany(client, companyId);+ baseProps = { ...sample, company: company.data ?? sample.company, locale };+ }++ const stream = await renderToStream(+ <Component+ {...baseProps}+ template={{+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType,+ blocks: parsed.data,+ theme: theme.data,+ settings,+ headerSectionId,+ footerSectionId+ }}+ sections={sections}+ />+ );++ const body: Buffer = await new Promise((resolve, reject) => {+ const buffers: Uint8Array[] = [];+ stream.on("data", (data) => buffers.push(data));+ stream.on("end", () => resolve(Buffer.concat(buffers)));+ stream.on("error", reject);+ });++ return new Response(new Uint8Array(body), {+ status: 200,+ headers: { "Content-Type": "application/pdf" }+ });+}diff --git a/apps/erp/app/routes/x+/templates+/$type.tsx b/apps/erp/app/routes/x+/templates+/$type.tsxnew file mode 100644index 0000000000..0e94e7ce3c--- /dev/null+++ b/apps/erp/app/routes/x+/templates+/$type.tsx@@ -0,0 +1,212 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type {+ DocumentBlock,+ DocumentSettings,+ DocumentTheme+} from "@carbon/documents/template";+import {+ documentTemplateTypeSchema,+ getDocumentLabel,+ resolveTemplate,+ withBuiltInSections+} from "@carbon/documents/template";+import { validationError, validator } from "@carbon/form";+import type { JSONContent } from "@carbon/react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, useLoaderData } from "react-router";+import { DocumentTemplateEditor } from "~/components/DocumentTemplateEditor";+import { usePermissions } from "~/hooks";+import {+ documentTemplateValidator,+ getCompany,+ getDocumentSections,+ getDocumentTemplate,+ getTerms,+ upsertDocumentTemplate+} from "~/modules/settings";+import { listPreviewEntities } from "~/modules/settings/documentPreview.server";+import { getCustomFieldsSchemas } from "~/modules/shared/shared.server";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const handle: Handle = {+ breadcrumb: (params: { type?: string }) => getDocumentLabel(params.type ?? "")+};++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings",+ role: "employee"+ });++ const documentType = documentTemplateTypeSchema.parse(params.type);++ const [+ stored,+ sections,+ customFieldSchemas,+ previewEntities,+ terms,+ company+ ] = await Promise.all([+ getDocumentTemplate(client, companyId, documentType),+ getDocumentSections(client, companyId),+ // Custom field definitions for this record type, to offer as insertable+ // blocks. The customField `table` matches the document type.+ getCustomFieldsSchemas(client, { companyId, table: documentType }),+ // Recent records to optionally preview against live data.+ listPreviewEntities(client, companyId, documentType),+ // Company terms setting — seeds the Terms block when it has no content.+ getTerms(client, companyId),+ getCompany(client, companyId)+ ]);++ // Map the document type to the relevant company terms setting (the Terms+ // block's default/fallback). Internal docs have no terms.+ const TERMS_FIELD: Partial<+ Record<typeof documentType, "salesTerms" | "purchasingTerms">+ > = {+ salesInvoice: "salesTerms",+ salesOrder: "salesTerms",+ quote: "salesTerms",+ packingSlip: "salesTerms",+ purchaseOrder: "purchasingTerms"+ };+ const termsField = TERMS_FIELD[documentType];+ const termsSeed = termsField+ ? ((terms.data as Record<string, JSONContent> | null)?.[termsField] ??+ undefined)+ : undefined;++ const customFields = (+ ((customFieldSchemas.data ?? []).find((t) => t.table === documentType)+ ?.fields ?? []) as { id: string; name: string }[]+ ).map((f) => ({ id: f.id, name: f.name }));++ const { blocks, theme, settings, headerSectionId, footerSectionId } =+ resolveTemplate(+ documentType,+ (stored.data ?? null) as Parameters<typeof resolveTemplate>[1]+ );++ return {+ documentType,+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ sections: withBuiltInSections(+ (sections.data ?? []) as {+ id: string;+ name: string;+ placement: "body" | "header" | "footer";+ content?: unknown;+ config?: unknown;+ }[]+ ).map((s) => ({+ id: s.id,+ name: s.name,+ placement: s.placement,+ content: (s as { content?: JSONContent }).content,+ config: (s as { config?: Record<string, unknown> }).config+ })),+ customFields,+ previewEntities,+ termsSeed,+ hasWatermark: Boolean(+ (company.data as { logoWatermark?: string | null } | null)?.logoWatermark+ )+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "settings"+ });++ const validation = await validator(documentTemplateValidator).validate(+ await request.formData()+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const {+ documentType,+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId+ } = validation.data;++ const upsert = await upsertDocumentTemplate(client, {+ companyId,+ documentType,+ // Validated at runtime by documentTemplateValidator; the form-data+ // inferred type is looser than the schema output, so assert here.+ blocks: blocks as DocumentBlock[],+ theme: theme as DocumentTheme,+ settings: settings as DocumentSettings,+ headerSectionId: headerSectionId || null,+ footerSectionId: footerSectionId || null,+ createdBy: userId,+ updatedBy: userId+ });++ if (upsert.error) {+ return data(+ { success: false },+ await flash(+ request,+ error(upsert.error, "Failed to save document layout")+ )+ );+ }++ return data(+ { success: true },+ await flash(request, success("Saved document layout"))+ );+}++export default function DocumentTemplateRoute() {+ const {+ documentType,+ blocks,+ theme,+ settings,+ headerSectionId,+ footerSectionId,+ sections,+ customFields,+ previewEntities,+ termsSeed,+ hasWatermark+ } = useLoaderData<typeof loader>();+ const permissions = usePermissions();++ return (+ <DocumentTemplateEditor+ key={documentType}+ documentType={documentType}+ actionPath={path.to.documentTemplate(documentType)}+ initialBlocks={blocks}+ initialTheme={theme}+ initialSettings={settings}+ initialHeaderSectionId={headerSectionId}+ initialFooterSectionId={footerSectionId}+ sections={sections}+ customFields={customFields}+ previewEntities={previewEntities}+ termsSeed={termsSeed as JSONContent | undefined}+ hasWatermark={hasWatermark}+ canEdit={permissions.can("update", "settings")}+ />+ );+}diff --git a/apps/erp/app/routes/x+/templates+/_index.tsx b/apps/erp/app/routes/x+/templates+/_index.tsxnew file mode 100644index 0000000000..3ed1dbc8c6--- /dev/null+++ b/apps/erp/app/routes/x+/templates+/_index.tsx@@ -0,0 +1,116 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { DOCUMENT_CATALOG } from "@carbon/documents/template";+import { Badge, Button, cn, Heading, ScrollArea, VStack } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { LuChevronRight, LuFileText, LuLibrary } from "react-icons/lu";+import type { LoaderFunctionArgs } from "react-router";+import { Link } from "react-router";+import { path } from "~/utils/path";++export async function loader({ request }: LoaderFunctionArgs) {+ await requirePermissions(request, { view: "settings", role: "employee" });+ return null;+}++const GROUP_ORDER = [+ "Sales",+ "Purchasing",+ "Inventory",+ "Production",+ "Quality",+ "Labels"+];++export default function DocumentTemplatesIndexRoute() {+ const groups = GROUP_ORDER.map((group) => ({+ group,+ docs: DOCUMENT_CATALOG.filter((entry) => entry.group === group)+ })).filter((g) => g.docs.length > 0);++ return (+ <ScrollArea className="h-full w-full">+ <VStack+ spacing={4}+ className="mx-auto h-full max-w-[60rem] gap-6 px-4 py-12"+ >+ <div className="flex w-full items-start justify-between gap-4">+ <div className="flex flex-col gap-1">+ <Heading size="h3">+ <Trans>Document Templates</Trans>+ </Heading>+ <p className="text-sm text-muted-foreground">+ <Trans>+ Customize the layout of your PDF documents — reorder sections,+ hide what you don't need, and add your own blocks.+ </Trans>+ </p>+ </div>+ <Button variant="secondary" leftIcon={<LuLibrary />} asChild>+ <Link to={path.to.documentSections}>+ <Trans>Shared Sections</Trans>+ </Link>+ </Button>+ </div>++ {groups.map(({ group, docs }) => (+ <section key={group} className="flex w-full flex-col gap-2">+ <h2 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">+ {group}+ </h2>+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {docs.map((doc) => (+ <DocumentCard key={doc.type} doc={doc} />+ ))}+ </div>+ </section>+ ))}+ </VStack>+ </ScrollArea>+ );+}++function DocumentCard({ doc }: { doc: (typeof DOCUMENT_CATALOG)[number] }) {+ const inner = (+ <>+ <span className="flex size-9 shrink-0 items-center justify-center rounded-md border bg-muted text-muted-foreground">+ <LuFileText className="size-4" />+ </span>+ <span className="flex flex-col">+ <span className="text-sm font-medium">{doc.label}</span>+ {!doc.supported && (+ <span className="text-xs text-muted-foreground">+ <Trans>Coming soon</Trans>+ </span>+ )}+ </span>+ {doc.supported ? (+ <LuChevronRight className="ml-auto size-4 text-muted-foreground" />+ ) : (+ <Badge variant="secondary" className="ml-auto">+ <Trans>Soon</Trans>+ </Badge>+ )}+ </>+ );++ const className = cn(+ "flex items-center gap-3 rounded-lg border bg-card p-3 transition-colors",+ doc.supported+ ? "hover:border-primary hover:bg-accent/30"+ : "cursor-not-allowed opacity-60"+ );++ if (!doc.supported) {+ return (+ <div aria-disabled className={className}>+ {inner}+ </div>+ );+ }++ return (+ <Link to={path.to.documentTemplate(doc.type)} className={className}>+ {inner}+ </Link>+ );+}diff --git a/apps/erp/app/routes/x+/templates+/_layout.tsx b/apps/erp/app/routes/x+/templates+/_layout.tsxnew file mode 100644index 0000000000..9304d335e9--- /dev/null+++ b/apps/erp/app/routes/x+/templates+/_layout.tsx@@ -0,0 +1,23 @@+import { msg } from "@lingui/core/macro";+import type { MetaFunction } from "react-router";+import { Outlet } from "react-router";+import type { Handle } from "~/utils/handle";+import { path } from "~/utils/path";++export const meta: MetaFunction = () => {+ return [{ title: "Carbon | Document Templates" }];+};++export const handle: Handle = {+ breadcrumb: msg`Templates`,+ to: path.to.documentTemplates,+ module: "settings"+};++export default function TemplatesRoute() {+ return (+ <div className="h-full w-full bg-background">+ <Outlet />+ </div>+ );+}diff --git a/apps/erp/app/routes/x+/templates+/shared.tsx b/apps/erp/app/routes/x+/templates+/shared.tsxnew file mode 100644index 0000000000..757db3a874--- /dev/null+++ b/apps/erp/app/routes/x+/templates+/shared.tsx@@ -0,0 +1,222 @@+import { assertIsPost, error, success } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import type {+ DocumentSectionPlacement,+ HeaderOptions+} from "@carbon/documents/template";+import { withBuiltInSections } from "@carbon/documents/template";+import { validationError, validator } from "@carbon/form";+import type { JSONContent } from "@carbon/react";+import {+ Badge,+ Button,+ Heading,+ IconButton,+ ScrollArea,+ useDisclosure,+ VStack+} from "@carbon/react";+import { useState } from "react";+import { LuArrowLeft, LuPencil, LuPlus, LuTrash2 } from "react-icons/lu";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data, Link, useFetcher, useLoaderData } from "react-router";+import { SectionFormModal } from "~/components/DocumentTemplateEditor/SectionFormModal";+import { usePermissions } from "~/hooks";+import {+ deleteDocumentSection,+ documentSectionValidator,+ getDocumentSections,+ upsertDocumentSection+} from "~/modules/settings";+import { path } from "~/utils/path";++const PLACEMENT_LABELS: Record<DocumentSectionPlacement, string> = {+ body: "Body section",+ header: "Page header",+ footer: "Page footer"+};++type Section = {+ id: string;+ name: string;+ placement: DocumentSectionPlacement;+ content: JSONContent;+ /** Header layout config (logo, which fields show). Header sections only. */+ config?: Partial<HeaderOptions>;+ /** System-provided default — editable (forks a copy), not deletable. */+ builtIn?: boolean;+};++export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings",+ role: "employee"+ });++ const sections = await getDocumentSections(client, companyId);+ return {+ sections: withBuiltInSections(+ (sections.data ?? []) as Section[]+ ) as Section[]+ };+}++export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "settings"+ });++ const formData = await request.formData();++ if (formData.get("intent") === "delete") {+ const id = String(formData.get("id") ?? "");+ const result = await deleteDocumentSection(client, id, companyId);+ if (result.error) {+ return data(+ { success: false },+ await flash(request, error(result.error, "Failed to delete section"))+ );+ }+ return data(+ { success: true },+ await flash(request, success("Section deleted"))+ );+ }++ const validation = await validator(documentSectionValidator).validate(+ formData+ );+ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, name, placement, content, config } = validation.data;+ const result = await upsertDocumentSection(client, {+ id,+ companyId,+ name,+ placement,+ content: content as JSONContent,+ config: config as Record<string, unknown> | undefined,+ ...(id ? { updatedBy: userId } : { createdBy: userId })+ });++ if (result.error) {+ return data(+ { success: false },+ await flash(request, error(result.error, "Failed to save section"))+ );+ }+ return data(+ { success: true },+ await flash(request, success("Section saved"))+ );+}++export default function SharedSectionsRoute() {+ const { sections } = useLoaderData<typeof loader>();+ const permissions = usePermissions();+ const canEdit = permissions.can("update", "settings");++ const [editing, setEditing] = useState<Section | null>(null);+ const disclosure = useDisclosure();+ const deleteFetcher = useFetcher();++ const openNew = () => {+ setEditing(null);+ disclosure.onOpen();+ };+ const openEdit = (section: Section) => {+ setEditing(section);+ disclosure.onOpen();+ };++ return (+ <ScrollArea className="h-full w-full">+ <VStack+ spacing={4}+ className="mx-auto h-full max-w-[60rem] gap-6 px-4 py-12"+ >+ <div className="flex w-full items-start justify-between">+ <div className="flex items-center gap-3">+ <Link+ to={path.to.documentTemplates}+ aria-label="Back to templates"+ className="flex size-8 items-center justify-center rounded-md border text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ >+ <LuArrowLeft className="size-4" />+ </Link>+ <div className="flex flex-col gap-1">+ <Heading size="h3">Shared Sections</Heading>+ <p className="text-sm text-muted-foreground">+ Reusable rich-text blocks referenced across your documents. Edit+ once — every document updates.+ </p>+ </div>+ </div>+ {canEdit && (+ <Button leftIcon={<LuPlus />} onClick={openNew}>+ New section+ </Button>+ )}+ </div>++ <div className="flex w-full flex-col gap-2">+ {sections.length === 0 && (+ <div className="rounded-lg border border-dashed px-4 py-10 text-center text-sm text-muted-foreground">+ No shared sections yet.+ </div>+ )}+ {sections.map((section) => (+ <div+ key={section.id}+ className="flex items-center gap-3 rounded-lg border bg-card p-3"+ >+ <div className="flex flex-1 flex-col">+ <span className="text-sm font-medium">{section.name}</span>+ </div>+ {section.builtIn && <Badge>System</Badge>}+ <Badge variant="secondary">+ {PLACEMENT_LABELS[section.placement]}+ </Badge>+ {canEdit && (+ <>+ <IconButton+ size="sm"+ variant="ghost"+ aria-label="Edit section"+ icon={<LuPencil />}+ onClick={() => openEdit(section)}+ />+ {!section.builtIn && (+ <deleteFetcher.Form method="post">+ <input type="hidden" name="intent" value="delete" />+ <input type="hidden" name="id" value={section.id} />+ <IconButton+ size="sm"+ variant="ghost"+ type="submit"+ aria-label="Delete section"+ icon={<LuTrash2 />}+ />+ </deleteFetcher.Form>+ )}+ </>+ )}+ </div>+ ))}+ </div>+ </VStack>++ {disclosure.isOpen && (+ <SectionFormModal+ key={editing?.id ?? "new"}+ section={editing}+ onClose={disclosure.onClose}+ />+ )}+ </ScrollArea>+ );+}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 574dc683cf..24121a1c6a 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1049,7 +1049,9 @@ export const path = {jobStatus: (id: string) => generatePath(`${x}/job/${id}/status`),kanban: (id: string) => generatePath(`${x}/inventory/kanbans/${id}`),kanbans: `${x}/inventory/kanbans`,- labelsSettings: `${x}/settings/labels`,+ documentTemplates: `${x}/templates`,+ documentSections: `${x}/templates/shared`,+ documentTemplate: (type: string) => generatePath(`${x}/templates/${type}`),manualPrint: `${x}/print`,location: (id: string) => generatePath(`${x}/resources/locations/${id}`),locations: `${x}/resources/locations`,diff --git a/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx b/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsxindex 91774c5156..3dd405725c 100644--- a/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx+++ b/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx@@ -3,8 +3,15 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";import { labelSizes } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";-import { getCompanySettings } from "~/services/inventory.service";+import { redirect } from "react-router";+import {+ getCompany,+ getCompanySettings,+ getDocumentTemplateConfig+} from "~/services/inventory.service";+import { resolveLabelLogo } from "~/services/labelLogo.server";import { getTrackedEntity } from "~/services/operations.service";+import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -17,12 +24,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getTrackedEntity(client, id)]);- // Get the label size from query params or default to avery5163+ // Get the label size from query params or default to avery5160const url = new URL(request.url);const labelParam = url.searchParams.get("labelSize");const labelSizeId =- labelParam || companySettings.data?.productLabelSize || "avery5163";+ labelParam || companySettings.data?.productLabelSize || "avery5160";// Find the label size configurationlet labelSize = labelSizes.find((size) => size.id === labelSizeId);@@ -31,6 +38,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Invalid label size");}+ if (labelSize.zpl) {+ throw redirect(+ path.to.file.trackedEntityLabelZpl(id, {+ labelSize: labelSize.id+ })+ );+ }+const item = await client.from("item").select("readableId, revision")@@ -51,8 +66,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}];+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);+const stream = await renderToStream(- <ProductLabelPDF items={items ?? []} labelSize={labelSize} />+ <ProductLabelPDF+ items={items ?? []}+ labelSize={labelSize}+ template={template}+ company={company.data as any}+ logo={logo}+ />);const body: Buffer = await new Promise((resolve, reject) => {diff --git a/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx b/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsxindex ee3e228357..80e58f4270 100644--- a/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx+++ b/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx@@ -3,7 +3,12 @@ import { generateProductLabelZPL } from "@carbon/documents/zpl";import { labelSizes } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCompanySettings } from "~/services/inventory.service";+import {+ getCompany,+ getCompanySettings,+ getDocumentTemplateConfig+} from "~/services/inventory.service";+import { resolveLabelLogo } from "~/services/labelLogo.server";import { getTrackedEntity } from "~/services/operations.service";import { path } from "~/utils/path";@@ -60,9 +65,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}];+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);+// Generate ZPL for each itemconst zplCommands = items.map((item) =>- generateProductLabelZPL(item, labelSize)+ generateProductLabelZPL(item, labelSize, template, logo));const zplOutput = zplCommands.join("\n");diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsxindex 1c29ab6bea..24515d01e6 100644--- a/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx@@ -3,8 +3,15 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";import { labelSizes } from "@carbon/utils";import { renderToStream } from "@react-pdf/renderer";import type { LoaderFunctionArgs } from "react-router";-import { getCompanySettings } from "~/services/inventory.service";+import { redirect } from "react-router";+import {+ getCompany,+ getCompanySettings,+ getDocumentTemplateConfig+} from "~/services/inventory.service";+import { resolveLabelLogo } from "~/services/labelLogo.server";import { getTrackedEntitiesByOperationId } from "~/services/operations.service";+import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -17,12 +24,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getTrackedEntitiesByOperationId(client, id)]);- // Get the label size from query params or default to avery5163+ // Get the label size from query params or default to avery5160const url = new URL(request.url);const labelParam = url.searchParams.get("labelSize");const trackedEntityIdParam = url.searchParams.get("trackedEntityId");const labelSizeId =- labelParam || companySettings.data?.productLabelSize || "avery5163";+ labelParam || companySettings.data?.productLabelSize || "avery5160";// Find the label size configurationlet labelSize = labelSizes.find((size) => size.id === labelSizeId);@@ -31,6 +38,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Invalid label size");}+ if (labelSize.zpl) {+ throw redirect(+ path.to.file.operationLabelsZpl(id, {+ labelSize: labelSize.id,+ trackedEntityId: trackedEntityIdParam ?? undefined+ })+ );+ }+let filteredTracking = trackedEntities.data;// Filter by lineId if provided@@ -68,8 +84,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);+const stream = await renderToStream(- <ProductLabelPDF items={items ?? []} labelSize={labelSize} />+ <ProductLabelPDF+ items={items ?? []}+ labelSize={labelSize}+ template={template}+ company={company.data as any}+ logo={logo}+ />);const body: Buffer = await new Promise((resolve, reject) => {diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsxindex 1f60d7a937..bd5dc85307 100644--- a/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx@@ -3,7 +3,12 @@ import { generateProductLabelZPL } from "@carbon/documents/zpl";import { labelSizes } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { redirect } from "react-router";-import { getCompanySettings } from "~/services/inventory.service";+import {+ getCompany,+ getCompanySettings,+ getDocumentTemplateConfig+} from "~/services/inventory.service";+import { resolveLabelLogo } from "~/services/labelLogo.server";import { getTrackedEntitiesByMakeMethodId } from "~/services/operations.service";import { path } from "~/utils/path";@@ -81,9 +86,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw new Error("Invalid label size or missing ZPL configuration");}+ const template = await getDocumentTemplateConfig(+ client,+ companyId,+ "trackingLabel"+ );++ const company = await getCompany(client, companyId);+ const logo = await resolveLabelLogo(company.data, template, labelSize);+// Generate ZPL for each itemconst zplCommands = items.map((item) =>- generateProductLabelZPL(item, labelSize)+ generateProductLabelZPL(item, labelSize, template, logo));const zplOutput = zplCommands.join("\n");diff --git a/apps/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.tsindex ac0e4709ff..77c73b13f6 100644--- a/apps/mes/app/services/inventory.service.ts+++ b/apps/mes/app/services/inventory.service.ts@@ -1,8 +1,33 @@+import { SUPABASE_URL } from "@carbon/auth";import type { Database } from "@carbon/database";+import type {+ DocumentTemplate,+ DocumentTemplateType+} from "@carbon/documents/template";+import { toDocumentTemplate } from "@carbon/documents/template";import type { SupabaseClient } from "@supabase/supabase-js";import { z } from "zod";import { zfd } from "zod-form-data";+/**+ * Load a stored document template as a `DocumentTemplate | null` to pass to a+ * PDF/ZPL generator (which runs it through `resolveTemplate`). Returns null when+ * nothing is stored, so the output falls back to the type's default.+ */+export async function getDocumentTemplateConfig(+ client: SupabaseClient<Database>,+ companyId: string,+ documentType: DocumentTemplateType+): Promise<DocumentTemplate | null> {+ const stored = await client+ .from("documentTemplate")+ .select("*")+ .eq("companyId", companyId)+ .eq("documentType", documentType)+ .maybeSingle();+ return toDocumentTemplate(stored.data, documentType);+}+export const inventoryAdjustmentValidator = z.object({itemId: z.string().min(1, { message: "Item ID is required" }),locationId: z.string().min(1, { message: "Location is required" }),@@ -56,6 +81,34 @@ export async function getCompanySettings(.single();}+const PUBLIC_STORAGE_URL_PREFIX = `${SUPABASE_URL}/storage/v1/object/public/public/`;++export async function getCompany(+ client: SupabaseClient<Database>,+ companyId: string+) {+ const company = await client+ .from("company")+ .select("*")+ .eq("id", companyId)+ .single();+ if (company.error || !company.data) return company;+ // Logos are stored as storage paths; expand to full public URLs (matches the+ // ERP getCompany) so they're fetchable by the PDF/ZPL pipeline.+ const url = (p: string | null) =>+ p ? `${PUBLIC_STORAGE_URL_PREFIX}${p}` : p;+ return {+ data: {+ ...company.data,+ logoLight: url(company.data.logoLight),+ logoDark: url(company.data.logoDark),+ logoLightIcon: url(company.data.logoLightIcon),+ logoDarkIcon: url(company.data.logoDarkIcon)+ },+ error: null+ };+}+export async function getSerialNumbersForItem(client: SupabaseClient<Database>,args: {diff --git a/apps/mes/app/services/labelLogo.server.ts b/apps/mes/app/services/labelLogo.server.tsnew file mode 100644index 0000000000..92f20fd4c3--- /dev/null+++ b/apps/mes/app/services/labelLogo.server.ts@@ -0,0 +1,20 @@+import { SUPABASE_URL } from "@carbon/auth";+import {+ type ResolvedLabelLogo,+ resolveLabelLogo as resolve+} from "@carbon/documents/labels";+import type { DocumentTemplate } from "@carbon/documents/template";+import type { LabelSize } from "@carbon/utils";++export type { ResolvedLabelLogo };++/** Binds the shared label-logo resolver to this app's Supabase URL. */+export function resolveLabelLogo(+ company: { logoLight?: string | null; logoLightIcon?: string | null } | null,+ template: DocumentTemplate | null,+ labelSize: LabelSize+): Promise<ResolvedLabelLogo | null> {+ return resolve(company, template, labelSize, {+ supabaseUrl: SUPABASE_URL ?? ""+ });+}diff --git a/llm/cache/document-template-customizer.md b/llm/cache/document-template-customizer.mdnew file mode 100644index 0000000000..025ccaccd5--- /dev/null+++ b/llm/cache/document-template-customizer.md@@ -0,0 +1,146 @@+# Document Template Customizer++Lets users customize the built-in PDF documents (reorder/hide sections, add+extension blocks, theme colors, fonts, page header/footer) with a live preview.+Editor lives at `apps/erp/app/routes/x+/templates+/`.++## Supported documents++`documentTemplateTypeSchema` enum (`packages/documents/src/template/schema.ts`)+and `DOCUMENT_CATALOG` (`defaults.ts`, `supported: true`) currently cover 9:+salesInvoice, salesOrder, purchaseOrder, quote (transactional); packingSlip+(fulfillment); stockTransfer (transfer); jobTraveler, issue; and trackingLabel+(the tracked-entity label — group "Labels").++## Template model (`packages/documents/src/template/`)++- **schema.ts** — zod. `blockSchema` is a discriminated union keyed on `type`.+ Built-in blocks (`builtInBlock("…")`) carry only `id`+`visible`; some carry+ `options` (header logo/fields, lineItems thumbnails/zebra, summary taxLabel).+ Extension blocks: `richText`, `keyValue`, `spacer`, `shared`, `customField`.+ `documentSettingsSchema` = fontFamily + footer page-numbers/format ++ registration line. `documentTemplateSchema` = blocks + theme + settings ++ header/footerSectionId.+- **defaults.ts** — `BLOCK_META` (label/isBuiltIn/removable/hideable/addable per+ block type — **every** block type must have an entry), default block-list+ helpers (`transactionalBlocks`/`fulfillmentBlocks`/`transferBlocks`/+ `jobTravelerBlocks`/`issueBlocks`), `DEFAULT_TEMPLATES` (one per doc type),+ `resolveTemplate(type, stored)` (falls back to default, appends missing+ built-ins hidden), `BUILT_IN_SECTIONS` (system-header/footer, id+ `BUILT_IN_SECTION_IDS`), `collectSectionIds`, `DOCUMENT_CATALOG`,+ `getDocumentLabel`.+- **merge.ts** — `MERGE_FIELDS[docType]` `{{token}}` catalog; `interpolateContent`+ / `interpolateString` fill header/footer/richText/keyValue at render.++## Per-doc PDF architecture (`packages/documents/src/pdf/`)++Each supported doc is a **thin driver** + a **per-doc block registry**:++- `<Doc>PDF.tsx` — resolves the template, builds a `<Doc>Data` bag + merge+ `vars`, computes header/footer section content, then renders+ `<Template …chrome>{visibleBlocks.map(registry[block.type])}</Template>`.+ Pattern reference: `StockTransferPDF.tsx`.+- `pdf/blocks/<doc>/` — `types.ts` (`<Doc>Data` + `BlockRenderer`), `vars.ts`+ (`build<Doc>Vars`), one component per block, `registry.tsx`+ (`Record<DocumentBlockType, BlockRenderer>` — **must have a key for every+ block type**; unused → `() => null`), `index.ts`. Extension-block renderers+ reuse the generic `pdf/blocks/{RichText,KeyValue,Spacer,Shared,CustomField}Block`.+- `pdf/components/Template.tsx` — `<Document><Page>` chrome: fixed header-section+ banner, body, `Footer` (page numbers + registration line + footer-section).+- `preview-documents.tsx` — `DOCUMENT_PDFS[type] = { Component, sample }` dispatch+ for the generic preview route. `pdf/index.ts` re-exports PDFs + `SAMPLE_*`.+- `pdf/<doc>.samples.ts` — `SAMPLE_*` fixture (cast `as any`) for preview.++**Adding a block type** to the union breaks every existing registry (they are+`Record<DocumentBlockType,…>`) → add the new key (usually `() => null`) to all+registries + a `BLOCK_META` entry.++## Job Traveler specifics++Multi-make-method: the route+`apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx` renders **multiple+`<Page>`** (one per make method), each with `JobTravelerPageContent` (the+block-driven body, exported from `JobTravelerPDF.tsx`) + its own `Footer`. The+single-page `JobTravelerPDF` default export wraps the same body in `Template`+and is what the editor **preview** uses.++## Tracking Label specifics++`trackingLabel` is `ProductLabelPDF` (used by the entity/receipt/shipment/+operation `*.labels.pdf.tsx` routes). It's block-driven via+`pdf/blocks/trackingLabel/` (per-field blocks: labelHeading, labelRevision,+labelQuantity, labelTracking, labelQrCode, labelEntityId — stacked vertically+in each tile). Label **size/grid** is NOT in the template — it stays a print-+time `?labelSize=` choice (Avery presets in `@carbon/utils` labelSizes; ZPL+sizes redirect). Default template: `headerSectionId: null` (no header block at+all → editor's HeaderRow auto-hides), `footerSectionId: system-footer` (keeps+page numbers, toggleable). Routes load the template via+`getDocumentTemplateConfig(client, companyId, "trackingLabel")`+(`settings.service.ts`) — a helper that returns `DocumentTemplate | null`.++Label blocks beyond the built-in fields: a single-line `field` (label+value), a+`labelBarcode` (pdf417/code128/datamatrix/qrcode; PDF via `bwip-js`+`qr/barcode.ts`, ZPL via `^B7/^BC/^BX/^BQ`), and a `labelLogo` (company logo;+color URL in PDF, monochrome toggle). Layout slots: fields top-left (two-column+aligned), logo+QR top-right, barcode full-width bottom, entity id bottom.++**Logo monochrome / ZPL `^GF`:** the `logo-resizer` Supabase edge function+(`supabase/functions/logo-resizer/`, magick-wasm; mirror of `image-resizer`)+flattens→grays→thresholds→resizes the logo and returns `{ monoPng, gfa }` — the+mono PNG drives the PDF B&W logo, `gfa` is a self-rolled `^GFA` (no `zpl-image`+dep). `resolveLabelLogo(company, template, labelSize)` (ERP+`modules/settings/labelLogo.server.ts` + MES `services/labelLogo.server.ts`)+calls it when a visible `labelLogo` block exists and threads `{color, mono, gfa,+widthDots}` into `ProductLabelPDF` (`company`/`logo` props) ++`generateProductLabelZPL` (`logo` arg). All 12 ERP/MES label routes pass it.++**ZPL output** honors the same template: `generateProductLabelZPL(item,+labelSize, template?, logo?)` (`packages/documents/src/zpl/ProductLabelZPL.tsx`)+resolves `trackingLabel` and emits only visible fields in block order (text+stacked, QR top-right, entity id bottom; extension/custom blocks skipped — no+ZPL equivalent). Both ERP and MES label routes (`file+/{entity,receipt,+shipment,operation}+/$id.labels[.]{pdf,zpl}.tsx`) pass the template. MES has its+own `getDocumentTemplateConfig` in `apps/mes/app/services/inventory.service.ts`+(mirrors the ERP helper). Label size/ZPL-vs-PDF is still the print-time+`?labelSize=` choice (ZPL sizes have a `zpl` config + DPI; others render PDF).++## Editor (`apps/erp/app/components/DocumentTemplateEditor/`)++`context.tsx` (state/actions provider), `index.tsx` (rails + toolbar; toolbar has+a centered `Combobox` to preview against a live record), `BlockList`/`BlockConfig`+/`FontConfig`/`ThemeConfig`/`SectionFormModal`/`TemplatePreview`/`NumberRow`.+`NumberRow` wraps react-aria `NumberField` with the required composed+`NumberInputGroup` child (a bare `label` prop renders no input).++## Terms & Conditions (per-document)++The built-in `terms` block carries its own optional rich-text `content` (schema+`termsBlock`). Renderers (`blocks/**/TermsBlock.tsx`) use `resolveTerms(block,+data.terms, vars)` from `blocks/resolveTerms.ts`: the block's authored content+(interpolated with merge fields) when present, else `data.terms` — the company+`terms` table setting (`salesTerms`/`purchasingTerms`), still passed by the PDF+file routes as the fallback. The editor `TermsConfig` (BlockConfig.tsx) seeds the+field from that setting via `termsSeed` (threaded loader→context→config). The+global Terms editors were removed from `settings+/sales.tsx` ++`settings+/purchasing.tsx`; the `terms` table remains as the seed + fallback.++## Routes / persistence++- `x+/templates+/$type.tsx` — loader resolves template + sections + customFields ++ `listPreviewEntities`; action upserts via `upsertDocumentTemplate`.+- `x+/templates+/$type.preview.tsx` — POST renders draft layout via+ `DOCUMENT_PDFS`; with a `previewId`, `buildPreviewProps`+ (`modules/settings/documentPreview.server.ts`) renders against real record data+ (supported: salesInvoice/salesOrder/purchaseOrder/quote/stockTransfer; others+ fall back to sample).+- File routes (`file+/<doc>+/…pdf.tsx`) — load `getDocumentTemplate`, build a+ `DocumentTemplate | null`, `resolveTemplate`, `resolveSections`,+ `ensureFont(settings.fontFamily)`, pass `template` + `sections` to the PDF.+- `modules/settings/settings.service.ts` — `getDocumentTemplate`,+ `upsertDocumentTemplate`, `getDocumentSections`, `resolveSections`,+ `upsertDocumentSection` (forks built-in sections on edit). DB tables:+ `documentTemplate`, `documentSection`.++> Note: `documentTemplate` rows are typed loosely until the generated DB types+> are regenerated — PDF routes cast `data.blocks/theme/settings` (`.blocks does+> not exist on ResultOne` tsgo errors are expected until regen).diff --git a/llm/cache/pdf-generation-patterns.md b/llm/cache/pdf-generation-patterns.mdindex edaed4681d..50651102fa 100644--- a/llm/cache/pdf-generation-patterns.md+++ b/llm/cache/pdf-generation-patterns.md@@ -38,7 +38,7 @@ export async function generateQRCode(#### In-Component QR/Barcode Generation-- **JobTravelerPDF**: Has its own `generateQRCode` function that creates QR codes for operation tracking URLs+- **JobTravelerPDF**: operation-tracking QR codes are generated in `blocks/jobTraveler/OperationsBlock.tsx` (uses the imported `generateQRCode` + `getMESUrl` start/end paths)- **PackingSlipPDF**: Has `generateBarcode` function for Code128 barcodes and uses imported `generateQRCode` for tracked entities- **ProductLabelPDF**: Uses `await generateQRCode(item.trackedEntityId, qrCodeSize / 72)` directly in JSXdiff --git a/llm/tasks/todo.md b/llm/tasks/todo.mddeleted file mode 100644index 6f771514c7..0000000000--- a/llm/tasks/todo.md+++ /dev/null@@ -1,62 +0,0 @@-# Thermo-Nuclear Review Fixes — feat/print-manager--Working state for applying review findings. Update checkboxes as items complete.-Spawn subtasks to query the cache folder any time I need to learn something about the codebase. NEVER update the cache with plans or information about code that is not yet committed.--## Priority order--### 1. Lift duplicated print UI into shared package (§1a) — DONE--- [x] Decided home: new `@carbon/printing/ui` entry (lingui catalogs updated to include `packages/printing/src/ui`; `@carbon/jobs`→`@carbon/printing` dep means the print action CANNOT move into printing — cycle)-- [x] Created `src/ui/`: PrintingProvider (context resolves all app differences at one site: printing data, printerRoutes, useMetric, printPath, settingsPath, settingsExternal), PrintButton, LabelDownloadModal-- [x] Created `src/assignments.ts`: canonical `PrinterContext` + `resolveContextAssignment` — replaces the duplicated context switch in usePrinting AND cache.server.ts (part of §2 landed early)-- [x] `manualPrintValidator` moved into printing models; both print.tsx routes now thin and identical-- [x] Both layouts wrap with PrintingProvider; mes `as any` casts removed (4 of them — §5 item done early)-- [x] `getPrinterRoutes` narrows `format` to "zpl"|"pdf" at the service boundary (DB CHECK enforces it)-- [x] Deleted 6 duplicated app files; barrels re-export from @carbon/printing/ui-- [x] Removed dead `variant` prop (declared but never used; one caller passed it)-- [x] Typechecks: packages/printing ✓, apps/mes ✓, apps/erp ✓, packages/jobs ✓; lingui extract → no catalog changes--### 2. Collapse context taxonomy to one model (§2) — DONE-- [x] `assignments.ts` in @carbon/printing: `printerContexts`, `PrinterContext`, `resolveContextAssignment` (read), `setContextAssignment` (write), `emptyLocationAssignment`, `getPrinterContextForSource` (sourceDocument→context lookup)-- [x] printing.tsx action: switch replaced with `setContextAssignment` + reuses `getPrintingSettings`/`updatePrintingSettings` service fns (JSON.parse(JSON.stringify) dance deleted)-- [x] LocationSection: 5 hand-written AssignmentRow blocks → data-driven `rows` array `.map`-- [x] print-job: nested ternary → `getPrinterContextForSource`-- [x] `updateAssignmentValidator`: enum from `printerContexts` + `.refine` requiring contextId for workCenter (was a silent no-op)-- [x] AssignmentUpdate payload typed with `PrinterContext`--### 3. Tighten ResolvedData typing (§3) — DONE-- [x] `ResolvedData<T>` generic; resolvers return `ProductLabelItem[]` / `KanbanCardItem[]` / `StorageUnitItem[]`-- [x] `PrintableDocumentItem` discriminated union; all `as string`/`as number` casts in renderers deleted-- [x] FLAG FOR USER: trackingType inferred from quantity in enrichTrackedEntities (kept as-is; behavior-preserving but smells like a bug per project rule against deriving Serial/Batch)--### 4. Decompose oversized files (§1b/§1c) — DONE-- [x] printing.tsx 942 → ~260 lines (loader/action/composition) + modules/settings/ui/Printing/{PrintersCard,AssignmentsCard}.tsx-- [x] print-job.tsx 756 → print-job/{index.tsx (~310 orchestration), resolvers.ts, renderers.tsx}; stayed in @carbon/jobs (moving to @carbon/printing would drag react-pdf/@carbon/documents into the package the apps' UI imports)-- [x] Merged verbatim-duplicate "Entity"/"Split" resolver cases; dead `!content` branch removed; DEFAULT_MEDIA_SIZE_ID constant--### 5. Medium cleanups (§4) — DONE-- [x] complete.tsx: `autoPrintFirstOperationLabel` helper replaces both ~50-line Serial/Batch blocks; redundant getCarbonServiceRole removed-- [x] printing.tsx JSON.parse(JSON.stringify()) — done in §2-- [x] packages/documents/src/zpl/utils.ts: `getZplLabelGeometry` + `zplLabelHeader`; both generators rewritten on top-- [x] _layout.tsx (mes): `as any` casts dropped — done in §1a-- [x] print-job: named constant for "label2x1" — done in §4--## Review--All five review sections applied. Verification:-- Typechecks clean: apps/erp, apps/mes (tsgo), packages/printing, packages/documents (tsgo), packages/jobs (tsc) — each scoped per-package, never whole-project-- ZPL refactor proven behavior-preserving: old-vs-new generators compared at runtime across all label sizes × 5 item shapes → 20/20 byte-identical-- lingui extract after the component move → zero catalog changes (same msgids)-- pnpm install clean after adding @carbon/printing deps/peer-deps + ./ui export--Key decisions:-- Print UI lives in `@carbon/printing/ui` (NOT @carbon/react — domain code doesn't belong in the generic UI package; NOT a shared action — @carbon/jobs→@carbon/printing dep makes that a cycle). `PrintingProvider` at each app's x+/_layout resolves the only real app differences (data shape, paths, external-vs-internal settings link).-- One canonical context model in `packages/printing/src/assignments.ts`: printerContexts/PrinterContext, resolveContextAssignment (read), setContextAssignment (write), getPrinterContextForSource (sourceDocument→context). Replaced 3 hand-maintained switches + 1 nested ternary + the loose `context: string` payloads.-- print-job stayed in @carbon/jobs as a directory (index/resolvers/renderers) — moving renderers into @carbon/printing would drag react-pdf into the package the apps import.--OPEN QUESTION for user: resolvers.ts still infers trackingType from quantity-((qty > 1 ? "Batch" : "Serial")) — preserved as-is, but it ignores the entity's-actual tracking type and looks like a latent bug.--Not done (left as-is deliberately): printing.jobs.tsx flash/data inconsistencies (cosmetic), Table.tsx controlled-selection addition (sound, documented contract), migration COMMIT after enum add (required by Postgres for enum use in same migration).diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 9b743add47..eeed42cdec 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -8248,6 +8248,291 @@ export type Database = {},]}+ documentSection: {+ Row: {+ companyId: string+ config: Json+ content: Json+ createdAt: string+ createdBy: string+ id: string+ name: string+ placement: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ config?: Json+ content?: Json+ createdAt?: string+ createdBy: string+ id?: string+ name: string+ placement?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ config?: Json+ content?: Json+ createdAt?: string+ createdBy?: string+ id?: string+ name?: string+ placement?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ documentTemplate: {+ Row: {+ blocks: Json+ companyId: string+ createdAt: string+ createdBy: string+ documentType: string+ footerSectionId: string | null+ formatVersion: number+ headerSectionId: string | null+ id: string+ settings: Json+ theme: Json+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ blocks?: Json+ companyId: string+ createdAt?: string+ createdBy: string+ documentType: string+ footerSectionId?: string | null+ formatVersion?: number+ headerSectionId?: string | null+ id?: string+ settings?: Json+ theme?: Json+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ blocks?: Json+ companyId?: string+ createdAt?: string+ createdBy?: string+ documentType?: string+ footerSectionId?: string | null+ formatVersion?: number+ headerSectionId?: string | null+ id?: string+ settings?: Json+ theme?: Json+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }documentTransaction: {Row: {createdAt: string@@ -38425,49 +38710,7 @@ export type Database = {},]}- searchIndex_d8labgm360h02et7s650: {- Row: {- createdAt: string- description: string | null- entityId: string- entityType: string- id: number- link: string- metadata: Json | null- searchVector: unknown- tags: string[] | null- title: string- updatedAt: string | null- }- Insert: {- createdAt?: string- description?: string | null- entityId: string- entityType: string- id?: number- link: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title: string- updatedAt?: string | null- }- Update: {- createdAt?: string- description?: string | null- entityId?: string- entityType?: string- id?: number- link?: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title?: string- updatedAt?: string | null- }- Relationships: []- }- searchIndex_K26piHAY3SwCbjCHpopqjz: {+ searchIndex_d8lrj78sm0h02bck1u9g: {Row: {createdAt: stringdescription: string | nulldiff --git a/packages/database/supabase/config.toml b/packages/database/supabase/config.tomlindex 40fd164bcf..978b711cab 100644--- a/packages/database/supabase/config.toml+++ b/packages/database/supabase/config.toml@@ -137,6 +137,10 @@ backend = "postgres"enabled = trueverify_jwt = false+[functions.logo-resizer]+enabled = true+verify_jwt = false+[functions.sync]enabled = trueverify_jwt = truediff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 9b743add47..eeed42cdec 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -8248,6 +8248,291 @@ export type Database = {},]}+ documentSection: {+ Row: {+ companyId: string+ config: Json+ content: Json+ createdAt: string+ createdBy: string+ id: string+ name: string+ placement: string+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ companyId: string+ config?: Json+ content?: Json+ createdAt?: string+ createdBy: string+ id?: string+ name: string+ placement?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ companyId?: string+ config?: Json+ content?: Json+ createdAt?: string+ createdBy?: string+ id?: string+ name?: string+ placement?: string+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentSection_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentSection_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }+ documentTemplate: {+ Row: {+ blocks: Json+ companyId: string+ createdAt: string+ createdBy: string+ documentType: string+ footerSectionId: string | null+ formatVersion: number+ headerSectionId: string | null+ id: string+ settings: Json+ theme: Json+ updatedAt: string | null+ updatedBy: string | null+ }+ Insert: {+ blocks?: Json+ companyId: string+ createdAt?: string+ createdBy: string+ documentType: string+ footerSectionId?: string | null+ formatVersion?: number+ headerSectionId?: string | null+ id?: string+ settings?: Json+ theme?: Json+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Update: {+ blocks?: Json+ companyId?: string+ createdAt?: string+ createdBy?: string+ documentType?: string+ footerSectionId?: string | null+ formatVersion?: number+ headerSectionId?: string | null+ id?: string+ settings?: Json+ theme?: Json+ updatedAt?: string | null+ updatedBy?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "companies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "company"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "customFieldTables"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentTemplate_companyId_fkey"+ columns: ["companyId"]+ isOneToOne: false+ referencedRelation: "integrations"+ referencedColumns: ["companyId"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_createdBy_fkey"+ columns: ["createdBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employees"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeesAcrossCompanies"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "employeeSummary"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "user"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "documentTemplate_updatedBy_fkey"+ columns: ["updatedBy"]+ isOneToOne: false+ referencedRelation: "userDefaults"+ referencedColumns: ["userId"]+ },+ ]+ }documentTransaction: {Row: {createdAt: string@@ -38425,49 +38710,7 @@ export type Database = {},]}- searchIndex_d8labgm360h02et7s650: {- Row: {- createdAt: string- description: string | null- entityId: string- entityType: string- id: number- link: string- metadata: Json | null- searchVector: unknown- tags: string[] | null- title: string- updatedAt: string | null- }- Insert: {- createdAt?: string- description?: string | null- entityId: string- entityType: string- id?: number- link: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title: string- updatedAt?: string | null- }- Update: {- createdAt?: string- description?: string | null- entityId?: string- entityType?: string- id?: number- link?: string- metadata?: Json | null- searchVector?: unknown- tags?: string[] | null- title?: string- updatedAt?: string | null- }- Relationships: []- }- searchIndex_K26piHAY3SwCbjCHpopqjz: {+ searchIndex_d8lrj78sm0h02bck1u9g: {Row: {createdAt: stringdescription: string | nulldiff --git a/packages/database/supabase/functions/logo-resizer/index.ts b/packages/database/supabase/functions/logo-resizer/index.tsnew file mode 100644index 0000000000..cab2247d43--- /dev/null+++ b/packages/database/supabase/functions/logo-resizer/index.ts@@ -0,0 +1,132 @@+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import {+ AlphaOption,+ ImageMagick,+ initializeImageMagick,+ MagickColor,+ MagickFormat,+ MagickGeometry,+ Percentage,+} from "npm:@imagemagick/[email protected]";++import { corsHeaders } from "../lib/headers.ts";++const wasmBytes = await Deno.readFile(+ new URL(+ "magick.wasm",+ import.meta.resolve("npm:@imagemagick/[email protected]")+ )+);+await initializeImageMagick(wasmBytes);++const HEX = "0123456789ABCDEF";++/**+ * Pack a monochrome RGBA buffer into a ZPL `^GFA` graphic field: rows of 1-bpp+ * pixels (MSB-first, `1` = black), padded to a byte boundary per row, hex-coded.+ */+function rgbaToGFA(rgba: Uint8Array, w: number, h: number, thresh = 128): string {+ const rowBytes = Math.ceil(w / 8);+ const total = rowBytes * h;+ const bytes = new Uint8Array(total);+ for (let y = 0; y < h; y++) {+ for (let x = 0; x < w; x++) {+ const i = (y * w + x) * 4;+ const a = rgba[i + 3];+ const lum =+ a === 0 ? 255 : rgba[i] * 0.299 + rgba[i + 1] * 0.587 + rgba[i + 2] * 0.114;+ if (lum < thresh) bytes[y * rowBytes + (x >> 3)] |= 0x80 >> (x & 7);+ }+ }+ let hex = "";+ for (let k = 0; k < total; k++) {+ hex += HEX[bytes[k] >> 4] + HEX[bytes[k] & 15];+ }+ return `^GFA,${total},${total},${rowBytes},${hex}`;+}++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }++ try {+ const formData = await req.formData();+ const file = formData.get("file") as File;+ const widthDots = Math.max(+ 16,+ Math.min(1200, parseInt((formData.get("widthDots") as string) || "240", 10))+ );+ const threshold = parseInt((formData.get("threshold") as string) || "50", 10);+ // Optional crop, normalized 0..1 relative to the source image.+ const num = (k: string) => {+ const v = formData.get(k);+ return v === null ? null : parseFloat(v as string);+ };+ const cropX = num("cropX");+ const cropY = num("cropY");+ const cropW = num("cropW");+ const cropH = num("cropH");+ const hasCrop =+ cropX !== null && cropY !== null && cropW !== null && cropH !== null;++ if (!file) throw new Error("No file provided");+ const bytes = new Uint8Array(await file.arrayBuffer());++ let monoPng = "";+ let gfa = "";+ let outW = 0;+ let outH = 0;++ ImageMagick.read(bytes, (img) => {+ // Crop first (normalized → pixels), so downstream sizing sees the region.+ if (hasCrop) {+ const px = Math.max(1, Math.round((cropW as number) * img.width));+ const py = Math.max(1, Math.round((cropH as number) * img.height));+ img.crop(+ new MagickGeometry(+ Math.round((cropX as number) * img.width),+ Math.round((cropY as number) * img.height),+ px,+ py+ )+ );+ img.resetPage();+ }+ // Flatten transparency onto white so it doesn't threshold to black.+ img.backgroundColor = new MagickColor("white");+ img.alpha(AlphaOption.Remove);+ // Grayscale + threshold → clean 1-bit black & white.+ img.grayscale();+ img.threshold(new Percentage(threshold));+ // Scale to the requested dot width (height proportional).+ img.resize(new MagickGeometry(`${widthDots}`));+ outW = img.width;+ outH = img.height;++ // PDF B&W logo.+ img.format = MagickFormat.Png;+ img.write((data) => {+ let b = "";+ for (let i = 0; i < data.length; i++) b += String.fromCharCode(data[i]);+ monoPng = `data:image/png;base64,${btoa(b)}`;+ });++ // ZPL graphic.+ img.getPixels((pixels) => {+ const rgba = pixels.toByteArray(0, 0, outW, outH, "RGBA");+ if (rgba) gfa = rgbaToGFA(rgba, outW, outH);+ });+ });++ return new Response(+ JSON.stringify({ monoPng, gfa, widthDots: outW, heightDots: outH }),+ { headers: { ...corsHeaders, "Content-Type": "application/json" } }+ );+ } catch (err) {+ return new Response(JSON.stringify({ error: (err as Error).message }), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+ }+});diff --git a/packages/database/supabase/migrations/20260609143732_document-template.sql b/packages/database/supabase/migrations/20260609143732_document-template.sqlnew file mode 100644index 0000000000..2c0062ebdb--- /dev/null+++ b/packages/database/supabase/migrations/20260609143732_document-template.sql@@ -0,0 +1,115 @@+CREATE TABLE "documentTemplate" (+ "id" TEXT NOT NULL DEFAULT id(),+ "companyId" TEXT NOT NULL,+ "documentType" TEXT NOT NULL,+ -- Schema version of `blocks`/`theme`; app migrates older rows forward on read.+ "formatVersion" INTEGER NOT NULL DEFAULT 1,+ "blocks" JSONB NOT NULL DEFAULT '[]',+ "theme" JSONB NOT NULL DEFAULT '{}',+ -- Document-level settings (footer page numbers + registration line).+ "settings" JSONB NOT NULL DEFAULT '{}',+ -- Optional references to a shared documentSection used as the page+ -- header/footer. Plain ids (no FK): a deleted section is skipped at render.+ "headerSectionId" TEXT,+ "footerSectionId" TEXT,++ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);++CREATE INDEX "documentTemplate_companyId_idx" ON "documentTemplate" ("companyId");+CREATE INDEX "documentTemplate_createdBy_idx" ON "documentTemplate" ("createdBy");++-- One template per document type per company+ALTER TABLE "documentTemplate" ADD CONSTRAINT "documentTemplate_companyId_documentType_key"+ UNIQUE ("companyId", "documentType");++-- Row Level Security+ALTER TABLE "public"."documentTemplate" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."documentTemplate"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."documentTemplate"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."documentTemplate"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."documentTemplate"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_delete'))::text[]+ )+);++-- Shared, reusable document sections (rich text) referenced across documents:+-- body sections (inserted as blocks) and page header/footer chrome.+CREATE TABLE "documentSection" (+ "id" TEXT NOT NULL DEFAULT id(),+ "companyId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ -- 'body' = referenceable content block; 'header'/'footer' = page chrome+ "placement" TEXT NOT NULL DEFAULT 'body',+ "content" JSONB NOT NULL DEFAULT '{}',+ -- Header layout config (logo, which company fields show); header sections only.+ "config" JSONB NOT NULL DEFAULT '{}',++ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ "updatedBy" TEXT REFERENCES "user"("id"),+ "updatedAt" TIMESTAMP WITH TIME ZONE,++ PRIMARY KEY ("id", "companyId"),+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE+);++CREATE INDEX "documentSection_companyId_idx" ON "documentSection" ("companyId");+CREATE INDEX "documentSection_createdBy_idx" ON "documentSection" ("createdBy");++ALTER TABLE "public"."documentSection" ENABLE ROW LEVEL SECURITY;++CREATE POLICY "SELECT" ON "public"."documentSection"+FOR SELECT USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++CREATE POLICY "INSERT" ON "public"."documentSection"+FOR INSERT WITH CHECK (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_create'))::text[]+ )+);++CREATE POLICY "UPDATE" ON "public"."documentSection"+FOR UPDATE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_update'))::text[]+ )+);++CREATE POLICY "DELETE" ON "public"."documentSection"+FOR DELETE USING (+ "companyId" = ANY (+ (SELECT get_companies_with_employee_permission('settings_delete'))::text[]+ )+);diff --git a/packages/database/supabase/migrations/20260610113428_seed-document-terms.sql b/packages/database/supabase/migrations/20260610113428_seed-document-terms.sqlnew file mode 100644index 0000000000..b86409b228--- /dev/null+++ b/packages/database/supabase/migrations/20260610113428_seed-document-terms.sql@@ -0,0 +1,61 @@+-- Seed the per-document Terms & Conditions from the company-level `terms`+-- setting. The Terms block now carries its own rich-text `content`; this+-- backfills that content for existing `documentTemplate` rows whose terms block+-- is still empty, so previously-saved templates keep their terms after the+-- switch from a global setting.+--+-- The `terms` table is intentionally NOT dropped — it remains the seed (editor)+-- and render fallback for documents without a stored template, so companies+-- that never open the editor are unaffected.+--+-- Idempotent: only fills terms blocks that are empty, and only when the company+-- actually has terms content. Re-running is a no-op.++UPDATE "documentTemplate" AS dt+SET+ "blocks" = sub.new_blocks,+ "updatedAt" = NOW()+FROM (+ SELECT+ dt2."id",+ dt2."companyId",+ jsonb_agg(+ CASE+ WHEN block->>'type' = 'terms'+ -- terms block has no usable content yet+ AND COALESCE(+ jsonb_array_length(COALESCE(block #> '{content,content}', '[]'::jsonb)),+ 0+ ) = 0+ -- and the company has terms content to copy in+ AND COALESCE(+ jsonb_array_length(COALESCE(seed.value #> '{content}', '[]'::jsonb)),+ 0+ ) > 0+ THEN block || jsonb_build_object('content', seed.value)+ ELSE block+ END+ ORDER BY ord+ ) AS new_blocks+ FROM "documentTemplate" AS dt2+ JOIN "terms" AS t ON t."id" = dt2."companyId"+ CROSS JOIN LATERAL (+ -- The `terms` columns are JSON; cast to jsonb so the operators below match.+ SELECT+ (+ CASE+ WHEN dt2."documentType" = 'purchaseOrder' THEN t."purchasingTerms"+ ELSE t."salesTerms"+ END+ )::jsonb AS value+ ) AS seed+ CROSS JOIN LATERAL jsonb_array_elements(dt2."blocks")+ WITH ORDINALITY AS arr(block, ord)+ WHERE dt2."documentType" IN (+ 'salesInvoice', 'salesOrder', 'quote', 'packingSlip', 'purchaseOrder'+ )+ GROUP BY dt2."id", dt2."companyId"+) AS sub+WHERE dt."id" = sub."id"+ AND dt."companyId" = sub."companyId"+ AND dt."blocks" IS DISTINCT FROM sub.new_blocks;diff --git a/packages/database/supabase/migrations/20260612143052_drop-pdf-thumbnail-settings.sql b/packages/database/supabase/migrations/20260612143052_drop-pdf-thumbnail-settings.sqlnew file mode 100644index 0000000000..a0228ce1af--- /dev/null+++ b/packages/database/supabase/migrations/20260612143052_drop-pdf-thumbnail-settings.sql@@ -0,0 +1,58 @@+-- The PDF thumbnail toggle is now per-document-template (Line Items block+-- "Show thumbnails" option). The company flag used to be authoritative at+-- render (the template's own option was ignored), so bake each company's+-- actual flag value into its existing templates' Line Items block before+-- dropping the columns — true OR false — so documents render identically.+-- (Companies with no stored template fall back to the template default of+-- thumbnails ON, matching the old column default of true.)++-- Sales documents: quote / sales order / sales invoice / packing slip.+UPDATE "documentTemplate" dt+SET blocks = (+ SELECT jsonb_agg(+ CASE+ WHEN block->>'type' = 'lineItems' THEN jsonb_set(+ block,+ '{options}',+ COALESCE(block->'options', '{}'::jsonb)+ || jsonb_build_object(+ 'showThumbnails', cs."includeThumbnailsOnSalesPdfs"+ )+ )+ ELSE block+ END+ )+ FROM jsonb_array_elements(dt.blocks) AS block+)+FROM "companySettings" cs+WHERE cs.id = dt."companyId"+ AND dt."documentType" IN ('quote', 'salesOrder', 'salesInvoice', 'packingSlip')+ AND dt.blocks @> '[{"type":"lineItems"}]';++-- Purchasing documents: purchase order.+UPDATE "documentTemplate" dt+SET blocks = (+ SELECT jsonb_agg(+ CASE+ WHEN block->>'type' = 'lineItems' THEN jsonb_set(+ block,+ '{options}',+ COALESCE(block->'options', '{}'::jsonb)+ || jsonb_build_object(+ 'showThumbnails', cs."includeThumbnailsOnPurchasingPdfs"+ )+ )+ ELSE block+ END+ )+ FROM jsonb_array_elements(dt.blocks) AS block+)+FROM "companySettings" cs+WHERE cs.id = dt."companyId"+ AND dt."documentType" = 'purchaseOrder'+ AND dt.blocks @> '[{"type":"lineItems"}]';++ALTER TABLE "companySettings"+ DROP COLUMN IF EXISTS "includeThumbnailsOnSalesPdfs";+ALTER TABLE "companySettings"+ DROP COLUMN IF EXISTS "includeThumbnailsOnPurchasingPdfs";diff --git a/packages/database/supabase/migrations/20260612151533_drop-job-traveler-work-instructions.sql b/packages/database/supabase/migrations/20260612151533_drop-job-traveler-work-instructions.sqlnew file mode 100644index 0000000000..d459d433cb--- /dev/null+++ b/packages/database/supabase/migrations/20260612151533_drop-job-traveler-work-instructions.sql@@ -0,0 +1,26 @@+-- "Include work instructions" is now a Job Traveler template option (operations+-- block "Show work instructions"). The company flag used to be authoritative at+-- render, so bake each company's actual flag value into its jobTraveler+-- template's operations block before dropping the column — true OR false — so+-- travelers render identically. (Companies with no stored template fall back to+-- the template default of OFF, matching the old column default of false.)+UPDATE "documentTemplate" dt+SET blocks = (+ SELECT jsonb_agg(+ CASE+ WHEN block->>'type' = 'operations' THEN block+ || jsonb_build_object(+ 'showWorkInstructions', cs."jobTravelerIncludeWorkInstructions"+ )+ ELSE block+ END+ )+ FROM jsonb_array_elements(dt.blocks) AS block+)+FROM "companySettings" cs+WHERE cs.id = dt."companyId"+ AND dt."documentType" = 'jobTraveler'+ AND dt.blocks @> '[{"type":"operations"}]';++ALTER TABLE "companySettings"+ DROP COLUMN IF EXISTS "jobTravelerIncludeWorkInstructions";diff --git a/packages/database/supabase/migrations/20260612163410_watermark-block.sql b/packages/database/supabase/migrations/20260612163410_watermark-block.sqlnew file mode 100644index 0000000000..5f8d0327c2--- /dev/null+++ b/packages/database/supabase/migrations/20260612163410_watermark-block.sql@@ -0,0 +1,21 @@+-- The watermark moved from a document setting (settings.showWatermark) to a+-- configurable built-in block. Existing transactional templates don't have the+-- block yet — without it, resolveTemplate would add it hidden and the watermark+-- would disappear. Prepend a watermark block, visible per the old setting+-- (default true, matching the old behaviour), then drop the stale setting key.+UPDATE "documentTemplate"+SET blocks =+ jsonb_build_array(+ jsonb_build_object(+ 'id', 'watermark',+ 'type', 'watermark',+ 'visible', COALESCE((settings->>'showWatermark')::boolean, true),+ 'opacity', 0.07::numeric+ )+ ) || blocks+WHERE "documentType" IN ('quote', 'salesOrder', 'salesInvoice', 'purchaseOrder')+ AND NOT (blocks @> '[{"type":"watermark"}]');++UPDATE "documentTemplate"+SET settings = settings - 'showWatermark'+WHERE settings ? 'showWatermark';diff --git a/packages/documents/package.json b/packages/documents/package.jsonindex 98c049a2fb..62b8f312c4 100644--- a/packages/documents/package.json+++ b/packages/documents/package.json@@ -13,7 +13,8 @@"nanoid": "catalog:","react-icons": "catalog:","react-pdf-tailwind": "2.3.0",- "sst": "catalog:"+ "sst": "catalog:",+ "zod": "catalog:"},"devDependencies": {"@carbon/config": "workspace:*",@@ -30,8 +31,10 @@"exports": {"./email": "./src/email/index.ts","./pdf": "./src/pdf/index.ts",+ "./template": "./src/template/index.ts","./zpl": "./src/zpl/index.ts",- "./qr": "./src/qr/qr-code.ts"+ "./qr": "./src/qr/qr-code.ts",+ "./labels": "./src/labels/index.ts"},"private": true,"scripts": {diff --git a/packages/documents/src/labels/index.ts b/packages/documents/src/labels/index.tsnew file mode 100644index 0000000000..fa5d7d2546--- /dev/null+++ b/packages/documents/src/labels/index.ts@@ -0,0 +1,2 @@+export type { ResolvedLabelLogo } from "./labelLogo";+export { resolveLabelLogo } from "./labelLogo";diff --git a/packages/documents/src/labels/labelLogo.ts b/packages/documents/src/labels/labelLogo.tsnew file mode 100644index 0000000000..c0a4d063eb--- /dev/null+++ b/packages/documents/src/labels/labelLogo.ts@@ -0,0 +1,78 @@+import type { LabelSize } from "@carbon/utils";+import type { DocumentTemplate } from "../template";+import { resolveTemplate } from "../template";++export interface ResolvedLabelLogo {+ /** Color logo URL for the PDF. */+ color?: string | null;+ /** Monochrome PNG data URL (PDF B&W). */+ mono?: string | null;+ /** ZPL `^GFA` graphic field. */+ gfa?: string | null;+ /** Rendered logo width in dots (for ZPL placement). */+ widthDots?: number;+}++/**+ * If the tracking-label template has a visible logo block, resolve the company+ * logo into a color URL (PDF), a monochrome PNG (PDF B&W) and a ZPL `^GFA`+ * graphic — the last two via the `logo-resizer` edge function (ImageMagick).+ * Returns null when there's no logo block or no company logo. `supabaseUrl` is+ * passed in so this stays free of app-specific auth imports.+ */+export async function resolveLabelLogo(+ company: { logoLight?: string | null; logoLightIcon?: string | null } | null,+ template: DocumentTemplate | null,+ labelSize: LabelSize,+ { supabaseUrl }: { supabaseUrl: string }+): Promise<ResolvedLabelLogo | null> {+ const resolved = resolveTemplate("trackingLabel", template);+ const logoBlock = resolved.blocks.find(+ (b) => b.type === "labelLogo" && b.visible+ );+ if (!logoBlock || logoBlock.type !== "labelLogo") return null;+ const { variant, crop } = logoBlock;+ const color =+ variant === "icon"+ ? (company?.logoLightIcon ?? company?.logoLight)+ : (company?.logoLight ?? company?.logoLightIcon);+ if (!color) return null;++ // Logo width ≈ 30% of the label, in printer dots.+ const dpi = labelSize.zpl?.dpi ?? 203;+ const labelInches = labelSize.zpl?.width ?? labelSize.width;+ const widthDots = Math.round(labelInches * dpi * 0.3);++ try {+ const imgRes = await fetch(color);+ const blob = await imgRes.blob();+ const formData = new FormData();+ formData.append("file", blob, "logo.png");+ formData.append("widthDots", String(widthDots));+ if (crop) {+ // ZPL/mono can't clip at render — crop server-side before threshold.+ formData.append("cropX", String(crop.x));+ formData.append("cropY", String(crop.y));+ formData.append("cropW", String(crop.width));+ formData.append("cropH", String(crop.height));+ }+ const res = await fetch(`${supabaseUrl}/functions/v1/logo-resizer`, {+ method: "POST",+ body: formData+ });+ const json = (await res.json()) as {+ monoPng?: string;+ gfa?: string;+ widthDots?: number;+ };+ return {+ color,+ mono: json.monoPng,+ gfa: json.gfa,+ widthDots: json.widthDots+ };+ } catch {+ // Edge function unavailable — color logo still works in the PDF.+ return { color };+ }+}diff --git a/packages/documents/src/pdf/IssuePDF.tsx b/packages/documents/src/pdf/IssuePDF.tsxindex beb0acfc88..5894c7f192 100644--- a/packages/documents/src/pdf/IssuePDF.tsx+++ b/packages/documents/src/pdf/IssuePDF.tsx@@ -1,80 +1,37 @@-import type { Database } from "@carbon/database";-import type { JSONContent } from "@carbon/react";-import { formatDate } from "@carbon/utils";-import { Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";import type { PDF } from "../types";-import { Header, Note, Template } from "./components";--type ListItem = {- id: string;- name: string;-};--type IssueItem = Database["public"]["Tables"]["nonConformanceItem"]["Row"] & {- name: string | null;-};--type ActionTask =- Database["public"]["Tables"]["nonConformanceActionTask"]["Row"] & {- supplier: { name: string } | null;- };--type JobOperationStepRecord =- Database["public"]["Tables"]["jobOperationStepRecord"]["Row"];--type JobOperationStepWithRecords = {- id: string;- name: string | null;- operationId: string;- nonConformanceActionId: string | null;- jobOperationStepRecord: JobOperationStepRecord[];-};--type Associations = {- items: any[];- customers: any[];- suppliers: any[];- jobOperations: any[];- purchaseOrderLines: any[];- salesOrderLines: any[];- shipmentLines: any[];- receiptLines: any[];- trackedEntities: any[];-};+import type {+ ActionTask,+ Associations,+ IssueData,+ IssueItem,+ JobOperationStepWithRecords,+ ListItem+} from "./blocks/issue";+import { buildIssueVars, issueBlockRegistry } from "./blocks/issue";+import { Template } from "./components";interface IssuePDFProps extends PDF {- nonConformance: Database["public"]["Tables"]["nonConformance"]["Row"];- nonConformanceTypes: Database["public"]["Tables"]["nonConformanceType"]["Row"][];+ nonConformance: IssueData["nonConformance"];+ nonConformanceTypes: IssueData["nonConformanceTypes"];actionTasks: ActionTask[];requiredActions: ListItem[];- reviewers: Database["public"]["Tables"]["nonConformanceReviewer"]["Row"][];+ reviewers: IssueData["reviewers"];items: IssueItem[];associations?: Associations | null;assignees?: Record<string, string>;jobOperationStepRecords?: JobOperationStepWithRecords[];operationToJobId?: Record<string, string>;+ template?: DocumentTemplate | null;+ sections?: Record<string, ResolvedSection>;}-const tw = createTw({- theme: {- fontFamily: {- sans: ["Inter", "Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 50: "#f9fafb",- 200: "#e5e7eb",- 400: "#9ca3af",- 600: "#4b5563",- 800: "#1f2937"- }- }- }- }-});-const IssuePDF = ({company,meta,@@ -83,19 +40,61 @@ const IssuePDF = ({actionTasks,requiredActions,reviewers,+ items,associations,assignees = {},jobOperationStepRecords = [],operationToJobId = {},locale,- title = "Issue Report"+ title = "Issue Report",+ template,+ sections = {}}: IssuePDFProps) => {- const sortedActionTasks = [...actionTasks].sort(- (a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)- );+ const resolved = resolveTemplate("issue", template ?? null);+ const vars = buildIssueVars({ nonConformance, company });++ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(resolved.headerSectionId+ ? (sections[resolved.headerSectionId]?.config ?? {})+ : {})+ };- const ncType = nonConformanceTypes.find(- (type) => type.id === nonConformance.nonConformanceTypeId+ const data: IssueData = {+ company,+ locale,+ nonConformance,+ nonConformanceTypes,+ actionTasks,+ requiredActions,+ reviewers,+ items,+ associations,+ assignees,+ jobOperationStepRecords,+ operationToJobId,+ theme: resolved.theme,+ sections,+ vars,+ headerOptions+ };++ const headerSection = resolved.headerSectionId+ ? sections[resolved.headerSectionId]?.content+ : undefined;+ const footerSection = resolved.footerSectionId+ ? sections[resolved.footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;++ const showHeader = resolved.headerSectionId !== null;+ const visibleBlocks = resolved.blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader));return (@@ -107,423 +106,19 @@ const IssuePDF = ({subject: meta?.subject ?? "Issue Report"}}footerLabel={`Issue #${nonConformance.nonConformanceId}`}+ showFooter={resolved.footerSectionId !== null}+ showPageNumbers={resolved.settings.showPageNumbers}+ pageNumberFormat={resolved.settings.pageNumberFormat}+ showRegistrationLine={resolved.settings.showRegistrationLine}+ fontFamily={resolved.settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}>- <Header- company={company}- title="Issue Report"- documentId={nonConformance.nonConformanceId}- date={nonConformance.openDate}- locale={locale}- />-- {/* Issue Details */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Issue Details- </Text>- <View style={tw("text-[10px] text-gray-800")}>- {nonConformance.name && (- <Text style={tw("font-bold")}>{nonConformance.name}</Text>- )}- {ncType?.name && (- <Text style={tw("mt-1")}>Type: {ncType.name}</Text>- )}- {nonConformance.status && (- <Text>Status: {nonConformance.status}</Text>- )}- <Text>- Initiated By: {assignees[nonConformance.createdBy] || "Unknown"}- </Text>- </View>- </View>- <View style={tw("w-1/2 p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Dates- </Text>- <View style={tw("text-[10px] text-gray-800")}>- {nonConformance.openDate && (- <Text>- Started:{" "}- {formatDate(nonConformance.openDate, undefined, locale)}- </Text>- )}- {nonConformance.closeDate && (- <Text>- Completed:{" "}- {formatDate(nonConformance.closeDate, undefined, locale)}- </Text>- )}- </View>- </View>- </View>- </View>-- {/* Associations */}- {associations && (- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Associations- </Text>- <View style={tw("flex flex-col")}>- {associations.items?.map((item: any) => (- <View- key={item.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>Item:</Text>- <Text style={tw("text-gray-800")}>- {item.documentReadableId}- </Text>- {item.disposition && (- <>- <Text style={tw("text-gray-400")}>-</Text>- <Text style={tw("text-gray-800")}>- {item.disposition}- </Text>- </>- )}- {item.quantity && (- <>- <Text style={tw("text-gray-400")}>-</Text>- <Text style={tw("text-gray-800")}>- Qty: {item.quantity}- </Text>- </>- )}- </View>- ))}- {associations.customers?.map((customer: any) => (- <View- key={customer.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Customer:- </Text>- <Text style={tw("text-gray-800")}>- {customer.documentReadableId}- </Text>- </View>- ))}- {associations.suppliers?.map((supplier: any) => (- <View- key={supplier.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Supplier:- </Text>- <Text style={tw("text-gray-800")}>- {supplier.documentReadableId}- </Text>- </View>- ))}- {associations.jobOperations?.map((job: any) => (- <View- key={job.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Job Operation:- </Text>- <Text style={tw("text-gray-800")}>- {job.documentReadableId}- </Text>- </View>- ))}- {associations.purchaseOrderLines?.map((po: any) => (- <View- key={po.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Purchase Order:- </Text>- <Text style={tw("text-gray-800")}>- {po.documentReadableId}- </Text>- </View>- ))}- {associations.salesOrderLines?.map((so: any) => (- <View- key={so.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Sales Order:- </Text>- <Text style={tw("text-gray-800")}>- {so.documentReadableId}- </Text>- </View>- ))}- {associations.shipmentLines?.map((shipment: any) => (- <View- key={shipment.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Shipment:- </Text>- <Text style={tw("text-gray-800")}>- {shipment.documentReadableId}- </Text>- </View>- ))}- {associations.receiptLines?.map((receipt: any) => (- <View- key={receipt.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Receipt:- </Text>- <Text style={tw("text-gray-800")}>- {receipt.documentReadableId}- </Text>- </View>- ))}- {associations.trackedEntities?.map((entity: any) => (- <View- key={entity.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"- )}- >- <Text style={tw("w-1/4 font-bold text-gray-600")}>- Tracked Entity:- </Text>- <Text style={tw("text-gray-800")}>- {entity.documentReadableId}- </Text>- </View>- ))}- </View>- </View>- </View>- )}-- {/* Description of Issue */}- {Object.keys(nonConformance.content ?? {}).length > 0 && (- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Description of Issue- </Text>- <View style={tw("mt-1")}>- <Note content={nonConformance.content as JSONContent} />- </View>- </View>- </View>- )}-- {/* Action Tasks */}- {sortedActionTasks.length > 0 && (- <View style={tw("mb-4")}>- {sortedActionTasks.map((task) => (- <View- key={task.id}- style={tw("border border-gray-200 mb-4")}- wrap={false}- >- <View style={tw("p-3")}>- <Text- style={tw(- "text-[9px] font-bold text-gray-600 mb-1 uppercase"- )}- >- {task.supplier?.name ? "Supplier " : ""}- {- requiredActions.find(- (action) => action.id === task.actionTypeId- )?.name- }- </Text>- <View style={tw("flex flex-col gap-1 text-[10px]")}>- {task.supplier?.name && (- <View style={tw("flex flex-row gap-2")}>- <Text style={tw("font-bold text-gray-600")}>- Supplier:- </Text>- <Text style={tw("text-gray-800")}>- {task.supplier.name}- </Text>- </View>- )}- {task.assignee && assignees[task.assignee] && (- <View style={tw("flex flex-row gap-2")}>- <Text style={tw("font-bold text-gray-600")}>- {task.supplier?.name ? "Verified by" : "Completed by"}:- </Text>- <Text style={tw("text-gray-800")}>- {assignees[task.assignee]}- </Text>- </View>- )}- {task.completedDate && (- <View style={tw("flex flex-row gap-2")}>- <Text style={tw("font-bold text-gray-600")}>- Completed on:- </Text>- <Text style={tw("text-gray-800")}>- {task.completedDate}- </Text>- </View>- )}- </View>- {Object.keys(task.notes ?? {}).length > 0 && (- <View style={tw("mt-2 pt-2 border-t border-gray-200")}>- <Note content={task.notes as JSONContent} />- </View>- )}- {/* Job Operation Step Records */}- {jobOperationStepRecords- .filter((step) => step.nonConformanceActionId === task.id)- .some((step) =>- step.jobOperationStepRecord?.some(- (record) => record.booleanValue !== null- )- ) && (- <View style={tw("mt-2 pt-2 border-t border-gray-200")}>- <Text- style={tw(- "text-[9px] font-bold text-gray-600 mb-1 uppercase"- )}- >- Inspections- </Text>- {jobOperationStepRecords- .filter((step) => step.nonConformanceActionId === task.id)- .map((step) =>- step.jobOperationStepRecord- ?.filter((record) => record.booleanValue !== null)- .map((record) => (- <View- key={record.id}- style={tw(- "flex flex-row gap-2 text-[10px] py-0.5"- )}- >- <View- style={{- width: 10,- height: 10,- border: "1px solid #9ca3af",- marginTop: 2,- position: "relative"- }}- >- <Text- style={{- position: "absolute",- fontSize: 10,- fontWeight: "bold",- lineHeight: 1,- textAlign: "center",- top: -3,- left: -1.5- }}- >- {record.booleanValue ? "✓" : ""}- </Text>- </View>- <View style={tw("flex flex-col")}>- <Text style={tw("text-gray-800")}>- {step.name}- </Text>- <Text- style={tw("text-[8px] text-gray-400 mt-0.5")}- >- {operationToJobId[step.operationId] && (- <>- Job {operationToJobId[step.operationId]} •{" "}- </>- )}- {assignees[record.createdBy] || "Unknown"} •{" "}- {- new Date(record.createdAt)- .toISOString()- .split("T")[0]- }- </Text>- </View>- </View>- ))- )}- </View>- )}- </View>- </View>- ))}- </View>- )}-- {/* MRB Reviewers */}- {reviewers.length > 0 && (- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-2 uppercase")}- >- MRB- </Text>- {reviewers.map((reviewer, index) => (- <View- key={reviewer.id}- style={tw(- `flex flex-col gap-1 py-2 ${- index < reviewers.length - 1- ? "border-b border-gray-200"- : ""- }`- )}- >- <View style={tw("flex flex-row justify-between")}>- <Text style={tw("text-[10px] font-bold text-gray-800")}>- {reviewer.title}- </Text>- <Text style={tw("text-[10px] text-gray-600")}>- {reviewer.status}- </Text>- </View>-- {Object.keys(reviewer.notes ?? {}).length > 0 && (- <View style={tw("mt-1")}>- <Note content={reviewer.notes as JSONContent} />- </View>- )}- </View>- ))}- </View>- </View>- )}+ {visibleBlocks.map((block) => {+ const render = issueBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</Template>);};diff --git a/packages/documents/src/pdf/JobTravelerPDF.tsx b/packages/documents/src/pdf/JobTravelerPDF.tsxindex 7268953788..78a1771ed9 100644--- a/packages/documents/src/pdf/JobTravelerPDF.tsx+++ b/packages/documents/src/pdf/JobTravelerPDF.tsx@@ -1,12 +1,21 @@import type { Database } from "@carbon/database";-import { getMESUrl } from "@carbon/env";import type { JSONContent } from "@carbon/react";-import { formatDate, formatFactor } from "@carbon/utils";-import { Image, StyleSheet, Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";-import { generateQRCode } from "../qr/qr-code";-import type { Company, PDF } from "../types";-import { Header, Note, Template } from "./components";+import { View } from "@react-pdf/renderer";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";+import type { PDF } from "../types";+import type { JobTravelerData } from "./blocks/jobTraveler";+import {+ buildJobTravelerVars,+ jobTravelerBlockRegistry+} from "./blocks/jobTraveler";+import { tw } from "./blocks/jobTraveler/tw";+import { Template } from "./components";type JobOperationStep = Database["public"]["Tables"]["jobOperationStep"]["Row"];@@ -17,7 +26,7 @@ type JobOperationWithSteps =interface JobTravelerProps extends PDF {job: Database["public"]["Views"]["jobs"]["Row"];- jobMakeMethod: Database["public"]["Tables"]["jobMakeMethod"]["Row"];+ jobMakeMethod?: Database["public"]["Tables"]["jobMakeMethod"]["Row"];jobOperations: JobOperationWithSteps[];customer: Database["public"]["Tables"]["customer"]["Row"] | null;item: Database["public"]["Tables"]["item"]["Row"];@@ -25,523 +34,69 @@ interface JobTravelerProps extends PDF {bomId?: string;notes?: JSONContent;thumbnail?: string | null;- includeWorkInstructions?: boolean;+ template?: DocumentTemplate | null;+ sections?: Record<string, ResolvedSection>;}-function getStartPath(operationId: string) {- return `${getMESUrl()}/x/start/${operationId}`;-}--function getEndPath(operationId: string) {- return `${getMESUrl()}/x/end/${operationId}`;-}--// Initialize tailwind-styled-components-const tw = createTw({- theme: {- fontFamily: {- sans: ["Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 500: "#7d7d7d"- }- }- }- }-});--// JobHeader styles-const jobHeaderStyles = StyleSheet.create({- jobHeader: {- border: "1px solid #CCC",- borderRadius: 6,- padding: 16,- fontSize: 10,- display: "flex",- flexDirection: "row",- justifyContent: "space-between",- alignItems: "flex-start",- marginBottom: 20,- gap: 60- },- leftSection: {- flex: 1,- marginTop: 5- },- rightSection: {- flex: 1- },- infoRow: {- display: "flex",- flexDirection: "row",- justifyContent: "space-between",- marginBottom: 4- },- label: {- fontSize: 11,- fontWeight: 600,- color: "#374151"- },- value: {- fontSize: 11,- fontWeight: 400,- color: "#111827"- },- sectionTitle: {- fontSize: 11,- fontWeight: 700,- marginBottom: 8,- color: "#111827",- borderBottom: "1px solid #d1d5db",- paddingBottom: 2- }-});--type JobHeaderProps = {- company: Company;- job: Database["public"]["Views"]["jobs"]["Row"];- customer: Database["public"]["Tables"]["customer"]["Row"] | null;- item: Database["public"]["Tables"]["item"]["Row"];- jobOperations: JobOperationWithSteps[];- batchNumber?: string;- bomId?: string;- thumbnail?: string | null;+type PageContentProps = Omit<+ JobTravelerProps,+ "meta" | "title" | "jobMakeMethod"+> & {methodRevision?: string | null;- locale?: string;};-const JobHeader = ({- batchNumber,- bomId,- company,- customer,- item,- job,- locale,- methodRevision,- thumbnail,- jobOperations-}: JobHeaderProps) => {- const getTargetInfo = () => {- if (job.salesOrderId && job.salesOrderLineId) {- return `Sales Order: ${job.salesOrderReadableId || "Make to Order"}`;- }- return "Inventory";+/** Build the data bag every Job Traveler block renderer reads from. */+function buildData(+ props: PageContentProps,+ template: DocumentTemplate+): JobTravelerData {+ const { sections = {} } = props;+ const vars = buildJobTravelerVars(props);+ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(template.headerSectionId+ ? (sections[template.headerSectionId]?.config ?? {})+ : {})};-- const getTrackingNumber = () => {- if (batchNumber) {- const trackingType = item.itemTrackingType;- return `${trackingType} Number: ${batchNumber}`;- }- return null;+ return {+ company: props.company,+ locale: props.locale,+ job: props.job,+ jobOperations: props.jobOperations,+ customer: props.customer,+ item: props.item,+ batchNumber: props.batchNumber,+ bomId: props.bomId,+ notes: props.notes,+ thumbnail: props.thumbnail,+ methodRevision: props.methodRevision,+ theme: template.theme,+ sections,+ vars,+ headerOptions};+}- return (- <View style={jobHeaderStyles.jobHeader}>- <View style={jobHeaderStyles.leftSection}>- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Job ID:</Text>- <Text style={jobHeaderStyles.value}>{job.jobId}</Text>- </View>-- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Part ID:</Text>- <Text style={jobHeaderStyles.value}>- {job.itemReadableIdWithRevision}- </Text>- </View>-- {methodRevision && methodRevision !== "0" && (- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Method Revision:</Text>- <Text style={jobHeaderStyles.value}>V{methodRevision}</Text>- </View>- )}-- {getTrackingNumber() && (- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Tracking:</Text>- <Text style={jobHeaderStyles.value}>{getTrackingNumber()}</Text>- </View>- )}-- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Item:</Text>- <Text style={jobHeaderStyles.value}>- {item.name || item.readableIdWithRevision}- </Text>- </View>-- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Quantity:</Text>- <Text style={jobHeaderStyles.value}>- {jobOperations?.[0]?.targetQuantity ?? job.quantity}{" "}- {job.unitOfMeasureCode}- </Text>- </View>-- {job.scrapQuantity && job.scrapQuantity > 0 && (- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Scrap Qty:</Text>- <Text style={jobHeaderStyles.value}>- {job.scrapQuantity} {job.unitOfMeasureCode}- </Text>- </View>- )}- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Target:</Text>- <Text style={jobHeaderStyles.value}>{getTargetInfo()}</Text>- </View>- {customer && (- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Customer:</Text>- <Text style={jobHeaderStyles.value}>{customer.name}</Text>- </View>- )}-- {job.startDate && (- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Start Date:</Text>- <Text style={jobHeaderStyles.value}>- {formatDate(job.startDate, undefined, locale)}- </Text>- </View>- )}-- {job.dueDate && (- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Due Date:</Text>- <Text style={jobHeaderStyles.value}>- {formatDate(job.dueDate, undefined, locale)}- </Text>- </View>- )}-- {job.deadlineType && (- <View style={jobHeaderStyles.infoRow}>- <Text style={jobHeaderStyles.label}>Deadline Type:</Text>- <Text style={jobHeaderStyles.value}>{job.deadlineType}</Text>- </View>- )}- </View>-- <View style={jobHeaderStyles.rightSection}>- {thumbnail && (- <View>- <Image- src={thumbnail}- style={tw("w-full h-auto border rounded-lg border-gray-300")}- />- </View>- )}- </View>- </View>+/**+ * Block-driven page body (no Document/Template wrapper) so the multi-make-method+ * route can render one of these per `<Page>`. Resolves the stored template and+ * maps each visible block through the registry.+ */+export const JobTravelerPageContent = (props: PageContentProps) => {+ const resolved = resolveTemplate("jobTraveler", props.template ?? null);+ const data = buildData(props, resolved);+ const showHeader = resolved.headerSectionId !== null;+ const visibleBlocks = resolved.blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader));-};-// Page content component without Document/Template wrapper (for combining multiple make methods)-export const JobTravelerPageContent = ({- company,- job,- jobOperations,- customer,- item,- batchNumber,- bomId,- locale,- notes,- thumbnail,- methodRevision,- includeWorkInstructions = false-}: Omit<JobTravelerProps, "meta" | "title" | "jobMakeMethod"> & {- methodRevision?: string | null;-}) => {return (<View style={tw("flex flex-col")}>- {/* Original Header Section with company logo and job title */}- <View style={tw("mb-6")}>- <Header- company={company}- title="Job Traveler"- documentId={job.jobId}- documentSubId={- job.salesOrderReadableId- ? `SO# ${job.salesOrderReadableId}`- : undefined- }- date={job.startDate}- locale={locale}- />- </View>-- {/* Job Header Section with detailed information */}- <View style={tw("mb-6")}>- <JobHeader- company={company}- job={job}- customer={customer}- item={item}- batchNumber={batchNumber}- bomId={bomId}- locale={locale}- thumbnail={thumbnail}- methodRevision={methodRevision}- jobOperations={jobOperations}- />- </View>-- {/* Job Information Section */}- <View style={tw("mb-6 text-xs")}>- <View- style={tw(- "flex flex-row justify-between items-center py-3 px-[6px] border-t border-b border-gray-300 font-bold uppercase page-break-inside-avoid gap-x-6"- )}- >- <Text style={tw("w-1/12 text-left")}>Seq</Text>- <Text style={tw("w-8/12 text-left")}>Operation</Text>- <Text style={tw("w-3/12 text-left")}>Expected Times</Text>- </View>-- {jobOperations- .sort((a, b) => a.order - b.order)- .map((operation, index) => {- const isInside = operation.operationType === "Inside";- const setupQrCode =- operation.setupTime > 0- ? generateQRCode(`${getStartPath(operation.id)}?type=Setup`, 10)- : null;- let laborQrCode =- operation.laborTime > 0- ? generateQRCode(`${getStartPath(operation.id)}?type=Labor`, 10)- : null;- let machiningQrCode =- operation.machineTime > 0- ? generateQRCode(- `${getStartPath(operation.id)}?type=Machine`,- 10- )- : null;- let completeQrCode = generateQRCode(getEndPath(operation.id), 10);-- if (- setupQrCode === null &&- laborQrCode === null &&- machiningQrCode === null- ) {- laborQrCode = generateQRCode(- `${getStartPath(operation.id)}?type=Labor`,- 10- );- }-- const setupTimeFormatted = formatFactor(- operation.setupTime,- operation.setupUnit- );- const laborTimeFormatted = formatFactor(- operation.laborTime,- operation.laborUnit- );- const machineTimeFormatted = formatFactor(- operation.machineTime,- operation.machineUnit- );- const hasExpectedTimes =- setupTimeFormatted || laborTimeFormatted || machineTimeFormatted;-- const workInstruction = operation.workInstruction as- | JSONContent- | undefined;- const hasWorkInstruction =- includeWorkInstructions &&- workInstruction &&- typeof workInstruction === "object" &&- "content" in workInstruction &&- Array.isArray(workInstruction.content) &&- workInstruction.content.length > 0;- const hasProcedureSteps =- includeWorkInstructions &&- operation.jobOperationStep &&- operation.jobOperationStep.length > 0;-- return (- <View- style={tw(- "flex flex-col border-b border-gray-300 py-4 px-[6px] page-break-inside-avoid"- )}- key={operation.id}- wrap={includeWorkInstructions ? true : false}- >- <View style={tw("flex flex-col gap-y-4")} wrap={false}>- <View- style={tw(- "flex flex-row justify-between items-start gap-x-6"- )}- wrap={false}- >- <Text style={tw("w-1/12 font-bold text-left")}>- {getParallelizedOrder(index, operation, jobOperations)}- </Text>- <View style={tw("w-8/12 text-left text-[12px]")}>- <Text style={tw("font-bold")}>- {operation.description}- </Text>- </View>- <View style={tw("w-3/12 text-left")}>- {hasExpectedTimes && (- <View style={tw("flex flex-col gap-1")}>- {setupTimeFormatted && (- <Text style={tw("text-[10px]")}>- Setup: {setupTimeFormatted}- </Text>- )}- {laborTimeFormatted && (- <Text style={tw("text-[10px]")}>- Labor: {laborTimeFormatted}- </Text>- )}- {machineTimeFormatted && (- <Text style={tw("text-[10px]")}>- Machine: {machineTimeFormatted}- </Text>- )}- </View>- )}- </View>- </View>-- <View- style={tw(- "flex flex-row justify-between items-center py-3 px-[6px] border-gray-300 font-bold uppercase page-break-inside-avoid"- )}- >- <Text style={tw("text-left pr-4")}>Actions</Text>- </View>-- <View style={tw("w-full flex flex-row justify-start gap-2")}>- {isInside && setupQrCode && (- <View style={tw("flex flex-col items-center w-1/4")}>- <>- <Image src={setupQrCode} style={tw("w-16 h-16")} />- <Text style={tw("text-[10px] mt-1")}>Setup</Text>- </>- </View>- )}-- {isInside && laborQrCode && (- <View style={tw("flex flex-col items-center w-1/4")}>- <>- <Image src={laborQrCode} style={tw("w-16 h-16")} />- <Text style={tw("text-[10px] mt-1")}>Labor</Text>- </>- </View>- )}- {isInside && machiningQrCode && (- <View style={tw("flex flex-col items-center w-1/4")}>- <>- <Image- src={machiningQrCode}- style={tw("w-16 h-16")}- />- <Text style={tw("text-[10px] mt-1")}>Machine</Text>- </>- </View>- )}- <View style={tw("flex flex-col items-center w-1/4")}>- <Image src={completeQrCode} style={tw("w-16 h-16")} />- <Text style={tw("text-[10px] mt-1")}>Complete</Text>- </View>- </View>- </View>-- {(hasWorkInstruction || hasProcedureSteps) && (- <View style={tw("mt-2 ml-8")}>- {hasProcedureSteps && (- <View style={tw("mb-2")}>- <Text- style={{- marginBottom: 8,- borderTopWidth: 1,- borderTopColor: "#d1d5db",- borderBottomWidth: 1,- borderColor: "#d1d5db",- paddingTop: 4,- paddingBottom: 4,- fontSize: 9,- fontWeight: 700,- textTransform: "uppercase"- }}- >- Procedure Steps- </Text>- {operation- .jobOperationStep!.sort(- (a, b) => a.sortOrder - b.sortOrder- )- .map((step) => {- const stepDescription = step.description as- | JSONContent- | undefined;- const hasStepDescription =- stepDescription &&- typeof stepDescription === "object" &&- "content" in stepDescription &&- Array.isArray(stepDescription.content) &&- stepDescription.content.length > 0;-- return (- <View- key={step.id}- style={tw("flex flex-row items-start mb-1")}- >- <View- style={{- width: 9,- height: 9,- borderWidth: 1,- borderColor: "#374151",- marginRight: 6,- marginTop: 1- }}- />- <View style={tw("flex-1")}>- <Text style={tw("text-[9px] font-bold")}>- {step.name}- </Text>- {hasStepDescription && (- <Note- title="Procedure Step"- content={stepDescription}- />- )}- </View>- </View>- );- })}- </View>- )}- {hasWorkInstruction && (- <Note- title="Work Instructions"- content={workInstruction}- />- )}- </View>- )}- </View>- );- })}- </View>-- {/* Notes Section */}- {notes && (- <View style={tw("mb-6")}>- <Note title="Job Notes" content={notes} />- </View>- )}+ {visibleBlocks.map((block) => {+ const render = jobTravelerBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</View>);};@@ -560,8 +115,25 @@ const JobTravelerPDF = ({notes,thumbnail,title = "Job Traveler",- includeWorkInstructions = false+ template,+ sections = {}}: JobTravelerProps) => {+ const resolved = resolveTemplate("jobTraveler", template ?? null);+ const vars = buildJobTravelerVars({ job, item, customer, company });++ const headerSection = resolved.headerSectionId+ ? sections[resolved.headerSectionId]?.content+ : undefined;+ const footerSection = resolved.footerSectionId+ ? sections[resolved.footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;+return (<Templatetitle={title}@@ -570,6 +142,14 @@ const JobTravelerPDF = ({keywords: meta?.keywords ?? "job traveler, manufacturing",subject: meta?.subject ?? "Job Traveler"}}+ footerDocumentId={job?.jobId}+ showFooter={resolved.footerSectionId !== null}+ showPageNumbers={resolved.settings.showPageNumbers}+ pageNumberFormat={resolved.settings.pageNumberFormat}+ showRegistrationLine={resolved.settings.showRegistrationLine}+ fontFamily={resolved.settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}><JobTravelerPageContentcompany={company}@@ -582,29 +162,12 @@ const JobTravelerPDF = ({locale={locale}notes={notes}thumbnail={thumbnail}- methodRevision={jobMakeMethod.version?.toString()}- includeWorkInstructions={includeWorkInstructions}+ methodRevision={jobMakeMethod?.version?.toString()}+ template={template}+ sections={sections}/></Template>);};export default JobTravelerPDF;--type Operation = Database["public"]["Tables"]["jobOperation"]["Row"];--function getParallelizedOrder(- index: number,- item: Operation,- items: Operation[]-) {- if (item?.operationOrder !== "With Previous") return index + 1;- // traverse backwards through the list of items to find the first item that is not "With Previous" and return its index + 1- for (let i = index - 1; i >= 0; i--) {- if (items[i]?.operationOrder !== "With Previous") {- return i + 1;- }- }-- return 1;-}diff --git a/packages/documents/src/pdf/PackingSlipPDF.tsx b/packages/documents/src/pdf/PackingSlipPDF.tsxindex 215c365379..46b7177e43 100644--- a/packages/documents/src/pdf/PackingSlipPDF.tsx+++ b/packages/documents/src/pdf/PackingSlipPDF.tsx@@ -1,14 +1,20 @@-import bwipjs from "@bwip-js/node";import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";-import type { TrackedEntityAttributes } from "@carbon/utils";-import { formatDate } from "@carbon/utils";-import { Image, Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";-import { generateQRCode } from "../qr/qr-code";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";import type { PDF } from "../types";import { getRegistrationFooter } from "../utils/shared";-import { Header, Note, Template } from "./components";+import type { PackingSlipData } from "./blocks/packingSlip";+import {+ buildPackingSlipVars,+ packingSlipBlockRegistry+} from "./blocks/packingSlip";+import { Template } from "./components";interface PackingSlipProps extends PDF {customer:@@ -25,27 +31,10 @@ interface PackingSlipProps extends PDF {terms: JSONContent;trackedEntities: Database["public"]["Tables"]["trackedEntity"]["Row"][];thumbnails?: Record<string, string | null>;+ template?: DocumentTemplate | null;+ sections?: Record<string, ResolvedSection>;}-const tw = createTw({- theme: {- fontFamily: {- sans: ["Inter", "Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 50: "#f9fafb",- 200: "#e5e7eb",- 400: "#9ca3af",- 600: "#4b5563",- 800: "#1f2937"- }- }- }- }-});-const PackingSlipPDF = ({company,customer,@@ -62,20 +51,64 @@ const PackingSlipPDF = ({title = "Packing Slip",locale,trackedEntities,- thumbnails+ thumbnails,+ template,+ sections = {}}: PackingSlipProps) => {- const {- addressLine1,- addressLine2,- city,- stateProvince,- postalCode,- countryCode- } = shippingAddress ?? {};-- const hasTrackedEntities = trackedEntities.length > 0;+ const { blocks, theme, settings, headerSectionId, footerSectionId } =+ resolveTemplate("packingSlip", template);++ const vars = buildPackingSlipVars({+ shipment,+ customer,+ shippingAddress,+ company+ });- let rowIndex = 0;+ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})+ };++ const data: PackingSlipData = {+ company,+ locale,+ customer,+ customerReference,+ sourceDocument,+ sourceDocumentId,+ shipment,+ shipmentLines,+ shippingAddress,+ paymentTerm,+ shippingMethod,+ terms,+ trackedEntities,+ thumbnails,+ theme,+ sections,+ vars,+ headerOptions+ };++ const headerSection = headerSectionId+ ? sections[headerSectionId]?.content+ : undefined;+ const footerSection = footerSectionId+ ? sections[footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;++ const showHeader = headerSectionId !== null;+ const showFooter = footerSectionId !== null;+ const visibleBlocks = blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader)+ );return (<Template@@ -91,234 +124,21 @@ const PackingSlipPDF = ({company.taxId)}footerDocumentId={shipment?.shipmentId}+ showFooter={showFooter}+ showPageNumbers={settings.showPageNumbers}+ pageNumberFormat={settings.pageNumberFormat}+ showRegistrationLine={settings.showRegistrationLine}+ fontFamily={settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}>- <Header- company={company}- title="Packing Slip"- documentId={shipment?.shipmentId}- date={shipment?.postingDate}- locale={locale}- />-- {/* Ship To */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Ship To- </Text>- <View style={tw("text-[10px] text-gray-800")}>- {customer.name && (- <Text style={tw("font-bold")}>{customer.name}</Text>- )}- {addressLine1 && <Text style={tw("mt-1")}>{addressLine1}</Text>}- {addressLine2 && <Text>{addressLine2}</Text>}- {city && <Text>{city}</Text>}- {(stateProvince || postalCode) && (- <Text>- {[stateProvince, postalCode].filter(Boolean).join(" ")}- </Text>- )}- {countryCode && <Text>{countryCode}</Text>}- </View>- </View>- <View style={tw("w-1/2 p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Shipment Details- </Text>- <View style={tw("text-[10px] text-gray-800")}>- {shipment?.postingDate && (- <Text>- Date: {formatDate(shipment.postingDate, undefined, locale)}- </Text>- )}- {sourceDocument && sourceDocumentId && (- <Text>- {sourceDocument}: {sourceDocumentId}- </Text>- )}- {customerReference && (- <Text>Customer PO #: {customerReference}</Text>- )}- {shipment?.trackingNumber && (- <Text>Tracking: {shipment.trackingNumber}</Text>- )}- </View>- </View>- </View>- </View>-- {/* Shipping & Payment */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Shipping- </Text>- <View style={tw("text-[10px] text-gray-800")}>- {shippingMethod?.name && (- <Text>Method: {shippingMethod.name}</Text>- )}- </View>- </View>- <View style={tw("w-1/2 p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Payment- </Text>- <View style={tw("text-[10px] text-gray-800")}>- {paymentTerm?.name && <Text>Terms: {paymentTerm.name}</Text>}- </View>- </View>- </View>- </View>-- {/* Line Items Table */}- <View style={tw("mb-4")}>- {/* Header */}- <View- style={tw(- "flex flex-row bg-gray-800 py-2 px-3 text-white text-[9px] font-bold"- )}- >- <Text- style={tw(`w-${hasTrackedEntities ? "5/12" : "7/12"} text-left`)}- >- Description- </Text>- <Text style={tw("w-2/12 text-right")}>Qty</Text>- {hasTrackedEntities && (- <Text style={tw("w-5/12 text-right")}>Serial/Batch</Text>- )}- </View>-- {/* Rows */}- {shipmentLines- .filter((line) => (line?.shippedQuantity ?? 0) > 0)- .map((line) => {- const barcodeDataUrl = generateBarcode(line?.itemReadableId || "");- const trackedEntitiesForLine = trackedEntities.filter(- (entity) =>- (entity.attributes as TrackedEntityAttributes)?.[- "Shipment Line"- ] === line.id- );- const isEven = rowIndex % 2 === 0;- rowIndex++;-- return (- <View- key={line.id}- style={tw(- `flex flex-row py-2 px-3 border-b border-gray-200 text-[10px] ${- isEven ? "bg-white" : "bg-gray-50"- }`- )}- wrap={false}- >- <View- style={tw(`w-${hasTrackedEntities ? "5/12" : "7/12"} pr-2`)}- >- <Text style={tw("text-gray-800")}>- {getLineDescription(line)}- </Text>- <Text style={tw("text-[8px] text-gray-400 mt-0.5")}>- {getLineDescriptionDetails(line)}- </Text>-- {thumbnails &&- line.id != null &&- line.id in thumbnails &&- thumbnails[line.id] && (- <View style={tw("mt-1 w-16")}>- <Image- src={thumbnails[line.id]!}- style={tw("w-full h-auto")}- />- </View>- )}-- <View style={tw("mt-1")}>- <Image src={barcodeDataUrl} style={tw("max-w-[50%]")} />- </View>- </View>- <Text style={tw("w-2/12 text-right text-gray-600")}>- {getLineQuantity(line)}- </Text>- {hasTrackedEntities && (- <View style={tw("w-5/12 flex flex-col gap-1 items-end")}>- {trackedEntitiesForLine.map((entity) => {- const qrCodeDataUrl = generateQRCode(entity.id, 8);- return (- <View- key={entity.id}- style={tw("mb-1 flex flex-row items-center gap-1")}- >- <Text style={tw("text-[8px] text-gray-600")}>- {entity.id}- </Text>- <Image- src={qrCodeDataUrl}- style={{ width: 24, height: 24 }}- />- </View>- );- })}- </View>- )}- </View>- );- })}- </View>-- {/* Notes & Terms */}- <View style={tw("flex flex-col gap-3 w-full")}>- {Object.keys(shipment.externalNotes ?? {}).length > 0 && (- <Note- title="Notes"- content={(shipment.externalNotes ?? {}) as JSONContent}- />- )}- <Note title="Standard Terms & Conditions" content={terms} />- </View>+ {visibleBlocks.map((block) => {+ const render = packingSlipBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</Template>);};-function getLineQuantity(- line: Database["public"]["Views"]["shipmentLines"]["Row"]-) {- return `${line.shippedQuantity} / ${line.orderQuantity} ${line.unitOfMeasure}`;-}--function getLineDescription(- line: Database["public"]["Views"]["shipmentLines"]["Row"]-) {- return line.itemReadableId;-}--function getLineDescriptionDetails(- line: Database["public"]["Views"]["shipmentLines"]["Row"]-) {- return line.description;-}--async function generateBarcode(text: string): Promise<string> {- const buffer = await bwipjs.toBuffer({- bcid: "code128", // Barcode type- text: text, // Text to encode- scale: 3, // 3x scaling factor- height: 5, // Bar height, in millimeters- includetext: true, // Show human-readable text- textxalign: "center" // Always good to set this- });- return `data:image/png;base64,${buffer.toString("base64")}`;-}export default PackingSlipPDF;diff --git a/packages/documents/src/pdf/ProductLabelPDF.tsx b/packages/documents/src/pdf/ProductLabelPDF.tsxindex 873ee641d5..f8cf3e8a18 100644--- a/packages/documents/src/pdf/ProductLabelPDF.tsx+++ b/packages/documents/src/pdf/ProductLabelPDF.tsx@@ -1,99 +1,235 @@import type { LabelSize, ProductLabelItem } from "@carbon/utils";-import { Document, Image, Page, Text, View } from "@react-pdf/renderer";-import { generateQRCode } from "../qr/qr-code";-import { getLabelPdfGeometry } from "./components/labelGeometry";+import { Document, Page, View } from "@react-pdf/renderer";+import { Fragment } from "react";+import { createTw } from "react-pdf-tailwind";+import type { DocumentTemplate, ResolvedSection } from "../template";+import { resolveTemplate } from "../template";+import type { Company } from "../types";+import type { LabelData, LabelLogo } from "./blocks/trackingLabel";+import {+ buildLabelVars,+ trackingLabelBlockRegistry+} from "./blocks/trackingLabel";+import Footer from "./components/Footer";interface ProductLabelProps {items: ProductLabelItem[];labelSize: LabelSize;+ template?: DocumentTemplate | null;+ sections?: Record<string, ResolvedSection>;+ company?: Company | null;+ logo?: LabelLogo | null;}-/**- * Renders one page per label, each page exactly the label size, with the- * same layout as the ZPL generator: item id top-left, detail lines below,- * QR code top-right, tracked entity id bottom-left.- */-const ProductLabelPDF = ({ items, labelSize }: ProductLabelProps) => {- const g = getLabelPdfGeometry(labelSize);- const qrX = g.pageWidth - g.qrSize - g.margin;+// Initialize tailwind-styled-components+const tw = createTw({+ theme: {+ fontFamily: {+ sans: ["Helvetica", "Arial", "sans-serif"]+ },+ extend: {+ colors: {+ gray: {+ 500: "#7d7d7d"+ }+ }+ }+ }+});++const ProductLabelPDF = ({+ items,+ labelSize,+ template,+ sections = {},+ company,+ logo+}: ProductLabelProps) => {+ // Default to 1 row and 1 column if not specified+ const rows = labelSize.rows || 1;+ const columns = labelSize.columns || 1;+ const rotated = labelSize.rotated || false;++ const resolved = resolveTemplate("trackingLabel", template ?? null);+ const visibleBlocks = resolved.blocks.filter((block) => block.visible);++ // Standard letter size paper (8.5 x 11 inches in points)+ const LETTER_WIDTH = 8.5 * 72;+ const LETTER_HEIGHT = 11 * 72;++ // Calculate dimensions in points (72 points per inch)+ const labelWidthPt = labelSize.width * 72;+ const labelHeightPt = labelSize.height * 72;++ // Account for rotation when calculating effective dimensions+ const effectiveLabelWidthPt = rotated ? labelHeightPt : labelWidthPt;+ const effectiveLabelHeightPt = rotated ? labelWidthPt : labelHeightPt;++ // Always print on a standard letter sheet, so a single label looks the same+ // as a multi-up sheet (top-left on a full page) rather than a tiny+ // label-sized page.+ const pageWidth = LETTER_WIDTH;+ const pageHeight = LETTER_HEIGHT;++ // Calculate font sizes based on label height+ // Base sizes are optimized for labelSize.height = 1+ // Scale up proportionally as height increases, with a cap at height = 4+ const scaleFactor = Math.min(labelSize.height, 4);+ const titleFontSize = 10 * Math.sqrt(scaleFactor);+ const descriptionFontSize = 7 * Math.sqrt(scaleFactor);++ // QR code size based on effective label dimensions accounting for rotation+ const qrCodeSize = Math.min(+ effectiveLabelHeightPt * 0.7,+ effectiveLabelWidthPt * 0.33+ );++ // Calculate how many pages we need+ const labelsPerPage = rows * columns;+ const pageCount = Math.ceil(items.length / labelsPerPage);++ // Reserve space for the footer (page number) at the bottom+ const footerHeight = 35;++ // Multi-up sheets center their grid; a single label sits at the top-left.+ const isMultiUp = rows > 1 || columns > 1;+ const singleLabelMargin = 24;+ const availableHeight = pageHeight - footerHeight;+ const horizontalMargin = isMultiUp+ ? (pageWidth - columns * effectiveLabelWidthPt) / 2+ : singleLabelMargin;+ const verticalMargin = isMultiUp+ ? (availableHeight - rows * effectiveLabelHeightPt) / 2+ : singleLabelMargin;++ const showFooter = resolved.footerSectionId !== null;return (<Document>- {items.map((item, index) => (- <Page- key={item.trackedEntityId || index}- size={[g.pageWidth, g.pageHeight]}- >- <View- style={{- position: "absolute",- left: g.margin,- top: g.contentTop,- maxWidth: qrX - g.margin - 4,- flexDirection: "column"- }}- >- <Text- style={{- fontSize: g.titleFontSize,- fontFamily: "Helvetica-Bold",- marginBottom: g.lineGap- }}- >- {item.itemId}- </Text>-- {item.revision && (- <Text- style={{ fontSize: g.descFontSize, marginBottom: g.lineGap }}- >- Rev: {item.revision}- </Text>- )}-- {["Serial", "Batch"].includes(item.trackingType) && (- <Text- style={{ fontSize: g.descFontSize, marginBottom: g.lineGap }}- >- Qty: {item.quantity}- </Text>- )}-- {item.trackingType === "Serial" && item.number && (- <Text style={{ fontSize: g.descFontSize }}>- S/N: {item.number}- </Text>- )}- {item.trackingType === "Batch" && item.number && (- <Text style={{ fontSize: g.descFontSize }}>- Batch: {item.number}- </Text>- )}- </View>-- <Image- src={generateQRCode(item.trackedEntityId, g.qrSize / 72)}- style={{- position: "absolute",- left: qrX,- top: g.contentTop,- width: g.qrSize,- height: g.qrSize,- objectFit: "contain"- }}- />-- {item.trackedEntityId && (- <Text+ {Array.from({ length: pageCount }).map((_, pageIndex) => (+ <Page key={pageIndex} size={[pageWidth, pageHeight]} style={tw("p-0")}>+ {Array.from({ length: rows }).map((_, rowIndex) => (+ <View+ key={`row-${rowIndex}`}style={{- position: "absolute",- left: g.margin,- bottom: g.bottomOffset,- fontSize: g.smallFontSize+ flexDirection: "row",+ marginLeft: horizontalMargin,+ marginTop: rowIndex === 0 ? verticalMargin : 0}}>- {item.trackedEntityId}- </Text>+ {Array.from({ length: columns }).map((_, colIndex) => {+ const itemIndex =+ pageIndex * labelsPerPage + rowIndex * columns + colIndex;+ const item = items[itemIndex];++ if (!item)+ return (+ <View+ key={`empty-${colIndex}`}+ style={{ width: labelWidthPt, height: labelHeightPt }}+ />+ );++ const data: LabelData = {+ item,+ company,+ logo,+ theme: resolved.theme,+ vars: buildLabelVars(item, company),+ titleFontSize,+ descriptionFontSize,+ qrCodeSize,+ labelColWidth: labelWidthPt * 0.26,+ labelHeightPt: effectiveLabelHeightPt,+ sections+ };++ const renderBlock = (block: (typeof visibleBlocks)[number]) => {+ const render = trackingLabelBlockRegistry[block.type];+ if (!render) return null;+ return (+ <Fragment key={block.id}>+ {render({ block, data })}+ </Fragment>+ );+ };++ // Slots: fields stack top-left; logo + "right" codes top-right;+ // "full" codes span full width near the bottom; entity id at the+ // very bottom.+ const rightBlocks = visibleBlocks.filter(+ (b) =>+ b.type === "labelLogo" ||+ (b.type === "labelBarcode" && b.placement === "right")+ );+ const barcodeBlocks = visibleBlocks.filter(+ (b) =>+ b.type === "labelBarcode" &&+ (b.placement === "full" || b.placement === "center")+ );+ const entityBlocks = visibleBlocks.filter(+ (b) => b.type === "labelEntityId"+ );+ const textBlocks = visibleBlocks.filter(+ (b) =>+ b.type !== "labelLogo" &&+ b.type !== "labelBarcode" &&+ b.type !== "labelEntityId"+ );++ return (+ <View+ key={`label-${itemIndex}`}+ style={{+ ...tw("relative p-2 flex flex-col pl-[10pt]"),+ width: labelWidthPt,+ height: labelHeightPt,+ // Clip so a dense label's content can't bleed into the+ // neighbouring cell (which clipped the next heading).+ overflow: "hidden",+ transform: rotated ? "rotate(90deg)" : undefined+ }}+ wrap={false}+ >+ <View+ style={{+ ...tw("flex flex-row justify-between"),+ flexShrink: 0+ }}+ >+ <View+ style={{+ ...tw("flex flex-col justify-start pr-2"),+ flex: 1,+ minWidth: 0+ }}+ >+ {textBlocks.map(renderBlock)}+ </View>+ {rightBlocks.length > 0 && (+ <View+ style={{+ ...tw("flex flex-col items-end justify-start"),+ flexShrink: 0+ }}+ >+ {rightBlocks.map(renderBlock)}+ </View>+ )}+ </View>+ {barcodeBlocks.map(renderBlock)}+ {entityBlocks.map(renderBlock)}+ </View>+ );+ })}+ </View>+ ))}+ {showFooter && (+ <Footer+ showPageNumbers={resolved.settings.showPageNumbers}+ pageNumberFormat={resolved.settings.pageNumberFormat}+ showRegistrationLine={resolved.settings.showRegistrationLine}+ />)}</Page>))}diff --git a/packages/documents/src/pdf/PurchaseOrderPDF.tsx b/packages/documents/src/pdf/PurchaseOrderPDF.tsxindex 69d0f4af03..6160b0b3c3 100644--- a/packages/documents/src/pdf/PurchaseOrderPDF.tsx+++ b/packages/documents/src/pdf/PurchaseOrderPDF.tsx@@ -1,27 +1,20 @@import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";-import { formatDate, isEoriCountry } from "@carbon/utils";-import { Image, Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";import type { AccountsPayableBillingAddress, PDF } from "../types";import { composeRegistrationLine } from "../utils/footer";+import type { PurchaseOrderData } from "./blocks/purchaseOrder";import {- getLineDescription,- getLineDescriptionDetails,- getLineTotal,- getTotal-} from "../utils/purchase-order";-import { formatTaxPercent } from "../utils/shared";-import { AddressBlock, Header, Note, Template } from "./components";--const INDIRECT_TYPES = new Set([- "Service",- "G/L Account",- "Fixed Asset",- "Comment"-]);-const isIndirect = (t: string | null | undefined) =>- !!t && INDIRECT_TYPES.has(t);+ buildPurchaseOrderVars,+ purchaseOrderBlockRegistry+} from "./blocks/purchaseOrder";+import { Template } from "./components";interface PurchaseOrderPDFProps extends PDF {purchaseOrder: Database["public"]["Views"]["purchaseOrders"]["Row"];@@ -34,27 +27,12 @@ interface PurchaseOrderPDFProps extends PDF {paymentTerms?: { id: string; name: string }[];terms: JSONContent;thumbnails?: Record<string, string | null>;+ /** Stored layout. When omitted, the default Purchase Order layout is used. */+ template?: DocumentTemplate | null;+ /** Shared sections referenced by the template, keyed by id. */+ sections?: Record<string, ResolvedSection>;}-const tw = createTw({- theme: {- fontFamily: {- sans: ["Inter", "Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 50: "#f9fafb",- 200: "#e5e7eb",- 400: "#9ca3af",- 600: "#4b5563",- 800: "#1f2937"- }- }- }- }-});-const PurchaseOrderPDF = ({accountsPayableBillingAddress,company,@@ -67,36 +45,10 @@ const PurchaseOrderPDF = ({terms,thumbnails,locale,+ template,+ sections = {},title = "Purchase Order"}: PurchaseOrderPDFProps) => {- const {- supplierName,- supplierAddressLine1,- supplierAddressLine2,- supplierCity,- supplierStateProvince,- supplierPostalCode,- supplierCountryCode,- supplierCountryName,- deliveryName,- deliveryAddressLine1,- deliveryAddressLine2,- deliveryCity,- deliveryStateProvince,- deliveryPostalCode,- deliveryCountryCode,- deliveryCountryName,- dropShipment,- customerName,- customerAddressLine1,- customerAddressLine2,- customerCity,- customerStateProvince,- customerPostalCode,- customerCountryCode,- customerCountryName- } = purchaseOrderLocations;-const currencyCode =purchaseOrder.currencyCode ?? company.baseCurrencyCode ?? "USD";const numberFormatter = new Intl.NumberFormat(locale, {@@ -104,49 +56,69 @@ const PurchaseOrderPDF = ({minimumFractionDigits: 2,maximumFractionDigits: 2});- const taxAmount = purchaseOrderLines.reduce(- (acc, line) => acc + (line.supplierTaxAmount ?? 0),- 0- );-- const shippingCost = purchaseOrder?.supplierShippingCost ?? 0;- const paymentTerm = paymentTerms?.find(- (term) => term.id === purchaseOrder?.paymentTermId- );-- const watermarkSrc = company.logoWatermark;- const shipAddress = dropShipment- ? {- name: customerName,- addressLine1: customerAddressLine1,- addressLine2: customerAddressLine2,- city: customerCity,- stateProvince: customerStateProvince,- postalCode: customerPostalCode,- country: customerCountryName ?? customerCountryCode- }- : {- name: deliveryName,- addressLine1: deliveryAddressLine1,- addressLine2: deliveryAddressLine2,- city: deliveryCity,- stateProvince: deliveryStateProvince,- postalCode: deliveryPostalCode,- country: deliveryCountryName ?? deliveryCountryCode- };+ const registrationLine = composeRegistrationLine({+ companyName: company.name,+ country: purchaseOrderLocations.companyCountryName ?? company.countryCode,+ eori: company.eori+ });const headerTitle = purchaseOrder?.purchaseOrderId? `${title}: ${purchaseOrder.purchaseOrderId}`: title;- const registrationLine = composeRegistrationLine({- companyName: company.name,- country: purchaseOrderLocations.companyCountryName ?? company.countryCode,- eori: company.eori+ const { blocks, theme, settings, headerSectionId, footerSectionId } =+ resolveTemplate("purchaseOrder", template);++ const vars = buildPurchaseOrderVars({+ purchaseOrder,+ purchaseOrderLocations,+ company,+ currencyCode});- let rowIndex = 0;+ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})+ };++ const data: PurchaseOrderData = {+ company,+ companySettings,+ locale,+ purchaseOrder,+ purchaseOrderLines,+ purchaseOrderLocations,+ accountsPayableBillingAddress,+ paymentTerms: paymentTerms ?? [],+ terms,+ thumbnails,+ theme,+ sections,+ currencyCode,+ numberFormatter,+ vars,+ headerOptions+ };++ const headerSection = headerSectionId+ ? sections[headerSectionId]?.content+ : undefined;+ const footerSection = footerSectionId+ ? sections[footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;++ const showHeader = headerSectionId !== null;+ const showFooter = footerSectionId !== null;+ const visibleBlocks = blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader)+ );return (<Template@@ -158,429 +130,19 @@ const PurchaseOrderPDF = ({}}footerDocumentId={purchaseOrder?.purchaseOrderId}footerLabel={registrationLine ?? undefined}+ showFooter={showFooter}+ showPageNumbers={settings.showPageNumbers}+ pageNumberFormat={settings.pageNumberFormat}+ showRegistrationLine={settings.showRegistrationLine}+ fontFamily={settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}>- {watermarkSrc && (- <View- fixed- style={{- position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0,- alignItems: "center",- marginTop: 100,- opacity: 0.07- }}- >- <Image src={watermarkSrc} style={{ width: "50%" }} />- </View>- )}- <Header- company={company}- title={title}- documentId={purchaseOrder?.purchaseOrderId}- locale={locale}- fixed- />-- {/* Body row — Supplier (left) | Right-column stack */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- {/* LEFT — Supplier block (full content with address) */}- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Supplier- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock- name={supplierName}- addressLine1={supplierAddressLine1}- addressLine2={supplierAddressLine2}- city={supplierCity}- stateProvince={supplierStateProvince}- postalCode={supplierPostalCode}- country={supplierCountryName ?? supplierCountryCode}- />- {purchaseOrderLocations.supplierTaxId &&- !isEoriCountry(supplierCountryCode) && (- <Text>Tax ID: {purchaseOrderLocations.supplierTaxId}</Text>- )}- {purchaseOrderLocations.supplierVatNumber && (- <Text>VAT: {purchaseOrderLocations.supplierVatNumber}</Text>- )}- {purchaseOrderLocations.supplierEori && (- <Text>EORI: {purchaseOrderLocations.supplierEori}</Text>- )}- {purchaseOrderLocations.supplierContactName && (- <Text>- Contact: {purchaseOrderLocations.supplierContactName}- </Text>- )}- {purchaseOrderLocations.supplierContactEmail && (- <Text>- Email: {purchaseOrderLocations.supplierContactEmail}- </Text>- )}- </View>- </View>-- {/* RIGHT — three stacked sub-blocks */}- <View style={tw("w-1/2 flex flex-col")}>- {/* Order Info — merges Order Details + Buyer Contact */}- <View style={tw("p-3 border-b border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Order Info- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {purchaseOrder?.purchaseOrderId && (- <Text>PO Number: {purchaseOrder.purchaseOrderId}</Text>- )}- {purchaseOrder?.orderDate && (- <Text>- Date:{" "}- {formatDate(purchaseOrder.orderDate, undefined, locale)}- </Text>- )}- <Text>Currency: {currencyCode}</Text>- {purchaseOrder?.supplierReference && (- <Text>Reference: {purchaseOrder.supplierReference}</Text>- )}- {purchaseOrder?.receiptRequestedDate && (- <Text>- Requested:{" "}- {formatDate(- purchaseOrder.receiptRequestedDate,- undefined,- locale- )}- </Text>- )}- {purchaseOrder?.receiptPromisedDate && (- <Text>- Promised:{" "}- {formatDate(- purchaseOrder.receiptPromisedDate,- undefined,- locale- )}- </Text>- )}- {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}- {purchaseOrder?.incoterm && (- <Text>- Incoterm: {purchaseOrder.incoterm}- {purchaseOrder.incotermLocation- ? ` — ${purchaseOrder.incotermLocation}`- : ""}- </Text>- )}- </View>- {/* Thin divider between Order Details and Buyer Contact halves */}- <View style={tw("h-[1px] bg-gray-200 my-2")} />- <View style={tw("text-[9px] text-gray-800")}>- {company.vatNumber && <Text>VAT: {company.vatNumber}</Text>}- {(() => {- const name =- purchaseOrder.assigneeFullName ??- purchaseOrder.accountManagerFullName ??- purchaseOrder.createdByFullName;- const email =- purchaseOrder.assigneeEmail ??- purchaseOrder.accountManagerEmail ??- purchaseOrder.createdByEmail;- const phone =- purchaseOrder.assigneePhone ??- purchaseOrder.accountManagerPhone ??- purchaseOrder.createdByPhone;- return (- <>- {name && <Text>Contact: {name}</Text>}- {email && <Text>Email: {email}</Text>}- {phone && <Text>Phone: {phone}</Text>}- </>- );- })()}- {accountsPayableBillingAddress?.email && (- <>- <Text style={tw("font-bold mt-1")}>- Billing documents and enquiries:- </Text>- <Text style={tw("font-bold")}>- {accountsPayableBillingAddress.email}- </Text>- </>- )}- </View>- </View>-- {/* Deliver To */}- <View style={tw("p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Deliver To- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock {...shipAddress} />- </View>- </View>- </View>- </View>- </View>-- {/* Notes (full width, always rendered for layout predictability) */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>- Notes- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {Object.keys(purchaseOrder?.externalNotes ?? {}).length > 0 ? (- <Note- content={(purchaseOrder.externalNotes ?? {}) as JSONContent}- />- ) : (- <Text style={tw("text-gray-400")}>None</Text>- )}- </View>- </View>- </View>-- {/* Line Items Table */}- <View style={tw("mb-4")}>- {/* Header — fixed so it repeats on every page the table spans */}- <View- fixed- style={tw(- "flex flex-row bg-gray-800 py-3 px-3 text-white text-[9px] font-bold items-center"- )}- >- <Text style={tw("w-[4%] text-center")}>#</Text>- <Text style={tw("w-[22%]")}>Description</Text>- <Text style={tw("w-[8%] text-center")}>Qty</Text>- <Text style={tw("w-[7%] text-center")}>UOM</Text>- <View style={tw("w-[10%] items-center")}>- <Text>Required</Text>- </View>- <Text style={tw("w-[12%] text-center")}>Unit Price</Text>- <Text style={tw("w-[12%] text-center")}>Net Value</Text>- <Text style={tw("w-[12%] text-center")}>Tax Value</Text>- <Text style={tw("w-[13%] text-center")}>Total</Text>- </View>-- {/* Rows */}- {purchaseOrderLines.map((line) => {- const isEven = rowIndex % 2 === 0;- rowIndex++;-- const netValue =- (line.purchaseQuantity ?? 0) * (line.supplierUnitPrice ?? 0);-- return (- <View key={line.id}>- <View- wrap={false}- style={[- tw(- "flex flex-col py-2 px-3 border-b border-gray-200 text-[9px]"- ),- {- backgroundColor: isEven- ? "transparent"- : "rgba(249, 250, 251, 0.6)"- }- ]}- >- <View style={tw("flex flex-row")}>- <Text style={tw("w-[4%] text-center text-gray-400")}>- {line.purchaseOrderLineType === "Comment" ? "" : rowIndex}- </Text>- <View style={tw("w-[22%] pr-2")}>- {isIndirect(line.purchaseOrderLineType) ? (- <Text style={tw("text-gray-900")}>- {line.description ?? ""}- </Text>- ) : (- <>- <Text style={tw("text-gray-900")}>- {getLineDescription(line)}- </Text>- <Text style={tw("text-[7px] text-gray-600 mt-0.5")}>- {getLineDescriptionDetails(line)}- </Text>- </>- )}- {purchaseOrder.purchaseOrderType === "Outside Processing" &&- line.jobOperationDescription && (- <Text style={tw("text-[7px] text-gray-600 mt-0.5")}>- {line.jobOperationDescription}- </Text>- )}- {thumbnails &&- line.id &&- line.id in thumbnails &&- thumbnails[line.id] && (- <View style={tw("mt-1 w-16")}>- <Image- src={thumbnails[line.id]!}- style={tw("w-full h-auto")}- />- </View>- )}- </View>- <Text style={tw("w-[8%] text-center text-gray-600")}>- {line.purchaseOrderLineType === "Comment"- ? ""- : line.purchaseQuantity}- </Text>- <Text style={tw("w-[7%] text-center text-gray-600")}>- {line.purchaseOrderLineType === "Comment"- ? ""- : line.purchaseUnitOfMeasureCode}- </Text>- <Text style={tw("w-[10%] text-center text-gray-600")}>- {line.purchaseOrderLineType === "Comment" ||- !line.requiredDate- ? ""- : formatDate(line.requiredDate, undefined, locale)}- </Text>- <Text style={tw("w-[12%] text-center text-gray-600")}>- {line.purchaseOrderLineType === "Comment"- ? ""- : numberFormatter.format(line.supplierUnitPrice ?? 0)}- </Text>- <Text style={tw("w-[12%] text-center text-gray-600")}>- {line.purchaseOrderLineType === "Comment"- ? ""- : numberFormatter.format(netValue)}- </Text>- <View style={tw("w-[12%]")}>- {line.purchaseOrderLineType !== "Comment" && (- <View style={tw("flex flex-col items-center")}>- <Text style={tw("text-gray-600")}>- {numberFormatter.format(line.supplierTaxAmount ?? 0)}- </Text>- {formatTaxPercent(line.taxPercent) && (- <Text style={tw("text-[6px] text-gray-400")}>- {formatTaxPercent(line.taxPercent)}- </Text>- )}- </View>- )}- </View>- <Text- style={tw("w-[13%] text-center text-gray-800 font-medium")}- >- {line.purchaseOrderLineType === "Comment"- ? ""- : numberFormatter.format(getLineTotal(line))}- </Text>- </View>- </View>- {Object.keys(line.externalNotes ?? {}).length > 0 && (- <View style={tw("px-3 py-2 border-b border-gray-200")}>- <Note- key={`${line.id}-notes`}- content={line.externalNotes as JSONContent}- />- </View>- )}- </View>- );- })}-- {/* Summary */}- <View>- {/* Subtotal */}- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-[87%] text-right pr-3 text-gray-600")}>- Subtotal ({currencyCode})- </Text>- <Text style={tw("w-[13%] text-center text-gray-800")}>- {numberFormatter.format(- purchaseOrderLines.reduce((sum, line) => {- if (line?.purchaseQuantity && line?.supplierUnitPrice) {- return sum + line.purchaseQuantity * line.supplierUnitPrice;- }- return sum;- }, 0)- )}- </Text>- </View>-- {/* Shipping */}- {shippingCost > 0 && (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-[87%] text-right pr-3 text-gray-600")}>- Shipping ({currencyCode})- </Text>- <Text style={tw("w-[13%] text-center text-gray-800")}>- {numberFormatter.format(shippingCost)}- </Text>- </View>- )}-- {/* Tax — amount only, no percentage subtext */}- {taxAmount > 0 && (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-[87%] text-right pr-3 text-gray-600")}>- Tax ({currencyCode})- </Text>- <Text style={tw("w-[13%] text-center text-gray-800")}>- {numberFormatter.format(taxAmount)}- </Text>- </View>- )}-- <View style={tw("h-[1px] bg-gray-200")} />- <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>- <Text style={tw("w-[87%] text-right pr-3 text-gray-800 font-bold")}>- Total ({currencyCode})- </Text>- <Text style={tw("w-[13%] text-center text-gray-800 font-bold")}>- {numberFormatter.format(- getTotal(purchaseOrderLines) + shippingCost- )}- </Text>- </View>- </View>- </View>-- {/* Terms */}- {terms?.content && terms.content.length > 0 && (- <View break>- <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>- <Text- style={tw(- "text-[14px] font-bold text-gray-800 uppercase tracking-wide"- )}- >- Terms & Conditions- </Text>- </View>- <Note content={terms} />- </View>- )}+ {visibleBlocks.map((block) => {+ const render = purchaseOrderBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</Template>);};diff --git a/packages/documents/src/pdf/QuotePDF.tsx b/packages/documents/src/pdf/QuotePDF.tsxindex 10b619642f..d4ccc4f4a6 100644--- a/packages/documents/src/pdf/QuotePDF.tsx+++ b/packages/documents/src/pdf/QuotePDF.tsx@@ -1,26 +1,26 @@import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";-import { formatDate, isEoriCountry, pluralize } from "@carbon/utils";-import { getLocalTimeZone, today } from "@internationalized/date";-import { Image, Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";import type { AccountsReceivableBillingAddress, PDF } from "../types";import { composeRegistrationLine } from "../utils/footer";-import { getLineDescription, getLineDescriptionDetails } from "../utils/quote";-import { AddressBlock, Header, Note, Template } from "./components";+import type { QuoteCustomerDetails, QuoteData } from "./blocks/quote";+import { buildQuoteVars, quoteBlockRegistry } from "./blocks/quote";+import { Template } from "./components";-type QuoteCustomerDetails =- Database["public"]["Views"]["quoteCustomerDetails"]["Row"] & {- customerTaxId?: string | null;- customerVatNumber?: string | null;- };+type QuoteLinePrice = Database["public"]["Tables"]["quoteLinePrice"]["Row"];interface QuotePDFProps extends PDF {exchangeRate: number;quote: Database["public"]["Views"]["quotes"]["Row"];quoteLines: Database["public"]["Views"]["quoteLines"]["Row"][];quoteCustomerDetails: QuoteCustomerDetails;- quoteLinePrices: Database["public"]["Tables"]["quoteLinePrice"]["Row"][];+ quoteLinePrices: QuoteLinePrice[];payment?: Database["public"]["Tables"]["quotePayment"]["Row"] | null;shipment?: Database["public"]["Tables"]["quoteShipment"]["Row"] | null;accountsReceivableBillingAddress?: AccountsReceivableBillingAddress | null;@@ -31,29 +31,11 @@ interface QuotePDFProps extends PDF {shippingMethods: { id: string; name: string }[];terms: JSONContent;thumbnails: Record<string, string | null>;+ template?: DocumentTemplate | null;+ sections?: Record<string, ResolvedSection>;}-const tw = createTw({- theme: {- fontFamily: {- sans: ["Inter", "Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 50: "#f9fafb",- 200: "#e5e7eb",- 400: "#9ca3af",- 600: "#4b5563",- 800: "#1f2937"- }- }- }- }-});-const QuotePDF = ({- accountsReceivableBillingAddress,company,companySettings,meta,@@ -68,24 +50,10 @@ const QuotePDF = ({terms,thumbnails,locale,+ template,+ sections = {},title = "Quote"}: QuotePDFProps) => {- const {- customerName,- customerAddressLine1,- customerAddressLine2,- customerCity,- customerStateProvince,- customerPostalCode,- customerCountryCode,- customerCountryName,- customerTaxId,- customerVatNumber,- customerEori,- contactName,- contactEmail- } = quoteCustomerDetails;-const currencyCode = quote.currencyCode ?? company.baseCurrencyCode;const shouldConvertCurrency =!!currencyCode && currencyCode !== company.baseCurrencyCode;@@ -101,136 +69,154 @@ const QuotePDF = ({eori: company.eori});- const pricesByLine = quoteLinePrices.reduce<- Record<string, Database["public"]["Tables"]["quoteLinePrice"]["Row"][]>- >((acc, price) => {- if (!acc[price.quoteLineId]) {- acc[price.quoteLineId] = [];- }- acc[price.quoteLineId]!.push(price);- return acc;- }, {});-- const paymentTerm = paymentTerms?.find(- (pt) => pt.id === payment?.paymentTermId+ const pricesByLine = quoteLinePrices.reduce<Record<string, QuoteLinePrice[]>>(+ (acc, price) => {+ (acc[price.quoteLineId] ??= []).push(price);+ return acc;+ },+ {});+ const priceForFirstQty = (line: (typeof quoteLines)[number]) => {+ const lineQuantity = line.quantity ?? [];+ const prices = line.id != null ? (pricesByLine[line.id] ?? []) : [];+ return prices.find((p) => p.quantity === lineQuantity[0]);+ };+const hasSinglePricePerLine = quoteLines.every((line) => (line.quantity ?? []).length === 1);-- // Check if any line has a lead time > 0const hasAnyLeadTime = quoteLines.some((line) => {if (line.status === "No Quote") return false;- const lineQuantity = line.quantity ?? [];- const prices = line.id != null ? (pricesByLine[line.id] ?? []) : [];- const price = prices.find(- (p: Database["public"]["Tables"]["quoteLinePrice"]["Row"]) =>- p.quantity === lineQuantity[0]- );- return price && price.leadTime > 0;+ return (priceForFirstQty(line)?.leadTime ?? 0) > 0;});- // Calculate column count for dynamic widths- // Base columns: Qty, Unit Price, Total = 3- // Optional: Tax & Fees (when multi-qty), Lead Time (when any has lead time)const columnCount =3 + (!hasSinglePricePerLine ? 1 : 0) + (hasAnyLeadTime ? 1 : 0);const colWidth =columnCount === 3 ? "w-1/3" : columnCount === 4 ? "w-1/4" : "w-1/5";- const getMaxLeadTime = () => {- let maxLeadTime = 0;- for (const prices of Object.values(pricesByLine)) {- for (const price of prices) {- if (price && price.leadTime > maxLeadTime) {- maxLeadTime = price.leadTime;- }- }+ let maxLeadTime = 0;+ for (const prices of Object.values(pricesByLine)) {+ for (const price of prices) {+ if (price && price.leadTime > maxLeadTime) maxLeadTime = price.leadTime;}- return maxLeadTime;- };+ }- const getTotalSubtotal = () => {- return quoteLines.reduce((total, line) => {- if (line.status === "No Quote") return total;- const lineQuantity = line.quantity ?? [];- const prices = line.id != null ? (pricesByLine[line.id] ?? []) : [];- const price = prices.find(- (p: Database["public"]["Tables"]["quoteLinePrice"]["Row"]) =>- p.quantity === lineQuantity[0]- );- return total + (price?.convertedNetExtendedPrice ?? 0);- }, 0);- };+ const subtotal = quoteLines.reduce((total, line) => {+ if (line.status === "No Quote") return total;+ return total + (priceForFirstQty(line)?.convertedNetExtendedPrice ?? 0);+ }, 0);- const getTotalShipping = () => {- const lineShipping = quoteLines.reduce((total, line) => {+ const shipping =+ quoteLines.reduce((total, line) => {if (line.status === "No Quote") return total;- const lineQuantity = line.quantity ?? [];- const prices = line.id != null ? (pricesByLine[line.id] ?? []) : [];- const price = prices.find(- (p: Database["public"]["Tables"]["quoteLinePrice"]["Row"]) =>- p.quantity === lineQuantity[0]- );- return total + (price?.convertedShippingCost ?? 0);+ return total + (priceForFirstQty(line)?.convertedShippingCost ?? 0);+ }, 0) ++ (shipment?.shippingCost ?? 0) * (exchangeRate ?? 1);++ const fees = quoteLines.reduce((total, line) => {+ if (line.status === "No Quote") return total;+ const additionalCharges = line.additionalCharges ?? {};+ const quantity = (line.quantity ?? [])[0];+ const charges = Object.values(additionalCharges).reduce((acc, charge) => {+ let amount = quantity != null ? (charge.amounts?.[quantity] ?? 0) : 0;+ if (shouldConvertCurrency) amount *= exchangeRate;+ return acc + amount;}, 0);- const quoteShipping = (shipment?.shippingCost ?? 0) * (exchangeRate ?? 1);- return lineShipping + quoteShipping;- };-- const getTotalFees = () => {- return quoteLines.reduce((total, line) => {- if (line.status === "No Quote") return total;- const additionalCharges = line.additionalCharges ?? {};- const quantity = (line.quantity ?? [])[0];- const charges = Object.values(additionalCharges).reduce((acc, charge) => {+ return total + charges;+ }, 0);++ const taxes = quoteLines.reduce((total, line) => {+ if (line.status === "No Quote") return total;+ const price = priceForFirstQty(line);+ const netExtendedPrice = price?.convertedNetExtendedPrice ?? 0;+ const additionalCharges = line.additionalCharges ?? {};+ const quantity = (line.quantity ?? [])[0];+ const taxableFees = Object.values(additionalCharges).reduce(+ (acc, charge) => {+ if (charge.taxable === false) return acc;let amount = quantity != null ? (charge.amounts?.[quantity] ?? 0) : 0;- if (shouldConvertCurrency) {- amount *= exchangeRate;- }+ if (shouldConvertCurrency) amount *= exchangeRate;return acc + amount;- }, 0);- return total + charges;- }, 0);+ },+ 0+ );+ const lineShipping = price?.convertedShippingCost ?? 0;+ const taxableAmount = netExtendedPrice + taxableFees + lineShipping;+ return total + taxableAmount * (line.taxPercent ?? 0);+ }, 0);++ const totals = {+ subtotal,+ shipping,+ fees,+ taxes,+ total: subtotal + shipping + fees + taxes};- const getTotalTaxes = () => {- return quoteLines.reduce((total, line) => {- if (line.status === "No Quote") return total;- const lineQuantity = line.quantity ?? [];- const prices = line.id != null ? (pricesByLine[line.id] ?? []) : [];- const price = prices.find(- (p: Database["public"]["Tables"]["quoteLinePrice"]["Row"]) =>- p.quantity === lineQuantity[0]- );- const netExtendedPrice = price?.convertedNetExtendedPrice ?? 0;- const additionalCharges = line.additionalCharges ?? {};- const quantity = lineQuantity[0];- const taxableFees = Object.values(additionalCharges).reduce(- (acc, charge) => {- if (charge.taxable === false) return acc;- let amount = quantity != null ? (charge.amounts?.[quantity] ?? 0) : 0;- if (shouldConvertCurrency) {- amount *= exchangeRate;- }- return acc + amount;- },- 0- );- const lineShipping = price?.convertedShippingCost ?? 0;- const taxableAmount = netExtendedPrice + taxableFees + lineShipping;- return total + taxableAmount * (line.taxPercent ?? 0);- }, 0);- };+ const { blocks, theme, settings, headerSectionId, footerSectionId } =+ resolveTemplate("quote", template);- const getTotal = () =>- getTotalSubtotal() + getTotalShipping() + getTotalFees() + getTotalTaxes();+ const vars = buildQuoteVars({+ quote,+ quoteCustomerDetails,+ company,+ currencyCode+ });++ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})+ };- const maxLeadTime = getMaxLeadTime();- const watermarkSrc = company.logoWatermark;+ const data: QuoteData = {+ company,+ companySettings,+ locale,+ quote,+ quoteLines,+ quoteLinePrices,+ quoteCustomerDetails,+ payment,+ shipment,+ paymentTerms,+ terms,+ thumbnails,+ exchangeRate,+ shouldConvertCurrency,+ pricesByLine,+ hasSinglePricePerLine,+ hasAnyLeadTime,+ colWidth,+ maxLeadTime,+ totals,+ theme,+ sections,+ currencyCode,+ numberFormatter,+ vars,+ headerOptions+ };- let rowIndex = 0;+ const headerSection = headerSectionId+ ? sections[headerSectionId]?.content+ : undefined;+ const footerSection = footerSectionId+ ? sections[footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;++ const showHeader = headerSectionId !== null;+ const showFooter = footerSectionId !== null;+ const visibleBlocks = blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader)+ );return (<Template@@ -242,478 +228,19 @@ const QuotePDF = ({}}footerDocumentId={quote?.quoteId}footerLabel={registrationLine ?? undefined}+ showFooter={showFooter}+ showPageNumbers={settings.showPageNumbers}+ pageNumberFormat={settings.pageNumberFormat}+ showRegistrationLine={settings.showRegistrationLine}+ fontFamily={settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}>- {watermarkSrc && (- <View- fixed- style={{- position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0,- alignItems: "center",- marginTop: 100,- opacity: 0.07- }}- >- <Image src={watermarkSrc} style={{ width: "50%" }} />- </View>- )}- <Header- company={company}- title="Quote"- documentId={quote?.quoteId}- currencyCode={quote?.currencyCode}- locale={locale}- />-- {/* Body row — TO (customer left) | QUOTE DETAILS (right) */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- {/* LEFT — Customer block (addressee) */}- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- To- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock- name={customerName}- addressLine1={customerAddressLine1}- addressLine2={customerAddressLine2}- city={customerCity}- stateProvince={customerStateProvince}- postalCode={customerPostalCode}- country={customerCountryName ?? customerCountryCode}- />- {customerTaxId && !isEoriCountry(customerCountryCode) && (- <Text>Tax ID: {customerTaxId}</Text>- )}- {customerVatNumber && <Text>VAT: {customerVatNumber}</Text>}- {customerEori && <Text>EORI: {customerEori}</Text>}- {contactName && <Text>Contact: {contactName}</Text>}- {contactEmail && <Text>Email: {contactEmail}</Text>}- </View>- </View>-- {/* RIGHT — Quote Details */}- <View style={tw("w-1/2 p-3")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Quote Details- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <Text>- Date:{" "}- {formatDate(- today(getLocalTimeZone()).toString(),- undefined,- locale- )}- </Text>- {quote.expirationDate && (- <Text style={tw("font-bold")}>- Expires: {formatDate(quote.expirationDate, undefined, locale)}- </Text>- )}- {quote.customerReference && (- <Text>Reference: {quote.customerReference}</Text>- )}- {maxLeadTime > 0 && (- <Text>- Max Lead Time: {maxLeadTime} {pluralize(maxLeadTime, "day")}- </Text>- )}- {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}- {shipment?.incoterm && (- <Text>- Incoterm: {shipment.incoterm}- {shipment.incotermLocation- ? ` — ${shipment.incotermLocation}`- : ""}- </Text>- )}- </View>- </View>- </View>- </View>-- {/* Notes (full width) */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>- Notes- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {Object.keys(quote?.externalNotes ?? {}).length > 0 ? (- <Note content={(quote.externalNotes ?? {}) as JSONContent} />- ) : (- <Text style={tw("text-gray-400")}>None</Text>- )}- </View>- </View>- </View>-- {/* Line Items Table */}- <View style={tw("mb-4")}>- {/* Header — fixed so it repeats on every page the table spans */}- <View- fixed- style={tw(- "flex flex-row bg-gray-800 py-2 px-3 text-white text-[9px] font-bold items-center"- )}- >- <View style={tw("w-1/3")}>- <Text>Description</Text>- </View>- <View style={tw("w-2/3 flex flex-row items-center")}>- <Text style={tw(`${colWidth} text-center pr-3`)}>Qty</Text>- <Text style={tw(`${colWidth} text-center pr-3`)}>Unit Price</Text>- {!hasSinglePricePerLine && (- <Text style={tw(`${colWidth} text-center pr-3`)}>Tax & Fees</Text>- )}- {hasAnyLeadTime && (- <Text style={tw(`${colWidth} text-center pr-3`)}>Lead Time</Text>- )}- <Text style={tw(`${colWidth} text-center`)}>Total</Text>- </View>- </View>-- {/* Rows */}- {quoteLines.map((line) => {- const unitPriceNumberFormatter = new Intl.NumberFormat(locale, {- style: "decimal",- minimumFractionDigits: line.unitPricePrecision ?? 2,- maximumFractionDigits: line.unitPricePrecision ?? 2- });-- const additionalCharges = line.additionalCharges ?? {};-- return (- <View key={line.id}>- {line.status !== "No Quote" ? (- <>- {(line.quantity ?? []).map((quantity, index) => {- const prices =- line.id != null ? (pricesByLine[line.id] ?? []) : [];- const price = prices.find(- (- p: Database["public"]["Tables"]["quoteLinePrice"]["Row"]- ) => p.quantity === quantity- );- const unitPrice = price?.convertedUnitPrice ?? 0;- const netExtendedPrice =- price?.convertedNetExtendedPrice ?? 0;- const isEven = rowIndex % 2 === 0;- rowIndex++;-- const leadTime = price?.leadTime ?? 0;-- // Calculate tax & fees for this quantity- const additionalCharge = Object.values(- additionalCharges- ).reduce((acc, charge) => {- let amount = charge.amounts?.[quantity] ?? 0;- if (shouldConvertCurrency) {- amount *= exchangeRate;- }- return acc + amount;- }, 0);- const taxableAdditionalCharge = Object.values(- additionalCharges- ).reduce((acc, charge) => {- if (charge.taxable === false) return acc;- let amount = charge.amounts?.[quantity] ?? 0;- if (shouldConvertCurrency) {- amount *= exchangeRate;- }- return acc + amount;- }, 0);- const shippingCost = price?.convertedShippingCost ?? 0;- const taxPercent = line.taxPercent ?? 0;- const taxableBeforeTax =- netExtendedPrice + taxableAdditionalCharge + shippingCost;- const taxAmount = taxableBeforeTax * taxPercent;- const totalTaxAndFees =- additionalCharge + shippingCost + taxAmount;- const totalPrice = netExtendedPrice + totalTaxAndFees;-- return (- <View- key={`${line.id}-${quantity}`}- wrap={false}- style={[- tw(- "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"- ),- {- backgroundColor: isEven- ? "transparent"- : "rgba(249, 250, 251, 0.6)"- }- ]}- >- <View style={tw("w-1/3 pr-2")}>- {index === 0 && (- <>- <Text style={tw("text-gray-800")}>- {getLineDescription(line)}- </Text>- <Text- style={tw("text-[8px] text-gray-400 mt-0.5")}- >- {getLineDescriptionDetails(line)}- </Text>- {thumbnails &&- line.id != null &&- line.id in thumbnails && (- <View style={tw("mt-2")}>- <Image- src={thumbnails[line.id]!}- style={{ width: 60, height: 60 }}- />- </View>- )}- {totalTaxAndFees > 0 && (- <View style={tw("mt-1")}>- <Text- style={tw(- "text-[8px] text-gray-400 font-bold"- )}- >- Tax & Fees- </Text>- {(price?.convertedShippingCost ?? 0) > 0 && (- <Text- style={tw("text-[8px] text-gray-400")}- >- - Shipping- </Text>- )}- {Object.values(additionalCharges)- .filter(- (charge) =>- charge.description &&- (charge.amounts?.[quantity] ?? 0) > 0- )- .sort((a, b) =>- a.description.localeCompare(b.description)- )- .map((charge) => (- <Text- key={charge.description}- style={tw("text-[8px] text-gray-400")}- >- - {charge.description}- </Text>- ))}- {taxPercent > 0 && (- <Text- style={tw("text-[8px] text-gray-400")}- >- - Tax ({(taxPercent * 100).toFixed(0)}%)- </Text>- )}- </View>- )}- </>- )}- </View>- <View style={tw("w-2/3 flex flex-row")}>- <Text- style={tw(- `${colWidth} text-center text-gray-600 pr-3`- )}- >- {quantity} EA- </Text>- <Text- style={tw(- `${colWidth} text-center text-gray-600 pr-3`- )}- >- {unitPrice- ? unitPriceNumberFormatter.format(unitPrice)- : "-"}- </Text>- {!hasSinglePricePerLine && (- <Text- style={tw(- `${colWidth} text-center text-gray-600 pr-3`- )}- >- {totalTaxAndFees > 0- ? numberFormatter.format(totalTaxAndFees)- : "-"}- </Text>- )}- {hasAnyLeadTime && (- <Text- style={tw(- `${colWidth} text-center text-gray-600 pr-3`- )}- >- {leadTime > 0- ? `${leadTime} ${pluralize(leadTime, "day")}`- : "-"}- </Text>- )}- <Text- style={tw(- `${colWidth} text-center text-gray-800 font-medium`- )}- >- {hasSinglePricePerLine- ? netExtendedPrice > 0- ? numberFormatter.format(netExtendedPrice)- : "-"- : totalPrice > 0- ? numberFormatter.format(totalPrice)- : "-"}- </Text>- </View>- </View>- );- })}- {Object.keys(line.externalNotes ?? {}).length > 0 && (- <View style={tw("px-3 py-2 border-b border-gray-200")}>- <Note- key={`${line.id}-notes`}- content={line.externalNotes as JSONContent}- />- </View>- )}- </>- ) : (- <View- wrap={false}- style={[- tw(- "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"- ),- {- backgroundColor:- rowIndex++ % 2 === 0- ? "transparent"- : "rgba(249, 250, 251, 0.6)"- }- ]}- >- <View style={tw("w-1/3 pr-2")}>- <Text style={tw("text-gray-800")}>- {getLineDescription(line)}- </Text>- <Text style={tw("text-[8px] text-gray-400 mt-0.5")}>- {getLineDescriptionDetails(line)}- </Text>- </View>- <View style={tw("w-2/3 flex flex-row")}>- <Text- style={tw(- `${colWidth} text-right text-gray-600 font-bold`- )}- >- No Quote- </Text>- <View style={tw("flex-1 text-right")}>- <Text style={tw("text-gray-400 text-[8px] text-right")}>- {line.noQuoteReason ?? ""}- </Text>- </View>- </View>- </View>- )}- </View>- );- })}-- {/* Summary - only show when single price per line */}- {hasSinglePricePerLine && (- <View>- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw(`w-5/6 text-right pr-3 text-gray-600`)}>- Subtotal ({currencyCode})- </Text>- <Text style={tw(`w-1/6 text-center text-gray-800`)}>- {numberFormatter.format(getTotalSubtotal())}- </Text>- </View>- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw(`w-5/6 text-right pr-3 text-gray-600`)}>- Shipping ({currencyCode})- </Text>- <Text style={tw(`w-1/6 text-center text-gray-800`)}>- {numberFormatter.format(getTotalShipping())}- </Text>- </View>- {getTotalFees() > 0 && (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw(`w-5/6 text-right pr-3 text-gray-600`)}>- Fees ({currencyCode})- </Text>- <Text style={tw(`w-1/6 text-center text-gray-800`)}>- {numberFormatter.format(getTotalFees())}- </Text>- </View>- )}- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw(`w-5/6 text-right pr-3 text-gray-600`)}>- Taxes ({currencyCode})- </Text>- <Text style={tw(`w-1/6 text-center text-gray-800`)}>- {numberFormatter.format(getTotalTaxes())}- </Text>- </View>- <View style={tw("h-[1px] bg-gray-200")} />- <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>- <Text style={tw(`w-5/6 text-right pr-3 text-gray-800 font-bold`)}>- Total ({currencyCode})- </Text>- <Text style={tw(`w-1/6 text-center text-gray-800 font-bold`)}>- {numberFormatter.format(getTotal())}- </Text>- </View>- </View>- )}- </View>-- {terms?.content && terms.content.length > 0 && (- <View break>- <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>- <Text- style={tw(- "text-[14px] font-bold text-gray-800 uppercase tracking-wide"- )}- >- Terms & Conditions- </Text>- </View>- <Note content={terms} />- </View>- )}+ {visibleBlocks.map((block) => {+ const render = quoteBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</Template>);};diff --git a/packages/documents/src/pdf/SalesInvoicePDF.tsx b/packages/documents/src/pdf/SalesInvoicePDF.tsxindex 71bf0f1bb4..ae39f32ea7 100644--- a/packages/documents/src/pdf/SalesInvoicePDF.tsx+++ b/packages/documents/src/pdf/SalesInvoicePDF.tsx@@ -1,24 +1,17 @@import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";-import { formatDate, isEoriCountry } from "@carbon/utils";-import { Image, Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";import type { AccountsReceivableBillingAddress, PDF } from "../types";import { composeRegistrationLine } from "../utils/footer";-import {- getLineDescription,- getLineDescriptionDetails,- getLineTaxableSubtotal,- getLineTotal,- getTotal-} from "../utils/sales-invoice";-import { AddressBlock, Header, Note, Template } from "./components";--type SalesInvoiceLocations =- Database["public"]["Views"]["salesInvoiceLocations"]["Row"] & {- customerTaxId?: string | null;- customerVatNumber?: string | null;- };+import type { SalesInvoiceData, SalesInvoiceLocations } from "./blocks";+import { buildSalesInvoiceVars, salesInvoiceBlockRegistry } from "./blocks";+import { Template } from "./components";interface SalesInvoicePDFProps extends PDF {salesInvoice: Database["public"]["Views"]["salesInvoices"]["Row"];@@ -34,27 +27,12 @@ interface SalesInvoicePDFProps extends PDF {shippingMethods: { id: string; name: string }[];terms: JSONContent;thumbnails?: Record<string, string | null>;+ /** Stored layout. When omitted, the default Sales Invoice layout is used. */+ template?: DocumentTemplate | null;+ /** Shared sections referenced by the template, keyed by id. */+ sections?: Record<string, ResolvedSection>;}-const tw = createTw({- theme: {- fontFamily: {- sans: ["Inter", "Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 50: "#f9fafb",- 200: "#e5e7eb",- 400: "#9ca3af",- 600: "#4b5563",- 800: "#1f2937"- }- }- }- }-});-const SalesInvoicePDF = ({accountsReceivableBillingAddress,company,@@ -70,35 +48,10 @@ const SalesInvoicePDF = ({shippingMethods,thumbnails,locale,+ template,+ sections = {},title = "Invoice"}: SalesInvoicePDFProps) => {- const {- customerName,- customerAddressLine1,- customerAddressLine2,- customerCity,- customerStateProvince,- customerPostalCode,- customerCountryName,- customerTaxId,- customerVatNumber,- customerEori,- invoiceCustomerName,- invoiceAddressLine1,- invoiceAddressLine2,- invoiceCity,- invoiceStateProvince,- invoicePostalCode,- invoiceCountryName,- shipmentCustomerName,- shipmentAddressLine1,- shipmentAddressLine2,- shipmentCity,- shipmentStateProvince,- shipmentPostalCode,- shipmentCountryName- } = salesInvoiceLocations;-const currencyCode = salesInvoice.currencyCode ?? company.baseCurrencyCode;const numberFormatter = new Intl.NumberFormat(locale, {style: "decimal",@@ -112,17 +65,67 @@ const SalesInvoicePDF = ({eori: company.eori});- const paymentTerm = paymentTerms?.find(- (term) => term.id === salesInvoice?.paymentTermId- );+ const { blocks, theme, settings, headerSectionId, footerSectionId } =+ resolveTemplate("salesInvoice", template);- const shippingMethod = shippingMethods?.find(- (method) => method.id === salesInvoiceShipment?.shippingMethodId- );+ const vars = buildSalesInvoiceVars({+ salesInvoice,+ salesInvoiceLocations,+ company,+ currencyCode+ });- const watermarkSrc = company.logoWatermark;+ // Header layout now lives on the global header section's config (not the+ // block), so every document shares one header configuration.+ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})+ };- let rowIndex = 0;+ const data: SalesInvoiceData = {+ company,+ companySettings,+ locale,+ salesInvoice,+ salesInvoiceLines,+ salesInvoiceLocations,+ salesInvoiceShipment,+ salesOrderIds,+ accountsReceivableBillingAddress,+ paymentTerms,+ shippingMethods,+ terms,+ thumbnails,+ theme,+ sections,+ currencyCode,+ numberFormatter,+ vars,+ headerOptions+ };++ const headerSection = headerSectionId+ ? sections[headerSectionId]?.content+ : undefined;+ const footerSection = footerSectionId+ ? sections[footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;++ // The header/footer selectors are the single control for the top header and+ // the footer band. "None" (null id) removes them entirely; the built-in+ // default id keeps them. This drives both the company Header block and the+ // structural footer (registration line + page numbers).+ const showHeader = headerSectionId !== null;+ const showFooter = footerSectionId !== null;+ const visibleBlocks = blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader)+ );return (<Template@@ -134,412 +137,19 @@ const SalesInvoicePDF = ({}}footerDocumentId={salesInvoice?.invoiceId}footerLabel={registrationLine ?? undefined}+ showFooter={showFooter}+ showPageNumbers={settings.showPageNumbers}+ pageNumberFormat={settings.pageNumberFormat}+ showRegistrationLine={settings.showRegistrationLine}+ fontFamily={settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}>- {watermarkSrc && (- <View- fixed- style={{- position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0,- alignItems: "center",- marginTop: 100,- opacity: 0.07- }}- >- <Image src={watermarkSrc} style={{ width: "50%" }} />- </View>- )}- <Header- company={company}- title="Invoice"- documentId={salesInvoice?.invoiceId}- currencyCode={salesInvoice?.currencyCode}- locale={locale}- />-- {/* Body row — Bill To (left) | Invoice Details + Ship To stacked (right) */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- {/* LEFT — Bill To (the customer being invoiced) */}- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Bill To- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock- name={invoiceCustomerName ?? customerName}- addressLine1={invoiceAddressLine1 ?? customerAddressLine1}- addressLine2={invoiceAddressLine2 ?? customerAddressLine2}- city={invoiceCity ?? customerCity}- stateProvince={invoiceStateProvince ?? customerStateProvince}- postalCode={invoicePostalCode ?? customerPostalCode}- country={invoiceCountryName ?? customerCountryName}- />- {customerTaxId &&- !isEoriCountry(invoiceCountryName ?? customerCountryName) && (- <Text>Tax ID: {customerTaxId}</Text>- )}- {customerVatNumber && <Text>VAT: {customerVatNumber}</Text>}- {customerEori && <Text>EORI: {customerEori}</Text>}- </View>- </View>-- {/* RIGHT — Invoice Details + Ship To stacked */}- <View style={tw("w-1/2 flex flex-col")}>- {/* Invoice Details — Due Date prominent */}- <View- style={tw(- shipmentCustomerName ? "p-3 border-b border-gray-200" : "p-3"- )}- >- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Invoice Details- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {salesInvoice?.dateIssued && (- <Text>- Date Issued:{" "}- {formatDate(salesInvoice.dateIssued, undefined, locale)}- </Text>- )}- {salesInvoice?.dateDue && (- <Text style={tw("font-bold")}>- Due Date:{" "}- {formatDate(salesInvoice.dateDue, undefined, locale)}- </Text>- )}- {salesInvoice?.customerReference && (- <Text>Customer Ref: {salesInvoice.customerReference}</Text>- )}- {salesOrderIds && salesOrderIds.length > 0 && (- <Text>- {salesOrderIds.length > 1- ? "Sales Orders: "- : "Sales Order: "}- {salesOrderIds.join(", ")}- </Text>- )}- {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}- {shippingMethod && <Text>Shipping: {shippingMethod.name}</Text>}- {salesInvoiceShipment?.shippingTermId && (- <Text>- Shipping Terms: {salesInvoiceShipment.shippingTermId}- </Text>- )}- {salesInvoiceShipment?.incoterm && (- <Text>- Incoterm: {salesInvoiceShipment.incoterm}- {salesInvoiceShipment.incotermLocation- ? ` — ${salesInvoiceShipment.incotermLocation}`- : ""}- </Text>- )}- </View>- </View>-- {/* Ship To — only when shipment has a distinct address (not falling back to customer's main address) */}- {shipmentCustomerName && (- <View style={tw("p-3")}>- <Text- style={tw(- "text-[9px] font-bold text-gray-600 mb-1 uppercase"- )}- >- Ship To- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock- name={shipmentCustomerName}- addressLine1={shipmentAddressLine1}- addressLine2={shipmentAddressLine2}- city={shipmentCity}- stateProvince={shipmentStateProvince}- postalCode={shipmentPostalCode}- country={shipmentCountryName}- />- </View>- </View>- )}- </View>- </View>- </View>-- {/* Notes (full width) */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>- Notes- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {Object.keys(salesInvoice?.externalNotes ?? {}).length > 0 ? (- <Note- content={(salesInvoice.externalNotes ?? {}) as JSONContent}- />- ) : (- <Text style={tw("text-gray-400")}>None</Text>- )}- </View>- </View>- </View>-- {/* Line Items Table */}- <View style={tw("mb-4")}>- {/* Header */}- <View- fixed- style={tw(- "flex flex-row bg-gray-800 py-2 px-3 text-white text-[9px] font-bold items-center"- )}- >- <Text style={tw("w-1/2")}>Description</Text>- <Text style={tw("w-1/6 text-center")}>Qty</Text>- <Text style={tw("w-1/6 text-center")}>Unit Price</Text>- <Text style={tw("w-1/6 text-center")}>Total</Text>- </View>-- {/* Rows */}- {salesInvoiceLines.map((line) => {- const isEven = rowIndex % 2 === 0;- rowIndex++;-- const lineAddOnCost = line.convertedAddOnCost ?? 0;- const lineNonTaxableAddOnCost =- line.convertedNonTaxableAddOnCost ?? 0;- const lineShippingCost = line.convertedShippingCost ?? 0;- const lineTaxPercent = line.taxPercent ?? 0;- const lineTaxAmount = getLineTaxableSubtotal(line) * lineTaxPercent;- const totalTaxAndFees =- lineAddOnCost +- lineNonTaxableAddOnCost +- lineShippingCost +- lineTaxAmount;-- return (- <View key={line.id}>- <View- wrap={false}- style={[- tw(- "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"- ),- {- backgroundColor: isEven- ? "transparent"- : "rgba(249, 250, 251, 0.6)"- }- ]}- >- <View style={tw("w-1/2 pr-2")}>- <Text style={tw("text-gray-800")}>- {getLineDescription(line)}- </Text>- <Text style={tw("text-[8px] text-gray-400 mt-0.5")}>- {getLineDescriptionDetails(line)}- </Text>- {thumbnails &&- line.id &&- line.id in thumbnails &&- thumbnails[line.id] && (- <View style={tw("mt-1 w-16")}>- <Image- src={thumbnails[line.id]!}- style={tw("w-full h-auto")}- />- </View>- )}- {line.invoiceLineType !== "Comment" &&- totalTaxAndFees > 0 && (- <View style={tw("mt-1")}>- <Text style={tw("text-[8px] text-gray-400 font-bold")}>- Tax & Fees- </Text>- {lineShippingCost > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Shipping- </Text>- )}- {lineAddOnCost > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Add-On- </Text>- )}- {lineNonTaxableAddOnCost > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Non-Taxable Add-On- </Text>- )}- {lineTaxPercent > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Tax ({(lineTaxPercent * 100).toFixed(0)}%)- </Text>- )}- </View>- )}- </View>- <Text style={tw("w-1/6 text-center text-gray-600")}>- {line.invoiceLineType === "Comment"- ? ""- : `${line.quantity} ${line.unitOfMeasureCode ?? "EA"}`}- </Text>- <Text style={tw("w-1/6 text-center text-gray-600")}>- {line.invoiceLineType === "Comment"- ? ""- : numberFormatter.format(line.convertedUnitPrice ?? 0)}- </Text>- <Text style={tw("w-1/6 text-center text-gray-800 font-medium")}>- {line.invoiceLineType === "Comment"- ? ""- : numberFormatter.format(getLineTotal(line))}- </Text>- </View>- {Object.keys(line.externalNotes ?? {}).length > 0 && (- <View style={tw("px-3 py-2 border-b border-gray-200")}>- <Note- key={`${line.id}-notes`}- content={line.externalNotes as JSONContent}- />- </View>- )}- </View>- );- })}-- {/* Summary */}- <View>- {/* Subtotal - extended price only */}- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Subtotal ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(- salesInvoiceLines.reduce(- (sum, line) =>- sum + (line.quantity ?? 0) * (line.convertedUnitPrice ?? 0),- 0- )- )}- </Text>- </View>-- {/* Add-Ons */}- {salesInvoiceLines.some(- (line) =>- (line.convertedAddOnCost ?? 0) > 0 ||- (line.convertedNonTaxableAddOnCost ?? 0) > 0- ) && (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Add-Ons ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(- salesInvoiceLines.reduce(- (sum, line) =>- sum +- (line.convertedAddOnCost ?? 0) +- (line.convertedNonTaxableAddOnCost ?? 0),- 0- )- )}- </Text>- </View>- )}-- {/* Shipping */}- {(() => {- const lineShipping = salesInvoiceLines.reduce(- (sum, line) => sum + (line.convertedShippingCost ?? 0),- 0- );- const invoiceShipping =- (salesInvoiceShipment?.shippingCost ?? 0) *- (salesInvoice.exchangeRate ?? 1);- const totalShipping = lineShipping + invoiceShipping;- return totalShipping > 0 ? (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Shipping ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(totalShipping)}- </Text>- </View>- ) : null;- })()}-- {/* Taxes */}- {salesInvoiceLines.some((line) => (line.taxPercent ?? 0) > 0) && (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Taxes ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(- salesInvoiceLines.reduce((sum, line) => {- const taxPercent = line.taxPercent ?? 0;- return sum + getLineTaxableSubtotal(line) * taxPercent;- }, 0)- )}- </Text>- </View>- )}-- <View style={tw("h-[1px] bg-gray-200")} />- <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>- <Text style={tw("w-5/6 text-right pr-3 text-gray-800 font-bold")}>- Total ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800 font-bold")}>- {numberFormatter.format(- getTotal(salesInvoiceLines, salesInvoice, salesInvoiceShipment)- )}- </Text>- </View>- </View>- </View>-- {terms?.content && terms.content.length > 0 && (- <View break>- <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>- <Text- style={tw(- "text-[14px] font-bold text-gray-800 uppercase tracking-wide"- )}- >- Terms & Conditions- </Text>- </View>- <Note content={terms} />- </View>- )}+ {visibleBlocks.map((block) => {+ const render = salesInvoiceBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</Template>);};diff --git a/packages/documents/src/pdf/SalesOrderPDF.tsx b/packages/documents/src/pdf/SalesOrderPDF.tsxindex f6f74f82a5..2afac60022 100644--- a/packages/documents/src/pdf/SalesOrderPDF.tsx+++ b/packages/documents/src/pdf/SalesOrderPDF.tsx@@ -1,24 +1,20 @@import type { Database } from "@carbon/database";import type { JSONContent } from "@carbon/react";-import { formatDate, isEoriCountry } from "@carbon/utils";-import { Image, Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";import type { AccountsReceivableBillingAddress, PDF } from "../types";import { composeRegistrationLine } from "../utils/footer";+import type { SalesOrderData, SalesOrderLocations } from "./blocks/salesOrder";import {- getLineDescription,- getLineDescriptionDetails,- getLineTaxableSubtotal,- getLineTotal,- getTotal-} from "../utils/sales-order";-import { AddressBlock, Header, Note, Template } from "./components";--type SalesOrderLocations =- Database["public"]["Views"]["salesOrderLocations"]["Row"] & {- customerTaxId?: string | null;- customerVatNumber?: string | null;- };+ buildSalesOrderVars,+ salesOrderBlockRegistry+} from "./blocks/salesOrder";+import { Template } from "./components";interface SalesOrderPDFProps extends PDF {salesOrder: Database["public"]["Views"]["salesOrders"]["Row"];@@ -32,27 +28,12 @@ interface SalesOrderPDFProps extends PDF {shippingMethods: { id: string; name: string }[];terms: JSONContent;thumbnails?: Record<string, string | null>;+ /** Stored layout. When omitted, the default Sales Order layout is used. */+ template?: DocumentTemplate | null;+ /** Shared sections referenced by the template, keyed by id. */+ sections?: Record<string, ResolvedSection>;}-const tw = createTw({- theme: {- fontFamily: {- sans: ["Inter", "Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 50: "#f9fafb",- 200: "#e5e7eb",- 400: "#9ca3af",- 600: "#4b5563",- 800: "#1f2937"- }- }- }- }-});-const SalesOrderPDF = ({accountsReceivableBillingAddress,company,@@ -66,28 +47,10 @@ const SalesOrderPDF = ({shippingMethods,thumbnails,locale,+ template,+ sections = {},title = "Sales Order"}: SalesOrderPDFProps) => {- const {- customerName,- customerAddressLine1,- customerAddressLine2,- customerCity,- customerStateProvince,- customerPostalCode,- customerCountryName,- customerTaxId,- customerVatNumber,- customerEori,- paymentCustomerName,- paymentAddressLine1,- paymentAddressLine2,- paymentCity,- paymentStateProvince,- paymentPostalCode,- paymentCountryName- } = salesOrderLocations;-const currencyCode = salesOrder.currencyCode ?? company.baseCurrencyCode;const numberFormatter = new Intl.NumberFormat(locale, {style: "decimal",@@ -101,17 +64,59 @@ const SalesOrderPDF = ({eori: company.eori});- const paymentTerm = paymentTerms?.find(- (term) => term.id === salesOrder?.paymentTermId- );+ const { blocks, theme, settings, headerSectionId, footerSectionId } =+ resolveTemplate("salesOrder", template);- const shippingMethod = shippingMethods?.find(- (method) => method.id === salesOrder?.shippingMethodId- );+ const vars = buildSalesOrderVars({+ salesOrder,+ salesOrderLocations,+ company,+ currencyCode+ });++ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})+ };- const watermarkSrc = company.logoWatermark;+ const data: SalesOrderData = {+ company,+ companySettings,+ locale,+ salesOrder,+ salesOrderLines,+ salesOrderLocations,+ accountsReceivableBillingAddress,+ paymentTerms,+ shippingMethods,+ terms,+ thumbnails,+ theme,+ sections,+ currencyCode,+ numberFormatter,+ vars,+ headerOptions+ };- let rowIndex = 0;+ const headerSection = headerSectionId+ ? sections[headerSectionId]?.content+ : undefined;+ const footerSection = footerSectionId+ ? sections[footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;++ const showHeader = headerSectionId !== null;+ const showFooter = footerSectionId !== null;+ const visibleBlocks = blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader)+ );return (<Template@@ -123,411 +128,19 @@ const SalesOrderPDF = ({}}footerDocumentId={salesOrder?.salesOrderId}footerLabel={registrationLine ?? undefined}+ showFooter={showFooter}+ showPageNumbers={settings.showPageNumbers}+ pageNumberFormat={settings.pageNumberFormat}+ showRegistrationLine={settings.showRegistrationLine}+ fontFamily={settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}>- {watermarkSrc && (- <View- fixed- style={{- position: "absolute",- top: 0,- left: 0,- right: 0,- bottom: 0,- alignItems: "center",- marginTop: 100,- opacity: 0.07- }}- >- <Image src={watermarkSrc} style={{ width: "50%" }} />- </View>- )}- <Header- company={company}- title="Sales Order"- documentId={salesOrder?.salesOrderId}- currencyCode={salesOrder?.currencyCode}- locale={locale}- />-- {/* Body row — Customer (left) | Order Details + Ship To + Bill To stacked (right) */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("flex flex-row")}>- {/* LEFT — Customer block */}- <View style={tw("w-1/2 p-3 border-r border-gray-200")}>- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Customer- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock- name={customerName}- addressLine1={customerAddressLine1}- addressLine2={customerAddressLine2}- city={customerCity}- stateProvince={customerStateProvince}- postalCode={customerPostalCode}- country={customerCountryName}- />- {customerTaxId && !isEoriCountry(customerCountryName) && (- <Text>Tax ID: {customerTaxId}</Text>- )}- {customerVatNumber && <Text>VAT: {customerVatNumber}</Text>}- {customerEori && <Text>EORI: {customerEori}</Text>}- </View>- </View>-- {/* RIGHT — Order Details + Ship To + Bill To stacked */}- <View style={tw("w-1/2 flex flex-col")}>- {/* Order Details */}- <View- style={tw(- paymentCustomerName ? "p-3 border-b border-gray-200" : "p-3"- )}- >- <Text- style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}- >- Order Details- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {salesOrder?.orderDate && (- <Text>- Date: {formatDate(salesOrder.orderDate, undefined, locale)}- </Text>- )}- {salesOrder?.customerReference && (- <Text>Customer Ref: {salesOrder.customerReference}</Text>- )}- {salesOrder?.receiptRequestedDate && (- <Text>- Requested:{" "}- {formatDate(- salesOrder.receiptRequestedDate,- undefined,- locale- )}- </Text>- )}- {salesOrder?.receiptPromisedDate && (- <Text>- Promised:{" "}- {formatDate(- salesOrder.receiptPromisedDate,- undefined,- locale- )}- </Text>- )}- {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}- {shippingMethod && <Text>Shipping: {shippingMethod.name}</Text>}- {salesOrder?.shippingTermName && (- <Text>Shipping Terms: {salesOrder.shippingTermName}</Text>- )}- {salesOrder?.incoterm && (- <Text>- Incoterm: {salesOrder.incoterm}- {salesOrder.incotermLocation- ? ` — ${salesOrder.incotermLocation}`- : ""}- </Text>- )}- </View>- </View>-- {/* Bill To (only if a separate billing customer is set) */}- {paymentCustomerName && (- <View style={tw("p-3")}>- <Text- style={tw(- "text-[9px] font-bold text-gray-600 mb-1 uppercase"- )}- >- Bill To- </Text>- <View style={tw("text-[9px] text-gray-800")}>- <AddressBlock- name={paymentCustomerName}- addressLine1={paymentAddressLine1}- addressLine2={paymentAddressLine2}- city={paymentCity}- stateProvince={paymentStateProvince}- postalCode={paymentPostalCode}- country={paymentCountryName}- />- </View>- </View>- )}- </View>- </View>- </View>-- {/* Notes (full width) */}- <View style={tw("border border-gray-200 mb-4")}>- <View style={tw("p-3")}>- <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>- Notes- </Text>- <View style={tw("text-[9px] text-gray-800")}>- {Object.keys(salesOrder?.externalNotes ?? {}).length > 0 ? (- <Note content={(salesOrder.externalNotes ?? {}) as JSONContent} />- ) : (- <Text style={tw("text-gray-400")}>None</Text>- )}- </View>- </View>- </View>-- {/* Line Items Table */}- <View style={tw("mb-4")}>- {/* Header */}- <View- fixed- style={tw(- "flex flex-row bg-gray-800 py-2 px-3 text-white text-[9px] font-bold items-center"- )}- >- <Text style={tw("w-1/2")}>Description</Text>- <Text style={tw("w-1/6 text-center")}>Qty</Text>- <Text style={tw("w-1/6 text-center")}>Unit Price</Text>- <Text style={tw("w-1/6 text-center")}>Total</Text>- </View>-- {/* Rows */}- {salesOrderLines.map((line) => {- const isEven = rowIndex % 2 === 0;- rowIndex++;-- const lineAddOnCost = line.convertedAddOnCost ?? 0;- const lineNonTaxableAddOnCost =- line.convertedNonTaxableAddOnCost ?? 0;- const lineShippingCost = line.convertedShippingCost ?? 0;- const lineTaxPercent = line.taxPercent ?? 0;- const lineTaxAmount = getLineTaxableSubtotal(line) * lineTaxPercent;- const totalTaxAndFees =- lineAddOnCost +- lineNonTaxableAddOnCost +- lineShippingCost +- lineTaxAmount;-- return (- <View key={line.id}>- <View- wrap={false}- style={[- tw(- "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"- ),- {- backgroundColor: isEven- ? "transparent"- : "rgba(249, 250, 251, 0.6)"- }- ]}- >- <View style={tw("w-1/2 pr-2")}>- <Text style={tw("text-gray-800")}>- {getLineDescription(line)}- </Text>- <Text style={tw("text-[8px] text-gray-400 mt-0.5")}>- {getLineDescriptionDetails(line)}- </Text>- {thumbnails &&- line.id &&- line.id in thumbnails &&- thumbnails[line.id] && (- <View style={tw("mt-1 w-16")}>- <Image- src={thumbnails[line.id]!}- style={tw("w-full h-auto")}- />- </View>- )}- {line.salesOrderLineType !== "Comment" &&- totalTaxAndFees > 0 && (- <View style={tw("mt-1")}>- <Text style={tw("text-[8px] text-gray-400 font-bold")}>- Tax & Fees- </Text>- {lineShippingCost > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Shipping- </Text>- )}- {lineAddOnCost > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Add-On- </Text>- )}- {lineNonTaxableAddOnCost > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Non-Taxable Add-On- </Text>- )}- {lineTaxPercent > 0 && (- <Text style={tw("text-[8px] text-gray-400")}>- - Tax ({(lineTaxPercent * 100).toFixed(0)}%)- </Text>- )}- </View>- )}- </View>- <Text style={tw("w-1/6 text-center text-gray-600")}>- {line.salesOrderLineType === "Comment"- ? ""- : `${line.saleQuantity} ${line.unitOfMeasureCode ?? "EA"}`}- </Text>- <Text style={tw("w-1/6 text-center text-gray-600")}>- {line.salesOrderLineType === "Comment"- ? ""- : numberFormatter.format(line.convertedUnitPrice ?? 0)}- </Text>- <Text style={tw("w-1/6 text-center text-gray-800 font-medium")}>- {line.salesOrderLineType === "Comment"- ? ""- : numberFormatter.format(getLineTotal(line))}- </Text>- </View>- {Object.keys(line.externalNotes ?? {}).length > 0 && (- <View style={tw("px-3 py-2 border-b border-gray-200")}>- <Note- key={`${line.id}-notes`}- content={line.externalNotes as JSONContent}- />- </View>- )}- </View>- );- })}-- {/* Summary */}- <View>- {/* Subtotal - extended price only */}- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Subtotal ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(- salesOrderLines.reduce(- (sum, line) =>- sum +- (line.saleQuantity ?? 0) * (line.convertedUnitPrice ?? 0),- 0- )- )}- </Text>- </View>-- {/* Add-Ons */}- {salesOrderLines.some(- (line) =>- (line.convertedAddOnCost ?? 0) > 0 ||- (line.convertedNonTaxableAddOnCost ?? 0) > 0- ) && (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Add-Ons ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(- salesOrderLines.reduce(- (sum, line) =>- sum +- (line.convertedAddOnCost ?? 0) +- (line.convertedNonTaxableAddOnCost ?? 0),- 0- )- )}- </Text>- </View>- )}-- {/* Shipping */}- {(() => {- const lineShipping = salesOrderLines.reduce(- (sum, line) => sum + (line.convertedShippingCost ?? 0),- 0- );- const orderShipping =- (salesOrder.shippingCost ?? 0) * (salesOrder.exchangeRate ?? 1);- const totalShipping = lineShipping + orderShipping;- return totalShipping > 0 ? (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Shipping ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(totalShipping)}- </Text>- </View>- ) : null;- })()}-- {/* Taxes */}- {salesOrderLines.some((line) => (line.taxPercent ?? 0) > 0) && (- <View- style={[- tw("flex flex-row py-1.5 px-3 text-[9px]"),- { backgroundColor: "rgba(249, 250, 251, 0.6)" }- ]}- >- <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>- Taxes ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800")}>- {numberFormatter.format(- salesOrderLines.reduce((sum, line) => {- const taxPercent = line.taxPercent ?? 0;- return sum + getLineTaxableSubtotal(line) * taxPercent;- }, 0)- )}- </Text>- </View>- )}-- <View style={tw("h-[1px] bg-gray-200")} />- <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>- <Text style={tw("w-5/6 text-right pr-3 text-gray-800 font-bold")}>- Total ({currencyCode})- </Text>- <Text style={tw("w-1/6 text-center text-gray-800 font-bold")}>- {numberFormatter.format(getTotal(salesOrderLines, salesOrder))}- </Text>- </View>- </View>- </View>-- {/* Terms */}- {terms?.content && terms.content.length > 0 && (- <View break>- <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>- <Text- style={tw(- "text-[14px] font-bold text-gray-800 uppercase tracking-wide"- )}- >- Terms & Conditions- </Text>- </View>- <Note content={terms} />- </View>- )}+ {visibleBlocks.map((block) => {+ const render = salesOrderBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</Template>);};diff --git a/packages/documents/src/pdf/StockTransferPDF.tsx b/packages/documents/src/pdf/StockTransferPDF.tsxindex 025f970a02..0d26f73e22 100644--- a/packages/documents/src/pdf/StockTransferPDF.tsx+++ b/packages/documents/src/pdf/StockTransferPDF.tsx@@ -1,73 +1,80 @@-import bwipjs from "@bwip-js/node";import type { Database } from "@carbon/database";-import { getAppUrl } from "@carbon/env";-import { formatDate } from "@carbon/utils";-import { Image, Text, View } from "@react-pdf/renderer";-import { createTw } from "react-pdf-tailwind";-import { generateQRCode } from "../qr/qr-code";+import { Fragment } from "react";+import type { DocumentTemplate, ResolvedSection } from "../template";+import {+ DEFAULT_HEADER_OPTIONS,+ interpolateContent,+ resolveTemplate+} from "../template";import type { PDF } from "../types";-import { Header, Summary, Template } from "./components";+import type { StockTransferData } from "./blocks/stockTransfer";+import {+ buildStockTransferVars,+ stockTransferBlockRegistry+} from "./blocks/stockTransfer";+import { Template } from "./components";interface StockTransferPDFProps extends PDF {stockTransfer: Database["public"]["Tables"]["stockTransfer"]["Row"];stockTransferLines: Database["public"]["Views"]["stockTransferLines"]["Row"][];location: Database["public"]["Tables"]["location"]["Row"];thumbnails?: Record<string, string | null>;+ template?: DocumentTemplate | null;+ sections?: Record<string, ResolvedSection>;}-// Initialize tailwind-styled-components-const tw = createTw({- theme: {- fontFamily: {- sans: ["Inter", "Helvetica", "Arial", "sans-serif"]- },- extend: {- colors: {- gray: {- 50: "#f9fafb",- 200: "#e5e7eb",- 400: "#9ca3af",- 500: "#7d7d7d",- 600: "#4b5563",- 800: "#1f2937"- }- }- }- }-});-const StockTransferPDF = ({company,stockTransfer,stockTransferLines,location,locale,- title = "Stock Transfer",- thumbnails+ thumbnails,+ template,+ sections = {},+ title = "Stock Transfer"}: StockTransferPDFProps) => {- const details = [- {- label: "Date",- value: stockTransfer?.createdAt- ? formatDate(stockTransfer.createdAt, undefined, locale)- : ""- },- {- label: "Stock Transfer",- value: stockTransfer?.stockTransferId- },- {- label: "Location",- value: location?.name- }- ];-- if (stockTransfer?.assignee) {- details.push({- label: "Assignee",- value: stockTransfer.assignee- });- }+ const { blocks, theme, settings, headerSectionId, footerSectionId } =+ resolveTemplate("stockTransfer", template);++ const vars = buildStockTransferVars({ stockTransfer, location, company });++ const headerOptions = {+ ...DEFAULT_HEADER_OPTIONS,+ ...(headerSectionId ? (sections[headerSectionId]?.config ?? {}) : {})+ };++ const data: StockTransferData = {+ company,+ locale,+ stockTransfer,+ stockTransferLines,+ location,+ thumbnails,+ theme,+ sections,+ vars,+ headerOptions+ };++ const headerSection = headerSectionId+ ? sections[headerSectionId]?.content+ : undefined;+ const footerSection = footerSectionId+ ? sections[footerSectionId]?.content+ : undefined;+ const headerContent = headerSection+ ? interpolateContent(headerSection, vars)+ : undefined;+ const footerContent = footerSection+ ? interpolateContent(footerSection, vars)+ : undefined;++ const showHeader = headerSectionId !== null;+ const showFooter = footerSectionId !== null;+ const visibleBlocks = blocks.filter(+ (block) => block.visible && !(block.type === "header" && !showHeader)+ );return (<Template@@ -77,131 +84,22 @@ const StockTransferPDF = ({keywords: "stock transfer",subject: "Stock Transfer"}}+ footerDocumentId={stockTransfer?.stockTransferId}+ showFooter={showFooter}+ showPageNumbers={settings.showPageNumbers}+ pageNumberFormat={settings.pageNumberFormat}+ showRegistrationLine={settings.showRegistrationLine}+ fontFamily={settings.fontFamily}+ headerContent={headerContent}+ footerContent={footerContent}>- <View style={tw("flex flex-col")}>- {/* Header Section - Always at the top */}- <View style={tw("mb-4")}>- <Header- company={company}- title={title}- documentId={stockTransfer?.stockTransferId}- date={stockTransfer?.createdAt}- locale={locale}- />- <Summary company={company} items={details} />- </View>-- {/* Line Items Section */}- <View style={tw("mb-6 text-xs")}>- <View- style={tw(- "flex flex-row bg-gray-800 py-2 px-3 text-white text-[9px] font-bold"- )}- >- <Text style={tw("w-2/5 text-left")}>Description</Text>- <Text style={tw("w-1/4 text-center")}>Transfer</Text>- <Text style={tw("w-1/6 text-center")}>Qty</Text>- <Text style={tw("w-1/8 text-center")}>Pick</Text>- </View>-- {stockTransferLines- .sort((a, b) => {- const storageUnitA = a.fromStorageUnitName || "Any";- const storageUnitB = b.fromStorageUnitName || "Any";- return storageUnitA.localeCompare(storageUnitB);- })- .map((line) => {- const barcodeDataUrl = generateBarcode(line.itemReadableId ?? "");- let pickUrl = `${getAppUrl()}/api/stock-transfer/${line.id}/pick`;- if (line.requiresSerialTracking) {- pickUrl += "?type=serial";- } else if (line.requiresBatchTracking) {- pickUrl += "?type=batch";- }- const pickQRCode = generateQRCode(pickUrl, 4);-- return (- <View- style={tw(- "flex flex-row justify-between py-2 px-3 border-b border-gray-200 text-[10px]"- )}- key={line.id}- wrap={false}- >- <View style={tw("w-2/5")}>- <Text style={tw("font-bold mb-1")}>- {getLineDescription(line)}- </Text>- <Text style={tw("text-[9px] opacity-80 mb-2")}>- {getLineDescriptionDetails(line)}- </Text>-- {thumbnails &&- line.id != null &&- line.id in thumbnails &&- thumbnails[line.id] && (- <View style={tw("mt-2 mb-2")}>- <Image- src={thumbnails[line.id]!}- style={tw("w-1/4 h-auto max-w-[25%]")}- />- </View>- )}-- <Image src={barcodeDataUrl} style={tw("max-w-[50%]")} />- </View>-- <View style={tw("w-1/4 text-center")}>- <Text style={tw("text-xs")}>- {line.fromStorageUnitName || "Any"} →{" "}- {line.toStorageUnitName || "Any"}- </Text>- </View>-- <Text style={tw("w-1/6 text-center")}>- {getLineQuantity(line)}- </Text>-- <View style={tw("w-1/8 flex flex-col items-center")}>- <Image src={pickQRCode} style={tw("h-16 w-16")} />- </View>- </View>- );- })}- </View>- </View>+ {visibleBlocks.map((block) => {+ const render = stockTransferBlockRegistry[block.type];+ if (!render) return null;+ return <Fragment key={block.id}>{render({ block, data })}</Fragment>;+ })}</Template>);};-function getLineQuantity(- line: Database["public"]["Views"]["stockTransferLines"]["Row"]-) {- return `${line.quantity} ${line.unitOfMeasure}`;-}--function getLineDescription(- line: Database["public"]["Views"]["stockTransferLines"]["Row"]-) {- return line.itemDescription;-}--function getLineDescriptionDetails(- line: Database["public"]["Views"]["stockTransferLines"]["Row"]-) {- return line.itemReadableId;-}--async function generateBarcode(text: string): Promise<string> {- const buffer = await bwipjs.toBuffer({- bcid: "code128", // Barcode type- text: text, // Text to encode- scale: 3, // 3x scaling factor- height: 5, // Bar height, in millimeters- includetext: true, // Show human-readable text- textxalign: "center" // Always good to set this- });- return `data:image/png;base64,${buffer.toString("base64")}`;-}-export default StockTransferPDF;diff --git a/packages/documents/src/pdf/blocks/CustomFieldBlock.tsx b/packages/documents/src/pdf/blocks/CustomFieldBlock.tsxnew file mode 100644index 0000000000..99e3bdb795--- /dev/null+++ b/packages/documents/src/pdf/blocks/CustomFieldBlock.tsx@@ -0,0 +1,30 @@+import { Text, View } from "@react-pdf/renderer";+import type { CustomFieldBlock as CustomFieldBlockType } from "../../template";+import { tw } from "./tw";++function formatValue(raw: unknown): string {+ if (raw === "on" || raw === true) return "Yes";+ if (raw === "off" || raw === false) return "No";+ if (raw == null) return "—";+ return String(raw);+}++/** Extension block — doc-agnostic. Takes the record's `customFields` map. */+export function CustomFieldBlock({+ block,+ customFields+}: {+ block: CustomFieldBlockType;+ customFields: Record<string, unknown>;+}) {+ const value = formatValue(customFields[block.fieldId]);++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row p-3 text-[9px]")}>+ <Text style={tw("w-1/3 text-gray-600")}>{block.label || "—"}</Text>+ <Text style={tw("w-2/3 text-gray-800")}>{value}</Text>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/FieldBlock.tsx b/packages/documents/src/pdf/blocks/FieldBlock.tsxnew file mode 100644index 0000000000..d941af4b04--- /dev/null+++ b/packages/documents/src/pdf/blocks/FieldBlock.tsx@@ -0,0 +1,34 @@+import { Text, View } from "@react-pdf/renderer";+import type { FieldBlock as FieldBlockType } from "../../template";+import { interpolateString } from "../../template";+import { tw } from "./tw";++/**+ * Extension block — doc-agnostic. A single line of plain text: an optional+ * bold `label` followed by an interpolated `value`. The simple alternative to+ * rich text when a user just needs one labelled line. Takes only the merge+ * `vars` so any document's registry can reuse it.+ */+export function FieldBlock({+ block,+ vars+}: {+ block: FieldBlockType;+ vars: Record<string, string>;+}) {+ const value = interpolateString(block.value ?? "", vars);+ if (!value && !block.label) return null;++ return (+ <View style={tw("flex flex-row mb-2 text-[10px] text-gray-800")}>+ {block.label ? (+ <>+ <Text style={tw("font-bold mr-1")}>{block.label}:</Text>+ <Text>{value}</Text>+ </>+ ) : (+ <Text>{value}</Text>+ )}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/HeaderBlock.tsxnew file mode 100644index 0000000000..16dde654a8--- /dev/null+++ b/packages/documents/src/pdf/blocks/HeaderBlock.tsx@@ -0,0 +1,15 @@+import { Header } from "../components";+import type { SalesInvoiceData } from "./types";++export function HeaderBlock({ data }: { data: SalesInvoiceData }) {+ return (+ <Header+ company={data.company}+ title="Invoice"+ documentId={data.salesInvoice?.invoiceId}+ currencyCode={data.salesInvoice?.currencyCode}+ locale={data.locale}+ options={data.headerOptions}+ />+ );+}diff --git a/packages/documents/src/pdf/blocks/KeyValueBlock.tsx b/packages/documents/src/pdf/blocks/KeyValueBlock.tsxnew file mode 100644index 0000000000..165321846d--- /dev/null+++ b/packages/documents/src/pdf/blocks/KeyValueBlock.tsx@@ -0,0 +1,43 @@+import { Text, View } from "@react-pdf/renderer";+import type { KeyValueBlock as KeyValueBlockType } from "../../template";+import { interpolateString } from "../../template";+import { tw } from "./tw";++/** Extension block — doc-agnostic. Takes only the merge-field `vars`. */+export function KeyValueBlock({+ block,+ vars+}: {+ block: KeyValueBlockType;+ vars: Record<string, string>;+}) {+ const rows = block.rows ?? [];+ if (rows.length === 0 && !block.title) return null;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ {block.title && (+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ {block.title}+ </Text>+ )}+ <View style={tw("text-[9px] text-gray-800")}>+ {rows.map((row, index) => (+ <View+ key={`${row.label}-${index}`}+ style={tw("flex flex-row mb-0.5")}+ >+ <Text style={tw("w-1/3 text-gray-600")}>+ {interpolateString(row.label, vars)}+ </Text>+ <Text style={tw("w-2/3 text-gray-800")}>+ {interpolateString(row.value, vars)}+ </Text>+ </View>+ ))}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/LineItemsBlock.tsxnew file mode 100644index 0000000000..81c2c9d010--- /dev/null+++ b/packages/documents/src/pdf/blocks/LineItemsBlock.tsx@@ -0,0 +1,159 @@+import type { JSONContent } from "@carbon/react";+import { Image, Text, View } from "@react-pdf/renderer";+import {+ DEFAULT_LINE_ITEMS_OPTIONS,+ type LineItemsBlock as LineItemsBlockType+} from "../../template";+import {+ getLineDescription,+ getLineDescriptionDetails,+ getLineTaxableSubtotal,+ getLineTotal+} from "../../utils/sales-invoice";+import { Note } from "../components";+import { itemTextOverflowStyle } from "./itemText";+import { tw } from "./tw";+import type { SalesInvoiceData } from "./types";++export function LineItemsBlock({+ block,+ data+}: {+ block: LineItemsBlockType;+ data: SalesInvoiceData;+}) {+ const { salesInvoiceLines, thumbnails, numberFormatter, theme } = data;+ const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };+ const overflow = itemTextOverflowStyle(opts);+ let rowIndex = 0;++ return (+ <View>+ {/* Header */}+ <View+ fixed+ style={[+ tw("flex flex-row py-2 px-3 text-[9px] font-bold items-center"),+ { backgroundColor: theme.accent, color: theme.accentForeground }+ ]}+ >+ <Text style={tw("w-1/2")}>Description</Text>+ <Text style={tw("w-1/6 text-center")}>Qty</Text>+ <Text style={tw("w-1/6 text-center")}>Unit Price</Text>+ <Text style={tw("w-1/6 text-center")}>Total</Text>+ </View>++ {/* Rows */}+ {salesInvoiceLines.map((line) => {+ const isEven = rowIndex % 2 === 0;+ rowIndex++;++ const lineAddOnCost = line.convertedAddOnCost ?? 0;+ const lineNonTaxableAddOnCost = line.convertedNonTaxableAddOnCost ?? 0;+ const lineShippingCost = line.convertedShippingCost ?? 0;+ const lineTaxPercent = line.taxPercent ?? 0;+ const lineTaxAmount = getLineTaxableSubtotal(line) * lineTaxPercent;+ const totalTaxAndFees =+ lineAddOnCost ++ lineNonTaxableAddOnCost ++ lineShippingCost ++ lineTaxAmount;++ return (+ <View key={line.id}>+ <View+ wrap={false}+ style={[+ tw(+ "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"+ ),+ {+ backgroundColor:+ opts.zebra && !isEven+ ? "rgba(249, 250, 251, 0.6)"+ : "transparent"+ }+ ]}+ >+ <View style={tw("w-1/2 pr-2")}>+ <Text style={{ ...tw("text-gray-800"), ...overflow }}>+ {getLineDescription(line)}+ </Text>+ <Text+ style={{+ ...tw("text-[9px] text-gray-600 mt-0.5"),+ ...overflow+ }}+ >+ {getLineDescriptionDetails(line)}+ </Text>+ {opts.showThumbnails &&+ thumbnails &&+ line.id &&+ line.id in thumbnails &&+ thumbnails[line.id] && (+ <View style={tw("mt-1 w-16")}>+ <Image+ src={thumbnails[line.id]!}+ style={tw("w-full h-auto")}+ />+ </View>+ )}+ {line.invoiceLineType !== "Comment" && totalTaxAndFees > 0 && (+ <View style={tw("mt-1")}>+ <Text style={tw("text-[9px] text-gray-600 font-bold")}>+ Tax & Fees+ </Text>+ {lineShippingCost > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Shipping+ </Text>+ )}+ {lineAddOnCost > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Add-On+ </Text>+ )}+ {lineNonTaxableAddOnCost > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Non-Taxable Add-On+ </Text>+ )}+ {lineTaxPercent > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Tax ({(lineTaxPercent * 100).toFixed(0)}%)+ </Text>+ )}+ </View>+ )}+ </View>+ <Text style={tw("w-1/6 text-center text-gray-600")}>+ {line.invoiceLineType === "Comment"+ ? ""+ : `${line.quantity} ${line.unitOfMeasureCode ?? "EA"}`}+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-600")}>+ {line.invoiceLineType === "Comment"+ ? ""+ : numberFormatter.format(line.convertedUnitPrice ?? 0)}+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800 font-medium")}>+ {line.invoiceLineType === "Comment"+ ? ""+ : numberFormatter.format(getLineTotal(line))}+ </Text>+ </View>+ {Object.keys(line.externalNotes ?? {}).length > 0 && (+ <View style={tw("px-3 py-2 border-b border-gray-200")}>+ <Note+ key={`${line.id}-notes`}+ content={line.externalNotes as JSONContent}+ />+ </View>+ )}+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/NotesBlock.tsx b/packages/documents/src/pdf/blocks/NotesBlock.tsxnew file mode 100644index 0000000000..402021e1ed--- /dev/null+++ b/packages/documents/src/pdf/blocks/NotesBlock.tsx@@ -0,0 +1,25 @@+import type { JSONContent } from "@carbon/react";+import { Text, View } from "@react-pdf/renderer";+import { Note } from "../components";+import { tw } from "./tw";+import type { SalesInvoiceData } from "./types";++export function NotesBlock({ data }: { data: SalesInvoiceData }) {+ const { salesInvoice } = data;+ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Notes+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ {Object.keys(salesInvoice?.externalNotes ?? {}).length > 0 ? (+ <Note content={(salesInvoice.externalNotes ?? {}) as JSONContent} />+ ) : (+ <Text style={tw("text-gray-400")}>None</Text>+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/PartiesBlock.tsx b/packages/documents/src/pdf/blocks/PartiesBlock.tsxnew file mode 100644index 0000000000..252966e6a8--- /dev/null+++ b/packages/documents/src/pdf/blocks/PartiesBlock.tsx@@ -0,0 +1,161 @@+import { formatDate, isEoriCountry } from "@carbon/utils";+import { Text, View } from "@react-pdf/renderer";+import { AddressBlock } from "../components";+import { tw } from "./tw";+import type { SalesInvoiceData } from "./types";++export function PartiesBlock({ data }: { data: SalesInvoiceData }) {+ const {+ salesInvoice,+ salesInvoiceShipment,+ salesInvoiceLocations,+ salesOrderIds,+ paymentTerms,+ shippingMethods,+ locale+ } = data;++ const {+ customerName,+ customerAddressLine1,+ customerAddressLine2,+ customerCity,+ customerStateProvince,+ customerPostalCode,+ customerCountryName,+ customerTaxId,+ customerVatNumber,+ customerEori,+ invoiceCustomerName,+ invoiceAddressLine1,+ invoiceAddressLine2,+ invoiceCity,+ invoiceStateProvince,+ invoicePostalCode,+ invoiceCountryName,+ shipmentCustomerName,+ shipmentAddressLine1,+ shipmentAddressLine2,+ shipmentCity,+ shipmentStateProvince,+ shipmentPostalCode,+ shipmentCountryName+ } = salesInvoiceLocations;++ const paymentTerm = paymentTerms?.find(+ (term) => term.id === salesInvoice?.paymentTermId+ );++ const shippingMethod = shippingMethods?.find(+ (method) => method.id === salesInvoiceShipment?.shippingMethodId+ );++ return (+ /* Body row — Bill To (left) | Invoice Details + Ship To stacked (right) */+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row")}>+ {/* LEFT — Bill To (the customer being invoiced) */}+ <View style={tw("w-1/2 p-3 border-r border-gray-200")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Bill To+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <AddressBlock+ name={invoiceCustomerName ?? customerName}+ addressLine1={invoiceAddressLine1 ?? customerAddressLine1}+ addressLine2={invoiceAddressLine2 ?? customerAddressLine2}+ city={invoiceCity ?? customerCity}+ stateProvince={invoiceStateProvince ?? customerStateProvince}+ postalCode={invoicePostalCode ?? customerPostalCode}+ country={invoiceCountryName ?? customerCountryName}+ />+ {customerTaxId &&+ !isEoriCountry(invoiceCountryName ?? customerCountryName) && (+ <Text>Tax ID: {customerTaxId}</Text>+ )}+ {customerVatNumber && <Text>VAT: {customerVatNumber}</Text>}+ {customerEori && <Text>EORI: {customerEori}</Text>}+ </View>+ </View>++ {/* RIGHT — Invoice Details + Ship To stacked */}+ <View style={tw("w-1/2 flex flex-col")}>+ {/* Invoice Details — Due Date prominent */}+ <View+ style={tw(+ shipmentCustomerName ? "p-3 border-b border-gray-200" : "p-3"+ )}+ >+ <Text+ style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}+ >+ Invoice Details+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ {salesInvoice?.dateIssued && (+ <Text>+ Date Issued:{" "}+ {formatDate(salesInvoice.dateIssued, undefined, locale)}+ </Text>+ )}+ {salesInvoice?.dateDue && (+ <Text style={tw("font-bold")}>+ Due Date:{" "}+ {formatDate(salesInvoice.dateDue, undefined, locale)}+ </Text>+ )}+ {salesInvoice?.customerReference && (+ <Text>Customer Ref: {salesInvoice.customerReference}</Text>+ )}+ {salesOrderIds && salesOrderIds.length > 0 && (+ <Text>+ {salesOrderIds.length > 1+ ? "Sales Orders: "+ : "Sales Order: "}+ {salesOrderIds.join(", ")}+ </Text>+ )}+ {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}+ {shippingMethod && <Text>Shipping: {shippingMethod.name}</Text>}+ {salesInvoiceShipment?.shippingTermId && (+ <Text>+ Shipping Terms: {salesInvoiceShipment.shippingTermId}+ </Text>+ )}+ {salesInvoiceShipment?.incoterm && (+ <Text>+ Incoterm: {salesInvoiceShipment.incoterm}+ {salesInvoiceShipment.incotermLocation+ ? ` — ${salesInvoiceShipment.incotermLocation}`+ : ""}+ </Text>+ )}+ </View>+ </View>++ {/* Ship To — only when shipment has a distinct address (not falling back to customer's main address) */}+ {shipmentCustomerName && (+ <View style={tw("p-3")}>+ <Text+ style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}+ >+ Ship To+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <AddressBlock+ name={shipmentCustomerName}+ addressLine1={shipmentAddressLine1}+ addressLine2={shipmentAddressLine2}+ city={shipmentCity}+ stateProvince={shipmentStateProvince}+ postalCode={shipmentPostalCode}+ country={shipmentCountryName}+ />+ </View>+ </View>+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/RichTextBlock.tsx b/packages/documents/src/pdf/blocks/RichTextBlock.tsxnew file mode 100644index 0000000000..26af27fbf4--- /dev/null+++ b/packages/documents/src/pdf/blocks/RichTextBlock.tsx@@ -0,0 +1,46 @@+import { Text, View } from "@react-pdf/renderer";+import type { RichTextBlock as RichTextBlockType } from "../../template";+import { interpolateContent } from "../../template";+import { Note } from "../components";+import { tw } from "./tw";++/**+ * Extension block — doc-agnostic. Takes only the merge-field `vars` so any+ * document's registry can reuse it.+ */+export function RichTextBlock({+ block,+ vars+}: {+ block: RichTextBlockType;+ vars: Record<string, string>;+}) {+ const hasContent =+ block.content &&+ typeof block.content === "object" &&+ Array.isArray(block.content.content) &&+ block.content.content.length > 0;++ if (!hasContent && !block.title) return null;++ const content = hasContent+ ? interpolateContent(block.content, vars)+ : block.content;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ {block.title && (+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ {block.title}+ </Text>+ )}+ {hasContent && (+ <View style={tw("text-[9px] text-gray-800")}>+ <Note content={content} />+ </View>+ )}+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/SharedBlock.tsx b/packages/documents/src/pdf/blocks/SharedBlock.tsxnew file mode 100644index 0000000000..8694f8f8dd--- /dev/null+++ b/packages/documents/src/pdf/blocks/SharedBlock.tsx@@ -0,0 +1,43 @@+import { Text, View } from "@react-pdf/renderer";+import type {+ ResolvedSection,+ SharedBlock as SharedBlockType+} from "../../template";+import { interpolateContent } from "../../template";+import { Note } from "../components";+import { tw } from "./tw";++/** Extension block — doc-agnostic. Takes resolved sections + merge `vars`. */+export function SharedBlock({+ block,+ sections,+ vars+}: {+ block: SharedBlockType;+ sections: Record<string, ResolvedSection>;+ vars: Record<string, string>;+}) {+ const section = sections[block.sectionId];+ if (!section) return null;++ const hasContent =+ section.content &&+ typeof section.content === "object" &&+ Array.isArray(section.content.content) &&+ section.content.content.length > 0;++ if (!hasContent) return null;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ {section.name}+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <Note content={interpolateContent(section.content, vars)} />+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/SpacerBlock.tsx b/packages/documents/src/pdf/blocks/SpacerBlock.tsxnew file mode 100644index 0000000000..7bcec84ef9--- /dev/null+++ b/packages/documents/src/pdf/blocks/SpacerBlock.tsx@@ -0,0 +1,27 @@+import { View } from "@react-pdf/renderer";+import type { SpacerBlock as SpacerBlockType } from "../../template";++/**+ * Structural spacing block. Uses explicit style objects (not Tailwind arbitrary+ * values like `h-[1px]`, which react-pdf-tailwind can silently drop) so every+ * variant renders deterministically.+ */+export function SpacerBlock({ block }: { block: SpacerBlockType }) {+ switch (block.variant) {+ case "divider":+ return (+ <View+ style={{+ borderBottomWidth: 1,+ borderBottomColor: "#e5e7eb",+ borderBottomStyle: "solid",+ marginVertical: 12+ }}+ />+ );+ case "pageBreak":+ return <View break />;+ default:+ return <View style={{ height: block.size ?? 16 }} />;+ }+}diff --git a/packages/documents/src/pdf/blocks/SummaryBlock.tsx b/packages/documents/src/pdf/blocks/SummaryBlock.tsxnew file mode 100644index 0000000000..fccd83301d--- /dev/null+++ b/packages/documents/src/pdf/blocks/SummaryBlock.tsx@@ -0,0 +1,143 @@+import { Text, View } from "@react-pdf/renderer";+import {+ DEFAULT_SUMMARY_OPTIONS,+ type SummaryBlock as SummaryBlockType+} from "../../template";+import { getLineTaxableSubtotal, getTotal } from "../../utils/sales-invoice";+import { tw } from "./tw";+import type { SalesInvoiceData } from "./types";++export function SummaryBlock({+ block,+ data+}: {+ block: SummaryBlockType;+ data: SalesInvoiceData;+}) {+ const {+ salesInvoiceLines,+ salesInvoice,+ salesInvoiceShipment,+ currencyCode,+ numberFormatter+ } = data;+ const opts = { ...DEFAULT_SUMMARY_OPTIONS, ...block.options };+ const taxLabel = opts.taxLabel?.trim() || DEFAULT_SUMMARY_OPTIONS.taxLabel;++ return (+ <View style={tw("mb-4")}>+ <View>+ {/* Subtotal - extended price only */}+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Subtotal ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(+ salesInvoiceLines.reduce(+ (sum, line) =>+ sum + (line.quantity ?? 0) * (line.convertedUnitPrice ?? 0),+ 0+ )+ )}+ </Text>+ </View>++ {/* Add-Ons */}+ {salesInvoiceLines.some(+ (line) =>+ (line.convertedAddOnCost ?? 0) > 0 ||+ (line.convertedNonTaxableAddOnCost ?? 0) > 0+ ) && (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Add-Ons ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(+ salesInvoiceLines.reduce(+ (sum, line) =>+ sum ++ (line.convertedAddOnCost ?? 0) ++ (line.convertedNonTaxableAddOnCost ?? 0),+ 0+ )+ )}+ </Text>+ </View>+ )}++ {/* Shipping */}+ {(() => {+ const lineShipping = salesInvoiceLines.reduce(+ (sum, line) => sum + (line.convertedShippingCost ?? 0),+ 0+ );+ const invoiceShipping =+ (salesInvoiceShipment?.shippingCost ?? 0) *+ (salesInvoice.exchangeRate ?? 1);+ const totalShipping = lineShipping + invoiceShipping;+ return totalShipping > 0 ? (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Shipping ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(totalShipping)}+ </Text>+ </View>+ ) : null;+ })()}++ {/* Taxes */}+ {salesInvoiceLines.some((line) => (line.taxPercent ?? 0) > 0) && (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ {taxLabel} ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(+ salesInvoiceLines.reduce((sum, line) => {+ const taxPercent = line.taxPercent ?? 0;+ return sum + getLineTaxableSubtotal(line) * taxPercent;+ }, 0)+ )}+ </Text>+ </View>+ )}++ <View style={tw("h-[1px] bg-gray-200")} />+ <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>+ <Text style={tw("w-5/6 text-right pr-3 text-gray-800 font-bold")}>+ Total ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800 font-bold")}>+ {numberFormatter.format(+ getTotal(salesInvoiceLines, salesInvoice, salesInvoiceShipment)+ )}+ </Text>+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/TermsBlock.tsx b/packages/documents/src/pdf/blocks/TermsBlock.tsxnew file mode 100644index 0000000000..4c5e054947--- /dev/null+++ b/packages/documents/src/pdf/blocks/TermsBlock.tsx@@ -0,0 +1,34 @@+import { Text, View } from "@react-pdf/renderer";+import type { TermsBlock as TermsBlockType } from "../../template";+import { Note } from "../components";+import { hasContent, resolveTerms } from "./resolveTerms";+import { tw } from "./tw";+import type { SalesInvoiceData } from "./types";++export function TermsBlock({+ block,+ data+}: {+ block: TermsBlockType;+ data: SalesInvoiceData;+}) {+ const { theme, vars } = data;+ const terms = resolveTerms(block, data.terms, vars);+ if (!hasContent(terms)) return null;++ return (+ <View break>+ <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>+ <Text+ style={[+ tw("text-[14px] font-bold uppercase tracking-wide"),+ { color: theme.accent }+ ]}+ >+ Terms & Conditions+ </Text>+ </View>+ <Note content={terms!} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/extensionRegistry.tsx b/packages/documents/src/pdf/blocks/extensionRegistry.tsxnew file mode 100644index 0000000000..e9705be8a7--- /dev/null+++ b/packages/documents/src/pdf/blocks/extensionRegistry.tsx@@ -0,0 +1,66 @@+import type {+ DocumentBlock,+ DocumentBlockType,+ ResolvedSection+} from "../../template";+import { Watermark } from "../components";+import { FieldBlock } from "./FieldBlock";+import { KeyValueBlock } from "./KeyValueBlock";+import { RichTextBlock } from "./RichTextBlock";+import { SharedBlock } from "./SharedBlock";+import { SpacerBlock } from "./SpacerBlock";++/**+ * The minimal data every extension renderer needs. Each document's richer data+ * bag (QuoteData, JobTravelerData, …) is a superset, so these renderers slot+ * into any document registry.+ */+interface ExtensionData {+ vars: Record<string, string>;+ sections: Record<string, ResolvedSection>;+ company?: { logoWatermark?: string | null };+}++type ExtensionRenderer = (args: {+ block: DocumentBlock;+ data: ExtensionData;+}) => JSX.Element | null;++/**+ * The doc-agnostic extension blocks, defined once. Every non-label document+ * registry spreads this in instead of copy-pasting the same five entries — so+ * adding an extension block is a one-line change here, not an edit across every+ * registry. (Tracking labels are text-only and intentionally opt out.)+ */+export const extensionBlocks: Partial<+ Record<DocumentBlockType, ExtensionRenderer>+> = {+ richText: ({ block, data }) =>+ block.type === "richText" ? (+ <RichTextBlock block={block} vars={data.vars} />+ ) : null,+ keyValue: ({ block, data }) =>+ block.type === "keyValue" ? (+ <KeyValueBlock block={block} vars={data.vars} />+ ) : null,+ spacer: ({ block }) =>+ block.type === "spacer" ? <SpacerBlock block={block} /> : null,+ shared: ({ block, data }) =>+ block.type === "shared" ? (+ <SharedBlock block={block} sections={data.sections} vars={data.vars} />+ ) : null,+ field: ({ block, data }) =>+ block.type === "field" ? (+ <FieldBlock block={block} vars={data.vars} />+ ) : null,+ watermark: ({ block, data }) =>+ block.type === "watermark" ? (+ <Watermark+ src={data.company?.logoWatermark}+ show+ opacity={block.opacity}+ placement={block.placement}+ size={block.size}+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/index.ts b/packages/documents/src/pdf/blocks/index.tsnew file mode 100644index 0000000000..17ace36f95--- /dev/null+++ b/packages/documents/src/pdf/blocks/index.ts@@ -0,0 +1,7 @@+export { salesInvoiceBlockRegistry } from "./registry";+export type {+ BlockRenderer,+ SalesInvoiceData,+ SalesInvoiceLocations+} from "./types";+export { buildSalesInvoiceVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/issue/ActionTasksBlock.tsx b/packages/documents/src/pdf/blocks/issue/ActionTasksBlock.tsxnew file mode 100644index 0000000000..101ce2f257--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/ActionTasksBlock.tsx@@ -0,0 +1,146 @@+import type { JSONContent } from "@carbon/react";+import { Text, View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "../tw";+import type { IssueData } from "./types";++/** Repeating action-task blocks, each with optional nested inspections. */+export function ActionTasksBlock({ data }: { data: IssueData }) {+ const {+ actionTasks,+ requiredActions,+ assignees,+ jobOperationStepRecords,+ operationToJobId+ } = data;++ const sortedActionTasks = [...actionTasks].sort(+ (a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0)+ );++ if (sortedActionTasks.length === 0) return null;++ return (+ <View style={tw("mb-4")}>+ {sortedActionTasks.map((task) => (+ <View+ key={task.id}+ style={tw("border border-gray-200 mb-4")}+ wrap={false}+ >+ <View style={tw("p-3")}>+ <Text+ style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}+ >+ {task.supplier?.name ? "Supplier " : ""}+ {+ requiredActions.find(+ (action) => action.id === task.actionTypeId+ )?.name+ }+ </Text>+ <View style={tw("flex flex-col gap-1 text-[10px]")}>+ {task.supplier?.name && (+ <View style={tw("flex flex-row gap-2")}>+ <Text style={tw("font-bold text-gray-600")}>Supplier:</Text>+ <Text style={tw("text-gray-800")}>{task.supplier.name}</Text>+ </View>+ )}+ {task.assignee && assignees[task.assignee] && (+ <View style={tw("flex flex-row gap-2")}>+ <Text style={tw("font-bold text-gray-600")}>+ {task.supplier?.name ? "Verified by" : "Completed by"}:+ </Text>+ <Text style={tw("text-gray-800")}>+ {assignees[task.assignee]}+ </Text>+ </View>+ )}+ {task.completedDate && (+ <View style={tw("flex flex-row gap-2")}>+ <Text style={tw("font-bold text-gray-600")}>+ Completed on:+ </Text>+ <Text style={tw("text-gray-800")}>{task.completedDate}</Text>+ </View>+ )}+ </View>+ {Object.keys(task.notes ?? {}).length > 0 && (+ <View style={tw("mt-2 pt-2 border-t border-gray-200")}>+ <Note content={task.notes as JSONContent} />+ </View>+ )}+ {/* Job Operation Step Records */}+ {jobOperationStepRecords+ .filter((step) => step.nonConformanceActionId === task.id)+ .some((step) =>+ step.jobOperationStepRecord?.some(+ (record) => record.booleanValue !== null+ )+ ) && (+ <View style={tw("mt-2 pt-2 border-t border-gray-200")}>+ <Text+ style={tw(+ "text-[9px] font-bold text-gray-600 mb-1 uppercase"+ )}+ >+ Inspections+ </Text>+ {jobOperationStepRecords+ .filter((step) => step.nonConformanceActionId === task.id)+ .map((step) =>+ step.jobOperationStepRecord+ ?.filter((record) => record.booleanValue !== null)+ .map((record) => (+ <View+ key={record.id}+ style={tw("flex flex-row gap-2 text-[10px] py-0.5")}+ >+ <View+ style={{+ width: 10,+ height: 10,+ border: "1px solid #9ca3af",+ marginTop: 2,+ position: "relative"+ }}+ >+ <Text+ style={{+ position: "absolute",+ fontSize: 10,+ fontWeight: "bold",+ lineHeight: 1,+ textAlign: "center",+ top: -3,+ left: -1.5+ }}+ >+ {record.booleanValue ? "✓" : ""}+ </Text>+ </View>+ <View style={tw("flex flex-col")}>+ <Text style={tw("text-gray-800")}>{step.name}</Text>+ <Text style={tw("text-[8px] text-gray-400 mt-0.5")}>+ {operationToJobId[step.operationId] && (+ <>Job {operationToJobId[step.operationId]} • </>+ )}+ {assignees[record.createdBy] || "Unknown"} •{" "}+ {+ new Date(record.createdAt)+ .toISOString()+ .split("T")[0]+ }+ </Text>+ </View>+ </View>+ ))+ )}+ </View>+ )}+ </View>+ </View>+ ))}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/issue/AssociationsBlock.tsx b/packages/documents/src/pdf/blocks/issue/AssociationsBlock.tsxnew file mode 100644index 0000000000..76bdbb467a--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/AssociationsBlock.tsx@@ -0,0 +1,70 @@+import { Text, View } from "@react-pdf/renderer";+import { tw } from "../tw";+import type { Associations, IssueData } from "./types";++const rowStyle = tw(+ "flex flex-row gap-2 text-[10px] py-1 border-b border-gray-200"+);++/** A single labeled association row (label + readable id). */+function Row({ label, value }: { label: string; value: string }) {+ return (+ <View style={rowStyle}>+ <Text style={tw("w-1/4 font-bold text-gray-600")}>{label}:</Text>+ <Text style={tw("text-gray-800")}>{value}</Text>+ </View>+ );+}++/** Groups that render as a plain label + documentReadableId, in order. */+const SIMPLE_GROUPS: { key: keyof Associations; label: string }[] = [+ { key: "customers", label: "Customer" },+ { key: "suppliers", label: "Supplier" },+ { key: "jobOperations", label: "Job Operation" },+ { key: "purchaseOrderLines", label: "Purchase Order" },+ { key: "salesOrderLines", label: "Sales Order" },+ { key: "shipmentLines", label: "Shipment" },+ { key: "receiptLines", label: "Receipt" },+ { key: "trackedEntities", label: "Tracked Entity" }+];++/** Related entities grouped by type. Renders nothing when there are none. */+export function AssociationsBlock({ data }: { data: IssueData }) {+ const { associations } = data;+ if (!associations) return null;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Associations+ </Text>+ <View style={tw("flex flex-col")}>+ {associations.items?.map((item) => (+ <View key={item.id} style={rowStyle}>+ <Text style={tw("w-1/4 font-bold text-gray-600")}>Item:</Text>+ <Text style={tw("text-gray-800")}>{item.documentReadableId}</Text>+ {item.disposition && (+ <>+ <Text style={tw("text-gray-400")}>-</Text>+ <Text style={tw("text-gray-800")}>{item.disposition}</Text>+ </>+ )}+ {item.quantity && (+ <>+ <Text style={tw("text-gray-400")}>-</Text>+ <Text style={tw("text-gray-800")}>Qty: {item.quantity}</Text>+ </>+ )}+ </View>+ ))}+ {SIMPLE_GROUPS.flatMap(({ key, label }) =>+ (associations[key] ?? []).map((row) => (+ <Row key={row.id} label={label} value={row.documentReadableId} />+ ))+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/issue/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/issue/HeaderBlock.tsxnew file mode 100644index 0000000000..1901169c5c--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/HeaderBlock.tsx@@ -0,0 +1,16 @@+import { Header } from "../../components";+import type { IssueData } from "./types";++/** Company logo + "Issue Report" title + issue id. */+export function HeaderBlock({ data }: { data: IssueData }) {+ return (+ <Header+ company={data.company}+ title="Issue Report"+ documentId={data.nonConformance.nonConformanceId}+ date={data.nonConformance.openDate}+ locale={data.locale}+ options={data.headerOptions}+ />+ );+}diff --git a/packages/documents/src/pdf/blocks/issue/IssueDetailsBlock.tsx b/packages/documents/src/pdf/blocks/issue/IssueDetailsBlock.tsxnew file mode 100644index 0000000000..0ceeaad8a8--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/IssueDetailsBlock.tsx@@ -0,0 +1,57 @@+import { formatDate } from "@carbon/utils";+import { Text, View } from "@react-pdf/renderer";+import { tw } from "../tw";+import type { IssueData } from "./types";++/** Two-column issue metadata box (name/type/status/initiator + dates). */+export function IssueDetailsBlock({ data }: { data: IssueData }) {+ const { nonConformance, nonConformanceTypes, assignees, locale } = data;+ const ncType = nonConformanceTypes.find(+ (type) => type.id === nonConformance.nonConformanceTypeId+ );++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row")}>+ <View style={tw("w-1/2 p-3 border-r border-gray-200")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Issue Details+ </Text>+ <View style={tw("text-[10px] text-gray-800")}>+ {nonConformance.name && (+ <Text style={tw("font-bold")}>{nonConformance.name}</Text>+ )}+ {ncType?.name && (+ <Text style={tw("mt-1")}>Type: {ncType.name}</Text>+ )}+ {nonConformance.status && (+ <Text>Status: {nonConformance.status}</Text>+ )}+ <Text>+ Initiated By: {assignees[nonConformance.createdBy] || "Unknown"}+ </Text>+ </View>+ </View>+ <View style={tw("w-1/2 p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Dates+ </Text>+ <View style={tw("text-[10px] text-gray-800")}>+ {nonConformance.openDate && (+ <Text>+ Started:{" "}+ {formatDate(nonConformance.openDate, undefined, locale)}+ </Text>+ )}+ {nonConformance.closeDate && (+ <Text>+ Completed:{" "}+ {formatDate(nonConformance.closeDate, undefined, locale)}+ </Text>+ )}+ </View>+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/issue/NotesBlock.tsx b/packages/documents/src/pdf/blocks/issue/NotesBlock.tsxnew file mode 100644index 0000000000..433d8ebd84--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/NotesBlock.tsx@@ -0,0 +1,24 @@+import type { JSONContent } from "@carbon/react";+import { Text, View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "../tw";+import type { IssueData } from "./types";++/** Description of the issue (rich text). Renders nothing when empty. */+export function NotesBlock({ data }: { data: IssueData }) {+ const { nonConformance } = data;+ if (Object.keys(nonConformance.content ?? {}).length === 0) return null;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Description of Issue+ </Text>+ <View style={tw("mt-1")}>+ <Note content={nonConformance.content as JSONContent} />+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/issue/ReviewersBlock.tsx b/packages/documents/src/pdf/blocks/issue/ReviewersBlock.tsxnew file mode 100644index 0000000000..4aefd91b95--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/ReviewersBlock.tsx@@ -0,0 +1,46 @@+import type { JSONContent } from "@carbon/react";+import { Text, View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "../tw";+import type { IssueData } from "./types";++/** MRB reviewer list with per-reviewer status + notes. Empty → nothing. */+export function ReviewersBlock({ data }: { data: IssueData }) {+ const { reviewers } = data;+ if (reviewers.length === 0) return null;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-2 uppercase")}>+ MRB+ </Text>+ {reviewers.map((reviewer, index) => (+ <View+ key={reviewer.id}+ style={tw(+ `flex flex-col gap-1 py-2 ${+ index < reviewers.length - 1 ? "border-b border-gray-200" : ""+ }`+ )}+ >+ <View style={tw("flex flex-row justify-between")}>+ <Text style={tw("text-[10px] font-bold text-gray-800")}>+ {reviewer.title}+ </Text>+ <Text style={tw("text-[10px] text-gray-600")}>+ {reviewer.status}+ </Text>+ </View>++ {Object.keys(reviewer.notes ?? {}).length > 0 && (+ <View style={tw("mt-1")}>+ <Note content={reviewer.notes as JSONContent} />+ </View>+ )}+ </View>+ ))}+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/issue/index.ts b/packages/documents/src/pdf/blocks/issue/index.tsnew file mode 100644index 0000000000..835f58415f--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/index.ts@@ -0,0 +1,11 @@+export { issueBlockRegistry } from "./registry";+export type {+ ActionTask,+ Associations,+ BlockRenderer,+ IssueData,+ IssueItem,+ JobOperationStepWithRecords,+ ListItem+} from "./types";+export { buildIssueVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/issue/registry.tsx b/packages/documents/src/pdf/blocks/issue/registry.tsxnew file mode 100644index 0000000000..07fe805b0f--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/registry.tsx@@ -0,0 +1,32 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import { extensionBlocks } from "../extensionRegistry";+import { ActionTasksBlock } from "./ActionTasksBlock";+import { AssociationsBlock } from "./AssociationsBlock";+import { HeaderBlock } from "./HeaderBlock";+import { IssueDetailsBlock } from "./IssueDetailsBlock";+import { NotesBlock } from "./NotesBlock";+import { ReviewersBlock } from "./ReviewersBlock";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for the Issue report. Extension blocks are shared. */+export const issueBlockRegistry: Partial<+ Record<DocumentBlockType, BlockRenderer>+> = {+ ...extensionBlocks,+ header: ({ data }) => <HeaderBlock data={data} />,+ issueDetails: ({ data }) => <IssueDetailsBlock data={data} />,+ associations: ({ data }) => <AssociationsBlock data={data} />,+ notes: ({ data }) => <NotesBlock data={data} />,+ actionTasks: ({ data }) => <ActionTasksBlock data={data} />,+ reviewers: ({ data }) => <ReviewersBlock data={data} />,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={+ (data.nonConformance?.customFields ?? {}) as Record<string, unknown>+ }+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/issue/types.ts b/packages/documents/src/pdf/blocks/issue/types.tsnew file mode 100644index 0000000000..f975bff9ce--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/types.ts@@ -0,0 +1,71 @@+import type { Database } from "@carbon/database";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions,+ ResolvedSection+} from "../../../template";+import type { Company } from "../../../types";++export type ListItem = { id: string; name: string };++export type IssueItem =+ Database["public"]["Tables"]["nonConformanceItem"]["Row"] & {+ name: string | null;+ };++export type ActionTask =+ Database["public"]["Tables"]["nonConformanceActionTask"]["Row"] & {+ supplier: { name: string } | null;+ };++type JobOperationStepRecord =+ Database["public"]["Tables"]["jobOperationStepRecord"]["Row"];++export type JobOperationStepWithRecords = {+ id: string;+ name: string | null;+ operationId: string;+ nonConformanceActionId: string | null;+ jobOperationStepRecord: JobOperationStepRecord[];+};++// Association rows are loose join shapes; renderers read ad-hoc props.+type AnyRow = Record<string, any>;++export type Associations = {+ items: AnyRow[];+ customers: AnyRow[];+ suppliers: AnyRow[];+ jobOperations: AnyRow[];+ purchaseOrderLines: AnyRow[];+ salesOrderLines: AnyRow[];+ shipmentLines: AnyRow[];+ receiptLines: AnyRow[];+ trackedEntities: AnyRow[];+};++/** Everything an Issue block renderer might need. */+export interface IssueData {+ company: Company;+ locale?: string;+ nonConformance: Database["public"]["Tables"]["nonConformance"]["Row"];+ nonConformanceTypes: Database["public"]["Tables"]["nonConformanceType"]["Row"][];+ actionTasks: ActionTask[];+ requiredActions: ListItem[];+ reviewers: Database["public"]["Tables"]["nonConformanceReviewer"]["Row"][];+ items: IssueItem[];+ associations?: Associations | null;+ assignees: Record<string, string>;+ jobOperationStepRecords: JobOperationStepWithRecords[];+ operationToJobId: Record<string, string>;+ theme: DocumentTheme;+ sections: Record<string, ResolvedSection>;+ vars: Record<string, string>;+ headerOptions: HeaderOptions;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: IssueData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/issue/vars.ts b/packages/documents/src/pdf/blocks/issue/vars.tsnew file mode 100644index 0000000000..fd88b2cb0c--- /dev/null+++ b/packages/documents/src/pdf/blocks/issue/vars.ts@@ -0,0 +1,20 @@+import type { IssueData } from "./types";++/** Merge-field variable map for an Issue. */+export function buildIssueVars(+ data: Pick<IssueData, "nonConformance" | "company">+): Record<string, string> {+ const nc = data.nonConformance;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "issue.number": str(nc?.nonConformanceId),+ "issue.name": str(nc?.name),+ "issue.status": str(nc?.status),+ "issue.openDate": str(nc?.openDate),+ "issue.closeDate": str(nc?.closeDate),+ "company.name": str(data.company?.name),+ "company.city": str(data.company?.city),+ "company.country": str(data.company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/itemText.ts b/packages/documents/src/pdf/blocks/itemText.tsnew file mode 100644index 0000000000..a381fdba5c--- /dev/null+++ b/packages/documents/src/pdf/blocks/itemText.ts@@ -0,0 +1,15 @@+import type { LineItemsOptions } from "../../template";++/**+ * Style for the line-item title/description text. With `truncate`, clamp to a+ * single line with an ellipsis; with `wrap` (default), let it flow onto new+ * lines (which grows the row height). Shared by every document's LineItemsBlock.+ */+export function itemTextOverflowStyle(options?: Partial<LineItemsOptions>): {+ maxLines?: number;+ textOverflow?: "ellipsis";+} {+ return options?.textOverflow === "truncate"+ ? { maxLines: 1, textOverflow: "ellipsis" }+ : {};+}diff --git a/packages/documents/src/pdf/blocks/jobTraveler/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/jobTraveler/HeaderBlock.tsxnew file mode 100644index 0000000000..50df44559a--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/HeaderBlock.tsx@@ -0,0 +1,26 @@+import { View } from "@react-pdf/renderer";+import { Header } from "../../components";+import { tw } from "./tw";+import type { JobTravelerData } from "./types";++/** Company logo + "Job Traveler" title + job id (and SO sub-id). */+export function HeaderBlock({ data }: { data: JobTravelerData }) {+ const { company, job, locale, headerOptions } = data;+ return (+ <View style={tw("mb-6")}>+ <Header+ company={company}+ title="Job Traveler"+ documentId={job.jobId}+ documentSubId={+ job.salesOrderReadableId+ ? `SO# ${job.salesOrderReadableId}`+ : undefined+ }+ date={job.startDate}+ locale={locale}+ options={headerOptions}+ />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/jobTraveler/JobDetailsBlock.tsx b/packages/documents/src/pdf/blocks/jobTraveler/JobDetailsBlock.tsxnew file mode 100644index 0000000000..224f0337c9--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/JobDetailsBlock.tsx@@ -0,0 +1,174 @@+import { formatDate } from "@carbon/utils";+import { Image, StyleSheet, Text, View } from "@react-pdf/renderer";+import { tw } from "./tw";+import type { JobTravelerData } from "./types";++const jobHeaderStyles = StyleSheet.create({+ jobHeader: {+ border: "1px solid #CCC",+ borderRadius: 6,+ padding: 16,+ fontSize: 10,+ display: "flex",+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "flex-start",+ marginBottom: 20,+ gap: 60+ },+ leftSection: {+ flex: 1,+ marginTop: 5+ },+ rightSection: {+ flex: 1+ },+ infoRow: {+ display: "flex",+ flexDirection: "row",+ justifyContent: "space-between",+ marginBottom: 4+ },+ label: {+ fontSize: 11,+ fontWeight: 600,+ color: "#374151"+ },+ value: {+ fontSize: 11,+ fontWeight: 400,+ color: "#111827"+ }+});++/** The two-column job info box (ids, qty, dates, thumbnail). */+export function JobDetailsBlock({ data }: { data: JobTravelerData }) {+ const {+ job,+ item,+ customer,+ batchNumber,+ methodRevision,+ thumbnail,+ locale,+ jobOperations+ } = data;++ const getTargetInfo = () => {+ if (job.salesOrderId && job.salesOrderLineId) {+ return `Sales Order: ${job.salesOrderReadableId || "Make to Order"}`;+ }+ return "Inventory";+ };++ const getTrackingNumber = () => {+ if (batchNumber) {+ return `${item.itemTrackingType} Number: ${batchNumber}`;+ }+ return null;+ };++ return (+ <View style={tw("mb-6")}>+ <View style={jobHeaderStyles.jobHeader}>+ <View style={jobHeaderStyles.leftSection}>+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Job ID:</Text>+ <Text style={jobHeaderStyles.value}>{job.jobId}</Text>+ </View>++ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Part ID:</Text>+ <Text style={jobHeaderStyles.value}>+ {job.itemReadableIdWithRevision}+ </Text>+ </View>++ {methodRevision && methodRevision !== "0" && (+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Method Revision:</Text>+ <Text style={jobHeaderStyles.value}>V{methodRevision}</Text>+ </View>+ )}++ {getTrackingNumber() && (+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Tracking:</Text>+ <Text style={jobHeaderStyles.value}>{getTrackingNumber()}</Text>+ </View>+ )}++ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Item:</Text>+ <Text style={jobHeaderStyles.value}>+ {item.name || item.readableIdWithRevision}+ </Text>+ </View>++ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Quantity:</Text>+ <Text style={jobHeaderStyles.value}>+ {jobOperations?.[0]?.targetQuantity ?? job.quantity}{" "}+ {job.unitOfMeasureCode}+ </Text>+ </View>++ {job.scrapQuantity && job.scrapQuantity > 0 && (+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Scrap Qty:</Text>+ <Text style={jobHeaderStyles.value}>+ {job.scrapQuantity} {job.unitOfMeasureCode}+ </Text>+ </View>+ )}+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Target:</Text>+ <Text style={jobHeaderStyles.value}>{getTargetInfo()}</Text>+ </View>+ {customer && (+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Customer:</Text>+ <Text style={jobHeaderStyles.value}>{customer.name}</Text>+ </View>+ )}++ {job.startDate && (+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Start Date:</Text>+ <Text style={jobHeaderStyles.value}>+ {formatDate(job.startDate, undefined, locale)}+ </Text>+ </View>+ )}++ {job.dueDate && (+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Due Date:</Text>+ <Text style={jobHeaderStyles.value}>+ {formatDate(job.dueDate, undefined, locale)}+ </Text>+ </View>+ )}++ {job.deadlineType && (+ <View style={jobHeaderStyles.infoRow}>+ <Text style={jobHeaderStyles.label}>Deadline Type:</Text>+ <Text style={jobHeaderStyles.value}>{job.deadlineType}</Text>+ </View>+ )}+ </View>++ <View style={jobHeaderStyles.rightSection}>+ {thumbnail && (+ <View>+ <Image+ src={thumbnail}+ style={tw("w-full h-auto border rounded-lg border-gray-300")}+ />+ </View>+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/jobTraveler/NotesBlock.tsx b/packages/documents/src/pdf/blocks/jobTraveler/NotesBlock.tsxnew file mode 100644index 0000000000..c13734195e--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/NotesBlock.tsx@@ -0,0 +1,14 @@+import { View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "./tw";+import type { JobTravelerData } from "./types";++/** Job notes (rich text). Renders nothing when there are no notes. */+export function NotesBlock({ data }: { data: JobTravelerData }) {+ if (!data.notes) return null;+ return (+ <View style={tw("mb-6")}>+ <Note title="Job Notes" content={data.notes} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/jobTraveler/OperationsBlock.tsx b/packages/documents/src/pdf/blocks/jobTraveler/OperationsBlock.tsxnew file mode 100644index 0000000000..130f6e761b--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/OperationsBlock.tsx@@ -0,0 +1,277 @@+import { getMESUrl } from "@carbon/env";+import type { JSONContent } from "@carbon/react";+import { formatFactor } from "@carbon/utils";+import { Image, Text, View } from "@react-pdf/renderer";+import { generateQRCode } from "../../../qr/qr-code";+import type { OperationsBlock as OperationsBlockType } from "../../../template";+import { Note } from "../../components";+import { tw } from "./tw";+import type { JobOperationWithSteps, JobTravelerData } from "./types";++function getStartPath(operationId: string) {+ return `${getMESUrl()}/x/start/${operationId}`;+}++function getEndPath(operationId: string) {+ return `${getMESUrl()}/x/end/${operationId}`;+}++function getParallelizedOrder(+ index: number,+ item: JobOperationWithSteps,+ items: JobOperationWithSteps[]+) {+ if (item?.operationOrder !== "With Previous") return index + 1;+ // traverse backwards to find the first non-"With Previous" item.+ for (let i = index - 1; i >= 0; i--) {+ if (items[i]?.operationOrder !== "With Previous") {+ return i + 1;+ }+ }+ return 1;+}++/** Routing table: seq, operation, expected times, QR actions, steps, work instructions. */+export function OperationsBlock({+ block,+ data+}: {+ block: OperationsBlockType;+ data: JobTravelerData;+}) {+ const { jobOperations } = data;+ const includeWorkInstructions = block.showWorkInstructions ?? false;++ return (+ <View style={tw("mb-6 text-xs")}>+ <View+ style={tw(+ "flex flex-row justify-between items-center py-3 px-[6px] border-t border-b border-gray-300 font-bold uppercase page-break-inside-avoid gap-x-6"+ )}+ >+ <Text style={tw("w-1/12 text-left")}>Seq</Text>+ <Text style={tw("w-8/12 text-left")}>Operation</Text>+ <Text style={tw("w-3/12 text-left")}>Expected Times</Text>+ </View>++ {jobOperations+ .sort((a, b) => a.order - b.order)+ .map((operation, index) => {+ const isInside = operation.operationType === "Inside";+ const setupQrCode =+ operation.setupTime > 0+ ? generateQRCode(`${getStartPath(operation.id)}?type=Setup`, 10)+ : null;+ let laborQrCode =+ operation.laborTime > 0+ ? generateQRCode(`${getStartPath(operation.id)}?type=Labor`, 10)+ : null;+ const machiningQrCode =+ operation.machineTime > 0+ ? generateQRCode(`${getStartPath(operation.id)}?type=Machine`, 10)+ : null;+ const completeQrCode = generateQRCode(getEndPath(operation.id), 10);++ if (+ setupQrCode === null &&+ laborQrCode === null &&+ machiningQrCode === null+ ) {+ laborQrCode = generateQRCode(+ `${getStartPath(operation.id)}?type=Labor`,+ 10+ );+ }++ const setupTimeFormatted = formatFactor(+ operation.setupTime,+ operation.setupUnit+ );+ const laborTimeFormatted = formatFactor(+ operation.laborTime,+ operation.laborUnit+ );+ const machineTimeFormatted = formatFactor(+ operation.machineTime,+ operation.machineUnit+ );+ const hasExpectedTimes =+ setupTimeFormatted || laborTimeFormatted || machineTimeFormatted;++ const workInstruction = operation.workInstruction as+ | JSONContent+ | undefined;+ const hasWorkInstruction =+ includeWorkInstructions &&+ workInstruction &&+ typeof workInstruction === "object" &&+ "content" in workInstruction &&+ Array.isArray(workInstruction.content) &&+ workInstruction.content.length > 0;+ const hasProcedureSteps =+ includeWorkInstructions &&+ operation.jobOperationStep &&+ operation.jobOperationStep.length > 0;++ return (+ <View+ style={tw(+ "flex flex-col border-b border-gray-300 py-4 px-[6px] page-break-inside-avoid"+ )}+ key={operation.id}+ wrap={includeWorkInstructions ? true : false}+ >+ <View style={tw("flex flex-col gap-y-4")} wrap={false}>+ <View+ style={tw(+ "flex flex-row justify-between items-start gap-x-6"+ )}+ wrap={false}+ >+ <Text style={tw("w-1/12 font-bold text-left")}>+ {getParallelizedOrder(index, operation, jobOperations)}+ </Text>+ <View style={tw("w-8/12 text-left text-[12px]")}>+ <Text style={tw("font-bold")}>{operation.description}</Text>+ </View>+ <View style={tw("w-3/12 text-left")}>+ {hasExpectedTimes && (+ <View style={tw("flex flex-col gap-1")}>+ {setupTimeFormatted && (+ <Text style={tw("text-[10px]")}>+ Setup: {setupTimeFormatted}+ </Text>+ )}+ {laborTimeFormatted && (+ <Text style={tw("text-[10px]")}>+ Labor: {laborTimeFormatted}+ </Text>+ )}+ {machineTimeFormatted && (+ <Text style={tw("text-[10px]")}>+ Machine: {machineTimeFormatted}+ </Text>+ )}+ </View>+ )}+ </View>+ </View>++ <View+ style={tw(+ "flex flex-row justify-between items-center py-3 px-[6px] border-gray-300 font-bold uppercase page-break-inside-avoid"+ )}+ >+ <Text style={tw("text-left pr-4")}>Actions</Text>+ </View>++ <View style={tw("w-full flex flex-row justify-start gap-2")}>+ {isInside && setupQrCode && (+ <View style={tw("flex flex-col items-center w-1/4")}>+ <>+ <Image src={setupQrCode} style={tw("w-16 h-16")} />+ <Text style={tw("text-[10px] mt-1")}>Setup</Text>+ </>+ </View>+ )}++ {isInside && laborQrCode && (+ <View style={tw("flex flex-col items-center w-1/4")}>+ <>+ <Image src={laborQrCode} style={tw("w-16 h-16")} />+ <Text style={tw("text-[10px] mt-1")}>Labor</Text>+ </>+ </View>+ )}+ {isInside && machiningQrCode && (+ <View style={tw("flex flex-col items-center w-1/4")}>+ <>+ <Image src={machiningQrCode} style={tw("w-16 h-16")} />+ <Text style={tw("text-[10px] mt-1")}>Machine</Text>+ </>+ </View>+ )}+ <View style={tw("flex flex-col items-center w-1/4")}>+ <Image src={completeQrCode} style={tw("w-16 h-16")} />+ <Text style={tw("text-[10px] mt-1")}>Complete</Text>+ </View>+ </View>+ </View>++ {(hasWorkInstruction || hasProcedureSteps) && (+ <View style={tw("mt-2 ml-8")}>+ {hasProcedureSteps && (+ <View style={tw("mb-2")}>+ <Text+ style={{+ marginBottom: 8,+ borderTopWidth: 1,+ borderTopColor: "#d1d5db",+ borderBottomWidth: 1,+ borderColor: "#d1d5db",+ paddingTop: 4,+ paddingBottom: 4,+ fontSize: 9,+ fontWeight: 700,+ textTransform: "uppercase"+ }}+ >+ Procedure Steps+ </Text>+ {operation+ .jobOperationStep!.sort(+ (a, b) => a.sortOrder - b.sortOrder+ )+ .map((step) => {+ const stepDescription = step.description as+ | JSONContent+ | undefined;+ const hasStepDescription =+ stepDescription &&+ typeof stepDescription === "object" &&+ "content" in stepDescription &&+ Array.isArray(stepDescription.content) &&+ stepDescription.content.length > 0;++ return (+ <View+ key={step.id}+ style={tw("flex flex-row items-start mb-1")}+ >+ <View+ style={{+ width: 9,+ height: 9,+ borderWidth: 1,+ borderColor: "#374151",+ marginRight: 6,+ marginTop: 1+ }}+ />+ <View style={tw("flex-1")}>+ <Text style={tw("text-[9px] font-bold")}>+ {step.name}+ </Text>+ {hasStepDescription && (+ <Note+ title="Procedure Step"+ content={stepDescription}+ />+ )}+ </View>+ </View>+ );+ })}+ </View>+ )}+ {hasWorkInstruction && (+ <Note title="Work Instructions" content={workInstruction} />+ )}+ </View>+ )}+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/jobTraveler/index.ts b/packages/documents/src/pdf/blocks/jobTraveler/index.tsnew file mode 100644index 0000000000..ee505120eb--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/index.ts@@ -0,0 +1,7 @@+export { jobTravelerBlockRegistry } from "./registry";+export type {+ BlockRenderer,+ JobOperationWithSteps,+ JobTravelerData+} from "./types";+export { buildJobTravelerVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/jobTraveler/registry.tsx b/packages/documents/src/pdf/blocks/jobTraveler/registry.tsxnew file mode 100644index 0000000000..ab78a021d3--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/registry.tsx@@ -0,0 +1,29 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import { extensionBlocks } from "../extensionRegistry";+import { HeaderBlock } from "./HeaderBlock";+import { JobDetailsBlock } from "./JobDetailsBlock";+import { NotesBlock } from "./NotesBlock";+import { OperationsBlock } from "./OperationsBlock";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for the Job Traveler. Extension blocks are shared. */+export const jobTravelerBlockRegistry: Partial<+ Record<DocumentBlockType, BlockRenderer>+> = {+ ...extensionBlocks,+ header: ({ data }) => <HeaderBlock data={data} />,+ jobDetails: ({ data }) => <JobDetailsBlock data={data} />,+ operations: ({ block, data }) =>+ block.type === "operations" ? (+ <OperationsBlock block={block} data={data} />+ ) : null,+ notes: ({ data }) => <NotesBlock data={data} />,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={(data.job?.customFields ?? {}) as Record<string, unknown>}+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/jobTraveler/tw.ts b/packages/documents/src/pdf/blocks/jobTraveler/tw.tsnew file mode 100644index 0000000000..1cba0137b8--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/tw.ts@@ -0,0 +1,20 @@+import { createTw } from "react-pdf-tailwind";++/**+ * Tailwind instance for Job Traveler blocks. Kept identical to the theme+ * previously inlined in JobTravelerPDF so block output is unchanged.+ */+export const tw = createTw({+ theme: {+ fontFamily: {+ sans: ["Helvetica", "Arial", "sans-serif"]+ },+ extend: {+ colors: {+ gray: {+ 500: "#7d7d7d"+ }+ }+ }+ }+});diff --git a/packages/documents/src/pdf/blocks/jobTraveler/types.ts b/packages/documents/src/pdf/blocks/jobTraveler/types.tsnew file mode 100644index 0000000000..9e502a44fe--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/types.ts@@ -0,0 +1,40 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions,+ ResolvedSection+} from "../../../template";+import type { Company } from "../../../types";++type JobOperationStep = Database["public"]["Tables"]["jobOperationStep"]["Row"];++export type JobOperationWithSteps =+ Database["public"]["Tables"]["jobOperation"]["Row"] & {+ jobOperationStep?: JobOperationStep[];+ };++/** Everything a Job Traveler block renderer might need. */+export interface JobTravelerData {+ company: Company;+ locale?: string;+ job: Database["public"]["Views"]["jobs"]["Row"];+ jobOperations: JobOperationWithSteps[];+ customer: Database["public"]["Tables"]["customer"]["Row"] | null;+ item: Database["public"]["Tables"]["item"]["Row"];+ batchNumber?: string;+ bomId?: string;+ notes?: JSONContent;+ thumbnail?: string | null;+ methodRevision?: string | null;+ theme: DocumentTheme;+ sections: Record<string, ResolvedSection>;+ vars: Record<string, string>;+ headerOptions: HeaderOptions;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: JobTravelerData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/jobTraveler/vars.ts b/packages/documents/src/pdf/blocks/jobTraveler/vars.tsnew file mode 100644index 0000000000..b2b0e03704--- /dev/null+++ b/packages/documents/src/pdf/blocks/jobTraveler/vars.ts@@ -0,0 +1,23 @@+import type { JobTravelerData } from "./types";++/** Merge-field variable map for a Job Traveler. */+export function buildJobTravelerVars(+ data: Pick<JobTravelerData, "job" | "item" | "customer" | "company">+): Record<string, string> {+ const { job, item, customer, company } = data;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "job.number": str(job?.jobId),+ "job.startDate": str(job?.startDate),+ "job.dueDate": str(job?.dueDate),+ "item.readableId": str(+ job?.itemReadableIdWithRevision ?? item?.readableIdWithRevision+ ),+ "item.name": str(item?.name),+ "customer.name": str(customer?.name),+ "company.name": str(company?.name),+ "company.city": str(company?.city),+ "company.country": str(company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/packingSlip/DetailsBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/DetailsBlock.tsxnew file mode 100644index 0000000000..ac88add234--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/DetailsBlock.tsx@@ -0,0 +1,31 @@+import { Text, View } from "@react-pdf/renderer";+import { tw } from "../tw";+import type { PackingSlipData } from "./types";++/** Shipping method + Payment terms box. */+export function DetailsBlock({ data }: { data: PackingSlipData }) {+ const { shippingMethod, paymentTerm } = data;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row")}>+ <View style={tw("w-1/2 p-3 border-r border-gray-200")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Shipping+ </Text>+ <View style={tw("text-[10px] text-gray-800")}>+ {shippingMethod?.name && <Text>Method: {shippingMethod.name}</Text>}+ </View>+ </View>+ <View style={tw("w-1/2 p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Payment+ </Text>+ <View style={tw("text-[10px] text-gray-800")}>+ {paymentTerm?.name && <Text>Terms: {paymentTerm.name}</Text>}+ </View>+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsxnew file mode 100644index 0000000000..e25deb5695--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/HeaderBlock.tsx@@ -0,0 +1,15 @@+import { Header } from "../../components";+import type { PackingSlipData } from "./types";++export function HeaderBlock({ data }: { data: PackingSlipData }) {+ return (+ <Header+ company={data.company}+ title="Packing Slip"+ documentId={data.shipment?.shipmentId}+ date={data.shipment?.postingDate}+ locale={data.locale}+ options={data.headerOptions}+ />+ );+}diff --git a/packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsxnew file mode 100644index 0000000000..97cfe07cd9--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/LineItemsBlock.tsx@@ -0,0 +1,138 @@+import bwipjs from "@bwip-js/node";+import type { Database } from "@carbon/database";+import type { TrackedEntityAttributes } from "@carbon/utils";+import { Image, Text, View } from "@react-pdf/renderer";+import { generateQRCode } from "../../../qr/qr-code";+import {+ DEFAULT_LINE_ITEMS_OPTIONS,+ type LineItemsBlock as LineItemsBlockType+} from "../../../template";+import { itemTextOverflowStyle } from "../itemText";+import { tw } from "../tw";+import type { PackingSlipData } from "./types";++type ShipmentLine = Database["public"]["Views"]["shipmentLines"]["Row"];++async function generateBarcode(text: string): Promise<string> {+ const buffer = await bwipjs.toBuffer({+ bcid: "code128",+ text,+ scale: 3,+ height: 5,+ includetext: true,+ textxalign: "center"+ });+ return `data:image/png;base64,${buffer.toString("base64")}`;+}++export function LineItemsBlock({+ block,+ data+}: {+ block: LineItemsBlockType;+ data: PackingSlipData;+}) {+ const { shipmentLines, trackedEntities, thumbnails } = data;+ const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };+ const overflow = itemTextOverflowStyle(opts);+ const hasTrackedEntities = trackedEntities.length > 0;+ let rowIndex = 0;++ return (+ <View style={tw("mb-4")}>+ <View+ style={tw(+ "flex flex-row bg-gray-800 py-2 px-3 text-white text-[9px] font-bold"+ )}+ >+ <Text style={tw(`w-${hasTrackedEntities ? "5/12" : "7/12"} text-left`)}>+ Description+ </Text>+ <Text style={tw("w-2/12 text-right")}>Qty</Text>+ {hasTrackedEntities && (+ <Text style={tw("w-5/12 text-right")}>Serial/Batch</Text>+ )}+ </View>++ {shipmentLines+ .filter((line) => (line?.shippedQuantity ?? 0) > 0)+ .map((line: ShipmentLine) => {+ const barcodeDataUrl = generateBarcode(line?.itemReadableId || "");+ const trackedEntitiesForLine = trackedEntities.filter(+ (entity) =>+ (entity.attributes as TrackedEntityAttributes)?.[+ "Shipment Line"+ ] === line.id+ );+ const isEven = rowIndex % 2 === 0;+ rowIndex++;+ const rowBg = !opts.zebra || isEven ? "bg-white" : "bg-gray-50";++ return (+ <View+ key={line.id}+ style={tw(+ `flex flex-row py-2 px-3 border-b border-gray-200 text-[10px] ${rowBg}`+ )}+ wrap={false}+ >+ <View+ style={tw(`w-${hasTrackedEntities ? "5/12" : "7/12"} pr-2`)}+ >+ <Text style={{ ...tw("text-gray-800"), ...overflow }}>+ {line.itemReadableId}+ </Text>+ <Text+ style={{+ ...tw("text-[8px] text-gray-400 mt-0.5"),+ ...overflow+ }}+ >+ {line.description}+ </Text>+ {opts.showThumbnails &&+ thumbnails &&+ line.id != null &&+ line.id in thumbnails &&+ thumbnails[line.id] && (+ <View style={tw("mt-1 w-16")}>+ <Image+ src={thumbnails[line.id]!}+ style={tw("w-full h-auto")}+ />+ </View>+ )}+ <View style={tw("mt-1")}>+ <Image src={barcodeDataUrl} style={tw("max-w-[50%]")} />+ </View>+ </View>+ <Text style={tw("w-2/12 text-right text-gray-600")}>+ {`${line.shippedQuantity} / ${line.orderQuantity} ${line.unitOfMeasure}`}+ </Text>+ {hasTrackedEntities && (+ <View style={tw("w-5/12 flex flex-col gap-1 items-end")}>+ {trackedEntitiesForLine.map((entity) => {+ const qrCodeDataUrl = generateQRCode(entity.id, 8);+ return (+ <View+ key={entity.id}+ style={tw("mb-1 flex flex-row items-center gap-1")}+ >+ <Text style={tw("text-[8px] text-gray-600")}>+ {entity.id}+ </Text>+ <Image+ src={qrCodeDataUrl}+ style={{ width: 24, height: 24 }}+ />+ </View>+ );+ })}+ </View>+ )}+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/packingSlip/NotesBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/NotesBlock.tsxnew file mode 100644index 0000000000..d7bee651cb--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/NotesBlock.tsx@@ -0,0 +1,16 @@+import type { JSONContent } from "@carbon/react";+import { View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "../tw";+import type { PackingSlipData } from "./types";++export function NotesBlock({ data }: { data: PackingSlipData }) {+ const notes = (data.shipment?.externalNotes ?? {}) as JSONContent;+ if (Object.keys(notes).length === 0) return null;++ return (+ <View style={tw("mb-3 w-full")}>+ <Note title="Notes" content={notes} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/packingSlip/PartiesBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/PartiesBlock.tsxnew file mode 100644index 0000000000..7aaa7858a7--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/PartiesBlock.tsx@@ -0,0 +1,74 @@+import { formatDate } from "@carbon/utils";+import { Text, View } from "@react-pdf/renderer";+import { tw } from "../tw";+import type { PackingSlipData } from "./types";++/** Ship-To address + Shipment details (date, source doc, customer PO, tracking). */+export function PartiesBlock({ data }: { data: PackingSlipData }) {+ const {+ customer,+ shippingAddress,+ shipment,+ sourceDocument,+ sourceDocumentId,+ customerReference,+ locale+ } = data;+ const {+ addressLine1,+ addressLine2,+ city,+ stateProvince,+ postalCode,+ countryCode+ } = shippingAddress ?? {};++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row")}>+ <View style={tw("w-1/2 p-3 border-r border-gray-200")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Ship To+ </Text>+ <View style={tw("text-[10px] text-gray-800")}>+ {customer.name && (+ <Text style={tw("font-bold")}>{customer.name}</Text>+ )}+ {addressLine1 && <Text style={tw("mt-1")}>{addressLine1}</Text>}+ {addressLine2 && <Text>{addressLine2}</Text>}+ {city && <Text>{city}</Text>}+ {(stateProvince || postalCode) && (+ <Text>+ {[stateProvince, postalCode].filter(Boolean).join(" ")}+ </Text>+ )}+ {countryCode && <Text>{countryCode}</Text>}+ </View>+ </View>+ <View style={tw("w-1/2 p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Shipment Details+ </Text>+ <View style={tw("text-[10px] text-gray-800")}>+ {shipment?.postingDate && (+ <Text>+ Date: {formatDate(shipment.postingDate, undefined, locale)}+ </Text>+ )}+ {sourceDocument && sourceDocumentId && (+ <Text>+ {sourceDocument}: {sourceDocumentId}+ </Text>+ )}+ {customerReference && (+ <Text>Customer PO #: {customerReference}</Text>+ )}+ {shipment?.trackingNumber && (+ <Text>Tracking: {shipment.trackingNumber}</Text>+ )}+ </View>+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/packingSlip/TermsBlock.tsx b/packages/documents/src/pdf/blocks/packingSlip/TermsBlock.tsxnew file mode 100644index 0000000000..97c6ca8051--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/TermsBlock.tsx@@ -0,0 +1,23 @@+import { View } from "@react-pdf/renderer";+import type { TermsBlock as TermsBlockType } from "../../../template";+import { Note } from "../../components";+import { hasContent, resolveTerms } from "../resolveTerms";+import { tw } from "../tw";+import type { PackingSlipData } from "./types";++export function TermsBlock({+ block,+ data+}: {+ block: TermsBlockType;+ data: PackingSlipData;+}) {+ const terms = resolveTerms(block, data.terms, data.vars);+ if (!hasContent(terms)) return null;++ return (+ <View style={tw("w-full")}>+ <Note title="Standard Terms & Conditions" content={terms!} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/packingSlip/index.ts b/packages/documents/src/pdf/blocks/packingSlip/index.tsnew file mode 100644index 0000000000..c90107ba35--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/index.ts@@ -0,0 +1,3 @@+export { packingSlipBlockRegistry } from "./registry";+export type { BlockRenderer, PackingSlipData } from "./types";+export { buildPackingSlipVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/packingSlip/registry.tsx b/packages/documents/src/pdf/blocks/packingSlip/registry.tsxnew file mode 100644index 0000000000..81b6e057b0--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/registry.tsx@@ -0,0 +1,36 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import { extensionBlocks } from "../extensionRegistry";+import { DetailsBlock } from "./DetailsBlock";+import { HeaderBlock } from "./HeaderBlock";+import { LineItemsBlock } from "./LineItemsBlock";+import { NotesBlock } from "./NotesBlock";+import { PartiesBlock } from "./PartiesBlock";+import { TermsBlock } from "./TermsBlock";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for Packing Slip (fulfillment; no summary/pricing). */+export const packingSlipBlockRegistry: Partial<+ Record<DocumentBlockType, BlockRenderer>+> = {+ ...extensionBlocks,+ header: ({ data }) => <HeaderBlock data={data} />,+ parties: ({ data }) => <PartiesBlock data={data} />,+ notes: ({ data }) => <NotesBlock data={data} />,+ details: ({ data }) => <DetailsBlock data={data} />,+ lineItems: ({ block, data }) =>+ block.type === "lineItems" ? (+ <LineItemsBlock block={block} data={data} />+ ) : null,+ terms: ({ block, data }) =>+ block.type === "terms" ? <TermsBlock block={block} data={data} /> : null,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={+ (data.shipment?.customFields ?? {}) as Record<string, unknown>+ }+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/packingSlip/types.ts b/packages/documents/src/pdf/blocks/packingSlip/types.tsnew file mode 100644index 0000000000..fe828ae665--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/types.ts@@ -0,0 +1,38 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions,+ ResolvedSection+} from "../../../template";+import type { Company } from "../../../types";++/** Everything a Packing Slip block renderer might need. */+export interface PackingSlipData {+ company: Company;+ locale: string;+ customer:+ | Database["public"]["Tables"]["customer"]["Row"]+ | Database["public"]["Tables"]["supplier"]["Row"];+ customerReference?: string;+ sourceDocument?: string;+ sourceDocumentId?: string;+ shipment: Database["public"]["Tables"]["shipment"]["Row"];+ shipmentLines: Database["public"]["Views"]["shipmentLines"]["Row"][];+ shippingAddress: Database["public"]["Tables"]["address"]["Row"] | null;+ paymentTerm: { id: string; name: string };+ shippingMethod: { id: string; name: string };+ terms: JSONContent;+ trackedEntities: Database["public"]["Tables"]["trackedEntity"]["Row"][];+ thumbnails?: Record<string, string | null>;+ theme: DocumentTheme;+ sections: Record<string, ResolvedSection>;+ vars: Record<string, string>;+ headerOptions: HeaderOptions;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: PackingSlipData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/packingSlip/vars.ts b/packages/documents/src/pdf/blocks/packingSlip/vars.tsnew file mode 100644index 0000000000..0678dea147--- /dev/null+++ b/packages/documents/src/pdf/blocks/packingSlip/vars.ts@@ -0,0 +1,25 @@+import type { PackingSlipData } from "./types";++/** Merge-field variable map for a Packing Slip. */+export function buildPackingSlipVars(+ data: Pick<+ PackingSlipData,+ "shipment" | "customer" | "shippingAddress" | "company"+ >+): Record<string, string> {+ const s = data.shipment;+ const a = data.shippingAddress;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "shipment.number": str(s?.shipmentId),+ "shipment.trackingNumber": str(s?.trackingNumber),+ "customer.name": str(data.customer?.name),+ "customer.addressLine1": str(a?.addressLine1),+ "customer.city": str(a?.city),+ "customer.country": str(a?.countryCode),+ "company.name": str(data.company?.name),+ "company.city": str(data.company?.city),+ "company.country": str(data.company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/HeaderBlock.tsxnew file mode 100644index 0000000000..0760dca672--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/HeaderBlock.tsx@@ -0,0 +1,15 @@+import { Header } from "../../components";+import type { PurchaseOrderData } from "./types";++export function HeaderBlock({ data }: { data: PurchaseOrderData }) {+ return (+ <Header+ company={data.company}+ title="Purchase Order"+ documentId={data.purchaseOrder?.purchaseOrderId}+ locale={data.locale}+ options={data.headerOptions}+ fixed+ />+ );+}diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/LineItemsBlock.tsxnew file mode 100644index 0000000000..c22230c96a--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/LineItemsBlock.tsx@@ -0,0 +1,197 @@+import type { JSONContent } from "@carbon/react";+import { formatDate } from "@carbon/utils";+import { Image, Text, View } from "@react-pdf/renderer";+import {+ DEFAULT_LINE_ITEMS_OPTIONS,+ type LineItemsBlock as LineItemsBlockType+} from "../../../template";+import {+ getLineDescription,+ getLineDescriptionDetails,+ getLineTotal+} from "../../../utils/purchase-order";+import { formatTaxPercent } from "../../../utils/shared";+import { Note } from "../../components";+import { itemTextOverflowStyle } from "../itemText";+import { tw } from "../tw";+import type { PurchaseOrderData } from "./types";++const INDIRECT_TYPES = new Set([+ "Service",+ "G/L Account",+ "Fixed Asset",+ "Comment"+]);+const isIndirect = (t: string | null | undefined) =>+ !!t && INDIRECT_TYPES.has(t);++export function LineItemsBlock({+ block,+ data+}: {+ block: LineItemsBlockType;+ data: PurchaseOrderData;+}) {+ const {+ purchaseOrder,+ purchaseOrderLines,+ thumbnails,+ numberFormatter,+ theme,+ locale+ } = data;+ const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };+ const overflow = itemTextOverflowStyle(opts);+ let rowIndex = 0;++ return (+ <View>+ <View+ fixed+ style={[+ tw("flex flex-row py-3 px-3 text-[9px] font-bold items-center"),+ { backgroundColor: theme.accent, color: theme.accentForeground }+ ]}+ >+ <Text style={tw("w-[4%] text-center")}>#</Text>+ <Text style={tw("w-[22%]")}>Description</Text>+ <Text style={tw("w-[8%] text-center")}>Qty</Text>+ <Text style={tw("w-[7%] text-center")}>UOM</Text>+ <View style={tw("w-[10%] items-center")}>+ <Text>Required</Text>+ </View>+ <Text style={tw("w-[12%] text-center")}>Unit Price</Text>+ <Text style={tw("w-[12%] text-center")}>Net Value</Text>+ <Text style={tw("w-[12%] text-center")}>Tax Value</Text>+ <Text style={tw("w-[13%] text-center")}>Total</Text>+ </View>++ {purchaseOrderLines.map((line) => {+ const isEven = rowIndex % 2 === 0;+ rowIndex++;++ const netValue =+ (line.purchaseQuantity ?? 0) * (line.supplierUnitPrice ?? 0);++ return (+ <View key={line.id}>+ <View+ wrap={false}+ style={[+ tw(+ "flex flex-col py-2 px-3 border-b border-gray-200 text-[9px]"+ ),+ {+ backgroundColor:+ opts.zebra && !isEven+ ? "rgba(249, 250, 251, 0.6)"+ : "transparent"+ }+ ]}+ >+ <View style={tw("flex flex-row")}>+ <Text style={tw("w-[4%] text-center text-gray-400")}>+ {line.purchaseOrderLineType === "Comment" ? "" : rowIndex}+ </Text>+ <View style={tw("w-[22%] pr-2")}>+ {isIndirect(line.purchaseOrderLineType) ? (+ <Text style={{ ...tw("text-gray-900"), ...overflow }}>+ {line.description ?? ""}+ </Text>+ ) : (+ <>+ <Text style={{ ...tw("text-gray-900"), ...overflow }}>+ {getLineDescription(line)}+ </Text>+ <Text+ style={{+ ...tw("text-[7px] text-gray-600 mt-0.5"),+ ...overflow+ }}+ >+ {getLineDescriptionDetails(line)}+ </Text>+ </>+ )}+ {purchaseOrder.purchaseOrderType === "Outside Processing" &&+ line.jobOperationDescription && (+ <Text style={tw("text-[7px] text-gray-600 mt-0.5")}>+ {line.jobOperationDescription}+ </Text>+ )}+ {opts.showThumbnails &&+ thumbnails &&+ line.id &&+ line.id in thumbnails &&+ thumbnails[line.id] && (+ <View style={tw("mt-1 w-16")}>+ <Image+ src={thumbnails[line.id]!}+ style={tw("w-full h-auto")}+ />+ </View>+ )}+ </View>+ <Text style={tw("w-[8%] text-center text-gray-600")}>+ {line.purchaseOrderLineType === "Comment"+ ? ""+ : line.purchaseQuantity}+ </Text>+ <Text style={tw("w-[7%] text-center text-gray-600")}>+ {line.purchaseOrderLineType === "Comment"+ ? ""+ : line.purchaseUnitOfMeasureCode}+ </Text>+ <Text style={tw("w-[10%] text-center text-gray-600")}>+ {line.purchaseOrderLineType === "Comment" ||+ !line.requiredDate+ ? ""+ : formatDate(line.requiredDate, undefined, locale)}+ </Text>+ <Text style={tw("w-[12%] text-center text-gray-600")}>+ {line.purchaseOrderLineType === "Comment"+ ? ""+ : numberFormatter.format(line.supplierUnitPrice ?? 0)}+ </Text>+ <Text style={tw("w-[12%] text-center text-gray-600")}>+ {line.purchaseOrderLineType === "Comment"+ ? ""+ : numberFormatter.format(netValue)}+ </Text>+ <View style={tw("w-[12%]")}>+ {line.purchaseOrderLineType !== "Comment" && (+ <View style={tw("flex flex-col items-center")}>+ <Text style={tw("text-gray-600")}>+ {numberFormatter.format(line.supplierTaxAmount ?? 0)}+ </Text>+ {formatTaxPercent(line.taxPercent) && (+ <Text style={tw("text-[6px] text-gray-400")}>+ {formatTaxPercent(line.taxPercent)}+ </Text>+ )}+ </View>+ )}+ </View>+ <Text+ style={tw("w-[13%] text-center text-gray-800 font-medium")}+ >+ {line.purchaseOrderLineType === "Comment"+ ? ""+ : numberFormatter.format(getLineTotal(line))}+ </Text>+ </View>+ </View>+ {Object.keys(line.externalNotes ?? {}).length > 0 && (+ <View style={tw("px-3 py-2 border-b border-gray-200")}>+ <Note+ key={`${line.id}-notes`}+ content={line.externalNotes as JSONContent}+ />+ </View>+ )}+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/NotesBlock.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/NotesBlock.tsxnew file mode 100644index 0000000000..85991713c2--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/NotesBlock.tsx@@ -0,0 +1,27 @@+import type { JSONContent } from "@carbon/react";+import { Text, View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "../tw";+import type { PurchaseOrderData } from "./types";++export function NotesBlock({ data }: { data: PurchaseOrderData }) {+ const notes = (data.purchaseOrder?.externalNotes ?? {}) as JSONContent;+ const hasNotes = Object.keys(notes).length > 0;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Notes+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ {hasNotes ? (+ <Note content={notes} />+ ) : (+ <Text style={tw("text-gray-400")}>None</Text>+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/PartiesBlock.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/PartiesBlock.tsxnew file mode 100644index 0000000000..d2c47005d8--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/PartiesBlock.tsx@@ -0,0 +1,208 @@+import { formatDate, isEoriCountry } from "@carbon/utils";+import { Text, View } from "@react-pdf/renderer";+import { AddressBlock } from "../../components";+import { tw } from "../tw";+import type { PurchaseOrderData } from "./types";++export function PartiesBlock({ data }: { data: PurchaseOrderData }) {+ const {+ purchaseOrder,+ purchaseOrderLocations,+ paymentTerms,+ company,+ accountsPayableBillingAddress,+ currencyCode,+ locale+ } = data;+ const {+ supplierName,+ supplierAddressLine1,+ supplierAddressLine2,+ supplierCity,+ supplierStateProvince,+ supplierPostalCode,+ supplierCountryCode,+ supplierCountryName,+ deliveryName,+ deliveryAddressLine1,+ deliveryAddressLine2,+ deliveryCity,+ deliveryStateProvince,+ deliveryPostalCode,+ deliveryCountryCode,+ deliveryCountryName,+ dropShipment,+ customerName,+ customerAddressLine1,+ customerAddressLine2,+ customerCity,+ customerStateProvince,+ customerPostalCode,+ customerCountryCode,+ customerCountryName+ } = purchaseOrderLocations;++ const paymentTerm = paymentTerms?.find(+ (term) => term.id === purchaseOrder?.paymentTermId+ );++ const shipAddress = dropShipment+ ? {+ name: customerName,+ addressLine1: customerAddressLine1,+ addressLine2: customerAddressLine2,+ city: customerCity,+ stateProvince: customerStateProvince,+ postalCode: customerPostalCode,+ country: customerCountryName ?? customerCountryCode+ }+ : {+ name: deliveryName,+ addressLine1: deliveryAddressLine1,+ addressLine2: deliveryAddressLine2,+ city: deliveryCity,+ stateProvince: deliveryStateProvince,+ postalCode: deliveryPostalCode,+ country: deliveryCountryName ?? deliveryCountryCode+ };++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row")}>+ {/* LEFT — Supplier */}+ <View style={tw("w-1/2 p-3 border-r border-gray-200")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Supplier+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <AddressBlock+ name={supplierName}+ addressLine1={supplierAddressLine1}+ addressLine2={supplierAddressLine2}+ city={supplierCity}+ stateProvince={supplierStateProvince}+ postalCode={supplierPostalCode}+ country={supplierCountryName ?? supplierCountryCode}+ />+ {purchaseOrderLocations.supplierTaxId &&+ !isEoriCountry(supplierCountryCode) && (+ <Text>Tax ID: {purchaseOrderLocations.supplierTaxId}</Text>+ )}+ {purchaseOrderLocations.supplierVatNumber && (+ <Text>VAT: {purchaseOrderLocations.supplierVatNumber}</Text>+ )}+ {purchaseOrderLocations.supplierEori && (+ <Text>EORI: {purchaseOrderLocations.supplierEori}</Text>+ )}+ {purchaseOrderLocations.supplierContactName && (+ <Text>Contact: {purchaseOrderLocations.supplierContactName}</Text>+ )}+ {purchaseOrderLocations.supplierContactEmail && (+ <Text>Email: {purchaseOrderLocations.supplierContactEmail}</Text>+ )}+ </View>+ </View>++ {/* RIGHT — Order Info + Deliver To */}+ <View style={tw("w-1/2 flex flex-col")}>+ <View style={tw("p-3 border-b border-gray-200")}>+ <Text+ style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}+ >+ Order Info+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ {purchaseOrder?.purchaseOrderId && (+ <Text>PO Number: {purchaseOrder.purchaseOrderId}</Text>+ )}+ {purchaseOrder?.orderDate && (+ <Text>+ Date: {formatDate(purchaseOrder.orderDate, undefined, locale)}+ </Text>+ )}+ <Text>Currency: {currencyCode}</Text>+ {purchaseOrder?.supplierReference && (+ <Text>Reference: {purchaseOrder.supplierReference}</Text>+ )}+ {purchaseOrder?.receiptRequestedDate && (+ <Text>+ Requested:{" "}+ {formatDate(+ purchaseOrder.receiptRequestedDate,+ undefined,+ locale+ )}+ </Text>+ )}+ {purchaseOrder?.receiptPromisedDate && (+ <Text>+ Promised:{" "}+ {formatDate(+ purchaseOrder.receiptPromisedDate,+ undefined,+ locale+ )}+ </Text>+ )}+ {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}+ {purchaseOrder?.incoterm && (+ <Text>+ Incoterm: {purchaseOrder.incoterm}+ {purchaseOrder.incotermLocation+ ? ` — ${purchaseOrder.incotermLocation}`+ : ""}+ </Text>+ )}+ </View>+ <View style={tw("h-[1px] bg-gray-200 my-2")} />+ <View style={tw("text-[9px] text-gray-800")}>+ {company.vatNumber && <Text>VAT: {company.vatNumber}</Text>}+ {(() => {+ const name =+ purchaseOrder.assigneeFullName ??+ purchaseOrder.accountManagerFullName ??+ purchaseOrder.createdByFullName;+ const email =+ purchaseOrder.assigneeEmail ??+ purchaseOrder.accountManagerEmail ??+ purchaseOrder.createdByEmail;+ const phone =+ purchaseOrder.assigneePhone ??+ purchaseOrder.accountManagerPhone ??+ purchaseOrder.createdByPhone;+ return (+ <>+ {name && <Text>Contact: {name}</Text>}+ {email && <Text>Email: {email}</Text>}+ {phone && <Text>Phone: {phone}</Text>}+ </>+ );+ })()}+ {accountsPayableBillingAddress?.email && (+ <>+ <Text style={tw("font-bold mt-1")}>+ Billing documents and enquiries:+ </Text>+ <Text style={tw("font-bold")}>+ {accountsPayableBillingAddress.email}+ </Text>+ </>+ )}+ </View>+ </View>++ <View style={tw("p-3")}>+ <Text+ style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}+ >+ Deliver To+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <AddressBlock {...shipAddress} />+ </View>+ </View>+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/SummaryBlock.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/SummaryBlock.tsxnew file mode 100644index 0000000000..80949a30dc--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/SummaryBlock.tsx@@ -0,0 +1,90 @@+import { Text, View } from "@react-pdf/renderer";+import type { SummaryBlock as SummaryBlockType } from "../../../template";+import { getTotal } from "../../../utils/purchase-order";+import { tw } from "../tw";+import type { PurchaseOrderData } from "./types";++export function SummaryBlock({+ block,+ data+}: {+ block: SummaryBlockType;+ data: PurchaseOrderData;+}) {+ const { purchaseOrderLines, purchaseOrder, currencyCode, numberFormatter } =+ data;+ const taxLabel = block.options?.taxLabel?.trim() || "Tax";++ const shippingCost = purchaseOrder?.supplierShippingCost ?? 0;+ const taxAmount = purchaseOrderLines.reduce(+ (acc, line) => acc + (line.supplierTaxAmount ?? 0),+ 0+ );++ return (+ <View style={tw("mb-4")}>+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-[87%] text-right pr-3 text-gray-600")}>+ Subtotal ({currencyCode})+ </Text>+ <Text style={tw("w-[13%] text-center text-gray-800")}>+ {numberFormatter.format(+ purchaseOrderLines.reduce((sum, line) => {+ if (line?.purchaseQuantity && line?.supplierUnitPrice) {+ return sum + line.purchaseQuantity * line.supplierUnitPrice;+ }+ return sum;+ }, 0)+ )}+ </Text>+ </View>++ {shippingCost > 0 && (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-[87%] text-right pr-3 text-gray-600")}>+ Shipping ({currencyCode})+ </Text>+ <Text style={tw("w-[13%] text-center text-gray-800")}>+ {numberFormatter.format(shippingCost)}+ </Text>+ </View>+ )}++ {taxAmount > 0 && (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-[87%] text-right pr-3 text-gray-600")}>+ {taxLabel} ({currencyCode})+ </Text>+ <Text style={tw("w-[13%] text-center text-gray-800")}>+ {numberFormatter.format(taxAmount)}+ </Text>+ </View>+ )}++ <View style={tw("h-[1px] bg-gray-200")} />+ <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>+ <Text style={tw("w-[87%] text-right pr-3 text-gray-800 font-bold")}>+ Total ({currencyCode})+ </Text>+ <Text style={tw("w-[13%] text-center text-gray-800 font-bold")}>+ {numberFormatter.format(getTotal(purchaseOrderLines) + shippingCost)}+ </Text>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/TermsBlock.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/TermsBlock.tsxnew file mode 100644index 0000000000..7d7f51463f--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/TermsBlock.tsx@@ -0,0 +1,34 @@+import { Text, View } from "@react-pdf/renderer";+import type { TermsBlock as TermsBlockType } from "../../../template";+import { Note } from "../../components";+import { hasContent, resolveTerms } from "../resolveTerms";+import { tw } from "../tw";+import type { PurchaseOrderData } from "./types";++export function TermsBlock({+ block,+ data+}: {+ block: TermsBlockType;+ data: PurchaseOrderData;+}) {+ const { theme, vars } = data;+ const terms = resolveTerms(block, data.terms, vars);+ if (!hasContent(terms)) return null;++ return (+ <View break>+ <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>+ <Text+ style={[+ tw("text-[14px] font-bold uppercase tracking-wide"),+ { color: theme.accent }+ ]}+ >+ Terms & Conditions+ </Text>+ </View>+ <Note content={terms!} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/index.ts b/packages/documents/src/pdf/blocks/purchaseOrder/index.tsnew file mode 100644index 0000000000..9d2bdebe79--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/index.ts@@ -0,0 +1,3 @@+export { purchaseOrderBlockRegistry } from "./registry";+export type { BlockRenderer, PurchaseOrderData } from "./types";+export { buildPurchaseOrderVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/registry.tsx b/packages/documents/src/pdf/blocks/purchaseOrder/registry.tsxnew file mode 100644index 0000000000..fd35489cd9--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/registry.tsx@@ -0,0 +1,39 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import { extensionBlocks } from "../extensionRegistry";+import { HeaderBlock } from "./HeaderBlock";+import { LineItemsBlock } from "./LineItemsBlock";+import { NotesBlock } from "./NotesBlock";+import { PartiesBlock } from "./PartiesBlock";+import { SummaryBlock } from "./SummaryBlock";+import { TermsBlock } from "./TermsBlock";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for Purchase Order. Extension blocks are shared. */+export const purchaseOrderBlockRegistry: Partial<+ Record<DocumentBlockType, BlockRenderer>+> = {+ ...extensionBlocks,+ header: ({ data }) => <HeaderBlock data={data} />,+ parties: ({ data }) => <PartiesBlock data={data} />,+ notes: ({ data }) => <NotesBlock data={data} />,+ lineItems: ({ block, data }) =>+ block.type === "lineItems" ? (+ <LineItemsBlock block={block} data={data} />+ ) : null,+ summary: ({ block, data }) =>+ block.type === "summary" ? (+ <SummaryBlock block={block} data={data} />+ ) : null,+ terms: ({ block, data }) =>+ block.type === "terms" ? <TermsBlock block={block} data={data} /> : null,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={+ (data.purchaseOrder?.customFields ?? {}) as Record<string, unknown>+ }+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/types.ts b/packages/documents/src/pdf/blocks/purchaseOrder/types.tsnew file mode 100644index 0000000000..102766a781--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/types.ts@@ -0,0 +1,38 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions,+ ResolvedSection+} from "../../../template";+import type {+ AccountsPayableBillingAddress,+ Company,+ CompanySettings+} from "../../../types";++/** Everything a Purchase Order block renderer might need. */+export interface PurchaseOrderData {+ company: Company;+ companySettings?: CompanySettings | null;+ locale: string;+ purchaseOrder: Database["public"]["Views"]["purchaseOrders"]["Row"];+ purchaseOrderLines: Database["public"]["Views"]["purchaseOrderLines"]["Row"][];+ purchaseOrderLocations: Database["public"]["Views"]["purchaseOrderLocations"]["Row"];+ accountsPayableBillingAddress?: AccountsPayableBillingAddress | null;+ paymentTerms: { id: string; name: string }[];+ terms: JSONContent;+ thumbnails?: Record<string, string | null>;+ theme: DocumentTheme;+ sections: Record<string, ResolvedSection>;+ currencyCode: string | null;+ numberFormatter: Intl.NumberFormat;+ vars: Record<string, string>;+ headerOptions: HeaderOptions;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: PurchaseOrderData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/purchaseOrder/vars.ts b/packages/documents/src/pdf/blocks/purchaseOrder/vars.tsnew file mode 100644index 0000000000..99d64cae56--- /dev/null+++ b/packages/documents/src/pdf/blocks/purchaseOrder/vars.ts@@ -0,0 +1,27 @@+import type { PurchaseOrderData } from "./types";++/** Merge-field variable map for a Purchase Order. */+export function buildPurchaseOrderVars(+ data: Pick<+ PurchaseOrderData,+ "purchaseOrder" | "purchaseOrderLocations" | "company" | "currencyCode"+ >+): Record<string, string> {+ const po = data.purchaseOrder;+ const loc = data.purchaseOrderLocations;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "order.number": str(po?.purchaseOrderId),+ "order.date": str(po?.orderDate),+ "order.supplierReference": str(po?.supplierReference),+ "order.currency": str(data.currencyCode),+ "supplier.name": str(loc?.supplierName),+ "supplier.addressLine1": str(loc?.supplierAddressLine1),+ "supplier.city": str(loc?.supplierCity),+ "supplier.country": str(loc?.supplierCountryName),+ "company.name": str(data.company?.name),+ "company.city": str(data.company?.city),+ "company.country": str(data.company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/quote/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/quote/HeaderBlock.tsxnew file mode 100644index 0000000000..13b90bd0aa--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/HeaderBlock.tsx@@ -0,0 +1,15 @@+import { Header } from "../../components";+import type { QuoteData } from "./types";++export function HeaderBlock({ data }: { data: QuoteData }) {+ return (+ <Header+ company={data.company}+ title="Quote"+ documentId={data.quote?.quoteId}+ currencyCode={data.quote?.currencyCode}+ locale={data.locale}+ options={data.headerOptions}+ />+ );+}diff --git a/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsxnew file mode 100644index 0000000000..537ac16ffa--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/LineItemsBlock.tsx@@ -0,0 +1,312 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import { pluralize } from "@carbon/utils";+import { Image, Text, View } from "@react-pdf/renderer";+import {+ DEFAULT_LINE_ITEMS_OPTIONS,+ type LineItemsBlock as LineItemsBlockType+} from "../../../template";+import {+ getLineDescription,+ getLineDescriptionDetails+} from "../../../utils/quote";+import { Note } from "../../components";+import { itemTextOverflowStyle } from "../itemText";+import { tw } from "../tw";+import type { QuoteData } from "./types";++type QuoteLinePrice = Database["public"]["Tables"]["quoteLinePrice"]["Row"];++export function LineItemsBlock({+ block,+ data+}: {+ block: LineItemsBlockType;+ data: QuoteData;+}) {+ const {+ quoteLines,+ pricesByLine,+ hasSinglePricePerLine,+ hasAnyLeadTime,+ colWidth,+ shouldConvertCurrency,+ exchangeRate,+ numberFormatter,+ thumbnails,+ theme,+ locale+ } = data;+ const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };+ const overflow = itemTextOverflowStyle(opts);+ let rowIndex = 0;++ return (+ <View>+ {/* Header */}+ <View+ fixed+ style={[+ tw("flex flex-row py-2 px-3 text-[9px] font-bold items-center"),+ { backgroundColor: theme.accent, color: theme.accentForeground }+ ]}+ >+ <View style={tw("w-1/3")}>+ <Text>Description</Text>+ </View>+ <View style={tw("w-2/3 flex flex-row items-center")}>+ <Text style={tw(`${colWidth} text-center pr-3`)}>Qty</Text>+ <Text style={tw(`${colWidth} text-center pr-3`)}>Unit Price</Text>+ {!hasSinglePricePerLine && (+ <Text style={tw(`${colWidth} text-center pr-3`)}>Tax & Fees</Text>+ )}+ {hasAnyLeadTime && (+ <Text style={tw(`${colWidth} text-center pr-3`)}>Lead Time</Text>+ )}+ <Text style={tw(`${colWidth} text-center`)}>Total</Text>+ </View>+ </View>++ {quoteLines.map((line) => {+ const unitPriceNumberFormatter = new Intl.NumberFormat(locale, {+ style: "decimal",+ minimumFractionDigits: line.unitPricePrecision ?? 2,+ maximumFractionDigits: line.unitPricePrecision ?? 2+ });++ const additionalCharges = line.additionalCharges ?? {};++ return (+ <View key={line.id}>+ {line.status !== "No Quote" ? (+ <>+ {(line.quantity ?? []).map((quantity, index) => {+ const prices =+ line.id != null ? (pricesByLine[line.id] ?? []) : [];+ const price = prices.find(+ (p: QuoteLinePrice) => p.quantity === quantity+ );+ const unitPrice = price?.convertedUnitPrice ?? 0;+ const netExtendedPrice =+ price?.convertedNetExtendedPrice ?? 0;+ const isEven = rowIndex % 2 === 0;+ rowIndex++;++ const leadTime = price?.leadTime ?? 0;++ const additionalCharge = Object.values(+ additionalCharges+ ).reduce((acc, charge) => {+ let amount = charge.amounts?.[quantity] ?? 0;+ if (shouldConvertCurrency) amount *= exchangeRate;+ return acc + amount;+ }, 0);+ const taxableAdditionalCharge = Object.values(+ additionalCharges+ ).reduce((acc, charge) => {+ if (charge.taxable === false) return acc;+ let amount = charge.amounts?.[quantity] ?? 0;+ if (shouldConvertCurrency) amount *= exchangeRate;+ return acc + amount;+ }, 0);+ const shippingCost = price?.convertedShippingCost ?? 0;+ const taxPercent = line.taxPercent ?? 0;+ const taxableBeforeTax =+ netExtendedPrice + taxableAdditionalCharge + shippingCost;+ const taxAmount = taxableBeforeTax * taxPercent;+ const totalTaxAndFees =+ additionalCharge + shippingCost + taxAmount;+ const totalPrice = netExtendedPrice + totalTaxAndFees;++ return (+ <View+ key={`${line.id}-${quantity}`}+ wrap={false}+ style={[+ tw(+ "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"+ ),+ {+ backgroundColor:+ opts.zebra && !isEven+ ? "rgba(249, 250, 251, 0.6)"+ : "transparent"+ }+ ]}+ >+ <View style={tw("w-1/3 pr-2")}>+ {index === 0 && (+ <>+ <Text+ style={{ ...tw("text-gray-800"), ...overflow }}+ >+ {getLineDescription(line)}+ </Text>+ <Text+ style={{+ ...tw("text-[8px] text-gray-400 mt-0.5"),+ ...overflow+ }}+ >+ {getLineDescriptionDetails(line)}+ </Text>+ {opts.showThumbnails &&+ thumbnails &&+ line.id != null &&+ line.id in thumbnails && (+ <View style={tw("mt-2")}>+ <Image+ src={thumbnails[line.id]!}+ style={{ width: 60, height: 60 }}+ />+ </View>+ )}+ {totalTaxAndFees > 0 && (+ <View style={tw("mt-1")}>+ <Text+ style={tw(+ "text-[8px] text-gray-400 font-bold"+ )}+ >+ Tax & Fees+ </Text>+ {(price?.convertedShippingCost ?? 0) > 0 && (+ <Text style={tw("text-[8px] text-gray-400")}>+ - Shipping+ </Text>+ )}+ {Object.values(additionalCharges)+ .filter(+ (charge) =>+ charge.description &&+ (charge.amounts?.[quantity] ?? 0) > 0+ )+ .sort((a, b) =>+ a.description.localeCompare(b.description)+ )+ .map((charge) => (+ <Text+ key={charge.description}+ style={tw("text-[8px] text-gray-400")}+ >+ - {charge.description}+ </Text>+ ))}+ {taxPercent > 0 && (+ <Text style={tw("text-[8px] text-gray-400")}>+ - Tax ({(taxPercent * 100).toFixed(0)}%)+ </Text>+ )}+ </View>+ )}+ </>+ )}+ </View>+ <View style={tw("w-2/3 flex flex-row")}>+ <Text+ style={tw(+ `${colWidth} text-center text-gray-600 pr-3`+ )}+ >+ {quantity} EA+ </Text>+ <Text+ style={tw(+ `${colWidth} text-center text-gray-600 pr-3`+ )}+ >+ {unitPrice+ ? unitPriceNumberFormatter.format(unitPrice)+ : "-"}+ </Text>+ {!hasSinglePricePerLine && (+ <Text+ style={tw(+ `${colWidth} text-center text-gray-600 pr-3`+ )}+ >+ {totalTaxAndFees > 0+ ? numberFormatter.format(totalTaxAndFees)+ : "-"}+ </Text>+ )}+ {hasAnyLeadTime && (+ <Text+ style={tw(+ `${colWidth} text-center text-gray-600 pr-3`+ )}+ >+ {leadTime > 0+ ? `${leadTime} ${pluralize(leadTime, "day")}`+ : "-"}+ </Text>+ )}+ <Text+ style={tw(+ `${colWidth} text-center text-gray-800 font-medium`+ )}+ >+ {hasSinglePricePerLine+ ? netExtendedPrice > 0+ ? numberFormatter.format(netExtendedPrice)+ : "-"+ : totalPrice > 0+ ? numberFormatter.format(totalPrice)+ : "-"}+ </Text>+ </View>+ </View>+ );+ })}+ {Object.keys(line.externalNotes ?? {}).length > 0 && (+ <View style={tw("px-3 py-2 border-b border-gray-200")}>+ <Note+ key={`${line.id}-notes`}+ content={line.externalNotes as JSONContent}+ />+ </View>+ )}+ </>+ ) : (+ <View+ wrap={false}+ style={[+ tw(+ "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"+ ),+ {+ backgroundColor:+ rowIndex++ % 2 !== 0 && opts.zebra+ ? "rgba(249, 250, 251, 0.6)"+ : "transparent"+ }+ ]}+ >+ <View style={tw("w-1/3 pr-2")}>+ <Text style={tw("text-gray-800")}>+ {getLineDescription(line)}+ </Text>+ <Text style={tw("text-[8px] text-gray-400 mt-0.5")}>+ {getLineDescriptionDetails(line)}+ </Text>+ </View>+ <View style={tw("w-2/3 flex flex-row")}>+ <Text+ style={tw(`${colWidth} text-right text-gray-600 font-bold`)}+ >+ No Quote+ </Text>+ <View style={tw("flex-1 text-right")}>+ <Text style={tw("text-gray-400 text-[8px] text-right")}>+ {line.noQuoteReason ?? ""}+ </Text>+ </View>+ </View>+ </View>+ )}+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/quote/NotesBlock.tsx b/packages/documents/src/pdf/blocks/quote/NotesBlock.tsxnew file mode 100644index 0000000000..f4b17029a7--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/NotesBlock.tsx@@ -0,0 +1,27 @@+import type { JSONContent } from "@carbon/react";+import { Text, View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "../tw";+import type { QuoteData } from "./types";++export function NotesBlock({ data }: { data: QuoteData }) {+ const notes = (data.quote?.externalNotes ?? {}) as JSONContent;+ const hasNotes = Object.keys(notes).length > 0;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Notes+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ {hasNotes ? (+ <Note content={notes} />+ ) : (+ <Text style={tw("text-gray-400")}>None</Text>+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/quote/PartiesBlock.tsx b/packages/documents/src/pdf/blocks/quote/PartiesBlock.tsxnew file mode 100644index 0000000000..38caf02568--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/PartiesBlock.tsx@@ -0,0 +1,107 @@+import { formatDate, isEoriCountry, pluralize } from "@carbon/utils";+import { getLocalTimeZone, today } from "@internationalized/date";+import { Text, View } from "@react-pdf/renderer";+import { AddressBlock } from "../../components";+import { tw } from "../tw";+import type { QuoteData } from "./types";++export function PartiesBlock({ data }: { data: QuoteData }) {+ const {+ quote,+ quoteCustomerDetails,+ payment,+ paymentTerms,+ shipment,+ maxLeadTime,+ locale+ } = data;+ const {+ customerName,+ customerAddressLine1,+ customerAddressLine2,+ customerCity,+ customerStateProvince,+ customerPostalCode,+ customerCountryCode,+ customerCountryName,+ customerTaxId,+ customerVatNumber,+ customerEori,+ contactName,+ contactEmail+ } = quoteCustomerDetails;++ const paymentTerm = paymentTerms?.find(+ (pt) => pt.id === payment?.paymentTermId+ );++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row")}>+ {/* LEFT — To (customer) */}+ <View style={tw("w-1/2 p-3 border-r border-gray-200")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ To+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <AddressBlock+ name={customerName}+ addressLine1={customerAddressLine1}+ addressLine2={customerAddressLine2}+ city={customerCity}+ stateProvince={customerStateProvince}+ postalCode={customerPostalCode}+ country={customerCountryName ?? customerCountryCode}+ />+ {customerTaxId && !isEoriCountry(customerCountryCode) && (+ <Text>Tax ID: {customerTaxId}</Text>+ )}+ {customerVatNumber && <Text>VAT: {customerVatNumber}</Text>}+ {customerEori && <Text>EORI: {customerEori}</Text>}+ {contactName && <Text>Contact: {contactName}</Text>}+ {contactEmail && <Text>Email: {contactEmail}</Text>}+ </View>+ </View>++ {/* RIGHT — Quote Details */}+ <View style={tw("w-1/2 p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Quote Details+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <Text>+ Date:{" "}+ {formatDate(+ today(getLocalTimeZone()).toString(),+ undefined,+ locale+ )}+ </Text>+ {quote.expirationDate && (+ <Text style={tw("font-bold")}>+ Expires: {formatDate(quote.expirationDate, undefined, locale)}+ </Text>+ )}+ {quote.customerReference && (+ <Text>Reference: {quote.customerReference}</Text>+ )}+ {maxLeadTime > 0 && (+ <Text>+ Max Lead Time: {maxLeadTime} {pluralize(maxLeadTime, "day")}+ </Text>+ )}+ {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}+ {shipment?.incoterm && (+ <Text>+ Incoterm: {shipment.incoterm}+ {shipment.incotermLocation+ ? ` — ${shipment.incotermLocation}`+ : ""}+ </Text>+ )}+ </View>+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/quote/SummaryBlock.tsx b/packages/documents/src/pdf/blocks/quote/SummaryBlock.tsxnew file mode 100644index 0000000000..b2223a089d--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/SummaryBlock.tsx@@ -0,0 +1,63 @@+import { Text, View } from "@react-pdf/renderer";+import { tw } from "../tw";+import type { QuoteData } from "./types";++const ROW = [+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+];++export function QuoteSummaryBlock({ data }: { data: QuoteData }) {+ const { hasSinglePricePerLine, totals, currencyCode, numberFormatter } = data;++ // The Quote summary only renders when every line has a single price.+ if (!hasSinglePricePerLine) return null;++ return (+ <View style={tw("mb-4")}>+ <View style={ROW}>+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Subtotal ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(totals.subtotal)}+ </Text>+ </View>+ <View style={ROW}>+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Shipping ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(totals.shipping)}+ </Text>+ </View>+ {totals.fees > 0 && (+ <View style={ROW}>+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Fees ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(totals.fees)}+ </Text>+ </View>+ )}+ <View style={ROW}>+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Taxes ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(totals.taxes)}+ </Text>+ </View>+ <View style={tw("h-[1px] bg-gray-200")} />+ <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>+ <Text style={tw("w-5/6 text-right pr-3 text-gray-800 font-bold")}>+ Total ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800 font-bold")}>+ {numberFormatter.format(totals.total)}+ </Text>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/quote/TermsBlock.tsx b/packages/documents/src/pdf/blocks/quote/TermsBlock.tsxnew file mode 100644index 0000000000..c1f8ff5655--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/TermsBlock.tsx@@ -0,0 +1,34 @@+import { Text, View } from "@react-pdf/renderer";+import type { TermsBlock as TermsBlockType } from "../../../template";+import { Note } from "../../components";+import { hasContent, resolveTerms } from "../resolveTerms";+import { tw } from "../tw";+import type { QuoteData } from "./types";++export function TermsBlock({+ block,+ data+}: {+ block: TermsBlockType;+ data: QuoteData;+}) {+ const { theme, vars } = data;+ const terms = resolveTerms(block, data.terms, vars);+ if (!hasContent(terms)) return null;++ return (+ <View break>+ <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>+ <Text+ style={[+ tw("text-[14px] font-bold uppercase tracking-wide"),+ { color: theme.accent }+ ]}+ >+ Terms & Conditions+ </Text>+ </View>+ <Note content={terms!} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/quote/index.ts b/packages/documents/src/pdf/blocks/quote/index.tsnew file mode 100644index 0000000000..63c26d11db--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/index.ts@@ -0,0 +1,8 @@+export { quoteBlockRegistry } from "./registry";+export type {+ BlockRenderer,+ QuoteCustomerDetails,+ QuoteData,+ QuoteTotals+} from "./types";+export { buildQuoteVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/quote/registry.tsx b/packages/documents/src/pdf/blocks/quote/registry.tsxnew file mode 100644index 0000000000..0eefa3e5e4--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/registry.tsx@@ -0,0 +1,36 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import { extensionBlocks } from "../extensionRegistry";+import { HeaderBlock } from "./HeaderBlock";+import { LineItemsBlock } from "./LineItemsBlock";+import { NotesBlock } from "./NotesBlock";+import { PartiesBlock } from "./PartiesBlock";+import { QuoteSummaryBlock } from "./SummaryBlock";+import { TermsBlock } from "./TermsBlock";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for Quote. Extension blocks are shared. */+export const quoteBlockRegistry: Partial<+ Record<DocumentBlockType, BlockRenderer>+> = {+ ...extensionBlocks,+ header: ({ data }) => <HeaderBlock data={data} />,+ parties: ({ data }) => <PartiesBlock data={data} />,+ notes: ({ data }) => <NotesBlock data={data} />,+ lineItems: ({ block, data }) =>+ block.type === "lineItems" ? (+ <LineItemsBlock block={block} data={data} />+ ) : null,+ summary: ({ data }) => <QuoteSummaryBlock data={data} />,+ terms: ({ block, data }) =>+ block.type === "terms" ? <TermsBlock block={block} data={data} /> : null,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={+ (data.quote?.customFields ?? {}) as Record<string, unknown>+ }+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/quote/types.ts b/packages/documents/src/pdf/blocks/quote/types.tsnew file mode 100644index 0000000000..7bebe5b85a--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/types.ts@@ -0,0 +1,61 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions,+ ResolvedSection+} from "../../../template";+import type { Company, CompanySettings } from "../../../types";++export type QuoteCustomerDetails =+ Database["public"]["Views"]["quoteCustomerDetails"]["Row"] & {+ customerTaxId?: string | null;+ customerVatNumber?: string | null;+ };++type QuoteLinePrice = Database["public"]["Tables"]["quoteLinePrice"]["Row"];++export interface QuoteTotals {+ subtotal: number;+ shipping: number;+ fees: number;+ taxes: number;+ total: number;+}++/** Everything a Quote block renderer needs, incl. precomputed derived values. */+export interface QuoteData {+ company: Company;+ companySettings?: CompanySettings | null;+ locale: string;+ quote: Database["public"]["Views"]["quotes"]["Row"];+ quoteLines: Database["public"]["Views"]["quoteLines"]["Row"][];+ quoteLinePrices: QuoteLinePrice[];+ quoteCustomerDetails: QuoteCustomerDetails;+ payment?: Database["public"]["Tables"]["quotePayment"]["Row"] | null;+ shipment?: Database["public"]["Tables"]["quoteShipment"]["Row"] | null;+ paymentTerms: { id: string; name: string }[];+ terms: JSONContent;+ thumbnails?: Record<string, string | null>;+ exchangeRate: number;+ shouldConvertCurrency: boolean;+ // Derived (built once in the driver):+ pricesByLine: Record<string, QuoteLinePrice[]>;+ hasSinglePricePerLine: boolean;+ hasAnyLeadTime: boolean;+ colWidth: string;+ maxLeadTime: number;+ totals: QuoteTotals;+ theme: DocumentTheme;+ sections: Record<string, ResolvedSection>;+ currencyCode: string | null;+ numberFormatter: Intl.NumberFormat;+ vars: Record<string, string>;+ headerOptions: HeaderOptions;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: QuoteData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/quote/vars.ts b/packages/documents/src/pdf/blocks/quote/vars.tsnew file mode 100644index 0000000000..6b104be8c5--- /dev/null+++ b/packages/documents/src/pdf/blocks/quote/vars.ts@@ -0,0 +1,27 @@+import type { QuoteData } from "./types";++/** Merge-field variable map for a Quote. */+export function buildQuoteVars(+ data: Pick<+ QuoteData,+ "quote" | "quoteCustomerDetails" | "company" | "currencyCode"+ >+): Record<string, string> {+ const q = data.quote;+ const c = data.quoteCustomerDetails;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "quote.number": str(q?.quoteId),+ "quote.expirationDate": str(q?.expirationDate),+ "quote.customerReference": str(q?.customerReference),+ "quote.currency": str(data.currencyCode),+ "customer.name": str(c?.customerName),+ "customer.addressLine1": str(c?.customerAddressLine1),+ "customer.city": str(c?.customerCity),+ "customer.country": str(c?.customerCountryName),+ "company.name": str(data.company?.name),+ "company.city": str(data.company?.city),+ "company.country": str(data.company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/registry.tsx b/packages/documents/src/pdf/blocks/registry.tsxnew file mode 100644index 0000000000..00595d35ac--- /dev/null+++ b/packages/documents/src/pdf/blocks/registry.tsx@@ -0,0 +1,86 @@+import type { DocumentBlockType } from "../../template";+import { Watermark } from "../components";+import { CustomFieldBlock } from "./CustomFieldBlock";+import { HeaderBlock } from "./HeaderBlock";+import { KeyValueBlock } from "./KeyValueBlock";+import { LineItemsBlock } from "./LineItemsBlock";+import { NotesBlock } from "./NotesBlock";+import { PartiesBlock } from "./PartiesBlock";+import { RichTextBlock } from "./RichTextBlock";+import { SharedBlock } from "./SharedBlock";+import { SpacerBlock } from "./SpacerBlock";+import { SummaryBlock } from "./SummaryBlock";+import { TermsBlock } from "./TermsBlock";+import type { BlockRenderer, SalesInvoiceData } from "./types";++/**+ * Maps each block type to its react-pdf renderer. Built-in renderers read+ * from `data`; extension renderers narrow `block` by its discriminant. The+ * driver looks up by `block.type` — an O(1) Map lookup per block.+ */+export const salesInvoiceBlockRegistry: Record<+ DocumentBlockType,+ BlockRenderer<SalesInvoiceData>+> = {+ header: ({ data }) => <HeaderBlock data={data} />,+ watermark: ({ block, data }) =>+ block.type === "watermark" ? (+ <Watermark+ src={data.company.logoWatermark}+ show+ opacity={block.opacity}+ placement={block.placement}+ size={block.size}+ />+ ) : null,+ parties: ({ data }) => <PartiesBlock data={data} />,+ notes: ({ data }) => <NotesBlock data={data} />,+ details: () => null,+ lineItems: ({ block, data }) =>+ block.type === "lineItems" ? (+ <LineItemsBlock block={block} data={data} />+ ) : null,+ summary: ({ block, data }) =>+ block.type === "summary" ? (+ <SummaryBlock block={block} data={data} />+ ) : null,+ terms: ({ block, data }) =>+ block.type === "terms" ? <TermsBlock block={block} data={data} /> : null,+ jobDetails: () => null,+ operations: () => null,+ issueDetails: () => null,+ associations: () => null,+ actionTasks: () => null,+ reviewers: () => null,+ labelHeading: () => null,+ labelRevision: () => null,+ labelQuantity: () => null,+ labelTracking: () => null,+ labelEntityId: () => null,+ richText: ({ block, data }) =>+ block.type === "richText" ? (+ <RichTextBlock block={block} vars={data.vars} />+ ) : null,+ keyValue: ({ block, data }) =>+ block.type === "keyValue" ? (+ <KeyValueBlock block={block} vars={data.vars} />+ ) : null,+ spacer: ({ block }) =>+ block.type === "spacer" ? <SpacerBlock block={block} /> : null,+ shared: ({ block, data }) =>+ block.type === "shared" ? (+ <SharedBlock block={block} sections={data.sections} vars={data.vars} />+ ) : null,+ labelBarcode: () => null,+ labelLogo: () => null,+ field: () => null,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={+ (data.salesInvoice?.customFields ?? {}) as Record<string, unknown>+ }+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/resolveTerms.ts b/packages/documents/src/pdf/blocks/resolveTerms.tsnew file mode 100644index 0000000000..0c066552d6--- /dev/null+++ b/packages/documents/src/pdf/blocks/resolveTerms.ts@@ -0,0 +1,29 @@+import type { JSONContent } from "@carbon/react";+import type { TermsBlock } from "../../template";+import { interpolateContent } from "../../template";++/** True when a tiptap doc has at least one node (i.e. renders something). */+export function hasContent(content?: JSONContent | null): boolean {+ return Boolean(+ content &&+ typeof content === "object" &&+ Array.isArray(content.content) &&+ content.content.length > 0+ );+}++/**+ * The effective terms for a document: the block's own authored content+ * (interpolated with merge fields) when present, otherwise the company-level+ * terms setting passed in as `fallback`. Returns undefined when neither exists.+ */+export function resolveTerms(+ block: TermsBlock,+ fallback: JSONContent | undefined,+ vars: Record<string, string>+): JSONContent | undefined {+ if (hasContent(block.content)) {+ return interpolateContent(block.content as JSONContent, vars);+ }+ return fallback;+}diff --git a/packages/documents/src/pdf/blocks/salesOrder/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/salesOrder/HeaderBlock.tsxnew file mode 100644index 0000000000..1d2c6c558a--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/HeaderBlock.tsx@@ -0,0 +1,15 @@+import { Header } from "../../components";+import type { SalesOrderData } from "./types";++export function HeaderBlock({ data }: { data: SalesOrderData }) {+ return (+ <Header+ company={data.company}+ title="Sales Order"+ documentId={data.salesOrder?.salesOrderId}+ currencyCode={data.salesOrder?.currencyCode}+ locale={data.locale}+ options={data.headerOptions}+ />+ );+}diff --git a/packages/documents/src/pdf/blocks/salesOrder/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/salesOrder/LineItemsBlock.tsxnew file mode 100644index 0000000000..d7d93ef9ce--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/LineItemsBlock.tsx@@ -0,0 +1,159 @@+import type { JSONContent } from "@carbon/react";+import { Image, Text, View } from "@react-pdf/renderer";+import {+ DEFAULT_LINE_ITEMS_OPTIONS,+ type LineItemsBlock as LineItemsBlockType+} from "../../../template";+import {+ getLineDescription,+ getLineDescriptionDetails,+ getLineTaxableSubtotal,+ getLineTotal+} from "../../../utils/sales-order";+import { Note } from "../../components";+import { itemTextOverflowStyle } from "../itemText";+import { tw } from "../tw";+import type { SalesOrderData } from "./types";++export function LineItemsBlock({+ block,+ data+}: {+ block: LineItemsBlockType;+ data: SalesOrderData;+}) {+ const { salesOrderLines, thumbnails, numberFormatter, theme } = data;+ const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };+ const overflow = itemTextOverflowStyle(opts);+ let rowIndex = 0;++ return (+ <View>+ {/* Header */}+ <View+ fixed+ style={[+ tw("flex flex-row py-2 px-3 text-[9px] font-bold items-center"),+ { backgroundColor: theme.accent, color: theme.accentForeground }+ ]}+ >+ <Text style={tw("w-1/2")}>Description</Text>+ <Text style={tw("w-1/6 text-center")}>Qty</Text>+ <Text style={tw("w-1/6 text-center")}>Unit Price</Text>+ <Text style={tw("w-1/6 text-center")}>Total</Text>+ </View>++ {salesOrderLines.map((line) => {+ const isEven = rowIndex % 2 === 0;+ rowIndex++;++ const lineAddOnCost = line.convertedAddOnCost ?? 0;+ const lineNonTaxableAddOnCost = line.convertedNonTaxableAddOnCost ?? 0;+ const lineShippingCost = line.convertedShippingCost ?? 0;+ const lineTaxPercent = line.taxPercent ?? 0;+ const lineTaxAmount = getLineTaxableSubtotal(line) * lineTaxPercent;+ const totalTaxAndFees =+ lineAddOnCost ++ lineNonTaxableAddOnCost ++ lineShippingCost ++ lineTaxAmount;++ return (+ <View key={line.id}>+ <View+ wrap={false}+ style={[+ tw(+ "flex flex-row py-2 px-3 border-b border-gray-200 text-[10px]"+ ),+ {+ backgroundColor:+ opts.zebra && !isEven+ ? "rgba(249, 250, 251, 0.6)"+ : "transparent"+ }+ ]}+ >+ <View style={tw("w-1/2 pr-2")}>+ <Text style={{ ...tw("text-gray-800"), ...overflow }}>+ {getLineDescription(line)}+ </Text>+ <Text+ style={{+ ...tw("text-[9px] text-gray-600 mt-0.5"),+ ...overflow+ }}+ >+ {getLineDescriptionDetails(line)}+ </Text>+ {opts.showThumbnails &&+ thumbnails &&+ line.id &&+ line.id in thumbnails &&+ thumbnails[line.id] && (+ <View style={tw("mt-1 w-16")}>+ <Image+ src={thumbnails[line.id]!}+ style={tw("w-full h-auto")}+ />+ </View>+ )}+ {line.salesOrderLineType !== "Comment" &&+ totalTaxAndFees > 0 && (+ <View style={tw("mt-1")}>+ <Text style={tw("text-[9px] text-gray-600 font-bold")}>+ Tax & Fees+ </Text>+ {lineShippingCost > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Shipping+ </Text>+ )}+ {lineAddOnCost > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Add-On+ </Text>+ )}+ {lineNonTaxableAddOnCost > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Non-Taxable Add-On+ </Text>+ )}+ {lineTaxPercent > 0 && (+ <Text style={tw("text-[9px] text-gray-600")}>+ - Tax ({(lineTaxPercent * 100).toFixed(0)}%)+ </Text>+ )}+ </View>+ )}+ </View>+ <Text style={tw("w-1/6 text-center text-gray-600")}>+ {line.salesOrderLineType === "Comment"+ ? ""+ : `${line.saleQuantity} ${line.unitOfMeasureCode ?? "EA"}`}+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-600")}>+ {line.salesOrderLineType === "Comment"+ ? ""+ : numberFormatter.format(line.convertedUnitPrice ?? 0)}+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800 font-medium")}>+ {line.salesOrderLineType === "Comment"+ ? ""+ : numberFormatter.format(getLineTotal(line))}+ </Text>+ </View>+ {Object.keys(line.externalNotes ?? {}).length > 0 && (+ <View style={tw("px-3 py-2 border-b border-gray-200")}>+ <Note+ key={`${line.id}-notes`}+ content={line.externalNotes as JSONContent}+ />+ </View>+ )}+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/salesOrder/NotesBlock.tsx b/packages/documents/src/pdf/blocks/salesOrder/NotesBlock.tsxnew file mode 100644index 0000000000..9596827086--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/NotesBlock.tsx@@ -0,0 +1,27 @@+import type { JSONContent } from "@carbon/react";+import { Text, View } from "@react-pdf/renderer";+import { Note } from "../../components";+import { tw } from "../tw";+import type { SalesOrderData } from "./types";++export function NotesBlock({ data }: { data: SalesOrderData }) {+ const notes = (data.salesOrder?.externalNotes ?? {}) as JSONContent;+ const hasNotes = Object.keys(notes).length > 0;++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("p-3")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Notes+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ {hasNotes ? (+ <Note content={notes} />+ ) : (+ <Text style={tw("text-gray-400")}>None</Text>+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/salesOrder/PartiesBlock.tsx b/packages/documents/src/pdf/blocks/salesOrder/PartiesBlock.tsxnew file mode 100644index 0000000000..28154e4de3--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/PartiesBlock.tsx@@ -0,0 +1,149 @@+import { formatDate, isEoriCountry } from "@carbon/utils";+import { Text, View } from "@react-pdf/renderer";+import { AddressBlock } from "../../components";+import { tw } from "../tw";+import type { SalesOrderData } from "./types";++export function PartiesBlock({ data }: { data: SalesOrderData }) {+ const {+ salesOrder,+ salesOrderLocations,+ paymentTerms,+ shippingMethods,+ locale+ } = data;+ const {+ customerName,+ customerAddressLine1,+ customerAddressLine2,+ customerCity,+ customerStateProvince,+ customerPostalCode,+ customerCountryName,+ customerTaxId,+ customerVatNumber,+ customerEori,+ paymentCustomerName,+ paymentAddressLine1,+ paymentAddressLine2,+ paymentCity,+ paymentStateProvince,+ paymentPostalCode,+ paymentCountryName+ } = salesOrderLocations;++ const paymentTerm = paymentTerms?.find(+ (term) => term.id === salesOrder?.paymentTermId+ );+ const shippingMethod = shippingMethods?.find(+ (method) => method.id === salesOrder?.shippingMethodId+ );++ return (+ <View style={tw("border border-gray-200 mb-4")}>+ <View style={tw("flex flex-row")}>+ {/* LEFT — Customer block */}+ <View style={tw("w-1/2 p-3 border-r border-gray-200")}>+ <Text style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}>+ Customer+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <AddressBlock+ name={customerName}+ addressLine1={customerAddressLine1}+ addressLine2={customerAddressLine2}+ city={customerCity}+ stateProvince={customerStateProvince}+ postalCode={customerPostalCode}+ country={customerCountryName}+ />+ {customerTaxId && !isEoriCountry(customerCountryName) && (+ <Text>Tax ID: {customerTaxId}</Text>+ )}+ {customerVatNumber && <Text>VAT: {customerVatNumber}</Text>}+ {customerEori && <Text>EORI: {customerEori}</Text>}+ </View>+ </View>++ {/* RIGHT — Order Details + Bill To stacked */}+ <View style={tw("w-1/2 flex flex-col")}>+ <View+ style={tw(+ paymentCustomerName ? "p-3 border-b border-gray-200" : "p-3"+ )}+ >+ <Text+ style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}+ >+ Order Details+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ {salesOrder?.orderDate && (+ <Text>+ Date: {formatDate(salesOrder.orderDate, undefined, locale)}+ </Text>+ )}+ {salesOrder?.customerReference && (+ <Text>Customer Ref: {salesOrder.customerReference}</Text>+ )}+ {salesOrder?.receiptRequestedDate && (+ <Text>+ Requested:{" "}+ {formatDate(+ salesOrder.receiptRequestedDate,+ undefined,+ locale+ )}+ </Text>+ )}+ {salesOrder?.receiptPromisedDate && (+ <Text>+ Promised:{" "}+ {formatDate(+ salesOrder.receiptPromisedDate,+ undefined,+ locale+ )}+ </Text>+ )}+ {paymentTerm && <Text>Payment Terms: {paymentTerm.name}</Text>}+ {shippingMethod && <Text>Shipping: {shippingMethod.name}</Text>}+ {salesOrder?.shippingTermName && (+ <Text>Shipping Terms: {salesOrder.shippingTermName}</Text>+ )}+ {salesOrder?.incoterm && (+ <Text>+ Incoterm: {salesOrder.incoterm}+ {salesOrder.incotermLocation+ ? ` — ${salesOrder.incotermLocation}`+ : ""}+ </Text>+ )}+ </View>+ </View>++ {paymentCustomerName && (+ <View style={tw("p-3")}>+ <Text+ style={tw("text-[9px] font-bold text-gray-600 mb-1 uppercase")}+ >+ Bill To+ </Text>+ <View style={tw("text-[9px] text-gray-800")}>+ <AddressBlock+ name={paymentCustomerName}+ addressLine1={paymentAddressLine1}+ addressLine2={paymentAddressLine2}+ city={paymentCity}+ stateProvince={paymentStateProvince}+ postalCode={paymentPostalCode}+ country={paymentCountryName}+ />+ </View>+ </View>+ )}+ </View>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/salesOrder/SummaryBlock.tsx b/packages/documents/src/pdf/blocks/salesOrder/SummaryBlock.tsxnew file mode 100644index 0000000000..bc895c89e8--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/SummaryBlock.tsx@@ -0,0 +1,128 @@+import { Text, View } from "@react-pdf/renderer";+import {+ DEFAULT_SUMMARY_OPTIONS,+ type SummaryBlock as SummaryBlockType+} from "../../../template";+import { getLineTaxableSubtotal, getTotal } from "../../../utils/sales-order";+import { tw } from "../tw";+import type { SalesOrderData } from "./types";++export function SummaryBlock({+ block,+ data+}: {+ block: SummaryBlockType;+ data: SalesOrderData;+}) {+ const { salesOrderLines, salesOrder, currencyCode, numberFormatter } = data;+ const opts = { ...DEFAULT_SUMMARY_OPTIONS, ...block.options };+ const taxLabel = opts.taxLabel?.trim() || DEFAULT_SUMMARY_OPTIONS.taxLabel;++ return (+ <View style={tw("mb-4")}>+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Subtotal ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(+ salesOrderLines.reduce(+ (sum, line) =>+ sum + (line.saleQuantity ?? 0) * (line.convertedUnitPrice ?? 0),+ 0+ )+ )}+ </Text>+ </View>++ {salesOrderLines.some(+ (line) =>+ (line.convertedAddOnCost ?? 0) > 0 ||+ (line.convertedNonTaxableAddOnCost ?? 0) > 0+ ) && (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Add-Ons ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(+ salesOrderLines.reduce(+ (sum, line) =>+ sum ++ (line.convertedAddOnCost ?? 0) ++ (line.convertedNonTaxableAddOnCost ?? 0),+ 0+ )+ )}+ </Text>+ </View>+ )}++ {(() => {+ const lineShipping = salesOrderLines.reduce(+ (sum, line) => sum + (line.convertedShippingCost ?? 0),+ 0+ );+ const orderShipping =+ (salesOrder.shippingCost ?? 0) * (salesOrder.exchangeRate ?? 1);+ const totalShipping = lineShipping + orderShipping;+ return totalShipping > 0 ? (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ Shipping ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(totalShipping)}+ </Text>+ </View>+ ) : null;+ })()}++ {salesOrderLines.some((line) => (line.taxPercent ?? 0) > 0) && (+ <View+ style={[+ tw("flex flex-row py-1.5 px-3 text-[9px]"),+ { backgroundColor: "rgba(249, 250, 251, 0.6)" }+ ]}+ >+ <Text style={tw("w-5/6 text-right pr-3 text-gray-600")}>+ {taxLabel} ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800")}>+ {numberFormatter.format(+ salesOrderLines.reduce((sum, line) => {+ const taxPercent = line.taxPercent ?? 0;+ return sum + getLineTaxableSubtotal(line) * taxPercent;+ }, 0)+ )}+ </Text>+ </View>+ )}++ <View style={tw("h-[1px] bg-gray-200")} />+ <View style={tw("flex flex-row py-2 px-3 text-[9px]")}>+ <Text style={tw("w-5/6 text-right pr-3 text-gray-800 font-bold")}>+ Total ({currencyCode})+ </Text>+ <Text style={tw("w-1/6 text-center text-gray-800 font-bold")}>+ {numberFormatter.format(getTotal(salesOrderLines, salesOrder))}+ </Text>+ </View>+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/salesOrder/TermsBlock.tsx b/packages/documents/src/pdf/blocks/salesOrder/TermsBlock.tsxnew file mode 100644index 0000000000..1aaabdcf6d--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/TermsBlock.tsx@@ -0,0 +1,34 @@+import { Text, View } from "@react-pdf/renderer";+import type { TermsBlock as TermsBlockType } from "../../../template";+import { Note } from "../../components";+import { hasContent, resolveTerms } from "../resolveTerms";+import { tw } from "../tw";+import type { SalesOrderData } from "./types";++export function TermsBlock({+ block,+ data+}: {+ block: TermsBlockType;+ data: SalesOrderData;+}) {+ const { theme, vars } = data;+ const terms = resolveTerms(block, data.terms, vars);+ if (!hasContent(terms)) return null;++ return (+ <View break>+ <View style={tw("border-b border-gray-400 mb-3 pb-2 mt-2")}>+ <Text+ style={[+ tw("text-[14px] font-bold uppercase tracking-wide"),+ { color: theme.accent }+ ]}+ >+ Terms & Conditions+ </Text>+ </View>+ <Note content={terms!} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/salesOrder/index.ts b/packages/documents/src/pdf/blocks/salesOrder/index.tsnew file mode 100644index 0000000000..0a5fbc9413--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/index.ts@@ -0,0 +1,7 @@+export { salesOrderBlockRegistry } from "./registry";+export type {+ BlockRenderer,+ SalesOrderData,+ SalesOrderLocations+} from "./types";+export { buildSalesOrderVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/salesOrder/registry.tsx b/packages/documents/src/pdf/blocks/salesOrder/registry.tsxnew file mode 100644index 0000000000..8405df4aef--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/registry.tsx@@ -0,0 +1,39 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import { extensionBlocks } from "../extensionRegistry";+import { HeaderBlock } from "./HeaderBlock";+import { LineItemsBlock } from "./LineItemsBlock";+import { NotesBlock } from "./NotesBlock";+import { PartiesBlock } from "./PartiesBlock";+import { SummaryBlock } from "./SummaryBlock";+import { TermsBlock } from "./TermsBlock";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for Sales Order. Extension blocks are shared. */+export const salesOrderBlockRegistry: Partial<+ Record<DocumentBlockType, BlockRenderer>+> = {+ ...extensionBlocks,+ header: ({ data }) => <HeaderBlock data={data} />,+ parties: ({ data }) => <PartiesBlock data={data} />,+ notes: ({ data }) => <NotesBlock data={data} />,+ lineItems: ({ block, data }) =>+ block.type === "lineItems" ? (+ <LineItemsBlock block={block} data={data} />+ ) : null,+ summary: ({ block, data }) =>+ block.type === "summary" ? (+ <SummaryBlock block={block} data={data} />+ ) : null,+ terms: ({ block, data }) =>+ block.type === "terms" ? <TermsBlock block={block} data={data} /> : null,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={+ (data.salesOrder?.customFields ?? {}) as Record<string, unknown>+ }+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/salesOrder/types.ts b/packages/documents/src/pdf/blocks/salesOrder/types.tsnew file mode 100644index 0000000000..4f95241e1b--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/types.ts@@ -0,0 +1,44 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions+} from "../../../template";+import type {+ AccountsReceivableBillingAddress,+ Company,+ CompanySettings+} from "../../../types";++export type SalesOrderLocations =+ Database["public"]["Views"]["salesOrderLocations"]["Row"] & {+ customerTaxId?: string | null;+ customerVatNumber?: string | null;+ };++/** Everything a Sales Order block renderer might need. Mirrors SalesInvoiceData. */+export interface SalesOrderData {+ company: Company;+ companySettings?: CompanySettings | null;+ locale: string;+ salesOrder: Database["public"]["Views"]["salesOrders"]["Row"];+ salesOrderLines: Database["public"]["Views"]["salesOrderLines"]["Row"][];+ salesOrderLocations: SalesOrderLocations;+ accountsReceivableBillingAddress?: AccountsReceivableBillingAddress | null;+ paymentTerms: { id: string; name: string }[];+ shippingMethods: { id: string; name: string }[];+ terms: JSONContent;+ thumbnails?: Record<string, string | null>;+ theme: DocumentTheme;+ sections: Record<string, import("../../../template").ResolvedSection>;+ currencyCode: string | null;+ numberFormatter: Intl.NumberFormat;+ vars: Record<string, string>;+ headerOptions: HeaderOptions;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: SalesOrderData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/salesOrder/vars.ts b/packages/documents/src/pdf/blocks/salesOrder/vars.tsnew file mode 100644index 0000000000..7f1bd6a56f--- /dev/null+++ b/packages/documents/src/pdf/blocks/salesOrder/vars.ts@@ -0,0 +1,30 @@+import type { SalesOrderData } from "./types";++/**+ * Merge-field variable map for a Sales Order. Tokens mirror+ * `SALES_ORDER_MERGE_FIELDS` in template/merge.ts.+ */+export function buildSalesOrderVars(+ data: Pick<+ SalesOrderData,+ "salesOrder" | "salesOrderLocations" | "company" | "currencyCode"+ >+): Record<string, string> {+ const so = data.salesOrder;+ const loc = data.salesOrderLocations;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "order.number": str(so?.salesOrderId),+ "order.date": str(so?.orderDate),+ "order.customerReference": str(so?.customerReference),+ "order.currency": str(data.currencyCode),+ "customer.name": str(loc?.customerName),+ "customer.addressLine1": str(loc?.customerAddressLine1),+ "customer.city": str(loc?.customerCity),+ "customer.country": str(loc?.customerCountryName),+ "company.name": str(data.company?.name),+ "company.city": str(data.company?.city),+ "company.country": str(data.company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/stockTransfer/DetailsBlock.tsx b/packages/documents/src/pdf/blocks/stockTransfer/DetailsBlock.tsxnew file mode 100644index 0000000000..93e702236c--- /dev/null+++ b/packages/documents/src/pdf/blocks/stockTransfer/DetailsBlock.tsx@@ -0,0 +1,30 @@+import { formatDate } from "@carbon/utils";+import { View } from "@react-pdf/renderer";+import { Summary } from "../../components";+import { tw } from "../tw";+import type { StockTransferData } from "./types";++/** Company + transfer metadata (date, id, location, assignee). */+export function DetailsBlock({ data }: { data: StockTransferData }) {+ const { company, stockTransfer, location, locale } = data;++ const items: { label: string; value: string | null | undefined }[] = [+ {+ label: "Date",+ value: stockTransfer?.createdAt+ ? formatDate(stockTransfer.createdAt, undefined, locale)+ : ""+ },+ { label: "Stock Transfer", value: stockTransfer?.stockTransferId },+ { label: "Location", value: location?.name }+ ];+ if (stockTransfer?.assignee) {+ items.push({ label: "Assignee", value: stockTransfer.assignee });+ }++ return (+ <View style={tw("mb-4")}>+ <Summary company={company} items={items} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/stockTransfer/HeaderBlock.tsx b/packages/documents/src/pdf/blocks/stockTransfer/HeaderBlock.tsxnew file mode 100644index 0000000000..a989881d7c--- /dev/null+++ b/packages/documents/src/pdf/blocks/stockTransfer/HeaderBlock.tsx@@ -0,0 +1,15 @@+import { Header } from "../../components";+import type { StockTransferData } from "./types";++export function HeaderBlock({ data }: { data: StockTransferData }) {+ return (+ <Header+ company={data.company}+ title="Stock Transfer"+ documentId={data.stockTransfer?.stockTransferId}+ date={data.stockTransfer?.createdAt}+ locale={data.locale}+ options={data.headerOptions}+ />+ );+}diff --git a/packages/documents/src/pdf/blocks/stockTransfer/LineItemsBlock.tsx b/packages/documents/src/pdf/blocks/stockTransfer/LineItemsBlock.tsxnew file mode 100644index 0000000000..54fe2e6f84--- /dev/null+++ b/packages/documents/src/pdf/blocks/stockTransfer/LineItemsBlock.tsx@@ -0,0 +1,117 @@+import bwipjs from "@bwip-js/node";+import { getAppUrl } from "@carbon/env";+import { Image, Text, View } from "@react-pdf/renderer";+import { generateQRCode } from "../../../qr/qr-code";+import {+ DEFAULT_LINE_ITEMS_OPTIONS,+ type LineItemsBlock as LineItemsBlockType+} from "../../../template";+import { itemTextOverflowStyle } from "../itemText";+import { tw } from "../tw";+import type { StockTransferData } from "./types";++async function generateBarcode(text: string): Promise<string> {+ const buffer = await bwipjs.toBuffer({+ bcid: "code128",+ text,+ scale: 3,+ height: 5,+ includetext: true,+ textxalign: "center"+ });+ return `data:image/png;base64,${buffer.toString("base64")}`;+}++export function LineItemsBlock({+ block,+ data+}: {+ block: LineItemsBlockType;+ data: StockTransferData;+}) {+ const { stockTransferLines, thumbnails, theme } = data;+ const opts = { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options };+ const overflow = itemTextOverflowStyle(opts);++ return (+ <View style={tw("mb-6 text-xs")}>+ <View+ style={[+ tw("flex flex-row py-2 px-3 text-[9px] font-bold"),+ { backgroundColor: theme.accent, color: theme.accentForeground }+ ]}+ >+ <Text style={tw("w-2/5 text-left")}>Description</Text>+ <Text style={tw("w-1/4 text-center")}>Transfer</Text>+ <Text style={tw("w-1/6 text-center")}>Qty</Text>+ <Text style={tw("w-1/8 text-center")}>Pick</Text>+ </View>++ {[...stockTransferLines]+ .sort((a, b) => {+ const storageUnitA = a.fromStorageUnitName || "Any";+ const storageUnitB = b.fromStorageUnitName || "Any";+ return storageUnitA.localeCompare(storageUnitB);+ })+ .map((line) => {+ const barcodeDataUrl = generateBarcode(line.itemReadableId ?? "");+ let pickUrl = `${getAppUrl()}/api/stock-transfer/${line.id}/pick`;+ if (line.requiresSerialTracking) {+ pickUrl += "?type=serial";+ } else if (line.requiresBatchTracking) {+ pickUrl += "?type=batch";+ }+ const pickQRCode = generateQRCode(pickUrl, 4);++ return (+ <View+ style={tw(+ "flex flex-row justify-between py-2 px-3 border-b border-gray-200 text-[10px]"+ )}+ key={line.id}+ wrap={false}+ >+ <View style={tw("w-2/5")}>+ <Text style={{ ...tw("font-bold mb-1"), ...overflow }}>+ {line.itemDescription}+ </Text>+ <Text+ style={{ ...tw("text-[9px] opacity-80 mb-2"), ...overflow }}+ >+ {line.itemReadableId}+ </Text>+ {opts.showThumbnails &&+ thumbnails &&+ line.id != null &&+ line.id in thumbnails &&+ thumbnails[line.id] && (+ <View style={tw("mt-2 mb-2")}>+ <Image+ src={thumbnails[line.id]!}+ style={tw("w-1/4 h-auto max-w-[25%]")}+ />+ </View>+ )}+ <Image src={barcodeDataUrl} style={tw("max-w-[50%]")} />+ </View>++ <View style={tw("w-1/4 text-center")}>+ <Text style={tw("text-xs")}>+ {line.fromStorageUnitName || "Any"} →{" "}+ {line.toStorageUnitName || "Any"}+ </Text>+ </View>++ <Text style={tw("w-1/6 text-center")}>+ {`${line.quantity} ${line.unitOfMeasure}`}+ </Text>++ <View style={tw("w-1/8 flex flex-col items-center")}>+ <Image src={pickQRCode} style={tw("h-16 w-16")} />+ </View>+ </View>+ );+ })}+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/stockTransfer/index.ts b/packages/documents/src/pdf/blocks/stockTransfer/index.tsnew file mode 100644index 0000000000..959c76e3da--- /dev/null+++ b/packages/documents/src/pdf/blocks/stockTransfer/index.ts@@ -0,0 +1,3 @@+export { stockTransferBlockRegistry } from "./registry";+export type { BlockRenderer, StockTransferData } from "./types";+export { buildStockTransferVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/stockTransfer/registry.tsx b/packages/documents/src/pdf/blocks/stockTransfer/registry.tsxnew file mode 100644index 0000000000..661aa8c999--- /dev/null+++ b/packages/documents/src/pdf/blocks/stockTransfer/registry.tsx@@ -0,0 +1,29 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import { extensionBlocks } from "../extensionRegistry";+import { DetailsBlock } from "./DetailsBlock";+import { HeaderBlock } from "./HeaderBlock";+import { LineItemsBlock } from "./LineItemsBlock";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for Stock Transfer. Extension blocks are shared. */+export const stockTransferBlockRegistry: Partial<+ Record<DocumentBlockType, BlockRenderer>+> = {+ ...extensionBlocks,+ header: ({ data }) => <HeaderBlock data={data} />,+ details: ({ data }) => <DetailsBlock data={data} />,+ lineItems: ({ block, data }) =>+ block.type === "lineItems" ? (+ <LineItemsBlock block={block} data={data} />+ ) : null,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={+ (data.stockTransfer?.customFields ?? {}) as Record<string, unknown>+ }+ />+ ) : null+};diff --git a/packages/documents/src/pdf/blocks/stockTransfer/types.ts b/packages/documents/src/pdf/blocks/stockTransfer/types.tsnew file mode 100644index 0000000000..9f15238381--- /dev/null+++ b/packages/documents/src/pdf/blocks/stockTransfer/types.ts@@ -0,0 +1,27 @@+import type { Database } from "@carbon/database";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions,+ ResolvedSection+} from "../../../template";+import type { Company } from "../../../types";++/** Everything a Stock Transfer block renderer might need. */+export interface StockTransferData {+ company: Company;+ locale: string;+ stockTransfer: Database["public"]["Tables"]["stockTransfer"]["Row"];+ stockTransferLines: Database["public"]["Views"]["stockTransferLines"]["Row"][];+ location: Database["public"]["Tables"]["location"]["Row"];+ thumbnails?: Record<string, string | null>;+ theme: DocumentTheme;+ sections: Record<string, ResolvedSection>;+ vars: Record<string, string>;+ headerOptions: HeaderOptions;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: StockTransferData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/stockTransfer/vars.ts b/packages/documents/src/pdf/blocks/stockTransfer/vars.tsnew file mode 100644index 0000000000..c6cbeb8a39--- /dev/null+++ b/packages/documents/src/pdf/blocks/stockTransfer/vars.ts@@ -0,0 +1,18 @@+import type { StockTransferData } from "./types";++/** Merge-field variable map for a Stock Transfer. */+export function buildStockTransferVars(+ data: Pick<StockTransferData, "stockTransfer" | "location" | "company">+): Record<string, string> {+ const t = data.stockTransfer;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "transfer.number": str(t?.stockTransferId),+ "transfer.location": str(data.location?.name),+ "transfer.assignee": str(t?.assignee),+ "company.name": str(data.company?.name),+ "company.city": str(data.company?.city),+ "company.country": str(data.company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/trackingLabel/LabelBlocks.tsx b/packages/documents/src/pdf/blocks/trackingLabel/LabelBlocks.tsxnew file mode 100644index 0000000000..afe5eb4ba8--- /dev/null+++ b/packages/documents/src/pdf/blocks/trackingLabel/LabelBlocks.tsx@@ -0,0 +1,247 @@+import { Image, Text, View } from "@react-pdf/renderer";+import { generateBarcode } from "../../../qr/barcode";+import type {+ FieldBlock,+ LabelBarcodeBlock as LabelBarcodeBlockType,+ LabelEntityIdBlock as LabelEntityIdBlockType,+ LabelLogoBlock as LabelLogoBlockType,+ LabelNamedBlock+} from "../../../template";+import { interpolateString } from "../../../template";+import { LogoImage } from "../../components/LogoImage";+import { tw } from "./tw";+import type { LabelData } from "./types";++/**+ * A two-column field row: name column (fixed width, so rows align) + value.+ * With no name, the value spans the row (plain text).+ */+function LabelFieldRow({+ name,+ value,+ data+}: {+ name?: string;+ value: string;+ data: LabelData;+}) {+ if (!value) return null;+ const fontSize = `${data.descriptionFontSize}pt`;+ if (!name) {+ return <Text style={{ ...tw("mb-1"), fontSize }}>{value}</Text>;+ }+ return (+ <View style={tw("flex flex-row mb-1")}>+ <Text style={{ width: data.labelColWidth, fontSize }}>{name}:</Text>+ <Text style={{ flex: 1, fontSize }}>{value}</Text>+ </View>+ );+}++/** A single authored line: `label: value` (or just the value when no label). */+export function LabelFieldBlock({+ block,+ data+}: {+ block: FieldBlock;+ data: LabelData;+}) {+ return (+ <LabelFieldRow+ name={block.label || undefined}+ value={interpolateString(block.value ?? "", data.vars)}+ data={data}+ />+ );+}++/** Item ID — the bold label heading. */+export function LabelHeadingBlock({ data }: { data: LabelData }) {+ const { item, titleFontSize } = data;+ if (!item.itemId) return null;+ return (+ <Text+ style={{+ maxWidth: "100%",+ ...tw("mb-1"),+ fontWeight: "bold",+ fontSize: `${titleFontSize}pt`,+ lineHeight: 1.2+ }}+ >+ {item.itemId}+ </Text>+ );+}++/** Revision row. */+export function LabelRevisionBlock({+ block,+ data+}: {+ block: LabelNamedBlock;+ data: LabelData;+}) {+ if (!data.item.revision) return null;+ return (+ <LabelFieldRow+ name={block.label || "Rev"}+ value={String(data.item.revision)}+ data={data}+ />+ );+}++/** Quantity row (serial/batch-tracked items only). */+export function LabelQuantityBlock({+ block,+ data+}: {+ block: LabelNamedBlock;+ data: LabelData;+}) {+ if (!["Serial", "Batch"].includes(data.item.trackingType)) return null;+ return (+ <LabelFieldRow+ name={block.label || "Qty"}+ value={String(data.item.quantity ?? "")}+ data={data}+ />+ );+}++/** Serial / Batch number row. */+export function LabelTrackingBlock({+ block,+ data+}: {+ block: LabelNamedBlock;+ data: LabelData;+}) {+ const { item } = data;+ if (!item.number) return null;+ const defaultName =+ item.trackingType === "Serial"+ ? "S/N"+ : item.trackingType === "Batch"+ ? "Batch"+ : null;+ if (!defaultName) return null;+ return (+ <LabelFieldRow+ name={block.label || defaultName}+ value={String(item.number)}+ data={data}+ />+ );+}++/** A human-readable identifier line (interpolated value), centered. */+export function LabelEntityIdBlock({+ block,+ data+}: {+ block: LabelEntityIdBlockType;+ data: LabelData;+}) {+ const value = interpolateString(block.value ?? "", data.vars);+ if (!value) return null;+ return (+ <Text+ style={{+ ...tw("mt-1 text-center"),+ fontSize: `${data.descriptionFontSize - 1}pt`,+ width: "100%",+ flexShrink: 0+ }}+ >+ {value}+ </Text>+ );+}++/**+ * The scannable code. `right` placement renders square (top-right, like the+ * old QR slot); `full` placement stretches full width (e.g. PDF417).+ */+export function LabelBarcodeBlock({+ block,+ data+}: {+ block: LabelBarcodeBlockType;+ data: LabelData;+}) {+ const value = interpolateString(block.value ?? "", data.vars);+ if (!value) return null;+ // 2D square codes scale by module (no height, or they distort); linear and+ // stacked codes take a bar/row height.+ const isSquare =+ block.symbology === "qrcode" || block.symbology === "datamatrix";+ const src = generateBarcode(+ value,+ block.symbology,+ isSquare ? { scale: 4 } : { height: block.symbology === "pdf417" ? 8 : 12 }+ );++ if (block.placement === "full") {+ // Scale to the label stock so a full-width code never crowds out the text+ // rows (which clip/overlap on short labels). ~32% of the cell height, capped.+ const height =+ block.height ?? Math.max(28, Math.min(64, data.labelHeightPt * 0.32));+ return (+ <View style={{ ...tw("w-full flex items-center mt-1"), flexShrink: 0 }}>+ <Image+ src={src}+ style={{ width: "100%", height, objectFit: "contain" }}+ />+ </View>+ );+ }++ const size = block.height ?? data.qrCodeSize;++ if (block.placement === "center") {+ // Centered square in its own full-width row (e.g. a QR-only small label).+ return (+ <View style={{ ...tw("w-full flex items-center mt-1"), flexShrink: 0 }}>+ <Image+ src={src}+ style={{ width: size, height: size, objectFit: "contain" }}+ />+ </View>+ );+ }++ return (+ <View style={tw("flex items-center justify-center mb-1")}>+ <Image+ src={src}+ style={{ width: size, height: size, objectFit: "contain" }}+ />+ </View>+ );+}++/** The company logo (color, or the monochrome variant when toggled / for ZPL). */+export function LabelLogoBlock({+ block,+ data+}: {+ block: LabelLogoBlockType;+ data: LabelData;+}) {+ const light = data.company?.logoLight;+ const icon = data.company?.logoLightIcon;+ // `icon` variant prefers the square logo; `mark` prefers the full logo.+ const companyLogo =+ block.variant === "icon" ? (icon ?? light) : (light ?? icon);+ const src = block.monochrome+ ? (data.logo?.mono ?? data.logo?.color ?? companyLogo)+ : (data.logo?.color ?? companyLogo);+ if (!src) return null;+ return (+ <View style={tw("flex items-end mb-1")}>+ <LogoImage src={src} height={block.height ?? 50} crop={block.crop} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/blocks/trackingLabel/index.ts b/packages/documents/src/pdf/blocks/trackingLabel/index.tsnew file mode 100644index 0000000000..20846905c0--- /dev/null+++ b/packages/documents/src/pdf/blocks/trackingLabel/index.ts@@ -0,0 +1,3 @@+export { trackingLabelBlockRegistry } from "./registry";+export type { BlockRenderer, LabelData, LabelLogo } from "./types";+export { buildLabelVars } from "./vars";diff --git a/packages/documents/src/pdf/blocks/trackingLabel/registry.tsx b/packages/documents/src/pdf/blocks/trackingLabel/registry.tsxnew file mode 100644index 0000000000..6f41fd917a--- /dev/null+++ b/packages/documents/src/pdf/blocks/trackingLabel/registry.tsx@@ -0,0 +1,76 @@+import type { DocumentBlockType } from "../../../template";+import { CustomFieldBlock } from "../CustomFieldBlock";+import {+ LabelBarcodeBlock,+ LabelEntityIdBlock,+ LabelFieldBlock,+ LabelHeadingBlock,+ LabelLogoBlock,+ LabelQuantityBlock,+ LabelRevisionBlock,+ LabelTrackingBlock+} from "./LabelBlocks";+import type { BlockRenderer } from "./types";++/** Block-type → renderer for a tracking label (per-field elements). */+export const trackingLabelBlockRegistry: Record<+ DocumentBlockType,+ BlockRenderer+> = {+ labelHeading: ({ data }) => <LabelHeadingBlock data={data} />,+ labelRevision: ({ block, data }) =>+ block.type === "labelRevision" ? (+ <LabelRevisionBlock block={block} data={data} />+ ) : null,+ labelQuantity: ({ block, data }) =>+ block.type === "labelQuantity" ? (+ <LabelQuantityBlock block={block} data={data} />+ ) : null,+ labelTracking: ({ block, data }) =>+ block.type === "labelTracking" ? (+ <LabelTrackingBlock block={block} data={data} />+ ) : null,+ labelEntityId: ({ block, data }) =>+ block.type === "labelEntityId" ? (+ <LabelEntityIdBlock block={block} data={data} />+ ) : null,+ labelBarcode: ({ block, data }) =>+ block.type === "labelBarcode" ? (+ <LabelBarcodeBlock block={block} data={data} />+ ) : null,+ labelLogo: ({ block, data }) =>+ block.type === "labelLogo" ? (+ <LabelLogoBlock block={block} data={data} />+ ) : null,+ header: () => null,+ watermark: () => null,+ parties: () => null,+ notes: () => null,+ details: () => null,+ lineItems: () => null,+ summary: () => null,+ terms: () => null,+ jobDetails: () => null,+ operations: () => null,+ issueDetails: () => null,+ associations: () => null,+ actionTasks: () => null,+ reviewers: () => null,+ // Single-line fields are supported (and mirrored in ZPL). Rich text /+ // key-value lists / spacers / shared sections are not.+ field: ({ block, data }) =>+ block.type === "field" ? (+ <LabelFieldBlock block={block} data={data} />+ ) : null,+ customField: ({ block, data }) =>+ block.type === "customField" ? (+ <CustomFieldBlock+ block={block}+ customFields={(data.item.customFields ?? {}) as Record<string, unknown>}+ />+ ) : null,+ richText: () => null,+ keyValue: () => null,+ spacer: () => null,+ shared: () => null+};diff --git a/packages/documents/src/pdf/blocks/trackingLabel/tw.ts b/packages/documents/src/pdf/blocks/trackingLabel/tw.tsnew file mode 100644index 0000000000..02902e7ed6--- /dev/null+++ b/packages/documents/src/pdf/blocks/trackingLabel/tw.ts@@ -0,0 +1,17 @@+import { createTw } from "react-pdf-tailwind";++/** Tailwind instance for tracking-label blocks (matches ProductLabelPDF). */+export const tw = createTw({+ theme: {+ fontFamily: {+ sans: ["Helvetica", "Arial", "sans-serif"]+ },+ extend: {+ colors: {+ gray: {+ 500: "#7d7d7d"+ }+ }+ }+ }+});diff --git a/packages/documents/src/pdf/blocks/trackingLabel/types.ts b/packages/documents/src/pdf/blocks/trackingLabel/types.tsnew file mode 100644index 0000000000..821bf57ba2--- /dev/null+++ b/packages/documents/src/pdf/blocks/trackingLabel/types.ts@@ -0,0 +1,36 @@+import type { ProductLabelItem } from "@carbon/utils";+import type {+ DocumentBlock,+ DocumentTheme,+ ResolvedSection+} from "../../../template";+import type { Company } from "../../../types";++/** Resolved logo sources for a label (color URL + monochrome data URL). */+export interface LabelLogo {+ color?: string | null;+ mono?: string | null;+}++/** Everything a tracking-label block renderer might need (one label's worth). */+export interface LabelData {+ item: ProductLabelItem;+ company?: Company | null;+ logo?: LabelLogo | null;+ theme: DocumentTheme;+ vars: Record<string, string>;+ /** Font sizes derived from the chosen label stock (set per render). */+ titleFontSize: number;+ descriptionFontSize: number;+ qrCodeSize: number;+ /** Width (pt) of the label-name column, so field rows align. */+ labelColWidth: number;+ /** Label cell height (pt), so full-width codes can size to the stock. */+ labelHeightPt: number;+ sections: Record<string, ResolvedSection>;+}++export type BlockRenderer = (args: {+ block: DocumentBlock;+ data: LabelData;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/trackingLabel/vars.ts b/packages/documents/src/pdf/blocks/trackingLabel/vars.tsnew file mode 100644index 0000000000..1c8d5941a2--- /dev/null+++ b/packages/documents/src/pdf/blocks/trackingLabel/vars.ts@@ -0,0 +1,21 @@+import type { Company } from "../../../types";+import type { LabelData } from "./types";++/** Merge-field variable map for a tracking label. */+export function buildLabelVars(+ item: Pick<LabelData, "item">["item"],+ company?: Company | null+): Record<string, string> {+ const str = (v: unknown): string => (v == null ? "" : String(v));+ return {+ "item.id": str(item?.itemId),+ "item.revision": str(item?.revision),+ "label.quantity": str(item?.quantity),+ "label.trackingType": str(item?.trackingType),+ "label.number": str(item?.number),+ "label.trackedEntityId": str(item?.trackedEntityId),+ "company.name": str(company?.name),+ "company.city": str(company?.city),+ "company.country": str(company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/blocks/tw.ts b/packages/documents/src/pdf/blocks/tw.tsnew file mode 100644index 0000000000..c6fc207d6a--- /dev/null+++ b/packages/documents/src/pdf/blocks/tw.ts@@ -0,0 +1,24 @@+import { createTw } from "react-pdf-tailwind";++/**+ * Shared Tailwind instance for sales-document blocks. Kept identical to the+ * theme previously inlined in SalesInvoicePDF so block output is unchanged.+ */+export const tw = createTw({+ theme: {+ fontFamily: {+ sans: ["Inter", "Helvetica", "Arial", "sans-serif"]+ },+ extend: {+ colors: {+ gray: {+ 50: "#f9fafb",+ 200: "#e5e7eb",+ 400: "#9ca3af",+ 600: "#4b5563",+ 800: "#1f2937"+ }+ }+ }+ }+});diff --git a/packages/documents/src/pdf/blocks/types.ts b/packages/documents/src/pdf/blocks/types.tsnew file mode 100644index 0000000000..9dc600c36f--- /dev/null+++ b/packages/documents/src/pdf/blocks/types.ts@@ -0,0 +1,61 @@+import type { Database } from "@carbon/database";+import type { JSONContent } from "@carbon/react";+import type {+ DocumentBlock,+ DocumentTheme,+ HeaderOptions,+ ResolvedSection+} from "../../template";+import type {+ AccountsReceivableBillingAddress,+ Company,+ CompanySettings+} from "../../types";++export type SalesInvoiceLocations =+ Database["public"]["Views"]["salesInvoiceLocations"]["Row"] & {+ customerTaxId?: string | null;+ customerVatNumber?: string | null;+ };++/**+ * Everything a Sales Invoice block renderer might need. Built-in blocks read+ * from this; the driver builds it once and hands the same object to every+ * block, so there is no per-section prop drilling.+ */+export interface SalesInvoiceData {+ company: Company;+ companySettings?: CompanySettings | null;+ locale: string;+ salesInvoice: Database["public"]["Views"]["salesInvoices"]["Row"];+ salesInvoiceLines: Database["public"]["Views"]["salesInvoiceLines"]["Row"][];+ salesInvoiceLocations: SalesInvoiceLocations;+ salesInvoiceShipment: Database["public"]["Tables"]["salesInvoiceShipment"]["Row"];+ salesOrderIds?: string[];+ accountsReceivableBillingAddress?: AccountsReceivableBillingAddress | null;+ paymentTerms: { id: string; name: string }[];+ shippingMethods: { id: string; name: string }[];+ terms: JSONContent;+ thumbnails?: Record<string, string | null>;+ /** Customizable color palette for the document. */+ theme: DocumentTheme;+ /** Resolved shared sections referenced by `shared` blocks, keyed by id. */+ sections: Record<string, ResolvedSection>;+ /** Precomputed display helpers (built once in the driver). */+ currencyCode: string | null;+ numberFormatter: Intl.NumberFormat;+ /** Merge-field values, keyed by token (e.g. `invoice.number`). */+ vars: Record<string, string>;+ /** Resolved header layout (from the global header section's config). */+ headerOptions: HeaderOptions;+}++/**+ * A block renderer is a pure function of the (block, data) pair. Built-in+ * renderers ignore `block` beyond its identity; extension renderers narrow+ * `block` by its `type` discriminant.+ */+export type BlockRenderer<D> = (args: {+ block: DocumentBlock;+ data: D;+}) => JSX.Element | null;diff --git a/packages/documents/src/pdf/blocks/vars.ts b/packages/documents/src/pdf/blocks/vars.tsnew file mode 100644index 0000000000..cba39921d4--- /dev/null+++ b/packages/documents/src/pdf/blocks/vars.ts@@ -0,0 +1,36 @@+import type { SalesInvoiceData } from "./types";++/**+ * Build the merge-field variable map for a Sales Invoice. Tokens here must stay+ * in sync with `SALES_INVOICE_MERGE_FIELDS` in template/merge.ts (the catalog+ * the editor offers). Missing values resolve to "" so a token never prints raw.+ */+export function buildSalesInvoiceVars(+ data: Pick<+ SalesInvoiceData,+ "salesInvoice" | "salesInvoiceLocations" | "company" | "currencyCode"+ >+): Record<string, string> {+ const inv = data.salesInvoice;+ const loc = data.salesInvoiceLocations;+ const str = (v: unknown): string => (v == null ? "" : String(v));++ return {+ "invoice.number": str(inv?.invoiceId),+ "invoice.dateIssued": str(inv?.dateIssued),+ "invoice.dateDue": str(inv?.dateDue),+ "invoice.customerReference": str(inv?.customerReference),+ "invoice.currency": str(data.currencyCode),+ "customer.name": str(loc?.invoiceCustomerName ?? loc?.customerName),+ "customer.addressLine1": str(+ loc?.invoiceAddressLine1 ?? loc?.customerAddressLine1+ ),+ "customer.city": str(loc?.invoiceCity ?? loc?.customerCity),+ "customer.country": str(+ loc?.invoiceCountryName ?? loc?.customerCountryName+ ),+ "company.name": str(data.company?.name),+ "company.city": str(data.company?.city),+ "company.country": str(data.company?.countryCode)+ };+}diff --git a/packages/documents/src/pdf/components/Footer.tsx b/packages/documents/src/pdf/components/Footer.tsxindex b50b8d66d7..86c52f3402 100644--- a/packages/documents/src/pdf/components/Footer.tsx+++ b/packages/documents/src/pdf/components/Footer.tsx@@ -1,5 +1,7 @@+import type { JSONContent } from "@carbon/react";import { Text, View } from "@react-pdf/renderer";import { createTw } from "react-pdf-tailwind";+import Note from "./Note";const tw = createTw({theme: {@@ -12,9 +14,28 @@ const tw = createTw({interface FooterProps {label?: string;documentId?: string | null;+ /** Optional shared-section content rendered above the registration line. */+ content?: JSONContent | null;+ /** Document settings (default: show everything). */+ showPageNumbers?: boolean;+ pageNumberFormat?: "pageOfTotal" | "page";+ showRegistrationLine?: boolean;}-const Footer = ({ label, documentId }: FooterProps) => {+const Footer = ({+ label,+ documentId,+ content,+ showPageNumbers = true,+ pageNumberFormat = "pageOfTotal",+ showRegistrationLine = true+}: FooterProps) => {+ const hasContent =+ content &&+ typeof content === "object" &&+ Array.isArray(content.content) &&+ content.content.length > 0;+return (<Viewstyle={[@@ -23,18 +44,27 @@ const Footer = ({ label, documentId }: FooterProps) => {]}fixed>+ {hasContent && (+ <View style={tw("text-[8px] text-gray-500 mb-2 px-1")}>+ <Note content={content} />+ </View>+ )}<View style={tw("border-t border-gray-200 pt-3")}><Viewstyle={tw("flex flex-row justify-between items-center text-xs text-gray-500 px-1")}>- <Text>{label ?? ""}</Text>- <Text- render={({ pageNumber, totalPages }) =>- `${documentId ? `${documentId} ` : ""}Page ${pageNumber} of ${totalPages}`- }- />+ <Text>{showRegistrationLine ? (label ?? "") : ""}</Text>+ {showPageNumbers && (+ <Text+ render={({ pageNumber, totalPages }) =>+ `${documentId ? `${documentId} ` : ""}Page ${pageNumber}${+ pageNumberFormat === "pageOfTotal" ? ` of ${totalPages}` : ""+ }`+ }+ />+ )}</View></View></View>diff --git a/packages/documents/src/pdf/components/Header.tsx b/packages/documents/src/pdf/components/Header.tsxindex 58c38e135b..418b41440f 100644--- a/packages/documents/src/pdf/components/Header.tsx+++ b/packages/documents/src/pdf/components/Header.tsx@@ -1,7 +1,9 @@import { formatCityStatePostalCode } from "@carbon/utils";-import { Image, Text, View } from "@react-pdf/renderer";+import { Text, View } from "@react-pdf/renderer";import { createTw } from "react-pdf-tailwind";+import { DEFAULT_HEADER_OPTIONS, type HeaderOptions } from "../../template";import type { Company } from "../../types";+import { LogoImage } from "./LogoImage";type HeaderProps = {company: Company;@@ -11,6 +13,8 @@ type HeaderProps = {date?: string | null;currencyCode?: string | null;locale?: string;+ /** Per-template display options (logo + which fields show). */+ options?: HeaderOptions;/*** When true, the header is wrapped in <View fixed> so it repeats on* every page. Used by PO PDF; sales PDFs default to non-fixed (page 1 only).@@ -42,51 +46,65 @@ const Header = ({title,documentId,documentSubId,+ options,fixed}: HeaderProps) => {+ const opts = { ...DEFAULT_HEADER_OPTIONS, ...options };+ // `icon` variant prefers the square logo; `mark` prefers the full logo.+ const logoSrc =+ opts.logoVariant === "icon"+ ? (company.logoLightIcon ?? company.logoLight)+ : (company.logoLight ?? company.logoLightIcon);+ const showLogo = opts.showLogo && Boolean(logoSrc);+ // Name fallback only when a logo is wanted but missing. With the logo turned+ // off, render nothing here (the company name still shows in the details block).+ const showNameFallback = opts.showLogo && !logoSrc;+const headerView = (<View style={tw("flex flex-row justify-between mb-1")}><View style={tw("flex flex-row")}>- {company.logoLightIcon ? (- <Image- src={company.logoLightIcon}- style={{ height: 50, width: "auto", marginRight: 12 }}+ {showLogo ? (+ <LogoImage+ src={logoSrc!}+ height={opts.logoHeight}+ crop={opts.logoCrop}+ marginRight={12}/>- ) : (- <Text- style={tw("text-2xl font-bold text-gray-800 tracking-tight mr-3")}- >+ ) : showNameFallback ? (+ <Text style={tw("text-2xl font-bold text-gray-800 mr-3")}>{company.name}</Text>+ ) : null}+ {opts.showCompanyDetails && (+ <View style={tw("flex flex-col text-[9px] text-gray-800")}>+ {company.name && (+ <Text style={tw("font-bold")}>{company.name}</Text>+ )}+ {company.addressLine1 && <Text>{company.addressLine1}</Text>}+ {company.addressLine2 && <Text>{company.addressLine2}</Text>}+ {(company.city || company.stateProvince || company.postalCode) && (+ <Text>+ {formatCityStatePostalCode(+ company.city,+ company.stateProvince,+ company.postalCode+ )}+ </Text>+ )}+ </View>)}- <View style={tw("flex flex-col text-[9px] text-gray-800")}>- {company.name && <Text style={tw("font-bold")}>{company.name}</Text>}- {company.addressLine1 && <Text>{company.addressLine1}</Text>}- {company.addressLine2 && <Text>{company.addressLine2}</Text>}- {(company.city || company.stateProvince || company.postalCode) && (- <Text>- {formatCityStatePostalCode(- company.city,- company.stateProvince,- company.postalCode- )}- </Text>- )}- </View></View><View style={tw("flex flex-col items-end justify-start")}>- <Text style={tw("text-2xl font-bold text-gray-800 tracking-tight")}>- {title}- </Text>- {documentId && (- <Text- style={tw("text-sm font-bold text-gray-600 tracking-tight -mt-4")}- >+ {opts.showDocumentTitle && (+ <Text style={tw("text-2xl font-bold text-gray-800")}>{title}</Text>+ )}+ {opts.showDocumentId && documentId && (+ <Text style={tw("text-sm font-bold text-gray-600 -mt-4")}>{documentId}</Text>)}{documentSubId && (- <Text style={tw("text-[8px] font-bold text-gray-600 tracking-tight")}>+ <Text style={tw("text-[8px] font-bold text-gray-600")}>{documentSubId}</Text>)}diff --git a/packages/documents/src/pdf/components/LogoImage.tsx b/packages/documents/src/pdf/components/LogoImage.tsxnew file mode 100644index 0000000000..347fceb400--- /dev/null+++ b/packages/documents/src/pdf/components/LogoImage.tsx@@ -0,0 +1,54 @@+import { Image, View } from "@react-pdf/renderer";+import type { LogoCrop } from "../../template";++/**+ * Renders a logo at a fixed height, optionally cropped. With a crop, it draws a+ * clip box sized to the crop's stored pixel aspect and blows the image up so the+ * cropped region fills it — `overflow: hidden` clips the rest. No intrinsic+ * image dimensions are needed at render time. Shared by the document header and+ * the tracking-label logo block so both crop identically.+ */+export function LogoImage({+ src,+ height,+ crop,+ marginRight+}: {+ src: string;+ height: number;+ crop?: LogoCrop;+ marginRight?: number;+}) {+ if (!crop) {+ return (+ <Image+ src={src}+ style={{ height, width: "auto", objectFit: "contain", marginRight }}+ />+ );+ }+ const boxH = height;+ const boxW = height * crop.aspect;+ return (+ <View+ style={{+ width: boxW,+ height: boxH,+ overflow: "hidden",+ position: "relative",+ marginRight+ }}+ >+ <Image+ src={src}+ style={{+ position: "absolute",+ width: boxW / crop.width,+ height: boxH / crop.height,+ left: -(crop.x / crop.width) * boxW,+ top: -(crop.y / crop.height) * boxH+ }}+ />+ </View>+ );+}diff --git a/packages/documents/src/pdf/components/Template.tsx b/packages/documents/src/pdf/components/Template.tsxindex 5a360f10fe..b64d928b97 100644--- a/packages/documents/src/pdf/components/Template.tsx+++ b/packages/documents/src/pdf/components/Template.tsx@@ -1,13 +1,26 @@-import { Document, Font, Page, StyleSheet } from "@react-pdf/renderer";+import type { JSONContent } from "@carbon/react";+import { Document, Font, Page, StyleSheet, View } from "@react-pdf/renderer";import type { PropsWithChildren } from "react";import type { Meta } from "../../types";import Footer from "./Footer";+import Note from "./Note";type TemplateProps = PropsWithChildren<{title: string;meta: Meta;footerLabel?: string;footerDocumentId?: string | null;+ /** When false, the entire footer band (registration line + page numbers) is omitted. */+ showFooter?: boolean;+ showPageNumbers?: boolean;+ pageNumberFormat?: "pageOfTotal" | "page";+ showRegistrationLine?: boolean;+ /** Body font (Inter is registered; the rest are PDF standard fonts). */+ fontFamily?: string;+ /** Shared-section content repeated at the top of every page. */+ headerContent?: JSONContent | null;+ /** Shared-section content repeated in the footer of every page. */+ footerContent?: JSONContent | null;}>;const Template = ({@@ -15,8 +28,20 @@ const Template = ({meta,footerLabel,footerDocumentId,+ showFooter = true,+ showPageNumbers = true,+ pageNumberFormat = "pageOfTotal",+ showRegistrationLine = true,+ fontFamily = "Inter",+ headerContent,+ footerContent,children}: TemplateProps) => {+ const hasHeader =+ headerContent &&+ typeof headerContent === "object" &&+ Array.isArray(headerContent.content) &&+ headerContent.content.length > 0;Font.register({family: "Inter",fonts: [@@ -42,9 +67,24 @@ const Template = ({]});+ // Built-ins need no registration; otherwise the font must have been+ // registered (Inter statically here, Google fonts via ensureFont before+ // render). Fall back to Helvetica so an unregistered font never errors.+ const BUILT_IN_FONTS = ["Helvetica", "Times-Roman", "Courier"];+ const safeFontFamily =+ BUILT_IN_FONTS.includes(fontFamily) ||+ Font.getRegisteredFontFamilies().includes(fontFamily)+ ? fontFamily+ : "Helvetica";+const styles = StyleSheet.create({body: {- fontFamily: "Inter",+ fontFamily: safeFontFamily,+ // Unitless line-height = a multiple of font size, so vertical rhythm is+ // identical for every font (Inter, serif, mono) and every text size.+ // letterSpacing 0 drops each font's default tracking for consistency.+ lineHeight: 1.4,+ letterSpacing: 0,padding: "10px 16px 36px 16px",color: "#000000",backgroundColor: "#FFFFFF"@@ -59,8 +99,22 @@ const Template = ({title={title}><Page size="A4" style={styles.body}>+ {hasHeader && (+ <View fixed style={{ marginBottom: 8 }}>+ <Note content={headerContent} />+ </View>+ )}{children}- <Footer label={footerLabel} documentId={footerDocumentId} />+ {showFooter && (+ <Footer+ label={footerLabel}+ documentId={footerDocumentId}+ content={footerContent}+ showPageNumbers={showPageNumbers}+ pageNumberFormat={pageNumberFormat}+ showRegistrationLine={showRegistrationLine}+ />+ )}</Page></Document>);diff --git a/packages/documents/src/pdf/components/Watermark.tsx b/packages/documents/src/pdf/components/Watermark.tsxnew file mode 100644index 0000000000..91848675a6--- /dev/null+++ b/packages/documents/src/pdf/components/Watermark.tsx@@ -0,0 +1,46 @@+import { Image, View } from "@react-pdf/renderer";++/**+ * Faint, page-fixed company watermark behind the document. Renders nothing when+ * disabled or when no watermark logo is set. Shared by every document that+ * supports a watermark.+ */+export function Watermark({+ src,+ show,+ opacity = 0.07,+ placement = "center",+ size = 50+}: {+ src?: string | null;+ show?: boolean;+ opacity?: number;+ placement?: "center" | "top" | "bottom";+ size?: number;+}) {+ if (!show || !src) return null;+ const justifyContent =+ placement === "top"+ ? "flex-start"+ : placement === "bottom"+ ? "flex-end"+ : "center";+ return (+ <View+ fixed+ style={{+ position: "absolute",+ top: 0,+ left: 0,+ right: 0,+ bottom: 0,+ alignItems: "center",+ justifyContent,+ padding: 64,+ opacity+ }}+ >+ <Image src={src} style={{ width: `${size}%` }} />+ </View>+ );+}diff --git a/packages/documents/src/pdf/components/index.ts b/packages/documents/src/pdf/components/index.tsindex 8c8f11a033..f4cfcaa6f4 100644--- a/packages/documents/src/pdf/components/index.ts+++ b/packages/documents/src/pdf/components/index.ts@@ -1,8 +1,19 @@import { AddressBlock } from "./AddressBlock";import Footer from "./Footer";import { Header } from "./Header";+import { LogoImage } from "./LogoImage";import Note from "./Note";import Summary from "./Summary";import Template from "./Template";+import { Watermark } from "./Watermark";-export { AddressBlock, Footer, Header, Note, Summary, Template };+export {+ AddressBlock,+ Footer,+ Header,+ LogoImage,+ Note,+ Summary,+ Template,+ Watermark+};diff --git a/packages/documents/src/pdf/fonts.ts b/packages/documents/src/pdf/fonts.tsnew file mode 100644index 0000000000..1cf60df8a3--- /dev/null+++ b/packages/documents/src/pdf/fonts.ts@@ -0,0 +1,82 @@+import { Font } from "@react-pdf/renderer";++/**+ * Google fonts offered in the template editor, registered on demand at render+ * time. Inter is registered statically in Template; Helvetica / Times-Roman /+ * Courier are PDF standard fonts and need no registration.+ *+ * react-pdf can render TTF/WOFF but NOT WOFF2, so we fetch the CSS2 stylesheet+ * with a legacy User-Agent that makes Google serve TTF `src` URLs, then parse+ * one TTF per weight and register them.+ */+const GOOGLE_FONTS: Record<string, { family: string; weights: number[] }> = {+ Roboto: { family: "Roboto", weights: [400, 700] },+ "Open Sans": { family: "Open Sans", weights: [400, 700] },+ Lato: { family: "Lato", weights: [400, 700] },+ Montserrat: { family: "Montserrat", weights: [400, 700] },+ Merriweather: { family: "Merriweather", weights: [400, 700] },+ "Playfair Display": { family: "Playfair Display", weights: [400, 700] },+ Lora: { family: "Lora", weights: [400, 700] }+};++// IE6 UA — Google serves plain TTF (no woff/woff2) to it.+const TTF_USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";++const done = new Set<string>();+const inFlight = new Map<string, Promise<void>>();++/**+ * Ensure `family` is registered with react-pdf before rendering. No-op for+ * built-ins, Inter, or unknown families. Best-effort: on any failure the font+ * is simply left unregistered (Template falls back to a safe font).+ */+export async function ensureFont(family: string): Promise<void> {+ const meta = GOOGLE_FONTS[family];+ if (!meta || done.has(family)) return;++ let pending = inFlight.get(family);+ if (!pending) {+ pending = registerGoogleFont(meta)+ .catch(() => {+ // Font load failure is non-fatal; PDF falls back to the default face.+ })+ .finally(() => {+ done.add(family);+ inFlight.delete(family);+ });+ inFlight.set(family, pending);+ }+ return pending;+}++async function registerGoogleFont(meta: {+ family: string;+ weights: number[];+}): Promise<void> {+ const url = `https://fonts.googleapis.com/css2?family=${meta.family.replace(+ / /g,+ "+"+ )}:wght@${meta.weights.join(";")}`;++ const res = await fetch(url, { headers: { "User-Agent": TTF_USER_AGENT } });+ if (!res.ok) return;+ const css = await res.text();++ // CSS2 emits one or more @font-face per weight (split by unicode-range);+ // keep the first TTF src for each weight.+ const fonts: { src: string; fontWeight: number }[] = [];+ const seen = new Set<number>();+ const re =+ /font-weight:\s*(\d+);[\s\S]*?src:\s*url\((https:\/\/fonts\.gstatic\.com\/[^)]+?\.ttf)\)/g;+ let match: RegExpExecArray | null;+ while ((match = re.exec(css)) !== null) {+ const weight = Number(match[1]);+ if (seen.has(weight)) continue;+ seen.add(weight);+ fonts.push({ src: match[2]!, fontWeight: weight });+ }++ if (fonts.length > 0) {+ Font.register({ family: meta.family, fonts });+ }+}diff --git a/packages/documents/src/pdf/index.ts b/packages/documents/src/pdf/index.tsindex f575c1512e..71966de565 100644--- a/packages/documents/src/pdf/index.ts+++ b/packages/documents/src/pdf/index.ts@@ -1,16 +1,25 @@import { Footer } from "./components";+import { ensureFont } from "./fonts";import IssuePDF from "./IssuePDF";+import { SAMPLE_ISSUE } from "./issue.samples";import JobTravelerPDF, { JobTravelerPageContent } from "./JobTravelerPDF";+import { SAMPLE_JOB_TRAVELER } from "./jobTraveler.samples";import KanbanLabelPDF from "./KanbanLabelPDF";import PackingSlipPDF from "./PackingSlipPDF";import ProductLabelPDF from "./ProductLabelPDF";import PurchaseOrderPDF from "./PurchaseOrderPDF";+import { DOCUMENT_PDFS } from "./preview-documents";import QuotePDF from "./QuotePDF";import SalesInvoicePDF from "./SalesInvoicePDF";import SalesOrderPDF from "./SalesOrderPDF";import StockTransferPDF from "./StockTransferPDF";import StorageUnitLabelPDF from "./StorageUnitLabelPDF";+import { SAMPLE_SALES_ORDER } from "./salesOrder.samples";+import { SAMPLE_SALES_INVOICE } from "./samples";+import { SAMPLE_TRACKING_LABEL } from "./trackingLabel.samples";export {+ DOCUMENT_PDFS,+ ensureFont,Footer,IssuePDF,JobTravelerPageContent,@@ -21,6 +30,11 @@ export {PurchaseOrderPDF,QuotePDF,SalesInvoicePDF,+ SAMPLE_ISSUE,+ SAMPLE_JOB_TRAVELER,+ SAMPLE_SALES_INVOICE,+ SAMPLE_SALES_ORDER,+ SAMPLE_TRACKING_LABEL,SalesOrderPDF,StockTransferPDF,StorageUnitLabelPDFdiff --git a/packages/documents/src/pdf/issue.samples.ts b/packages/documents/src/pdf/issue.samples.tsnew file mode 100644index 0000000000..04754c1ee5--- /dev/null+++ b/packages/documents/src/pdf/issue.samples.ts@@ -0,0 +1,121 @@+/** Sample data for previewing the Issue template. Cast `any`. */+export const SAMPLE_ISSUE = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ addressLine1: "1 Industrial Way",+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US",+ logoLight: null,+ logoLightIcon: null+ },+ nonConformance: {+ id: "nc-1",+ nonConformanceId: "NCR-000241",+ name: "Surface finish out of spec",+ status: "In Progress",+ nonConformanceTypeId: "nct-1",+ createdBy: "user-1",+ openDate: "2026-06-02",+ closeDate: null,+ customFields: {},+ content: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ {+ type: "text",+ text: "Anodized surface shows visible streaking on 12 of 100 parts. Suspected rack contact points during the anodize bath."+ }+ ]+ }+ ]+ }+ },+ nonConformanceTypes: [+ { id: "nct-1", name: "Cosmetic Defect" },+ { id: "nct-2", name: "Dimensional" }+ ],+ actionTasks: [+ {+ id: "task-1",+ sortOrder: 1,+ actionTypeId: "ra-1",+ assignee: "user-1",+ completedDate: "2026-06-04",+ supplier: null,+ notes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ {+ type: "text",+ text: "Re-racked affected parts and re-anodized."+ }+ ]+ }+ ]+ }+ },+ {+ id: "task-2",+ sortOrder: 2,+ actionTypeId: "ra-2",+ assignee: null,+ completedDate: null,+ supplier: { name: "Apex Anodizing" },+ notes: {}+ }+ ],+ requiredActions: [+ { id: "ra-1", name: "Corrective Action" },+ { id: "ra-2", name: "Containment" }+ ],+ reviewers: [+ {+ id: "rev-1",+ title: "Quality Manager",+ status: "Approved",+ notes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ { type: "text", text: "Disposition: use as-is after rework." }+ ]+ }+ ]+ }+ },+ { id: "rev-2", title: "Engineering", status: "Pending", notes: {} }+ ],+ items: [],+ associations: {+ items: [+ {+ id: "a-1",+ documentReadableId: "WIDGET-100",+ disposition: "Rework",+ quantity: 12+ }+ ],+ customers: [{ id: "a-2", documentReadableId: "Globex Corporation" }],+ suppliers: [],+ jobOperations: [{ id: "a-3", documentReadableId: "JOB-002310 / Op 30" }],+ purchaseOrderLines: [],+ salesOrderLines: [{ id: "a-4", documentReadableId: "SO-001188" }],+ shipmentLines: [],+ receiptLines: [],+ trackedEntities: []+ },+ assignees: { "user-1": "Dana Cruz" },+ jobOperationStepRecords: [],+ operationToJobId: {}+} as any;diff --git a/packages/documents/src/pdf/jobTraveler.samples.ts b/packages/documents/src/pdf/jobTraveler.samples.tsnew file mode 100644index 0000000000..06342f6d15--- /dev/null+++ b/packages/documents/src/pdf/jobTraveler.samples.ts@@ -0,0 +1,104 @@+/** Sample data for previewing the Job Traveler template. Cast `any`. */+export const SAMPLE_JOB_TRAVELER = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ addressLine1: "1 Industrial Way",+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US",+ logoLight: null,+ logoLightIcon: null+ },+ job: {+ id: "job-1",+ jobId: "JOB-002310",+ itemReadableIdWithRevision: "WIDGET-100 / A",+ quantity: 100,+ unitOfMeasureCode: "EA",+ scrapQuantity: 5,+ startDate: "2026-06-01",+ dueDate: "2026-06-18",+ deadlineType: "Hard Deadline",+ salesOrderId: "so-1",+ salesOrderLineId: "sol-1",+ salesOrderReadableId: "SO-001188",+ customFields: {},+ notes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ {+ type: "text",+ text: "Handle finished parts with gloves to avoid fingerprints on the anodized surface."+ }+ ]+ }+ ]+ }+ },+ jobMakeMethod: { id: "jmm-1", version: 2 },+ jobOperations: [+ {+ id: "op-1",+ order: 1,+ operationOrder: "After Previous",+ description: "CNC Mill — rough + finish",+ operationType: "Inside",+ setupTime: 0.5,+ setupUnit: "Hours",+ laborTime: 2,+ laborUnit: "Hours",+ machineTime: 1.5,+ machineUnit: "Hours",+ targetQuantity: 100,+ workInstruction: null,+ jobOperationStep: []+ },+ {+ id: "op-2",+ order: 2,+ operationOrder: "After Previous",+ description: "Deburr & inspect",+ operationType: "Inside",+ setupTime: 0,+ setupUnit: "Hours",+ laborTime: 0.75,+ laborUnit: "Hours",+ machineTime: 0,+ machineUnit: "Hours",+ targetQuantity: 100,+ workInstruction: null,+ jobOperationStep: []+ },+ {+ id: "op-3",+ order: 3,+ operationOrder: "After Previous",+ description: "Anodize (outside vendor)",+ operationType: "Outside",+ setupTime: 0,+ setupUnit: "Hours",+ laborTime: 0,+ laborUnit: "Hours",+ machineTime: 0,+ machineUnit: "Hours",+ targetQuantity: 100,+ workInstruction: null,+ jobOperationStep: []+ }+ ],+ customer: { id: "cust-1", name: "Globex Corporation" },+ item: {+ id: "item-1",+ name: "Precision Widget, anodized",+ readableIdWithRevision: "WIDGET-100 / A",+ itemTrackingType: "Batch"+ },+ batchNumber: "BATCH-44021",+ thumbnail: null,+ includeWorkInstructions: false+} as any;diff --git a/packages/documents/src/pdf/packingSlip.samples.ts b/packages/documents/src/pdf/packingSlip.samples.tsnew file mode 100644index 0000000000..a3cf991a2f--- /dev/null+++ b/packages/documents/src/pdf/packingSlip.samples.ts@@ -0,0 +1,69 @@+/** Sample data for previewing the Packing Slip template. Cast `any`. */+export const SAMPLE_PACKING_SLIP = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ countryCode: "US",+ city: "Detroit",+ taxId: null,+ logoLight: null,+ logoLightIcon: null+ },+ customer: { name: "Globex Corporation" },+ customerReference: "PO-88421",+ sourceDocument: "Sales Order",+ sourceDocumentId: "SO-001042",+ shipment: {+ shipmentId: "SHP-001042",+ postingDate: "2026-06-05",+ trackingNumber: "1Z999AA10123456784",+ externalNotes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Handle with care." }]+ }+ ]+ }+ },+ shipmentLines: [+ {+ id: "line-1",+ itemReadableId: "WIDGET-100",+ description: "Precision Widget, anodized",+ shippedQuantity: 10,+ orderQuantity: 10,+ unitOfMeasure: "EA"+ },+ {+ id: "line-2",+ itemReadableId: "BRACKET-22",+ description: "Mounting Bracket",+ shippedQuantity: 4,+ orderQuantity: 4,+ unitOfMeasure: "EA"+ }+ ],+ shippingAddress: {+ addressLine1: "500 Commerce Blvd",+ city: "Chicago",+ stateProvince: "IL",+ postalCode: "60601",+ countryCode: "US"+ },+ paymentTerm: { id: "net30", name: "Net 30" },+ shippingMethod: { id: "ground", name: "Ground" },+ terms: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Goods received in good condition." }]+ }+ ]+ },+ trackedEntities: [],+ thumbnails: {},+ locale: "en-US"+} as any;diff --git a/packages/documents/src/pdf/preview-documents.tsx b/packages/documents/src/pdf/preview-documents.tsxnew file mode 100644index 0000000000..75556a4369--- /dev/null+++ b/packages/documents/src/pdf/preview-documents.tsx@@ -0,0 +1,51 @@+import type { ComponentType } from "react";+import type { DocumentTemplateType } from "../template";+import IssuePDF from "./IssuePDF";+import { SAMPLE_ISSUE } from "./issue.samples";+import JobTravelerPDF from "./JobTravelerPDF";+import { SAMPLE_JOB_TRAVELER } from "./jobTraveler.samples";+import PackingSlipPDF from "./PackingSlipPDF";+import ProductLabelPDF from "./ProductLabelPDF";+import PurchaseOrderPDF from "./PurchaseOrderPDF";+import { SAMPLE_PACKING_SLIP } from "./packingSlip.samples";+import { SAMPLE_PURCHASE_ORDER } from "./purchaseOrder.samples";+import QuotePDF from "./QuotePDF";+import { SAMPLE_QUOTE } from "./quote.samples";+import SalesInvoicePDF from "./SalesInvoicePDF";+import SalesOrderPDF from "./SalesOrderPDF";+import StockTransferPDF from "./StockTransferPDF";+import { SAMPLE_SALES_ORDER } from "./salesOrder.samples";+import { SAMPLE_SALES_INVOICE } from "./samples";+import { SAMPLE_STOCK_TRANSFER } from "./stockTransfer.samples";+import { SAMPLE_TRACKING_LABEL } from "./trackingLabel.samples";++/**+ * Maps a document type to its PDF component + sample fixture, so the template+ * preview route can render any supported document generically. Adding a doc =+ * add an entry here (plus its enum / default template / registry).+ */+type PreviewEntry = { Component: ComponentType<any>; sample: any };++export const DOCUMENT_PDFS: Record<DocumentTemplateType, PreviewEntry> = {+ salesInvoice: { Component: SalesInvoicePDF, sample: SAMPLE_SALES_INVOICE },+ salesOrder: { Component: SalesOrderPDF, sample: SAMPLE_SALES_ORDER },+ purchaseOrder: {+ Component: PurchaseOrderPDF,+ sample: SAMPLE_PURCHASE_ORDER+ },+ quote: { Component: QuotePDF, sample: SAMPLE_QUOTE },+ packingSlip: { Component: PackingSlipPDF, sample: SAMPLE_PACKING_SLIP },+ stockTransfer: {+ Component: StockTransferPDF,+ sample: SAMPLE_STOCK_TRANSFER+ },+ jobTraveler: {+ Component: JobTravelerPDF,+ sample: SAMPLE_JOB_TRAVELER+ },+ issue: { Component: IssuePDF, sample: SAMPLE_ISSUE },+ trackingLabel: {+ Component: ProductLabelPDF,+ sample: SAMPLE_TRACKING_LABEL+ }+};diff --git a/packages/documents/src/pdf/purchaseOrder.samples.ts b/packages/documents/src/pdf/purchaseOrder.samples.tsnew file mode 100644index 0000000000..eb3887681e--- /dev/null+++ b/packages/documents/src/pdf/purchaseOrder.samples.ts@@ -0,0 +1,96 @@+/** Sample data for previewing the Purchase Order template. Cast `any`. */+export const SAMPLE_PURCHASE_ORDER = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ addressLine1: "1 Industrial Way",+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US",+ baseCurrencyCode: "USD",+ vatNumber: null,+ logoLight: null,+ logoLightIcon: null,+ logoWatermark: null,+ eori: null+ },+ purchaseOrder: {+ purchaseOrderId: "PO-001042",+ currencyCode: "USD",+ orderDate: "2026-06-01",+ supplierReference: "Q-55120",+ paymentTermId: "net30",+ supplierShippingCost: 0,+ purchaseOrderType: "Purchase",+ externalNotes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Please confirm lead times." }]+ }+ ]+ }+ },+ purchaseOrderLines: [+ {+ id: "line-1",+ purchaseOrderLineType: "Part",+ itemReadableId: "STEEL-BAR-50",+ description: "Steel Bar, 50mm",+ purchaseQuantity: 100,+ purchaseUnitOfMeasureCode: "EA",+ supplierUnitPrice: 5.22,+ supplierTaxAmount: 78.3,+ taxPercent: 0.15,+ requiredDate: "2026-06-20",+ externalNotes: {}+ },+ {+ id: "line-2",+ purchaseOrderLineType: "Part",+ itemReadableId: "BOLT-M8",+ description: "M8 Bolt, zinc",+ purchaseQuantity: 500,+ purchaseUnitOfMeasureCode: "EA",+ supplierUnitPrice: 0.12,+ supplierTaxAmount: 9,+ taxPercent: 0.15,+ requiredDate: "2026-06-20",+ externalNotes: {}+ }+ ],+ purchaseOrderLocations: {+ supplierName: "Steelworks Ltd",+ supplierAddressLine1: "200 Foundry Rd",+ supplierCity: "Pittsburgh",+ supplierStateProvince: "PA",+ supplierPostalCode: "15201",+ supplierCountryName: "United States",+ deliveryName: "Acme Manufacturing Co.",+ deliveryAddressLine1: "1 Industrial Way",+ deliveryCity: "Detroit",+ deliveryStateProvince: "MI",+ deliveryPostalCode: "48201",+ deliveryCountryName: "United States",+ dropShipment: false,+ companyCountryName: "United States"+ },+ paymentTerms: [{ id: "net30", name: "Net 30" }],+ terms: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ {+ type: "text",+ text: "Goods remain the property of the buyer until inspection and acceptance."+ }+ ]+ }+ ]+ },+ locale: "en-US"+} as any;diff --git a/packages/documents/src/pdf/quote.samples.ts b/packages/documents/src/pdf/quote.samples.tsnew file mode 100644index 0000000000..f4c1b4a6f3--- /dev/null+++ b/packages/documents/src/pdf/quote.samples.ts@@ -0,0 +1,123 @@+/** Sample data for previewing the Quote template. Cast `any`. */+export const SAMPLE_QUOTE = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ addressLine1: "1 Industrial Way",+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US",+ baseCurrencyCode: "USD",+ logoLight: null,+ logoLightIcon: null,+ logoWatermark: null,+ eori: null+ },+ exchangeRate: 1,+ quote: {+ quoteId: "QUO-001042",+ currencyCode: "USD",+ expirationDate: "2026-07-01",+ customerReference: "RFQ-88421",+ externalNotes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Pricing valid for 30 days." }]+ }+ ]+ }+ },+ quoteLines: [+ {+ id: "line-1",+ status: "Active",+ itemReadableId: "WIDGET-100",+ description: "Precision Widget, anodized",+ quantity: [10],+ unitPricePrecision: 2,+ taxPercent: 0.06,+ additionalCharges: {},+ externalNotes: {}+ },+ {+ id: "line-2",+ status: "Active",+ itemReadableId: "BRACKET-22",+ description: "Mounting Bracket",+ quantity: [4],+ unitPricePrecision: 2,+ taxPercent: 0.06,+ additionalCharges: {},+ externalNotes: {}+ },+ {+ // Long title + description — exercises the Line Items text overflow+ // option (wrap grows the row; truncate clamps each to one line).+ id: "line-3",+ status: "Active",+ itemReadableId:+ "ASSEMBLY-HOUSING-ANODIZED-LONG-PART-NUMBER-FOR-OVERFLOW-0001",+ description:+ "Fully machined precision aluminium housing assembly with anodized finish, integrated mounting flange, and laser-etched serial marking — used to verify line-item text wrap versus truncate behaviour",+ quantity: [2],+ unitPricePrecision: 2,+ taxPercent: 0.06,+ additionalCharges: {},+ externalNotes: {}+ }+ ],+ quoteLinePrices: [+ {+ quoteLineId: "line-1",+ quantity: 10,+ convertedUnitPrice: 24.5,+ convertedNetExtendedPrice: 245,+ convertedShippingCost: 0,+ leadTime: 14+ },+ {+ quoteLineId: "line-2",+ quantity: 4,+ convertedUnitPrice: 12,+ convertedNetExtendedPrice: 48,+ convertedShippingCost: 0,+ leadTime: 7+ },+ {+ quoteLineId: "line-3",+ quantity: 2,+ convertedUnitPrice: 120,+ convertedNetExtendedPrice: 240,+ convertedShippingCost: 0,+ leadTime: 21+ }+ ],+ quoteCustomerDetails: {+ customerName: "Globex Corporation",+ customerAddressLine1: "500 Commerce Blvd",+ customerCity: "Chicago",+ customerStateProvince: "IL",+ customerPostalCode: "60601",+ customerCountryName: "United States"+ },+ payment: { paymentTermId: "net30" },+ shipment: { shippingCost: 0 },+ paymentTerms: [{ id: "net30", name: "Net 30" }],+ shippingMethods: [],+ terms: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ { type: "text", text: "Prices exclude applicable duties and taxes." }+ ]+ }+ ]+ },+ thumbnails: {},+ locale: "en-US"+} as any;diff --git a/packages/documents/src/pdf/salesOrder.samples.ts b/packages/documents/src/pdf/salesOrder.samples.tsnew file mode 100644index 0000000000..963a338782--- /dev/null+++ b/packages/documents/src/pdf/salesOrder.samples.ts@@ -0,0 +1,96 @@+/**+ * Sample data for previewing the Sales Order template. Cast to `any` — it only+ * needs the fields the blocks read.+ */+export const SAMPLE_SALES_ORDER = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ addressLine1: "1 Industrial Way",+ addressLine2: null,+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US",+ baseCurrencyCode: "USD",+ logoLight: null,+ logoLightIcon: null,+ logoWatermark: null,+ eori: null+ },+ salesOrder: {+ salesOrderId: "SO-001042",+ currencyCode: "USD",+ exchangeRate: 1,+ orderDate: "2026-06-01",+ receiptRequestedDate: "2026-06-20",+ customerReference: "PO-88421",+ paymentTermId: "net30",+ shippingMethodId: "ground",+ shippingCost: 0,+ externalNotes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Thank you for your business." }]+ }+ ]+ }+ },+ salesOrderLines: [+ {+ id: "line-1",+ salesOrderLineType: "Part",+ itemReadableId: "WIDGET-100",+ description: "Precision Widget, anodized",+ saleQuantity: 10,+ unitOfMeasureCode: "EA",+ convertedUnitPrice: 24.5,+ convertedAddOnCost: 0,+ convertedNonTaxableAddOnCost: 0,+ convertedShippingCost: 0,+ taxPercent: 0.06,+ externalNotes: {}+ },+ {+ id: "line-2",+ salesOrderLineType: "Part",+ itemReadableId: "BRACKET-22",+ description: "Mounting Bracket",+ saleQuantity: 4,+ unitOfMeasureCode: "EA",+ convertedUnitPrice: 12,+ convertedAddOnCost: 5,+ convertedNonTaxableAddOnCost: 0,+ convertedShippingCost: 0,+ taxPercent: 0.06,+ externalNotes: {}+ }+ ],+ salesOrderLocations: {+ customerName: "Globex Corporation",+ customerAddressLine1: "500 Commerce Blvd",+ customerCity: "Chicago",+ customerStateProvince: "IL",+ customerPostalCode: "60601",+ customerCountryName: "United States"+ },+ paymentTerms: [{ id: "net30", name: "Net 30" }],+ shippingMethods: [{ id: "ground", name: "Ground" }],+ terms: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ {+ type: "text",+ text: "Payment due within 30 days. Late payments accrue 1.5% monthly interest."+ }+ ]+ }+ ]+ },+ locale: "en-US"+} as any;diff --git a/packages/documents/src/pdf/samples.ts b/packages/documents/src/pdf/samples.tsnew file mode 100644index 0000000000..849ed5989e--- /dev/null+++ b/packages/documents/src/pdf/samples.ts@@ -0,0 +1,105 @@+/**+ * Representative sample data for previewing a document template without a real+ * record. Co-located with the PDFs (the "sample" half of Bindery's+ * schema+sample idea; the "schema" half is the merge-field catalog in+ * template/merge.ts). Cast to `any` — it only needs the fields blocks read.+ */+export const SAMPLE_SALES_INVOICE = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ addressLine1: "1 Industrial Way",+ addressLine2: null,+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US",+ baseCurrencyCode: "USD",+ logoLightIcon: null,+ logoWatermark: null,+ eori: null+ },+ salesInvoice: {+ invoiceId: "INV-001042",+ currencyCode: "USD",+ exchangeRate: 1,+ dateIssued: "2026-06-01",+ dateDue: "2026-07-01",+ customerReference: "PO-88421",+ paymentTermId: "net30",+ externalNotes: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Thank you for your business." }]+ }+ ]+ }+ },+ salesInvoiceLines: [+ {+ id: "line-1",+ invoiceLineType: "Part",+ itemReadableId: "WIDGET-100",+ description: "Precision Widget, anodized",+ quantity: 10,+ unitOfMeasureCode: "EA",+ convertedUnitPrice: 24.5,+ convertedAddOnCost: 0,+ convertedNonTaxableAddOnCost: 0,+ convertedShippingCost: 0,+ taxPercent: 0.06,+ externalNotes: {}+ },+ {+ id: "line-2",+ invoiceLineType: "Part",+ itemReadableId: "BRACKET-22",+ description: "Mounting Bracket",+ quantity: 4,+ unitOfMeasureCode: "EA",+ convertedUnitPrice: 12,+ convertedAddOnCost: 5,+ convertedNonTaxableAddOnCost: 0,+ convertedShippingCost: 0,+ taxPercent: 0.06,+ externalNotes: {}+ }+ ],+ salesInvoiceLocations: {+ customerName: "Globex Corporation",+ customerAddressLine1: "500 Commerce Blvd",+ customerCity: "Chicago",+ customerStateProvince: "IL",+ customerPostalCode: "60601",+ customerCountryName: "United States",+ invoiceCustomerName: "Globex Corporation",+ invoiceAddressLine1: "500 Commerce Blvd",+ invoiceCity: "Chicago",+ invoiceStateProvince: "IL",+ invoicePostalCode: "60601",+ invoiceCountryName: "United States"+ },+ salesInvoiceShipment: {+ shippingCost: 0,+ shippingMethodId: "ground"+ },+ paymentTerms: [{ id: "net30", name: "Net 30" }],+ shippingMethods: [{ id: "ground", name: "Ground" }],+ terms: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [+ {+ type: "text",+ text: "Payment due within 30 days. Late payments accrue 1.5% monthly interest."+ }+ ]+ }+ ]+ },+ locale: "en-US"+} as any;diff --git a/packages/documents/src/pdf/stockTransfer.samples.ts b/packages/documents/src/pdf/stockTransfer.samples.tsnew file mode 100644index 0000000000..a23bb5e1b5--- /dev/null+++ b/packages/documents/src/pdf/stockTransfer.samples.ts@@ -0,0 +1,46 @@+/** Sample data for previewing the Stock Transfer template. Cast `any`. */+export const SAMPLE_STOCK_TRANSFER = {+ company: {+ id: "sample",+ name: "Acme Manufacturing Co.",+ addressLine1: "1 Industrial Way",+ city: "Detroit",+ stateProvince: "MI",+ postalCode: "48201",+ countryCode: "US",+ logoLight: null,+ logoLightIcon: null+ },+ stockTransfer: {+ stockTransferId: "ST-001042",+ createdAt: "2026-06-05",+ assignee: "Jordan Lee"+ },+ stockTransferLines: [+ {+ id: "line-1",+ itemReadableId: "WIDGET-100",+ itemDescription: "Precision Widget, anodized",+ quantity: 50,+ unitOfMeasure: "EA",+ fromStorageUnitName: "Bin A1",+ toStorageUnitName: "Bin B3",+ requiresSerialTracking: false,+ requiresBatchTracking: false+ },+ {+ id: "line-2",+ itemReadableId: "BRACKET-22",+ itemDescription: "Mounting Bracket",+ quantity: 20,+ unitOfMeasure: "EA",+ fromStorageUnitName: "Bin A2",+ toStorageUnitName: "Bin C1",+ requiresSerialTracking: false,+ requiresBatchTracking: false+ }+ ],+ location: { name: "Main Warehouse" },+ thumbnails: {},+ locale: "en-US"+} as any;diff --git a/packages/documents/src/pdf/trackingLabel.samples.ts b/packages/documents/src/pdf/trackingLabel.samples.tsnew file mode 100644index 0000000000..0945392dfe--- /dev/null+++ b/packages/documents/src/pdf/trackingLabel.samples.ts@@ -0,0 +1,22 @@+/** Sample data for previewing the Tracking Label template. Cast `any`. */+export const SAMPLE_TRACKING_LABEL = {+ items: [+ {+ itemId: "SD08810002",+ revision: "0",+ quantity: 1,+ number: "04/06/2026",+ trackedEntityId: "dtClCvNm9blDY0H3FXmDC",+ trackingType: "Serial"+ }+ ],+ labelSize: {+ id: "preview",+ name: "Preview",+ width: 4,+ height: 2,+ rows: 1,+ columns: 1,+ rotated: false+ }+} as any;diff --git a/packages/documents/src/qr/barcode.ts b/packages/documents/src/qr/barcode.tsnew file mode 100644index 0000000000..ea7e603379--- /dev/null+++ b/packages/documents/src/qr/barcode.ts@@ -0,0 +1,26 @@+import bwipjs from "@bwip-js/node";++export type BarcodeSymbology = "pdf417" | "code128" | "datamatrix" | "qrcode";++/**+ * Render a barcode to a base64 PNG data URL. react-pdf's `<Image src>` resolves+ * the returned promise, so it can be used directly in JSX. Mirrors+ * `generateQRCode` but with a selectable symbology.+ */+export async function generateBarcode(+ text: string,+ symbology: BarcodeSymbology,+ opts: { scale?: number; height?: number; includetext?: boolean } = {}+): Promise<string> {+ const buffer = await bwipjs.toBuffer({+ bcid: symbology,+ text: text || " ",+ scale: opts.scale ?? 3,+ // `height` distorts 2D square codes (QR / DataMatrix) — only set it for the+ // linear/stacked symbologies that need a bar height.+ ...(opts.height ? { height: opts.height } : {}),+ includetext: opts.includetext ?? false,+ textxalign: "center"+ });+ return `data:image/png;base64,${buffer.toString("base64")}`;+}diff --git a/packages/documents/src/template/defaults.ts b/packages/documents/src/template/defaults.tsnew file mode 100644index 0000000000..bf16872d0e--- /dev/null+++ b/packages/documents/src/template/defaults.ts@@ -0,0 +1,707 @@+import type { JSONContent } from "@carbon/react";+import type {+ DocumentBlock,+ DocumentBlockType,+ DocumentSettings,+ DocumentTemplate,+ DocumentTemplateType,+ DocumentTheme,+ ResolvedSection+} from "./schema";+import {+ CURRENT_TEMPLATE_FORMAT_VERSION,+ DEFAULT_DOCUMENT_SETTINGS,+ DEFAULT_HEADER_OPTIONS,+ DEFAULT_LINE_ITEMS_OPTIONS,+ DEFAULT_THEME+} from "./schema";++/** Empty tiptap doc — renders nothing, so referencing it keeps output identical. */+function emptyDoc(): JSONContent {+ return { type: "doc", content: [] };+}++/**+ * Stable ids for the system-provided header/footer sections. Every company+ * gets these in the library (read-only) and every default template references+ * them, so the page header/footer is customizable out of the box without a+ * per-company DB seed. They start empty — the structural footer (registration+ * line + page numbers, see pdf/components/Footer) renders as it does today;+ * editing one forks it into a real `documentSection` row.+ */+export const BUILT_IN_SECTION_IDS = {+ header: "system-header",+ footer: "system-footer"+} as const;++export const BUILT_IN_SECTIONS: ResolvedSection[] = [+ {+ id: BUILT_IN_SECTION_IDS.header,+ name: "Default Header",+ placement: "header",+ content: emptyDoc(),+ config: { ...DEFAULT_HEADER_OPTIONS },+ builtIn: true+ },+ {+ id: BUILT_IN_SECTION_IDS.footer,+ name: "Default Footer",+ placement: "footer",+ content: emptyDoc(),+ builtIn: true+ }+];++export function isBuiltInSectionId(id: string): boolean {+ return BUILT_IN_SECTIONS.some((s) => s.id === id);+}++export function getBuiltInSection(id: string): ResolvedSection | undefined {+ return BUILT_IN_SECTIONS.find((s) => s.id === id);+}++/**+ * Prepend the system sections to a company's stored rows (DB rows win on id+ * collision, so a forked/customized default replaces the built-in). Use this+ * anywhere the full section list is shown or resolved.+ */+export function withBuiltInSections<T extends { id: string }>(+ rows: T[]+): (T | ResolvedSection)[] {+ const builtInIds = new Set(BUILT_IN_SECTIONS.map((s) => s.id));+ const overridden = new Set(rows.map((r) => r.id));+ // A built-in section the user has customized exists as a DB row — keep its+ // `builtIn` flag so it still reads as System (editable, not deletable).+ const flaggedRows = rows.map((r) =>+ builtInIds.has(r.id) ? { ...r, builtIn: true } : r+ );+ return [+ ...BUILT_IN_SECTIONS.filter((s) => !overridden.has(s.id)),+ ...flaggedRows+ ];+}++export interface BlockMeta {+ /** Human label shown in the editor block list. */+ label: string;+ /** Built-in blocks are data-bound and cannot be added/removed by users. */+ isBuiltIn: boolean;+ /** Whether the user may delete the block (extension blocks only). */+ removable: boolean;+ /** Whether the user may hide the block. Data-critical blocks stay visible. */+ hideable: boolean;+ /** Whether the block appears in the "Add block" menu. */+ addable: boolean;+}++export const BLOCK_META: Record<DocumentBlockType, BlockMeta> = {+ header: {+ label: "Header",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ watermark: {+ label: "Watermark",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ parties: {+ label: "Addresses & Details",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ notes: {+ label: "Notes",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ details: {+ label: "Details",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ lineItems: {+ label: "Line Items",+ isBuiltIn: true,+ removable: false,+ hideable: false,+ addable: false+ },+ summary: {+ label: "Summary",+ isBuiltIn: true,+ removable: false,+ hideable: false,+ addable: false+ },+ terms: {+ label: "Terms & Conditions",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ jobDetails: {+ label: "Job Details",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ operations: {+ label: "Operations",+ isBuiltIn: true,+ removable: false,+ hideable: false,+ addable: false+ },+ issueDetails: {+ label: "Issue Details",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ associations: {+ label: "Associations",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ actionTasks: {+ label: "Action Tasks",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ reviewers: {+ label: "Reviewers",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ labelHeading: {+ label: "Item ID",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ labelRevision: {+ label: "Revision",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ labelQuantity: {+ label: "Quantity",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ labelTracking: {+ label: "Serial / Batch",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ labelEntityId: {+ label: "Identifier",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ labelBarcode: {+ // The scannable code (QR / barcode) — built-in, configurable symbology.+ label: "Code",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ labelLogo: {+ // Built-in like the Code block — toggle it on/off, not add/remove.+ label: "Logo",+ isBuiltIn: true,+ removable: false,+ hideable: true,+ addable: false+ },+ richText: {+ label: "Rich Text",+ isBuiltIn: false,+ removable: true,+ hideable: true,+ addable: true+ },+ keyValue: {+ label: "Key-Value List",+ isBuiltIn: false,+ removable: true,+ hideable: true,+ addable: true+ },+ spacer: {+ label: "Spacer / Divider",+ isBuiltIn: false,+ removable: true,+ hideable: true,+ addable: true+ },+ shared: {+ // Added via the "Shared section" submenu (lists real sections), not the+ // generic add menu — so addable is false.+ label: "Shared Section",+ isBuiltIn: false,+ removable: true,+ hideable: true,+ addable: false+ },+ customField: {+ // Added via the "Custom field" submenu (lists the record's fields).+ label: "Custom Field",+ isBuiltIn: false,+ removable: true,+ hideable: true,+ addable: false+ },+ field: {+ // Added via the label add menu ("Text" / "Key-value"), not the generic one.+ label: "Field",+ isBuiltIn: false,+ removable: true,+ hideable: true,+ addable: false+ }+};++/** Block types a user may append, in menu order. */+export const ADDABLE_BLOCK_TYPES = (+ Object.keys(BLOCK_META) as DocumentBlockType[]+).filter((type) => BLOCK_META[type].addable);++/**+ * Standard layout for a transactional document (quote, order, invoice, PO).+ * Mirrors the hardcoded section order in the existing PDFs so output is+ * identical until a user customizes. Built-in blocks use stable ids (not+ * nanoid) so defaults are deterministic.+ */+function transactionalBlocks(): DocumentBlock[] {+ return [+ {+ id: "watermark",+ type: "watermark",+ visible: true,+ opacity: 0.07,+ placement: "center",+ size: 50+ },+ { id: "header", type: "header", visible: true },+ { id: "parties", type: "parties", visible: true },+ { id: "notes", type: "notes", visible: true },+ { id: "lineItems", type: "lineItems", visible: true },+ { id: "summary", type: "summary", visible: true },+ { id: "terms", type: "terms", visible: true }+ ];+}++/** Standard layout for a fulfillment document (packing slip): no summary. */+function fulfillmentBlocks(): DocumentBlock[] {+ return [+ { id: "header", type: "header", visible: true },+ { id: "parties", type: "parties", visible: true },+ { id: "details", type: "details", visible: true },+ { id: "lineItems", type: "lineItems", visible: true },+ { id: "notes", type: "notes", visible: true },+ { id: "terms", type: "terms", visible: true }+ ];+}++/** Internal warehouse doc (stock transfer): header + details + line items. */+function transferBlocks(): DocumentBlock[] {+ return [+ { id: "header", type: "header", visible: true },+ { id: "details", type: "details", visible: true },+ { id: "lineItems", type: "lineItems", visible: true }+ ];+}++/** Manufacturing routing doc (job traveler): header + job box + ops + notes. */+function jobTravelerBlocks(): DocumentBlock[] {+ return [+ { id: "header", type: "header", visible: true },+ { id: "jobDetails", type: "jobDetails", visible: true },+ {+ id: "operations",+ type: "operations",+ visible: true,+ showWorkInstructions: false+ },+ { id: "notes", type: "notes", visible: true }+ ];+}++/**+ * Tracking label: per-field elements stacked vertically inside each label tile.+ * No header/footer chrome belongs to the label body itself.+ */+function labelBlocks(): DocumentBlock[] {+ return [+ { id: "labelHeading", type: "labelHeading", visible: true },+ { id: "labelRevision", type: "labelRevision", visible: true },+ { id: "labelQuantity", type: "labelQuantity", visible: true },+ { id: "labelTracking", type: "labelTracking", visible: true },+ {+ id: "labelLogo",+ type: "labelLogo",+ visible: false,+ variant: "mark"+ },+ {+ id: "labelCode",+ type: "labelBarcode",+ visible: true,+ symbology: "qrcode",+ value: "{label.trackedEntityId}",+ placement: "right"+ },+ {+ id: "labelEntityId",+ type: "labelEntityId",+ visible: true,+ value: "{label.trackedEntityId}"+ }+ ];+}++/** Quality doc (issue): header + details + associations + notes + tasks + MRB. */+function issueBlocks(): DocumentBlock[] {+ return [+ { id: "header", type: "header", visible: true },+ { id: "issueDetails", type: "issueDetails", visible: true },+ { id: "associations", type: "associations", visible: true },+ { id: "notes", type: "notes", visible: true },+ { id: "actionTasks", type: "actionTasks", visible: true },+ { id: "reviewers", type: "reviewers", visible: true }+ ];+}++/**+ * Default template per supported document type. Adding a document = wire its+ * PDF to consume a template, then add its default here + to the schema enum.+ */+export const DEFAULT_TEMPLATES: Record<DocumentTemplateType, DocumentTemplate> =+ {+ salesInvoice: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "salesInvoice",+ blocks: transactionalBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ salesOrder: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "salesOrder",+ blocks: transactionalBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ purchaseOrder: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "purchaseOrder",+ blocks: transactionalBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ quote: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "quote",+ blocks: transactionalBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ packingSlip: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "packingSlip",+ blocks: fulfillmentBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ stockTransfer: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "stockTransfer",+ blocks: transferBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ jobTraveler: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "jobTraveler",+ blocks: jobTravelerBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ issue: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "issue",+ blocks: issueBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ headerSectionId: BUILT_IN_SECTION_IDS.header,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ },+ trackingLabel: {+ formatVersion: CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType: "trackingLabel",+ blocks: labelBlocks(),+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS },+ // Labels print on a full letter sheet: no page header, but the footer+ // (page numbers) is on by default. Both are toggleable in the editor.+ headerSectionId: null,+ footerSectionId: BUILT_IN_SECTION_IDS.footer+ }+ };++/** @deprecated prefer getDefaultTemplate("salesInvoice"). Kept for callers. */+export const DEFAULT_SALES_INVOICE_TEMPLATE = DEFAULT_TEMPLATES.salesInvoice;++export function getDefaultTemplate(+ documentType: DocumentTemplateType+): DocumentTemplate {+ return DEFAULT_TEMPLATES[documentType];+}++interface StoredTemplate {+ formatVersion?: number | null;+ blocks?: DocumentBlock[] | null;+ theme?: Partial<DocumentTheme> | null;+ settings?: Partial<DocumentSettings> | null;+ headerSectionId?: string | null;+ footerSectionId?: string | null;+}++/**+ * Migrate a stored template's block list to the current format version. Today+ * v1 is the only version, so this is a pass-through — but it's the single seam+ * where future shape changes get upgraded on read.+ */+function migrateBlocks(+ blocks: DocumentBlock[],+ _from: number+): DocumentBlock[] {+ return blocks;+}++/**+ * Resolve a stored template row to a renderable template, falling back to the+ * type's default when nothing is stored. Built-in blocks that are missing from+ * a stored template are appended (hidden) so a section added in a later release+ * never silently disappears from existing customer templates.+ */+export function resolveTemplate(+ documentType: DocumentTemplateType,+ stored?: StoredTemplate | null+): DocumentTemplate {+ const fallback = getDefaultTemplate(documentType);+ if (!stored) {+ return {+ ...fallback,+ theme: { ...DEFAULT_THEME },+ settings: { ...DEFAULT_DOCUMENT_SETTINGS }+ };+ }++ const theme = { ...DEFAULT_THEME, ...(stored.theme ?? {}) };+ const settings = { ...DEFAULT_DOCUMENT_SETTINGS, ...(stored.settings ?? {}) };+ // A stored row carries explicit header/footer ids (null = "none" chosen by+ // the user). Only fall back to the default's ids when the field is absent.+ const headerSectionId =+ stored.headerSectionId !== undefined+ ? stored.headerSectionId+ : fallback.headerSectionId;+ const footerSectionId =+ stored.footerSectionId !== undefined+ ? stored.footerSectionId+ : fallback.footerSectionId;++ const formatVersion = CURRENT_TEMPLATE_FORMAT_VERSION;+ const storedBlocks = stored.blocks+ ? migrateBlocks(stored.blocks, stored.formatVersion ?? 1)+ : stored.blocks;++ if (!storedBlocks || storedBlocks.length === 0) {+ return {+ ...fallback,+ formatVersion,+ theme,+ settings,+ headerSectionId,+ footerSectionId+ };+ }++ const present = new Set(storedBlocks.map((b) => b.type));+ const missingBuiltIns = fallback.blocks+ .filter((b) => BLOCK_META[b.type].isBuiltIn && !present.has(b.type))+ .map((b) => ({ ...b, visible: false }));++ return {+ formatVersion,+ documentType,+ blocks: [...storedBlocks, ...missingBuiltIns],+ theme,+ settings,+ headerSectionId,+ footerSectionId+ };+}++/**+ * Whether a document's Line Items block renders thumbnails — the per-template+ * replacement for the old company-level `includeThumbnailsOn*Pdfs` flags. Used+ * by the file routes to decide whether to fetch the (expensive) image data.+ */+export function templateShowsThumbnails(+ template: StoredTemplate | null,+ documentType: DocumentTemplateType+): boolean {+ const resolved = resolveTemplate(documentType, template);+ const block = resolved.blocks.find(+ (b) => b.type === "lineItems" && b.visible+ );+ if (!block || block.type !== "lineItems") return false;+ return { ...DEFAULT_LINE_ITEMS_OPTIONS, ...block.options }.showThumbnails;+}++/** Collect every section id a template references (body blocks + header/footer). */+export function collectSectionIds(template: {+ blocks: DocumentBlock[];+ headerSectionId?: string | null;+ footerSectionId?: string | null;+}): string[] {+ const ids = new Set<string>();+ for (const block of template.blocks) {+ if (block.type === "shared" && block.sectionId) ids.add(block.sectionId);+ }+ if (template.headerSectionId) ids.add(template.headerSectionId);+ if (template.footerSectionId) ids.add(template.footerSectionId);+ return [...ids];+}++/**+ * Every document users can browse in the customizer picker. `supported` flags+ * whether its PDF is wired to consume a template yet — unsupported docs render+ * disabled ("coming soon") in the picker. Keep `type` of supported entries in+ * sync with `documentTemplateTypeSchema`.+ */+/**+ * Which user-authored extension blocks a document supports:+ * - "all": rich text, key-value, custom field, spacer, shared section.+ * - "text": only the plain-text blocks (rich text, key-value, custom field) —+ * used by labels, where every block must also be renderable as ZPL text.+ */+export type ExtensionSupport = "all" | "text";++export interface DocumentCatalogEntry {+ type: string;+ label: string;+ group: string;+ supported: boolean;+ /** Defaults to "all". */+ extensions?: ExtensionSupport;+}++export const DOCUMENT_CATALOG: DocumentCatalogEntry[] = [+ { type: "quote", label: "Quote", group: "Sales", supported: true },+ {+ type: "salesOrder",+ label: "Sales Order",+ group: "Sales",+ supported: true+ },+ {+ type: "salesInvoice",+ label: "Sales Invoice",+ group: "Sales",+ supported: true+ },+ {+ type: "purchaseOrder",+ label: "Purchase Order",+ group: "Purchasing",+ supported: true+ },+ {+ type: "packingSlip",+ label: "Packing Slip",+ group: "Inventory",+ supported: true+ },+ {+ type: "stockTransfer",+ label: "Stock Transfer",+ group: "Inventory",+ supported: true+ },+ {+ type: "jobTraveler",+ label: "Job Traveler",+ group: "Production",+ supported: true+ },+ { type: "issue", label: "Issue", group: "Quality", supported: true },+ {+ type: "trackingLabel",+ label: "Tracking Label",+ group: "Labels",+ supported: true,+ extensions: "text"+ }+];++export function getDocumentLabel(documentType: string): string {+ return (+ DOCUMENT_CATALOG.find((entry) => entry.type === documentType)?.label ??+ documentType+ );+}++/** Which extension blocks a document supports (defaults to "all"). */+export function extensionSupport(documentType: string): ExtensionSupport {+ return (+ DOCUMENT_CATALOG.find((entry) => entry.type === documentType)?.extensions ??+ "all"+ );+}diff --git a/packages/documents/src/template/index.ts b/packages/documents/src/template/index.tsnew file mode 100644index 0000000000..afe884c885--- /dev/null+++ b/packages/documents/src/template/index.ts@@ -0,0 +1,3 @@+export * from "./defaults";+export * from "./merge";+export * from "./schema";diff --git a/packages/documents/src/template/merge.ts b/packages/documents/src/template/merge.tsnew file mode 100644index 0000000000..692c2636e7--- /dev/null+++ b/packages/documents/src/template/merge.ts@@ -0,0 +1,198 @@+import type { JSONContent } from "@carbon/react";++/**+ * Merge fields — `{token}` placeholders that resolve to live document data at+ * render time. Inspired by Bindery's `{ expression }` content model, but kept+ * as inline string tokens so they compose inside rich text and key-value rows+ * the user already authors, with no separate value|expression object. Uses+ * single braces to match the storage-rules condition builder.+ */+export interface MergeField {+ /** Token text without braces, e.g. `invoice.number`. */+ token: string;+ label: string;+ group: string;+}++const TOKEN_RE = /\{\s*([\w.]+)\s*\}/g;++/** Replace every `{token}` in a string with its variable value ("" if unknown). */+export function interpolateString(+ text: string,+ vars: Record<string, string>+): string {+ return text.replace(TOKEN_RE, (_match, token: string) => vars[token] ?? "");+}++/**+ * Deep-clone a tiptap document, replacing `{token}` inside every text node.+ * Pure — never mutates the input (block state stays as the user authored it).+ */+export function interpolateContent(+ content: JSONContent,+ vars: Record<string, string>+): JSONContent {+ const walk = (node: JSONContent): JSONContent => {+ const next: JSONContent = { ...node };+ if (typeof next.text === "string") {+ next.text = interpolateString(next.text, vars);+ }+ if (Array.isArray(next.content)) {+ next.content = next.content.map(walk);+ }+ return next;+ };+ return walk(content);+}++/** Wrap a token for insertion into authored content. */+export function mergeToken(token: string): string {+ return `{${token}}`;+}++const SALES_INVOICE_MERGE_FIELDS: MergeField[] = [+ { token: "invoice.number", label: "Invoice Number", group: "Invoice" },+ { token: "invoice.dateIssued", label: "Issue Date", group: "Invoice" },+ { token: "invoice.dateDue", label: "Due Date", group: "Invoice" },+ {+ token: "invoice.customerReference",+ label: "Customer Reference",+ group: "Invoice"+ },+ { token: "invoice.currency", label: "Currency", group: "Invoice" },+ { token: "customer.name", label: "Customer Name", group: "Customer" },+ { 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" }+];++const SALES_ORDER_MERGE_FIELDS: MergeField[] = [+ { token: "order.number", label: "Order Number", group: "Order" },+ { token: "order.date", label: "Order Date", group: "Order" },+ {+ token: "order.customerReference",+ label: "Customer Reference",+ group: "Order"+ },+ { token: "order.currency", label: "Currency", group: "Order" },+ { token: "customer.name", label: "Customer Name", group: "Customer" },+ { 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" }+];++const PURCHASE_ORDER_MERGE_FIELDS: MergeField[] = [+ { token: "order.number", label: "PO Number", group: "Order" },+ { token: "order.date", label: "Order Date", group: "Order" },+ {+ token: "order.supplierReference",+ label: "Supplier Reference",+ group: "Order"+ },+ { token: "order.currency", label: "Currency", group: "Order" },+ { token: "supplier.name", label: "Supplier Name", group: "Supplier" },+ { 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" }+];++const QUOTE_MERGE_FIELDS: MergeField[] = [+ { token: "quote.number", label: "Quote Number", group: "Quote" },+ { token: "quote.expirationDate", label: "Expiration Date", group: "Quote" },+ {+ token: "quote.customerReference",+ label: "Customer Reference",+ group: "Quote"+ },+ { token: "quote.currency", label: "Currency", group: "Quote" },+ { token: "customer.name", label: "Customer Name", group: "Customer" },+ { 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" }+];++const PACKING_SLIP_MERGE_FIELDS: MergeField[] = [+ { token: "shipment.number", label: "Shipment Number", group: "Shipment" },+ {+ token: "shipment.trackingNumber",+ label: "Tracking Number",+ group: "Shipment"+ },+ { token: "customer.name", label: "Customer Name", group: "Customer" },+ { 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" }+];++const STOCK_TRANSFER_MERGE_FIELDS: MergeField[] = [+ { token: "transfer.number", label: "Transfer Number", group: "Transfer" },+ { token: "transfer.location", label: "Location", group: "Transfer" },+ { token: "transfer.assignee", label: "Assignee", group: "Transfer" },+ { token: "company.name", label: "Company Name", group: "Company" },+ { token: "company.city", label: "Company City", group: "Company" },+ { token: "company.country", label: "Company Country", group: "Company" }+];++const JOB_TRAVELER_MERGE_FIELDS: MergeField[] = [+ { token: "job.number", label: "Job Number", group: "Job" },+ { token: "job.startDate", label: "Start Date", group: "Job" },+ { token: "job.dueDate", label: "Due Date", group: "Job" },+ { token: "item.readableId", label: "Item ID", group: "Item" },+ { token: "item.name", label: "Item Name", group: "Item" },+ { token: "customer.name", label: "Customer Name", 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" }+];++const ISSUE_MERGE_FIELDS: MergeField[] = [+ { token: "issue.number", label: "Issue Number", group: "Issue" },+ { token: "issue.name", label: "Issue Name", group: "Issue" },+ { token: "issue.status", label: "Status", group: "Issue" },+ { token: "issue.openDate", label: "Open Date", group: "Issue" },+ { token: "issue.closeDate", label: "Close Date", group: "Issue" },+ { token: "company.name", label: "Company Name", group: "Company" },+ { token: "company.city", label: "Company City", group: "Company" },+ { token: "company.country", label: "Company Country", group: "Company" }+];++const TRACKING_LABEL_MERGE_FIELDS: MergeField[] = [+ { token: "item.id", label: "Item ID", group: "Item" },+ { token: "item.revision", label: "Revision", group: "Item" },+ { token: "label.quantity", label: "Quantity", group: "Label" },+ { token: "label.trackingType", label: "Tracking Type", group: "Label" },+ { token: "label.number", label: "Serial / Batch Number", group: "Label" },+ { token: "label.trackedEntityId", label: "Tracked Entity ID", group: "Label" }+];++/** Catalog of insertable merge fields per document type (editor-facing). */+export const MERGE_FIELDS: Record<string, MergeField[]> = {+ salesInvoice: SALES_INVOICE_MERGE_FIELDS,+ salesOrder: SALES_ORDER_MERGE_FIELDS,+ purchaseOrder: PURCHASE_ORDER_MERGE_FIELDS,+ quote: QUOTE_MERGE_FIELDS,+ packingSlip: PACKING_SLIP_MERGE_FIELDS,+ stockTransfer: STOCK_TRANSFER_MERGE_FIELDS,+ jobTraveler: JOB_TRAVELER_MERGE_FIELDS,+ issue: ISSUE_MERGE_FIELDS,+ trackingLabel: TRACKING_LABEL_MERGE_FIELDS+};++export function getMergeFields(documentType: string): MergeField[] {+ return MERGE_FIELDS[documentType] ?? [];+}diff --git a/packages/documents/src/template/schema.ts b/packages/documents/src/template/schema.tsnew file mode 100644index 0000000000..aaca5d0575--- /dev/null+++ b/packages/documents/src/template/schema.ts@@ -0,0 +1,483 @@+import type { JSONContent } from "@carbon/react";+import { z } from "zod";++/**+ * Tiptap document content. We keep validation loose (the editor owns the real+ * shape) and only pin the static TS type — mirrors how `terms` is stored.+ */+const jsonContentSchema = z.custom<JSONContent>(+ (val) => typeof val === "object" && val !== null+);++/** Fields shared by every block, built-in or extension. */+const baseFields = {+ id: z.string(),+ visible: z.boolean().default(true)+};++/**+ * Built-in blocks map 1:1 to the hardcoded sections of a document. They are+ * data-bound (the renderer fills them from the document) so they carry no+ * user-authored props — only identity + visibility.+ */+const builtInBlock = <T extends string>(type: T) =>+ z.object({ ...baseFields, type: z.literal(type) });++/**+ * A crop rectangle, normalized to the source image (0..1). `aspect` is the+ * pixel aspect ratio of the cropped region (cropPxW / cropPxH) so renderers can+ * size a clip box without knowing the image's intrinsic dimensions. Shared by+ * the document header logo and the tracking-label logo block.+ */+export const cropSchema = z.object({+ x: z.number().min(0).max(1),+ y: z.number().min(0).max(1),+ width: z.number().min(0).max(1),+ height: z.number().min(0).max(1),+ aspect: z.number().positive()+});+export type LogoCrop = z.infer<typeof cropSchema>;++/** Per-block display options for the Header block (logo + which fields show). */+export const DEFAULT_HEADER_OPTIONS = {+ showLogo: true,+ logoVariant: "mark",+ logoHeight: 50,+ showCompanyDetails: true,+ showDocumentTitle: true,+ showDocumentId: true+} as const;++export const headerOptionsSchema = z.object({+ showLogo: z.boolean().default(true),+ /** Which company logo to use: full logo (`mark`) or the square `icon`. */+ logoVariant: z.enum(["mark", "icon"]).default("mark"),+ logoHeight: z.number().min(16).max(120).default(50),+ /** Optional crop applied before rendering (PDF clip box). */+ logoCrop: cropSchema.optional(),+ showCompanyDetails: z.boolean().default(true),+ showDocumentTitle: z.boolean().default(true),+ showDocumentId: z.boolean().default(true)+});++/** Per-block display options for the Line Items table. */+export const DEFAULT_LINE_ITEMS_OPTIONS = {+ showThumbnails: true,+ zebra: true,+ textOverflow: "truncate"+} as const;++const lineItemsOptionsSchema = z.object({+ showThumbnails: z.boolean().default(true),+ zebra: z.boolean().default(true),+ /** How the item title/description behave: wrap to new lines or truncate. */+ textOverflow: z.enum(["wrap", "truncate"]).default("truncate")+});++/** Per-block options for the Summary totals. */+export const DEFAULT_SUMMARY_OPTIONS = {+ taxLabel: "Taxes"+} as const;++const summaryOptionsSchema = z.object({+ taxLabel: z.string().default("Taxes")+});++const headerBlock = z.object({+ ...baseFields,+ type: z.literal("header"),+ options: headerOptionsSchema.optional()+});+const partiesBlock = builtInBlock("parties");+const notesBlock = builtInBlock("notes");+/** Data-bound metadata block (e.g. shipment/transfer details). */+const detailsBlock = builtInBlock("details");+const lineItemsBlock = z.object({+ ...baseFields,+ type: z.literal("lineItems"),+ options: lineItemsOptionsSchema.optional()+});+const summaryBlock = z.object({+ ...baseFields,+ type: z.literal("summary"),+ options: summaryOptionsSchema.optional()+});+/**+ * Terms & Conditions. Built-in (not addable/removable) but carries its own+ * rich-text `content` — per-document, seeded from the company terms setting.+ * Empty content falls back to that setting at render time.+ */+const termsBlock = z.object({+ ...baseFields,+ type: z.literal("terms"),+ content: jsonContentSchema.optional()+});+/** Job Traveler built-ins (data-bound; render the existing bespoke content). */+const jobDetailsBlock = builtInBlock("jobDetails");+const operationsBlock = z.object({+ ...baseFields,+ type: z.literal("operations"),+ /** Print the full work instructions / procedure steps under each operation. */+ showWorkInstructions: z.boolean().default(false)+});+/** Issue built-ins (data-bound; render the existing bespoke content). */+const issueDetailsBlock = builtInBlock("issueDetails");+const associationsBlock = builtInBlock("associations");+const actionTasksBlock = builtInBlock("actionTasks");+const reviewersBlock = builtInBlock("reviewers");+/** Tracking-label fields (data-bound; one per label element). */+const labelHeadingBlock = builtInBlock("labelHeading");+/** A label field whose printed name (the prefix before the value) is editable. */+const labelNamedField = <T extends string>(type: T) =>+ z.object({+ ...baseFields,+ type: z.literal(type),+ label: z.string().optional()+ });+const labelRevisionBlock = labelNamedField("labelRevision");+const labelQuantityBlock = labelNamedField("labelQuantity");+const labelTrackingBlock = labelNamedField("labelTracking");+/** A human-readable identifier line (defaults to the tracked-entity id). */+const labelEntityIdBlock = z.object({+ ...baseFields,+ type: z.literal("labelEntityId"),+ value: z.string().default("{label.trackedEntityId}")+});+/**+ * A scannable code (QR / PDF417 / Code128 / DataMatrix). `placement` is "right"+ * (small, top-right next to the logo) or "full" (full-width band, e.g. PDF417).+ */+const labelBarcodeBlock = z.object({+ ...baseFields,+ type: z.literal("labelBarcode"),+ symbology: z+ .enum(["qrcode", "pdf417", "code128", "datamatrix"])+ .default("qrcode"),+ value: z.string().default("{label.trackedEntityId}"),+ placement: z.enum(["right", "full", "center"]).default("right"),+ height: z.number().min(16).max(300).optional()+});+/** The company logo. Color in the PDF by default; `monochrome` for B&W / ZPL. */+const labelLogoBlock = z.object({+ ...baseFields,+ type: z.literal("labelLogo"),+ /** Which company logo to use: full logo (`mark`) or the square `icon`. */+ variant: z.enum(["mark", "icon"]).default("mark"),+ monochrome: z.boolean().optional(),+ /** Optional crop applied before rendering (PDF clip box / ZPL pre-crop). */+ crop: cropSchema.optional(),+ height: z.number().min(16).max(160).optional()+});++/** Extension blocks are user-authored and fully removable. */+const richTextBlock = z.object({+ ...baseFields,+ type: z.literal("richText"),+ title: z.string().optional(),+ content: jsonContentSchema+});++const keyValueBlock = z.object({+ ...baseFields,+ type: z.literal("keyValue"),+ title: z.string().optional(),+ rows: z.array(z.object({ label: z.string(), value: z.string() })).default([])+});++const spacerBlock = z.object({+ ...baseFields,+ type: z.literal("spacer"),+ variant: z.enum(["space", "divider", "pageBreak"]).default("space"),+ /** Height in pt, only used by the "space" variant. */+ size: z.number().min(0).max(200).optional()+});++/** Reference to a shared documentSection, resolved at render time. */+const sharedBlock = z.object({+ ...baseFields,+ type: z.literal("shared"),+ sectionId: z.string()+});++/**+ * A single authored line: an optional `label` plus a `value`. With no label it+ * is plain text; with a label it is a single key-value. Maps 1:1 to one ZPL+ * `^FD` line, so it's the label-safe alternative to rich text / key-value lists.+ */+const fieldBlock = z.object({+ ...baseFields,+ type: z.literal("field"),+ label: z.string().optional(),+ value: z.string().default("")+});++/** Displays a single custom-field value (label + value) from the record. */+const customFieldBlock = z.object({+ ...baseFields,+ type: z.literal("customField"),+ /** The custom field's id (key into the record's `customFields` JSON). */+ fieldId: z.string(),+ /** Display label — defaults to the field's name at insert time. */+ label: z.string().default("")+});++/** Faint full-page company watermark (uses the company's watermark logo). */+const watermarkBlock = z.object({+ ...baseFields,+ type: z.literal("watermark"),+ opacity: z.number().min(0).max(1).default(0.07),+ placement: z.enum(["center", "top", "bottom"]).default("center"),+ size: z.number().min(10).max(100).default(50)+});++export const blockSchema = z.discriminatedUnion("type", [+ headerBlock,+ watermarkBlock,+ partiesBlock,+ notesBlock,+ detailsBlock,+ lineItemsBlock,+ summaryBlock,+ termsBlock,+ jobDetailsBlock,+ operationsBlock,+ issueDetailsBlock,+ associationsBlock,+ actionTasksBlock,+ reviewersBlock,+ labelHeadingBlock,+ labelRevisionBlock,+ labelQuantityBlock,+ labelTrackingBlock,+ labelEntityIdBlock,+ labelBarcodeBlock,+ labelLogoBlock,+ richTextBlock,+ keyValueBlock,+ spacerBlock,+ sharedBlock,+ fieldBlock,+ customFieldBlock+]);++/** Shared, reusable rich-text section. `placement` scopes where it's used. */+export const documentSectionPlacementSchema = z.enum([+ "body",+ "header",+ "footer"+]);++/**+ * Layout config carried by a header section — logo + which company fields show.+ * Global: the header is one shared section reused across every document.+ */+export const sectionConfigSchema = headerOptionsSchema.partial();++export const documentSectionSchema = z.object({+ name: z.string().min(1),+ placement: documentSectionPlacementSchema.default("body"),+ content: jsonContentSchema,+ config: sectionConfigSchema.optional()+});++const HEX_COLOR = /^#([0-9a-fA-F]{6})$/;++export const DEFAULT_THEME = {+ /** Strong brand color — fills the line-items header bar. */+ accent: "#1f2937",+ /** Text/icons drawn on top of the accent color. */+ accentForeground: "#ffffff"+} as const;++export const themeSchema = z.object({+ accent: z.string().regex(HEX_COLOR).default(DEFAULT_THEME.accent),+ accentForeground: z+ .string()+ .regex(HEX_COLOR)+ .default(DEFAULT_THEME.accentForeground)+});++/**+ * Document body fonts. "Inter" is registered in Template; the rest are the+ * react-pdf built-in PDF standard fonts (no registration needed).+ */+export const DOCUMENT_FONTS = [+ // Inter is registered in Template; Helvetica/Times/Courier are PDF built-ins.+ { value: "Inter", label: "Inter", kind: "Sans" },+ { value: "Helvetica", label: "Helvetica", kind: "Sans" },+ { value: "Times-Roman", label: "Times", kind: "Serif" },+ { value: "Courier", label: "Courier", kind: "Mono" },+ // Google fonts — registered on demand at render (see pdf/fonts.ts).+ { value: "Roboto", label: "Roboto", kind: "Sans" },+ { value: "Open Sans", label: "Open Sans", kind: "Sans" },+ { value: "Lato", label: "Lato", kind: "Sans" },+ { value: "Montserrat", label: "Montserrat", kind: "Sans" },+ { value: "Merriweather", label: "Merriweather", kind: "Serif" },+ { value: "Playfair Display", label: "Playfair Display", kind: "Serif" },+ { value: "Lora", label: "Lora", kind: "Serif" }+] as const;++export type DocumentFont = (typeof DOCUMENT_FONTS)[number]["value"];++/** Document-level settings (font + footer page numbers + registration line). */+export const DEFAULT_DOCUMENT_SETTINGS = {+ fontFamily: "Inter",+ showPageNumbers: true,+ pageNumberFormat: "pageOfTotal",+ showRegistrationLine: true+} as const;++export const documentSettingsSchema = z.object({+ fontFamily: z+ .enum([+ "Inter",+ "Helvetica",+ "Times-Roman",+ "Courier",+ "Roboto",+ "Open Sans",+ "Lato",+ "Montserrat",+ "Merriweather",+ "Playfair Display",+ "Lora"+ ])+ .default("Inter"),+ showPageNumbers: z.boolean().default(true),+ /** "pageOfTotal" → "Page 1 of 3"; "page" → "Page 1". */+ pageNumberFormat: z.enum(["pageOfTotal", "page"]).default("pageOfTotal"),+ showRegistrationLine: z.boolean().default(true)+});++/** Document types that support a customizable template. Widen as docs ship. */+export const documentTemplateTypeSchema = z.enum([+ "salesInvoice",+ "salesOrder",+ "purchaseOrder",+ "quote",+ "packingSlip",+ "stockTransfer",+ "jobTraveler",+ "issue",+ "trackingLabel"+]);++/**+ * Schema version of the stored template JSON. Bump when the block/theme shape+ * changes in a non-additive way; `resolveTemplate` migrates older versions+ * forward on read. (Idea borrowed from Bindery's `formatVersion`.)+ */+export const CURRENT_TEMPLATE_FORMAT_VERSION = 1;++export const documentTemplateSchema = z.object({+ formatVersion: z.number().int().default(CURRENT_TEMPLATE_FORMAT_VERSION),+ documentType: documentTemplateTypeSchema,+ blocks: z.array(blockSchema),+ theme: themeSchema.default(DEFAULT_THEME),+ settings: documentSettingsSchema.default(DEFAULT_DOCUMENT_SETTINGS),+ /** Shared sections used as the repeating page header/footer (or none). */+ headerSectionId: z.string().nullable().default(null),+ footerSectionId: z.string().nullable().default(null)+});++export type DocumentBlock = z.infer<typeof blockSchema>;+export type DocumentBlockType = DocumentBlock["type"];+export type SharedBlock = Extract<DocumentBlock, { type: "shared" }>;+export type DocumentSection = z.infer<typeof documentSectionSchema>;+export type DocumentSectionPlacement = z.infer<+ typeof documentSectionPlacementSchema+>;+/** A section row resolved for rendering (id + name + content + layout config). */+export interface ResolvedSection {+ id: string;+ name: string;+ placement: DocumentSectionPlacement;+ content: JSONContent;+ /** Header layout config (logo, which fields show). Header sections only. */+ config?: SectionConfig;+ /** True for code-provided system sections — shown read-only in the library. */+ builtIn?: boolean;+}+export type DocumentTheme = z.infer<typeof themeSchema>;+export type DocumentSettings = z.infer<typeof documentSettingsSchema>;+export type DocumentTemplate = z.infer<typeof documentTemplateSchema>;+export type DocumentTemplateType = z.infer<typeof documentTemplateTypeSchema>;++/** The stored `documentTemplate` row shape (JSON columns are untyped here). */+export interface StoredDocumentTemplateRow {+ formatVersion?: number | null;+ blocks?: unknown;+ theme?: unknown;+ settings?: unknown;+ headerSectionId?: string | null;+ footerSectionId?: string | null;+}++/**+ * Map a stored `documentTemplate` row to a `DocumentTemplate` (or null). The one+ * place the JSON columns are cast — callers (services + PDF/ZPL routes) use this+ * instead of re-deriving the shape. The result still passes through+ * `resolveTemplate` at render, which applies defaults/validation.+ */+export function toDocumentTemplate(+ row: unknown,+ documentType: DocumentTemplateType+): DocumentTemplate | null {+ if (!row) return null;+ const r = row as StoredDocumentTemplateRow;+ return {+ formatVersion: r.formatVersion ?? CURRENT_TEMPLATE_FORMAT_VERSION,+ documentType,+ blocks: r.blocks as DocumentTemplate["blocks"],+ theme: r.theme as DocumentTemplate["theme"],+ settings: r.settings as DocumentTemplate["settings"],+ headerSectionId: r.headerSectionId ?? null,+ footerSectionId: r.footerSectionId ?? null+ };+}++/** Narrowing helpers for the extension blocks (used by editor + renderers). */+export type RichTextBlock = Extract<DocumentBlock, { type: "richText" }>;+export type KeyValueBlock = Extract<DocumentBlock, { type: "keyValue" }>;+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 SectionConfig = z.infer<typeof sectionConfigSchema>;+export type LineItemsBlock = Extract<DocumentBlock, { type: "lineItems" }>;+export type LineItemsOptions = z.infer<typeof lineItemsOptionsSchema>;+export type SummaryBlock = Extract<DocumentBlock, { type: "summary" }>;+export type SummaryOptions = z.infer<typeof summaryOptionsSchema>;+export type FieldBlock = Extract<DocumentBlock, { type: "field" }>;+export type CustomFieldBlock = Extract<DocumentBlock, { type: "customField" }>;+export type JobDetailsBlock = Extract<DocumentBlock, { type: "jobDetails" }>;+export type OperationsBlock = Extract<DocumentBlock, { type: "operations" }>;+export type IssueDetailsBlock = Extract<+ DocumentBlock,+ { type: "issueDetails" }+>;+export type AssociationsBlock = Extract<+ DocumentBlock,+ { type: "associations" }+>;+export type ActionTasksBlock = Extract<DocumentBlock, { type: "actionTasks" }>;+export type ReviewersBlock = Extract<DocumentBlock, { type: "reviewers" }>;+export type LabelHeadingBlock = Extract<+ DocumentBlock,+ { type: "labelHeading" }+>;+/** Label fields whose printed name is editable. */+export type LabelNamedBlock = Extract<+ DocumentBlock,+ { type: "labelRevision" | "labelQuantity" | "labelTracking" }+>;+export type LabelBarcodeBlock = Extract<+ DocumentBlock,+ { type: "labelBarcode" }+>;+export type LabelLogoBlock = Extract<DocumentBlock, { type: "labelLogo" }>;+export type WatermarkBlock = Extract<DocumentBlock, { type: "watermark" }>;+export type LabelEntityIdBlock = Extract<+ DocumentBlock,+ { type: "labelEntityId" }+>;diff --git a/packages/documents/src/template/template.test.ts b/packages/documents/src/template/template.test.tsnew file mode 100644index 0000000000..839a8f1b15--- /dev/null+++ b/packages/documents/src/template/template.test.ts@@ -0,0 +1,138 @@+import { describe, expect, it } from "vitest";+import {+ ADDABLE_BLOCK_TYPES,+ BLOCK_META,+ DEFAULT_SALES_INVOICE_TEMPLATE,+ resolveTemplate+} from "./defaults";+import { blockSchema, documentTemplateSchema } from "./schema";++describe("resolveTemplate", () => {+ it("falls back to the default template when nothing is stored", () => {+ expect(resolveTemplate("salesInvoice", undefined)).toEqual(+ DEFAULT_SALES_INVOICE_TEMPLATE+ );+ expect(resolveTemplate("salesInvoice", { blocks: [] })).toEqual(+ DEFAULT_SALES_INVOICE_TEMPLATE+ );+ });++ it("preserves stored block order and visibility", () => {+ const stored = [+ { id: "summary", type: "summary" as const, visible: true },+ { id: "lineItems", type: "lineItems" as const, visible: true },+ { id: "header", type: "header" as const, visible: false },+ { id: "parties", type: "parties" as const, visible: true },+ { id: "notes", type: "notes" as const, visible: true },+ { id: "terms", type: "terms" as const, visible: true }+ ];+ const { blocks } = resolveTemplate("salesInvoice", { blocks: stored });+ expect(blocks.map((b) => b.type)).toEqual([+ "summary",+ "lineItems",+ "header",+ "parties",+ "notes",+ "terms"+ ]);+ expect(blocks.find((b) => b.type === "header")?.visible).toBe(false);+ });++ it("appends missing built-in blocks as hidden", () => {+ const stored = [+ { id: "lineItems", type: "lineItems" as const, visible: true },+ { id: "summary", type: "summary" as const, visible: true }+ ];+ const { blocks } = resolveTemplate("salesInvoice", { blocks: stored });+ const header = blocks.find((b) => b.type === "header");+ expect(header).toBeDefined();+ expect(header?.visible).toBe(false);+ // stored blocks stay first, appended built-ins follow+ expect(blocks.slice(0, 2).map((b) => b.type)).toEqual([+ "lineItems",+ "summary"+ ]);+ });+});++describe("block metadata invariants", () => {+ it("keeps line items and summary non-hideable and non-removable", () => {+ for (const type of ["lineItems", "summary"] as const) {+ expect(BLOCK_META[type].hideable).toBe(false);+ expect(BLOCK_META[type].removable).toBe(false);+ }+ });++ it("only exposes extension blocks in the add menu", () => {+ expect(ADDABLE_BLOCK_TYPES).toEqual(["richText", "keyValue", "spacer"]);+ for (const type of ADDABLE_BLOCK_TYPES) {+ expect(BLOCK_META[type].isBuiltIn).toBe(false);+ expect(BLOCK_META[type].removable).toBe(true);+ }+ });+});++describe("document settings", () => {+ it("includes default settings on the default template", () => {+ expect(DEFAULT_SALES_INVOICE_TEMPLATE.settings).toEqual({+ fontFamily: "Inter",+ showPageNumbers: true,+ pageNumberFormat: "pageOfTotal",+ showRegistrationLine: true+ });+ });++ it("merges a partial stored settings over defaults", () => {+ const { settings } = resolveTemplate("salesInvoice", {+ blocks: [{ id: "summary", type: "summary", visible: true }],+ settings: { showPageNumbers: false }+ });+ expect(settings).toEqual({+ fontFamily: "Inter",+ showPageNumbers: false,+ pageNumberFormat: "pageOfTotal",+ showRegistrationLine: true+ });+ });+});++describe("schema validation", () => {+ it("parses extension blocks and applies defaults", () => {+ const spacer = blockSchema.parse({ id: "s1", type: "spacer" });+ expect(spacer).toMatchObject({ visible: true, variant: "space" });++ const keyValue = blockSchema.parse({ id: "k1", type: "keyValue" });+ expect(keyValue).toMatchObject({ visible: true, rows: [] });+ });++ it("parses built-in blocks with and without options", () => {+ const bare = blockSchema.parse({ id: "header", type: "header" });+ expect(bare).toMatchObject({ type: "header", visible: true });++ const withOptions = blockSchema.parse({+ id: "header",+ type: "header",+ options: { showLogo: false, logoHeight: 40 }+ });+ expect(withOptions).toMatchObject({+ type: "header",+ options: { showLogo: false, logoHeight: 40 }+ });++ const lineItems = blockSchema.parse({+ id: "lineItems",+ type: "lineItems",+ options: { zebra: false }+ });+ expect(lineItems).toMatchObject({ options: { zebra: false } });+ });++ it("rejects unknown block types", () => {+ expect(() => blockSchema.parse({ id: "x", type: "bogus" })).toThrow();+ });++ it("validates a full template document", () => {+ const parsed = documentTemplateSchema.parse(DEFAULT_SALES_INVOICE_TEMPLATE);+ expect(parsed.blocks).toHaveLength(6);+ });+});diff --git a/packages/documents/src/zpl/ProductLabelZPL.tsx b/packages/documents/src/zpl/ProductLabelZPL.tsxindex a589eaf2b7..5f58282b9f 100644--- a/packages/documents/src/zpl/ProductLabelZPL.tsx+++ b/packages/documents/src/zpl/ProductLabelZPL.tsx@@ -1,54 +1,208 @@import type { LabelSize, ProductLabelItem } from "@carbon/utils";-import { getZplLabelGeometry, zplLabelHeader } from "./utils";+import type { DocumentTemplate } from "../template";+import { interpolateString, resolveTemplate } from "../template";++/** Merge-field values for a label (kept in sync with buildLabelVars). */+function labelVars(item: ProductLabelItem): Record<string, string> {+ const str = (v: unknown): string => (v == null ? "" : String(v));+ return {+ "item.id": str(item.itemId),+ "item.revision": str(item.revision),+ "label.quantity": str(item.quantity),+ "label.trackingType": str(item.trackingType),+ "label.number": str(item.number),+ "label.trackedEntityId": str(item.trackedEntityId)+ };+}++/**+ * Generate ZPL for a tracked-entity label. Honors the `trackingLabel` template:+ * only visible fields are emitted, and the text fields stack in block order+ * (QR stays top-right, the entity id stays at the bottom — same partitioning as+ * the PDF). Extension/custom blocks are skipped (no ZPL equivalent).+ */+/** Map a barcode symbology to its ZPL command for a given dot height. */+function zplBarcode(+ symbology: string,+ value: string,+ heightDots: number+): string {+ switch (symbology) {+ case "code128":+ return `^BCN,${heightDots},N,N,N^FD${value}^FS`;+ case "datamatrix":+ return `^BXN,${Math.max(3, Math.floor(heightDots / 20))},200^FD${value}^FS`;+ case "qrcode":+ return `^BQN,2,${Math.max(3, Math.floor(heightDots / 30))}^FD${value}^FS`;+ default: // pdf417+ return `^BY2^B7N,${Math.max(2, Math.floor(heightDots / 20))},5,0,0,N^FD${value}^FS`;+ }+}export function generateProductLabelZPL(item: ProductLabelItem,- labelSize: LabelSize+ labelSize: LabelSize,+ template?: DocumentTemplate | null,+ logo?: { gfa?: string | null; widthDots?: number } | null): string {- const geometry = getZplLabelGeometry(labelSize);- const { widthDots, heightDots, hScale, scale, margin } = geometry;-- const titleFont = Math.round(25 * scale);- const descFont = Math.round(18 * scale);- const smallFont = Math.round(12 * scale);- const lineGap = Math.round(25 * scale);-- // QR module size scales with the smaller dimension- const qrModuleSize = Math.max(2, Math.min(8, Math.round(4 * scale)));- // Approximate QR pixel width: module * (21 + 2*error_correction_overhead) ≈ module * 29- const qrPixelSize = qrModuleSize * 29;- const qrX = widthDots - qrPixelSize - margin;- const qrY = Math.round(30 * hScale);+ if (!labelSize.zpl) {+ throw new Error("Invalid label size or missing ZPL configuration");+ }+ const { width, height } = labelSize.zpl;+ const dpi = labelSize.zpl.dpi || 203;- let zpl = zplLabelHeader(geometry);+ // Convert inches to dots based on DPI+ const widthDots = Math.round(width * dpi);+ const heightDots = Math.round(height * dpi);- let y = Math.round(30 * hScale);+ // Determine if this is a small or large label+ const isSmallLabel = width <= 2.5; // Consider 2x1 as small- zpl += `^FO${margin},${y}^A0N,${titleFont},${titleFont}^FD${item.itemId}^FS`;- y += titleFont + Math.round(10 * hScale);+ // Calculate positions based on label size+ const textStartX = 20;+ const fontSize = isSmallLabel ? 25 : 35; // Smaller font for small labels+ const descFontSize = isSmallLabel ? 18 : 25;+ const smallFontSize = isSmallLabel ? 12 : 18;+ const headingGap = isSmallLabel ? 35 : 50;+ const descGap = isSmallLabel ? 25 : 35;- if (item.revision) {- zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDRev: ${item.revision}^FS`;- y += lineGap;- }+ // QR code positioning and sizing+ const qrSize = isSmallLabel+ ? Math.min(heightDots * 0.6, widthDots * 0.35) // Smaller QR for small labels+ : Math.min(heightDots * 0.7, widthDots * 0.25); // Larger QR with more space on bigger labels- if (["Serial", "Batch"].includes(item.trackingType)) {- zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDQty: ${item.quantity}^FS`;- y += lineGap;- }+ const qrStartX = isSmallLabel+ ? widthDots - qrSize - 15 // Tighter spacing on small labels+ : widthDots - qrSize - 40; // More spacing on larger labels- if (item.trackingType === "Serial") {- zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDS/N: ${item.number}^FS`;- } else if (item.trackingType === "Batch") {- zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDBatch: ${item.number}^FS`;- }+ const resolved = resolveTemplate("trackingLabel", template ?? null);+ const visibleBlocks = resolved.blocks.filter((block) => block.visible);+ const vars = labelVars(item);- zpl += `^FO${qrX},${qrY}^BQN,2,${qrModuleSize}^FDMA,${item.trackedEntityId}^FS`;+ let zpl = "^XA"; // Start format+ zpl += `^PW${widthDots}`;+ zpl += `^LL${heightDots}`;- const idY = heightDots - smallFont - Math.round(10 * hScale);- zpl += `^FO${margin},${idY}^A0N,${smallFont},${smallFont}^FD${item.trackedEntityId}^FS`;+ // Text fields stack from the top, following block order.+ let yPosition = 30;+ const textLine = (size: number, text: string) => {+ zpl += `^FO${textStartX},${yPosition}^A0N,${size},${size}^FD${text}^FS`;+ };- zpl += "^XZ";+ for (const block of visibleBlocks) {+ switch (block.type) {+ case "labelHeading":+ if (item.itemId) {+ textLine(fontSize, item.itemId);+ yPosition += headingGap;+ }+ break;+ case "labelRevision":+ if (item.revision) {+ textLine(descFontSize, `${block.label || "Rev"}: ${item.revision}`);+ yPosition += descGap;+ }+ break;+ case "labelQuantity":+ if (["Serial", "Batch"].includes(item.trackingType)) {+ textLine(descFontSize, `${block.label || "Qty"}: ${item.quantity}`);+ yPosition += descGap;+ }+ break;+ case "labelTracking":+ if (item.number && ["Serial", "Batch"].includes(item.trackingType)) {+ const defaultName = item.trackingType === "Serial" ? "S/N" : "Batch";+ textLine(+ descFontSize,+ `${block.label || defaultName}: ${item.number}`+ );+ yPosition += descGap;+ }+ break;+ case "labelEntityId": {+ // Human-readable identifier text at the bottom (interpolated value).+ const value = interpolateString(block.value ?? "", vars);+ if (value) {+ const idYPosition = isSmallLabel ? heightDots - 25 : heightDots - 35;+ zpl += `^FO${textStartX},${idYPosition}^A0N,${smallFontSize},${smallFontSize}^FD${value}^FS`;+ }+ break;+ }+ case "labelLogo":+ if (logo?.gfa) {+ // Top-right, like the QR slot.+ const logoW = logo.widthDots ?? Math.round(widthDots * 0.3);+ const logoX = widthDots - logoW - 15;+ zpl += `^FO${logoX > 0 ? logoX : 15},20${logo.gfa}^FS`;+ }+ break;+ case "labelBarcode": {+ const value = interpolateString(block.value ?? "", vars);+ if (value) {+ if (block.placement === "full") {+ // Full-width band that flows *below* the text (not a fixed bottom+ // offset, which collided with the last text line). Scale it to the+ // space left between the text and the bottom entity-id line.+ const gap = 6;+ // Clear the bottom entity-id line (placed at heightDots-25/-35).+ const bottomReserve = isSmallLabel ? 30 : 44;+ const bcY = yPosition + gap;+ const avail = heightDots - bottomReserve - bcY;+ const bcHeight = Math.max(+ 20,+ Math.min(isSmallLabel ? 60 : 110, avail)+ );+ zpl += `^FO${textStartX},${bcY}`;+ zpl += zplBarcode(block.symbology, value, bcHeight);+ yPosition = bcY + bcHeight;+ } else if (block.placement === "center") {+ // Centered square that flows below the text (e.g. QR-only label).+ const gap = 6;+ const bottomReserve = isSmallLabel ? 30 : 44;+ const bcY = yPosition + gap;+ const avail = heightDots - bottomReserve - bcY;+ const bcSize = Math.max(20, Math.min(qrSize, avail));+ const bcX = Math.max(+ textStartX,+ Math.round((widthDots - bcSize) / 2)+ );+ zpl += `^FO${bcX},${bcY}`;+ zpl += zplBarcode(block.symbology, value, bcSize);+ yPosition = bcY + bcSize;+ } else {+ // Top-right, like the old QR slot.+ const bcHeight = isSmallLabel ? 80 : 130;+ zpl += `^FO${qrStartX},${isSmallLabel ? 30 : 40}`;+ zpl += zplBarcode(block.symbology, value, bcHeight);+ }+ }+ break;+ }+ case "field": {+ // A single authored line: "label: value" (or just the value).+ const value = interpolateString(block.value ?? "", vars);+ const text = block.label ? `${block.label}: ${value}` : value;+ if (text) {+ textLine(descFontSize, text);+ yPosition += descGap;+ }+ break;+ }+ case "customField": {+ const value = item.customFields?.[block.fieldId];+ if (value != null && value !== "") {+ textLine(descFontSize, `${block.label}: ${value}`);+ yPosition += descGap;+ }+ break;+ }+ // Rich text / key-value lists / spacers / shared sections have no+ // single-line ZPL equivalent — skip.+ default:+ break;+ }+ }+ zpl += "^XZ"; // End formatreturn zpl;}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 7ded89be71..6fcfe9a44d 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -1534,9 +1534,6 @@ msgstr "Konfigurieren Sie Benachrichtigungen für den Fall, dass Wartungseinsätmsgid "Configure notifications for when new suggestions are submitted."msgstr "Konfigurieren Sie Benachrichtigungen für neue eingereichte Vorschläge."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Konfigurieren Sie den auf Job-Traveler-PDFs angezeigten Inhalt."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Konfigurieren Sie die Standardkonten, die für verschiedene Transaktionstypen in Ihrem System verwendet werden"@@ -2116,6 +2113,9 @@ msgstr "Kundentypen"msgid "Customers"msgstr "Kunden"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "Tägliche Nutzung"@@ -2252,12 +2252,6 @@ msgstr "Standardeinheit"msgid "Defaults"msgstr "Standardwerte"-msgid "Define the terms and conditions for purchase orders"-msgstr "Definieren Sie die Bedingungen für Bestellungen"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Definieren Sie die Bedingungen für Angebote und Verkaufsaufträge"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Definiert, wie viele nachverfolgten Entitäten pro Charge inspiziert werden und wie viele Fehler toleriert werden, bevor die Charge abgelehnt wird."@@ -2606,6 +2600,9 @@ msgstr "Dokument"msgid "Document Control"msgstr "Dokumentenkontrolle"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "Dokument:"@@ -3045,9 +3042,6 @@ msgstr "Aktivieren Sie diese Option, um steuerspezifische Abschreibungsmethodenmsgid "Enable to generate IDs and descriptions for raw materials."msgstr "Aktivieren Sie diese Option, um IDs und Beschreibungen für Rohstoffe zu generieren."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Aktivieren Sie diese Option, um Arbeitsanweisungen in Job-Traveler-PDFs einzubeziehen."-msgid "Enable to start tracking changes to your data."msgstr "Aktivieren Sie diese Option, um Änderungen an Ihren Daten zu verfolgen."@@ -3948,12 +3942,6 @@ msgstr "Zusätzliche Teile in Sendung einbeziehen"msgid "Include Inactive"msgstr "Inaktive einschließen"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Miniaturansichten in Einkaufsdokumenten einschließen"--msgid "Include Thumbnails on Sales Documents"-msgstr "Miniaturansichten in Verkaufsdokumenten einschließen"-msgid "Includes tax and shipping costs"msgstr "Enthält Steuern und Versandkosten"@@ -4239,12 +4227,6 @@ msgstr "Arbeitsgang"msgid "Job Operations"msgstr "Arbeitsvorgänge"-msgid "Job Traveler"-msgstr "Arbeitsauftrag-Begleiter"--msgid "Job traveler PDFs include work instructions."-msgstr "Job-Traveler-PDFs enthalten Arbeitsanweisungen."-msgid "Jobs"msgstr "Aufträge"@@ -6170,9 +6152,6 @@ msgstr "Beschaffung"msgid "Purchasing Contact"msgstr "Einkaufskontakt"-msgid "Purchasing Terms & Conditions"-msgstr "Einkaufsbedingungen"-msgid "Purchasing Unit of Measure"msgstr "Einkaufsmaßeinheit"@@ -6783,9 +6762,6 @@ msgstr "Verkäufer"msgid "Sales Revenue"msgstr "Verkaufsumsatz"-msgid "Sales Terms & Conditions"-msgstr "Verkaufsbedingungen"-msgid "Sample"msgstr "Probe"@@ -7182,6 +7158,9 @@ msgstr "Link teilen"msgid "Share Quote"msgstr "Angebot teilen"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "Haltbarkeit"@@ -7293,12 +7272,6 @@ msgstr "Dauern anzeigen"msgid "Show parent items"msgstr "Übergeordnete Elemente anzeigen"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Zeige Teile-Miniaturansichten auf Bestellungs-PDFs an."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Zeigen Sie Teilthumbnails auf Angeboten, Bestellungen, Rechnungen und Lieferungen an."-msgid "Show Supplier IDs"msgstr "Lieferanten-IDs anzeigen"@@ -7353,6 +7326,9 @@ msgstr "Übersprungen"msgid "Something went wrong. Please try again."msgstr "Etwas ist schief gelaufen. Bitte versuchen Sie es erneut."+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "Früheste Verfallsdatum über alle Materialien bestimmt das Fertigprodukt."@@ -7795,6 +7771,9 @@ msgstr "Temperatur"msgid "Template ID"msgstr "Vorlagen-ID"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "Bedingungen und Datenschutz"@@ -8764,12 +8743,6 @@ msgstr "Arbeitszentren"msgid "Work Instructions"msgstr "Arbeitsanweisungen"-msgid "Work instructions are included"-msgstr "Arbeitsanweisungen sind enthalten"--msgid "Work instructions are not included"-msgstr "Arbeitsanweisungen sind nicht enthalten"-msgid "Work Phone"msgstr "Geschäftstelefon"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 1638a5cea5..0108684be3 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -1534,9 +1534,6 @@ msgstr "Configure notifications for when maintenance dispatches are created frommsgid "Configure notifications for when new suggestions are submitted."msgstr "Configure notifications for when new suggestions are submitted."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Configure the content displayed on job traveler PDFs."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Configure the default accounts used for various transaction types across your system"@@ -2116,6 +2113,9 @@ msgstr "Customer Types"msgid "Customers"msgstr "Customers"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgid "Daily Usage"msgstr "Daily Usage"@@ -2252,12 +2252,6 @@ msgstr "Default Unit"msgid "Defaults"msgstr "Defaults"-msgid "Define the terms and conditions for purchase orders"-msgstr "Define the terms and conditions for purchase orders"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Define the terms and conditions for quotes and sales orders"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."@@ -2606,6 +2600,9 @@ msgstr "Document"msgid "Document Control"msgstr "Document Control"+msgid "Document Templates"+msgstr "Document Templates"+msgid "Document:"msgstr "Document:"@@ -3045,9 +3042,6 @@ msgstr "Enable to configure tax-specific depreciation methods on asset classes (msgid "Enable to generate IDs and descriptions for raw materials."msgstr "Enable to generate IDs and descriptions for raw materials."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Enable to include work instructions on job traveler PDFs."-msgid "Enable to start tracking changes to your data."msgstr "Enable to start tracking changes to your data."@@ -3948,12 +3942,6 @@ msgstr "Include extra parts in shipment"msgid "Include Inactive"msgstr "Include Inactive"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Include Thumbnails on Purchasing Documents"--msgid "Include Thumbnails on Sales Documents"-msgstr "Include Thumbnails on Sales Documents"-msgid "Includes tax and shipping costs"msgstr "Includes tax and shipping costs"@@ -4239,12 +4227,6 @@ msgstr "Job Operation"msgid "Job Operations"msgstr "Job Operations"-msgid "Job Traveler"-msgstr "Job Traveler"--msgid "Job traveler PDFs include work instructions."-msgstr "Job traveler PDFs include work instructions."-msgid "Jobs"msgstr "Jobs"@@ -6170,9 +6152,6 @@ msgstr "Purchasing"msgid "Purchasing Contact"msgstr "Purchasing Contact"-msgid "Purchasing Terms & Conditions"-msgstr "Purchasing Terms & Conditions"-msgid "Purchasing Unit of Measure"msgstr "Purchasing Unit of Measure"@@ -6783,9 +6762,6 @@ msgstr "Sales Person"msgid "Sales Revenue"msgstr "Sales Revenue"-msgid "Sales Terms & Conditions"-msgstr "Sales Terms & Conditions"-msgid "Sample"msgstr "Sample"@@ -7182,6 +7158,9 @@ msgstr "Share Link"msgid "Share Quote"msgstr "Share Quote"+msgid "Shared Sections"+msgstr "Shared Sections"+msgid "Shelf life"msgstr "Shelf life"@@ -7293,12 +7272,6 @@ msgstr "Show Durations"msgid "Show parent items"msgstr "Show parent items"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Show part thumbnails on purchase order PDFs."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgid "Show Supplier IDs"msgstr "Show Supplier IDs"@@ -7353,6 +7326,9 @@ msgstr "Skipped"msgid "Something went wrong. Please try again."msgstr "Something went wrong. Please try again."+msgid "Soon"+msgstr "Soon"+msgid "Soonest expiry across every material sets the finished good."msgstr "Soonest expiry across every material sets the finished good."@@ -7795,6 +7771,9 @@ msgstr "Temperature"msgid "Template ID"msgstr "Template ID"+msgid "Templates"+msgstr "Templates"+msgid "Terms and Privacy"msgstr "Terms and Privacy"@@ -8764,12 +8743,6 @@ msgstr "Work Centers"msgid "Work Instructions"msgstr "Work Instructions"-msgid "Work instructions are included"-msgstr "Work instructions are included"--msgid "Work instructions are not included"-msgstr "Work instructions are not included"-msgid "Work Phone"msgstr "Work Phone"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 64969c5f4c..a6d954e0b5 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -1534,9 +1534,6 @@ msgstr "Configura notificaciones para cuando se crean despachos de mantenimientomsgid "Configure notifications for when new suggestions are submitted."msgstr "Configura notificaciones para cuando se envíen nuevas sugerencias."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Configura el contenido mostrado en los PDF del viajero de trabajo."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Configura las cuentas predeterminadas utilizadas para varios tipos de transacciones en todo tu sistema"@@ -2116,6 +2113,9 @@ msgstr "Tipos de Cliente"msgid "Customers"msgstr "Clientes"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "Uso Diario"@@ -2252,12 +2252,6 @@ msgstr "Unidad Predeterminada"msgid "Defaults"msgstr "Valores predeterminados"-msgid "Define the terms and conditions for purchase orders"-msgstr "Define los términos y condiciones para órdenes de compra"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Define los términos y condiciones para cotizaciones y órdenes de venta"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Define cuántas entidades rastreadas se inspeccionan por lote y cuántas fallas se toleran antes de que el lote sea rechazado."@@ -2606,6 +2600,9 @@ msgstr "Documento"msgid "Document Control"msgstr "Control de Documentos"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "Documento:"@@ -3045,9 +3042,6 @@ msgstr "Habilitar para configurar métodos de depreciación específicos de impumsgid "Enable to generate IDs and descriptions for raw materials."msgstr "Habilitar para generar IDs y descripciones para materias primas."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Habilitar para incluir instrucciones de trabajo en los PDF del viajero de trabajo."-msgid "Enable to start tracking changes to your data."msgstr "Habilita para comenzar a rastrear cambios en tus datos."@@ -3948,12 +3942,6 @@ msgstr "Incluir piezas adicionales en el envío"msgid "Include Inactive"msgstr "Incluir Inactivos"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Incluir miniaturas en documentos de compra"--msgid "Include Thumbnails on Sales Documents"-msgstr "Incluir miniaturas en documentos de ventas"-msgid "Includes tax and shipping costs"msgstr "Incluye impuestos y costos de envío"@@ -4239,12 +4227,6 @@ msgstr "Operación de Trabajo"msgid "Job Operations"msgstr "Operaciones de Trabajo"-msgid "Job Traveler"-msgstr "Viajero de Trabajo"--msgid "Job traveler PDFs include work instructions."-msgstr "Los PDF del viajero de trabajo incluyen instrucciones de trabajo."-msgid "Jobs"msgstr "Trabajos"@@ -6170,9 +6152,6 @@ msgstr "Compras"msgid "Purchasing Contact"msgstr "Contacto de Compras"-msgid "Purchasing Terms & Conditions"-msgstr "Términos y Condiciones de Compra"-msgid "Purchasing Unit of Measure"msgstr "Unidad de Medida de Compra"@@ -6783,9 +6762,6 @@ msgstr "Persona de Ventas"msgid "Sales Revenue"msgstr "Ingresos de Ventas"-msgid "Sales Terms & Conditions"-msgstr "Términos y Condiciones de Ventas"-msgid "Sample"msgstr "Muestra"@@ -7182,6 +7158,9 @@ msgstr "Enlace compartido"msgid "Share Quote"msgstr "Compartir Cotización"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "Vida útil"@@ -7293,12 +7272,6 @@ msgstr "Mostrar duraciones"msgid "Show parent items"msgstr "Mostrar elementos principales"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Mostrar miniaturas de piezas en los PDF de órdenes de compra."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Mostrar miniaturas de piezas en cotizaciones, órdenes de venta, facturas y envíos."-msgid "Show Supplier IDs"msgstr "Mostrar IDs de Proveedores"@@ -7353,6 +7326,9 @@ msgstr "Omitido"msgid "Something went wrong. Please try again."msgstr "Algo salió mal. Por favor, inténtalo de nuevo."+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "La fecha de vencimiento más próxima entre todos los materiales establece el producto terminado."@@ -7795,6 +7771,9 @@ msgstr "Temperatura"msgid "Template ID"msgstr "ID de plantilla"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "Términos y Privacidad"@@ -8764,12 +8743,6 @@ msgstr "Centros de Trabajo"msgid "Work Instructions"msgstr "Instrucciones de Trabajo"-msgid "Work instructions are included"-msgstr "Las instrucciones de trabajo están incluidas"--msgid "Work instructions are not included"-msgstr "Las instrucciones de trabajo no están incluidas"-msgid "Work Phone"msgstr "Teléfono de trabajo"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 1e57b60875..838f900176 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -1534,9 +1534,6 @@ msgstr "Configurez les notifications pour lorsque les ordres de maintenance sontmsgid "Configure notifications for when new suggestions are submitted."msgstr "Configurez les notifications pour lorsque de nouvelles suggestions sont soumises."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Configurez le contenu affiché sur les PDF de bon de travail."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Configurez les comptes par défaut utilisés pour différents types de transactions dans votre système"@@ -2116,6 +2113,9 @@ msgstr "Types de clients"msgid "Customers"msgstr "Clients"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "Utilisation quotidienne"@@ -2252,12 +2252,6 @@ msgstr "Unité par défaut"msgid "Defaults"msgstr "Paramètres par défaut"-msgid "Define the terms and conditions for purchase orders"-msgstr "Définir les conditions générales pour les commandes d'achat"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Définir les conditions générales pour les devis et les commandes de vente"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Définit le nombre d'entités suivies inspectées par lot et le nombre de défaillances tolérées avant le rejet du lot."@@ -2606,6 +2600,9 @@ msgstr "Document"msgid "Document Control"msgstr "Contrôle des documents"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "Document :"@@ -3045,9 +3042,6 @@ msgstr "Activez cette option pour configurer les méthodes d'amortissement spécmsgid "Enable to generate IDs and descriptions for raw materials."msgstr "Activez pour générer des identifiants et des descriptions pour les matières premières."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Activez cette option pour inclure les instructions de travail sur les PDF de bon de travail."-msgid "Enable to start tracking changes to your data."msgstr "Activez pour commencer à suivre les modifications de vos données."@@ -3948,12 +3942,6 @@ msgstr "Inclure les pièces supplémentaires dans l'expédition"msgid "Include Inactive"msgstr "Inclure les inactifs"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Inclure les miniatures sur les documents d'achat"--msgid "Include Thumbnails on Sales Documents"-msgstr "Inclure les miniatures sur les documents commerciaux"-msgid "Includes tax and shipping costs"msgstr "Inclut les taxes et les frais d'expédition"@@ -4239,12 +4227,6 @@ msgstr "Opération de travail"msgid "Job Operations"msgstr "Opérations de travail"-msgid "Job Traveler"-msgstr "Bon de travail"--msgid "Job traveler PDFs include work instructions."-msgstr "Les PDF de bon de travail incluent les instructions de travail."-msgid "Jobs"msgstr "Travaux"@@ -6170,9 +6152,6 @@ msgstr "Approvisionnement"msgid "Purchasing Contact"msgstr "Contact d'achat"-msgid "Purchasing Terms & Conditions"-msgstr "Conditions générales d'achat"-msgid "Purchasing Unit of Measure"msgstr "Unité de mesure d'achat"@@ -6783,9 +6762,6 @@ msgstr "Responsable commercial"msgid "Sales Revenue"msgstr "Chiffre d'affaires"-msgid "Sales Terms & Conditions"-msgstr "Conditions générales de vente"-msgid "Sample"msgstr "Échantillon"@@ -7182,6 +7158,9 @@ msgstr "Lien de partage"msgid "Share Quote"msgstr "Partager le devis"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "Durée de conservation"@@ -7293,12 +7272,6 @@ msgstr "Afficher les durées"msgid "Show parent items"msgstr "Afficher les éléments parents"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Afficher les vignettes des pièces sur les PDF des commandes d'achat."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Afficher les vignettes des pièces sur les devis, les commandes de vente, les factures et les expéditions."-msgid "Show Supplier IDs"msgstr "Afficher les ID fournisseur"@@ -7353,6 +7326,9 @@ msgstr "Ignoré"msgid "Something went wrong. Please try again."msgstr "Quelque chose s'est mal passé. Veuillez réessayer."+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "L'expiration la plus proche parmi tous les matériaux détermine le produit fini."@@ -7795,6 +7771,9 @@ msgstr "Température"msgid "Template ID"msgstr "ID de modèle"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "Conditions et Confidentialité"@@ -8764,12 +8743,6 @@ msgstr "Centres de travail"msgid "Work Instructions"msgstr "Instructions de travail"-msgid "Work instructions are included"-msgstr "Les instructions de travail sont incluses"--msgid "Work instructions are not included"-msgstr "Les instructions de travail ne sont pas incluses"-msgid "Work Phone"msgstr "Téléphone professionnel"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex d8b93634b3..936ed0c92d 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -1534,9 +1534,6 @@ msgstr "दुकान के फर्श से रखरखाव डिसmsgid "Configure notifications for when new suggestions are submitted."msgstr "नए सुझाव जमा किए जाने पर सूचनाएं कॉन्फ़िगर करें।"-msgid "Configure the content displayed on job traveler PDFs."-msgstr "जॉब ट्रैवलर पीडीएफ पर प्रदर्शित सामग्री को कॉन्फ़िगर करें।"-msgid "Configure the default accounts used for various transaction types across your system"msgstr "विभिन्न लेनदेन प्रकारों के लिए आपके सिस्टम में उपयोग किए जाने वाले डिफ़ॉल्ट खातों को कॉन्फ़िगर करें"@@ -2116,6 +2113,9 @@ msgstr "ग्राहक प्रकार"msgid "Customers"msgstr "ग्राहक"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "दैनिक उपयोग"@@ -2252,12 +2252,6 @@ msgstr "डिफ़ॉल्ट यूनिट"msgid "Defaults"msgstr "डिफ़ॉल्ट"-msgid "Define the terms and conditions for purchase orders"-msgstr "क्रय आदेशों के लिए शर्तें और शर्तें परिभाषित करें"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "उद्धरण और बिक्री आदेशों के लिए शर्तें और शर्तें परिभाषित करें"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "परिभाषित करता है कि प्रति लॉट कितनी ट्रैक की गई संस्थाओं का निरीक्षण किया जाता है, और लॉट को अस्वीकार करने से पहले कितनी विफलताओं को सहन किया जाता है।"@@ -2606,6 +2600,9 @@ msgstr "दस्तावेज़"msgid "Document Control"msgstr "दस्तावेज़ नियंत्रण"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "दस्तावेज़:"@@ -3045,9 +3042,6 @@ msgstr "कर-विशिष्ट मूल्यह्रास विधिmsgid "Enable to generate IDs and descriptions for raw materials."msgstr "कच्चे माल के लिए आईडी और विवरण उत्पन्न करने के लिए सक्षम करें।"-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "जॉब ट्रैवलर PDFs पर कार्य निर्देश शामिल करने के लिए सक्षम करें।"-msgid "Enable to start tracking changes to your data."msgstr "अपने डेटा में परिवर्तन ट्रैक करना शुरू करने के लिए सक्षम करें।"@@ -3948,12 +3942,6 @@ msgstr "शिपमेंट में अतिरिक्त पार्टmsgid "Include Inactive"msgstr "निष्क्रिय शामिल करें"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "खरीद दस्तावेजों पर थंबनेल शामिल करें"--msgid "Include Thumbnails on Sales Documents"-msgstr "बिक्रय दस्तावेज़ों पर थंबनेल शामिल करें"-msgid "Includes tax and shipping costs"msgstr "कर और शिपिंग लागत शामिल है"@@ -4239,12 +4227,6 @@ msgstr "जॉब ऑपरेशन"msgid "Job Operations"msgstr "कार्य संचालन"-msgid "Job Traveler"-msgstr "जॉब ट्रैवलर"--msgid "Job traveler PDFs include work instructions."-msgstr "जॉब ट्रैवलर पीडीएफ में कार्य निर्देश शामिल हैं।"-msgid "Jobs"msgstr "नौकरियां"@@ -6170,9 +6152,6 @@ msgstr "क्रय"msgid "Purchasing Contact"msgstr "क्रय संपर्क"-msgid "Purchasing Terms & Conditions"-msgstr "क्रय शर्तें और शर्तें"-msgid "Purchasing Unit of Measure"msgstr "क्रय माप की इकाई"@@ -6783,9 +6762,6 @@ msgstr "विक्रय व्यक्ति"msgid "Sales Revenue"msgstr "बिक्रय राजस्व"-msgid "Sales Terms & Conditions"-msgstr "बिक्रय शर्तें और शर्तें"-msgid "Sample"msgstr "नमूना"@@ -7182,6 +7158,9 @@ msgstr "लिंक साझा करें"msgid "Share Quote"msgstr "उद्धरण साझा करें"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "शेल्फ लाइफ"@@ -7293,12 +7272,6 @@ msgstr "अवधि दिखाएं"msgid "Show parent items"msgstr "माता-पिता की वस्तुओं को दिखाएं"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "खरीद आदेश पीडीएफ पर भाग थंबनेल दिखाएं।"--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "उद्धरण, बिक्री आदेश, चालान और शिपमेंट पर भाग थंबनेल दिखाएं।"-msgid "Show Supplier IDs"msgstr "आपूर्तिकर्ता आईडी दिखाएं"@@ -7353,6 +7326,9 @@ msgstr "छोड़ा गया"msgid "Something went wrong. Please try again."msgstr "कुछ गलत हो गया। कृपया पुनः प्रयास करें।"+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "सबसे जल्दी समाप्त होने वाली सामग्री तैयार माल को निर्धारित करती है।"@@ -7795,6 +7771,9 @@ msgstr "तापमान"msgid "Template ID"msgstr "टेम्पलेट आईडी"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "शर्तें और गोपनीयता"@@ -8764,12 +8743,6 @@ msgstr "कार्य केंद्र"msgid "Work Instructions"msgstr "कार्य निर्देश"-msgid "Work instructions are included"-msgstr "कार्य निर्देश शामिल हैं"--msgid "Work instructions are not included"-msgstr "कार्य निर्देश शामिल नहीं हैं"-msgid "Work Phone"msgstr "कार्य फोन"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 8821f89ece..ca165378e8 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -1534,9 +1534,6 @@ msgstr "Configura le notifiche per quando gli ordini di manutenzione vengono cremsgid "Configure notifications for when new suggestions are submitted."msgstr "Configura le notifiche per quando vengono inviate nuove suggerimenti."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Configura il contenuto visualizzato nei PDF del foglio di viaggio del lavoro."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Configura gli account predefiniti utilizzati per vari tipi di transazioni nel tuo sistema"@@ -2116,6 +2113,9 @@ msgstr "Tipi di Cliente"msgid "Customers"msgstr "Clienti"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "Utilizzo Giornaliero"@@ -2252,12 +2252,6 @@ msgstr "Unità Predefinita"msgid "Defaults"msgstr "Impostazioni predefinite"-msgid "Define the terms and conditions for purchase orders"-msgstr "Definire i termini e le condizioni per gli ordini di acquisto"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Definire i termini e le condizioni per preventivi e ordini di vendita"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Definisce quante entità tracciate vengono ispezionate per lotto e quanti difetti sono tollerati prima che il lotto venga rifiutato."@@ -2606,6 +2600,9 @@ msgstr "Documento"msgid "Document Control"msgstr "Controllo Documenti"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "Documento:"@@ -3045,9 +3042,6 @@ msgstr "Abilita per configurare metodi di ammortamento specifici per le impostemsgid "Enable to generate IDs and descriptions for raw materials."msgstr "Abilita per generare ID e descrizioni per le materie prime."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Abilita per includere le istruzioni di lavoro nei PDF del foglio di viaggio."-msgid "Enable to start tracking changes to your data."msgstr "Abilita per iniziare a tracciare le modifiche ai tuoi dati."@@ -3948,12 +3942,6 @@ msgstr "Includi parti extra nella spedizione"msgid "Include Inactive"msgstr "Includi Inattivi"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Includi miniature nei documenti di acquisto"--msgid "Include Thumbnails on Sales Documents"-msgstr "Includi miniature nei documenti di vendita"-msgid "Includes tax and shipping costs"msgstr "Include tasse e costi di spedizione"@@ -4239,12 +4227,6 @@ msgstr "Operazione di Lavoro"msgid "Job Operations"msgstr "Operazioni di Lavoro"-msgid "Job Traveler"-msgstr "Documento di Viaggio Lavoro"--msgid "Job traveler PDFs include work instructions."-msgstr "I PDF del foglio di lavoro includono istruzioni di lavoro."-msgid "Jobs"msgstr "Lavori"@@ -6170,9 +6152,6 @@ msgstr "Acquisti"msgid "Purchasing Contact"msgstr "Contatto Acquisti"-msgid "Purchasing Terms & Conditions"-msgstr "Termini e Condizioni di Acquisto"-msgid "Purchasing Unit of Measure"msgstr "Unità di Misura di Acquisto"@@ -6783,9 +6762,6 @@ msgstr "Addetto alle vendite"msgid "Sales Revenue"msgstr "Ricavi di vendita"-msgid "Sales Terms & Conditions"-msgstr "Termini e Condizioni di Vendita"-msgid "Sample"msgstr "Campione"@@ -7182,6 +7158,9 @@ msgstr "Condividi Link"msgid "Share Quote"msgstr "Condividi Preventivo"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "Durata di conservazione"@@ -7293,12 +7272,6 @@ msgstr "Mostra durate"msgid "Show parent items"msgstr "Mostra elementi padre"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Mostra le miniature delle parti nei PDF degli ordini di acquisto."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Mostra le miniature delle parti su preventivi, ordini di vendita, fatture e spedizioni."-msgid "Show Supplier IDs"msgstr "Mostra ID Fornitore"@@ -7353,6 +7326,9 @@ msgstr "Saltato"msgid "Something went wrong. Please try again."msgstr "Qualcosa è andato storto. Riprova."+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "La scadenza più prossima tra tutti i materiali determina il prodotto finito."@@ -7795,6 +7771,9 @@ msgstr "Temperatura"msgid "Template ID"msgstr "ID Modello"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "Termini e Privacy"@@ -8764,12 +8743,6 @@ msgstr "Centri di Lavoro"msgid "Work Instructions"msgstr "Istruzioni di lavoro"-msgid "Work instructions are included"-msgstr "Le istruzioni di lavoro sono incluse"--msgid "Work instructions are not included"-msgstr "Le istruzioni di lavoro non sono incluse"-msgid "Work Phone"msgstr "Telefono di lavoro"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 41015ef558..2cca47e4b5 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -1534,9 +1534,6 @@ msgstr "保全ディスパッチが作業現場から作成されるときの通msgid "Configure notifications for when new suggestions are submitted."msgstr "新しい提案が送信されたときの通知を設定します。"-msgid "Configure the content displayed on job traveler PDFs."-msgstr "ジョブトラベラーPDFに表示されるコンテンツを設定します。"-msgid "Configure the default accounts used for various transaction types across your system"msgstr "様々なトランザクションタイプに使用されるデフォルトアカウントをシステム全体で設定します"@@ -2116,6 +2113,9 @@ msgstr "顧客タイプ"msgid "Customers"msgstr "顧客"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "日次使用量"@@ -2252,12 +2252,6 @@ msgstr "デフォルト単位"msgid "Defaults"msgstr "デフォルト"-msgid "Define the terms and conditions for purchase orders"-msgstr "購買注文の利用規約と条件を定義します"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "見積書と販売注文の利用規約と条件を定義します"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "ロットごとに検査される追跡対象エンティティの数と、ロットが却下される前に許容される失敗の数を定義します。"@@ -2606,6 +2600,9 @@ msgstr "ドキュメント"msgid "Document Control"msgstr "ドキュメント管理"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "ドキュメント:"@@ -3045,9 +3042,6 @@ msgstr "税固有の減価償却方法を資産クラスで設定するためにmsgid "Enable to generate IDs and descriptions for raw materials."msgstr "有効にして、原材料のIDと説明を生成します。"-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "ジョブトラベラーPDFに作業指示を含めるには有効にしてください。"-msgid "Enable to start tracking changes to your data."msgstr "データへの変更の追跡を開始するには有効にしてください。"@@ -3948,12 +3942,6 @@ msgstr "出荷に追加部品を含める"msgid "Include Inactive"msgstr "非アクティブを含める"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "購買ドキュメントにサムネイルを含める"--msgid "Include Thumbnails on Sales Documents"-msgstr "販売ドキュメントにサムネイルを含める"-msgid "Includes tax and shipping costs"msgstr "税金と送料を含みます"@@ -4239,12 +4227,6 @@ msgstr "作業操作"msgid "Job Operations"msgstr "ジョブ操作"-msgid "Job Traveler"-msgstr "ジョブトラベラー"--msgid "Job traveler PDFs include work instructions."-msgstr "ジョブトラベラーPDFに作業指示が含まれています。"-msgid "Jobs"msgstr "ジョブ"@@ -6170,9 +6152,6 @@ msgstr "購買"msgid "Purchasing Contact"msgstr "購買担当者"-msgid "Purchasing Terms & Conditions"-msgstr "購買条件"-msgid "Purchasing Unit of Measure"msgstr "購買単位"@@ -6783,9 +6762,6 @@ msgstr "営業担当者"msgid "Sales Revenue"msgstr "売上収益"-msgid "Sales Terms & Conditions"-msgstr "営業条件"-msgid "Sample"msgstr "サンプル"@@ -7182,6 +7158,9 @@ msgstr "リンクを共有"msgid "Share Quote"msgstr "見積もりを共有"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "棚卸し期間"@@ -7293,12 +7272,6 @@ msgstr "期間を表示"msgid "Show parent items"msgstr "親アイテムを表示"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "購買注文PDFに部品のサムネイルを表示します。"--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "見積書、販売注文書、請求書、および出荷書にパーツサムネイルを表示します。"-msgid "Show Supplier IDs"msgstr "仕入先IDを表示"@@ -7353,6 +7326,9 @@ msgstr "スキップ"msgid "Something went wrong. Please try again."msgstr "何か問題が発生しました。もう一度お試しください。"+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "最も早い有効期限が完成品を決定します。"@@ -7795,6 +7771,9 @@ msgstr "温度"msgid "Template ID"msgstr "テンプレートID"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "利用規約とプライバシー"@@ -8764,12 +8743,6 @@ msgstr "作業センター"msgid "Work Instructions"msgstr "作業指示"-msgid "Work instructions are included"-msgstr "作業指示が含まれています"--msgid "Work instructions are not included"-msgstr "作業指示は含まれていません"-msgid "Work Phone"msgstr "仕事用電話"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex d8bcd2524f..452f1b2c7d 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -1534,9 +1534,6 @@ msgstr "Skonfiguruj powiadomienia dla dyspozycji konserwacyjnych tworzonych z hamsgid "Configure notifications for when new suggestions are submitted."msgstr "Skonfiguruj powiadomienia dla nowych przesłanych sugestii."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Skonfiguruj zawartość wyświetlaną w plikach PDF podróżnika zadania."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Skonfiguruj domyślne konta używane dla różnych typów transakcji w całym systemie"@@ -2116,6 +2113,9 @@ msgstr "Typy klientów"msgid "Customers"msgstr "Klienci"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "Dzienne użycie"@@ -2252,12 +2252,6 @@ msgstr "Jednostka domyślna"msgid "Defaults"msgstr "Ustawienia domyślne"-msgid "Define the terms and conditions for purchase orders"-msgstr "Zdefiniuj warunki i zasady dla zamówień zakupu"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Zdefiniuj warunki i zasady dla ofert i zamówień sprzedaży"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Określa, ile śledzonych jednostek jest sprawdzanych na partię i ile błędów jest tolerowanych przed odrzuceniem partii."@@ -2606,6 +2600,9 @@ msgstr "Dokument"msgid "Document Control"msgstr "Kontrola dokumentów"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "Dokument:"@@ -3045,9 +3042,6 @@ msgstr "Włącz, aby skonfigurować metody amortyzacji specyficzne dla podatku nmsgid "Enable to generate IDs and descriptions for raw materials."msgstr "Włącz, aby generować identyfikatory i opisy dla surowców."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Włącz, aby dołączyć instrukcje pracy do plików PDF podróżnika zadania."-msgid "Enable to start tracking changes to your data."msgstr "Włącz, aby rozpocząć śledzenie zmian w Twoich danych."@@ -3948,12 +3942,6 @@ msgstr "Dołącz dodatkowe części do wysyłki"msgid "Include Inactive"msgstr "Uwzględnij nieaktywne"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Dołącz miniatury w dokumentach zakupowych"--msgid "Include Thumbnails on Sales Documents"-msgstr "Dołącz miniatury do dokumentów sprzedaży"-msgid "Includes tax and shipping costs"msgstr "Obejmuje podatki i koszty wysyłki"@@ -4239,12 +4227,6 @@ msgstr "Operacja zadania"msgid "Job Operations"msgstr "Operacje Zadań"-msgid "Job Traveler"-msgstr "Dokument Podróży Pracy"--msgid "Job traveler PDFs include work instructions."-msgstr "Pliki PDF podróżnika zadania zawierają instrukcje pracy."-msgid "Jobs"msgstr "Zadania"@@ -6170,9 +6152,6 @@ msgstr "Zakupy"msgid "Purchasing Contact"msgstr "Kontakt ds. Zakupów"-msgid "Purchasing Terms & Conditions"-msgstr "Warunki zakupu i dostawy"-msgid "Purchasing Unit of Measure"msgstr "Jednostka miary zakupu"@@ -6783,9 +6762,6 @@ msgstr "Pracownik sprzedaży"msgid "Sales Revenue"msgstr "Przychód ze sprzedaży"-msgid "Sales Terms & Conditions"-msgstr "Warunki sprzedaży"-msgid "Sample"msgstr "Próbka"@@ -7182,6 +7158,9 @@ msgstr "Udostępnij Link"msgid "Share Quote"msgstr "Udostępnij Ofertę"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "Okres przydatności"@@ -7293,12 +7272,6 @@ msgstr "Pokaż czasy trwania"msgid "Show parent items"msgstr "Pokaż elementy nadrzędne"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Pokaż miniatury części na plikach PDF zamówień zakupu."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Pokaż miniatury części na ofertach, zamówieniach sprzedaży, fakturach i wysyłkach."-msgid "Show Supplier IDs"msgstr "Pokaż identyfikatory dostawców"@@ -7353,6 +7326,9 @@ msgstr "Pominięte"msgid "Something went wrong. Please try again."msgstr "Coś poszło nie tak. Spróbuj ponownie."+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "Najwcześniejsza data wygaśnięcia spośród wszystkich materiałów określa produkt gotowy."@@ -7795,6 +7771,9 @@ msgstr "Temperatura"msgid "Template ID"msgstr "Identyfikator szablonu"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "Regulamin i prywatnosc"@@ -8764,12 +8743,6 @@ msgstr "Centra pracy"msgid "Work Instructions"msgstr "Instrukcje pracy"-msgid "Work instructions are included"-msgstr "Instrukcje pracy są dołączone"--msgid "Work instructions are not included"-msgstr "Instrukcje pracy nie są uwzględnione"-msgid "Work Phone"msgstr "Telefon służbowy"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex f9e2ffdcc5..f39a2b9a0c 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -1534,9 +1534,6 @@ msgstr "Configure notificações para quando despachos de manutenção são criamsgid "Configure notifications for when new suggestions are submitted."msgstr "Configure notificações para quando novas sugestões são enviadas."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Configure o conteúdo exibido nos PDFs do job traveler."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Configure as contas padrão usadas para vários tipos de transação em todo o seu sistema"@@ -2116,6 +2113,9 @@ msgstr "Tipos de Cliente"msgid "Customers"msgstr "Clientes"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "Uso Diário"@@ -2252,12 +2252,6 @@ msgstr "Unidade Padrão"msgid "Defaults"msgstr "Padrões"-msgid "Define the terms and conditions for purchase orders"-msgstr "Defina os termos e condições para pedidos de compra"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Defina os termos e condições para cotações e pedidos de venda"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Define quantas entidades rastreadas são inspecionadas por lote e quantas falhas são toleradas antes que o lote seja rejeitado."@@ -2606,6 +2600,9 @@ msgstr "Documento"msgid "Document Control"msgstr "Controle de Documentos"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "Documento:"@@ -3045,9 +3042,6 @@ msgstr "Ativar para configurar métodos de depreciação específicos de impostomsgid "Enable to generate IDs and descriptions for raw materials."msgstr "Ativar para gerar IDs e descrições para matérias-primas."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Ativar para incluir instruções de trabalho nos PDFs do viajante de trabalho."-msgid "Enable to start tracking changes to your data."msgstr "Ative para começar a rastrear alterações nos seus dados."@@ -3948,12 +3942,6 @@ msgstr "Incluir peças extras no envio"msgid "Include Inactive"msgstr "Incluir Inativos"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Incluir Miniaturas em Documentos de Compra"--msgid "Include Thumbnails on Sales Documents"-msgstr "Incluir Miniaturas em Documentos de Vendas"-msgid "Includes tax and shipping costs"msgstr "Inclui impostos e custos de envio"@@ -4239,12 +4227,6 @@ msgstr "Operação de Trabalho"msgid "Job Operations"msgstr "Operações de Trabalho"-msgid "Job Traveler"-msgstr "Viagem de Trabalho"--msgid "Job traveler PDFs include work instructions."-msgstr "Os PDFs do viajante de trabalho incluem instruções de trabalho."-msgid "Jobs"msgstr "Trabalhos"@@ -6170,9 +6152,6 @@ msgstr "Compras"msgid "Purchasing Contact"msgstr "Contacto de Compras"-msgid "Purchasing Terms & Conditions"-msgstr "Termos e Condições de Compra"-msgid "Purchasing Unit of Measure"msgstr "Unidade de Medida de Compra"@@ -6783,9 +6762,6 @@ msgstr "Pessoa de Vendas"msgid "Sales Revenue"msgstr "Receita de Vendas"-msgid "Sales Terms & Conditions"-msgstr "Termos e Condições de Vendas"-msgid "Sample"msgstr "Amostra"@@ -7182,6 +7158,9 @@ msgstr "Compartilhar Link"msgid "Share Quote"msgstr "Compartilhar Cotação"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "Vida útil"@@ -7293,12 +7272,6 @@ msgstr "Mostrar Durações"msgid "Show parent items"msgstr "Mostrar itens pai"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Mostrar miniaturas de peças em PDFs de pedidos de compra."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Mostrar miniaturas de peças em cotações, pedidos de venda, faturas e remessas."-msgid "Show Supplier IDs"msgstr "Mostrar IDs de Fornecedor"@@ -7353,6 +7326,9 @@ msgstr "Ignorado"msgid "Something went wrong. Please try again."msgstr "Algo deu errado. Tente novamente."+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "A expiração mais próxima em todos os materiais define o produto acabado."@@ -7795,6 +7771,9 @@ msgstr "Temperatura"msgid "Template ID"msgstr "ID do Modelo"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "Termos e Privacidade"@@ -8764,12 +8743,6 @@ msgstr "Centros de Trabalho"msgid "Work Instructions"msgstr "Instruções de Trabalho"-msgid "Work instructions are included"-msgstr "As instruções de trabalho estão incluídas"--msgid "Work instructions are not included"-msgstr "As instruções de trabalho não estão incluídas"-msgid "Work Phone"msgstr "Telefone Comercial"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 28e711b563..f356b2eb6f 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -1534,9 +1534,6 @@ msgstr "Настройте уведомления для случаев, когmsgid "Configure notifications for when new suggestions are submitted."msgstr "Настройте уведомления для новых предложений."-msgid "Configure the content displayed on job traveler PDFs."-msgstr "Настройте содержимое, отображаемое в PDF-файлах путевого листа работы."-msgid "Configure the default accounts used for various transaction types across your system"msgstr "Настройте учетные записи по умолчанию, используемые для различных типов транзакций в вашей системе"@@ -2116,6 +2113,9 @@ msgstr "Типы клиентов"msgid "Customers"msgstr "Клиенты"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "Ежедневное использование"@@ -2252,12 +2252,6 @@ msgstr "Единица по умолчанию"msgid "Defaults"msgstr "Значения по умолчанию"-msgid "Define the terms and conditions for purchase orders"-msgstr "Определите условия и положения для заказов на покупку"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "Определите условия и положения для предложений и заказов на продажу"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "Определяет, сколько отслеживаемых объектов проверяется на партию и сколько отказов допускается перед отклонением партии."@@ -2606,6 +2600,9 @@ msgstr "Документ"msgid "Document Control"msgstr "Управление документами"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "Документ:"@@ -3045,9 +3042,6 @@ msgstr "Включите, чтобы настроить методы налогmsgid "Enable to generate IDs and descriptions for raw materials."msgstr "Включите для создания идентификаторов и описаний для сырья."-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "Включите, чтобы добавить рабочие инструкции в PDF-файлы маршрутных листов."-msgid "Enable to start tracking changes to your data."msgstr "Включите, чтобы начать отслеживание изменений ваших данных."@@ -3948,12 +3942,6 @@ msgstr "Включить дополнительные детали в отпраmsgid "Include Inactive"msgstr "Включить неактивные"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "Включить миниатюры в документы закупок"--msgid "Include Thumbnails on Sales Documents"-msgstr "Включить миниатюры в документы продаж"-msgid "Includes tax and shipping costs"msgstr "Включает налоги и стоимость доставки"@@ -4239,12 +4227,6 @@ msgstr "Операция задания"msgid "Job Operations"msgstr "Операции задания"-msgid "Job Traveler"-msgstr "Путевой лист работы"--msgid "Job traveler PDFs include work instructions."-msgstr "PDF-документы маршрутного листа включают рабочие инструкции."-msgid "Jobs"msgstr "Работы"@@ -6170,9 +6152,6 @@ msgstr "Закупки"msgid "Purchasing Contact"msgstr "Контакт по закупкам"-msgid "Purchasing Terms & Conditions"-msgstr "Условия закупки"-msgid "Purchasing Unit of Measure"msgstr "Единица измерения закупки"@@ -6783,9 +6762,6 @@ msgstr "Менеджер по продажам"msgid "Sales Revenue"msgstr "Выручка от продаж"-msgid "Sales Terms & Conditions"-msgstr "Условия продажи"-msgid "Sample"msgstr "Образец"@@ -7182,6 +7158,9 @@ msgstr "Поделиться ссылкой"msgid "Share Quote"msgstr "Поделиться предложением"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "Срок годности"@@ -7293,12 +7272,6 @@ msgstr "Показать длительность"msgid "Show parent items"msgstr "Показать родительские элементы"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "Показывать миниатюры деталей в PDF-файлах заказов на покупку."--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "Показывать миниатюры деталей на предложениях, заказах на продажу, счетах-фактурах и отправках."-msgid "Show Supplier IDs"msgstr "Показать ID поставщиков"@@ -7353,6 +7326,9 @@ msgstr "Пропущено"msgid "Something went wrong. Please try again."msgstr "Что-то пошло не так. Пожалуйста, попробуйте еще раз."+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "Самый ранний срок истечения среди всех материалов определяет готовый продукт."@@ -7795,6 +7771,9 @@ msgstr "Температура"msgid "Template ID"msgstr "ID шаблона"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "Условия и конфиденциальность"@@ -8764,12 +8743,6 @@ msgstr "Рабочие центры"msgid "Work Instructions"msgstr "Рабочие инструкции"-msgid "Work instructions are included"-msgstr "Рабочие инструкции включены"--msgid "Work instructions are not included"-msgstr "Рабочие инструкции не включены"-msgid "Work Phone"msgstr "Рабочий телефон"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 14b6a6b0a1..86820dfc45 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -1534,9 +1534,6 @@ msgstr "配置当从车间创建维护派遣时的通知。通知根据故障模msgid "Configure notifications for when new suggestions are submitted."msgstr "配置在提交新建议时的通知。"-msgid "Configure the content displayed on job traveler PDFs."-msgstr "配置在工作单据PDF上显示的内容。"-msgid "Configure the default accounts used for various transaction types across your system"msgstr "配置用于系统中各种交易类型的默认账户"@@ -2116,6 +2113,9 @@ msgstr "客户类型"msgid "Customers"msgstr "客户"+msgid "Customize the layout of your PDF documents — reorder sections, hide what you don't need, and add your own blocks."+msgstr ""+msgid "Daily Usage"msgstr "日常使用"@@ -2252,12 +2252,6 @@ msgstr "默认单位"msgid "Defaults"msgstr "默认值"-msgid "Define the terms and conditions for purchase orders"-msgstr "定义采购订单的条款和条件"--msgid "Define the terms and conditions for quotes and sales orders"-msgstr "定义报价单和销售订单的条款和条件"-msgid "Defines how many tracked entities are inspected per lot, and how many failures are tolerated before the lot is rejected."msgstr "定义每批检查多少个跟踪实体,以及在批次被拒绝前允许多少个失败。"@@ -2606,6 +2600,9 @@ msgstr "文档"msgid "Document Control"msgstr "文件控制"+msgid "Document Templates"+msgstr ""+msgid "Document:"msgstr "文档:"@@ -3045,9 +3042,6 @@ msgstr "启用以在资产类别上配置特定于税收的折旧方法(例如msgid "Enable to generate IDs and descriptions for raw materials."msgstr "启用以为原材料生成ID和描述。"-msgid "Enable to include work instructions on job traveler PDFs."-msgstr "启用以在工作单据 PDF 上包含工作说明。"-msgid "Enable to start tracking changes to your data."msgstr "启用以开始跟踪您的数据变化。"@@ -3948,12 +3942,6 @@ msgstr "在发货中包含额外零件"msgid "Include Inactive"msgstr "包括不活跃"-msgid "Include Thumbnails on Purchasing Documents"-msgstr "在采购文件上包含缩略图"--msgid "Include Thumbnails on Sales Documents"-msgstr "在销售文件上包含缩略图"-msgid "Includes tax and shipping costs"msgstr "包括税费和运费"@@ -4239,12 +4227,6 @@ msgstr "工作操作"msgid "Job Operations"msgstr "工作操作"-msgid "Job Traveler"-msgstr "工作单据"--msgid "Job traveler PDFs include work instructions."-msgstr "工作单据PDF包含工作说明。"-msgid "Jobs"msgstr "工作"@@ -6170,9 +6152,6 @@ msgstr "采购"msgid "Purchasing Contact"msgstr "采购联系人"-msgid "Purchasing Terms & Conditions"-msgstr "采购条款和条件"-msgid "Purchasing Unit of Measure"msgstr "采购计量单位"@@ -6783,9 +6762,6 @@ msgstr "销售人员"msgid "Sales Revenue"msgstr "销售收入"-msgid "Sales Terms & Conditions"-msgstr "销售条款和条件"-msgid "Sample"msgstr "样本"@@ -7182,6 +7158,9 @@ msgstr "分享链接"msgid "Share Quote"msgstr "分享报价"+msgid "Shared Sections"+msgstr ""+msgid "Shelf life"msgstr "保质期"@@ -7293,12 +7272,6 @@ msgstr "显示时长"msgid "Show parent items"msgstr "显示父项"-msgid "Show part thumbnails on purchase order PDFs."-msgstr "在采购订单 PDF 上显示零件缩略图。"--msgid "Show part thumbnails on quotes, sales orders, invoices, and shipments."-msgstr "在报价单、销售订单、发票和发货单上显示零件缩略图。"-msgid "Show Supplier IDs"msgstr "显示供应商ID"@@ -7353,6 +7326,9 @@ msgstr "已跳过"msgid "Something went wrong. Please try again."msgstr "出现问题。请重试。"+msgid "Soon"+msgstr ""+msgid "Soonest expiry across every material sets the finished good."msgstr "最早的过期日期决定了成品的保质期。"@@ -7795,6 +7771,9 @@ msgstr "温度"msgid "Template ID"msgstr "模板 ID"+msgid "Templates"+msgstr ""+msgid "Terms and Privacy"msgstr "条款和隐私"@@ -8764,12 +8743,6 @@ msgstr "工作中心"msgid "Work Instructions"msgstr "工作说明"-msgid "Work instructions are included"-msgstr "工作说明已包含"--msgid "Work instructions are not included"-msgstr "工作说明未包含"-msgid "Work Phone"msgstr "工作电话"diff --git a/packages/react/src/Editor/Editor.tsx b/packages/react/src/Editor/Editor.tsxindex 5ff83c2eb7..d4a159cf26 100644Binary files a/packages/react/src/Editor/Editor.tsx and b/packages/react/src/Editor/Editor.tsx differdiff --git a/packages/react/src/RichText/RichText.tsx b/packages/react/src/RichText/RichText.tsxindex aaa59161b1..dcfb451769 100644--- a/packages/react/src/RichText/RichText.tsx+++ b/packages/react/src/RichText/RichText.tsx@@ -10,6 +10,8 @@ import { Toolbar } from "./Toolbar";export const useRichText = (content: string) => {const richText = useEditor({+ // Avoid SSR hydration mismatch (Tiptap renders on the client).+ immediatelyRender: false,extensions: [Color.configure({ types: [TextStyle.name, ListItem.name] }),TextStyle,diff --git a/packages/tiptap/src/components/editor.tsx b/packages/tiptap/src/components/editor.tsxindex 2cd2d637f2..a1f84bebdf 100644--- a/packages/tiptap/src/components/editor.tsx+++ b/packages/tiptap/src/components/editor.tsx@@ -37,7 +37,12 @@ export type EditorContentProps = Omit<EditorProviderProps, "content"> & {export const EditorContent = forwardRef<HTMLDivElement, EditorContentProps>(({ className, children, initialContent, ...rest }, ref) => (<div ref={ref} className={className}>- <EditorProvider {...rest} content={initialContent}>+ {/* immediatelyRender false: avoid SSR hydration mismatch (overridable). */}+ <EditorProvider+ immediatelyRender={false}+ {...rest}+ content={initialContent}+ >{children}</EditorProvider></div>diff --git a/packages/tiptap/src/extensions/index.ts b/packages/tiptap/src/extensions/index.tsindex 0d5c1fddd4..a353b2385a 100644--- a/packages/tiptap/src/extensions/index.ts+++ b/packages/tiptap/src/extensions/index.ts@@ -62,6 +62,7 @@ const Horizontal = HorizontalRule.extend({export * from "./ai-highlight";export * from "./mention";+export * from "./merge-token-highlight";export * from "./slash-command";export {CharacterCount,diff --git a/packages/tiptap/src/extensions/merge-token-highlight.ts b/packages/tiptap/src/extensions/merge-token-highlight.tsnew file mode 100644index 0000000000..71fde2f01d--- /dev/null+++ b/packages/tiptap/src/extensions/merge-token-highlight.ts@@ -0,0 +1,69 @@+import { Extension } from "@tiptap/core";+import { Plugin, PluginKey } from "@tiptap/pm/state";+import { Decoration, DecorationSet } from "@tiptap/pm/view";++/** Matches a single-brace merge token like `{invoice.number}`. */+const TOKEN_RE = /\{[\w.]+\}/g;++const KNOWN_CLS = "rounded-sm bg-blue-500/25 ring-1 ring-blue-500/50 px-0.5";+const UNKNOWN_CLS =+ "rounded-sm bg-destructive/20 ring-1 ring-destructive/50 px-0.5";++export interface MergeTokenHighlightOptions {+ /**+ * Token names considered valid (e.g. `invoice.number`). Known tokens render+ * blue, unknown ones red — mirroring the storage-rules condition builder.+ * An empty list treats every `{token}` as known.+ */+ knownTokens: string[];+}++/**+ * Visually highlights `{token}` merge fields with an inline decoration. Purely+ * decorative — the document content stays plain `{token}` text, so merge-field+ * interpolation is unaffected.+ */+export const MergeTokenHighlight = Extension.create<MergeTokenHighlightOptions>(+ {+ name: "mergeTokenHighlight",++ addOptions() {+ return { knownTokens: [] };+ },++ addProseMirrorPlugins() {+ const options = this.options;+ return [+ new Plugin({+ key: new PluginKey("mergeTokenHighlight"),+ props: {+ decorations(state) {+ const known = new Set(options.knownTokens);+ const decorations: Decoration[] = [];+ state.doc.descendants((node, pos) => {+ if (!node.isText || !node.text) return;+ const re = new RegExp(TOKEN_RE);+ let match: RegExpExecArray | null = re.exec(node.text);+ while (match !== null) {+ const token = match[0].slice(1, -1);+ const cls =+ known.size === 0 || known.has(token)+ ? KNOWN_CLS+ : UNKNOWN_CLS;+ const from = pos + match.index;+ decorations.push(+ Decoration.inline(from, from + match[0].length, {+ class: cls+ })+ );+ match = re.exec(node.text);+ }+ });+ return DecorationSet.create(state.doc, decorations);+ }+ }+ })+ ];+ }+ }+);diff --git a/packages/tiptap/src/index.ts b/packages/tiptap/src/index.tsindex e18995e0e6..a5ade06b12 100644--- a/packages/tiptap/src/index.ts+++ b/packages/tiptap/src/index.ts@@ -40,6 +40,8 @@ export {MarkdownExtension,Mention,type MentionSuggestion,+ MergeTokenHighlight,+ type MergeTokenHighlightOptions,Placeholder,removeAIHighlight,renderItems,diff --git a/packages/utils/src/labels.ts b/packages/utils/src/labels.tsindex eb10ff4568..16be602ecc 100644--- a/packages/utils/src/labels.ts+++ b/packages/utils/src/labels.ts@@ -5,6 +5,8 @@ export type ProductLabelItem = {number: string;trackedEntityId: string;trackingType: string;+ /** Custom-field values for the tracked entity, keyed by field id. */+ customFields?: Record<string, unknown>;};export type LabelSize = {@@ -13,6 +15,10 @@ export type LabelSize = {width: number;height: number;metric?: boolean;+ /** Multi-up sheet layout (e.g. Avery). Omitted = a single label per page. */+ rows?: number;+ columns?: number;+ rotated?: boolean;zpl?: {dpi: number;width: number;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 960cc3d2b8..f437aaab06 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1904,6 +1904,9 @@ importers:sst:specifier: 'catalog:'version: 4.6.9+ zod:+ specifier: 'catalog:'+ version: 3.25.76devDependencies:'@carbon/config':specifier: workspace:*