Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix: label template
Sidwebworks33c3596226ca
diff --git a/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx b/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsxindex b80ba14550..ce6bdc4175 100644--- a/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx+++ b/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx@@ -126,6 +126,8 @@ export function BlockList() {// renders as one ZPL `^FD` line — no rich text, key-value lists, spacers, or// shared sections.const isTextOnly = extensionSupport(documentType) === "text";+ // Labels have no page chrome — no footer row.+ const isLabel = documentType === "trackingLabel";const bodySections = sections.filter((s) => s.placement === "body");// Header & footer are page chrome — pinned (not reorderable). Only the body// blocks between them are sortable.@@ -177,7 +179,7 @@ export function BlockList() {)}</Fragment>))}- <FooterRow />+ {!isLabel && <FooterRow />}</div></SortableContext></DndContext>diff --git a/packages/documents/src/pdf/ProductLabelPDF.tsx b/packages/documents/src/pdf/ProductLabelPDF.tsxindex f8cf3e8a18..8177170390 100644--- a/packages/documents/src/pdf/ProductLabelPDF.tsx+++ b/packages/documents/src/pdf/ProductLabelPDF.tsx@@ -10,7 +10,7 @@ import {buildLabelVars,trackingLabelBlockRegistry} from "./blocks/trackingLabel";-import Footer from "./components/Footer";+import { getLabelPdfGeometry } from "./components/labelGeometry";interface ProductLabelProps {items: ProductLabelItem[];@@ -65,44 +65,36 @@ const ProductLabelPDF = ({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- );+ // A single label prints on a page sized exactly to the label, with no+ // margins, so it feeds correctly on a thermal/label printer. Multi-up sheets+ // (rows × columns, e.g. Avery) print on a standard letter sheet with the+ // grid centred.+ const isMultiUp = rows > 1 || columns > 1;+ const pageWidth = isMultiUp ? LETTER_WIDTH : effectiveLabelWidthPt;+ const pageHeight = isMultiUp ? LETTER_HEIGHT : effectiveLabelHeightPt;++ // Font + QR sizing comes from the shared label geometry (203dpi, 2"x1"+ // baseline, unit-matched to the ZPL output) so the PDF and ZPL prints look+ // alike and scale continuously across stock sizes.+ const geometry = getLabelPdfGeometry(labelSize);+ const titleFontSize = geometry.titleFontSize;+ const descriptionFontSize = geometry.descFontSize;+ const qrCodeSize = geometry.qrSize;// Calculate how many pages we needconst 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;+ // Labels never carry a footer (no page numbers / registration line) — every+ // millimetre of the stock is for the label content. Multi-up sheets centre+ // their grid on the letter page; a single label fills its label-sized page+ // edge-to-edge (no margins).const horizontalMargin = isMultiUp? (pageWidth - columns * effectiveLabelWidthPt) / 2- : singleLabelMargin;+ : 0;const verticalMargin = isMultiUp- ? (availableHeight - rows * effectiveLabelHeightPt) / 2- : singleLabelMargin;-- const showFooter = resolved.footerSectionId !== null;+ ? (pageHeight - rows * effectiveLabelHeightPt) / 2+ : 0;return (<Document>@@ -224,13 +216,6 @@ const ProductLabelPDF = ({})}</View>))}- {showFooter && (- <Footer- showPageNumbers={resolved.settings.showPageNumbers}- pageNumberFormat={resolved.settings.pageNumberFormat}- showRegistrationLine={resolved.settings.showRegistrationLine}- />- )}</Page>))}</Document>diff --git a/packages/documents/src/pdf/productLabelPDF.test.ts b/packages/documents/src/pdf/productLabelPDF.test.tsnew file mode 100644index 0000000000..3775c13cb3--- /dev/null+++ b/packages/documents/src/pdf/productLabelPDF.test.ts@@ -0,0 +1,61 @@+import type { LabelSize, ProductLabelItem } from "@carbon/utils";+import { labelSizes } from "@carbon/utils";+import { renderToBuffer } from "@react-pdf/renderer";+import { createElement } from "react";+import { describe, expect, it } from "vitest";+import ProductLabelPDF from "./ProductLabelPDF";++const item: ProductLabelItem = {+ itemId: "WIDGET-100",+ revision: "A",+ quantity: 5,+ number: "SN-0001",+ trackedEntityId: "dtClCvNm9blDY0H3FXmDC",+ trackingType: "Serial"+};++function render(labelSize: LabelSize, items = [item]) {+ return renderToBuffer(+ createElement(ProductLabelPDF, { items, labelSize }) as never+ );+}++/** First /MediaBox [...] in the raw PDF bytes. */+function mediaBox(pdf: Buffer): number[] {+ const match = pdf.toString("latin1").match(/\/MediaBox \[([^\]]+)\]/);+ if (!match) throw new Error("No MediaBox found");+ return match[1]!.trim().split(/\s+/).map(Number);+}++const size = (id: string): LabelSize => {+ const found = labelSizes.find((s) => s.id === id);+ if (!found) throw new Error(`Missing label size ${id}`);+ return found;+};++describe("ProductLabelPDF page sizing", () => {+ it("sizes a single label's page exactly to the label (no margins)", async () => {+ const box = mediaBox(await render(size("label2x1")));+ expect(box).toEqual([0, 0, 2 * 72, 1 * 72]);+ });++ it("sizes metric stock exactly too", async () => {+ const s = size("label50x25mm");+ const box = mediaBox(await render(s));+ expect(box[2]).toBeCloseTo(s.width * 72, 1);+ expect(box[3]).toBeCloseTo(s.height * 72, 1);+ });++ it("multi-up sheets still print on a letter page", async () => {+ const sheet: LabelSize = {+ id: "test-sheet",+ name: "Test sheet",+ width: 4,+ height: 2,+ rows: 5,+ columns: 2+ };+ const box = mediaBox(await render(sheet));+ expect(box).toEqual([0, 0, 8.5 * 72, 11 * 72]);+ });+});diff --git a/packages/documents/src/template/defaults.ts b/packages/documents/src/template/defaults.tsindex bf16872d0e..a800e4addd 100644--- a/packages/documents/src/template/defaults.ts+++ b/packages/documents/src/template/defaults.ts@@ -487,10 +487,11 @@ export const DEFAULT_TEMPLATES: Record<DocumentTemplateType, DocumentTemplate> =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.+ // Labels have no page chrome: the page is the label itself, so there is+ // no header or footer (the renderer ignores them and the editor hides+ // the rows).headerSectionId: null,- footerSectionId: BUILT_IN_SECTION_IDS.footer+ footerSectionId: null}};diff --git a/packages/documents/src/zpl/ProductLabelZPL.tsx b/packages/documents/src/zpl/ProductLabelZPL.tsxindex 5f58282b9f..db473480c9 100644--- a/packages/documents/src/zpl/ProductLabelZPL.tsx+++ b/packages/documents/src/zpl/ProductLabelZPL.tsx@@ -1,6 +1,7 @@import type { LabelSize, ProductLabelItem } from "@carbon/utils";import type { DocumentTemplate } from "../template";import { interpolateString, resolveTemplate } from "../template";+import { getZplLabelGeometry, zplLabelHeader } from "./utils";/** Merge-field values for a label (kept in sync with buildLabelVars). */function labelVars(item: ProductLabelItem): Record<string, string> {@@ -16,106 +17,101 @@ function labelVars(item: ProductLabelItem): Record<string, string> {}/**- * 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. `scale`+ * sizes the QR module so it stays scannable across label stock sizes.*/-/** Map a barcode symbology to its ZPL command for a given dot height. */function zplBarcode(symbology: string,value: string,- heightDots: number+ heightDots: number,+ scale: 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`;+ case "qrcode": {+ // `MA,` field-data prefix = error-correction level M + Automatic input+ // mode. Module scales with the label rather than a fixed step.+ const module = Math.max(2, Math.min(8, Math.round(4 * scale)));+ return `^BQN,2,${module}^FDMA,${value}^FS`;+ }default: // pdf417return `^BY2^B7N,${Math.max(2, Math.floor(heightDots / 20))},5,0,0,N^FD${value}^FS`;}}+/**+ * 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).+ *+ * Sizing is driven by `getZplLabelGeometry` so margins, fonts and the QR scale+ * continuously with the stock (203dpi, 2"x1" baseline), and the header carries+ * `^MNW` (continuous media) + `^CI28` (UTF-8).+ */export function generateProductLabelZPL(item: ProductLabelItem,labelSize: LabelSize,template?: DocumentTemplate | null,logo?: { gfa?: string | null; widthDots?: number } | null): string {- if (!labelSize.zpl) {- throw new Error("Invalid label size or missing ZPL configuration");- }- const { width, height } = labelSize.zpl;- const dpi = labelSize.zpl.dpi || 203;-- // Convert inches to dots based on DPI- const widthDots = Math.round(width * dpi);- const heightDots = Math.round(height * dpi);+ const geometry = getZplLabelGeometry(labelSize);+ const { widthDots, heightDots, hScale, scale, margin } = geometry;- // Determine if this is a small or large label- const isSmallLabel = width <= 2.5; // Consider 2x1 as small+ const titleFont = Math.round(25 * scale);+ const descFont = Math.round(18 * scale);+ const smallFont = Math.round(12 * scale);+ const headingGap = titleFont + Math.round(10 * hScale);+ const descGap = Math.round(25 * scale);- // 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;-- // 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-- const qrStartX = isSmallLabel- ? widthDots - qrSize - 15 // Tighter spacing on small labels- : widthDots - qrSize - 40; // More spacing on larger labels+ // Top-right code slot, scaled to the stock. All dot values are rounded —+ // ZPL coordinates and sizes must be integers.+ const qrModuleSize = Math.max(2, Math.min(8, Math.round(4 * scale)));+ const qrPixelSize = qrModuleSize * 29;+ const qrSlotSize = Math.round(Math.min(heightDots * 0.7, widthDots * 0.3));+ const qrStartX = widthDots - qrSlotSize - margin;+ // Reserve for the bottom entity-id line so flowed barcodes clear it.+ const bottomReserve = smallFont + Math.round(18 * hScale);const resolved = resolveTemplate("trackingLabel", template ?? null);const visibleBlocks = resolved.blocks.filter((block) => block.visible);const vars = labelVars(item);- let zpl = "^XA"; // Start format- zpl += `^PW${widthDots}`;- zpl += `^LL${heightDots}`;+ let zpl = zplLabelHeader(geometry);// Text fields stack from the top, following block order.- let yPosition = 30;+ let yPosition = Math.round(30 * hScale);const textLine = (size: number, text: string) => {- zpl += `^FO${textStartX},${yPosition}^A0N,${size},${size}^FD${text}^FS`;+ zpl += `^FO${margin},${yPosition}^A0N,${size},${size}^FD${text}^FS`;};for (const block of visibleBlocks) {switch (block.type) {case "labelHeading":if (item.itemId) {- textLine(fontSize, item.itemId);+ textLine(titleFont, item.itemId);yPosition += headingGap;}break;case "labelRevision":if (item.revision) {- textLine(descFontSize, `${block.label || "Rev"}: ${item.revision}`);+ textLine(descFont, `${block.label || "Rev"}: ${item.revision}`);yPosition += descGap;}break;case "labelQuantity":if (["Serial", "Batch"].includes(item.trackingType)) {- textLine(descFontSize, `${block.label || "Qty"}: ${item.quantity}`);+ textLine(descFont, `${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}`- );+ textLine(descFont, `${block.label || defaultName}: ${item.number}`);yPosition += descGap;}break;@@ -123,8 +119,8 @@ export function generateProductLabelZPL(// 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`;+ const idY = heightDots - smallFont - Math.round(10 * hScale);+ zpl += `^FO${margin},${idY}^A0N,${smallFont},${smallFont}^FD${value}^FS`;}break;}@@ -132,48 +128,47 @@ export function generateProductLabelZPL(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`;+ const logoX = widthDots - logoW - margin;+ zpl += `^FO${logoX > 0 ? logoX : margin},${Math.round(20 * hScale)}${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;+ // Full-width band that flows below the text, sized to the space+ // left between the text and the bottom entity-id line.+ const gap = Math.round(6 * hScale);const bcY = yPosition + gap;const avail = heightDots - bottomReserve - bcY;const bcHeight = Math.max(20,- Math.min(isSmallLabel ? 60 : 110, avail)+ Math.min(Math.round(110 * scale), avail));- zpl += `^FO${textStartX},${bcY}`;- zpl += zplBarcode(block.symbology, value, bcHeight);+ zpl += `^FO${margin},${bcY}`;+ zpl += zplBarcode(block.symbology, value, bcHeight, scale);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 gap = Math.round(6 * hScale);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)- );+ const bcSize = Math.max(20, Math.min(qrSlotSize, avail));+ const bcX = Math.max(margin, Math.round((widthDots - bcSize) / 2));zpl += `^FO${bcX},${bcY}`;- zpl += zplBarcode(block.symbology, value, bcSize);+ zpl += zplBarcode(block.symbology, value, bcSize, scale);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);+ // Top-right slot. QR positions by its real pixel width.+ const isQr = block.symbology === "qrcode";+ const bcX = isQr ? widthDots - qrPixelSize - margin : qrStartX;+ zpl += `^FO${bcX > 0 ? bcX : margin},${Math.round(30 * hScale)}`;+ zpl += zplBarcode(+ block.symbology,+ value,+ Math.round(110 * scale),+ scale+ );}}break;@@ -183,7 +178,7 @@ export function generateProductLabelZPL(const value = interpolateString(block.value ?? "", vars);const text = block.label ? `${block.label}: ${value}` : value;if (text) {- textLine(descFontSize, text);+ textLine(descFont, text);yPosition += descGap;}break;@@ -191,7 +186,7 @@ export function generateProductLabelZPL(case "customField": {const value = item.customFields?.[block.fieldId];if (value != null && value !== "") {- textLine(descFontSize, `${block.label}: ${value}`);+ textLine(descFont, `${block.label}: ${value}`);yPosition += descGap;}break;diff --git a/packages/documents/src/zpl/productLabelZPL.test.ts b/packages/documents/src/zpl/productLabelZPL.test.tsnew file mode 100644index 0000000000..414ff2a3ec--- /dev/null+++ b/packages/documents/src/zpl/productLabelZPL.test.ts@@ -0,0 +1,110 @@+import type { LabelSize, ProductLabelItem } from "@carbon/utils";+import { labelSizes } from "@carbon/utils";+import { describe, expect, it } from "vitest";+import { resolveTemplate } from "../template";+import { generateProductLabelZPL } from "./ProductLabelZPL";++const item: ProductLabelItem = {+ itemId: "WIDGET-100",+ revision: "A",+ quantity: 5,+ number: "SN-0001",+ trackedEntityId: "dtClCvNm9blDY0H3FXmDC",+ trackingType: "Serial"+};++const zplSizes = labelSizes.filter((s) => s.zpl);+const size = (id: string): LabelSize => {+ const found = labelSizes.find((s) => s.id === id);+ if (!found) throw new Error(`Missing label size ${id}`);+ return found;+};++/** Template exercising every barcode placement path (right/full/center). */+const allPlacementsTemplate = {+ ...resolveTemplate("trackingLabel", null),+ blocks: [+ { id: "h", type: "labelHeading" as const, visible: true },+ {+ id: "b1",+ type: "labelBarcode" as const,+ visible: true,+ symbology: "code128" as const,+ value: "{label.trackedEntityId}",+ placement: "right" as const+ },+ {+ id: "b2",+ type: "labelBarcode" as const,+ visible: true,+ symbology: "qrcode" as const,+ value: "{label.trackedEntityId}",+ placement: "center" as const+ },+ {+ id: "b3",+ type: "labelBarcode" as const,+ visible: true,+ symbology: "code128" as const,+ value: "{label.trackedEntityId}",+ placement: "full" as const+ }+ ]+};++describe("generateProductLabelZPL", () => {+ it("emits the standard header (size, no media tracking, UTF-8)", () => {+ for (const s of zplSizes) {+ const dpi = s.zpl!.dpi || 203;+ const zpl = generateProductLabelZPL(item, s);+ expect(zpl.startsWith("^XA")).toBe(true);+ expect(zpl).toContain(`^PW${Math.round(s.zpl!.width * dpi)}`);+ expect(zpl).toContain(`^LL${Math.round(s.zpl!.height * dpi)}`);+ expect(zpl).toContain("^MNW^CI28");+ expect(zpl.endsWith("^XZ")).toBe(true);+ }+ });++ it("QR codes carry the MA, prefix (error correction + auto mode)", () => {+ const zpl = generateProductLabelZPL(item, size("label2x1"));+ expect(zpl).toContain(`^FDMA,${item.trackedEntityId}`);+ });++ it("QR module size scales with the label stock", () => {+ expect(generateProductLabelZPL(item, size("label2x1"))).toContain(+ "^BQN,2,4"+ );+ expect(generateProductLabelZPL(item, size("label4x2"))).toContain(+ "^BQN,2,8"+ );+ });++ it("fonts and margins scale with the label stock", () => {+ // 2x1 = baseline scale 1; 4x2 = scale 2.+ expect(generateProductLabelZPL(item, size("label2x1"))).toContain(+ "^FO20,30^A0N,25,25"+ );+ expect(generateProductLabelZPL(item, size("label4x2"))).toContain(+ "^FO40,60^A0N,50,50"+ );+ });++ it("emits only integer coordinates and sizes for every placement", () => {+ for (const s of zplSizes) {+ const zpl = generateProductLabelZPL(item, s, allPlacementsTemplate);+ expect(zpl).not.toMatch(/\d+\.\d+/);+ }+ });++ it("throws for sizes without ZPL support", () => {+ expect(() => generateProductLabelZPL(item, size("avery5163"))).toThrow();+ });+});++describe("trackingLabel default template", () => {+ it("has no page chrome (labels carry no header or footer)", () => {+ const resolved = resolveTemplate("trackingLabel", null);+ expect(resolved.headerSectionId).toBeNull();+ expect(resolved.footerSectionId).toBeNull();+ });+});