Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Label Printing (#842)

Brad Barbinbba8c7ebfd28
diff --git a/.gitignore b/.gitignore
index 7040164858..62001e9f1a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,6 +17,7 @@ vite.config.ts.timestamp*
.claude-flow
.claude/settings.json
.claude/settings.local.json
+.claude/scheduled_tasks.lock
.mcp.json
opencode.json
.windsurf
@@ -56,6 +57,8 @@ packages/database/supabase/seed.sql
# C++ (cad-engine)
**/build/
!**/build/.gitkeep
+.orcka
+**/supabase/snippets
# Worktree-isolated dev environment
.carbon-worktree
diff --git a/.pr-review/feat-improve-bulk-imports.html b/.pr-review/feat-improve-bulk-imports.html
deleted file mode 100644
index 5a75913394..0000000000
--- a/.pr-review/feat-improve-bulk-imports.html
+++ /dev/null
@@ -1,708 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-<meta charset="UTF-8">
-<meta name="viewport" content="width=device-width, initial-scale=1.0">
-<title>PR Review: Improve Bulk Imports</title>
-<style>
- :root {
- --bg: #0d1117;
- --surface: #161b22;
- --surface2: #1c2128;
- --border: #30363d;
- --text: #e6edf3;
- --text-muted: #8b949e;
- --accent: #58a6ff;
- --green: #3fb950;
- --green-bg: rgba(63, 185, 80, 0.1);
- --red: #f85149;
- --red-bg: rgba(248, 81, 73, 0.1);
- --yellow: #d29922;
- --yellow-bg: rgba(210, 153, 34, 0.12);
- --purple: #bc8cff;
- }
- * { margin: 0; padding: 0; box-sizing: border-box; }
- body {
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
- background: var(--bg);
- color: var(--text);
- line-height: 1.6;
- max-width: 900px;
- margin: 0 auto;
- padding: 2rem 1.5rem;
- }
- h1 { font-size: 1.75rem; margin-bottom: 0.25rem; }
- h2 { font-size: 1.35rem; color: var(--accent); margin: 2.5rem 0 1rem; border-bottom: 1px solid var(--border); padding-bottom: 0.5rem; }
- h3 { font-size: 1.1rem; margin: 1.5rem 0 0.75rem; color: var(--text); }
- p { margin-bottom: 0.75rem; }
- a { color: var(--accent); text-decoration: none; }
- a:hover { text-decoration: underline; }
- code { background: var(--surface2); padding: 0.15em 0.4em; border-radius: 4px; font-size: 0.9em; font-family: 'SF Mono', 'Fira Code', monospace; }
- ul, ol { padding-left: 1.5rem; margin-bottom: 0.75rem; }
- li { margin-bottom: 0.35rem; }
-
- .hero {
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: 8px;
- padding: 1.5rem;
- margin-bottom: 2rem;
- }
- .hero .subtitle { color: var(--text-muted); font-size: 1rem; margin-bottom: 1rem; }
- .metrics {
- display: flex;
- gap: 1.5rem;
- flex-wrap: wrap;
- margin-top: 1rem;
- }
- .metric {
- background: var(--surface2);
- border: 1px solid var(--border);
- border-radius: 6px;
- padding: 0.5rem 0.85rem;
- font-size: 0.85rem;
- }
- .metric strong { color: var(--accent); }
-
- .callout {
- border-left: 3px solid var(--yellow);
- background: var(--yellow-bg);
- padding: 0.75rem 1rem;
- border-radius: 0 6px 6px 0;
- margin: 1rem 0;
- font-size: 0.92rem;
- }
- .callout.info {
- border-color: var(--accent);
- background: rgba(88, 166, 255, 0.08);
- }
- .callout.success {
- border-color: var(--green);
- background: var(--green-bg);
- }
-
- .diff {
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: 8px;
- margin: 1rem 0;
- overflow: hidden;
- }
- .diff-title {
- background: var(--surface2);
- padding: 0.5rem 1rem;
- font-size: 0.82rem;
- font-family: 'SF Mono', 'Fira Code', monospace;
- color: var(--text-muted);
- border-bottom: 1px solid var(--border);
- }
- .diff pre {
- padding: 0.75rem 1rem;
- font-size: 0.82rem;
- font-family: 'SF Mono', 'Fira Code', monospace;
- overflow-x: auto;
- line-height: 1.55;
- margin: 0;
- }
- .del { color: var(--red); background: var(--red-bg); display: inline-block; width: 100%; }
- .add { color: var(--green); background: var(--green-bg); display: inline-block; width: 100%; }
- .ctx { color: var(--text-muted); }
-
- .flow {
- display: flex;
- align-items: center;
- gap: 0;
- flex-wrap: wrap;
- margin: 1rem 0;
- font-size: 0.9rem;
- }
- .flow-node {
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: 6px;
- padding: 0.4rem 0.75rem;
- white-space: nowrap;
- }
- .flow-node.new {
- border-color: var(--green);
- background: var(--green-bg);
- }
- .flow-arrow {
- color: var(--text-muted);
- padding: 0 0.4rem;
- font-size: 0.8rem;
- }
-
- table {
- width: 100%;
- border-collapse: collapse;
- margin: 1rem 0;
- font-size: 0.88rem;
- }
- th, td {
- border: 1px solid var(--border);
- padding: 0.45rem 0.75rem;
- text-align: left;
- }
- th {
- background: var(--surface2);
- color: var(--text-muted);
- font-weight: 600;
- font-size: 0.82rem;
- text-transform: uppercase;
- letter-spacing: 0.03em;
- }
- td { background: var(--surface); }
-
- .tag {
- display: inline-block;
- font-size: 0.75rem;
- padding: 0.15em 0.5em;
- border-radius: 12px;
- font-weight: 500;
- }
- .tag-core { background: rgba(88, 166, 255, 0.15); color: var(--accent); }
- .tag-plumbing { background: rgba(188, 140, 255, 0.15); color: var(--purple); }
- .tag-unrelated { background: rgba(139, 148, 158, 0.15); color: var(--text-muted); }
-
- .section-grid {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 1rem;
- margin: 1rem 0;
- }
- .section-card {
- background: var(--surface);
- border: 1px solid var(--border);
- border-radius: 8px;
- padding: 1rem;
- }
- .section-card h4 {
- font-size: 0.9rem;
- color: var(--accent);
- margin-bottom: 0.5rem;
- }
- .section-card ul { padding-left: 1.2rem; font-size: 0.88rem; }
-
- @media (max-width: 640px) {
- .section-grid { grid-template-columns: 1fr; }
- .metrics { gap: 0.75rem; }
- body { padding: 1rem; }
- }
-</style>
-</head>
-<body>
-
-<!-- ==================== HERO ==================== -->
-<div class="hero">
- <h1>Improve Bulk Imports</h1>
- <p class="subtitle">Make CSV imports smarter, more robust, and more complete &mdash; import supplier/customer details and item purchasing data in a single file.</p>
- <div style="font-size: 0.85rem; color: var(--text-muted); margin-bottom: 0.5rem;">
- Branch: <code>feat/improve-bulk-imports</code> &rarr; <code>main</code>
- </div>
- <div class="metrics">
- <div class="metric"><strong>178</strong> files changed</div>
- <div class="metric"><strong>+12.5k</strong> / <strong>-1.9k</strong> lines</div>
- <div class="metric"><strong>3</strong> core import files</div>
- <div class="metric"><strong>5</strong> item types expanded</div>
- <div class="metric"><strong>2</strong> partner types expanded</div>
- </div>
-</div>
-
-<div class="callout">
- <strong>Note:</strong> This branch includes several other merged features (rework flow, purchasing planning 2.0, MRP changes, approval rule fixes, etc.). This review focuses on the <strong>core bulk-import improvements</strong>. The unrelated changes are catalogued at the end.
-</div>
-
-<!-- ==================== PROBLEM ==================== -->
-<h2>1. Problem</h2>
-
-<p>Bulk CSV imports in Carbon were functional but limited:</p>
-
-<ul>
- <li><strong>Shallow data:</strong> Importing items only set name and basic fields. Supplier-part links, lead times, and purchasing parameters required manual entry afterwards.</li>
- <li><strong>Shallow partners:</strong> Importing customers or suppliers created the record but not their address, payment terms, shipping method, status, or type &mdash; all had to be set one-by-one.</li>
- <li><strong>Fragile matching:</strong> Re-importing a CSV after deleting and recreating entities broke because orphan external-ID mappings pointed at deleted rows, causing FK violations.</li>
- <li><strong>No template guidance:</strong> The download-template button produced a bare header row; users had to guess which columns were required and what values were valid.</li>
- <li><strong>Manual enum mapping:</strong> Users had to manually map every CSV value (like employee emails) to system IDs, even when the values matched exactly.</li>
- <li><strong>Malformed CSVs hard-failed:</strong> A single mismatched row width in the CSV (common in exports from other ERPs) aborted the entire import.</li>
-</ul>
-
-<!-- ==================== SYSTEM CONTEXT ==================== -->
-<h2>2. System Context</h2>
-
-<p>CSV imports flow through three layers:</p>
-
-<div class="flow">
- <div class="flow-node">ImportCSVModal (UI)</div>
- <div class="flow-arrow">&rarr;</div>
- <div class="flow-node">imports.models.ts (schemas)</div>
- <div class="flow-arrow">&rarr;</div>
- <div class="flow-node">import-csv edge fn (server)</div>
-</div>
-
-<table>
- <tr>
- <th>Layer</th>
- <th>File</th>
- <th>Responsibility</th>
- </tr>
- <tr>
- <td><strong>UI</strong></td>
- <td><code>ImportCSVModal/*</code></td>
- <td>File upload, column mapping, enum value mapping, submit</td>
- </tr>
- <tr>
- <td><strong>Schema</strong></td>
- <td><code>imports.models.ts</code></td>
- <td>Defines which columns exist per entity type, their types, validation, and lookup fetchers</td>
- </tr>
- <tr>
- <td><strong>Server</strong></td>
- <td><code>import-csv/index.ts</code></td>
- <td>Supabase edge function: parses CSV, resolves entity matching, upserts rows + side-tables in a transaction</td>
- </tr>
-</table>
-
-<p>The schema layer is the <strong>single source of truth</strong> for both the UI (which columns to show, which need enum mapping) and the server (which fields to expect). Adding a new column to an import means adding it in the schema, then handling it in the server handler.</p>
-
-<!-- ==================== BEFORE / AFTER ==================== -->
-<h2>3. Before / After</h2>
-
-<h3>Item Import (part, material, tool, fixture, consumable)</h3>
-
-<div class="section-grid">
- <div class="section-card">
- <h4>Before</h4>
- <ul>
- <li>ID, Name, Short Description, Long Description</li>
- <li>Item group, unit of measure, replenishment</li>
- <li>No supplier linkage</li>
- <li>No lead time</li>
- <li>No purchasing parameters</li>
- </ul>
- </div>
- <div class="section-card">
- <h4>After</h4>
- <ul>
- <li>ID, Name, Description <em>(merged)</em></li>
- <li>Item group, unit of measure, replenishment</li>
- <li style="color: var(--green);">+ Supplier ID, Supplier Part ID</li>
- <li style="color: var(--green);">+ Supplier UoM, Min Order Qty, Order Multiple</li>
- <li style="color: var(--green);">+ Conversion Factor, Unit Price</li>
- <li style="color: var(--green);">+ Lead Time (Days)</li>
- </ul>
- </div>
-</div>
-
-<h3>Customer Import</h3>
-
-<div class="section-grid">
- <div class="section-card">
- <h4>Before</h4>
- <ul>
- <li>Name, Tax ID, Account Manager</li>
- <li>No address</li>
- <li>No status/type</li>
- <li>No payment terms</li>
- </ul>
- </div>
- <div class="section-card">
- <h4>After</h4>
- <ul>
- <li>Name, Tax ID, Account Manager</li>
- <li style="color: var(--green);">+ Customer Status, Customer Type</li>
- <li style="color: var(--green);">+ Address (7 fields: name through country)</li>
- <li style="color: var(--green);">+ Payment Term</li>
- </ul>
- </div>
-</div>
-
-<h3>Supplier Import</h3>
-
-<div class="section-grid">
- <div class="section-card">
- <h4>Before</h4>
- <ul>
- <li>Name, Tax ID, Account Manager</li>
- <li>No address, shipping, or payment</li>
- <li>No status/type</li>
- </ul>
- </div>
- <div class="section-card">
- <h4>After</h4>
- <ul>
- <li>Name, Tax ID, Account Manager</li>
- <li style="color: var(--green);">+ Supplier Status, Supplier Type</li>
- <li style="color: var(--green);">+ Address (7 fields)</li>
- <li style="color: var(--green);">+ Payment Term</li>
- <li style="color: var(--green);">+ Shipping Method, Incoterm, Incoterm Location</li>
- </ul>
- </div>
-</div>
-
-<h3>Entity Matching (all types)</h3>
-
-<div class="section-grid">
- <div class="section-card">
- <h4>Before</h4>
- <ul>
- <li>Match only by CSV external ID</li>
- <li>Orphan mappings cause FK errors</li>
- <li>No within-CSV dedup</li>
- <li>Empty strings written as <code>""</code></li>
- </ul>
- </div>
- <div class="section-card">
- <h4>After</h4>
- <ul>
- <li style="color: var(--green);">Two-tier: external ID &rarr; name fallback</li>
- <li style="color: var(--green);">Orphan mappings cleaned before import</li>
- <li style="color: var(--green);">In-CSV name dedup prevents constraint violations</li>
- <li style="color: var(--green);">Empty strings &rarr; NULL</li>
- </ul>
- </div>
-</div>
-
-<!-- ==================== ARCHITECTURE DIAGRAM ==================== -->
-<h2>4. Import Flow (After)</h2>
-
-<div style="background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 1.25rem; font-family: 'SF Mono', monospace; font-size: 0.8rem; line-height: 1.7; overflow-x: auto;">
-<pre style="margin:0;">
-CSV Upload
- │
- ▼
-┌──────────────────────────────────────────────────────┐
-│ Parse CSV │
-│ ├─ std/csv with lazyQuotes: true │
-│ └─ fallback: parsePermissiveCsv() on row mismatch │
-└──────────────────────────┬───────────────────────────┘
- │
- ▼
-┌──────────────────────────────────────────────────────┐
-│ Resolve Identity (per row) │
-│ ├─ 1. externalIdMap (CSV ID → entity ID) │
-│ ├─ 2. nameMap (entity name → entity ID) │
-│ └─ 3. new insert (no match) │
-└──────────────────────────┬───────────────────────────┘
- │
- ▼
-┌──────────────────────────────────────────────────────┐
-│ Transaction │
-│ ├─ Upsert parent entity (customer/supplier/item) │
-│ ├─ Write extensions: │
-│ │ ├─ address + location (partner types) │
-│ │ ├─ payment / shipping (partner types) │
-│ │ ├─ supplierPart (item types) │
-│ │ ├─ itemReplenishment (lead time) │
-│ │ └─ itemPlanning (order multiple) │
-│ └─ Upsert CSV mappings (for future re-imports) │
-└──────────────────────────────────────────────────────┘
-</pre>
-</div>
-
-<!-- ==================== CODE WALKTHROUGH ==================== -->
-<h2>5. Code Walkthrough</h2>
-
-<h3>5.1 &mdash; Reusable Field Groups (Schema Layer)</h3>
-
-<p>Five new field-group constants are defined once and spread into every relevant import type, keeping the definitions DRY:</p>
-
-<div class="diff">
- <div class="diff-title">apps/erp/app/modules/shared/imports.models.ts</div>
- <pre>
-<span class="add">+ const supplierPartImportFields = {</span>
-<span class="add">+ supplierId: { label: "Supplier", type: "enum", required: false,</span>
-<span class="add">+ enumData: { fetcher: { table: "supplier", ... } } },</span>
-<span class="add">+ supplierPartId: { ... },</span>
-<span class="add">+ minimumOrderQuantity: { ... },</span>
-<span class="add">+ orderMultiple: { ... },</span>
-<span class="add">+ conversionFactor: { ... },</span>
-<span class="add">+ unitPrice: { ... },</span>
-<span class="add">+ };</span>
-<span class="add">+ const itemPurchasingImportFields = {</span>
-<span class="add">+ leadTime: { label: "Lead Time (Days)", type: "string" },</span>
-<span class="add">+ };</span>
-<span class="add">+ const partnerLocationImportFields = { /* 7 address fields */ };</span>
-<span class="add">+ const partnerPaymentImportFields = { /* paymentTermId */ };</span>
-<span class="add">+ const supplierShippingImportFields = { /* shippingMethodId, incoterm, incotermLocation */ };</span>
- </pre>
-</div>
-
-<p>Each item type (part, tool, fixture, consumable, material) spreads <code>...supplierPartImportFields</code> and <code>...itemPurchasingImportFields</code>. Customer spreads location + payment. Supplier spreads location + payment + shipping.</p>
-
-<h3>5.2 &mdash; Smart Template Download (UI)</h3>
-
-<p>The "Download Template" button was moved into the upload step and now generates a <strong>hint row</strong> beneath the headers, telling users what each column expects:</p>
-
-<div class="diff">
- <div class="diff-title">apps/erp/app/components/ImportCSVModal/UploadCSV.tsx</div>
- <pre>
-<span class="add">+ const hints = fields.map((f) => {</span>
-<span class="add">+ const prefix = f.required ? "REQUIRED" : "optional";</span>
-<span class="add">+ if (f.type === "enum" && f.enumData?.options) {</span>
-<span class="add">+ return `${prefix} — one of: ${f.enumData.options.join(" | ")}`;</span>
-<span class="add">+ }</span>
-<span class="add">+ if (f.type === "boolean") return `${prefix} — true | false`;</span>
-<span class="add">+ if (f.type === "numeric") return `${prefix} — number`;</span>
-<span class="add">+ return prefix;</span>
-<span class="add">+ });</span>
-<span class="add">+ const csv = Papa.unparse({ fields: headers, data: [hints] });</span>
- </pre>
-</div>
-
-<p>A user downloading the "Parts" template now gets a CSV like:</p>
-<div style="background: var(--surface); border: 1px solid var(--border); border-radius: 6px; padding: 0.75rem 1rem; font-family: monospace; font-size: 0.82rem; overflow-x: auto; margin: 0.75rem 0;">
-ID, Description, Item Group, ..., Supplier, Lead Time (Days)<br>
-REQUIRED, REQUIRED, optional — see your configured options, ..., optional, optional — number
-</div>
-
-<h3>5.3 &mdash; Auto-Match Enum Values (UI)</h3>
-
-<p>When the user reaches the enum-mapping step, the UI now auto-matches CSV values to system options by case-insensitive comparison. This eliminates tedious manual mapping when the CSV already uses correct names:</p>
-
-<div class="diff">
- <div class="diff-title">apps/erp/app/components/ImportCSVModal/FieldMappings.tsx</div>
- <pre>
-<span class="add">+ const autoMatchedRef = useRef(false);</span>
-<span class="add">+ useEffect(() => {</span>
-<span class="add">+ if (autoMatchedRef.current) return;</span>
-<span class="add">+ const lookup = new Map(</span>
-<span class="add">+ options.map((o) => [o.label.toLowerCase().trim(), o.value])</span>
-<span class="add">+ );</span>
-<span class="add">+ for (const csvValue of uniqueValues) {</span>
-<span class="add">+ if (mappings[csvValue]) continue;</span>
-<span class="add">+ const matched = lookup.get(csvValue.toLowerCase().trim());</span>
-<span class="add">+ if (matched) onEnumMappingChange(name, csvValue, matched);</span>
-<span class="add">+ }</span>
-<span class="add">+ autoMatchedRef.current = true;</span>
-<span class="add">+ }, [options, mappedColumn]);</span>
- </pre>
-</div>
-
-<p>The <code>useRef</code> guard ensures auto-matching runs exactly once, so user edits aren't overwritten on re-render.</p>
-
-<h3>5.4 &mdash; Employee Email Matching</h3>
-
-<p>The <code>accountManagerId</code> fetcher on both customer and supplier now returns <code>email</code> from the DB. The enum label uses <code>item.email ?? item.name</code>, so CSV values containing employee emails match automatically via the auto-match logic above.</p>
-
-<h3>5.5 &mdash; Permissive CSV Parsing (Server)</h3>
-
-<p>Real-world CSV exports frequently have inconsistent row widths. The server now catches parse errors and retries with a tolerant parser:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/import-csv/index.ts</div>
- <pre>
-<span class="add">+ function parsePermissiveCsv(text: string): string[][] {</span>
-<span class="add">+ // RFC-4180 tolerant: extra cells dropped, missing cells become ""</span>
-<span class="add">+ ...</span>
-<span class="add">+ }</span>
-<span class="ctx"> </span>
-<span class="ctx"> // Main parse path:</span>
-<span class="ctx"> try {</span>
-<span class="ctx"> rows = parse(text, { lazyQuotes: true });</span>
-<span class="ctx"> } catch {</span>
-<span class="add">+ rows = parsePermissiveCsv(text);</span>
-<span class="ctx"> }</span>
- </pre>
-</div>
-
-<h3>5.6 &mdash; Two-Tier Entity Matching (Server)</h3>
-
-<p>The biggest robustness improvement. Previously, entities could only be matched by their CSV external ID. Now the server falls back to matching by name:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/import-csv/index.ts</div>
- <pre>
-<span class="ctx"> // For each CSV row:</span>
-<span class="add">+ const existingId = externalIdMap[csvId] ?? nameMap.get(name.toLowerCase());</span>
-<span class="ctx"> </span>
-<span class="ctx"> if (existingId) {</span>
-<span class="ctx"> // UPDATE existing entity</span>
-<span class="ctx"> } else {</span>
-<span class="ctx"> // INSERT new entity</span>
-<span class="ctx"> }</span>
- </pre>
-</div>
-
-<p>When a name-based match is used, a new CSV mapping is written so subsequent imports use the fast external-ID path.</p>
-
-<h3>5.7 &mdash; Orphan Mapping Cleanup (Server)</h3>
-
-<p>Before building the external-ID map, the server now validates that every mapped entity still exists in the database. Orphan mappings (from deleted entities) are filtered out, preventing FK violations on side-tables like <code>supplierTax</code>:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/import-csv/index.ts</div>
- <pre>
-<span class="add">+ async function fetchLiveEntityIds(</span>
-<span class="add">+ entityType: CsvEntityType, ids: string[]</span>
-<span class="add">+ ): Promise&lt;Set&lt;string&gt;&gt; {</span>
-<span class="add">+ // Queries the actual entity table to verify IDs exist</span>
-<span class="add">+ }</span>
-<span class="ctx"> </span>
-<span class="ctx"> // In getCsvExternalIdMap:</span>
-<span class="add">+ const liveIds = await fetchLiveEntityIds(entityType, allEntityIds);</span>
-<span class="add">+ // Filter out mappings whose entity was deleted</span>
- </pre>
-</div>
-
-<h3>5.8 &mdash; Side-Table Writes (Server)</h3>
-
-<p>The biggest functional addition. After the parent entity upsert, dedicated helpers write related records in the same transaction:</p>
-
-<table>
- <tr>
- <th>Entity Type</th>
- <th>Side-Table</th>
- <th>Helper Function</th>
- </tr>
- <tr>
- <td>Supplier</td>
- <td><code>address</code>, <code>supplierLocation</code>, <code>supplierPayment</code>, <code>supplierShipping</code></td>
- <td><code>writeSupplierExtensions()</code></td>
- </tr>
- <tr>
- <td>Customer</td>
- <td><code>address</code>, <code>customerLocation</code>, <code>customerPayment</code></td>
- <td><code>writeCustomerExtensions()</code></td>
- </tr>
- <tr>
- <td>Item (all 5)</td>
- <td><code>supplierPart</code></td>
- <td><code>writeSupplierPartLinks()</code></td>
- </tr>
- <tr>
- <td>Item (all 5)</td>
- <td><code>itemReplenishment</code></td>
- <td><code>writeItemPurchasingLeadTimes()</code></td>
- </tr>
- <tr>
- <td>Item (all 5)</td>
- <td><code>itemPlanning</code></td>
- <td><code>writeItemPlanningOrderMultiples()</code></td>
- </tr>
-</table>
-
-<p>All side-table writes use <strong>bulk preloading</strong> (e.g., <code>preloadPrimaryLocationAddressIds()</code>) to avoid N+1 queries inside the transaction loop.</p>
-
-<h3>5.9 &mdash; Empty String Nullification (Server)</h3>
-
-<p>A simple but important utility that converts empty CSV cells to <code>NULL</code> before database writes. Without this, empty strings would violate FK and enum constraints:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/import-csv/index.ts</div>
- <pre>
-<span class="add">+ function nullifyEmptyStrings(obj: Record&lt;string, unknown&gt;) {</span>
-<span class="add">+ for (const [k, v] of Object.entries(obj)) {</span>
-<span class="add">+ if (v === "") obj[k] = undefined;</span>
-<span class="add">+ }</span>
-<span class="add">+ return obj;</span>
-<span class="add">+ }</span>
- </pre>
-</div>
-
-<!-- ==================== TESTS / VERIFICATION ==================== -->
-<h2>6. Tests / Verification</h2>
-
-<div class="callout info">
- <strong>Verification status:</strong> The import-csv edge function runs as a Supabase Edge Function (Deno). Changes to <code>imports.models.ts</code> are validated by the Zod schema at runtime during CSV upload. No dedicated unit tests were added in this PR for the import logic &mdash; the import flow is primarily tested through manual E2E verification.
-</div>
-
-<p><strong>Recommended verification commands:</strong></p>
-<div style="background: var(--surface); border: 1px solid var(--border); border-radius: 6px; padding: 0.75rem 1rem; font-family: monospace; font-size: 0.82rem; margin: 0.75rem 0;">
- # Type check the schema file<br>
- pnpm tsc --noEmit apps/erp/app/modules/shared/imports.models.ts<br><br>
- # Manual E2E: upload a CSV with supplier-part columns for a part import<br>
- # Verify supplierPart, itemReplenishment, and itemPlanning rows are created<br><br>
- # Manual E2E: upload a supplier CSV with address + payment + shipping columns<br>
- # Verify address, supplierLocation, supplierPayment, supplierShipping rows are created<br><br>
- # Manual E2E: delete a supplier, re-import the same CSV<br>
- # Verify no FK violation &mdash; orphan mapping should be cleaned up<br><br>
- # Manual E2E: upload a malformed CSV (inconsistent row widths)<br>
- # Verify it falls back to permissive parsing and imports successfully
-</div>
-
-<!-- ==================== UNRELATED CHANGES ==================== -->
-<h2>7. Other Changes on This Branch</h2>
-
-<p>This branch includes several features merged from main or developed in parallel. They are <strong>not part of the bulk-import improvements</strong>:</p>
-
-<table>
- <tr>
- <th>Feature</th>
- <th>Key Files</th>
- <th style="width: 5rem;">Tag</th>
- </tr>
- <tr>
- <td>Serial/batch rework flow</td>
- <td><code>trigger-rework/</code>, <code>ReworkModal.tsx</code>, rework migration</td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>Purchasing Planning 2.0</td>
- <td><code>purchasing.models.ts</code> (planned order fields), <code>planning.update.tsx</code></td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>MRP engine + demand forecast sources</td>
- <td><code>mrp-engine.ts</code>, <code>demandForecastSource</code> queries, forecast UI</td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>Approval rule upper-bound removal</td>
- <td><code>shared.models.ts</code>, <code>approval-rules.*.tsx</code></td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>Sales invoice PDF: sales order number</td>
- <td><code>SalesInvoicePDF.tsx</code></td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>Negative adjustment on serial items</td>
- <td><code>inventory.service.ts</code></td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>Supplier/customer readable ID</td>
- <td>Migration <code>20260521*</code>, <code>readableId</code> in validators</td>
- <td><span class="tag tag-plumbing">Import-adjacent</span></td>
- </tr>
- <tr>
- <td>CI workflows (labeler, complexity, checks)</td>
- <td><code>.github/workflows/*</code></td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>Claude skills + .gitignore</td>
- <td><code>.claude/skills/*</code></td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
- <tr>
- <td>Locale translations (all languages)</td>
- <td><code>packages/locale/locales/**/*.po</code></td>
- <td><span class="tag tag-unrelated">Unrelated</span></td>
- </tr>
-</table>
-
-<!-- ==================== REVIEWER TAKEAWAY ==================== -->
-<h2>8. Reviewer Takeaway</h2>
-
-<div class="callout success">
- <strong>Mental model:</strong> This PR makes CSV imports a one-shot setup tool. Instead of importing bare entities and then manually configuring their details, users can now import complete records &mdash; items with their supplier and purchasing data, customers/suppliers with their addresses and payment terms &mdash; in a single CSV upload.
-</div>
-
-<p><strong>Focus your review on:</strong></p>
-<ol>
- <li><strong><code>import-csv/index.ts</code></strong> &mdash; the side-table write helpers (<code>writeSupplierExtensions</code>, <code>writeSupplierPartLinks</code>, etc.). Verify they handle the insert-vs-update paths correctly, especially for address upserts.</li>
- <li><strong>Two-tier matching logic</strong> &mdash; the external-ID-first, name-fallback pattern. Check that name-matched entities get their CSV mapping written so the next import is idempotent.</li>
- <li><strong>Orphan mapping cleanup</strong> &mdash; <code>fetchLiveEntityIds</code> queries the entity table before using the mapping. Confirm the FK safety it provides.</li>
- <li><strong><code>imports.models.ts</code></strong> &mdash; the reusable field groups. Verify the Zod schemas match the field mappings 1:1.</li>
- <li><strong>Auto-match in <code>FieldMappings.tsx</code></strong> &mdash; the <code>useRef</code> guard for one-shot auto-matching. Confirm it doesn't clobber user edits.</li>
-</ol>
-
-<p style="color: var(--text-muted); font-size: 0.85rem; margin-top: 2rem; text-align: center;">
- Generated for branch <code>feat/improve-bulk-imports</code> &bull; 2026-05-31
-</p>
-
-</body>
-</html>
diff --git a/.pr-review/feat-rework.html b/.pr-review/feat-rework.html
deleted file mode 100644
index 7a63062f32..0000000000
--- a/.pr-review/feat-rework.html
+++ /dev/null
@@ -1,587 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head>
-<meta charset="UTF-8">
-<meta name="viewport" content="width=device-width, initial-scale=1.0">
-<title>PR Review: feat/rework</title>
-<style>
- :root {
- --bg: #0d1117; --surface: #161b22; --border: #30363d;
- --text: #e6edf3; --muted: #8b949e; --accent: #58a6ff;
- --green: #3fb950; --red: #f85149; --yellow: #d29922;
- --orange: #db6d28; --purple: #bc8cff;
- --green-bg: #12261e; --red-bg: #2d1214;
- }
- * { box-sizing: border-box; margin: 0; padding: 0; }
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
- background: var(--bg); color: var(--text); line-height: 1.6; padding: 2rem; max-width: 960px; margin: 0 auto; }
- h1, h2, h3 { font-weight: 600; }
- h1 { font-size: 1.8rem; margin-bottom: 0.5rem; }
- h2 { font-size: 1.3rem; margin: 2.5rem 0 1rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--border); }
- h3 { font-size: 1.05rem; margin: 1.5rem 0 0.5rem; }
- p, li { color: var(--text); }
- a { color: var(--accent); text-decoration: none; }
- a:hover { text-decoration: underline; }
- code { font-family: 'SF Mono', Consolas, 'Liberation Mono', Menlo, monospace;
- font-size: 0.85em; background: var(--surface); padding: 0.15em 0.4em; border-radius: 4px; }
- ul, ol { padding-left: 1.5rem; margin: 0.5rem 0; }
- li { margin: 0.3rem 0; }
-
- .hero { background: var(--surface); border: 1px solid var(--border); border-radius: 8px;
- padding: 1.5rem 2rem; margin-bottom: 2rem; }
- .hero h1 { color: var(--accent); }
- .hero .summary { font-size: 1.05rem; color: var(--muted); margin: 0.5rem 0 1rem; }
- .metrics { display: flex; gap: 1.5rem; flex-wrap: wrap; }
- .metric { background: var(--bg); border: 1px solid var(--border); border-radius: 6px;
- padding: 0.5rem 1rem; font-size: 0.85rem; }
- .metric strong { color: var(--accent); display: block; font-size: 1.3rem; }
- .badge { display: inline-block; font-size: 0.75rem; font-weight: 600; padding: 0.15rem 0.5rem;
- border-radius: 10px; margin-left: 0.5rem; vertical-align: middle; }
- .badge-branch { background: #1f3a5f; color: var(--accent); }
-
- .callout { border-left: 3px solid var(--accent); background: var(--surface);
- padding: 0.8rem 1.2rem; border-radius: 0 6px 6px 0; margin: 1rem 0; font-size: 0.9rem; }
- .callout.warn { border-left-color: var(--yellow); }
- .callout.ok { border-left-color: var(--green); }
-
- .diff { background: var(--surface); border: 1px solid var(--border); border-radius: 6px;
- margin: 1rem 0; overflow: hidden; font-size: 0.82rem; }
- .diff-title { background: var(--bg); padding: 0.5rem 1rem; font-family: monospace;
- font-size: 0.8rem; color: var(--muted); border-bottom: 1px solid var(--border); }
- .diff pre { padding: 0.8rem 1rem; margin: 0; overflow-x: auto; white-space: pre; line-height: 1.5; }
- .diff .add { color: var(--green); background: var(--green-bg); display: block; }
- .diff .del { color: var(--red); background: var(--red-bg); display: block; }
- .diff .ctx { color: var(--muted); display: block; }
-
- .diagram { background: var(--surface); border: 1px solid var(--border); border-radius: 8px;
- padding: 1.5rem; margin: 1rem 0; overflow-x: auto; }
- .diagram pre { color: var(--text); font-size: 0.8rem; line-height: 1.6; }
- .diagram .label { color: var(--accent); font-weight: 600; }
- .diagram .arrow { color: var(--muted); }
- .diagram .highlight { color: var(--green); font-weight: 600; }
- .diagram .warn-text { color: var(--yellow); }
-
- .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; margin: 1rem 0; }
- .grid-2 > div { background: var(--surface); border: 1px solid var(--border); border-radius: 6px; padding: 1rem; }
- .grid-2 h4 { font-size: 0.9rem; margin-bottom: 0.5rem; color: var(--muted); }
- @media (max-width: 700px) { .grid-2 { grid-template-columns: 1fr; } }
-
- table { border-collapse: collapse; width: 100%; margin: 1rem 0; font-size: 0.85rem; }
- th, td { border: 1px solid var(--border); padding: 0.5rem 0.8rem; text-align: left; }
- th { background: var(--surface); color: var(--muted); font-weight: 600; }
- td { background: var(--bg); }
- td code { font-size: 0.8rem; }
-
- .file-list { columns: 2; column-gap: 2rem; font-size: 0.82rem; }
- .file-list li { break-inside: avoid; }
- @media (max-width: 700px) { .file-list { columns: 1; } }
-
- .tag { display: inline-block; font-size: 0.7rem; padding: 0.1rem 0.4rem; border-radius: 4px;
- margin-right: 0.3rem; font-weight: 600; }
- .tag-core { background: #1f3a5f; color: var(--accent); }
- .tag-ui { background: #2d1f4e; color: var(--purple); }
- .tag-db { background: #2d2a10; color: var(--yellow); }
- .tag-infra { background: #1a2d1e; color: var(--green); }
- .tag-pkg { background: #2d1e16; color: var(--orange); }
-
- .section-nav { position: sticky; top: 0; background: var(--bg); padding: 0.8rem 0;
- border-bottom: 1px solid var(--border); margin-bottom: 1rem; z-index: 10;
- display: flex; gap: 1rem; flex-wrap: wrap; font-size: 0.82rem; }
- .section-nav a { color: var(--muted); }
- .section-nav a:hover { color: var(--accent); }
-</style>
-</head>
-<body>
-
-<!-- ═══════════════ HERO ═══════════════ -->
-<div class="hero">
- <h1>feat/rework <span class="badge badge-branch">feat/rework &rarr; main</span></h1>
- <p class="summary">Production rework workflows, MRP demand-forecast lineage, and purchasing planning improvements.</p>
- <div class="metrics">
- <div class="metric"><strong>~140</strong>files changed</div>
- <div class="metric"><strong>4</strong>migrations</div>
- <div class="metric"><strong>1</strong>new edge function</div>
- <div class="metric"><strong>1</strong>new npm package</div>
- <div class="metric"><strong>22</strong>new unit tests</div>
- <div class="metric"><strong>5</strong>apps/packages</div>
- </div>
-</div>
-
-<nav class="section-nav">
- <a href="#problem">Problem</a>
- <a href="#context">System Context</a>
- <a href="#rework-flow">Rework Flow</a>
- <a href="#mrp">MRP Engine</a>
- <a href="#purchasing">Purchasing Planning</a>
- <a href="#ui">UI Components</a>
- <a href="#migrations">Migrations</a>
- <a href="#file-map">File Map</a>
- <a href="#verification">Verification</a>
- <a href="#takeaway">Takeaway</a>
-</nav>
-
-<!-- ═══════════════ PROBLEM ═══════════════ -->
-<h2 id="problem">1. Problem</h2>
-
-<p>Three gaps existed in Carbon's production and planning pipeline:</p>
-
-<ol>
- <li><strong>No rework path.</strong> When a job operation failed quality checks, there was no way to loop back to an earlier operation, clone the relevant steps, and re-execute them. Operators had to manually create new operations or work around the system.</li>
- <li><strong>No demand-forecast lineage.</strong> MRP generated demand forecasts, but there was no way to trace <em>why</em> a forecast existed&mdash;which parent job, sales order, or demand projection caused it. Planning decisions lacked auditability.</li>
- <li><strong>Purchasing planning friction.</strong> The purchasing planning flow needed improvements to handle supplier&ndash;period grouping, MOQ enforcement, existing PO reuse, and supply forecast deduplication.</li>
-</ol>
-
-<!-- ═══════════════ SYSTEM CONTEXT ═══════════════ -->
-<h2 id="context">2. System Context</h2>
-
-<div class="diagram">
-<pre>
-<span class="label">MES App</span> (shop floor) <span class="label">ERP App</span> (planning)
- │ │
- ├─ JobOperation UI ├─ Item Planning Charts
- │ └─ <span class="highlight">ReworkModal (NEW)</span> │ ├─ <span class="highlight">DemandForecastSourcesPopover (NEW)</span>
- │ │ │ └─ <span class="highlight">PlannedOrderDetailsPopover (NEW)</span>
- │ ▼ │
- │ POST /trigger-rework ├─ Purchasing Planning
- │ │ │ └─ planning.update.tsx (refactored)
- │ ▼ │
- <span class="label">Supabase Edge Functions</span> │
- ├─ <span class="highlight">trigger-rework (NEW)</span> │
- │ ├─ BFS path finding │
- │ ├─ Operation cloning │
- │ ├─ DAG wiring │
- │ └─ Reschedule call ─────────┐ │
- │ │ │
- ├─ reschedule ◄──────┘
- │ └─ scheduling-engine.ts (updated)
- │
- ├─ mrp (updated)
- │ └─ <span class="highlight">lib/mrp-engine.ts (NEW)</span> ─── shared BOM explosion algorithm
- │
- └─ recalculate
-</pre>
-</div>
-
-<div class="callout">
- <strong>What didn't change:</strong> The scheduling engine's forward-scheduling algorithm, the MRP edge function's data-fetching phases, and all existing job/operation CRUD flows are untouched. Rework operations are invisible to the scheduler's dependency builder (filtered by <code>reworkId</code>).
-</div>
-
-<!-- ═══════════════ REWORK FLOW ═══════════════ -->
-<h2 id="rework-flow">3. Rework Flow (the headline feature)</h2>
-
-<h3>3.1 User Journey</h3>
-
-<div class="diagram">
-<pre>
-<span class="label">Operator on MES</span>
-
- 1. Working on operation "Inspect"
- 2. Finds defect &rarr; opens Rework action
- 3. <span class="highlight">ReworkModal</span> loads upstream operations via BFS
- 4. Selects target: "go back to Weld"
- 5. Sets quantity: 2 units, enters reason
- 6. Submits
-
-<span class="label">Backend (single transaction)</span>
-
- 7. <span class="highlight">findReworkPath()</span>: BFS finds path Weld &rarr; Paint &rarr; Inspect
- 8. Creates <code>rework</code> record (reason, qty, traceability)
- 9. Clones 3 operations: Weld(R), Paint(R), Inspect(R)
- &bull; First op: status = "Ready", operationOrder = "With Previous"
- &bull; Remaining: status = "Waiting"
- 10. Clones steps, tools, parameters for each
- 11. Wires DAG: Weld(R) &rarr; Paint(R) &rarr; Inspect(R)
- 12. Convergence: downstream ops now also depend on Inspect(R)
- 13. Records productionQuantity type = "Rework"
-
-<span class="label">Post-transaction</span>
-
- 14. Triggers reschedule for date recalculation
- 15. Operator sees new operations on their board
-</pre>
-</div>
-
-<h3>3.2 Before / After DAG</h3>
-
-<div class="grid-2">
- <div>
- <h4>Before: linear</h4>
-<pre style="font-size: 0.8rem; color: var(--text); line-height: 1.8;">
-Weld &rarr; Paint &rarr; Inspect &rarr; Pack
- <span style="color:var(--red)">&#x2718; defect found</span>
-</pre>
- </div>
- <div>
- <h4>After: branch &amp; converge</h4>
-<pre style="font-size: 0.8rem; color: var(--text); line-height: 1.8;">
-Weld &rarr; Paint &rarr; Inspect &rarr;&rarr;&rarr;&rarr; Pack
- <span style="color:var(--green)">&#x2514; Weld(R) &rarr; Paint(R) &rarr; Inspect(R) &#x2518;</span>
-</pre>
- </div>
-</div>
-
-<h3>3.3 Key Code: Batch Operation Cloning</h3>
-
-<p>Operations are cloned in a single batch <code>INSERT ... RETURNING</code> instead of sequential inserts:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/trigger-rework/index.ts</div>
- <pre>
-<span class="ctx"> // 5. Clone operations (batch insert)</span>
-<span class="add">+ const clonedOps = await trx</span>
-<span class="add">+ .insertInto("jobOperation")</span>
-<span class="add">+ .values(</span>
-<span class="add">+ sourceOperations.map((sourceOp, i) => ({</span>
-<span class="add">+ ...cloneFields,</span>
-<span class="add">+ order: triggerOrder + increment * (i + 1),</span>
-<span class="add">+ reworkId: rework.id,</span>
-<span class="add">+ status: i === 0 ? "Ready" : "Waiting",</span>
-<span class="add">+ }))</span>
-<span class="add">+ )</span>
-<span class="add">+ .returning(["id"])</span>
-<span class="add">+ .execute();</span></pre>
-</div>
-
-<p>Steps, tools, and parameters are also fetched in 3 parallel queries and inserted in 3 parallel batches:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/trigger-rework/index.ts</div>
- <pre>
-<span class="ctx"> // 6. Clone steps, tools, and parameters (batch fetch + batch insert)</span>
-<span class="add">+ const [allSteps, allTools, allParams] = await Promise.all([</span>
-<span class="add">+ trx.selectFrom("jobOperationStep").selectAll()</span>
-<span class="add">+ .where("operationId", "in", operationPath).execute(),</span>
-<span class="add">+ trx.selectFrom("jobOperationTool").selectAll()</span>
-<span class="add">+ .where("operationId", "in", operationPath).execute(),</span>
-<span class="add">+ trx.selectFrom("jobOperationParameter").selectAll()</span>
-<span class="add">+ .where("operationId", "in", operationPath).execute(),</span>
-<span class="add">+ ]);</span></pre>
-</div>
-
-<p>DAG edges (inter-rework + convergence) are collected into a single array and inserted once:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/trigger-rework/index.ts</div>
- <pre>
-<span class="ctx"> // 7. Wire the rework operations into the DAG</span>
-<span class="add">+ const dagEdges = [];</span>
-<span class="add">+ // 7a. Sequential: each rework op depends on the previous</span>
-<span class="add">+ for (let i = 1; i < clonedOperationIds.length; i++) {</span>
-<span class="add">+ dagEdges.push({ operationId: clonedOperationIds[i],</span>
-<span class="add">+ dependsOnId: clonedOperationIds[i - 1], jobId, companyId });</span>
-<span class="add">+ }</span>
-<span class="add">+ // 7b. Convergence: downstream ops also depend on last rework op</span>
-<span class="add">+ for (const dep of downstreamDeps) {</span>
-<span class="add">+ dagEdges.push({ operationId: dep.operationId,</span>
-<span class="add">+ dependsOnId: lastReworkOpId, jobId, companyId });</span>
-<span class="add">+ }</span>
-<span class="add">+ if (dagEdges.length > 0) {</span>
-<span class="add">+ await trx.insertInto("jobOperationDependency").values(dagEdges).execute();</span>
-<span class="add">+ }</span></pre>
-</div>
-
-<h3>3.4 Auto-Completion Trigger</h3>
-
-<p>The <code>complete_rework_trigger</code> in the migration fires when any <code>jobOperation</code> status changes to <code>'Done'</code>. It checks if ALL operations sharing the same <code>reworkId</code> are Done, and if so, sets <code>rework.completedAt</code>.</p>
-
-<div class="diff">
- <div class="diff-title">migrations/20260527142837_rework.sql</div>
- <pre>
-<span class="add">+ CREATE OR REPLACE FUNCTION complete_rework()</span>
-<span class="add">+ RETURNS TRIGGER AS $$</span>
-<span class="add">+ BEGIN</span>
-<span class="add">+ IF NEW.status = 'Done' AND NEW."reworkId" IS NOT NULL THEN</span>
-<span class="add">+ IF NOT EXISTS (</span>
-<span class="add">+ SELECT 1 FROM "jobOperation"</span>
-<span class="add">+ WHERE "reworkId" = NEW."reworkId" AND status != 'Done'</span>
-<span class="add">+ ) THEN</span>
-<span class="add">+ UPDATE rework SET "completedAt" = now()</span>
-<span class="add">+ WHERE id = NEW."reworkId";</span>
-<span class="add">+ END IF;</span>
-<span class="add">+ END IF;</span>
-<span class="add">+ RETURN NEW;</span>
-<span class="add">+ END; $$ LANGUAGE plpgsql;</span></pre>
-</div>
-
-<!-- ═══════════════ MRP ENGINE ═══════════════ -->
-<h2 id="mrp">4. MRP Engine &amp; Demand Forecast Lineage</h2>
-
-<h3>4.1 New Package: <code>@carbon/mrp</code></h3>
-
-<p>A new standalone package (<code>packages/mrp/</code>) extracts the pure BOM explosion algorithm into a testable, dependency-free module.</p>
-
-<table>
- <tr><th>Export</th><th>Purpose</th></tr>
- <tr><td><code>explodeBom(input)</code></td><td>Level-by-level BOM explosion with inventory netting, lead-time offsetting, and contributor propagation</td></tr>
- <tr><td><code>computeLowLevelCodes(bom)</code></td><td>Assigns low-level codes to determine processing order</td></tr>
- <tr><td><code>splitKey(key)</code> / <code>makeKey(...)</code></td><td>Encode/decode <code>locationId-periodId-itemId</code> composite keys</td></tr>
-</table>
-
-<p>22 unit tests cover demand propagation, inventory netting, Make vs Buy handling, inline production coercion, and contributor scaling.</p>
-
-<h3>4.2 Shared Engine for Edge Functions</h3>
-
-<p>The MRP edge function previously had the BOM explosion algorithm inlined (~100 lines). A shared copy now lives at <code>lib/mrp-engine.ts</code> and the edge function calls <code>explodeBom()</code>:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/mrp/index.ts</div>
- <pre>
-<span class="del">- const llc = computeLowLevelCodes(bomByItem);</span>
-<span class="del">- const maxLevel = llc.size > 0 ? Math.max(...llc.values()) : 0;</span>
-<span class="del">- const onHandByLocationItem = new Map(baseInventoryByLocationItem);</span>
-<span class="del">- const bomDerivedDemand = new Map&lt;string, number&gt;();</span>
-<span class="del">- for (let level = 0; level &lt;= maxLevel; level++) {</span>
-<span class="del">- // ... 100 lines of BOM explosion ...</span>
-<span class="del">- }</span>
-<span class="add">+ const { bomDerivedDemand, demandContributors } = explodeBom({</span>
-<span class="add">+ grossDemand, bomByItem, replenishmentSystemByItem,</span>
-<span class="add">+ leadTimeByItem,</span>
-<span class="add">+ periods: periods.map((p) => ({ id: p.id ?? "" })),</span>
-<span class="add">+ onHandByLocationItem: new Map(baseInventoryByLocationItem),</span>
-<span class="add">+ jobSupplyByLocationPeriodItem, topLevelContributors,</span>
-<span class="add">+ });</span></pre>
-</div>
-
-<div class="callout ok">
- <strong>Zero behavioral change.</strong> The algorithm is character-for-character identical. The only mechanical differences: <code>effectiveReplenishment()</code> extracted to a helper, <code>makeKey()</code> replaces template literals, <code>p.id ?? ""</code> coercion moved to the call site. No downstream maps (<code>grossDemand</code>, <code>onHandByLocationItem</code>) are read after the explosion, so the copy-vs-mutate change is invisible.
-</div>
-
-<h3>4.3 Demand Forecast Source Lineage</h3>
-
-<p>New <code>demandForecastSource</code> table tracks which parent entity caused each MRP-generated forecast row:</p>
-
-<div class="diagram">
-<pre>
- <span class="label">demandForecastSource</span>
- ┌─────────────────────────────────────────────────────────┐
- │ itemId, locationId, periodId │
- │ sourceType: 'Job Material' | 'Sales Order' | 'Demand Projection' │
- │ jobId | salesOrderLineId | demandProjectionId (exactly one set) │
- │ parentItemId, quantity │
- └─────────────────────────────────────────────────────────┘
- <span class="arrow">▲</span>
- <span class="arrow">│</span> populated during BOM explosion via contributor propagation
- <span class="arrow">│</span>
- <span class="label">explodeBom()</span> &rarr; demandContributors map &rarr; batch insert
-</pre>
-</div>
-
-<p>The ERP app surfaces this via <code>DemandForecastSourcesPopover</code>: users click a forecast row and see exactly which jobs, sales orders, or projections contributed to it.</p>
-
-<!-- ═══════════════ PURCHASING PLANNING ═══════════════ -->
-<h2 id="purchasing">5. Purchasing Planning Improvements</h2>
-
-<p>The <code>planning.update.tsx</code> route handler was refactored for the Purchasing Planning 2.0 workflow. Key changes:</p>
-
-<table>
- <tr><th>Area</th><th>What changed</th></tr>
- <tr><td>Order grouping</td><td>Orders grouped by <code>supplier+period</code> key; each group gets one PO</td></tr>
- <tr><td>PO reuse</td><td>Finds existing Draft/Planned POs for the same supplier+period before creating new ones</td></tr>
- <tr><td>Existing lines</td><td>Separates existing-line updates from new orders upfront</td></tr>
- <tr><td>MOQ enforcement</td><td>Adjusts quantity up to supplier part's minimum order quantity</td></tr>
- <tr><td>Line dedup</td><td>If PO already has a line for the same item, adds quantity instead of duplicating</td></tr>
- <tr><td>Supply forecasts</td><td>Extracted <code>deduplicateForecasts()</code> helper for clean grouping</td></tr>
-</table>
-
-<div class="diff">
- <div class="diff-title">apps/erp/app/routes/x+/purchasing+/planning.update.tsx</div>
- <pre>
-<span class="del">- const forecastMap = new Map&lt;string, ...&gt;();</span>
-<span class="del">- for (const forecast of allSupplyForecasts) {</span>
-<span class="del">- const key = `${forecast.itemId}-${forecast.locationId}-${forecast.periodId}`;</span>
-<span class="del">- const existing = forecastMap.get(key);</span>
-<span class="del">- if (existing) { existing.forecastQuantity += forecast.forecastQuantity; }</span>
-<span class="del">- else { forecastMap.set(key, { ...forecast }); }</span>
-<span class="del">- }</span>
-<span class="del">- const uniqueSupplyForecasts = Array.from(forecastMap.values());</span>
-<span class="add">+ const uniqueSupplyForecasts = deduplicateForecasts(allSupplyForecasts);</span></pre>
-</div>
-
-<!-- ═══════════════ UI COMPONENTS ═══════════════ -->
-<h2 id="ui">6. UI Components</h2>
-
-<h3>6.1 New Components</h3>
-
-<table>
- <tr><th>Component</th><th>Package</th><th>Purpose</th></tr>
- <tr><td><code>BottomSheet</code></td><td><code>@carbon/react</code></td><td>Bottom-sliding modal (Radix Dialog wrapper) for MES mobile actions</td></tr>
- <tr><td><code>ReworkModal</code></td><td>MES app</td><td>Rework creation form: loads upstream ops, validates, submits</td></tr>
- <tr><td><code>DemandForecastSourcesPopover</code></td><td>ERP app</td><td>Traces forecast to parent jobs/sales orders/projections</td></tr>
- <tr><td><code>PlannedOrderDetailsPopover</code></td><td>ERP app</td><td>Shows planned order details: supplier, policy, linked PO</td></tr>
-</table>
-
-<h3>6.2 Updated Components</h3>
-
-<table>
- <tr><th>Component</th><th>Change</th></tr>
- <tr><td><code>BarProgress</code></td><td>Refactored gradient interpolation, added segment support for multi-color bars</td></tr>
- <tr><td><code>JobOperation</code> (MES)</td><td>Added rework badge, BottomSheet actions, ReworkModal integration (+130 / -78 lines)</td></tr>
- <tr><td><code>ItemPlanningChart</code></td><td>Added forecast source popover integration</td></tr>
- <tr><td><code>ItemReorderPolicy</code></td><td>Extended to show policy details in planned order popover</td></tr>
- <tr><td><code>Select</code>, <code>Textarea</code>, <code>DateTimePicker</code></td><td>Minor prop additions (disabled states, controlled values)</td></tr>
- <tr><td>Kanban <code>ItemCard</code> (ERP + MES)</td><td>Added rework indicator to kanban cards</td></tr>
-</table>
-
-<!-- ═══════════════ MIGRATIONS ═══════════════ -->
-<h2 id="migrations">7. Migrations</h2>
-
-<table>
- <tr><th>Migration</th><th>What</th><th>Lines</th></tr>
- <tr>
- <td><code>20260527110002</code></td>
- <td><strong>demandForecastSource</strong> &mdash; new table + enum + surrogate <code>id</code> on <code>demandProjection</code></td>
- <td>128</td>
- </tr>
- <tr>
- <td><code>20260527142837</code></td>
- <td><strong>rework</strong> &mdash; new table, <code>reworkId</code> column on <code>jobOperation</code>, auto-completion trigger, updated views</td>
- <td>119</td>
- </tr>
- <tr>
- <td><code>20260529074512</code></td>
- <td><strong>openPurchaseOrderLines</strong> &mdash; new view for open PO lines with unit conversion and date coalescing</td>
- <td>28</td>
- </tr>
- <tr>
- <td><code>20260529163847</code></td>
- <td><strong>reworkId in RPCs</strong> &mdash; updates <code>get_job_operation_by_id</code>, <code>sync_update_job_operation_quantities</code>, <code>sync_finish_job_operation</code> to handle rework quantities and terminal-op sums</td>
- <td>411</td>
- </tr>
-</table>
-
-<div class="callout">
- <strong>RPC update detail:</strong> The <code>sync_update_job_operation_quantities</code> function now sums quantities across ALL terminal operations (not just the last one). This is critical for branch-and-converge: if Inspect completes 1 unit and Inspect(R) reworks 2 units, the job's total is 3.
-</div>
-
-<!-- ═══════════════ SCHEDULING ═══════════════ -->
-<h3>7.1 Scheduling Engine Awareness</h3>
-
-<p>The scheduling engine was updated to be rework-aware:</p>
-
-<div class="diff">
- <div class="diff-title">packages/database/supabase/functions/lib/scheduling/scheduling-engine.ts</div>
- <pre>
-<span class="ctx"> // Group non-rework operations by jobMakeMethodId</span>
-<span class="del">- for (const op of this.operations) {</span>
-<span class="del">- if (op.jobMakeMethodId) {</span>
-<span class="add">+ for (const op of allOperations) {</span>
-<span class="add">+ if (op.jobMakeMethodId && !op.reworkId) {</span>
-
-<span class="ctx"> // Delete existing dependencies, preserving rework operation dependencies</span>
-<span class="add">+ const reworkOpIds = allOperations.filter(op => op.reworkId).map(op => op.id!);</span>
-<span class="add">+ let deleteQuery = this.db.deleteFrom("jobOperationDependency")</span>
-<span class="add">+ .where("jobId", "=", this.jobId);</span>
-<span class="add">+ if (reworkOpIds.length > 0) {</span>
-<span class="add">+ deleteQuery = deleteQuery</span>
-<span class="add">+ .where("operationId", "not in", reworkOpIds)</span>
-<span class="add">+ .where("dependsOnId", "not in", reworkOpIds);</span>
-<span class="add">+ }</span></pre>
-</div>
-
-<p>Rework operations are excluded from the dependency builder and their DAG edges are preserved during reschedule.</p>
-
-<!-- ═══════════════ FILE MAP ═══════════════ -->
-<h2 id="file-map">8. File Map</h2>
-
-<h3>Core Behavior</h3>
-<ul class="file-list">
- <li><span class="tag tag-core">core</span> <code>trigger-rework/index.ts</code> &mdash; rework edge function</li>
- <li><span class="tag tag-core">core</span> <code>lib/mrp-engine.ts</code> &mdash; shared BOM explosion</li>
- <li><span class="tag tag-core">core</span> <code>mrp/index.ts</code> &mdash; MRP edge function (refactored)</li>
- <li><span class="tag tag-core">core</span> <code>scheduling-engine.ts</code> &mdash; rework-aware scheduling</li>
- <li><span class="tag tag-core">core</span> <code>planning.update.tsx</code> &mdash; purchasing PO creation</li>
- <li><span class="tag tag-core">core</span> <code>operations.service.ts</code> &mdash; upstream BFS for rework targets</li>
-</ul>
-
-<h3>UI &amp; Frontend</h3>
-<ul class="file-list">
- <li><span class="tag tag-ui">ui</span> <code>ReworkModal.tsx</code> &mdash; rework creation form</li>
- <li><span class="tag tag-ui">ui</span> <code>JobOperation.tsx</code> &mdash; MES operation page</li>
- <li><span class="tag tag-ui">ui</span> <code>DemandForecastSourcesPopover.tsx</code></li>
- <li><span class="tag tag-ui">ui</span> <code>PlannedOrderDetailsPopover.tsx</code></li>
- <li><span class="tag tag-ui">ui</span> <code>BottomSheet.tsx</code> &mdash; new shared component</li>
- <li><span class="tag tag-ui">ui</span> <code>BarProgress.tsx</code> &mdash; refactored gradient</li>
- <li><span class="tag tag-ui">ui</span> <code>ItemPlanningChart.tsx</code>, <code>ItemReorderPolicy.tsx</code></li>
- <li><span class="tag tag-ui">ui</span> <code>PurchasingPlanningOrderDrawer.tsx</code></li>
-</ul>
-
-<h3>Database</h3>
-<ul class="file-list">
- <li><span class="tag tag-db">db</span> 4 migrations (rework, forecast source, open PO view, RPC updates)</li>
- <li><span class="tag tag-db">db</span> <code>types.ts</code> (x2) &mdash; auto-generated schema types</li>
-</ul>
-
-<h3>Package</h3>
-<ul class="file-list">
- <li><span class="tag tag-pkg">pkg</span> <code>packages/mrp/</code> &mdash; new MRP engine package with 22 tests</li>
-</ul>
-
-<h3>Infrastructure / Noise (safe to skim)</h3>
-<ul class="file-list">
- <li><span class="tag tag-infra">infra</span> <code>.github/workflows/</code> &mdash; labeler, complexity scoring</li>
- <li><span class="tag tag-infra">infra</span> <code>scripts/pr-complexity/</code> &mdash; PR scoring tool</li>
- <li><span class="tag tag-infra">infra</span> <code>packages/locale/</code> &mdash; 12 locale files with new strings</li>
- <li><span class="tag tag-infra">infra</span> <code>pnpm-lock.yaml</code>, <code>turbo.json</code></li>
-</ul>
-
-<!-- ═══════════════ VERIFICATION ═══════════════ -->
-<h2 id="verification">9. Verification</h2>
-
-<h3>Tests</h3>
-
-<div class="diff">
- <div class="diff-title">MRP engine tests: 22 passing</div>
- <pre>
-<span class="add">$ cd packages/mrp && npx vitest run</span>
-<span class="add"> Test Files 1 passed (1)</span>
-<span class="add"> Tests 22 passed (22)</span>
-<span class="add"> Duration 140ms</span></pre>
-</div>
-
-<h3>Recommended Commands</h3>
-<pre style="background:var(--surface); padding:1rem; border-radius:6px; font-size:0.82rem; overflow-x:auto;">
-# MRP engine unit tests
-cd packages/mrp && npx vitest run
-
-# Full build (check for type errors)
-pnpm turbo build --filter ./packages/mrp
-
-# Manual verification: trigger rework on a running job
-# 1. Open MES, find a job with multiple operations
-# 2. Start and complete an early operation
-# 3. On a later operation, open the rework action
-# 4. Select a target operation, set quantity, enter reason
-# 5. Verify: cloned operations appear in the DAG
-# 6. Verify: completing all rework ops marks the rework as complete
-# 7. Verify: MRP re-run includes rework quantities in forecasts
-</pre>
-
-<div class="callout warn">
- <strong>Not yet verified:</strong> The full rework flow requires a running database with the migrations applied. The MRP engine tests validate the pure algorithm. Integration testing of the edge function, scheduling engine rework awareness, and the auto-completion trigger should be done against a dev environment.
-</div>
-
-<!-- ═══════════════ TAKEAWAY ═══════════════ -->
-<h2 id="takeaway">10. Reviewer Takeaway</h2>
-
-<p><strong>Mental model:</strong> This PR adds a "branch and reconverge" primitive to job operations. When something goes wrong mid-production, the system clones the relevant operation path, runs it as a parallel branch in the DAG, and merges back downstream. Everything else&mdash;scheduling, MRP, quantity tracking&mdash;is made rework-aware without changing its core logic.</p>
-
-<h3>Where to focus your review</h3>
-
-<ol>
- <li><strong><code>trigger-rework/index.ts</code></strong> &mdash; the core transaction. Verify the DAG wiring logic: do rework ops converge correctly? Is the sort-order interpolation correct for edge cases (e.g., no downstream operations)?</li>
- <li><strong>Migration <code>20260529163847</code></strong> &mdash; the RPC updates. The terminal-op quantity summing is the most complex logic. Verify it handles: single terminal, multiple terminals, rework + non-rework terminals.</li>
- <li><strong><code>scheduling-engine.ts</code></strong> &mdash; the <code>!op.reworkId</code> filter. Verify rework ops are truly invisible to the dependency builder and their edges survive reschedule.</li>
- <li><strong><code>mrp/index.ts</code> refactoring</strong> &mdash; the <code>explodeBom()</code> call. Confirmed zero behavioral change; reviewable by diffing the removed loop against <code>lib/mrp-engine.ts</code>.</li>
- <li><strong><code>ReworkModal.tsx</code></strong> &mdash; the user-facing form. Check validation, quantity defaults, error handling.</li>
-</ol>
-
-<div class="callout ok">
- <strong>What you can skim:</strong> Locale files (auto-generated translations), <code>.github/workflows/</code> (CI tooling), <code>packages/database/src/types.ts</code> (auto-generated), <code>scripts/pr-complexity/</code> (separate tooling feature), UI prop additions on Select/Textarea/DateTimePicker (minor controlled-value wiring).
-</div>
-
-<p style="color:var(--muted); font-size:0.8rem; margin-top:3rem; text-align:center;">
- Generated by PR Explainer &bull; feat/rework &bull; 2026-05-30
-</p>
-
-</body>
-</html>
diff --git a/.vscode/settings.json b/.vscode/settings.json
index e9b519ee54..f2c2326c76 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -1,6 +1,6 @@
{
"deno.cacheOnSave": true,
- "deno.enablePaths": ["./packages/database"],
+ "deno.enablePaths": ["./packages/database/supabase/functions"],
"typescript.tsdk": "node_modules/typescript/lib",
"deno.enable": true,
"js/ts.tsdk.path": "node_modules/typescript/lib",
diff --git a/apps/erp/app/components/Message.tsx b/apps/erp/app/components/Message.tsx
index 3e959b8ad0..998c85475c 100644
--- a/apps/erp/app/components/Message.tsx
+++ b/apps/erp/app/components/Message.tsx
@@ -28,7 +28,7 @@ export const MessageContent = ({
<div
className={cn(
"flex flex-col gap-2 overflow-hidden rounded-lg px-4 py-3 text-foreground text-sm bg-card",
- "group-[.is-user]:!bg-muted group-[.is-user]:!text-primary group-[.is-user]:!px-4 group-[.is-user]:!py-2 group-[.is-user]:max-w-fit group-[.is-user]:rounded-2xl group-[.is-user]:rounded-br-none",
+ "group-[.is-user]:!bg-muted group-[.is-user]:!text-foreground group-[.is-user]:!px-4 group-[.is-user]:!py-2 group-[.is-user]:max-w-fit group-[.is-user]:rounded-2xl group-[.is-user]:rounded-br-none",
"group-[.is-assistant]:!bg-transparent group-[.is-assistant]:!shadow-none group-[.is-assistant]:!border-none group-[.is-assistant]:!px-0 group-[.is-assistant]:!py-0 group-[.is-assistant]:!rounded-none group-[.is-assistant]:!text-muted-foreground",
className
)}
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsx
index da9cd049a3..adc7a7f550 100644
--- a/apps/erp/app/components/Table/Table.tsx
+++ b/apps/erp/app/components/Table/Table.tsx
@@ -30,6 +30,7 @@ import type {
ColumnDef,
ColumnOrderState,
ColumnPinningState,
+ OnChangeFn,
Table as ReactTable,
RowData,
RowSelectionState
@@ -102,6 +103,9 @@ interface TableProps<T extends object> {
withSearch?: boolean;
withSelectableRows?: boolean;
withSimpleSorting?: boolean;
+ getRowId?: (originalRow: T, index: number) => string;
+ rowSelection?: RowSelectionState;
+ onRowSelectionChange?: OnChangeFn<RowSelectionState>;
onSelectedRowsChange?: (selectedRows: T[]) => void;
renderActions?: (selectedRows: T[]) => ReactNode;
renderContextMenu?: (row: T) => JSX.Element | null;
@@ -237,6 +241,9 @@ const Table = <T extends object>({
withSearch = true,
withSelectableRows = false,
withSimpleSorting = true,
+ getRowId,
+ rowSelection: controlledRowSelection,
+ onRowSelectionChange,
onSelectedRowsChange,
renderActions,
renderContextMenu,
@@ -265,17 +272,25 @@ const Table = <T extends object>({
setInternalData(data);
}, [data]);
- /* Clear row selection when data changes */
+ /* Selectable Rows */
+ const [internalRowSelection, setInternalRowSelection] =
+ useState<RowSelectionState>({});
+ const isSelectionControlled = controlledRowSelection !== undefined;
+ const rowSelection = isSelectionControlled
+ ? controlledRowSelection
+ : internalRowSelection;
+ const setRowSelection = onRowSelectionChange ?? setInternalRowSelection;
+
+ /* Clear row selection when data changes. Skip when rows have stable ids
+ (getRowId) or selection is controlled — the selection survives data
+ reshapes like tree expansion in those cases. */
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
- if (withSelectableRows) {
+ if (withSelectableRows && !getRowId && !isSelectionControlled) {
setRowSelection({});
}
}, [data.length, withSelectableRows]);
- /* Selectable Rows */
- const [rowSelection, setRowSelection] = useState<RowSelectionState>({});
-
/* Pagination */
const pagination = usePagination(count, setRowSelection);
@@ -433,6 +448,7 @@ const Table = <T extends object>({
onColumnOrderChange: setColumnOrder,
onColumnPinningChange: setColumnPinning,
onRowSelectionChange: setRowSelection,
+ getRowId,
getCoreRowModel: getCoreRowModel(),
meta: {
// These are not part of the standard API, but are accessible via table.options.meta
@@ -793,6 +809,12 @@ const Table = <T extends object>({
calculateColumnWidths();
});
resizeObserver.observe(tableWrapper);
+ // Also observe the table itself: internal layout changes (e.g. tree
+ // expansion adding rows/widening columns) resize the table without
+ // resizing the wrapper, which would leave pinned offsets stale.
+ if (tableRef.current) {
+ resizeObserver.observe(tableRef.current);
+ }
return () => resizeObserver.disconnect();
}
}, [
@@ -966,7 +988,8 @@ const Table = <T extends object>({
colSpan={header.colSpan}
id={`header-${header.id}`}
className={cn(
- "px-4 py-3 whitespace-nowrap bg-card",
+ "py-3 whitespace-nowrap bg-card",
+ header.column.id === "Select" ? "px-2" : "px-4",
editMode && "border-r-1 border-border",
sortable && "cursor-pointer"
)}
@@ -1189,7 +1212,11 @@ function getRowSelectionColumn<T>(): ColumnDef<T>[] {
return [
{
id: "Select",
- size: 50,
+ // width:1 + whitespace-nowrap = shrink-to-fit. A fixed pixel width
+ // inflates on w-full auto-layout tables because leftover space is
+ // distributed proportionally to specified column widths.
+ size: 1,
+ minSize: 1,
enablePinning: true,
header: ({ table }) => (
<IndeterminateCheckbox
diff --git a/apps/erp/app/components/Table/components/Cell.tsx b/apps/erp/app/components/Table/components/Cell.tsx
index 9cb4979674..b668b184dd 100644
--- a/apps/erp/app/components/Table/components/Cell.tsx
+++ b/apps/erp/app/components/Table/components/Cell.tsx
@@ -57,7 +57,8 @@ const Cell = <T extends object>({
return (
<Td
className={cn(
- "relative px-4 py-2 whitespace-nowrap text-sm outline-none max-w-[30dvw] truncate",
+ "relative py-2 whitespace-nowrap text-sm outline-none max-w-[30dvw] truncate",
+ cell.column.id === "Select" ? "px-2" : "px-4",
wasEdited && "bg-yellow-100 dark:bg-yellow-900",
isEditMode && !hasEditableTableCellComponent && "bg-muted/50",
isEditMode && "border-border border-r",
diff --git a/apps/erp/app/components/index.ts b/apps/erp/app/components/index.ts
index 5b7378e60a..f9b272cf6d 100644
--- a/apps/erp/app/components/index.ts
+++ b/apps/erp/app/components/index.ts
@@ -1,3 +1,4 @@
+import { PrintButton } from "@carbon/printing/ui";
import Assignee, { useOptimisticAssignment } from "./Assignee";
import Avatar from "./Avatar";
import AvatarMenu from "./AvatarMenu";
@@ -65,6 +66,7 @@ export {
ModuleIcon,
New,
OperationStatusIcon,
+ PrintButton,
RealtimeDataProvider,
SearchFilter,
SearchLandingPage,
diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.ts
index 9f06be428f..5495d9085d 100644
--- a/apps/erp/app/hooks/index.ts
+++ b/apps/erp/app/hooks/index.ts
@@ -1,10 +1,10 @@
+import { usePrinting } from "@carbon/printing/ui";
import {
useNanoStore,
useOptimisticLocation,
useRouteData,
useUrlParams
} from "@carbon/react";
-
import { useCompanySettings } from "./useCompanySettings";
import { useCurrencyFormatter } from "./useCurrencyFormatter";
import { useDateFormatter } from "./useDateFormatter";
@@ -43,6 +43,7 @@ export {
usePercentFormatter,
usePermissions,
usePlanGate,
+ usePrinting,
useRealtime,
useRouteData,
useScrollPosition,
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
index d340849455..29b3beb46f 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryStorageUnits.tsx
@@ -6,6 +6,7 @@ import {
Submit,
ValidatedForm
} from "@carbon/form";
+import { LabelDownloadModal } from "@carbon/printing/ui";
import {
Button,
Card,
@@ -18,10 +19,6 @@ import {
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
- DropdownMenuPortal,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
DropdownMenuTrigger,
HStack,
IconButton,
@@ -37,27 +34,28 @@ import {
Th,
Thead,
Tr,
+ toast,
useDisclosure,
VStack
} from "@carbon/react";
-import { labelSizes } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import { nanoid } from "nanoid";
import { useMemo, useState } from "react";
import {
+ LuCheck,
LuEllipsisVertical,
LuPencil,
LuPrinter,
LuQrCode
} from "react-icons/lu";
-import { Outlet } from "react-router";
+import { Outlet, useFetcher } from "react-router";
import type { z } from "zod";
import { Enumerable } from "~/components/Enumerable";
import { Input, Location, Select, TextArea } from "~/components/Form";
import { StorageUnitDrillSelectField } from "~/components/Form/StorageUnitDrillSelect";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
-import { usePermissions } from "~/hooks";
+import { usePermissions, usePrinting } from "~/hooks";
import type {
ItemStorageUnitQuantities,
itemTrackingTypes,
@@ -160,27 +158,49 @@ const InventoryStorageUnits = ({
adjustmentModal.onOpen();
};
- const navigateToLabel = (
- trackedEntityId: string,
- zpl?: boolean,
- labelSize?: string
- ) => {
- if (!window) return;
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.trackedEntityLabelZpl(trackedEntityId, { labelSize }),
- "_blank"
- );
+ const { printerRoutes, resolvePrinterRoute } = usePrinting();
+ const printerModal = useDisclosure();
+ const downloadModal = useDisclosure();
+ const printFetcher = useFetcher<{ success: boolean; message: string }>();
+ const [pendingPrintEntityId, setPendingPrintEntityId] = useState<
+ string | null
+ >(null);
+ const locationId = pickMethod.locationId;
+ const defaultPrinter = resolvePrinterRoute(locationId, "inventory");
+ const [selectedPrinterId, setSelectedPrinterId] = useState<string>(
+ defaultPrinter?.id ?? ""
+ );
+
+ const handlePrintLabel = (trackedEntityId: string) => {
+ setPendingPrintEntityId(trackedEntityId);
+ if (printerRoutes.length > 0) {
+ setSelectedPrinterId(defaultPrinter?.id ?? printerRoutes[0]?.id ?? "");
+ printerModal.onOpen();
} else {
- window.open(
- window.location.origin +
- path.to.file.trackedEntityLabelPdf(trackedEntityId, { labelSize }),
- "_blank"
- );
+ downloadModal.onOpen();
}
};
+ const handleConfirmPrint = () => {
+ if (!pendingPrintEntityId || !selectedPrinterId) return;
+ printFetcher.submit(
+ {
+ sourceDocument: "Entity",
+ sourceDocumentId: pendingPrintEntityId,
+ locationId,
+ printerRouteId: selectedPrinterId
+ },
+ {
+ method: "POST",
+ action: path.to.manualPrint,
+ encType: "application/json"
+ }
+ );
+ toast.success("Print job queued");
+ printerModal.onClose();
+ setPendingPrintEntityId(null);
+ };
+
return (
<>
<Card className="w-full">
@@ -271,30 +291,14 @@ const InventoryStorageUnits = ({
<Trans>Update Quantity</Trans>
</DropdownMenuItem>
{item.trackedEntityId && (
- <DropdownMenuSub>
- <DropdownMenuSubTrigger>
- <LuPrinter className="mr-2 h-4 w-4" />
- <Trans>Print Label</Trans>
- </DropdownMenuSubTrigger>
- <DropdownMenuPortal>
- <DropdownMenuSubContent>
- {labelSizes.map((size) => (
- <DropdownMenuItem
- key={size.id}
- onClick={() =>
- navigateToLabel(
- item.trackedEntityId!,
- !!size.zpl,
- size.id
- )
- }
- >
- {size.name}
- </DropdownMenuItem>
- ))}
- </DropdownMenuSubContent>
- </DropdownMenuPortal>
- </DropdownMenuSub>
+ <DropdownMenuItem
+ onClick={() =>
+ handlePrintLabel(item.trackedEntityId!)
+ }
+ >
+ <DropdownMenuIcon icon={<LuPrinter />} />
+ <Trans>Print Label</Trans>
+ </DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
@@ -433,6 +437,73 @@ const InventoryStorageUnits = ({
</Modal>
)}
<ruleViolations.ViolationModal />
+ {printerModal.isOpen && pendingPrintEntityId && (
+ <Modal open onOpenChange={(open) => !open && printerModal.onClose()}>
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Select Printer</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-1">
+ {printerRoutes.map((route) => (
+ <button
+ type="button"
+ key={route.id}
+ className={`flex items-center gap-3 rounded-lg border p-3 text-left transition-colors ${
+ selectedPrinterId === route.id
+ ? "border-primary bg-primary/5"
+ : "border-border hover:bg-muted"
+ }`}
+ onClick={() => setSelectedPrinterId(route.id)}
+ >
+ <LuPrinter className="size-4 text-muted-foreground shrink-0" />
+ <div className="flex-1 min-w-0">
+ <span className="text-sm font-medium">{route.name}</span>
+ <span className="text-xs text-muted-foreground ml-2 uppercase">
+ {route.format}
+ </span>
+ </div>
+ {selectedPrinterId === route.id && (
+ <LuCheck className="size-4 text-primary shrink-0" />
+ )}
+ </button>
+ ))}
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <div className="flex gap-2">
+ <Button
+ variant="primary"
+ leftIcon={<LuPrinter />}
+ disabled={!selectedPrinterId}
+ onClick={handleConfirmPrint}
+ >
+ <Trans>Print</Trans>
+ </Button>
+ <Button variant="solid" onClick={printerModal.onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </div>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
+ {downloadModal.isOpen && pendingPrintEntityId && (
+ <LabelDownloadModal
+ sourceDocumentId={pendingPrintEntityId}
+ fileRoutes={{
+ pdf: path.to.file.trackedEntityLabelPdf,
+ zpl: path.to.file.trackedEntityLabelZpl
+ }}
+ isOpen={downloadModal.isOpen}
+ onClose={() => {
+ downloadModal.onClose();
+ setPendingPrintEntityId(null);
+ }}
+ />
+ )}
<Outlet />
</>
);
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
index d7124fe1f6..e752226a66 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptForm/ReceiptForm.tsx
@@ -7,16 +7,13 @@ import {
DropdownMenuIcon,
DropdownMenuItem,
DropdownMenuSeparator,
- SplitButton,
useDisclosure,
VStack
} from "@carbon/react";
-import { labelSizes } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import {
LuCheckCheck,
LuCreditCard,
- LuQrCode,
LuShoppingCart,
LuTicketX,
LuTrash,
@@ -24,7 +21,7 @@ import {
} from "react-icons/lu";
import { Link, useParams } from "react-router";
import type { z } from "zod";
-import { DocumentHeader } from "~/components";
+import { DocumentHeader, PrintButton } from "~/components";
import { useAuditLog } from "~/components/AuditLog";
import {
Combobox,
@@ -111,23 +108,6 @@ const ReceiptForm = ({
const receiptLineTracking = routeData?.receiptLineTracking ?? [];
- const navigateToTrackingLabels = (zpl?: boolean, labelSize?: string) => {
- if (!window) return;
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.receiptLabelsZpl(receiptId, { labelSize }),
- "_blank"
- );
- } else {
- window.open(
- window.location.origin +
- path.to.file.receiptLabelsPdf(receiptId, { labelSize }),
- "_blank"
- );
- }
- };
-
const canInvoice =
isPosted &&
!isInvoiced &&
@@ -186,18 +166,16 @@ const ReceiptForm = ({
actions={
<>
{receiptLineTracking.length > 0 && (
- <SplitButton
- leftIcon={<LuQrCode />}
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () =>
- navigateToTrackingLabels(!!size.zpl, size.id)
- }))}
- onClick={() => navigateToTrackingLabels(false)}
- variant={isPosted ? "primary" : "secondary"}
- >
- <Trans>Tracking Labels</Trans>
- </SplitButton>
+ <PrintButton
+ sourceDocument="Receipt"
+ sourceDocumentId={receiptId}
+ locationId={locationId ?? undefined}
+ context="receiving"
+ fileRoutes={{
+ pdf: path.to.file.receiptLabelsPdf,
+ zpl: path.to.file.receiptLabelsZpl
+ }}
+ />
)}
<SourceDocumentLink
sourceDocument={
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 0e1b5c2f9d..97c6d94fbb 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -27,7 +27,6 @@ import {
ModalTitle,
NumberField,
NumberInput,
- SplitButton,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -36,7 +35,6 @@ import {
VStack
} from "@carbon/react";
import type { TrackedEntityAttributes } from "@carbon/utils";
-import { labelSizes } from "@carbon/utils";
import { parseDate } from "@internationalized/date";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
@@ -46,7 +44,6 @@ import {
LuCircleAlert,
LuEllipsisVertical,
LuGroup,
- LuQrCode,
LuSplit,
LuTrash,
LuX
@@ -60,7 +57,12 @@ import {
useRevalidator,
useSubmit
} from "react-router";
-import { DocumentPreview, Empty, ItemThumbnail } from "~/components";
+import {
+ DocumentPreview,
+ Empty,
+ ItemThumbnail,
+ PrintButton
+} from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { Enumerable } from "~/components/Enumerable";
import FileDropzone from "~/components/FileDropzone";
@@ -453,7 +455,7 @@ function ReceiptLineItem({
aria-label={t`Line options`}
variant="secondary"
icon={<LuEllipsisVertical />}
- size="sm"
+ size="md"
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
@@ -822,28 +824,6 @@ function BatchForm({
updateBatchNumber(newValues);
};
- const navigateToLineTrackingLabels = (zpl?: boolean, labelSize?: string) => {
- if (!window) return;
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.receiptLabelsZpl(receipt?.id ?? "", {
- lineId: line.id!,
- labelSize
- }),
- "_blank"
- );
- } else {
- window.open(
- window.location.origin +
- path.to.file.receiptLabelsPdf(receipt?.id ?? "", {
- lineId: line.id!,
- labelSize
- }),
- "_blank"
- );
- }
- };
const propertiesDisclosure = useDisclosure();
return (
@@ -851,22 +831,30 @@ function BatchForm({
<div className="flex justify-between items-center gap-4">
<Heading size="h4">Batch Properties</Heading>
<div className="flex items-center gap-2">
- <SplitButton
- size="sm"
- leftIcon={<LuQrCode />}
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () => navigateToLineTrackingLabels(!!size.zpl, size.id)
- }))}
- onClick={() => navigateToLineTrackingLabels(false)}
- variant="secondary"
- >
- Tracking Labels
- </SplitButton>
+ {values.number.trim() !== "" && (
+ <PrintButton
+ sourceDocument="Receipt"
+ sourceDocumentId={receipt?.id ?? ""}
+ locationId={receipt?.locationId ?? undefined}
+ context="receiving"
+ fileRoutes={{
+ pdf: (id, opts) =>
+ path.to.file.receiptLabelsPdf(id, {
+ ...opts,
+ lineId: line.id!
+ }),
+ zpl: (id, opts) =>
+ path.to.file.receiptLabelsZpl(id, {
+ ...opts,
+ lineId: line.id!
+ })
+ }}
+ />
+ )}
<Button
variant="secondary"
leftIcon={<LuGroup />}
- size="sm"
+ size="md"
onClick={propertiesDisclosure.onOpen}
>
Edit Properties
@@ -1075,47 +1063,31 @@ function SerialForm({
[line.id, line.itemId, receipt?.id, validateSerialNumber, expiryDate]
);
- const navigateToLineTrackingLabels = (zpl?: boolean, labelSize?: string) => {
- if (!window) return;
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.receiptLabelsZpl(receipt?.id ?? "", {
- lineId: line.id!,
- labelSize
- }),
- "_blank"
- );
- } else {
- window.open(
- window.location.origin +
- path.to.file.receiptLabelsPdf(receipt?.id ?? "", {
- lineId: line.id!,
- labelSize
- }),
- "_blank"
- );
- }
- };
const propertiesDisclosure = useDisclosure();
- console.log({ serialNumbers, expiryDate });
+
return (
<div className="flex flex-col gap-6 p-6 border rounded-lg">
<div className="flex justify-between items-center gap-6">
<Heading size="h4">Serial Numbers</Heading>
<div className="flex items-center gap-2">
- <SplitButton
- size="sm"
- leftIcon={<LuQrCode />}
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () => navigateToLineTrackingLabels(!!size.zpl, size.id)
- }))}
- onClick={() => navigateToLineTrackingLabels(false)}
- variant="secondary"
- >
- Tracking Labels
- </SplitButton>
+ <PrintButton
+ sourceDocument="Receipt"
+ sourceDocumentId={receipt?.id ?? ""}
+ locationId={receipt?.locationId ?? undefined}
+ context="receiving"
+ fileRoutes={{
+ pdf: (id, opts) =>
+ path.to.file.receiptLabelsPdf(id, {
+ ...opts,
+ lineId: line.id!
+ }),
+ zpl: (id, opts) =>
+ path.to.file.receiptLabelsZpl(id, {
+ ...opts,
+ lineId: line.id!
+ })
+ }}
+ />
</div>
</div>
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
index 86097671dc..0fee9b270e 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentForm/ShipmentForm.tsx
@@ -11,12 +11,9 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
HStack,
- SplitButton,
useDisclosure,
VStack
} from "@carbon/react";
-import type { TrackedEntityAttributes } from "@carbon/utils";
-import { labelSizes } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { Suspense } from "react";
import {
@@ -25,7 +22,6 @@ import {
LuChevronDown,
LuCirclePlus,
LuCreditCard,
- LuQrCode,
LuShoppingCart,
LuTicketX,
LuTrash,
@@ -34,7 +30,7 @@ import {
import { RiProgress8Line } from "react-icons/ri";
import { Await, Link, useNavigate, useParams } from "react-router";
import type { z } from "zod";
-import { DocumentHeader } from "~/components";
+import { DocumentHeader, PrintButton } from "~/components";
import { useAuditLog } from "~/components/AuditLog";
import {
Combobox,
@@ -125,26 +121,7 @@ const ShipmentForm = ({
hasShippableFaLines;
const shipmentLineTracking = routeData?.shipmentLineTracking ?? [];
- const hasTrackingLabels = shipmentLineTracking.some(
- (line) => "Split Entity ID" in (line.attributes as TrackedEntityAttributes)
- );
-
- const navigateToTrackingLabels = (zpl?: boolean, labelSize?: string) => {
- if (!window) return;
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.shipmentLabelsZpl(shipmentId, { labelSize }),
- "_blank"
- );
- } else {
- window.open(
- window.location.origin +
- path.to.file.shipmentLabelsPdf(shipmentId, { labelSize }),
- "_blank"
- );
- }
- };
+ const hasTrackingLabels = shipmentLineTracking.length > 0;
const createInvoice = (shipment?: Shipment) => {
if (!shipment) return;
@@ -205,18 +182,16 @@ const ShipmentForm = ({
actions={
<>
{hasTrackingLabels && (
- <SplitButton
- leftIcon={<LuQrCode />}
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () =>
- navigateToTrackingLabels(!!size.zpl, size.id)
- }))}
- onClick={() => navigateToTrackingLabels(false)}
- variant="primary"
- >
- <Trans>Tracking Labels</Trans>
- </SplitButton>
+ <PrintButton
+ sourceDocument="Shipment"
+ sourceDocumentId={shipmentId}
+ locationId={locationId ?? undefined}
+ context="shipping"
+ fileRoutes={{
+ pdf: path.to.file.shipmentLabelsPdf,
+ zpl: path.to.file.shipmentLabelsZpl
+ }}
+ />
)}
<Button variant="secondary" leftIcon={<LuBarcode />} asChild>
<a
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
index c4a91134b2..c4dc138d40 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
@@ -29,7 +29,6 @@ import {
ModalTitle,
NumberField,
NumberInput,
- SplitButton,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -37,7 +36,7 @@ import {
VStack
} from "@carbon/react";
import type { TrackedEntityAttributes } from "@carbon/utils";
-import { getItemReadableId, labelSizes } from "@carbon/utils";
+import { getItemReadableId } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useState } from "react";
import {
@@ -57,7 +56,7 @@ import {
useParams,
useSubmit
} from "react-router";
-import { Empty, ItemThumbnail } from "~/components";
+import { Empty, ItemThumbnail, PrintButton } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useStorageUnits } from "~/components/Form/StorageUnit";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
@@ -269,10 +268,7 @@ const ShipmentLines = () => {
routeData?.shipmentLineTracking?.some((t) => {
const attributes =
t.attributes as TrackedEntityAttributes;
- return (
- attributes["Shipment Line"] === line.id &&
- attributes["Split Entity ID"]
- );
+ return attributes["Shipment Line"] === line.id;
}) ?? false
}
isReadOnly={isReadOnly}
@@ -458,7 +454,7 @@ function ShipmentLineItem({
aria-label={t`Line options`}
variant="secondary"
icon={<LuEllipsisVertical />}
- size="sm"
+ size="md"
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
@@ -629,6 +625,7 @@ function ShipmentLineItem({
<SerialForm
shipment={shipment}
line={line}
+ hasTrackingLabel={hasTrackingLabel}
serialNumbers={serialNumbers}
isReadOnly={isReadOnly}
onSerialNumbersChange={onSerialNumbersChange}
@@ -870,46 +867,29 @@ function BatchForm({
});
};
- const navigateToLineTrackingLabels = (zpl?: boolean, labelSize?: string) => {
- if (!window) return;
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.shipmentLabelsZpl(shipment?.id ?? "", {
- lineId: line.id!,
- labelSize
- }),
- "_blank"
- );
- } else {
- window.open(
- window.location.origin +
- path.to.file.shipmentLabelsPdf(shipment?.id ?? "", {
- lineId: line.id!,
- labelSize
- }),
- "_blank"
- );
- }
- };
-
return (
<div className="flex flex-col gap-6 w-full p-6 border rounded-lg">
<div className="flex justify-between items-center gap-4">
<Heading size="h4">Tracking Number</Heading>
{hasTrackingLabel && (
- <SplitButton
- size="sm"
- leftIcon={<LuQrCode />}
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () => navigateToLineTrackingLabels(!!size.zpl, size.id)
- }))}
- onClick={() => navigateToLineTrackingLabels(false)}
- variant="primary"
- >
- Tracking Labels
- </SplitButton>
+ <PrintButton
+ sourceDocument="Shipment"
+ sourceDocumentId={shipment?.id ?? ""}
+ locationId={shipment?.locationId ?? undefined}
+ context="shipping"
+ fileRoutes={{
+ pdf: (id, opts) =>
+ path.to.file.shipmentLabelsPdf(id, {
+ ...opts,
+ lineId: line.id!
+ }),
+ zpl: (id, opts) =>
+ path.to.file.shipmentLabelsZpl(id, {
+ ...opts,
+ lineId: line.id!
+ })
+ }}
+ />
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4 ">
@@ -973,12 +953,14 @@ function BatchForm({
function SerialForm({
line,
shipment,
+ hasTrackingLabel,
serialNumbers,
isReadOnly,
onSerialNumbersChange
}: {
line: ShipmentLine;
shipment?: Shipment;
+ hasTrackingLabel: boolean;
serialNumbers: { index: number; id: string }[];
isReadOnly: boolean;
onSerialNumbersChange: (
@@ -1139,7 +1121,29 @@ function SerialForm({
return (
<div className="flex flex-col gap-6 p-6 border rounded-lg">
- <Heading size="h4">Tracking Numbers</Heading>
+ <div className="flex justify-between items-center gap-4">
+ <Heading size="h4">Tracking Numbers</Heading>
+ {hasTrackingLabel && (
+ <PrintButton
+ sourceDocument="Shipment"
+ sourceDocumentId={shipment?.id ?? ""}
+ locationId={shipment?.locationId ?? undefined}
+ context="shipping"
+ fileRoutes={{
+ pdf: (id, opts) =>
+ path.to.file.shipmentLabelsPdf(id, {
+ ...opts,
+ lineId: line.id!
+ }),
+ zpl: (id, opts) =>
+ path.to.file.shipmentLabelsZpl(id, {
+ ...opts,
+ lineId: line.id!
+ })
+ }}
+ />
+ )}
+ </div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-x-4 gap-y-3">
{serialNumbers.map((serialNumber, index) => {
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
index a043356bd6..0e95b994c4 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
@@ -24,6 +24,7 @@ import {
LuTrash
} from "react-icons/lu";
import { useFetcher, useParams } from "react-router";
+import { PrintButton } from "~/components";
import Assignee, { useOptimisticAssignment } from "~/components/Assignee";
import { useAuditLog } from "~/components/AuditLog";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
@@ -97,6 +98,10 @@ const StockTransferHeader = () => {
(line) => line.pickedQuantity && line.pickedQuantity > 0
);
+ const hasTrackedLines = routeData?.stockTransferLines.some(
+ (line) => !!line.trackedEntityId
+ );
+
return (
<>
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1)]">
@@ -167,6 +172,18 @@ const StockTransferHeader = () => {
table="stockTransfer"
isReadOnly={!permissions.can("update", "inventory")}
/>
+ {hasTrackedLines && (
+ <PrintButton
+ sourceDocument="StockTransfer"
+ sourceDocumentId={id}
+ locationId={routeData?.stockTransfer?.locationId ?? undefined}
+ context="inventory"
+ fileRoutes={{
+ pdf: path.to.file.stockTransferLabelsPdf,
+ zpl: path.to.file.stockTransferLabelsZpl
+ }}
+ />
+ )}
<Button variant="secondary" leftIcon={<LuBarcode />} asChild>
<a
target="_blank"
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx
index f470548f27..dbbf0938fd 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferLines.tsx
@@ -36,7 +36,7 @@ import {
useParams,
useSubmit
} from "react-router";
-import { Empty, ItemThumbnail } from "~/components";
+import { Empty, ItemThumbnail, PrintButton } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
@@ -54,6 +54,7 @@ interface StockTransferLineProps {
line: StockTransferLine;
index: number;
totalLines: number;
+ locationId?: string;
pickedQuantity: number;
isPickable: boolean;
isEditable: boolean;
@@ -68,6 +69,7 @@ function StockTransferLineComponent({
line,
index,
totalLines,
+ locationId,
pickedQuantity,
isPickable,
isEditable,
@@ -152,6 +154,18 @@ function StockTransferLineComponent({
)}
</HStack>
<HStack spacing={1}>
+ {line.trackedEntityId && (
+ <PrintButton
+ sourceDocument="Entity"
+ sourceDocumentId={line.trackedEntityId}
+ locationId={locationId}
+ context="inventory"
+ fileRoutes={{
+ pdf: path.to.file.trackedEntityLabelPdf,
+ zpl: path.to.file.trackedEntityLabelZpl
+ }}
+ />
+ )}
{pickedQuantity === line.quantity ? (
<Button
variant="secondary"
@@ -367,6 +381,7 @@ export default function StockTransferLines() {
line={line}
index={index}
totalLines={lines.length}
+ locationId={routeData?.stockTransfer?.locationId ?? undefined}
pickedQuantity={pickedQuantitiesById.get(line.id ?? "") ?? 0}
isPickable={isPickable}
isEditable={isEditable}
diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
index 3341ac55e9..00da544683 100644
--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitForm.tsx
@@ -14,6 +14,7 @@ import {
import { Trans, useLingui } from "@lingui/react/macro";
import { useFetcher } from "react-router";
import type { z } from "zod";
+import { PrintButton } from "~/components";
import {
Hidden,
Input,
@@ -115,6 +116,20 @@ const StorageUnitForm = ({
<Button size="md" variant="solid" onClick={onClose}>
<Trans>Cancel</Trans>
</Button>
+ {isEditing && initialValues.id && (
+ <PrintButton
+ sourceDocument="StorageUnit"
+ sourceDocumentId={initialValues.id}
+ locationId={locationId || undefined}
+ context="inventory"
+ fileRoutes={{
+ pdf: (id: string, opts?: { labelSize?: string }) =>
+ path.to.file.storageUnitLabelsPdf(id, opts),
+ zpl: (id: string, opts?: { labelSize?: string }) =>
+ path.to.file.storageUnitLabelsZpl(id, opts)
+ }}
+ />
+ )}
</HStack>
</ModalDrawerFooter>
</ValidatedForm>
diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx
index df6dbcd10a..e0d2d599ca 100644
--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx
@@ -1,15 +1,24 @@
+import { LabelDownloadModal } from "@carbon/printing/ui";
import {
+ Button,
Checkbox,
Combobox,
HStack,
- IconButton,
MenuIcon,
MenuItem,
- Spinner
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ Spinner,
+ toast,
+ useDisclosure
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
LuBookMarked,
LuCheck,
@@ -19,6 +28,7 @@ import {
LuMapPin,
LuPencil,
LuPlus,
+ LuPrinter,
LuTrash
} from "react-icons/lu";
import { useNavigate } from "react-router";
@@ -26,7 +36,8 @@ import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { useStorageTypes } from "~/components/Form/StorageTypes";
-import { usePermissions, useUrlParams } from "~/hooks";
+import { IndeterminateCheckbox } from "~/components/Table/components";
+import { usePermissions, usePrinting, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
type StorageUnit = {
@@ -115,14 +126,44 @@ const StorageUnitsTable = memo(
() => new Set(initialExpanded)
);
const [loadingIds, setLoadingIds] = useState<Set<string>>(new Set());
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
- // Reset state when the loader payload changes (location switch, search,
- // pagination) so stale expand state doesn't leak across navigations.
+ // Reset tree state only when the loader payload MEANINGFULLY changes
+ // (location switch, search, pagination). Keying on object identity would
+ // also fire on every revalidation (e.g. after a fetcher POST or opening
+ // a drawer route), collapsing the tree and wiping the selection.
+ const dataSignature = useMemo(
+ () =>
+ `${locationId}::${data.map((r) => r.id).join(",")}::${initialExpanded.join(",")}`,
+ [locationId, data, initialExpanded]
+ );
+ const prevSignature = useRef(dataSignature);
useEffect(() => {
+ if (prevSignature.current === dataSignature) return;
+ prevSignature.current = dataSignature;
setChildrenCache(initialChildrenCache);
setExpandedIds(new Set(initialExpanded));
setLoadingIds(new Set());
- }, [initialChildrenCache, initialExpanded]);
+ setSelectedIds(new Set());
+ }, [dataSignature, initialChildrenCache, initialExpanded]);
+
+ // Keep a ref to the cache so the recursive descendant walk always sees
+ // the latest children without stale-closure issues.
+ const childrenCacheRef = useRef(childrenCache);
+ childrenCacheRef.current = childrenCache;
+
+ const collectDescendantIds = useCallback((id: string): string[] => {
+ const cache = childrenCacheRef.current;
+ const out: string[] = [];
+ const walk = (parentId: string) => {
+ for (const kid of cache[parentId] ?? []) {
+ out.push(kid.id);
+ walk(kid.id);
+ }
+ };
+ walk(id);
+ return out;
+ }, []);
const toggleExpand = useCallback(
async (id: string) => {
@@ -142,7 +183,15 @@ const StorageUnitsTable = memo(
try {
const res = await fetch(path.to.api.storageUnitChildren(id));
const body = (await res.json()) as { data: StorageUnit[] };
- setChildrenCache((prev) => ({ ...prev, [id]: body.data ?? [] }));
+ const kids = body.data ?? [];
+ setChildrenCache((prev) => ({ ...prev, [id]: kids }));
+ // Newly loaded children inherit a selected parent's selection
+ setSelectedIds((prev) => {
+ if (!prev.has(id)) return prev;
+ const next = new Set(prev);
+ for (const kid of kids) next.add(kid.id);
+ return next;
+ });
} finally {
setLoadingIds((prev) => {
const next = new Set(prev);
@@ -154,6 +203,27 @@ const StorageUnitsTable = memo(
[expandedIds, childrenCache]
);
+ // Checking a unit cascades to all loaded descendants; unchecking removes
+ // them. A parent with some (but not all of) its subtree selected renders
+ // as indeterminate.
+ const toggleSelected = useCallback(
+ (id: string) => {
+ setSelectedIds((prev) => {
+ const next = new Set(prev);
+ const isSelecting = !next.has(id);
+ if (isSelecting) {
+ next.add(id);
+ for (const descId of collectDescendantIds(id)) next.add(descId);
+ } else {
+ next.delete(id);
+ for (const descId of collectDescendantIds(id)) next.delete(descId);
+ }
+ return next;
+ });
+ },
+ [collectDescendantIds]
+ );
+
// Build the displayed flat-row list by walking roots and recursing into
// expanded subtrees. Roots = depth-1 rows in `data` (true for both
// root-mode and search-mode payloads).
@@ -173,8 +243,51 @@ const StorageUnitsTable = memo(
return out;
}, [data, expandedIds, childrenCache]);
+ const allSelected =
+ displayRows.length > 0 && displayRows.every((r) => selectedIds.has(r.id));
+ const someSelected = selectedIds.size > 0 && !allSelected;
+
+ const toggleAllSelected = useCallback(() => {
+ setSelectedIds((prev) => {
+ const visible = displayRows.map((r) => r.id);
+ const everyVisibleSelected =
+ visible.length > 0 && visible.every((id) => prev.has(id));
+ return everyVisibleSelected ? new Set() : new Set(visible);
+ });
+ }, [displayRows]);
+
const columns = useMemo<ColumnDef<StorageUnit>[]>(() => {
return [
+ {
+ // The id "Select" opts into the Table's compact checkbox-column
+ // styling (px-2, shrink-to-fit width).
+ id: "Select",
+ size: 50,
+ minSize: 1,
+ header: () => (
+ <IndeterminateCheckbox
+ checked={allSelected}
+ indeterminate={someSelected}
+ onChange={toggleAllSelected}
+ />
+ ),
+ cell: ({ row }) => {
+ const id = row.original.id;
+ const isChecked = selectedIds.has(id);
+ const isIndeterminate =
+ !isChecked &&
+ collectDescendantIds(id).some((descId) =>
+ selectedIds.has(descId)
+ );
+ return (
+ <IndeterminateCheckbox
+ checked={isChecked}
+ indeterminate={isIndeterminate}
+ onChange={() => toggleSelected(id)}
+ />
+ );
+ }
+ },
{
accessorKey: "name",
header: t`Name`,
@@ -185,32 +298,7 @@ const StorageUnitsTable = memo(
const hasChildren = hasChildrenSet.has(row.original.id);
return (
- <div className="flex items-stretch self-stretch gap-1">
- <div className="size-7 shrink-0 flex items-center justify-center self-center">
- {hasChildren ? (
- <IconButton
- aria-label={
- isExpanded ? t`Collapse subtree` : t`Expand subtree`
- }
- icon={
- isLoading ? (
- <Spinner className="size-3" />
- ) : isExpanded ? (
- <LuChevronDown />
- ) : (
- <LuChevronRight />
- )
- }
- size="sm"
- variant="ghost"
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- toggleExpand(row.original.id);
- }}
- />
- ) : null}
- </div>
+ <div className="flex flex-1">
{Array.from({ length: depth }).map((_, i) => (
<div
key={i}
@@ -218,6 +306,32 @@ const StorageUnitsTable = memo(
className="w-5 shrink-0 border-l border-border -my-2"
/>
))}
+ <div className="w-5 shrink-0 flex items-center justify-center self-center">
+ {hasChildren ? (
+ isLoading ? (
+ <Spinner className="size-3" />
+ ) : (
+ <button
+ type="button"
+ aria-label={
+ isExpanded ? t`Collapse subtree` : t`Expand subtree`
+ }
+ className="text-muted-foreground hover:text-foreground shrink-0"
+ onClick={(e) => {
+ e.stopPropagation();
+ e.preventDefault();
+ toggleExpand(row.original.id);
+ }}
+ >
+ {isExpanded ? (
+ <LuChevronDown className="size-4" />
+ ) : (
+ <LuChevronRight className="size-4" />
+ )}
+ </button>
+ )
+ ) : null}
+ </div>
<div className="flex items-center py-1">
<Hyperlink
to={`${path.to.storageUnit(row.original.id)}?${params}`}
@@ -307,20 +421,94 @@ const StorageUnitsTable = memo(
expandedIds,
loadingIds,
hasChildrenSet,
- toggleExpand
+ toggleExpand,
+ selectedIds,
+ allSelected,
+ someSelected,
+ toggleAllSelected,
+ toggleSelected,
+ collectDescendantIds
]);
+ /* Bulk printing */
+ const { printerRoutes, resolvePrinterRoute } = usePrinting();
+ const printerModal = useDisclosure();
+ const downloadModal = useDisclosure();
+ const defaultPrinter = resolvePrinterRoute(locationId, "inventory");
+ const [selectedPrinterId, setSelectedPrinterId] = useState<string>("");
+ const [isPrinting, setIsPrinting] = useState(false);
+
+ const handlePrintLabels = useCallback(() => {
+ if (printerRoutes.length > 0) {
+ setSelectedPrinterId(defaultPrinter?.id ?? printerRoutes[0]?.id ?? "");
+ printerModal.onOpen();
+ } else {
+ downloadModal.onOpen();
+ }
+ }, [printerRoutes, defaultPrinter?.id, printerModal, downloadModal]);
+
+ // Raw fetch (not a fetcher): parallel submissions don't abort each other
+ // and nothing revalidates, so the tree and selection stay intact.
+ const handleConfirmPrint = useCallback(async () => {
+ const ids = Array.from(selectedIds);
+ if (ids.length === 0 || !selectedPrinterId) return;
+
+ setIsPrinting(true);
+ try {
+ const results = await Promise.allSettled(
+ ids.map((id) =>
+ fetch(path.to.manualPrint, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ sourceDocument: "StorageUnit",
+ sourceDocumentId: id,
+ locationId,
+ printerRouteId: selectedPrinterId
+ })
+ })
+ )
+ );
+
+ const failed = results.filter(
+ (r) => r.status === "rejected" || !r.value.ok
+ ).length;
+
+ if (failed > 0) {
+ toast.error(
+ `${failed} of ${ids.length} print job${ids.length === 1 ? "" : "s"} failed`
+ );
+ } else {
+ toast.success(
+ `Queued ${ids.length} label${ids.length === 1 ? "" : "s"} for printing`
+ );
+ }
+ } finally {
+ setIsPrinting(false);
+ printerModal.onClose();
+ }
+ }, [selectedIds, selectedPrinterId, locationId, printerModal]);
+
const defaultColumnVisibility = {
active: false
};
const defaultColumnPinning = {
- left: ["name"]
+ left: ["Select", "name"]
};
const actions = useMemo(() => {
return (
<div className="flex items-center gap-2">
+ {selectedIds.size > 0 && (
+ <Button
+ variant="secondary"
+ leftIcon={<LuPrinter />}
+ onClick={handlePrintLabels}
+ >
+ <Trans>Print {selectedIds.size} Labels</Trans>
+ </Button>
+ )}
<Combobox
asButton
size="sm"
@@ -337,7 +525,7 @@ const StorageUnitsTable = memo(
/>
</div>
);
- }, [locationId, locations, t]);
+ }, [locationId, locations, t, selectedIds.size, handlePrintLabels]);
const renderContextMenu = useCallback(
(row: StorageUnit) => {
@@ -383,18 +571,92 @@ const StorageUnitsTable = memo(
);
return (
- <Table<StorageUnit>
- count={count}
- columns={columns}
- data={displayRows}
- defaultColumnVisibility={defaultColumnVisibility}
- defaultColumnPinning={defaultColumnPinning}
- primaryAction={actions}
- renderContextMenu={renderContextMenu}
- title={t`Storage Units`}
- table="storageUnit"
- withSavedView
- />
+ <>
+ <Table<StorageUnit>
+ count={count}
+ columns={columns}
+ data={displayRows}
+ defaultColumnVisibility={defaultColumnVisibility}
+ defaultColumnPinning={defaultColumnPinning}
+ primaryAction={actions}
+ renderContextMenu={renderContextMenu}
+ title={t`Storage Units`}
+ table="storageUnit"
+ withSavedView
+ />
+ {printerModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) printerModal.onClose();
+ }}
+ >
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Select Printer</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-1">
+ {printerRoutes.map((route) => (
+ <button
+ type="button"
+ key={route.id}
+ className={`flex items-center gap-3 rounded-lg border p-3 text-left transition-colors ${
+ selectedPrinterId === route.id
+ ? "border-primary bg-primary/5"
+ : "border-border hover:bg-muted"
+ }`}
+ onClick={() => setSelectedPrinterId(route.id)}
+ >
+ <LuPrinter className="size-4 text-muted-foreground shrink-0" />
+ <div className="flex-1 min-w-0">
+ <span className="text-sm font-medium">
+ {route.name}
+ </span>
+ <span className="text-xs text-muted-foreground ml-2 uppercase">
+ {route.format}
+ </span>
+ {route.mediaSizeId && (
+ <span className="text-xs text-muted-foreground ml-2">
+ {route.mediaSizeId}
+ </span>
+ )}
+ </div>
+ {selectedPrinterId === route.id && (
+ <LuCheck className="size-4 text-primary shrink-0" />
+ )}
+ </button>
+ ))}
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <div className="flex gap-2">
+ <Button
+ variant="primary"
+ leftIcon={<LuPrinter />}
+ disabled={!selectedPrinterId || isPrinting}
+ onClick={handleConfirmPrint}
+ >
+ <Trans>Print {selectedIds.size} Labels</Trans>
+ </Button>
+ <Button variant="solid" onClick={printerModal.onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </div>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
+ {downloadModal.isOpen && selectedIds.size > 0 && (
+ <StorageUnitDownloadModal
+ ids={Array.from(selectedIds)}
+ isOpen={downloadModal.isOpen}
+ onClose={downloadModal.onClose}
+ />
+ )}
+ </>
);
}
);
@@ -403,6 +665,30 @@ StorageUnitsTable.displayName = "StorageUnitsTable";
export default StorageUnitsTable;
+function StorageUnitDownloadModal({
+ ids,
+ isOpen,
+ onClose
+}: {
+ ids: string[];
+ isOpen: boolean;
+ onClose: () => void;
+}) {
+ return (
+ <LabelDownloadModal
+ sourceDocumentId=""
+ fileRoutes={{
+ pdf: (_id: string, opts?: { labelSize?: string }) =>
+ path.to.file.storageUnitLabelsPdf(ids, opts),
+ zpl: (_id: string, opts?: { labelSize?: string }) =>
+ path.to.file.storageUnitLabelsZpl(ids, opts)
+ }}
+ isOpen={isOpen}
+ onClose={onClose}
+ />
+ );
+}
+
function getLocationPath(locationId: string) {
return `${path.to.storageUnits}?location=${locationId}`;
}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index 8fccb4e756..449e4c190e 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -20,7 +20,6 @@ import {
ModalFooter,
ModalHeader,
ModalTitle,
- SplitButton,
Tabs,
TabsContent,
TabsList,
@@ -30,7 +29,6 @@ import {
useMount,
VStack
} from "@carbon/react";
-import { labelSizes } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { Fragment, useEffect, useState } from "react";
import {
@@ -38,13 +36,13 @@ import {
LuGitBranch,
LuGitFork,
LuGitMerge,
- LuQrCode,
LuSettings,
LuSquareStack,
LuTriangleAlert
} from "react-icons/lu";
import { RiProgress4Line } from "react-icons/ri";
import { Link, useFetcher, useLocation, useParams } from "react-router";
+import { PrintButton } from "~/components";
import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";
import { Hidden, Item, Submit, useConfigurableItems } from "~/components/Form";
import type { Tree } from "~/components/TreeView";
@@ -181,36 +179,6 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
);
};
- const navigateToTrackingLabels = (
- makeMethodId: string,
- zpl: boolean,
- {
- labelSize,
- trackedEntityId
- }: { labelSize?: string; trackedEntityId?: string } = {}
- ) => {
- if (!window) return;
- if (!makeMethodId) return;
-
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.operationLabelsZpl(makeMethodId, {
- labelSize
- }),
- "_blank"
- );
- } else {
- window.open(
- window.location.origin +
- path.to.file.operationLabelsPdf(makeMethodId, {
- labelSize
- }),
- "_blank"
- );
- }
- };
-
const {
company: { id: companyId }
} = useUser();
@@ -318,22 +286,16 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
{makeMethod &&
(makeMethod.requiresSerialTracking ||
makeMethod.requiresBatchTracking) && (
- <SplitButton
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () =>
- navigateToTrackingLabels(makeMethod.id, !!size.zpl, {
- labelSize: size.id
- })
- }))}
- leftIcon={<LuQrCode />}
- variant="ghost"
- onClick={() =>
- navigateToTrackingLabels(makeMethod.id, false)
- }
- >
- <Trans>Tracking Labels</Trans>
- </SplitButton>
+ <PrintButton
+ sourceDocument="Operation"
+ sourceDocumentId={makeMethod.id}
+ locationId={routeData?.job?.locationId ?? undefined}
+ context="workCenter"
+ fileRoutes={{
+ pdf: path.to.file.operationLabelsPdf,
+ zpl: path.to.file.operationLabelsZpl
+ }}
+ />
)}
</HStack>
</HStack>
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
index 2fd3df945c..49084bd4e4 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
@@ -878,9 +878,10 @@ function NewTrackedEntityAssociation({ items }: { items?: string[] }) {
setTrackedEntities(
data?.map((entity) => ({
- label: entity.readableId ?? entity.id,
- value: entity.id,
- helper: entity.id
+ label: entity.readableId
+ ? `${entity.readableId} — ${entity.id}`
+ : entity.id,
+ value: entity.id
})) ?? []
);
setTrackedEntitiesAreLoading(false);
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx
index bc340cda92..593b4eda3e 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx
@@ -134,9 +134,10 @@ export function MaintenanceAddPartModal({
setSerialOptions(
serials?.map((sn) => ({
- label: sn.id ?? "",
- value: sn.id,
- helper: sn.readableId ? `Serial ${sn.readableId}` : undefined
+ label: sn.readableId
+ ? `${sn.readableId} — ${sn.id}`
+ : (sn.id ?? ""),
+ value: sn.id
})) ?? []
);
}
@@ -151,11 +152,10 @@ export function MaintenanceAddPartModal({
setBatchOptions(
batches?.map((batch) => ({
- label: batch.id ?? "",
+ label: batch.readableId
+ ? `${batch.readableId} — ${batch.id.slice(0, 10)} — ${batch.quantity} available`
+ : `${batch.id.slice(0, 10)} — ${batch.quantity} available`,
value: batch.id,
- helper: batch.readableId
- ? `Batch ${batch.readableId} (${batch.quantity} available)`
- : `${batch.quantity} available`,
quantity: batch.quantity ?? 0
})) ?? []
);
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 31302f1bb6..4aac79fa18 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -184,6 +184,11 @@ export const materialUnitsValidator = z.object({
useMetric: zfd.checkbox()
});
+export {
+ printerRouteValidator,
+ updateAssignmentValidator
+} from "@carbon/printing";
+
export const productLabelSizeValidator = z.object({
productLabelSize: z.enum(
labelSizes.map((size) => size.id) as [string, ...string[]],
diff --git a/apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsx b/apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsx
new file mode 100644
index 0000000000..4bfb6b1b7f
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Printing/AssignmentsCard.tsx
@@ -0,0 +1,337 @@
+import type {
+ ContextAssignment,
+ LocationAssignment,
+ PrinterContext,
+ PrinterRoute,
+ PrintingSettings
+} from "@carbon/printing";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ Combobox,
+ Switch,
+ toast
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ReactNode } from "react";
+import { useCallback, useEffect, useMemo } from "react";
+import {
+ LuHandCoins,
+ LuMapPin,
+ LuPackage,
+ LuTruck,
+ LuWrench
+} from "react-icons/lu";
+import { useFetcher } from "react-router";
+
+type AssignmentUpdate = {
+ locationId: string;
+ context: PrinterContext;
+ contextId?: string;
+ printerRouteId?: string;
+ autoPrint?: boolean;
+};
+
+export function AssignmentsCard({
+ printing,
+ printerRoutes,
+ locations,
+ workCenters
+}: {
+ printing: PrintingSettings | null;
+ printerRoutes: PrinterRoute[];
+ locations: { id: string; name: string }[];
+ workCenters: {
+ id: string | null;
+ name: string | null;
+ locationId: string | null;
+ }[];
+}) {
+ const { t } = useLingui();
+ const assignmentFetcher = useFetcher<{ success: boolean; message: string }>();
+
+ const printerRouteOptions = useMemo(
+ () => [
+ { value: "", label: t`None` },
+ ...printerRoutes.map((r) => ({
+ value: r.id,
+ label: r.name
+ }))
+ ],
+ [printerRoutes, t]
+ );
+
+ const printerRouteMap = useMemo(
+ () => new Map(printerRoutes.map((r) => [r.id, r.name])),
+ [printerRoutes]
+ );
+
+ const workCentersByLocation = useMemo(() => {
+ const map = new Map<string, { id: string; name: string }[]>();
+ for (const wc of workCenters) {
+ if (!wc.id || !wc.name || !wc.locationId) continue;
+ const existing = map.get(wc.locationId) ?? [];
+ existing.push({ id: wc.id, name: wc.name });
+ map.set(wc.locationId, existing);
+ }
+ return map;
+ }, [workCenters]);
+
+ useEffect(() => {
+ if (
+ assignmentFetcher.data?.success === true &&
+ assignmentFetcher.data?.message
+ ) {
+ toast.success(assignmentFetcher.data.message);
+ }
+ if (
+ assignmentFetcher.data?.success === false &&
+ assignmentFetcher.data?.message
+ ) {
+ toast.error(assignmentFetcher.data.message);
+ }
+ }, [assignmentFetcher.data?.message, assignmentFetcher.data?.success]);
+
+ const submitAssignment = useCallback(
+ (data: AssignmentUpdate) => {
+ const formData = new FormData();
+ formData.set("intent", "updateAssignment");
+ formData.set("locationId", data.locationId);
+ formData.set("context", data.context);
+ if (data.contextId) formData.set("contextId", data.contextId);
+ if (data.printerRouteId)
+ formData.set("printerRouteId", data.printerRouteId);
+ if (data.autoPrint) formData.set("autoPrint", "on");
+ assignmentFetcher.submit(formData, { method: "POST" });
+ },
+ [assignmentFetcher]
+ );
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Trans>Assignments</Trans>
+ </CardTitle>
+ <CardDescription>
+ <Trans>
+ Assign printers to locations. Shipping, receiving, and work centers
+ inherit the location default unless overridden.
+ </Trans>
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {locations.length > 0 ? (
+ <div className="flex flex-col">
+ {locations.map((location) => (
+ <LocationSection
+ key={location.id}
+ locationId={location.id}
+ locationName={location.name}
+ assignment={printing?.assignments?.[location.id] ?? null}
+ workCenters={workCentersByLocation.get(location.id) ?? []}
+ printerRouteOptions={printerRouteOptions}
+ printerRouteMap={printerRouteMap}
+ onUpdate={submitAssignment}
+ />
+ ))}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ <Trans>No locations found.</Trans>
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+type AssignmentRowModel = {
+ context: PrinterContext;
+ contextId?: string;
+ label: string;
+ icon: ReactNode;
+ isDefault?: boolean;
+ /** The explicitly stored assignment for this context (not the resolved one) */
+ explicit: ContextAssignment | null;
+};
+
+function LocationSection({
+ locationId,
+ locationName,
+ assignment,
+ workCenters,
+ printerRouteOptions,
+ printerRouteMap,
+ onUpdate
+}: {
+ locationId: string;
+ locationName: string;
+ assignment: LocationAssignment | null;
+ workCenters: { id: string; name: string }[];
+ printerRouteOptions: { value: string; label: string }[];
+ printerRouteMap: Map<string, string>;
+ onUpdate: (data: AssignmentUpdate) => void;
+}) {
+ const defaultPrinterId = assignment?.defaultPrinterRouteId ?? null;
+ const defaultPrinterName = defaultPrinterId
+ ? (printerRouteMap.get(defaultPrinterId) ?? null)
+ : null;
+
+ const rows: AssignmentRowModel[] = [
+ {
+ context: "default",
+ label: locationName,
+ icon: <LuMapPin />,
+ isDefault: true,
+ explicit: assignment
+ ? {
+ printerRouteId: assignment.defaultPrinterRouteId,
+ autoPrint: assignment.defaultAutoPrint
+ }
+ : null
+ },
+ {
+ context: "shipping",
+ label: "Shipping",
+ icon: <LuTruck />,
+ explicit: assignment?.shipping ?? null
+ },
+ {
+ context: "receiving",
+ label: "Receiving",
+ icon: <LuHandCoins />,
+ explicit: assignment?.receiving ?? null
+ },
+ {
+ context: "inventory",
+ label: "Inventory",
+ icon: <LuPackage />,
+ explicit: assignment?.inventory ?? null
+ },
+ ...workCenters.map<AssignmentRowModel>((wc) => ({
+ context: "workCenter",
+ contextId: wc.id,
+ label: wc.name,
+ icon: <LuWrench />,
+ explicit: assignment?.workCenters?.[wc.id] ?? null
+ }))
+ ];
+
+ return (
+ <div className="border-b border-border last:border-b-0">
+ {rows.map((row) => (
+ <AssignmentRow
+ key={row.contextId ?? row.context}
+ label={row.label}
+ icon={row.icon}
+ isBold={row.isDefault}
+ isIndented={!row.isDefault}
+ printerRouteId={row.explicit?.printerRouteId ?? null}
+ inheritedName={row.isDefault ? null : defaultPrinterName}
+ autoPrint={row.explicit?.autoPrint ?? true}
+ printerRouteOptions={printerRouteOptions}
+ onPrinterChange={(printerRouteId) =>
+ onUpdate({
+ locationId,
+ context: row.context,
+ contextId: row.contextId,
+ printerRouteId,
+ autoPrint: printerRouteId
+ ? true
+ : (row.explicit?.autoPrint ?? false)
+ })
+ }
+ onAutoPrintChange={(autoPrint) =>
+ onUpdate({
+ locationId,
+ context: row.context,
+ contextId: row.contextId,
+ printerRouteId: row.explicit?.printerRouteId ?? undefined,
+ autoPrint
+ })
+ }
+ />
+ ))}
+ </div>
+ );
+}
+
+function AssignmentRow({
+ label,
+ icon,
+ isBold,
+ isIndented,
+ printerRouteId,
+ inheritedName,
+ autoPrint,
+ printerRouteOptions,
+ onPrinterChange,
+ onAutoPrintChange
+}: {
+ label: string;
+ icon: ReactNode;
+ isBold?: boolean;
+ isIndented?: boolean;
+ printerRouteId: string | null;
+ inheritedName: string | null;
+ autoPrint: boolean;
+ printerRouteOptions: { value: string; label: string }[];
+ onPrinterChange: (printerRouteId: string) => void;
+ onAutoPrintChange: (autoPrint: boolean) => void;
+}) {
+ const displayState = printerRouteId
+ ? ("assigned" as const)
+ : inheritedName
+ ? ("inherited" as const)
+ : ("missing" as const);
+
+ const placeholder =
+ displayState === "inherited"
+ ? `inherits ${inheritedName}`
+ : displayState === "missing"
+ ? "No printer"
+ : undefined;
+
+ return (
+ <div
+ className={`flex items-center justify-between py-2.5 ${isIndented ? "pl-7" : ""} ${!isBold ? "border-t border-border/50" : ""}`}
+ >
+ <div className="flex items-center gap-2">
+ <div className="size-7 bg-muted rounded-lg flex items-center justify-center shrink-0">
+ <span className="size-4 text-muted-foreground">{icon}</span>
+ </div>
+ <span
+ className={`text-sm ${isBold ? "font-medium" : "text-muted-foreground"}`}
+ >
+ {label}
+ </span>
+ </div>
+
+ <div className="flex items-center gap-4">
+ <div className="w-[320px]">
+ <Combobox
+ size="sm"
+ value={printerRouteId ?? ""}
+ options={printerRouteOptions}
+ onChange={(selected) => onPrinterChange(selected)}
+ isClearable
+ placeholder={placeholder}
+ />
+ </div>
+
+ <div className="flex items-center gap-1.5">
+ <Switch
+ variant="small"
+ checked={autoPrint}
+ onCheckedChange={onAutoPrintChange}
+ />
+ <span className="text-xs text-muted-foreground">Auto-print</span>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx b/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx
new file mode 100644
index 0000000000..76a8c70650
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx
@@ -0,0 +1,480 @@
+import type { PrintJob } from "@carbon/printing";
+import {
+ Badge,
+ Button,
+ HStack,
+ MenuIcon,
+ MenuItem,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle
+} from "@carbon/react";
+import { formatDateTime } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useEffect, useMemo, useState } from "react";
+import {
+ LuCalendar,
+ LuCircleCheck,
+ LuCircleX,
+ LuClock,
+ LuEye,
+ LuFileText,
+ LuLoader,
+ LuPrinter,
+ LuRefreshCw,
+ LuTrash
+} from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { Table } from "~/components";
+
+type PrintJobsTableProps = {
+ jobs: PrintJob[];
+ count: number;
+};
+
+type ViewContent = {
+ content: string;
+ contentType: string;
+ printJobId: string;
+};
+
+const statusConfig: Record<
+ string,
+ {
+ variant: "yellow" | "blue" | "green" | "red" | "purple";
+ icon: React.ReactNode;
+ label: string;
+ }
+> = {
+ generating: {
+ variant: "purple",
+ icon: <LuLoader className="size-3" />,
+ label: "Generating"
+ },
+ queued: {
+ variant: "yellow",
+ icon: <LuClock className="size-3" />,
+ label: "Queued"
+ },
+ printing: {
+ variant: "blue",
+ icon: <LuPrinter className="size-3" />,
+ label: "Printing"
+ },
+ completed: {
+ variant: "green",
+ icon: <LuCircleCheck className="size-3" />,
+ label: "Completed"
+ },
+ failed: {
+ variant: "red",
+ icon: <LuCircleX className="size-3" />,
+ label: "Failed"
+ }
+};
+
+const ExpandedRowContent = memo(({ job }: { job: PrintJob }) => {
+ return (
+ <div className="px-6 py-4">
+ <div className="grid grid-cols-4 gap-4 mb-4 text-sm">
+ <div>
+ <span className="text-muted-foreground">Printer URL</span>
+ <div className="font-mono text-xs break-all">{job.printerUrl}</div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Source Document</span>
+ <div className="font-mono text-xs">
+ {job.sourceDocumentReadableId ?? job.sourceDocumentId}
+ </div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Attempts</span>
+ <div className="font-mono text-xs">{job.attempts}</div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Completed At</span>
+ <div className="font-mono text-xs">
+ {job.completedAt ? formatDateTime(job.completedAt) : "—"}
+ </div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Event ID</span>
+ <div className="font-mono text-xs">{job.id}</div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Created At</span>
+ <div className="font-mono text-xs">
+ {formatDateTime(job.createdAt)}
+ </div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Updated At</span>
+ <div className="font-mono text-xs">
+ {job.updatedAt ? formatDateTime(job.updatedAt) : "—"}
+ </div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Created By</span>
+ <div className="font-mono text-xs">{job.createdBy}</div>
+ </div>
+ </div>
+
+ {job.error && (
+ <div>
+ <h4 className="text-sm font-medium mb-2">Error</h4>
+ <pre className="text-xs font-mono bg-red-500/10 text-red-500 p-3 rounded-md whitespace-pre-wrap">
+ {job.error}
+ </pre>
+ </div>
+ )}
+ </div>
+ );
+});
+ExpandedRowContent.displayName = "ExpandedRowContent";
+
+function parseZplDimensions(zplContent: string) {
+ const pwMatch = zplContent.match(/\^PW(\d+)/);
+ const llMatch = zplContent.match(/\^LL(\d+)/);
+ const dpi = 203;
+ const dpmm = Math.round(dpi / 25.4);
+
+ const widthInches = pwMatch
+ ? Math.max(0.5, Math.round((Number(pwMatch[1]) / dpi) * 10) / 10)
+ : 2;
+ const heightInches = llMatch
+ ? Math.max(0.5, Math.round((Number(llMatch[1]) / dpi) * 10) / 10)
+ : 1;
+
+ return { dpmm, width: widthInches, height: heightInches };
+}
+
+function ZplPreview({ zpl }: { zpl: string }) {
+ const { t } = useLingui();
+ const [imageUrl, setImageUrl] = useState<string | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let revoked = false;
+ let objectUrl: string | null = null;
+ const { dpmm, width, height } = parseZplDimensions(zpl);
+
+ fetch(
+ `https://api.labelary.com/v1/printers/${dpmm}dpmm/labels/${width}x${height}/0/`,
+ {
+ method: "POST",
+ headers: {
+ Accept: "image/png",
+ "Content-Type": "application/x-www-form-urlencoded"
+ },
+ body: zpl
+ }
+ )
+ .then((res) => {
+ if (!res.ok) throw new Error(`Labelary returned ${res.status}`);
+ return res.blob();
+ })
+ .then((blob) => {
+ if (revoked) return;
+ objectUrl = URL.createObjectURL(blob);
+ setImageUrl(objectUrl);
+ setLoading(false);
+ })
+ .catch((err) => {
+ if (revoked) return;
+ setError(err.message);
+ setLoading(false);
+ });
+
+ return () => {
+ revoked = true;
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
+ };
+ }, [zpl]);
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center p-8 text-sm text-muted-foreground">
+ <Trans>Rendering label preview...</Trans>
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <div className="flex flex-col gap-2">
+ <p className="text-sm text-destructive">
+ <Trans>Preview failed: {error}</Trans>
+ </p>
+ <pre className="text-xs font-mono bg-muted p-4 rounded-md overflow-auto whitespace-pre-wrap break-all max-h-[40vh]">
+ {zpl}
+ </pre>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-3">
+ <img
+ src={imageUrl!}
+ alt={t`ZPL Label Preview`}
+ className="border border-border rounded-md max-h-[350px] object-contain self-start"
+ />
+ <pre className="text-xs font-mono bg-muted p-4 rounded-md overflow-auto whitespace-pre-wrap break-all max-h-[30vh]">
+ {zpl}
+ </pre>
+ </div>
+ );
+}
+
+const PrintJobsTable = memo(({ jobs, count }: PrintJobsTableProps) => {
+ const { t } = useLingui();
+ const fetcher = useFetcher<{
+ success: boolean;
+ message?: string;
+ content?: string;
+ contentType?: string;
+ printJobId?: string;
+ }>();
+ const [viewContent, setViewContent] = useState<ViewContent | null>(null);
+
+ useEffect(() => {
+ if (fetcher.data && "content" in fetcher.data && fetcher.data.content) {
+ setViewContent({
+ content: fetcher.data.content,
+ contentType: fetcher.data.contentType as string,
+ printJobId: fetcher.data.printJobId as string
+ });
+ }
+ }, [fetcher.data]);
+
+ const columns = useMemo<ColumnDef<PrintJob>[]>(
+ () => [
+ {
+ accessorKey: "status",
+ header: t`Status`,
+ cell: ({ row }) => {
+ const config = statusConfig[row.original.status];
+ return (
+ <Badge
+ variant={config?.variant ?? "secondary"}
+ className="shrink-0"
+ >
+ <HStack className="gap-1">
+ {config?.icon}
+ <span>{config?.label ?? row.original.status}</span>
+ </HStack>
+ </Badge>
+ );
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { label: "Generating", value: "generating" },
+ { label: "Queued", value: "queued" },
+ { label: "Printing", value: "printing" },
+ { label: "Completed", value: "completed" },
+ { label: "Failed", value: "failed" }
+ ]
+ }
+ }
+ },
+ {
+ accessorKey: "description",
+ header: t`Description`,
+ cell: ({ row }) => (
+ <div className="max-w-[300px] truncate font-medium">
+ {row.original.description}
+ </div>
+ ),
+ meta: {
+ icon: <LuFileText />
+ }
+ },
+ {
+ accessorKey: "sourceDocument",
+ header: t`Source`,
+ cell: ({ row }) => (
+ <span className="text-sm text-muted-foreground">
+ {row.original.sourceDocument}
+ </span>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { label: "Receipt", value: "receipt" },
+ { label: "Shipment", value: "shipment" },
+ { label: "Operation", value: "operation" },
+ { label: "Job", value: "job" },
+ { label: "Item", value: "item" },
+ { label: "Kanban", value: "kanban" },
+ { label: "Split", value: "split" }
+ ]
+ }
+ }
+ },
+ {
+ accessorKey: "contentType",
+ header: t`Type`,
+ cell: ({ row }) => (
+ <span className="font-mono text-xs uppercase text-muted-foreground">
+ {row.original.contentType ?? "—"}
+ </span>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { label: "ZPL", value: "zpl" },
+ { label: "PDF", value: "pdf" }
+ ]
+ }
+ }
+ },
+ {
+ accessorKey: "origin",
+ header: t`Origin`,
+ cell: ({ row }) => (
+ <span className="text-sm text-muted-foreground capitalize">
+ {row.original.origin}
+ </span>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { label: "Auto", value: "auto" },
+ { label: "Manual", value: "manual" },
+ { label: "Reprint", value: "reprint" }
+ ]
+ }
+ }
+ },
+ {
+ accessorKey: "createdAt",
+ header: t`When`,
+ cell: ({ row }) => (
+ <span className="text-sm text-muted-foreground">
+ {formatDateTime(row.original.createdAt)}
+ </span>
+ ),
+ meta: {
+ icon: <LuCalendar />
+ }
+ }
+ ],
+ [t]
+ );
+
+ const renderExpandedRow = useCallback(
+ (job: PrintJob) => <ExpandedRowContent job={job} />,
+ []
+ );
+
+ const renderContextMenu = useCallback(
+ (job: PrintJob) => (
+ <>
+ <MenuItem
+ disabled={job.status === "generating"}
+ onClick={() => {
+ fetcher.submit(
+ { intent: "viewContent", printJobId: job.id },
+ { method: "post" }
+ );
+ }}
+ >
+ <MenuIcon icon={<LuEye />} />
+ <Trans>View</Trans>
+ </MenuItem>
+ <MenuItem
+ disabled={job.status === "generating"}
+ onClick={() => {
+ fetcher.submit(
+ {
+ intent: "reprint",
+ printJobId: job.id,
+ printerUrl: job.printerUrl
+ },
+ { method: "post" }
+ );
+ }}
+ >
+ <MenuIcon icon={<LuRefreshCw />} />
+ <Trans>Reprint</Trans>
+ </MenuItem>
+ <MenuItem
+ destructive
+ onClick={() => {
+ fetcher.submit(
+ { intent: "delete", printJobId: job.id },
+ { method: "post" }
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ <Trans>Delete</Trans>
+ </MenuItem>
+ </>
+ ),
+ [fetcher]
+ );
+
+ return (
+ <>
+ <Table
+ data={jobs}
+ columns={columns}
+ count={count}
+ title={t`Print Jobs`}
+ table="printJob"
+ withSearch
+ withPagination
+ renderExpandedRow={renderExpandedRow}
+ renderContextMenu={renderContextMenu}
+ />
+ {viewContent && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) setViewContent(null);
+ }}
+ >
+ <ModalContent size="large">
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>
+ Print Output ({viewContent.contentType?.toUpperCase()})
+ </Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ {viewContent.contentType === "zpl" ? (
+ <ZplPreview zpl={viewContent.content} />
+ ) : viewContent.contentType === "pdf" ? (
+ <iframe
+ src={`data:application/pdf;base64,${viewContent.content}`}
+ className="w-full h-[60vh] border border-border rounded-md"
+ title={t`PDF Preview`}
+ />
+ ) : null}
+ </ModalBody>
+ <ModalFooter>
+ <Button variant="secondary" onClick={() => setViewContent(null)}>
+ <Trans>Close</Trans>
+ </Button>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
+ </>
+ );
+});
+
+PrintJobsTable.displayName = "PrintJobsTable";
+export default PrintJobsTable;
diff --git a/apps/erp/app/modules/settings/ui/Printing/PrintersCard.tsx b/apps/erp/app/modules/settings/ui/Printing/PrintersCard.tsx
new file mode 100644
index 0000000000..2764799ad2
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Printing/PrintersCard.tsx
@@ -0,0 +1,284 @@
+import { Input, Select, Submit, ValidatedForm } from "@carbon/form";
+import type { PrinterRoute } from "@carbon/printing";
+import { printerRouteValidator } from "@carbon/printing";
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ toast,
+ useDisclosure
+} from "@carbon/react";
+import { getLabelSizeLabel, labelSizes } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useEffect, useMemo, useState } from "react";
+import { LuEllipsisVertical, LuPlay, LuPlus, LuTrash } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { Empty } from "~/components";
+import ConfirmDelete from "~/components/Modals/ConfirmDelete";
+import { path } from "~/utils/path";
+
+function getMediaSizeLabel(mediaSizeId: string): string {
+ const size = labelSizes.find((s) => s.id === mediaSizeId);
+ return size ? getLabelSizeLabel(size) : mediaSizeId;
+}
+
+export function PrintersCard({
+ printerRoutes
+}: {
+ printerRoutes: PrinterRoute[];
+}) {
+ const { t } = useLingui();
+ const routeFetcher = useFetcher<{ success: boolean; message: string }>();
+
+ const formatOptions = [
+ { value: "zpl", label: t`ZPL (Thermal Label)` },
+ { value: "pdf", label: t`PDF (Document)` }
+ ];
+
+ const newPrinterDisclosure = useDisclosure();
+ const deletePrinterDisclosure = useDisclosure();
+ const [printerToDelete, setPrinterToDelete] = useState<{
+ id: string;
+ name: string;
+ } | null>(null);
+
+ // ZPL printers can only print thermal sizes; PDF printers can print any size
+ const [selectedFormat, setSelectedFormat] = useState<"zpl" | "pdf">("zpl");
+ const mediaSizeOptions = useMemo(
+ () =>
+ labelSizes
+ .filter((s) => (selectedFormat === "zpl" ? Boolean(s.zpl) : true))
+ .map((s) => ({ value: s.id, label: getLabelSizeLabel(s) })),
+ [selectedFormat]
+ );
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: we don't need to re-run this effect when onClose changes
+ useEffect(() => {
+ if (routeFetcher.data?.success === true && routeFetcher.data?.message) {
+ toast.success(routeFetcher.data.message);
+ newPrinterDisclosure.onClose();
+ }
+ if (routeFetcher.data?.success === false && routeFetcher.data?.message) {
+ toast.error(routeFetcher.data.message);
+ }
+ }, [routeFetcher.data?.message, routeFetcher.data?.success]);
+
+ return (
+ <>
+ <Card>
+ <HStack className="w-full justify-between items-start">
+ <CardHeader>
+ <CardTitle>
+ <Trans>Printers</Trans>
+ </CardTitle>
+ <CardDescription>
+ <Trans>Physical printers available for assignment.</Trans>
+ </CardDescription>
+ </CardHeader>
+ <CardAction className="py-6">
+ <Button
+ leftIcon={<LuPlus />}
+ onClick={() => {
+ setSelectedFormat("zpl");
+ newPrinterDisclosure.onOpen();
+ }}
+ >
+ <Trans>Add Printer</Trans>
+ </Button>
+ </CardAction>
+ </HStack>
+ <CardContent>
+ {printerRoutes.length > 0 ? (
+ <div className="flex flex-col gap-2">
+ {printerRoutes.map((route) => (
+ <div
+ key={route.id}
+ className="flex items-center justify-between rounded-lg border border-border p-3"
+ >
+ <div className="flex items-center gap-3 min-w-0">
+ <span className="text-sm font-medium">{route.name}</span>
+ <span className="text-xs text-muted-foreground uppercase">
+ {route.format}
+ </span>
+ {route.mediaSizeId && (
+ <span className="text-xs text-muted-foreground">
+ {getMediaSizeLabel(route.mediaSizeId)}
+ </span>
+ )}
+ <span className="text-xs text-muted-foreground font-mono truncate max-w-[300px]">
+ {route.printerUrl}
+ </span>
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label={t`More`}
+ icon={<LuEllipsisVertical />}
+ variant="ghost"
+ size="sm"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ onSelect={() =>
+ routeFetcher.submit(
+ { intent: "testPrint", routeId: route.id },
+ { method: "POST" }
+ )
+ }
+ >
+ <DropdownMenuIcon icon={<LuPlay />} />
+ <Trans>Test</Trans>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ destructive
+ onSelect={() => {
+ setPrinterToDelete({
+ id: route.id,
+ name: route.name
+ });
+ deletePrinterDisclosure.onOpen();
+ }}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ <Trans>Delete</Trans>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <Empty>
+ <p className="text-sm text-muted-foreground mt-10">
+ <Trans>
+ No printers configured. Click "Add Printer" to create one.
+ </Trans>
+ </p>
+ </Empty>
+ )}
+ </CardContent>
+ </Card>
+
+ {newPrinterDisclosure.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) newPrinterDisclosure.onClose();
+ }}
+ >
+ <ModalContent size="large">
+ <ValidatedForm
+ method="post"
+ validator={printerRouteValidator}
+ fetcher={routeFetcher}
+ defaultValues={{ format: "zpl" }}
+ className="flex flex-col h-full"
+ >
+ <input type="hidden" name="intent" value="upsertRoute" />
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Add Printer</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-4">
+ <div className="grid grid-cols-1 gap-4">
+ <Input
+ name="name"
+ label={t`Name`}
+ placeholder={t`e.g. Zebra 2x1`}
+ />
+ <Select
+ name="format"
+ label={t`Format`}
+ options={formatOptions}
+ onChange={(option) => {
+ if (
+ option?.value === "zpl" ||
+ option?.value === "pdf"
+ ) {
+ setSelectedFormat(option.value);
+ }
+ }}
+ />
+
+ <Select
+ name="mediaSizeId"
+ label={t`Media Size`}
+ options={mediaSizeOptions}
+ />
+ <Input
+ name="templateId"
+ label={t`Template ID`}
+ placeholder={t`Leave blank for built-in`}
+ />
+
+ <Input
+ name="printerUrl"
+ label={t`Printer URL`}
+ placeholder="https://pbx-XXXX.pbxz.cloud/api/v1/print/..."
+ />
+ <Input
+ name="apiKey"
+ label={t`API Key`}
+ placeholder={t`Optional`}
+ />
+ </div>
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <HStack>
+ <Button
+ size="md"
+ variant="solid"
+ onClick={newPrinterDisclosure.onClose}
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Submit>
+ <Trans>Add Printer</Trans>
+ </Submit>
+ </HStack>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+
+ {deletePrinterDisclosure.isOpen && printerToDelete && (
+ <ConfirmDelete
+ action={path.to.deletePrinterRoute(printerToDelete.id)}
+ isOpen={deletePrinterDisclosure.isOpen}
+ name={printerToDelete.name}
+ text={t`Are you sure you want to delete the printer "${printerToDelete.name}"? Any assignments referencing this printer will be cleared. This cannot be undone.`}
+ onCancel={() => {
+ deletePrinterDisclosure.onClose();
+ setPrinterToDelete(null);
+ }}
+ onSubmit={() => {
+ deletePrinterDisclosure.onClose();
+ setPrinterToDelete(null);
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/erp/app/modules/settings/ui/Printing/index.ts b/apps/erp/app/modules/settings/ui/Printing/index.ts
new file mode 100644
index 0000000000..550d3a8e51
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Printing/index.ts
@@ -0,0 +1,3 @@
+export { AssignmentsCard } from "./AssignmentsCard";
+export { PrintersCard } from "./PrintersCard";
+export { default as PrintJobsTable } from "./PrintJobsTable";
diff --git a/apps/erp/app/modules/settings/ui/index.ts b/apps/erp/app/modules/settings/ui/index.ts
index 9040ab9d35..5b7066eb11 100644
--- a/apps/erp/app/modules/settings/ui/index.ts
+++ b/apps/erp/app/modules/settings/ui/index.ts
@@ -7,6 +7,7 @@ export * from "./Companies";
export * from "./Company";
export * from "./CustomFields";
export * from "./Integrations";
+export * from "./Printing";
export * from "./Sequences";
export * from "./Theme";
export { useSettingsSubmodules };
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index 82cd6fa1b4..f5ab991a7d 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -1,7 +1,6 @@
import { useLingui } from "@lingui/react/macro";
import { useMemo } from "react";
import {
- LuBarcode,
LuBox,
LuCircleCheck,
LuClipboardCheck,
@@ -14,6 +13,7 @@ import {
LuLandmark,
LuLayoutDashboard,
LuNetwork,
+ LuPrinter,
LuSheet,
LuShoppingCart,
LuSquareStack,
@@ -42,6 +42,14 @@ export default function useSettingsSubmodules() {
{
name: t`Company`,
routes: [
+ {
+ name: t`Billing`,
+ to: path.to.billing,
+ role: "employee",
+ icon: <LuCreditCard />,
+ requiresOwnership: true,
+ requiresCloudEnvironment: true
+ },
{
name: t`Company`,
to: path.to.company,
@@ -54,25 +62,17 @@ export default function useSettingsSubmodules() {
role: "employee",
icon: <LuNetwork />
},
- {
- name: t`Billing`,
- to: path.to.billing,
- role: "employee",
- icon: <LuCreditCard />,
- requiresOwnership: true,
- requiresCloudEnvironment: true
- },
- {
- name: t`Labels`,
- to: path.to.labelsSettings,
- role: "employee",
- icon: <LuBarcode />
- },
{
name: t`Logos`,
to: path.to.logos,
role: "employee",
icon: <LuImage />
+ },
+ {
+ name: t`Printing`,
+ to: path.to.printingSettings,
+ role: "employee",
+ icon: <LuPrinter />
}
]
},
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 09ad34d856..492267dbbd 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-06-09T18:06:44.043Z",
+ "generated": "2026-06-11T15:16:25.602Z",
"totalTools": 1181,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
index ce13ee556d..fa7251b9be 100644
--- a/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
@@ -3,9 +3,7 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect } from "react-router";
import { getCompany } from "~/modules/settings";
-import { path } from "~/utils/path";
import { getEntityLabelData } from "./labels.server";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -31,7 +29,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 || "avery5160";
+ labelParam || companySettings?.data?.productLabelSize || "avery5163";
const labelSize = labelSizes.find((size) => size.id === labelSizeId);
@@ -39,12 +37,6 @@ 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 stream = await renderToStream(
<ProductLabelPDF items={[labelItem!]} labelSize={labelSize} />
);
diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
index 10286c4206..f73a553d37 100644
--- a/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
@@ -23,7 +23,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 || "zebra2x1";
+ labelParam || companySettings?.data?.productLabelSize || "label2x1";
const labelSize = labelSizes.find((size) => size.id === labelSizeId);
diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
index aaf1e93651..47e67f3a31 100644
--- a/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
@@ -3,11 +3,9 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect } from "react-router";
import { getTrackedEntitiesByMakeMethodId } from "~/modules/inventory";
import { getCompany } from "~/modules/settings";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {});
@@ -26,12 +24,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Failed to load company");
}
- // Get the label size from query params or default to avery5160
+ // Get the label size from query params or default to avery5163
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const trackedEntityIdParam = url.searchParams.get("trackedEntityId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "avery5160";
+ labelParam || companySettings.data?.productLabelSize || "avery5163";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
@@ -40,15 +38,6 @@ 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
diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
index 5d4b3d2337..7a6ac8e980 100644
--- a/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
@@ -19,12 +19,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getTrackedEntitiesByMakeMethodId(client, id)
]);
- // Get the label size from query params or default to zebra2x1
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const trackedEntityIdParam = url.searchParams.get("trackedEntityId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "zebra2x1";
+ labelParam || companySettings.data?.productLabelSize || "label2x1";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
index 8dd4de7e87..137f1e01b5 100644
--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
@@ -4,11 +4,9 @@ import type { TrackedEntityAttributes } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect } from "react-router";
import { getReceiptTracking } from "~/modules/inventory";
import { getCompany } from "~/modules/settings";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -29,12 +27,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Failed to load company");
}
- // Get the label size from query params or default to avery5160
+ // Get the label size from query params or default to avery5163
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const lineIdParam = url.searchParams.get("lineId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "avery5160";
+ labelParam || companySettings.data?.productLabelSize || "avery5163";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
@@ -43,15 +41,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Invalid label size");
}
- if (labelSize.zpl) {
- throw redirect(
- path.to.file.receiptLabelsZpl(id, {
- labelSize: labelSize.id,
- lineId: lineIdParam ?? undefined
- })
- );
- }
-
let filteredTracking = receiptLineTracking.data;
// Filter by lineId if provided
diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
index 3215b950f6..69a12e3b88 100644
--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
@@ -21,12 +21,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getReceiptTracking(client, id, companyId)
]);
- // Get the label size from query params or default to zebra2x1
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const lineIdParam = url.searchParams.get("lineId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "zebra2x1";
+ labelParam || companySettings.data?.productLabelSize || "label2x1";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
index 64ffef40ea..972078000a 100644
--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
@@ -4,11 +4,9 @@ import type { TrackedEntityAttributes } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect } from "react-router";
import { getShipmentTracking } from "~/modules/inventory";
import { getCompany } from "~/modules/settings";
import { getCompanySettings } from "~/modules/settings/settings.service";
-import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
@@ -29,12 +27,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Failed to load company");
}
- // Get the label size from query params or default to avery5160
+ // Get the label size from query params or default to avery5163
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const lineIdParam = url.searchParams.get("lineId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "avery5160";
+ labelParam || companySettings.data?.productLabelSize || "avery5163";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
@@ -43,15 +41,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
throw new Error("Invalid label size");
}
- if (labelSize.zpl) {
- throw redirect(
- path.to.file.shipmentLabelsZpl(id, {
- labelSize: labelSize.id,
- lineId: lineIdParam ?? undefined
- })
- );
- }
-
let filteredTracking = shipmentTracking.data;
// Filter by lineId if provided
diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
index c455684a19..3b4b480df0 100644
--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
@@ -21,12 +21,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getShipmentTracking(client, id, companyId)
]);
- // Get the label size from query params or default to zebra2x1
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const lineIdParam = url.searchParams.get("lineId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "zebra2x1";
+ labelParam || companySettings.data?.productLabelSize || "label2x1";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
diff --git a/apps/erp/app/routes/file+/stock-transfer+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/stock-transfer+/$id.labels[.]pdf.tsx
new file mode 100644
index 0000000000..4f52cb3d6c
--- /dev/null
+++ b/apps/erp/app/routes/file+/stock-transfer+/$id.labels[.]pdf.tsx
@@ -0,0 +1,69 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+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 "~/modules/settings/settings.service";
+import { getStockTransferLabelItems } from "./labels.server";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "inventory"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const url = new URL(request.url);
+ const labelParam = url.searchParams.get("labelSize");
+ const lineIdParam = url.searchParams.get("lineId");
+
+ const companySettings = await getCompanySettings(client, companyId);
+ const labelSizeId =
+ labelParam || companySettings.data?.productLabelSize || "avery5163";
+
+ const labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ throw new Error("Invalid label size");
+ }
+
+ const items = await getStockTransferLabelItems(
+ client,
+ companyId,
+ id,
+ lineIdParam ?? undefined
+ );
+
+ if (items.length === 0) {
+ return new Response(
+ `No tracked items found for stock transfer ${id}${
+ lineIdParam ? ` and line ${lineIdParam}` : ""
+ }`,
+ { status: 404 }
+ );
+ }
+
+ const stream = await renderToStream(
+ <ProductLabelPDF items={items} labelSize={labelSize} />
+ );
+
+ 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",
+ "Content-Disposition": `inline; filename="Stock Transfer Labels.pdf"`
+ }
+ });
+}
diff --git a/apps/erp/app/routes/file+/stock-transfer+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/stock-transfer+/$id.labels[.]zpl.tsx
new file mode 100644
index 0000000000..4b14e17862
--- /dev/null
+++ b/apps/erp/app/routes/file+/stock-transfer+/$id.labels[.]zpl.tsx
@@ -0,0 +1,68 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+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 "~/modules/settings/settings.service";
+import { path } from "~/utils/path";
+import { getStockTransferLabelItems } from "./labels.server";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "inventory"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const url = new URL(request.url);
+ const labelParam = url.searchParams.get("labelSize");
+ const lineIdParam = url.searchParams.get("lineId");
+
+ const companySettings = await getCompanySettings(client, companyId);
+ const labelSizeId =
+ labelParam || companySettings.data?.productLabelSize || "label2x1";
+
+ const labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ throw new Error("Invalid label size");
+ }
+
+ if (!labelSize.zpl) {
+ throw redirect(
+ path.to.file.stockTransferLabelsPdf(id, {
+ labelSize: labelSize.id,
+ lineId: lineIdParam ?? undefined
+ })
+ );
+ }
+
+ const items = await getStockTransferLabelItems(
+ client,
+ companyId,
+ id,
+ lineIdParam ?? undefined
+ );
+
+ if (items.length === 0) {
+ return new Response(
+ `No tracked items found for stock transfer ${id}${
+ lineIdParam ? ` and line ${lineIdParam}` : ""
+ }`,
+ { status: 404 }
+ );
+ }
+
+ const zplOutput = items
+ .map((item) => generateProductLabelZPL(item, labelSize))
+ .join("\n");
+
+ return new Response(zplOutput, {
+ status: 200,
+ headers: {
+ "Content-Type": "application/zpl",
+ "Content-Disposition": `attachment; filename="labels-${id}.zpl"`
+ }
+ });
+}
diff --git a/apps/erp/app/routes/file+/stock-transfer+/labels.server.ts b/apps/erp/app/routes/file+/stock-transfer+/labels.server.ts
new file mode 100644
index 0000000000..27d9c9b7f8
--- /dev/null
+++ b/apps/erp/app/routes/file+/stock-transfer+/labels.server.ts
@@ -0,0 +1,73 @@
+import type { Database } from "@carbon/database";
+import type { ProductLabelItem } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+export async function getStockTransferLabelItems(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ stockTransferId: string,
+ lineId?: string
+): Promise<ProductLabelItem[]> {
+ let query = client
+ .from("stockTransferLine")
+ .select("id, trackedEntityId")
+ .eq("stockTransferId", stockTransferId)
+ .not("trackedEntityId", "is", null);
+
+ if (lineId) {
+ query = query.eq("id", lineId);
+ }
+
+ const { data: lines } = await query;
+
+ const entityIds = [
+ ...new Set(
+ (lines ?? [])
+ .map((l) => l.trackedEntityId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+
+ if (entityIds.length === 0) return [];
+
+ const { data: trackedEntities } = await client
+ .from("trackedEntity")
+ .select("*")
+ .in("id", entityIds)
+ .eq("companyId", companyId);
+
+ const itemIds = [
+ ...new Set(
+ (trackedEntities ?? [])
+ .map((e) => e.sourceDocumentId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+
+ const { data: items } = await client
+ .from("item")
+ .select("id, itemTrackingType")
+ .in("id", itemIds);
+
+ const trackingTypeByItemId = new Map(
+ items?.map((i) => [i.id, i.itemTrackingType]) ?? []
+ );
+
+ return (trackedEntities ?? [])
+ .map((entity) => ({
+ itemId: entity.sourceDocumentReadableId ?? "",
+ revision: "0",
+ number: entity.readableId ?? "",
+ trackedEntityId: entity.id,
+ quantity: entity.quantity,
+ trackingType:
+ trackingTypeByItemId.get(entity.sourceDocumentId ?? "") ??
+ (entity.quantity > 1 ? "Batch" : "Serial")
+ }))
+ .sort((a, b) => {
+ if (a.itemId === b.itemId) {
+ return a.number.localeCompare(b.number);
+ }
+ return a.itemId.localeCompare(b.itemId);
+ });
+}
diff --git a/apps/erp/app/routes/file+/storage-unit+/labels[.]pdf.tsx b/apps/erp/app/routes/file+/storage-unit+/labels[.]pdf.tsx
new file mode 100644
index 0000000000..19315b19b5
--- /dev/null
+++ b/apps/erp/app/routes/file+/storage-unit+/labels[.]pdf.tsx
@@ -0,0 +1,65 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { StorageUnitLabelPDF } from "@carbon/documents/pdf";
+import { labelSizes } from "@carbon/utils";
+import { renderToStream } from "@react-pdf/renderer";
+import type { LoaderFunctionArgs } from "react-router";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory"
+ });
+
+ const url = new URL(request.url);
+ const idsParam = url.searchParams.get("ids");
+
+ if (!idsParam) {
+ return new Response("No storage unit IDs provided", { status: 400 });
+ }
+
+ const ids = idsParam
+ .split(",")
+ .map((id) => id.trim())
+ .filter(Boolean);
+ if (ids.length === 0) {
+ return new Response("No valid storage unit IDs provided", { status: 400 });
+ }
+
+ const labelSizeId = url.searchParams.get("labelSize") ?? "avery5163";
+ const labelSize = labelSizes.find((s) => s.id === labelSizeId);
+
+ if (!labelSize) {
+ return new Response(`Invalid label size: ${labelSizeId}`, { status: 400 });
+ }
+
+ const { data: units, error } = await client
+ .from("storageUnit")
+ .select("id, name")
+ .in("id", ids);
+
+ if (error || !units?.length) {
+ return new Response("No storage units found", { status: 404 });
+ }
+
+ const stream = await renderToStream(
+ <StorageUnitLabelPDF items={units} labelSize={labelSize} />
+ );
+
+ const body: Buffer = await new Promise((resolve, reject) => {
+ const buffers: Uint8Array[] = [];
+ stream.on("data", (data: Uint8Array) => {
+ 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",
+ "Content-Disposition": `attachment; filename="storage-unit-labels.pdf"`
+ }
+ });
+}
diff --git a/apps/erp/app/routes/file+/storage-unit+/labels[.]zpl.tsx b/apps/erp/app/routes/file+/storage-unit+/labels[.]zpl.tsx
new file mode 100644
index 0000000000..a755778766
--- /dev/null
+++ b/apps/erp/app/routes/file+/storage-unit+/labels[.]zpl.tsx
@@ -0,0 +1,55 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { generateStorageUnitLabelZPL } from "@carbon/documents/zpl";
+import { labelSizes } from "@carbon/utils";
+import type { LoaderFunctionArgs } from "react-router";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory"
+ });
+
+ const url = new URL(request.url);
+ const idsParam = url.searchParams.get("ids");
+
+ if (!idsParam) {
+ return new Response("No storage unit IDs provided", { status: 400 });
+ }
+
+ const ids = idsParam
+ .split(",")
+ .map((id) => id.trim())
+ .filter(Boolean);
+ if (ids.length === 0) {
+ return new Response("No valid storage unit IDs provided", { status: 400 });
+ }
+
+ const labelSizeId = url.searchParams.get("labelSize") ?? "label2x1";
+ const labelSize = labelSizes.find((s) => s.id === labelSizeId);
+
+ if (!labelSize?.zpl) {
+ return new Response(`Label size ${labelSizeId} does not support ZPL`, {
+ status: 400
+ });
+ }
+
+ const { data: units, error } = await client
+ .from("storageUnit")
+ .select("id, name")
+ .in("id", ids);
+
+ if (error || !units?.length) {
+ return new Response("No storage units found", { status: 404 });
+ }
+
+ const zplOutput = units
+ .map((unit) => generateStorageUnitLabelZPL(unit, labelSize))
+ .join("\n");
+
+ return new Response(zplOutput, {
+ status: 200,
+ headers: {
+ "Content-Type": "application/zpl",
+ "Content-Disposition": `attachment; filename="storage-unit-labels.zpl"`
+ }
+ });
+}
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index fc7f454922..f7fa53cda4 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -12,6 +12,9 @@ import {
updateCompanySession
} from "@carbon/auth/session.server";
import { isAuditLogEnabled } from "@carbon/database/audit";
+import type { PrintingSettings } from "@carbon/printing";
+import { getPrinterRoutes } from "@carbon/printing";
+import { PrintingProvider } from "@carbon/printing/ui";
import {
ItarPopup,
TooltipProvider,
@@ -113,7 +116,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
groups,
defaults,
auditLogEnabled,
- modulePreferences
+ modulePreferences,
+ printerRoutes
] = await Promise.all([
getCompanies(client, userId),
getEmployeeCompanies(client, userId),
@@ -127,7 +131,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
getUserGroups(client, userId),
getUserDefaults(client, userId, companyId),
isAuditLogEnabled(client, companyId),
- getModulePreferences(client, userId, companyId)
+ getModulePreferences(client, userId, companyId),
+ getPrinterRoutes(client, companyId)
]);
if (!claims || user.error || !user.data || !groups.data) {
@@ -203,6 +208,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
user: user.data,
modulePreferences: modulePreferences.data ?? [],
savedViews: savedViews.data ?? [],
+ printerRoutes: printerRoutes.data ?? [],
supplierApprovalRequired: isApprovalRequired(client, "supplier", companyId),
openClockEntry: companySettings.data?.timeCardEnabled
? getOpenClockEntry(client, userId, companyId)
@@ -211,7 +217,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function AuthenticatedRoute() {
- const { session, user, companySettings, openClockEntry } =
+ const { session, user, companySettings, openClockEntry, printerRoutes } =
useLoaderData<typeof loader>();
const navigate = useNavigate();
const { isOpen, training, dismiss } = useTrainingPanel();
@@ -247,42 +253,53 @@ export default function AuthenticatedRoute() {
/>
) : (
<CarbonProvider session={session}>
- <RealtimeDataProvider>
- <TooltipProvider>
- <div className="flex flex-col h-screen">
- <Topbar />
- <div className="flex flex-1 h-[calc(100vh-49px)] relative">
- <PrimaryNavigation />
- <main className="flex-1 overflow-y-auto scrollbar-hide border-l border-t bg-muted sm:rounded-tl-2xl relative z-10">
- <Outlet />
- </main>
+ <PrintingProvider
+ value={{
+ printing:
+ (companySettings?.printing as PrintingSettings | null) ?? null,
+ printerRoutes,
+ useMetric: Boolean(companySettings?.useMetric),
+ printPath: path.to.manualPrint,
+ settingsPath: path.to.printingSettings
+ }}
+ >
+ <RealtimeDataProvider>
+ <TooltipProvider>
+ <div className="flex flex-col h-screen">
+ <Topbar />
+ <div className="flex flex-1 h-[calc(100vh-49px)] relative">
+ <PrimaryNavigation />
+ <main className="flex-1 overflow-y-auto scrollbar-hide border-l border-t bg-muted sm:rounded-tl-2xl relative z-10">
+ <Outlet />
+ </main>
+ </div>
</div>
- </div>
- <TrainingPanel
- training={training}
- isOpen={isOpen}
- onDismiss={dismiss}
- />
- {companySettings?.timeCardEnabled && (
- <Suspense fallback={null}>
- <Await resolve={openClockEntry}>
- {(resolved) => (
- <TimeCardWarning
- openClockEntry={
- resolved?.data
- ? {
- id: resolved.data.id,
- clockIn: resolved.data.clockIn
- }
- : null
- }
- />
- )}
- </Await>
- </Suspense>
- )}
- </TooltipProvider>
- </RealtimeDataProvider>
+ <TrainingPanel
+ training={training}
+ isOpen={isOpen}
+ onDismiss={dismiss}
+ />
+ {companySettings?.timeCardEnabled && (
+ <Suspense fallback={null}>
+ <Await resolve={openClockEntry}>
+ {(resolved) => (
+ <TimeCardWarning
+ openClockEntry={
+ resolved?.data
+ ? {
+ id: resolved.data.id,
+ clockIn: resolved.data.clockIn
+ }
+ : null
+ }
+ />
+ )}
+ </Await>
+ </Suspense>
+ )}
+ </TooltipProvider>
+ </RealtimeDataProvider>
+ </PrintingProvider>
</CarbonProvider>
)}
</div>
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx
index 11c5493b61..dc649517be 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx
@@ -1,6 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { trigger } from "@carbon/jobs";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { z } from "zod";
@@ -97,6 +98,22 @@ export async function action({ request, params }: ActionFunctionArgs) {
{ status: 400 }
);
}
+
+ const splitEntities = issue.data?.splitEntities || [];
+ if (splitEntities.length > 0) {
+ try {
+ for (const split of splitEntities) {
+ await trigger("print-job", {
+ sourceDocument: "Split",
+ sourceDocumentId: split.newId,
+ companyId,
+ userId
+ });
+ }
+ } catch (e) {
+ console.error("Auto-print for split entities failed:", e);
+ }
+ }
} else {
// Inventory item
const issue = await serviceRole.functions.invoke("issue", {
diff --git a/apps/erp/app/routes/x+/print.tsx b/apps/erp/app/routes/x+/print.tsx
new file mode 100644
index 0000000000..6b96b6fb69
--- /dev/null
+++ b/apps/erp/app/routes/x+/print.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { trigger } from "@carbon/jobs";
+import { manualPrintValidator } from "@carbon/printing";
+import type { ActionFunctionArgs } from "react-router";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {});
+
+ const json = await request.json();
+ const validation = manualPrintValidator.safeParse(json);
+
+ if (!validation.success) {
+ return { success: false, message: "Invalid print request" };
+ }
+
+ const {
+ sourceDocument,
+ sourceDocumentId,
+ locationId,
+ workCenterId,
+ printerRouteId
+ } = validation.data;
+
+ try {
+ await trigger("print-job", {
+ sourceDocument,
+ sourceDocumentId,
+ companyId,
+ userId,
+ locationId,
+ workCenterId,
+ printerRouteId
+ });
+ return { success: true, message: "Print job queued" };
+ } catch (e) {
+ return {
+ success: false,
+ message: e instanceof Error ? e.message : "Failed to queue print job"
+ };
+ }
+}
diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
index f062c9bb23..293effe734 100644
--- a/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx
@@ -7,6 +7,8 @@ import {
evaluateLinesForSurface,
isBlocked
} from "@carbon/ee/storage-rules.server";
+import { trigger } from "@carbon/jobs";
+import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { path } from "~/utils/path";
@@ -126,7 +128,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
.single();
const companySettings = await (serviceRole.from("companySettings") as any)
- .select("updateLeadTimesOnReceipt")
+ .select("updateLeadTimesOnReceipt,printing")
.eq("id", companyId)
.single();
@@ -182,8 +184,40 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
}
- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
- } catch (error) {
+
+ // Auto-print labels if enabled
+ try {
+ const { data: receipt } = await serviceRole
+ .from("receipt")
+ .select("locationId")
+ .eq("id", receiptId)
+ .single();
+ const locationId = receipt?.locationId as string | undefined;
+ if (locationId) {
+ const config = await getCachedPrinterConfig(
+ serviceRole,
+ companyId,
+ locationId,
+ "receiving"
+ );
+ if (config?.autoPrint ?? true) {
+ await trigger("print-job", {
+ sourceDocument: "Receipt",
+ sourceDocumentId: receiptId,
+ companyId,
+ userId,
+ locationId
+ });
+ }
+ }
+ } catch (e) {
+ console.error("Auto-print failed:", e);
+ }
+ } catch (thrown) {
+ // Re-throw redirects — don't swallow them
+ if (thrown instanceof Response) throw thrown;
+
+ // Only reset to Draft for actual errors
await client
.from("receipt")
.update({
diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
index 71f29c254d..7ce5d0d53b 100644
--- a/apps/erp/app/routes/x+/settings+/audit-logs.tsx
+++ b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
@@ -165,7 +165,7 @@ export default function AuditLogRoute() {
<Trans>Audit Logs</Trans>
</Heading>
{enabled && (
- <Button leftIcon={<LuHistory />} asChild>
+ <Button variant="secondary" leftIcon={<LuHistory />} asChild>
<Link to={path.to.auditLogDetails}>
<Trans>View All</Trans>
</Link>
diff --git a/apps/erp/app/routes/x+/settings+/labels.tsx b/apps/erp/app/routes/x+/settings+/labels.tsx
deleted file mode 100644
index 5081d1ff30..0000000000
--- a/apps/erp/app/routes/x+/settings+/labels.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { Select, Submit, ValidatedForm, validator } from "@carbon/form";
-import {
- Card,
- CardContent,
- CardDescription,
- CardFooter,
- CardHeader,
- CardTitle,
- Heading,
- ScrollArea,
- toast,
- VStack
-} from "@carbon/react";
-import { labelSizes } from "@carbon/utils";
-import { msg } from "@lingui/core/macro";
-import { Trans, useLingui } from "@lingui/react/macro";
-import { useEffect } from "react";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { redirect, useFetcher, useLoaderData } from "react-router";
-import {
- getCompanySettings,
- productLabelSizeValidator,
- updateProductLabelSize
-} from "~/modules/settings";
-import type { Handle } from "~/utils/handle";
-import { path } from "~/utils/path";
-export const handle: Handle = {
- breadcrumb: msg`Labels`,
- to: path.to.labelsSettings
-};
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "settings"
- });
-
- const companySettings = await getCompanySettings(client, companyId);
- if (!companySettings.data)
- throw redirect(
- path.to.settings,
- await flash(
- request,
- error(companySettings.error, "Failed to get company settings")
- )
- );
- return { companySettings: companySettings.data };
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- update: "settings"
- });
-
- const formData = await request.formData();
- const intent = formData.get("intent");
-
- switch (intent) {
- case "productLabelSize":
- const validation = await validator(productLabelSizeValidator).validate(
- formData
- );
-
- if (validation.error) {
- return { success: false, message: "Invalid form data" };
- }
-
- const productLabelSize = await updateProductLabelSize(
- client,
- companyId,
- validation.data.productLabelSize
- );
- if (productLabelSize.error)
- return {
- success: false,
- message: productLabelSize.error.message
- };
- }
-
- return { success: true, message: "Label settings updated" };
-}
-
-export default function SalesSettingsRoute() {
- const { t } = useLingui();
- const { companySettings } = useLoaderData<typeof loader>();
- const fetcher = useFetcher<typeof action>();
-
- useEffect(() => {
- if (fetcher.data?.success === true && fetcher?.data?.message) {
- toast.success(fetcher.data.message);
- }
-
- if (fetcher.data?.success === false && fetcher?.data?.message) {
- toast.error(fetcher.data.message);
- }
- }, [fetcher.data?.message, fetcher.data?.success]);
-
- return (
- <ScrollArea className="w-full h-[calc(100dvh-49px)]">
- <VStack
- spacing={4}
- className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"
- >
- <Heading size="h3">
- <Trans>Labels</Trans>
- </Heading>
- <Card>
- <ValidatedForm
- method="post"
- validator={productLabelSizeValidator}
- defaultValues={{
- productLabelSize: companySettings.productLabelSize ?? "avery5160"
- }}
- fetcher={fetcher}
- >
- <input type="hidden" name="intent" value="productLabelSize" />
- <CardHeader>
- <CardTitle className="flex items-center gap-2">
- <Trans>Product Label Size</Trans>
- </CardTitle>
- <CardDescription>
- <Trans>
- Define the default size of the product label. Used for
- tracking items in inventory.
- </Trans>
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="flex flex-col gap-8 max-w-[400px]">
- <div className="flex flex-col gap-2">
- <Select
- name="productLabelSize"
- label={t`Product Label Size`}
- options={labelSizes.map((size) => ({
- value: size.id,
- label: size.name
- }))}
- />
- </div>
- </div>
- </CardContent>
- <CardFooter>
- <Submit>
- <Trans>Save</Trans>
- </Submit>
- </CardFooter>
- </ValidatedForm>
- </Card>
- </VStack>
- </ScrollArea>
- );
-}
diff --git a/apps/erp/app/routes/x+/settings+/printing.$id.delete.tsx b/apps/erp/app/routes/x+/settings+/printing.$id.delete.tsx
new file mode 100644
index 0000000000..3079b84f1e
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/printing.$id.delete.tsx
@@ -0,0 +1,93 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import type { PrintingSettings } from "@carbon/printing";
+import { deletePrinterRoute } from "@carbon/printing";
+import { invalidatePrinterCache } from "@carbon/printing/printing.server";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
+import { path } from "~/utils/path";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Printer route ID is required");
+
+ const result = await deletePrinterRoute(client, id, companyId);
+ if (result.error) {
+ throw redirect(
+ path.to.printingSettings,
+ await flash(
+ request,
+ error(result.error, "Failed to delete printer route")
+ )
+ );
+ }
+
+ // Clean up dangling references in printing settings
+ const { data: existing } = await client
+ .from("companySettings")
+ .select("printing")
+ .eq("id", companyId)
+ .single();
+
+ const current = existing?.printing as PrintingSettings | null;
+ if (current) {
+ let dirty = false;
+ const settings = { ...current };
+
+ if (settings.assignments) {
+ const assignments = { ...settings.assignments };
+ for (const [locId, location] of Object.entries(assignments)) {
+ if (!location) continue;
+ const loc = { ...location };
+
+ if (loc.defaultPrinterRouteId === id) {
+ loc.defaultPrinterRouteId = null;
+ dirty = true;
+ }
+
+ if (loc.shipping?.printerRouteId === id) {
+ loc.shipping = { ...loc.shipping, printerRouteId: null };
+ dirty = true;
+ }
+
+ if (loc.receiving?.printerRouteId === id) {
+ loc.receiving = { ...loc.receiving, printerRouteId: null };
+ dirty = true;
+ }
+
+ if (loc.workCenters) {
+ const workCenters = { ...loc.workCenters };
+ for (const [wcId, wc] of Object.entries(workCenters)) {
+ if (wc?.printerRouteId === id) {
+ workCenters[wcId] = { ...wc, printerRouteId: null };
+ dirty = true;
+ }
+ }
+ loc.workCenters = workCenters;
+ }
+
+ assignments[locId] = loc;
+ }
+ settings.assignments = assignments;
+ }
+
+ if (dirty) {
+ await client
+ .from("companySettings")
+ .update({ printing: JSON.parse(JSON.stringify(settings)) })
+ .eq("id", companyId);
+ }
+ }
+
+ await invalidatePrinterCache(companyId);
+
+ throw redirect(
+ path.to.printingSettings,
+ await flash(request, success("Printer route deleted"))
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/printing.jobs.tsx b/apps/erp/app/routes/x+/settings+/printing.jobs.tsx
new file mode 100644
index 0000000000..0ce71b9ebe
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/printing.jobs.tsx
@@ -0,0 +1,221 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { trigger } from "@carbon/jobs";
+import {
+ createPrintJob,
+ getPrintJob,
+ getPrintJobContent,
+ getPrintJobs,
+ type PrintJob,
+ reprintValidator
+} from "@carbon/printing";
+import {
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerHeader,
+ DrawerTitle
+} from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data, useLoaderData, useNavigate } from "react-router";
+import { useRealtime } from "~/hooks";
+import { PrintJobsTable } from "~/modules/settings";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, filters } = getGenericQueryFilters(searchParams);
+
+ const status = filters?.find((f) => f.column === "status")?.value;
+ const origin = filters?.find((f) => f.column === "origin")?.value;
+ const sourceDocument = filters?.find(
+ (f) => f.column === "sourceDocument"
+ )?.value;
+ const contentType = filters?.find((f) => f.column === "contentType")?.value;
+
+ const result = await getPrintJobs(client, companyId, {
+ status,
+ origin,
+ sourceDocument,
+ contentType,
+ search,
+ limit,
+ offset
+ });
+
+ return {
+ jobs: (result.data ?? []) as PrintJob[],
+ count: result.count ?? 0
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ switch (intent) {
+ case "reprint": {
+ const validation = reprintValidator.safeParse(
+ Object.fromEntries(formData)
+ );
+ if (!validation.success)
+ return data(
+ { success: false, message: "Invalid reprint request" },
+ await flash(request, error(null, "Invalid reprint request"))
+ );
+
+ const { printJobId, printerUrl: overrideUrl } = validation.data;
+
+ const original = await getPrintJobContent(client, printJobId, companyId);
+ const originalMeta = await getPrintJob(client, printJobId, companyId);
+ if (
+ original.error ||
+ !original.data ||
+ originalMeta.error ||
+ !originalMeta.data
+ )
+ return data(
+ { success: false, message: "Failed to load print job" },
+ await flash(
+ request,
+ error(
+ original.error ?? originalMeta.error,
+ "Failed to load print job"
+ )
+ )
+ );
+
+ if (!original.data.content || !original.data.contentType)
+ return data(
+ { success: false, message: "Cannot reprint a job with no content" },
+ await flash(
+ request,
+ error(null, "Cannot reprint a job that is still generating")
+ )
+ );
+
+ const newJob = await createPrintJob(client, {
+ companyId,
+ contentType: original.data.contentType as "zpl" | "pdf",
+ content: original.data.content,
+ printerUrl: overrideUrl || originalMeta.data.printerUrl,
+ sourceDocument: originalMeta.data.sourceDocument,
+ sourceDocumentId: originalMeta.data.sourceDocumentId,
+ sourceDocumentReadableId:
+ originalMeta.data.sourceDocumentReadableId ?? undefined,
+ description: originalMeta.data.description,
+ status: "queued",
+ origin: "reprint",
+ createdBy: userId
+ });
+
+ if (newJob.error || !newJob.data)
+ return data(
+ { success: false, message: "Failed to create reprint job" },
+ await flash(request, error(newJob.error, "Failed to create reprint"))
+ );
+
+ try {
+ await trigger("print-job-deliver", {
+ printJobId: newJob.data.id,
+ companyId
+ });
+ } catch (e) {
+ console.error("Failed to trigger delivery:", e);
+ }
+
+ return data(
+ { success: true, message: "Reprint job created" },
+ await flash(request, success("Reprint job created"))
+ );
+ }
+
+ case "delete": {
+ const printJobId = formData.get("printJobId") as string;
+ if (!printJobId)
+ return data(
+ { success: false, message: "Print job ID required" },
+ await flash(request, error(null, "Print job ID required"))
+ );
+
+ const result = await client
+ .from("printJob")
+ .delete()
+ .eq("id", printJobId)
+ .eq("companyId", companyId);
+
+ if (result.error)
+ return data(
+ { success: false, message: result.error.message },
+ await flash(request, error(result.error, "Failed to delete job"))
+ );
+
+ return data(
+ { success: true, message: "Print job deleted" },
+ await flash(request, success("Print job deleted"))
+ );
+ }
+
+ case "viewContent": {
+ const printJobId = formData.get("printJobId") as string;
+ if (!printJobId)
+ return { success: false, message: "Print job ID required" };
+
+ const content = await getPrintJobContent(client, printJobId, companyId);
+ if (content.error || !content.data)
+ return { success: false, message: "Failed to load content" };
+
+ return {
+ success: true,
+ content: content.data.content,
+ contentType: content.data.contentType,
+ printJobId: content.data.id
+ };
+ }
+ }
+
+ return { success: false, message: "Unknown intent" };
+}
+
+export default function PrintJobsRoute() {
+ const { jobs, count } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ useRealtime("printJob");
+
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ navigate(path.to.printingSettings);
+ }
+ }}
+ >
+ <DrawerContent size="full">
+ <DrawerHeader>
+ <DrawerTitle>
+ <Trans>Print Jobs</Trans>
+ </DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody className="p-0">
+ <PrintJobsTable jobs={jobs} count={count} />
+ </DrawerBody>
+ </DrawerContent>
+ </Drawer>
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/printing.tsx b/apps/erp/app/routes/x+/settings+/printing.tsx
new file mode 100644
index 0000000000..6dcdd9fe6c
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/printing.tsx
@@ -0,0 +1,262 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import type { PrintingSettings } from "@carbon/printing";
+import {
+ getPrinterRoutes,
+ getPrintingSettings,
+ setContextAssignment,
+ updateAssignmentValidator,
+ updatePrintingSettings,
+ upsertPrinterRoute
+} from "@carbon/printing";
+import { invalidatePrinterCache } from "@carbon/printing/printing.server";
+import { Button, Heading, ScrollArea, VStack } from "@carbon/react";
+import { labelSizes } from "@carbon/utils";
+import { Trans } from "@lingui/react/macro";
+import { LuPrinter } from "react-icons/lu";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { Link, Outlet, redirect, useLoaderData } from "react-router";
+import { getLocationsList, getWorkCentersList } from "~/modules/resources";
+import { getCompanySettings, printerRouteValidator } from "~/modules/settings";
+import { AssignmentsCard, PrintersCard } from "~/modules/settings/ui/Printing";
+import { getUserDefaults } from "~/modules/users/users.server";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Printing",
+ to: path.to.printingSettings
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "settings"
+ });
+
+ const [companySettings, printerRoutes, workCenters, locations, userDefaults] =
+ await Promise.all([
+ getCompanySettings(client, companyId),
+ getPrinterRoutes(client, companyId),
+ getWorkCentersList(client, companyId),
+ getLocationsList(client, companyId),
+ getUserDefaults(client, userId, companyId)
+ ]);
+
+ if (!companySettings.data)
+ throw redirect(
+ path.to.settings,
+ await flash(
+ request,
+ error(companySettings.error, "Failed to get company settings")
+ )
+ );
+
+ return {
+ printing:
+ (companySettings.data.printing as PrintingSettings | null) ?? null,
+ printerRoutes: printerRoutes.data ?? [],
+ workCenters: workCenters.data ?? [],
+ locations: locations.data ?? [],
+ defaultLocationId: userDefaults.data?.locationId ?? null
+ };
+}
+
+function generateTestLabel(
+ format: string,
+ mediaSizeId: string | null
+): string | null {
+ if (format !== "zpl" || !mediaSizeId) return null;
+
+ const labelSize = labelSizes.find((s) => s.id === mediaSizeId);
+ if (!labelSize?.zpl) return null;
+
+ const { width, height } = labelSize.zpl;
+ const dpi = labelSize.zpl.dpi || 203;
+ const widthDots = Math.round(width * dpi);
+ const heightDots = Math.round(height * dpi);
+
+ const now = new Date();
+ const timestamp = `${now.toLocaleDateString()} ${now.toLocaleTimeString()}`;
+
+ return [
+ "^XA",
+ `^PW${widthDots}`,
+ `^LL${heightDots}`,
+ "^MNW",
+ "^FO20,20^A0N,30,30^FDTest Print^FS",
+ `^FO20,60^A0N,20,20^FD${mediaSizeId} — ${width}x${height}"^FS`,
+ `^FO20,90^A0N,16,16^FD${timestamp}^FS`,
+ "^XZ"
+ ].join("\n");
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ switch (intent) {
+ case "upsertRoute": {
+ const validation = await validator(printerRouteValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const result = await upsertPrinterRoute(client, {
+ id: validation.data.id || undefined,
+ companyId,
+ name: validation.data.name,
+ format: validation.data.format,
+ mediaSizeId: validation.data.mediaSizeId || null,
+ printerUrl: validation.data.printerUrl,
+ apiKey: validation.data.apiKey || null,
+ locationId: validation.data.locationId || null,
+ templateId: validation.data.templateId || null
+ });
+
+ if (result.error)
+ return { success: false, message: result.error.message };
+
+ await invalidatePrinterCache(companyId);
+
+ return {
+ success: true,
+ message: validation.data.id
+ ? "Printer route updated"
+ : "Printer route created"
+ };
+ }
+
+ case "testPrint": {
+ const routeId = formData.get("routeId") as string;
+ if (!routeId) return { success: false, message: "Route ID required" };
+
+ const { data: route } = await client
+ .from("printerRoute")
+ .select("printerUrl, format, mediaSizeId, apiKey")
+ .eq("id", routeId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (!route) return { success: false, message: "Printer route not found" };
+
+ try {
+ const headers: Record<string, string> = {
+ "Content-Type": "application/octet-stream"
+ };
+ if (route.apiKey) headers["X-API-Key"] = route.apiKey;
+
+ const testLabel = generateTestLabel(route.format, route.mediaSizeId);
+
+ if (!testLabel) {
+ return {
+ success: false,
+ message:
+ "Test print is only supported for ZPL label printers with a media size configured."
+ };
+ }
+
+ const response = await fetch(route.printerUrl, {
+ method: "POST",
+ headers,
+ body: testLabel,
+ signal: AbortSignal.timeout(10_000)
+ });
+
+ if (!response.ok) {
+ return {
+ success: false,
+ message: `Print failed (${response.status} ${response.statusText})`
+ };
+ }
+
+ return { success: true, message: "Test label sent to printer" };
+ } catch (err) {
+ return {
+ success: false,
+ message: `Print failed: ${err instanceof Error ? err.message : "Unknown error"}`
+ };
+ }
+ }
+
+ case "updateAssignment": {
+ const validation = await validator(updateAssignmentValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return { success: false, message: "Invalid form data" };
+ }
+
+ const { locationId, context, contextId, printerRouteId, autoPrint } =
+ validation.data;
+
+ const { data: existing } = await getPrintingSettings(client, companyId);
+ const current = (existing?.printing as PrintingSettings | null) ?? {
+ assignments: {}
+ };
+
+ const updated = setContextAssignment(
+ current,
+ locationId,
+ context,
+ { printerRouteId: printerRouteId || null, autoPrint },
+ contextId
+ );
+
+ const result = await updatePrintingSettings(client, companyId, updated);
+
+ if (result.error)
+ return { success: false, message: result.error.message };
+
+ await invalidatePrinterCache(companyId);
+
+ return { success: true, message: "Assignment updated" };
+ }
+ }
+
+ return { success: false, message: "Unknown intent" };
+}
+
+export default function PrintingSettingsRoute() {
+ const { printing, printerRoutes, workCenters, locations } =
+ useLoaderData<typeof loader>();
+
+ return (
+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">
+ <VStack
+ spacing={4}
+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"
+ >
+ <div className="flex items-center justify-between w-full">
+ <Heading size="h3">
+ <Trans>Printing</Trans>
+ </Heading>
+ <Button variant="secondary" leftIcon={<LuPrinter />} asChild>
+ <Link to={path.to.printingSettingsJobs}>
+ <Trans>View Prints</Trans>
+ </Link>
+ </Button>
+ </div>
+
+ <PrintersCard printerRoutes={printerRoutes} />
+
+ <AssignmentsCard
+ printing={printing}
+ printerRoutes={printerRoutes}
+ locations={locations}
+ workCenters={workCenters}
+ />
+ </VStack>
+ <Outlet />
+ </ScrollArea>
+ );
+}
diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
index c58d5c2920..72b4e4b80a 100644
--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx
@@ -7,6 +7,8 @@ import {
evaluateLinesForSurface,
isBlocked
} from "@carbon/ee/storage-rules.server";
+import { trigger } from "@carbon/jobs";
+import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
@@ -270,8 +272,54 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
);
}
- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
- } catch (error) {
+
+ // Auto-print labels if enabled
+ try {
+ const { data: shipmentForPrint } = await serviceRole
+ .from("shipment")
+ .select("locationId")
+ .eq("id", shipmentId)
+ .single();
+ const locationId = shipmentForPrint?.locationId as string | undefined;
+ if (locationId) {
+ const config = await getCachedPrinterConfig(
+ serviceRole,
+ companyId,
+ locationId,
+ "shipping"
+ );
+ if (config?.autoPrint ?? true) {
+ await trigger("print-job", {
+ sourceDocument: "Shipment",
+ sourceDocumentId: shipmentId,
+ companyId,
+ userId,
+ locationId
+ });
+ }
+ }
+ } catch (e) {
+ console.error("Auto-print failed:", e);
+ }
+
+ // Auto-print labels for batch split entities
+ const splitEntityIds = postShipment.data?.splitEntityIds || [];
+ if (splitEntityIds.length > 0) {
+ try {
+ for (const entityId of splitEntityIds) {
+ await trigger("print-job", {
+ sourceDocument: "Split",
+ sourceDocumentId: entityId,
+ companyId,
+ userId
+ });
+ }
+ } catch (e) {
+ console.error("Auto-print for split entities failed:", e);
+ }
+ }
+ } catch (thrown) {
+ if (thrown instanceof Response) throw thrown;
await client
.from("shipment")
.update({
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx
index 2631ae1b19..9d53ccaf64 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx
@@ -1,6 +1,7 @@
import { assertIsPost, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { trigger } from "@carbon/jobs";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { getStockTransfer } from "~/modules/inventory";
@@ -89,9 +90,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
// Call the post-stock-transfer function for inventory items
- const { error: functionError } = await client.functions.invoke(
- "post-stock-transfer",
- {
+ const { data: transferResult, error: functionError } =
+ await client.functions.invoke("post-stock-transfer", {
body: JSON.stringify({
type: type,
stockTransferId: stockTransferLine.data.stockTransferId,
@@ -102,8 +102,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
userId,
companyId
})
- }
- );
+ });
if (functionError) {
return data(
@@ -120,6 +119,30 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ if (transferResult?.splitEntityId) {
+ try {
+ await trigger("print-job", {
+ sourceDocument: "Split",
+ sourceDocumentId: transferResult.splitEntityId,
+ companyId,
+ userId,
+ locationId: locationId || undefined
+ });
+ // Reprint the original batch too — its quantity changed in the split
+ if (trackedEntityId) {
+ await trigger("print-job", {
+ sourceDocument: "Entity",
+ sourceDocumentId: trackedEntityId,
+ companyId,
+ userId,
+ locationId: locationId || undefined
+ });
+ }
+ } catch (e) {
+ console.error("Auto-print for split entity failed:", e);
+ }
+ }
+
return data(
{
success: true
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
index 22db38a1c8..fcd19756d2 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
@@ -3,6 +3,7 @@ import { error, success, useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { Hidden, ValidatedForm } from "@carbon/form";
+import { trigger } from "@carbon/jobs";
import {
Alert,
AlertTitle,
@@ -130,12 +131,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
companyId
};
- const { error: functionError } = await client.functions.invoke(
- "post-stock-transfer",
- {
+ const { data: transferResult, error: functionError } =
+ await client.functions.invoke("post-stock-transfer", {
body: JSON.stringify(functionPayload)
- }
- );
+ });
if (functionError) {
return data(
@@ -150,6 +149,30 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ if (transferResult?.splitEntityId) {
+ try {
+ await trigger("print-job", {
+ sourceDocument: "Split",
+ sourceDocumentId: transferResult.splitEntityId,
+ companyId,
+ userId,
+ locationId: locationId || undefined
+ });
+ // Reprint the original batch too — its quantity changed in the split
+ if (trackedEntityId) {
+ await trigger("print-job", {
+ sourceDocument: "Entity",
+ sourceDocumentId: trackedEntityId,
+ companyId,
+ userId,
+ locationId: locationId || undefined
+ });
+ }
+ } catch (e) {
+ console.error("Auto-print for split entity failed:", e);
+ }
+ }
+
throw redirect(
path.to.stockTransfer(stockTransferId),
await flash(request, success("Tracked entity scanned and transferred"))
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index e3c74a6bb6..574dc683cf 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -372,8 +372,56 @@ export const path = {
return generatePath(url);
},
+ storageUnitLabelsZpl: (
+ ids: string | string[],
+ opts?: { labelSize?: string }
+ ) => {
+ const idString = Array.isArray(ids) ? ids.join(",") : ids;
+ let url = `${file}/storage-unit/labels.zpl?ids=${idString}`;
+ if (opts?.labelSize) url += `&labelSize=${opts.labelSize}`;
+ return url;
+ },
+ storageUnitLabelsPdf: (
+ ids: string | string[],
+ opts?: { labelSize?: string }
+ ) => {
+ const idString = Array.isArray(ids) ? ids.join(",") : ids;
+ let url = `${file}/storage-unit/labels.pdf?ids=${idString}`;
+ if (opts?.labelSize) url += `&labelSize=${opts.labelSize}`;
+ return url;
+ },
stockTransfer: (id: string) =>
generatePath(`${file}/stock-transfer/${id}.pdf`),
+ stockTransferLabelsPdf: (
+ id: string,
+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}
+ ) => {
+ let url = `${file}/stock-transfer/${id}/labels.pdf`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+ if (lineId) params.append("lineId", lineId);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
+ stockTransferLabelsZpl: (
+ id: string,
+ { labelSize, lineId }: { labelSize?: string; lineId?: string } = {}
+ ) => {
+ let url = `${file}/stock-transfer/${id}/labels.zpl`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+ if (lineId) params.append("lineId", lineId);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
quote: (id: string) => generatePath(`${file}/quote/${id}.pdf`)
},
legal: {
@@ -1002,6 +1050,7 @@ export const path = {
kanban: (id: string) => generatePath(`${x}/inventory/kanbans/${id}`),
kanbans: `${x}/inventory/kanbans`,
labelsSettings: `${x}/settings/labels`,
+ manualPrint: `${x}/print`,
location: (id: string) => generatePath(`${x}/resources/locations/${id}`),
locations: `${x}/resources/locations`,
login: "/login",
@@ -1356,6 +1405,10 @@ export const path = {
generatePath(`${x}/resources/processes/activate/${id}`),
processDeactivate: (id: string) =>
generatePath(`${x}/resources/processes/deactivate/${id}`),
+ printingSettings: `${x}/settings/printing`,
+ printingSettingsJobs: `${x}/settings/printing/jobs`,
+ deletePrinterRoute: (id: string) =>
+ generatePath(`${x}/settings/printing/${id}/delete`),
production: `${x}/production`,
productionPlanning: `${x}/production/planning`,
productionPlanningItem: (itemId: string) =>
diff --git a/apps/erp/package.json b/apps/erp/package.json
index a689a54b00..4d31400daa 100644
--- a/apps/erp/package.json
+++ b/apps/erp/package.json
@@ -22,6 +22,7 @@
"@carbon/lib": "workspace:*",
"@carbon/locale": "workspace:*",
"@carbon/notifications": "workspace:*",
+ "@carbon/printing": "workspace:*",
"@carbon/react": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index b510c2b8de..eb999ed99a 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -28,7 +28,6 @@ import {
ScrollArea,
Separator,
SidebarTrigger,
- SplitButton,
Table,
Tabs,
TabsContent,
@@ -46,6 +45,7 @@ import {
useDisclosure,
useKeyboardWedge,
useMode,
+ useRouteData,
VStack
} from "@carbon/react";
import type { TrackedEntityAttributes } from "@carbon/utils";
@@ -53,8 +53,7 @@ import {
convertDateStringToIsoString,
convertKbToString,
formatDurationMilliseconds,
- getItemReadableId,
- labelSizes
+ getItemReadableId
} from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
@@ -78,7 +77,6 @@ import {
LuGitPullRequest,
LuHammer,
LuHardHat,
- LuPrinter,
LuQrCode,
LuSquareUser,
LuTimer,
@@ -90,7 +88,8 @@ import {
DeadlineIcon,
FileIcon,
FilePreview,
- OperationStatusIcon
+ OperationStatusIcon,
+ PrintButton
} from "~/components";
import {
MethodIcon,
@@ -386,36 +385,10 @@ export const JobOperation = ({
attributeRecordDeleteModal.onClose();
};
- const navigateToTrackingLabels = (
- zpl?: boolean,
- {
- labelSize,
- trackedEntityId
- }: { labelSize?: string; trackedEntityId?: string } = {}
- ) => {
- if (!window) return;
- if (!operationId) return;
-
- if (zpl) {
- window.open(
- window.location.origin +
- path.to.file.operationLabelsZpl(operationId, {
- labelSize,
- trackedEntityId
- }),
- "_blank"
- );
- } else {
- window.open(
- window.location.origin +
- path.to.file.operationLabelsPdf(operationId, {
- labelSize,
- trackedEntityId
- }),
- "_blank"
- );
- }
- };
+ const layoutData = useRouteData<{ location: string }>(
+ path.to.authenticatedRoot
+ );
+ const locationId = layoutData?.location;
const completeFetcher = useFetcher<Result>();
useKeyboardWedge({
@@ -1010,19 +983,19 @@ export const JobOperation = ({
return (
<>
- <Table className="w-full">
+ <Table className="w-full text-base">
<Thead>
<Tr>
- <Th>
+ <Th className="text-sm">
<Trans>Part</Trans>
</Th>
- <Th className="lg:table-cell hidden">
+ <Th className="text-sm lg:table-cell hidden">
<Trans>Source</Trans>
</Th>
- <Th>
+ <Th className="text-sm">
<Trans>Estimated</Trans>
</Th>
- <Th>
+ <Th className="text-sm">
<Trans>Actual</Trans>
</Th>
<Th className="text-right" />
@@ -1061,6 +1034,7 @@ export const JobOperation = ({
<Tr
key={`material-${material.id}`}
className={cn(
+ "[&>td]:py-3",
!isRelatedToOperation &&
"opacity-50 hover:opacity-100"
)}
@@ -1071,13 +1045,13 @@ export const JobOperation = ({
className="justify-between"
>
<VStack spacing={0}>
- <span className="font-semibold">
+ <span className="font-semibold text-base">
{getItemReadableId(
items,
material.itemId ?? ""
)}
</span>
- <span className="text-muted-foreground text-xs">
+ <span className="text-muted-foreground text-sm">
{material.description}
</span>
</VStack>
@@ -1206,6 +1180,7 @@ export const JobOperation = ({
material.requiresSerialTracking) && (
<Button
className="flex-shrink-0"
+ size="lg"
variant={
someRelatedMaterialIsIssued ||
!isRelatedToOperation
@@ -1388,6 +1363,8 @@ export const JobOperation = ({
<IssueMaterialModal
operationId={operation.id}
expiredEntityPolicy={expiredEntityPolicy}
+ locationId={locationId}
+ workCenterId={operation.workCenterId ?? undefined}
material={selectedMaterial ?? undefined}
parentId={trackedEntityId ?? ""}
parentIdIsSerialized={
@@ -1427,13 +1404,13 @@ export const JobOperation = ({
>
<Await resolve={files}>
{(resolvedFiles) => (
- <Table className="w-full">
+ <Table className="w-full text-base">
<Thead>
<Tr>
- <Th>
+ <Th className="text-sm">
<Trans>Name</Trans>
</Th>
- <Th>
+ <Th className="text-sm">
<Trans>Size</Trans>
</Th>
<Th></Th>
@@ -1452,14 +1429,14 @@ export const JobOperation = ({
) : (
<>
{modelUpload?.modelName && (
- <Tr>
+ <Tr className="[&>td]:py-3">
<Td>
<HStack>
<LuAxis3D className="text-emerald-500 w-6 h-6" />
<span>{modelUpload.modelName}</span>
</HStack>
</Td>
- <Td className="text-xs font-mono">
+ <Td className="text-sm font-mono">
{modelUpload.modelSize
? convertKbToString(
Math.floor(
@@ -1498,7 +1475,10 @@ export const JobOperation = ({
{resolvedFiles.map((file) => {
const type = getFileType(file.name);
return (
- <Tr key={`file-${file.id}`}>
+ <Tr
+ key={`file-${file.id}`}
+ className="[&>td]:py-3"
+ >
<Td>
<HStack>
<FileIcon type={type} />
@@ -1534,7 +1514,7 @@ export const JobOperation = ({
</span>
</HStack>
</Td>
- <Td className="text-xs font-mono">
+ <Td className="text-sm font-mono">
{convertKbToString(
Math.floor(
(file.metadata?.size ?? 0) / 1024
@@ -1588,21 +1568,17 @@ export const JobOperation = ({
</Heading>
{trackedEntities?.length > 0 && (
<HStack>
- <SplitButton
- leftIcon={<LuQrCode />}
- size="lg"
- dropdownItems={labelSizes.map((size) => ({
- label: size.name,
- onClick: () =>
- navigateToTrackingLabels(!!size.zpl, {
- labelSize: size.id
- })
- }))}
- // TODO: if we knew the preferred label size, we could use that here
- onClick={() => navigateToTrackingLabels(false)}
- >
- <Trans>Tracking Labels</Trans>
- </SplitButton>
+ <PrintButton
+ sourceDocument="Operation"
+ sourceDocumentId={operationId!}
+ locationId={locationId}
+ context="workCenter"
+ workCenterId={operation.workCenterId ?? undefined}
+ fileRoutes={{
+ pdf: path.to.file.operationLabelsPdf,
+ zpl: path.to.file.operationLabelsZpl
+ }}
+ />
<Button
variant="secondary"
size="lg"
@@ -1614,10 +1590,10 @@ export const JobOperation = ({
)}
</HStack>
- <Table className="w-full">
+ <Table className="w-full text-base">
<Thead>
<Tr>
- <Th>
+ <Th className="text-sm">
<Trans>Serial</Trans>
</Th>
<Th className="text-right" />
@@ -1636,31 +1612,38 @@ export const JobOperation = ({
</Tr>
) : (
trackedEntities?.map((entity) => (
- <Tr key={`serial-${entity.id}`}>
- <Td className="flex gap-2 items-center">
- <span>{entity.id}</span>
- {entity.id === trackedEntityId && (
- <LuCheck className="text-emerald-500 size-4" />
- )}
- <Copy text={entity.id} />
+ <Tr
+ key={`serial-${entity.id}`}
+ className="[&>td]:py-3"
+ >
+ <Td>
+ <div className="flex gap-2 items-center">
+ <span>{entity.id}</span>
+ {entity.id === trackedEntityId && (
+ <LuCheck className="text-emerald-500 size-4" />
+ )}
+ <Copy text={entity.id} />
+ </div>
</Td>
<Td className="text-right">
<div className="flex justify-end gap-2">
- <IconButton
- aria-label="Print Label"
- size="sm"
- icon={<LuPrinter />}
- variant="secondary"
- onClick={() => {
- navigateToTrackingLabels(false, {
- trackedEntityId: entity.id
- });
+ <PrintButton
+ sourceDocument="Entity"
+ sourceDocumentId={entity.id}
+ locationId={locationId}
+ context="workCenter"
+ workCenterId={
+ operation.workCenterId ?? undefined
+ }
+ fileRoutes={{
+ pdf: path.to.file.trackedEntityLabelPdf,
+ zpl: path.to.file.trackedEntityLabelZpl
}}
/>
<Button
variant="secondary"
- size="sm"
+ size="lg"
isDisabled={entity.id === trackedEntityId}
onClick={() => {
const entityIndex =
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index bc97474d37..3008a62387 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -43,7 +43,6 @@ import {
toast,
useDisclosure
} from "@carbon/react";
-
import { getItemReadableId } from "@carbon/utils";
import { getLocalTimeZone, parseDate, today } from "@internationalized/date";
import { useNumberFormatter } from "@react-aria/i18n";
@@ -56,7 +55,6 @@ import {
LuCirclePlus,
LuGitBranch,
LuList,
- LuPrinter,
LuQrCode,
LuScale,
LuTrash,
@@ -64,6 +62,7 @@ import {
LuX
} from "react-icons/lu";
import { useFetcher } from "react-router";
+import { PrintButton } from "~/components";
import type {
getBatchNumbersForItem,
getSerialNumbersForItem
@@ -87,6 +86,8 @@ type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";
export function IssueMaterialModal({
operationId,
expiredEntityPolicy = "Block",
+ locationId,
+ workCenterId,
material,
parentId,
parentIdIsSerialized,
@@ -95,6 +96,8 @@ export function IssueMaterialModal({
}: {
operationId: string;
expiredEntityPolicy?: ExpiredEntityPolicy;
+ locationId?: string;
+ workCenterId?: string;
material?: JobMaterial;
parentId?: string;
parentIdIsSerialized?: boolean;
@@ -181,29 +184,24 @@ export function IssueMaterialModal({
)
.map((sn) => {
const expired = isExpiryPast(sn.expirationDate);
- const labelText = sn.id ?? "";
- // ComboboxBase.label accepts JSX, so render the readableId next to a
- // small destructive Badge for expired stock — pops in the dropdown
- // far better than a plain "EXPIRED" prefix in the helper line.
- const label = expired ? (
+ const label = (
<span key={sn.id} className="flex items-center gap-2">
- <span className="truncate">{labelText}</span>
- <Badge variant="red">Expired</Badge>
+ {sn.readableId && (
+ <span className="font-medium">{sn.readableId}</span>
+ )}
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {sn.id}
+ </span>
+ {expired && <Badge variant="red">Expired</Badge>}
</span>
- ) : (
- labelText
);
- const helperParts = [
- sn.readableId ? `Serial ${sn.readableId}` : null,
- sn.expirationDate
- ? `${expired ? "Expired" : "Expires"} ${formatExpiry(sn.expirationDate)}`
- : null
- ].filter(Boolean) as string[];
+ const helper = sn.expirationDate
+ ? `${expired ? "Expired" : "Expires"} ${formatExpiry(sn.expirationDate)}`
+ : undefined;
return {
label,
value: sn.id,
- helper:
- helperParts.length > 0 ? helperParts.join(" · ") : undefined,
+ helper,
expirationDate: sn.expirationDate ?? null,
isExpired: expired
};
@@ -226,18 +224,27 @@ export function IssueMaterialModal({
)
.map((bn) => {
const expired = isExpiryPast(bn.expirationDate);
- const expiryNote = bn.expirationDate
- ? expired
- ? `EXPIRED ${formatExpiry(bn.expirationDate)}`
- : `Expires ${formatExpiry(bn.expirationDate)}`
- : null;
- const stockHelper = bn.readableId
- ? `${bn.id.slice(0, 10)} - ${bn.quantity} Available of Batch ${bn.readableId}`
- : `${bn.id.slice(0, 10)} - ${bn.quantity} Available`;
+ const label = (
+ <span key={bn.id} className="flex items-center gap-2">
+ {bn.readableId && (
+ <span className="font-medium">{bn.readableId}</span>
+ )}
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {bn.id.slice(0, 10)}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {bn.quantity} available
+ </span>
+ {expired && <Badge variant="red">Expired</Badge>}
+ </span>
+ );
+ const helper = bn.expirationDate
+ ? `${expired ? "Expired" : "Expires"} ${formatExpiry(bn.expirationDate)}`
+ : undefined;
return {
- label: bn.sourceDocumentReadableId ?? "",
+ label,
value: bn.id,
- helper: [expiryNote, stockHelper].filter(Boolean).join(" · "),
+ helper,
availableQuantity: bn.quantity,
expirationDate: bn.expirationDate ?? null,
isExpired: expired
@@ -249,9 +256,20 @@ export function IssueMaterialModal({
// Unconsume options for batch
const unconsumeOptions = useMemo(() => {
return trackedInputs.map((input) => ({
- label: input.id,
- value: input.id,
- helper: `${input.quantity} ${input.readableId ? `of Batch ${input.readableId}` : ""}`
+ label: (
+ <span className="flex items-center gap-2">
+ {input.readableId && (
+ <span className="font-medium">{input.readableId}</span>
+ )}
+ <span className="text-xs text-muted-foreground font-mono truncate">
+ {input.id.slice(0, 10)}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ qty {input.quantity}
+ </span>
+ </span>
+ ),
+ value: input.id
}));
}, [trackedInputs]);
@@ -874,21 +892,17 @@ export function IssueMaterialModal({
</span>
</div>
<div className="flex gap-2 mt-4">
- <Button
- variant="primary"
- leftIcon={<LuPrinter />}
- onClick={() => {
- window.open(
- window.location.origin +
- path.to.file.trackedEntityLabelPdf(
- split.newId
- ),
- "_blank"
- );
+ <PrintButton
+ sourceDocument="Split"
+ sourceDocumentId={split.newId}
+ locationId={locationId}
+ context="workCenter"
+ workCenterId={workCenterId}
+ fileRoutes={{
+ pdf: path.to.file.trackedEntityLabelPdf,
+ zpl: path.to.file.trackedEntityLabelZpl
}}
- >
- Print Label
- </Button>
+ />
<Button
variant="secondary"
leftIcon={<LuArrowRightLeft />}
diff --git a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
index e8b57fd4db..ef47e6fd82 100644
--- a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx
@@ -20,7 +20,7 @@ import {
VStack
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
-import { useMemo, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import { useFetcher } from "react-router";
import {
@@ -66,6 +66,14 @@ export function QuantityModal({
const fetcher = useFetcher<ProductionQuantity>();
const [quantity, setQuantity] = useState(parentIsSerial ? 1 : 0);
const [confirmedUnissued, setConfirmedUnissued] = useState(false);
+ const submitted = useRef(false);
+ const isSubmitting = fetcher.state !== "idle";
+
+ useEffect(() => {
+ if (submitted.current && fetcher.state === "idle") {
+ onClose();
+ }
+ }, [fetcher.state, onClose]);
const titleMap = {
scrap: t`Log scrap for ${operation.itemReadableId}`,
@@ -152,7 +160,7 @@ export function QuantityModal({
}}
fetcher={fetcher}
onSubmit={() => {
- onClose();
+ submitted.current = true;
}}
>
<ModalHeader>
@@ -192,6 +200,7 @@ export function QuantityModal({
onCheckedChange={(checked) =>
setConfirmedUnissued(checked === true)
}
+ className="bg-primary"
/>
<span className="text-sm">
<Trans>
@@ -300,10 +309,12 @@ export function QuantityModal({
: "primary"
}
type="submit"
+ isLoading={isSubmitting}
disabled={
- type === "complete" &&
- hasUnissuedTrackedMaterials &&
- !confirmedUnissued
+ isSubmitting ||
+ (type === "complete" &&
+ hasUnissuedTrackedMaterials &&
+ !confirmedUnissued)
}
>
{actionButtonMap[type]}
diff --git a/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx b/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx
index 6a33b26fd4..ed84a235c5 100644
--- a/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx
+++ b/apps/mes/app/components/MaintenanceDispatch/MaintenanceAddPartModal.tsx
@@ -123,9 +123,10 @@ export function MaintenanceAddPartModal({
setSerialOptions(
serials?.map((sn) => ({
- label: sn.id ?? "",
- value: sn.id,
- helper: sn.readableId ? t`Serial ${sn.readableId}` : undefined
+ label: sn.readableId
+ ? `${sn.readableId} — ${sn.id}`
+ : (sn.id ?? ""),
+ value: sn.id
})) ?? []
);
}
@@ -140,11 +141,10 @@ export function MaintenanceAddPartModal({
setBatchOptions(
batches?.map((batch) => ({
- label: batch.id ?? "",
+ label: batch.readableId
+ ? `${batch.readableId} — ${batch.id.slice(0, 10)} — ${batch.quantity} available`
+ : `${batch.id.slice(0, 10)} — ${batch.quantity} available`,
value: batch.id,
- helper: batch.readableId
- ? t`Batch ${batch.readableId} (${batch.quantity} available)`
- : t`${batch.quantity} available`,
quantity: batch.quantity ?? 0
})) ?? []
);
@@ -153,7 +153,7 @@ export function MaintenanceAddPartModal({
setIsLoadingItem(false);
}
},
- [carbon, t]
+ [carbon]
);
const validateSerialNumber = useCallback(
diff --git a/apps/mes/app/components/index.ts b/apps/mes/app/components/index.ts
index 6f444271f8..f4f5805fb4 100644
--- a/apps/mes/app/components/index.ts
+++ b/apps/mes/app/components/index.ts
@@ -1,6 +1,6 @@
+import { PrintButton } from "@carbon/printing/ui";
import { AppSidebar } from "./AppSidebar";
import Avatar from "./Avatar";
-
import FilePreview from "./FilePreview";
import Hyperlink from "./Hyperlink";
import { DeadlineIcon, FileIcon, OperationStatusIcon } from "./Icons";
@@ -14,5 +14,6 @@ export {
FilePreview,
Hyperlink,
OperationsList,
- OperationStatusIcon
+ OperationStatusIcon,
+ PrintButton
};
diff --git a/apps/mes/app/hooks/index.ts b/apps/mes/app/hooks/index.ts
index a14de2b2f0..36add944f4 100644
--- a/apps/mes/app/hooks/index.ts
+++ b/apps/mes/app/hooks/index.ts
@@ -1,10 +1,10 @@
+import { usePrinting } from "@carbon/printing/ui";
import {
useNanoStore,
useOptimisticLocation,
useRouteData,
useUrlParams
} from "@carbon/react";
-
import { useDateFormatter } from "./useDateFormatter";
import { useRealtime } from "./useRealtime";
import { useUser } from "./useUser";
@@ -13,6 +13,7 @@ export {
useDateFormatter,
useNanoStore,
useOptimisticLocation,
+ usePrinting,
useRealtime,
useRouteData,
useUrlParams,
diff --git a/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx b/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx
index 9358ef6a6e..91774c5156 100644
--- a/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx
+++ b/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx
@@ -3,10 +3,8 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect } from "react-router";
import { getCompanySettings } from "~/services/inventory.service";
import { getTrackedEntity } from "~/services/operations.service";
-import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {});
@@ -19,12 +17,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getTrackedEntity(client, id)
]);
- // Get the label size from query params or default to avery5160
+ // Get the label size from query params or default to avery5163
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "avery5160";
+ labelParam || companySettings.data?.productLabelSize || "avery5163";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
@@ -33,14 +31,6 @@ 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")
diff --git a/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx b/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx
index 018d2354a4..ee3e228357 100644
--- a/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx
+++ b/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx
@@ -18,12 +18,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getTrackedEntity(client, id)
]);
- // Get the label size from query params or default to zebra2x1
+ // Get the label size from query params or default to label2x1
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "zebra2x1";
+ labelParam || companySettings.data?.productLabelSize || "label2x1";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
index 85a075556e..1c29ab6bea 100644
--- a/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
@@ -3,10 +3,8 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
import type { LoaderFunctionArgs } from "react-router";
-import { redirect } from "react-router";
import { getCompanySettings } from "~/services/inventory.service";
import { getTrackedEntitiesByOperationId } from "~/services/operations.service";
-import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {});
@@ -19,12 +17,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getTrackedEntitiesByOperationId(client, id)
]);
- // Get the label size from query params or default to avery5160
+ // Get the label size from query params or default to avery5163
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const trackedEntityIdParam = url.searchParams.get("trackedEntityId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "avery5160";
+ labelParam || companySettings.data?.productLabelSize || "avery5163";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
@@ -33,15 +31,6 @@ 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
diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
index 1271c2f674..1f60d7a937 100644
--- a/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
@@ -18,12 +18,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
getTrackedEntitiesByMakeMethodId(client, id)
]);
- // Get the label size from query params or default to zebra2x1
const url = new URL(request.url);
const labelParam = url.searchParams.get("labelSize");
const trackedEntityIdParam = url.searchParams.get("trackedEntityId");
const labelSizeId =
- labelParam || companySettings.data?.productLabelSize || "zebra2x1";
+ labelParam || companySettings.data?.productLabelSize || "label2x1";
// Find the label size configuration
let labelSize = labelSizes.find((size) => size.id === labelSizeId);
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index ae4a3e07f5..79c573c29d 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -11,6 +11,9 @@ import {
destroyAuthSession,
requireAuthSession
} from "@carbon/auth/session.server";
+import type { PrintingSettings } from "@carbon/printing";
+import { getPrinterRoutes } from "@carbon/printing";
+import { PrintingProvider } from "@carbon/printing/ui";
import {
ItarPopup,
SidebarProvider,
@@ -105,7 +108,8 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
activeEvents,
companySettings,
openClockEntry,
- locationEmployees
+ locationEmployees,
+ printerRoutes
] = await Promise.all([
getStripeCustomerByCompanyId(companyId, userId),
getLocationsByCompany(client, companyId),
@@ -115,7 +119,7 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
}),
client
.from("companySettings")
- .select("timeCardEnabled, consoleEnabled")
+ .select("timeCardEnabled, consoleEnabled, printing, useMetric")
.eq("id", companyId)
.single(),
getOpenClockEntry(client, effectiveUserId, companyId),
@@ -126,14 +130,14 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
.select("id")
.eq("locationId", locationId)
.eq("companyId", companyId)
- : Promise.resolve({ data: [] as { id: string }[] })
+ : Promise.resolve({ data: [] as { id: string }[] }),
+ getPrinterRoutes(serviceRole, companyId)
]);
const locationEmployeeIds =
locationEmployees.data?.map((e: { id: string }) => e.id) ?? [];
- const timeCardEnabled =
- (companySettings.data as any)?.timeCardEnabled ?? false;
- const consoleEnabled = (companySettings.data as any)?.consoleEnabled ?? false;
+ const timeCardEnabled = companySettings.data?.timeCardEnabled ?? false;
+ const consoleEnabled = companySettings.data?.consoleEnabled ?? false;
// Get active maintenance count after we have the location
const activeMaintenanceCount = await getActiveMaintenanceEventsCount(
@@ -185,7 +189,11 @@ export async function loader({ request, context }: LoaderFunctionArgs) {
effectiveUserId,
pinnedInUser,
plan: companyPlan?.planId,
+ printing:
+ (companySettings.data?.printing as PrintingSettings | null) ?? null,
+ printerRoutes: printerRoutes.data ?? [],
timeCardEnabled,
+ useMetric: companySettings.data?.useMetric ?? false,
user: user.data
},
headers.has("Set-Cookie") ? { headers } : undefined
@@ -206,7 +214,10 @@ export default function AuthenticatedRoute() {
locations,
openClockEntry,
pinnedInUser,
+ printing,
+ printerRoutes,
timeCardEnabled,
+ useMetric,
user
} = useLoaderData<typeof loader>();
@@ -243,60 +254,71 @@ export default function AuthenticatedRoute() {
/>
) : (
<CarbonProvider session={session}>
- <RealtimeDataProvider>
- <SidebarProvider defaultOpen={false}>
- <TooltipProvider delayDuration={0}>
- <AppSidebar
- activeEvents={activeEvents}
- activeMaintenanceCount={activeMaintenanceCount}
- company={company}
- companies={companies}
- consoleEnabled={consoleEnabled}
- consoleMode={consoleMode}
- location={location}
- locations={locations}
- openClockEntry={openClockEntry}
- pinnedInUser={pinnedInUser}
- timeCardEnabled={timeCardEnabled}
- />
- <Outlet />
- {timeCardEnabled && (
- <Suspense fallback={null}>
- <Await resolve={openClockEntry}>
- {(resolved) => (
- <TimeCardWarning
- openClockEntry={
- resolved?.data
- ? {
- id: resolved.data.id,
- clockIn: resolved.data.clockIn
- }
- : null
- }
- />
- )}
- </Await>
- </Suspense>
- )}
- {consoleMode && !pinnedInUser && (
- <PinInOverlay
- companyId={company.companyId!}
- locationEmployeeIds={locationEmployeeIds}
- sessionUserId={user?.id ?? ""}
- hasPinnedUser={false}
+ <PrintingProvider
+ value={{
+ printing,
+ printerRoutes,
+ useMetric,
+ printPath: path.to.manualPrint,
+ settingsPath: path.to.printingSettings,
+ settingsExternal: true
+ }}
+ >
+ <RealtimeDataProvider>
+ <SidebarProvider defaultOpen={false}>
+ <TooltipProvider delayDuration={0}>
+ <AppSidebar
+ activeEvents={activeEvents}
+ activeMaintenanceCount={activeMaintenanceCount}
+ company={company}
+ companies={companies}
+ consoleEnabled={consoleEnabled}
+ consoleMode={consoleMode}
+ location={location}
+ locations={locations}
+ openClockEntry={openClockEntry}
+ pinnedInUser={pinnedInUser}
+ timeCardEnabled={timeCardEnabled}
/>
- )}
- {consoleMode && pinnedInUser && (
- <ConsolePill
- user={pinnedInUser}
- companyId={company.companyId!}
- locationEmployeeIds={locationEmployeeIds}
- sessionUserId={user?.id ?? ""}
- />
- )}
- </TooltipProvider>
- </SidebarProvider>
- </RealtimeDataProvider>
+ <Outlet />
+ {timeCardEnabled && (
+ <Suspense fallback={null}>
+ <Await resolve={openClockEntry}>
+ {(resolved) => (
+ <TimeCardWarning
+ openClockEntry={
+ resolved?.data
+ ? {
+ id: resolved.data.id,
+ clockIn: resolved.data.clockIn
+ }
+ : null
+ }
+ />
+ )}
+ </Await>
+ </Suspense>
+ )}
+ {consoleMode && !pinnedInUser && (
+ <PinInOverlay
+ companyId={company.companyId!}
+ locationEmployeeIds={locationEmployeeIds}
+ sessionUserId={user?.id ?? ""}
+ hasPinnedUser={false}
+ />
+ )}
+ {consoleMode && pinnedInUser && (
+ <ConsolePill
+ user={pinnedInUser}
+ companyId={company.companyId!}
+ locationEmployeeIds={locationEmployeeIds}
+ sessionUserId={user?.id ?? ""}
+ />
+ )}
+ </TooltipProvider>
+ </SidebarProvider>
+ </RealtimeDataProvider>
+ </PrintingProvider>
</CarbonProvider>
)}
</div>
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 58bb4c37c2..9fa5ebfdaf 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -3,6 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { trigger } from "@carbon/jobs";
+import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
import type { ActionFunctionArgs } from "react-router";
import { data, redirect } from "react-router";
import { nonScrapQuantityValidator } from "~/services/models";
@@ -12,6 +14,68 @@ import {
} from "~/services/operations.service";
import { path } from "~/utils/path";
+/**
+ * Triggers an auto-print of the entity's label when this is its first
+ * operation (i.e. the entity was just minted) and the work center's
+ * printer assignment has auto-print enabled.
+ */
+async function autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId,
+ workCenterId,
+ companyId,
+ userId
+}: {
+ serviceRole: ReturnType<typeof getCarbonServiceRole>;
+ trackedEntityId: string;
+ workCenterId: string | undefined;
+ companyId: string;
+ userId: string;
+}) {
+ try {
+ const { data: entity } = await serviceRole
+ .from("trackedEntity")
+ .select("attributes")
+ .eq("id", trackedEntityId)
+ .single();
+
+ const attributes = (entity?.attributes ?? {}) as Record<string, unknown>;
+ const operationCount = Object.keys(attributes).filter((k) =>
+ k.startsWith("Operation ")
+ ).length;
+ if (operationCount > 1) return;
+
+ if (!workCenterId) return;
+ const { data: workCenter } = await serviceRole
+ .from("workCenter")
+ .select("locationId")
+ .eq("id", workCenterId)
+ .single();
+ const locationId = workCenter?.locationId ?? undefined;
+ if (!locationId) return;
+
+ const config = await getCachedPrinterConfig(
+ serviceRole,
+ companyId,
+ locationId,
+ "workCenter",
+ workCenterId
+ );
+ if (config?.autoPrint ?? true) {
+ await trigger("print-job", {
+ sourceDocument: "Job",
+ sourceDocumentId: trackedEntityId,
+ companyId,
+ userId,
+ locationId,
+ workCenterId
+ });
+ }
+ } catch (e) {
+ console.error("Auto-print failed:", e);
+ }
+}
+
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {});
@@ -66,6 +130,23 @@ export async function action({ request }: ActionFunctionArgs) {
}
});
+ const newTrackedEntityId = response.data?.newTrackedEntityId;
+ // Print the entity that was just completed (from form), not the new reserved one
+ const completedEntityId = validation.data.trackedEntityId;
+
+ // Auto-print label on first operation only (entity was just minted)
+ const printEntityId = completedEntityId || newTrackedEntityId;
+ if (printEntityId) {
+ await autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId: printEntityId,
+ workCenterId: jobOperation.data.workCenterId ?? undefined,
+ companyId,
+ userId
+ });
+ }
+
+ const trackedEntityId = newTrackedEntityId;
if (response.error) {
return data(
{},
@@ -76,8 +157,6 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- const trackedEntityId = response.data?.newTrackedEntityId;
-
if (willBeFinished) {
const finishOperation = await finishJobOperation(serviceRole, {
jobOperationId: jobOperation.data.id,
@@ -114,7 +193,6 @@ export async function action({ request }: ActionFunctionArgs) {
return redirect(`${path.to.operation(validation.data.jobOperationId)}`);
} else if (validation.data.trackingType === "Batch") {
- const serviceRole = await getCarbonServiceRole();
const response = await serviceRole.functions.invoke("issue", {
body: {
type: "jobOperationBatchComplete",
@@ -134,6 +212,17 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
+ // Auto-print label on first operation only (batch entity was just minted)
+ if (validation.data.trackedEntityId) {
+ await autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId: validation.data.trackedEntityId,
+ workCenterId: jobOperation.data.workCenterId ?? undefined,
+ companyId,
+ userId
+ });
+ }
+
if (willBeFinished) {
const finishOperation = await finishJobOperation(serviceRole, {
jobOperationId: jobOperation.data.id,
diff --git a/apps/mes/app/routes/x+/issue-tracked-entity.tsx b/apps/mes/app/routes/x+/issue-tracked-entity.tsx
index e367e75c6f..e6f7be4509 100644
--- a/apps/mes/app/routes/x+/issue-tracked-entity.tsx
+++ b/apps/mes/app/routes/x+/issue-tracked-entity.tsx
@@ -1,6 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { trigger } from "@carbon/jobs";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { issueTrackedEntityValidator } from "~/services/models";
@@ -70,6 +71,43 @@ export async function action({ request }: ActionFunctionArgs) {
const splitEntities = issue.data?.splitEntities || [];
const warning = issue.data?.warning as string | undefined;
+ // Auto-print labels for split entities
+ if (splitEntities.length > 0) {
+ try {
+ let locationId: string | undefined;
+ let workCenterId: string | undefined;
+ if (jobOperationId) {
+ const { data: op } = await serviceRole
+ .from("jobOperation")
+ .select("workCenterId")
+ .eq("id", jobOperationId)
+ .single();
+ workCenterId = op?.workCenterId ?? undefined;
+ }
+ if (workCenterId) {
+ const { data: wc } = await serviceRole
+ .from("workCenter")
+ .select("locationId")
+ .eq("id", workCenterId)
+ .single();
+ locationId = wc?.locationId ?? undefined;
+ }
+
+ for (const split of splitEntities) {
+ await trigger("print-job", {
+ sourceDocument: "Split",
+ sourceDocumentId: split.newId,
+ companyId,
+ userId,
+ locationId,
+ workCenterId
+ });
+ }
+ } catch (e) {
+ console.error("Auto-print for split entities failed:", e);
+ }
+ }
+
return {
success: true,
message: "Material issued successfully",
diff --git a/apps/mes/app/routes/x+/print.tsx b/apps/mes/app/routes/x+/print.tsx
new file mode 100644
index 0000000000..6b96b6fb69
--- /dev/null
+++ b/apps/mes/app/routes/x+/print.tsx
@@ -0,0 +1,43 @@
+import { assertIsPost } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { trigger } from "@carbon/jobs";
+import { manualPrintValidator } from "@carbon/printing";
+import type { ActionFunctionArgs } from "react-router";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {});
+
+ const json = await request.json();
+ const validation = manualPrintValidator.safeParse(json);
+
+ if (!validation.success) {
+ return { success: false, message: "Invalid print request" };
+ }
+
+ const {
+ sourceDocument,
+ sourceDocumentId,
+ locationId,
+ workCenterId,
+ printerRouteId
+ } = validation.data;
+
+ try {
+ await trigger("print-job", {
+ sourceDocument,
+ sourceDocumentId,
+ companyId,
+ userId,
+ locationId,
+ workCenterId,
+ printerRouteId
+ });
+ return { success: true, message: "Print job queued" };
+ } catch (e) {
+ return {
+ success: false,
+ message: e instanceof Error ? e.message : "Failed to queue print job"
+ };
+ }
+}
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index ce2102e8c1..341ff45bd8 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -115,6 +115,7 @@ export const path = {
issueTrackedEntity: `${x}/issue-tracked-entity`,
qualityIssueNew: `${x}/quality-issue/new`,
location: `${x}/location`,
+ manualPrint: `${x}/print`,
login: "/login",
logout: "/logout",
maintenance: `${x}/maintenance`,
@@ -127,6 +128,7 @@ export const path = {
messagingNotify: `${x}/proxy/api/messaging/notify`,
newMaintenanceDispatch: `${x}/dispatch/new`,
onboarding: `${ERP_URL}/onboarding`,
+ printingSettings: `${ERP_URL}/x/settings/printing`,
operation: (id: string) => generatePath(`${x}/operation/${id}`),
operations: `${x}/operations?saved=1`,
productionEvent: `${x}/event`,
diff --git a/apps/mes/package.json b/apps/mes/package.json
index 126a05c5da..fa9009b2f3 100644
--- a/apps/mes/package.json
+++ b/apps/mes/package.json
@@ -12,6 +12,7 @@
"@carbon/lib": "workspace:*",
"@carbon/locale": "workspace:*",
"@carbon/notifications": "workspace:*",
+ "@carbon/printing": "workspace:*",
"@carbon/react": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
diff --git a/docs/superpowers/specs/2026-05-09-printing-settings-redesign.md b/docs/superpowers/specs/2026-05-09-printing-settings-redesign.md
new file mode 100644
index 0000000000..787bfcd861
--- /dev/null
+++ b/docs/superpowers/specs/2026-05-09-printing-settings-redesign.md
@@ -0,0 +1,152 @@
+# Printing Settings UI Redesign
+
+## Summary
+
+Replace the current multi-card printing settings page with a two-section layout: a printers list at top, and an assignment tree below that shows every location with its shipping, receiving, and work center rows. The tree makes it immediately obvious which printer handles any given print job, where printers are missing, and where inheritance is in effect.
+
+## Data Model Changes
+
+### PrintingSettings type (replaces current structure)
+
+```typescript
+type PrintingSettings = {
+ assignments: Record<string, LocationAssignment>;
+ // keyed by locationId
+};
+
+type LocationAssignment = {
+ defaultPrinterRouteId: string | null;
+ defaultAutoPrint: boolean;
+ shipping: ContextAssignment;
+ receiving: ContextAssignment;
+ workCenters: Record<string, ContextAssignment>;
+ // workCenters keyed by workCenterId
+};
+
+type ContextAssignment = {
+ printerRouteId: string | null; // null = inherit from location default
+ autoPrint: boolean;
+};
+```
+
+### PrinterRoute table changes
+
+Add `templateId` column (text, nullable) to the `printerRoute` table. This replaces the per-document-type template assignment.
+
+Remove: `autoPrint` from companySettings.printing (now per-row in assignments). Remove: `locationOverrides`, `workCenterOverrides`, `assignments` (old shape) from companySettings.printing.
+
+## UI Structure
+
+### Page Layout
+
+```
+┌─────────────────────────────────────────────┐
+│ Printing [View Prints] │
+├─────────────────────────────────────────────┤
+│ Printers [+ Add Printer] │
+│ ┌─────────────────────────────────────────┐ │
+│ │ Zebra 4x6 ZPL label4x6 https://... │ │
+│ │ Zebra 2x1 ZPL label2x1 https://... │ │
+│ │ HP LaserJet PDF https://... │ │
+│ └─────────────────────────────────────────┘ │
+├─────────────────────────────────────────────┤
+│ Assignments │
+│ │
+│ Main Warehouse Zebra 4x6 [auto] │
+│ Shipping Zebra 2x1 [auto] │
+│ Receiving inherits 4x6 [auto] │
+│ WC Assembly Line 1 Zebra 2x1 [auto] │
+│ WC Pack Station inherits 4x6 [auto] │
+│ │
+│ East Facility ⚠ No printer [auto] │
+│ Shipping ⚠ No printer [auto] │
+│ Receiving ⚠ No printer [auto] │
+│ WC Inspection ⚠ No printer [auto] │
+└─────────────────────────────────────────────┘
+```
+
+### Printers Section
+
+A card with a list of physical printers. Each row shows:
+- Printer name (font-medium)
+- Format badge (uppercase, muted)
+- Media size (muted, if set)
+- URL (monospace, muted, truncated)
+- Template ID (muted, if set)
+- Actions: dropdown menu with Test, Edit, Delete
+
+"Add Printer" button opens a modal with fields: name, format, media size, location, printer URL, API key, template ID.
+
+### Assignments Section
+
+A card with the full assignment tree. The tree is built from all locations, with their work centers nested underneath.
+
+**Row structure:** Each row is a flex container with:
+- Left: context label (location name bold at top level, "Shipping"/"Receiving"/WC name indented)
+- Right: printer assignment + auto-print toggle
+
+**Work center prefix:** Work center rows show a "WC" label in small muted text before the name, to visually distinguish them from shipping/receiving.
+
+**Indentation:** Shipping, receiving, and work center rows are indented with `pl-7` (28px).
+
+### Printer Assignment States
+
+Each assignment cell has three visual states:
+
+1. **Explicitly assigned** — printer name shown in normal text. Clickable to change via inline dropdown.
+2. **Inherited** — "inherits [printer name]" in italic muted text. Clickable to set an explicit override.
+3. **No printer** — warning icon + "No printer" in destructive/red text. Clickable to assign. This appears when no printer is set AND the location has no default to inherit from.
+
+### Inline Editing
+
+Clicking any printer assignment (in any state) converts that cell to a Select dropdown populated with available printers, plus a "None" option to clear an override (which reverts to inheritance). The dropdown saves immediately on selection (no save button needed).
+
+### Auto-Print Toggle
+
+Each row has a Switch/toggle on the right side. This controls whether labels auto-print for that context. The toggle saves immediately on change.
+
+### Inheritance Logic
+
+- Shipping/receiving/work center rows inherit from their location's default printer.
+- If a row has an explicit `printerRouteId`, that's used (shown as assigned).
+- If a row's `printerRouteId` is null, it inherits the location default (shown as "inherits X").
+- If a row's `printerRouteId` is null AND the location default is also null, it shows the warning state.
+
+## Action Intents
+
+The page action handler supports these intents:
+
+| Intent | Fields | Description |
+|--------|--------|-------------|
+| `upsertRoute` | id?, name, format, mediaSizeId, printerUrl, apiKey?, locationId?, templateId? | Create or update a printer |
+| `testPrint` | routeId | Send test label to printer |
+| `updateAssignment` | locationId, context, contextId?, printerRouteId?, autoPrint? | Update a single assignment row |
+
+The `context` field is one of: `default`, `shipping`, `receiving`, `workCenter`. When context is `workCenter`, `contextId` is the work center ID.
+
+`updateAssignment` reads the current printing settings, merges the change into the correct location/context, and writes back. This replaces the old separate intents for location overrides, work center overrides, and auto-print.
+
+Printer deletion continues to use the existing `printing.$id.delete.tsx` child route.
+
+## Loader Data
+
+The loader fetches:
+- `companySettings` (for printing JSON)
+- `printerRoutes` (list of printers)
+- `locations` (all locations)
+- `workCenters` (all work centers — grouped by locationId on the client)
+
+Work centers are grouped by `locationId` client-side to build the tree.
+
+## Migration Notes
+
+- Add `templateId` column to `printerRoute` table.
+- Migrate existing `assignments[docType].templateId` values to the corresponding printer's `templateId` column.
+- Migrate existing `locationOverrides`, `workCenterOverrides`, and `autoPrint` data into the new `assignments` shape in the printing JSONB column.
+- Old shape can be dropped after migration.
+
+## Out of Scope
+
+- Kanban card document type (deferred)
+- Per-document-type assignments (simplified to product labels only)
+- Template management UI (just a text field on the printer for now)
diff --git a/lingui.config.js b/lingui.config.js
index 3c2fb166b3..fe98c8a71f 100644
--- a/lingui.config.js
+++ b/lingui.config.js
@@ -14,12 +14,22 @@ export default defineConfig({
catalogs: [
{
path: "packages/locale/locales/{locale}/erp",
- include: ["apps/erp/app", "packages/react/src", "packages/form/src"],
+ include: [
+ "apps/erp/app",
+ "packages/react/src",
+ "packages/form/src",
+ "packages/printing/src/ui"
+ ],
exclude: ["**/*.server.*", "**/*.test.*", "**/*.spec.*"]
},
{
path: "packages/locale/locales/{locale}/mes",
- include: ["apps/mes/app", "packages/react/src", "packages/form/src"],
+ include: [
+ "apps/mes/app",
+ "packages/react/src",
+ "packages/form/src",
+ "packages/printing/src/ui"
+ ],
exclude: ["**/*.server.*", "**/*.test.*", "**/*.spec.*"]
}
]
diff --git a/llm/cache/database-patterns.md b/llm/cache/database-patterns.md
index 2aa3e7704a..c5ce3a6008 100644
--- a/llm/cache/database-patterns.md
+++ b/llm/cache/database-patterns.md
@@ -156,3 +156,9 @@ return data;
- Applied automatically via Supabase CLI
+
+## Generated DB Types
+
+- `packages/database/src/types.ts` and `packages/database/supabase/functions/lib/types.ts` are generated — never hand-edit.
+- Regenerate with `pnpm run db:types` (root script, `scripts/generate-db-types.ts`). Requires the local Supabase DB running (`SUPABASE_DB_URL` in `.env`/`.env.local`, localhost only) with all migrations applied.
+- After merging branches that add migrations, regenerate types or typecheck will fail with `SelectQueryError` / "excessively deep" errors in packages that query the new tables.
diff --git a/llm/cache/mes-job-operation-ui.md b/llm/cache/mes-job-operation-ui.md
index 65e4028240..e1c62759b3 100644
--- a/llm/cache/mes-job-operation-ui.md
+++ b/llm/cache/mes-job-operation-ui.md
@@ -90,7 +90,7 @@ Displays job-related files with:
Only visible when `parentIsSerial` is true:
- Lists tracked entities
-- Print label button
+- `PrintButton` (shared component from `~/components`) with sourceDocument="Operation" and context="workCenter" — sends to a configured printer via `/x/print`, or falls back to a label download modal when no printers are configured (see `llm/cache/printing-system.md`)
- Select button for each serial
## Modals
diff --git a/llm/cache/printing-system.md b/llm/cache/printing-system.md
new file mode 100644
index 0000000000..a23e6788f1
--- /dev/null
+++ b/llm/cache/printing-system.md
@@ -0,0 +1,118 @@
+# Printing System
+
+## Overview
+
+The Print Manager is a centralized print job queue at `packages/printing/` (`@carbon/printing`). Full design doc at `packages/printing/printing-integration.md`.
+
+## Key Packages
+
+- **@carbon/printing** (`packages/printing/`) — Print job queue, delivery, routing, document type registry, settings management, BinderyPress client, Redis printer-config cache. Two entry points:
+ - `@carbon/printing` (`src/index.ts`) — isomorphic: validators, registry, service functions, types
+ - `@carbon/printing/printing.server` (`src/printing.server.ts`) — server-only: `getCachedPrinterConfig`, `invalidatePrinterCache`, `sendToProxyBox`, `renderWithBinderyPress`
+- **@carbon/documents** (`packages/documents/`) — PDF and ZPL renderers (SalesInvoicePDF, KanbanLabelPDF, ProductLabelZPL, StorageUnitLabelZPL, PackingSlipPDF, etc.). The print system's built-in renderers call into this package for actual content generation.
+
+## Architecture
+
+Two Inngest tasks (triggered via `trigger("print-job", payload)` from `@carbon/jobs`; event payloads defined in `packages/lib/src/events.ts`):
+
+- **print-job** (`packages/jobs/src/inngest/functions/tasks/print-job.tsx`) — Content generation. Payload: `{ sourceDocument, sourceDocumentId, companyId, userId, locationId?, workCenterId?, printerRouteId? }`. 30-second dedupe: skips if an `origin = "auto"` printJob for the same sourceDocumentId was created in the last 30s. Resolves printer config once up front:
+ 1. If `printerRouteId` is passed (manual print), fetches that route directly.
+ 2. Else derives a context from sourceDocument (Shipment → shipping, Receipt → receiving, StockTransfer/StorageUnit → inventory, else workCenter if workCenterId present, else default) and calls `getCachedPrinterConfig`.
+ Falls back to `docType.defaultFormat` and mediaSizeId `"label2x1"` when no printer is configured. Per-item streaming: creates job with `generating` status (visible immediately), renders content via built-in renderer or BinderyPress (when route has a templateId), updates job with content (→ `queued`), triggers delivery.
+- **print-job-deliver** (`packages/jobs/src/inngest/functions/tasks/print-job-deliver.ts`) — Delivery. Sends content to printer via ProxyBox HTTP POST (`sendToProxyBox` from `@carbon/printing/printing.server`).
+
+## Document Type Registry
+
+`packages/printing/src/registry.ts` — Defines `DocumentTypeDefinition` entries. Currently:
+- `productLabel` — ZPL, sources: Receipt, Shipment, Operation, Entity, Job, Split, StockTransfer
+- `kanbanCard` — PDF, sources: Kanban
+- `storageUnitLabel` — ZPL, sources: StorageUnit ("Labels for shelves, bins, and storage locations")
+
+Each type has a data resolver in print-job.tsx (`resolvers` map: productLabel → resolveTrackedEntityData, kanbanCard → resolveKanbanData, storageUnitLabel → resolveStorageUnitData) and a built-in render branch. Adding a new type: add registry entry + resolver + renderer branch.
+
+## Database Tables
+
+- **printerRoute** — Printer definitions. Columns: id(pr), companyId, locationId, name, format(zpl/pdf), mediaSizeId, printerUrl, apiKey, templateId, createdAt, updatedAt. Unique on (companyId, COALESCE(locationId,''), name).
+- **printJob** — Job queue + audit trail. Columns: id(pj), companyId, status(generating/queued/printing/completed/failed), contentType(zpl/pdf, nullable), content(nullable), printerUrl, sourceDocument, sourceDocumentId, sourceDocumentReadableId, description, origin(auto/manual/reprint), error, attempts, createdBy, createdAt, updatedAt, updatedBy, completedAt. Realtime-enabled.
+
+## PrintingSettings (JSONB on companySettings.printing)
+
+Per-location assignments with per-context printer + auto-print:
+
+```typescript
+type ContextAssignment = { printerRouteId: string | null; autoPrint: boolean };
+type LocationAssignment = {
+ defaultPrinterRouteId: string | null;
+ defaultAutoPrint: boolean;
+ shipping: ContextAssignment;
+ receiving: ContextAssignment;
+ inventory: ContextAssignment;
+ workCenters: Record<string, ContextAssignment>; // keyed by workCenterId
+};
+type PrintingSettings = { assignments: Record<string, LocationAssignment> }; // keyed by locationId
+```
+
+Contexts (`updateAssignmentValidator` in models.ts): `default | shipping | receiving | inventory | workCenter`.
+
+## Printer Route Resolution
+
+Context assignment's printerRouteId first; if null, falls back to the location's `defaultPrinterRouteId`. Resolution happens in two places that must stay in sync:
+- Server: `resolvePrinterConfig` in `packages/printing/src/cache.server.ts`
+- Client: `resolvePrinterRoute` in `apps/{erp,mes}/app/hooks/usePrinting.tsx`
+
+## Redis Printer Config Cache
+
+`packages/printing/src/cache.server.ts` (uses `@carbon/kv` redis):
+- `getCachedPrinterConfig(client, companyId, locationId, context, contextId?)` → `CachedPrinterConfig { printerRouteId, printerUrl, format, mediaSizeId, templateId, autoPrint }`. Cache key `printing:{companyId}:{locationId}:{context}` (workCenter: `wc:{contextId}`), TTL 1 hour. Redis failures fall through to DB silently.
+- `invalidatePrinterCache(companyId)` — deletes `printing:{companyId}:*`. Called from the printing settings action (printer upsert, assignment update) and `printing.$id.delete.tsx`.
+
+## Module Structure (packages/printing/src/)
+
+- `types.ts` — PrintingSettings, LocationAssignment, ContextAssignment, PrinterRoute, PrintJob, status/origin/contentType unions
+- `registry.ts` — documentTypeRegistry, getDocumentTypesForSource(), getDocumentType(), getDocumentTypeOptions()
+- `service.ts` — DB functions: getPrintJobs, getPrintJob, getPrintJobContent, createPrintJob (defaults to generating status, null content), updatePrintJobContent (sets content, transitions to queued), updatePrintJobStatus, getPrinterRoutes, getPrinterRoute, upsertPrinterRoute, deletePrinterRoute, getPrintingSettings, updatePrintingSettings
+- `models.ts` — Zod validators: printerRouteValidator (includes templateId), updateAssignmentValidator, reprintValidator
+- `cache.server.ts` — Redis printer-config cache (see above)
+- `delivery/proxybox.ts` — sendToProxyBox() HTTP POST
+- `generation/binderypress.ts` — renderWithBinderyPress() calls https://api.binderypress.dev/v1/render
+
+## Client-Side Printing (ERP and MES, mirrored)
+
+- Root layouts (`apps/{erp,mes}/app/routes/x+/_layout.tsx`) load `getPrinterRoutes` and expose `printerRoutes` in route data.
+- **usePrinting** (`apps/{erp,mes}/app/hooks/usePrinting.tsx`) — reads `companySettings.printing` + `printerRoutes` from the authenticated root route data. Returns `{ printing, printerRoutes, resolvePrinterRoute(locationId, context, workCenterId?), hasPrinter(...) }`.
+- **PrintButton** (`apps/{erp,mes}/app/components/PrintButton.tsx`) — props: sourceDocument, sourceDocumentId, locationId, context (shipping/receiving/inventory/workCenter), workCenterId?, fileRoutes ({pdf, zpl} URL builders). If any printer routes exist: opens a printer-select modal (pre-selects the resolved route) and POSTs JSON to `path.to.manualPrint`. If no printers configured: falls back to **LabelDownloadModal** (download ZPL/PDF at a chosen label size from `labelSizes` in `@carbon/utils`, via the fileRoutes prop).
+- **Manual print route** (`apps/{erp,mes}/app/routes/x+/print.tsx`, `path.to.manualPrint` = `/x/print`) — POST JSON `{ sourceDocument, sourceDocumentId, locationId?, workCenterId?, printerRouteId? }` → `trigger("print-job", ...)`. Returns `{ success, message }`.
+- PrintButton replaced the old "Tracking Labels" download dropdowns in: ReceiptForm, ShipmentForm, StockTransferHeader, StorageUnitForm, JobMakeMethodTools (ERP); JobOperation, IssueMaterialModal (MES).
+- **StorageUnitsTable** (`apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx`) — tree multi-select with checkboxes (children inherit parent selection); bulk "Print N Labels" opens a printer-select modal (one manualPrint POST per selected id) or falls back to label download when no printers exist.
+
+## Label File Routes (ERP)
+
+- `apps/erp/app/routes/file+/stock-transfer+/$id.labels[.]zpl.tsx` / `$id.labels[.]pdf.tsx` — product labels for tracked entities on stock transfer lines; optional `lineId` query param; ZPL route redirects to the PDF route if the label size has no ZPL config. Shared data fetch in `labels.server.ts` (`getStockTransferLabelItems`).
+- `apps/erp/app/routes/file+/storage-unit+/labels[.]zpl.tsx` / `labels[.]pdf.tsx` — `?ids=` comma-separated storage unit ids; renders name-only labels via `generateStorageUnitLabelZPL` (`packages/documents/src/zpl/StorageUnitLabelZPL.tsx`).
+- Path helpers: `path.to.file.stockTransferLabelsPdf/Zpl(id, { labelSize, lineId })`, `path.to.file.storageUnitLabelsZpl/Pdf(ids, { labelSize })`.
+
+## Settings UI
+
+`apps/erp/app/routes/x+/settings+/printing.tsx` (`path.to.printingSettings`) — two cards: Printers (CRUD + test print) and Assignments (per-location rows: Default, Shipping, Receiving, Inventory, and one row per Work Center — each with a printer select and auto-print toggle). Actions invalidate the Redis printer cache. "View Prints" links to the jobs page.
+
+The old standalone label-size settings page (`x+/settings+/labels.tsx`) was removed.
+
+## Print Jobs UI
+
+`apps/erp/app/routes/x+/settings+/printing.jobs.tsx` (`path.to.printingSettingsJobs`) — PrintJobsTable with status/origin/sourceDocument/contentType filters, view content drawer, reprint (creates a new job with origin `reprint`), realtime updates via `useRealtime`. (The former standalone `x+/print-manager.tsx` route no longer exists.)
+
+## Business Event Integration Points (auto-print)
+
+All check `getCachedPrinterConfig(...).autoPrint` (default true) before triggering, wrapped in try/catch that never blocks the parent operation:
+
+- Receipt posting: `apps/erp/app/routes/x+/receipt+/$receiptId.post.tsx` (receiving context)
+- Shipment posting: `apps/erp/app/routes/x+/shipment+/$shipmentId.post.tsx` (shipping context)
+- MES serial/batch completion: `apps/mes/app/routes/x+/complete.tsx` (workCenter context)
+- Stock transfer batch splits: `apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx` and `$id.scan.$lineId.tsx` — print the new Split entity AND reprint the original Entity (its quantity changed), passing locationId
+- Other trigger sites: `apps/erp/app/routes/x+/maintenance+/$dispatchId.add-and-issue.tsx`, `apps/mes/app/routes/x+/issue-tracked-entity.tsx`
+
+Dedupe is handled inside the print-job task (30-second window on auto jobs per sourceDocumentId).
+
+## Cleanup
+
+In `packages/jobs/src/inngest/functions/scheduled/cleanup.ts`: completed jobs > 30 days deleted, failed jobs > 90 days deleted.
diff --git a/llm/tasks/todo.md b/llm/tasks/todo.md
index 00ca71b79c..6f771514c7 100644
--- a/llm/tasks/todo.md
+++ b/llm/tasks/todo.md
@@ -1,40 +1,62 @@
-# Fix Lingui SSR crash ("Attempted to call a translation function without setting a locale")
+# 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
-## Root cause
-
-19 ERP route files use the `t` macro from `@lingui/core/macro` at render time. That macro
-compiles to `i18n._()` on the **global** i18n singleton from `@lingui/core`, which is never
-activated anywhere (server or client) — only `LocaleProvider`'s context-scoped instance
-(`packages/locale/src/i18n.tsx`) is activated. SSR on Vercel crashes when rendering any of
-these routes (user hit it on /x/settings/company). `msg` descriptors in `handle` exports and
-`<Trans>` components are unaffected (descriptor-only / context-bound).
-
-## Fix
-
-Replace render-time global `t` with the context-bound `t` from `useLingui()`
-(`@lingui/react/macro`) — the pattern already used by ~dozens of components
-(e.g. apps/erp/app/components/Breadcrumb.tsx).
+## Review
-## Tasks
+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
-- [x] Convert batch 1: settings/company, settings/billing, settings/labels, settings/production, settings/quality (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.)
-- [x] Convert batch 2: settings/sales, settings/purchasing, settings/inventory, settings/resources, quality/_index (same cache rule)
-- [x] Convert batch 3: tool/$itemId, part/$itemId, issue/$id, traceability/_index, users/operators (same cache rule)
-- [x] Convert batch 4: schedule/dates, schedule/operations, resources/assignments, resources/assignments.$trainingId (same cache rule)
-- [x] Verify: no remaining render-time `t` from @lingui/core/macro in apps; spot-check diffs (same cache rule)
+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.
-## Review
+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.
-- The initial grep was over-broad: it flagged 19 files, but 18 of them already used the
- context-bound `const { t } = useLingui()` pattern (converted in an earlier migration) and
- only imported `msg` from core/macro. **Only `settings+/company.tsx` still imported `t`
- from `@lingui/core/macro`** — the one route the user reported.
-- Fix applied (single file, apps/erp/app/routes/x+/settings+/company.tsx): import `msg`
- only from `@lingui/core/macro`, add `useLingui` to the `@lingui/react/macro` import, and
- add `const { t } = useLingui();` at the top of the `Company` component (its one `t` usage
- is the copy-button aria-label).
-- Verified by grep: no file in `apps/` or `packages/` imports `t` from
- `@lingui/core/macro` anymore.
-- Not run here: production SSR repro (needs a deploy/build); the failure mode is fully
- explained by the stack trace (`I18n._` on the never-activated global singleton during
- react-dom-server render).
+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/seed-dev.ts b/packages/database/src/seed-dev.ts
index 1059311ed4..9820129054 100644
--- a/packages/database/src/seed-dev.ts
+++ b/packages/database/src/seed-dev.ts
@@ -33,6 +33,7 @@ import {
unitOfMeasures
} from "../supabase/functions/lib/seed.data.ts";
import { getPostgresConnectionPool } from "./client.ts";
+import { seedPrinting } from "./seed-printing.ts";
import type { Database } from "./types.ts";
// Load environment variables
@@ -61,6 +62,10 @@ const { values } = parseArgs({
email: {
type: "string",
short: "e"
+ },
+ printing: {
+ type: "boolean",
+ default: false
}
},
strict: true
@@ -68,13 +73,15 @@ const { values } = parseArgs({
function printUsage() {
console.log(`
-Usage: pnpm run db:seed:dev -- --email <email>
+Usage: pnpm run db:seed:dev -- --email <email> [--printing]
Arguments:
--email, -e Required. The email address for the dev user.
+ --printing Optional. Seed printing test data (printer routes, receipts, etc.).
Example:
pnpm run db:seed:dev -- --email [email protected]
+ pnpm run db:seed:dev -- --email [email protected] --printing
`);
}
@@ -582,6 +589,12 @@ async function seedDev() {
console.log(" User permissions updated.");
+ // Seed printing test data (opt-in via --printing flag)
+ if (values.printing) {
+ console.log("8. Seeding printing test data...");
+ await seedPrinting(client, { companyId, userId, locationId });
+ }
+
// Commit the transaction
await client.query("COMMIT");
console.log(" Transaction committed successfully.");
diff --git a/packages/database/src/seed-printing.ts b/packages/database/src/seed-printing.ts
new file mode 100644
index 0000000000..89dd9faef7
--- /dev/null
+++ b/packages/database/src/seed-printing.ts
@@ -0,0 +1,559 @@
+/**
+ * Printing seed data for Carbon
+ *
+ * Seeds test data for the Print Manager: printer routes, printing settings,
+ * items with tracking, receipts, shipments, kanbans, jobs, and a second
+ * location with a location override for testing printer routing.
+ *
+ * This is called within an existing transaction — do NOT commit or rollback.
+ *
+ * Usage:
+ * import { seedPrinting } from "./seed-printing.ts";
+ * await seedPrinting(client, { companyId, userId, locationId });
+ */
+
+import type { PoolClient } from "pg";
+
+export async function seedPrinting(
+ client: PoolClient,
+ ctx: {
+ companyId: string;
+ userId: string;
+ locationId: string;
+ }
+) {
+ const { companyId, userId, locationId } = ctx;
+
+ console.log(" Seeding printing test data...");
+
+ // --- Shared test data ---
+
+ // Supplier
+ const supplierResult = await client.query(
+ `INSERT INTO supplier (name, "companyId", "createdBy") VALUES ($1, $2, $3) RETURNING id`,
+ ["Test Parts Supplier", companyId, userId]
+ );
+ const supplierId = supplierResult.rows[0].id;
+
+ // Customer (for shipments)
+ const customerResult = await client.query(
+ `INSERT INTO customer (name, "companyId", "createdBy") VALUES ($1, $2, $3) RETURNING id`,
+ ["Test Customer", companyId, userId]
+ );
+ const customerId = customerResult.rows[0].id;
+
+ // Items
+ const itemDefs = [
+ {
+ readableId: "WIDGET-001",
+ name: "Precision Widget",
+ trackingType: "Serial",
+ replenishment: "Buy"
+ },
+ {
+ readableId: "BRACKET-002",
+ name: "Mounting Bracket",
+ trackingType: "Serial",
+ replenishment: "Buy"
+ },
+ {
+ readableId: "FASTENER-003",
+ name: "Hex Fastener Kit",
+ trackingType: "Batch",
+ replenishment: "Buy"
+ },
+ {
+ readableId: "GEAR-004",
+ name: "Drive Gear Assembly",
+ trackingType: "Serial",
+ replenishment: "Make"
+ }
+ ];
+
+ const methodTypeMap: Record<string, string> = {
+ Buy: "Purchase to Order",
+ Make: "Make to Order"
+ };
+
+ const itemIds: string[] = [];
+ for (const item of itemDefs) {
+ const result = await client.query(
+ `INSERT INTO item (
+ "readableId", name, type, "replenishmentSystem", "defaultMethodType",
+ "itemTrackingType", "unitOfMeasureCode", active, "companyId", "createdBy"
+ ) VALUES ($1, $2, 'Part', $3, $4, $5, 'EA', true, $6, $7) RETURNING id`,
+ [
+ item.readableId,
+ item.name,
+ item.replenishment,
+ methodTypeMap[item.replenishment] ?? "Pull from Inventory",
+ item.trackingType,
+ companyId,
+ userId
+ ]
+ );
+ itemIds.push(result.rows[0].id);
+ }
+
+ // Item costs (required by post-receipt and post-shipment)
+ for (const itemId of itemIds) {
+ await client.query(
+ `INSERT INTO "itemCost" ("itemId", "costingMethod", "companyId", "createdBy") VALUES ($1, 'Standard', $2, $3)`,
+ [itemId, companyId, userId]
+ );
+ }
+
+ // Supplier interaction (required FK for purchase orders)
+ const siResult = await client.query(
+ `INSERT INTO "supplierInteraction" ("companyId", "supplierId") VALUES ($1, $2) RETURNING id`,
+ [companyId, supplierId]
+ );
+ const supplierInteractionId = siResult.rows[0].id;
+
+ // --- Flow 1: Receipt (auto-print receipt labels) ---
+ console.log(" Flow 1: Receipt RE000001...");
+
+ const poResult = await client.query(
+ `INSERT INTO "purchaseOrder" (
+ "purchaseOrderId", "supplierId", "supplierInteractionId", status, "purchaseOrderType",
+ "exchangeRate", "companyId", "createdBy"
+ ) VALUES ('PO000001', $1, $2, 'To Receive', 'Purchase', 1, $3, $4) RETURNING id`,
+ [supplierId, supplierInteractionId, companyId, userId]
+ );
+ const purchaseOrderId = poResult.rows[0].id;
+
+ await client.query(
+ `INSERT INTO "purchaseOrderDelivery" (id, "companyId") VALUES ($1, $2)`,
+ [purchaseOrderId, companyId]
+ );
+
+ // Bump sequences past the seeded data to avoid conflicts
+ await client.query(
+ `UPDATE sequence SET next = 3 WHERE "table" IN ('purchaseOrder', 'receipt') AND "companyId" = $1`,
+ [companyId]
+ );
+ await client.query(
+ `UPDATE sequence SET next = 2 WHERE "table" = 'job' AND "companyId" = $1`,
+ [companyId]
+ );
+
+ const poLineIds: string[] = [];
+ const receiptQuantities = [2, 1, 5];
+ for (let i = 0; i < 3; i++) {
+ const lineResult = await client.query(
+ `INSERT INTO "purchaseOrderLine" (
+ "purchaseOrderId", "purchaseOrderLineType", "itemId",
+ "purchaseQuantity", "quantityReceived", "quantityInvoiced",
+ "supplierUnitPrice", "supplierShippingCost", "supplierTaxAmount",
+ "exchangeRate", "setupPrice", "conversionFactor",
+ "purchaseUnitOfMeasureCode", "inventoryUnitOfMeasureCode",
+ "companyId", "createdBy"
+ ) VALUES ($1, 'Part', $2, $3, 0, 0, 10.00, 0, 0, 1, 0, 1, 'EA', 'EA', $4, $5) RETURNING id`,
+ [purchaseOrderId, itemIds[i], receiptQuantities[i], companyId, userId]
+ );
+ poLineIds.push(lineResult.rows[0].id);
+ }
+
+ const receiptResult = await client.query(
+ `INSERT INTO receipt (
+ "receiptId", "supplierId", "sourceDocument", "sourceDocumentId",
+ "locationId", status, "companyId", "createdBy"
+ ) VALUES ('RE000001', $1, 'Purchase Order', $2, $3, 'Draft', $4, $5) RETURNING id`,
+ [supplierId, purchaseOrderId, locationId, companyId, userId]
+ );
+ const receiptId = receiptResult.rows[0].id;
+
+ for (let i = 0; i < 3; i++) {
+ const trackingType = itemDefs[i]?.trackingType;
+ const isSerial = trackingType === "Serial";
+ await client.query(
+ `INSERT INTO "receiptLine" (
+ "receiptId", "lineId", "itemId", "orderQuantity", "receivedQuantity", "unitPrice",
+ "unitOfMeasure", "locationId",
+ "requiresSerialTracking", "requiresBatchTracking",
+ "companyId", "createdBy"
+ ) VALUES ($1, $2, $3, $4, $4, 10.00, 'EA', $5, $6, $7, $8, $9)`,
+ [
+ receiptId,
+ poLineIds[i],
+ itemIds[i],
+ receiptQuantities[i],
+ locationId,
+ isSerial,
+ !isSerial && trackingType === "Batch",
+ companyId,
+ userId
+ ]
+ );
+ }
+
+ // Pre-populate tracked entities for receipt (serial/batch numbers)
+ const receiptLinesResult = await client.query(
+ `SELECT id, "itemId" FROM "receiptLine" WHERE "receiptId" = $1 ORDER BY "createdAt"`,
+ [receiptId]
+ );
+ const receiptLines = receiptLinesResult.rows as {
+ id: string;
+ itemId: string;
+ }[];
+
+ const widgetLine = receiptLines.find((rl) => rl.itemId === itemIds[0]);
+ if (widgetLine) {
+ for (let i = 0; i < 2; i++) {
+ await client.query(
+ `INSERT INTO "trackedEntity" ("readableId", quantity, "sourceDocument", "sourceDocumentId", attributes, "companyId", "createdBy")
+ VALUES ($1, 1, 'Item', $2, $3, $4, $5)`,
+ [
+ `SN-W${1001 + i}`,
+ itemIds[0],
+ JSON.stringify({
+ Receipt: receiptId,
+ "Receipt Line": widgetLine.id,
+ "Receipt Line Index": i
+ }),
+ companyId,
+ userId
+ ]
+ );
+ }
+ }
+ const bracketLine = receiptLines.find((rl) => rl.itemId === itemIds[1]);
+ if (bracketLine) {
+ await client.query(
+ `INSERT INTO "trackedEntity" ("readableId", quantity, "sourceDocument", "sourceDocumentId", attributes, "companyId", "createdBy")
+ VALUES ($1, 1, 'Item', $2, $3, $4, $5)`,
+ [
+ "SN-B3001",
+ itemIds[1],
+ JSON.stringify({
+ Receipt: receiptId,
+ "Receipt Line": bracketLine.id,
+ "Receipt Line Index": 0
+ }),
+ companyId,
+ userId
+ ]
+ );
+ }
+ const fastenerLine = receiptLines.find((rl) => rl.itemId === itemIds[2]);
+ if (fastenerLine) {
+ await client.query(
+ `INSERT INTO "trackedEntity" ("readableId", quantity, "sourceDocument", "sourceDocumentId", attributes, "companyId", "createdBy")
+ VALUES ($1, 5, 'Item', $2, $3, $4, $5)`,
+ [
+ "BATCH-7042",
+ itemIds[2],
+ JSON.stringify({
+ Receipt: receiptId,
+ "Receipt Line": fastenerLine.id
+ }),
+ companyId,
+ userId
+ ]
+ );
+ }
+
+ // --- Flow 2: Shipment (auto-print shipment labels) ---
+ console.log(" Flow 2: Shipment SH000001...");
+
+ // Sales order (source document for shipment)
+ const soResult = await client.query(
+ `INSERT INTO "salesOrder" (
+ "salesOrderId", "customerId", "currencyCode", status, "companyId", "createdBy"
+ ) VALUES ('SO000001', $1, 'USD', 'To Ship', $2, $3) RETURNING id`,
+ [customerId, companyId, userId]
+ );
+ const salesOrderId = soResult.rows[0].id;
+
+ await client.query(
+ `INSERT INTO "salesOrderShipment" (id, "companyId") VALUES ($1, $2)`,
+ [salesOrderId, companyId]
+ );
+
+ await client.query(
+ `INSERT INTO "salesOrderLine" (
+ "salesOrderId", "salesOrderLineType", "itemId",
+ "saleQuantity", "unitPrice", "unitOfMeasureCode",
+ "companyId", "createdBy"
+ ) VALUES ($1, 'Part', $2, 1, 10.00, 'EA', $3, $4)`,
+ [salesOrderId, itemIds[0], companyId, userId]
+ );
+
+ const shipmentResult = await client.query(
+ `INSERT INTO shipment (
+ "shipmentId", "locationId", status, "companyId", "createdBy"
+ ) VALUES ('SH000001', $1, 'Draft', $2, $3) RETURNING id`,
+ [locationId, companyId, userId]
+ );
+ const shipmentId = shipmentResult.rows[0].id;
+
+ await client.query(
+ `INSERT INTO "shipmentLine" (
+ "shipmentId", "itemId",
+ "orderQuantity", "unitOfMeasure", "unitPrice", "locationId",
+ "requiresSerialTracking",
+ "companyId", "createdBy"
+ ) VALUES ($1, $2, 1, 'EA', 10.00, $3, true, $4, $5)`,
+ [shipmentId, itemIds[0], locationId, companyId, userId]
+ );
+
+ // Pre-populate tracked entity for shipment
+ const shipmentLinesResult = await client.query(
+ `SELECT id FROM "shipmentLine" WHERE "shipmentId" = $1 LIMIT 1`,
+ [shipmentId]
+ );
+ const shipmentLineId = shipmentLinesResult.rows[0]?.id;
+ if (shipmentLineId) {
+ await client.query(
+ `INSERT INTO "trackedEntity" ("readableId", quantity, "sourceDocument", "sourceDocumentId", attributes, "companyId", "createdBy")
+ VALUES ($1, 1, 'Item', $2, $3, $4, $5)`,
+ [
+ "SN-W1001",
+ itemIds[0],
+ JSON.stringify({
+ Shipment: shipmentId,
+ "Shipment Line": shipmentLineId,
+ "Shipment Line Index": 0
+ }),
+ companyId,
+ userId
+ ]
+ );
+ }
+
+ // --- Flow 3: Kanban (auto-print kanban cards) ---
+ console.log(" Flow 3: Kanban for FASTENER-003...");
+
+ await client.query(
+ `INSERT INTO kanban (
+ "itemId", "replenishmentSystem", quantity, "locationId",
+ "supplierId", "companyId", "createdBy"
+ ) VALUES ($1, 'Buy', 100, $2, $3, $4, $5)`,
+ [itemIds[2], locationId, supplierId, companyId, userId]
+ );
+
+ // --- Flow 4: MES Operation Completion (auto-print operation labels) ---
+ console.log(" Flow 4: Job J000001 with operation...");
+
+ const workCenterResult = await client.query(
+ `INSERT INTO "workCenter" (name, "locationId", "companyId", "createdBy") VALUES ($1, $2, $3, $4) RETURNING id`,
+ ["Assembly Station 1", locationId, companyId, userId]
+ );
+ const workCenterId = workCenterResult.rows[0].id;
+
+ const processResult = await client.query(
+ `INSERT INTO process (name, "defaultStandardFactor", "companyId", "createdBy") VALUES ($1, 'Hours/Piece', $2, $3) RETURNING id`,
+ ["Assembly", companyId, userId]
+ );
+ const processId = processResult.rows[0].id;
+
+ const jobResult = await client.query(
+ `INSERT INTO job (
+ "jobId", "itemId", quantity, "locationId", status,
+ "unitOfMeasureCode", "companyId", "createdBy"
+ ) VALUES ('J000001', $1, 2, $2, 'In Progress', 'EA', $3, $4) RETURNING id`,
+ [itemIds[3], locationId, companyId, userId]
+ );
+ const jobId = jobResult.rows[0].id;
+
+ // Get auto-created jobMakeMethod (created by DB trigger on job insert)
+ const jmmResult = await client.query(
+ `SELECT id FROM "jobMakeMethod" WHERE "jobId" = $1 LIMIT 1`,
+ [jobId]
+ );
+ let methodId: string;
+ if (jmmResult.rows.length > 0) {
+ methodId = jmmResult.rows[0].id;
+ } else {
+ const jmmInsert = await client.query(
+ `INSERT INTO "jobMakeMethod" ("jobId", "itemId", "companyId", "createdBy")
+ VALUES ($1, $2, $3, $4) RETURNING id`,
+ [jobId, itemIds[3], companyId, userId]
+ );
+ methodId = jmmInsert.rows[0].id;
+ }
+
+ const opResult = await client.query(
+ `INSERT INTO "jobOperation" (
+ "jobId", "jobMakeMethodId", "processId", "workCenterId",
+ "operationQuantity", status,
+ "companyId", "createdBy"
+ ) VALUES ($1, $2, $3, $4, 2, 'In Progress', $5, $6) RETURNING id`,
+ [jobId, methodId, processId, workCenterId, companyId, userId]
+ );
+ const operationId = opResult.rows[0].id;
+
+ // Pre-create tracked entity for serial completion in MES
+ await client.query(
+ `INSERT INTO "trackedEntity" ("readableId", quantity, "sourceDocument", "sourceDocumentId", attributes, status, "companyId", "createdBy")
+ VALUES ($1, 1, 'Item', $2, $3, 'Reserved', $4, $5)`,
+ [
+ "SN-G4001",
+ itemIds[3],
+ JSON.stringify({
+ "Job Make Method": methodId,
+ "Job Operation": operationId
+ }),
+ companyId,
+ userId
+ ]
+ );
+
+ // --- Configure printing ---
+ console.log(" Configuring printing settings...");
+ await client.query(
+ `UPDATE "companySettings" SET printing = $1, "productLabelSize" = 'label2x1', "kanbanOutput" = 'url' WHERE id = $2`,
+ [
+ JSON.stringify({
+ assignments: {}
+ }),
+ companyId
+ ]
+ );
+ const printerRouteResult = await client.query(
+ `INSERT INTO "printerRoute" ("companyId", "name", "format", "mediaSizeId", "printerUrl", "templateId")
+ VALUES ($1, 'Zebra 2x1', 'zpl', 'label2x1', 'https://your-proxybox-address.pbxz.cloud/api/v1/print/tag_2x1', 'carbon:product-label-2x1'),
+ ($1, 'Document Printer', 'pdf', NULL, 'https://your-proxybox-address.pbxz.cloud/api/v1/print/tag_BWLASER', NULL)
+ RETURNING id, name`,
+ [companyId]
+ );
+
+ const zplRouteId = printerRouteResult.rows.find(
+ (r: { name: string }) => r.name === "Zebra 2x1"
+ )?.id;
+
+ // Wire the default location to use the ZPL printer with auto-print enabled
+ await client.query(
+ `UPDATE "companySettings" SET printing = $1 WHERE id = $2`,
+ [
+ JSON.stringify({
+ assignments: {
+ [locationId]: {
+ defaultPrinterRouteId: zplRouteId,
+ defaultAutoPrint: true,
+ shipping: { printerRouteId: null, autoPrint: true },
+ receiving: { printerRouteId: null, autoPrint: true },
+ workCenters: {}
+ }
+ }
+ }),
+ companyId
+ ]
+ );
+
+ // --- Second location + receipt for testing location overrides ---
+ console.log(" Creating second location and receipt for override testing...");
+
+ const location2Result = await client.query(
+ `INSERT INTO location (name, "addressLine1", city, "stateProvince", "postalCode", "countryCode", timezone, "companyId", "createdBy")
+ VALUES ('Warehouse B', '456 Industrial Blvd', 'Round Rock', 'TX', '78664', 'US', 'America/Chicago', $1, 'system') RETURNING id`,
+ [companyId]
+ );
+ const location2Id = location2Result.rows[0].id;
+
+ // Add a second printer route at Warehouse B
+ const route2Result = await client.query(
+ `INSERT INTO "printerRoute" ("companyId", "locationId", "name", "format", "mediaSizeId", "printerUrl")
+ VALUES ($1, $2, 'Warehouse B Rollo', 'pdf', 'label2x1', 'https://your-proxybox-address.pbxz.cloud/api/v1/print/tag_ROLLO-LABELS')
+ RETURNING id`,
+ [companyId, location2Id]
+ );
+ const route2Id = route2Result.rows[0].id;
+
+ // Add Warehouse B assignment with the Rollo as default
+ await client.query(
+ `UPDATE "companySettings" SET printing = jsonb_set(
+ printing, '{assignments,${location2Id}}', $1::jsonb
+ ) WHERE id = $2`,
+ [
+ JSON.stringify({
+ defaultPrinterRouteId: route2Id,
+ defaultAutoPrint: false,
+ shipping: { printerRouteId: null, autoPrint: false },
+ receiving: { printerRouteId: null, autoPrint: true },
+ workCenters: {}
+ }),
+ companyId
+ ]
+ );
+
+ // Second PO + Receipt at Warehouse B
+ const po2Result = await client.query(
+ `INSERT INTO "purchaseOrder" (
+ "purchaseOrderId", "supplierId", "supplierInteractionId", status, "purchaseOrderType",
+ "exchangeRate", "companyId", "createdBy"
+ ) VALUES ('PO000002', $1, $2, 'To Receive', 'Purchase', 1, $3, $4) RETURNING id`,
+ [supplierId, supplierInteractionId, companyId, userId]
+ );
+ const purchaseOrder2Id = po2Result.rows[0].id;
+
+ await client.query(
+ `INSERT INTO "purchaseOrderDelivery" (id, "companyId") VALUES ($1, $2)`,
+ [purchaseOrder2Id, companyId]
+ );
+
+ const po2LineResult = await client.query(
+ `INSERT INTO "purchaseOrderLine" (
+ "purchaseOrderId", "purchaseOrderLineType", "itemId",
+ "purchaseQuantity", "quantityReceived", "quantityInvoiced",
+ "supplierUnitPrice", "supplierShippingCost", "supplierTaxAmount",
+ "exchangeRate", "setupPrice", "conversionFactor",
+ "purchaseUnitOfMeasureCode", "inventoryUnitOfMeasureCode",
+ "companyId", "createdBy"
+ ) VALUES ($1, 'Part', $2, 1, 0, 0, 10.00, 0, 0, 1, 0, 1, 'EA', 'EA', $3, $4) RETURNING id`,
+ [purchaseOrder2Id, itemIds[0], companyId, userId]
+ );
+ const po2LineId = po2LineResult.rows[0].id;
+
+ const receipt2Result = await client.query(
+ `INSERT INTO receipt (
+ "receiptId", "supplierId", "sourceDocument", "sourceDocumentId",
+ "locationId", status, "companyId", "createdBy"
+ ) VALUES ('RE000002', $1, 'Purchase Order', $2, $3, 'Draft', $4, $5) RETURNING id`,
+ [supplierId, purchaseOrder2Id, location2Id, companyId, userId]
+ );
+ const receipt2Id = receipt2Result.rows[0].id;
+
+ const receipt2LineResult = await client.query(
+ `INSERT INTO "receiptLine" (
+ "receiptId", "lineId", "itemId", "orderQuantity", "receivedQuantity", "unitPrice",
+ "unitOfMeasure", "locationId",
+ "requiresSerialTracking", "requiresBatchTracking",
+ "companyId", "createdBy"
+ ) VALUES ($1, $2, $3, 1, 1, 10.00, 'EA', $4, true, false, $5, $6) RETURNING id`,
+ [receipt2Id, po2LineId, itemIds[0], location2Id, companyId, userId]
+ );
+ const receipt2LineId = receipt2LineResult.rows[0].id;
+
+ // Pre-populate tracked entity for receipt 2
+ await client.query(
+ `INSERT INTO "trackedEntity" ("readableId", quantity, "sourceDocument", "sourceDocumentId", attributes, "companyId", "createdBy")
+ VALUES ($1, 1, 'Item', $2, $3, $4, $5)`,
+ [
+ "SN-W2001",
+ itemIds[0],
+ JSON.stringify({
+ Receipt: receipt2Id,
+ "Receipt Line": receipt2LineId,
+ "Receipt Line Index": 0
+ }),
+ companyId,
+ userId
+ ]
+ );
+
+ console.log(
+ " Printing: auto-print ON, label2x1 → your-proxybox-address.pbxz.cloud"
+ );
+ console.log(
+ " Receipt RE000001: WIDGET-001 x2, BRACKET-002 x1, FASTENER-003 x5 (tracking pre-filled)"
+ );
+ console.log(
+ " Receipt RE000002: WIDGET-001 x1 at Warehouse B (location override test)"
+ );
+ console.log(" Shipment SH000001: WIDGET-001 x1 (tracking pre-filled)");
+ console.log(" Kanban: FASTENER-003 Buy x100");
+ console.log(
+ " Job J000001: GEAR-004 x2, operation In Progress (tracked entity SN-G4001)"
+ );
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 51dd449eee..f36fa1c488 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -45855,6 +45855,258 @@ export default {
tags: ["costLedger"]
}
},
+ "/printJob": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.printJob.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.contentType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.content"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.printerUrl"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.description"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.origin"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.error"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.attempts"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.completedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/printJob"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["printJob"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.printJob"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["printJob"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.printJob.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.contentType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.content"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.printerUrl"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.description"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.origin"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.error"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.attempts"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.completedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["printJob"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.printJob.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.status"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.contentType"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.content"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.printerUrl"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocument"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocumentId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.sourceDocumentReadableId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.description"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.origin"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.error"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.attempts"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printJob.completedAt"
+ },
+ {
+ $ref: "#/parameters/body.printJob"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["printJob"]
+ }
+ },
"/journalLine": {
get: {
parameters: [
@@ -57513,47 +57765,38 @@ export default {
tags: ["nonConformanceJobOperation"]
}
},
- "/salesInvoiceShipment": {
+ "/printerRoute": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.id"
+ $ref: "#/parameters/rowFilter.printerRoute.id"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingCost"
+ $ref: "#/parameters/rowFilter.printerRoute.companyId"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.locationId"
+ $ref: "#/parameters/rowFilter.printerRoute.locationId"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingMethodId"
+ $ref: "#/parameters/rowFilter.printerRoute.name"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingTermId"
+ $ref: "#/parameters/rowFilter.printerRoute.format"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.customFields"
+ $ref: "#/parameters/rowFilter.printerRoute.mediaSizeId"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.companyId"
+ $ref: "#/parameters/rowFilter.printerRoute.printerUrl"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdAt"
+ $ref: "#/parameters/rowFilter.printerRoute.apiKey"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdBy"
+ $ref: "#/parameters/rowFilter.printerRoute.createdAt"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedAt"
- },
- {
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedBy"
- },
- {
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.incoterm"
- },
- {
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.incotermLocation"
+ $ref: "#/parameters/rowFilter.printerRoute.updatedAt"
},
{
$ref: "#/parameters/select"
@@ -57582,7 +57825,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/salesInvoiceShipment"
+ $ref: "#/definitions/printerRoute"
},
type: "array"
}
@@ -57591,12 +57834,12 @@ export default {
description: "Partial Content"
}
},
- tags: ["salesInvoiceShipment"]
+ tags: ["printerRoute"]
},
post: {
parameters: [
{
- $ref: "#/parameters/body.salesInvoiceShipment"
+ $ref: "#/parameters/body.printerRoute"
},
{
$ref: "#/parameters/select"
@@ -57610,48 +57853,85 @@ export default {
description: "Created"
}
},
- tags: ["salesInvoiceShipment"]
+ tags: ["printerRoute"]
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.id"
+ $ref: "#/parameters/rowFilter.printerRoute.id"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingCost"
+ $ref: "#/parameters/rowFilter.printerRoute.companyId"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.locationId"
+ $ref: "#/parameters/rowFilter.printerRoute.locationId"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingMethodId"
+ $ref: "#/parameters/rowFilter.printerRoute.name"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingTermId"
+ $ref: "#/parameters/rowFilter.printerRoute.format"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.customFields"
+ $ref: "#/parameters/rowFilter.printerRoute.mediaSizeId"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.companyId"
+ $ref: "#/parameters/rowFilter.printerRoute.printerUrl"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdAt"
+ $ref: "#/parameters/rowFilter.printerRoute.apiKey"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdBy"
+ $ref: "#/parameters/rowFilter.printerRoute.createdAt"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedAt"
+ $ref: "#/parameters/rowFilter.printerRoute.updatedAt"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedBy"
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["printerRoute"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.id"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.incoterm"
+ $ref: "#/parameters/rowFilter.printerRoute.companyId"
},
{
- $ref: "#/parameters/rowFilter.salesInvoiceShipment.incotermLocation"
+ $ref: "#/parameters/rowFilter.printerRoute.locationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.name"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.format"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.mediaSizeId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.printerUrl"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.apiKey"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.printerRoute.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.printerRoute"
},
{
$ref: "#/parameters/preferReturn"
@@ -57662,9 +57942,161 @@ export default {
description: "No Content"
}
},
- tags: ["salesInvoiceShipment"]
- },
- patch: {
+ tags: ["printerRoute"]
+ }
+ },
+ "/salesInvoiceShipment": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingCost"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.locationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingMethodId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingTermId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.customFields"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.incoterm"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.incotermLocation"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/salesInvoiceShipment"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["salesInvoiceShipment"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.salesInvoiceShipment"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["salesInvoiceShipment"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingCost"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.locationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingMethodId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.shippingTermId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.customFields"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.incoterm"
+ },
+ {
+ $ref: "#/parameters/rowFilter.salesInvoiceShipment.incotermLocation"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["salesInvoiceShipment"]
+ },
+ patch: {
parameters: [
{
$ref: "#/parameters/rowFilter.salesInvoiceShipment.id"
@@ -67188,6 +67620,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.timeCardEnabled"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.printing"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.updateLeadTimesOnReceipt"
},
@@ -67364,6 +67799,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.timeCardEnabled"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.printing"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.updateLeadTimesOnReceipt"
},
@@ -67494,6 +67932,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.timeCardEnabled"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.printing"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.updateLeadTimesOnReceipt"
},
@@ -84965,7 +85406,8 @@ export default {
"Sales",
"Settings",
"Users",
- "Quality"
+ "Quality",
+ "Printing"
],
format: "public.module",
type: "string"
@@ -85264,7 +85706,8 @@ export default {
"Sales",
"Settings",
"Users",
- "Quality"
+ "Quality",
+ "Printing"
],
format: "public.module",
type: "string"
@@ -99586,6 +100029,106 @@ export default {
},
type: "object"
},
+ printJob: {
+ required: [
+ "id",
+ "companyId",
+ "status",
+ "printerUrl",
+ "sourceDocument",
+ "sourceDocumentId",
+ "description",
+ "origin",
+ "attempts",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('pj'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ status: {
+ default: "generating",
+ format: "text",
+ type: "string"
+ },
+ contentType: {
+ format: "text",
+ type: "string"
+ },
+ content: {
+ format: "text",
+ type: "string"
+ },
+ printerUrl: {
+ format: "text",
+ type: "string"
+ },
+ sourceDocument: {
+ format: "text",
+ type: "string"
+ },
+ sourceDocumentId: {
+ format: "text",
+ type: "string"
+ },
+ sourceDocumentReadableId: {
+ format: "text",
+ type: "string"
+ },
+ description: {
+ format: "text",
+ type: "string"
+ },
+ origin: {
+ default: "auto",
+ format: "text",
+ type: "string"
+ },
+ error: {
+ format: "text",
+ type: "string"
+ },
+ attempts: {
+ default: 0,
+ format: "int32",
+ type: "integer"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ format: "text",
+ type: "string"
+ },
+ completedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
journalLine: {
required: [
"id",
@@ -104078,7 +104621,8 @@ export default {
"Sales",
"Settings",
"Users",
- "Quality"
+ "Quality",
+ "Printing"
],
format: "public.module",
type: "string"
@@ -105271,6 +105815,66 @@ export default {
},
type: "object"
},
+ printerRoute: {
+ required: [
+ "id",
+ "companyId",
+ "name",
+ "format",
+ "printerUrl",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('pr'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ locationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `location.id`.<fk table='location' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ name: {
+ format: "text",
+ type: "string"
+ },
+ format: {
+ format: "text",
+ type: "string"
+ },
+ mediaSizeId: {
+ format: "text",
+ type: "string"
+ },
+ printerUrl: {
+ format: "text",
+ type: "string"
+ },
+ apiKey: {
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
salesInvoiceShipment: {
required: [
"id",
@@ -109915,7 +110519,8 @@ export default {
"Sales",
"Settings",
"Users",
- "Quality"
+ "Quality",
+ "Printing"
],
format: "public.module",
type: "string"
@@ -110024,12 +110629,12 @@ export default {
type: "array"
},
productLabelSize: {
- default: "avery5160",
+ default: "avery5163",
format: "text",
type: "string"
},
shelfLabelSize: {
- default: "avery5160",
+ default: "avery5163",
format: "text",
type: "string"
},
@@ -110186,6 +110791,9 @@ export default {
format: "boolean",
type: "boolean"
},
+ printing: {
+ format: "jsonb"
+ },
updateLeadTimesOnReceipt: {
default: false,
format: "boolean",
@@ -110449,7 +111057,8 @@ export default {
"Sales",
"Settings",
"Users",
- "Quality"
+ "Quality",
+ "Printing"
],
format: "public.module",
type: "string"
@@ -135340,6 +135949,123 @@ export default {
in: "query",
type: "string"
},
+ "body.printJob": {
+ name: "printJob",
+ description: "printJob",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/printJob"
+ }
+ },
+ "rowFilter.printJob.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.status": {
+ name: "status",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.contentType": {
+ name: "contentType",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.content": {
+ name: "content",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.printerUrl": {
+ name: "printerUrl",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.sourceDocument": {
+ name: "sourceDocument",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.sourceDocumentId": {
+ name: "sourceDocumentId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.sourceDocumentReadableId": {
+ name: "sourceDocumentReadableId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.description": {
+ name: "description",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.origin": {
+ name: "origin",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.error": {
+ name: "error",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.attempts": {
+ name: "attempts",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printJob.completedAt": {
+ name: "completedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.journalLine": {
name: "journalLine",
description: "journalLine",
@@ -141704,6 +142430,75 @@ export default {
in: "query",
type: "string"
},
+ "body.printerRoute": {
+ name: "printerRoute",
+ description: "printerRoute",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/printerRoute"
+ }
+ },
+ "rowFilter.printerRoute.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.locationId": {
+ name: "locationId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.name": {
+ name: "name",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.format": {
+ name: "format",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.mediaSizeId": {
+ name: "mediaSizeId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.printerUrl": {
+ name: "printerUrl",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.apiKey": {
+ name: "apiKey",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.printerRoute.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.salesInvoiceShipment": {
name: "salesInvoiceShipment",
description: "salesInvoiceShipment",
@@ -147083,6 +147878,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companySettings.printing": {
+ name: "printing",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.companySettings.updateLeadTimesOnReceipt": {
name: "updateLeadTimesOnReceipt",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 1197a7e66f..9b743add47 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -3063,6 +3063,7 @@ export type Database = {
materialGeneratedIds: boolean
operationsDispatchNotificationGroup: string[] | null
otherDispatchNotificationGroup: string[] | null
+ printing: Json | null
productLabelSize: string | null
purchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
qualityDispatchNotificationGroup: string[] | null
@@ -3108,6 +3109,7 @@ export type Database = {
materialGeneratedIds?: boolean
operationsDispatchNotificationGroup?: string[] | null
otherDispatchNotificationGroup?: string[] | null
+ printing?: Json | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
qualityDispatchNotificationGroup?: string[] | null
@@ -3153,6 +3155,7 @@ export type Database = {
materialGeneratedIds?: boolean
operationsDispatchNotificationGroup?: string[] | null
otherDispatchNotificationGroup?: string[] | null
+ printing?: Json | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
qualityDispatchNotificationGroup?: string[] | null
@@ -26864,6 +26867,211 @@ export type Database = {
},
]
}
+ printerRoute: {
+ Row: {
+ apiKey: string | null
+ companyId: string
+ createdAt: string
+ format: string
+ id: string
+ locationId: string | null
+ mediaSizeId: string | null
+ name: string
+ printerUrl: string
+ templateId: string | null
+ updatedAt: string | null
+ }
+ Insert: {
+ apiKey?: string | null
+ companyId: string
+ createdAt?: string
+ format: string
+ id?: string
+ locationId?: string | null
+ mediaSizeId?: string | null
+ name: string
+ printerUrl: string
+ templateId?: string | null
+ updatedAt?: string | null
+ }
+ Update: {
+ apiKey?: string | null
+ companyId?: string
+ createdAt?: string
+ format?: string
+ id?: string
+ locationId?: string | null
+ mediaSizeId?: string | null
+ name?: string
+ printerUrl?: string
+ templateId?: string | null
+ updatedAt?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printerRoute_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ printJob: {
+ Row: {
+ attempts: number
+ companyId: string
+ completedAt: string | null
+ content: string | null
+ contentType: string | null
+ createdAt: string
+ createdBy: string
+ description: string
+ error: string | null
+ id: string
+ origin: string
+ printerUrl: string
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string | null
+ status: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ attempts?: number
+ companyId: string
+ completedAt?: string | null
+ content?: string | null
+ contentType?: string | null
+ createdAt?: string
+ createdBy: string
+ description: string
+ error?: string | null
+ id?: string
+ origin?: string
+ printerUrl: string
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId?: string | null
+ status?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ attempts?: number
+ companyId?: string
+ completedAt?: string | null
+ content?: string | null
+ contentType?: string | null
+ createdAt?: string
+ createdBy?: string
+ description?: string
+ error?: string | null
+ id?: string
+ origin?: string
+ printerUrl?: string
+ sourceDocument?: string
+ sourceDocumentId?: string
+ sourceDocumentReadableId?: string | null
+ status?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
procedure: {
Row: {
assignee: string | null
@@ -38217,7 +38425,7 @@ export type Database = {
},
]
}
- searchIndex_d8i6c9cjm0h04743p2ng: {
+ searchIndex_d8labgm360h02et7s650: {
Row: {
createdAt: string
description: string | null
@@ -38259,7 +38467,7 @@ export type Database = {
}
Relationships: []
}
- searchIndex_Vah7cNqpjARtZDhq8CcaPu: {
+ searchIndex_K26piHAY3SwCbjCHpopqjz: {
Row: {
createdAt: string
description: string | null
@@ -55853,14 +56061,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -59293,14 +59501,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -65663,6 +65871,7 @@ export type Database = {
| "Settings"
| "Users"
| "Quality"
+ | "Printing"
month:
| "January"
| "February"
@@ -66961,6 +67170,7 @@ export const Constants = {
"Settings",
"Users",
"Quality",
+ "Printing",
],
month: [
"January",
diff --git a/packages/database/supabase/functions/issue/index.ts b/packages/database/supabase/functions/issue/index.ts
index beb1bfa395..68ba53d1e6 100644
--- a/packages/database/supabase/functions/issue/index.ts
+++ b/packages/database/supabase/functions/issue/index.ts
@@ -1159,34 +1159,33 @@ serve(async (req: Request) => {
}
if (trackedEntity.status !== "Consumed") {
- // const activityId = nanoid();
- // await trx
- // .insertInto("trackedActivity")
- // .values({
- // id: activityId,
- // type: "Complete",
- // sourceDocument: "Job Operation",
- // sourceDocumentId: row.jobOperationId,
- // attributes: {
- // "Job Operation": row.jobOperationId,
- // Employee: userId,
- // },
- // companyId,
- // createdBy: userId,
- // })
- // .execute();
-
- // await trx
- // .insertInto("trackedActivityOutput")
- // .values({
- // trackedActivityId: activityId,
- // trackedEntityId: trackedEntityId,
- // quantity: 1,
- // companyId,
- // createdBy: userId,
- // })
- // .execute();
- // Update the current trackedEntity to Complete
+ const activityId = nanoid();
+ await trx
+ .insertInto("trackedActivity")
+ .values({
+ id: activityId,
+ type: "Complete",
+ sourceDocument: "Job Operation",
+ sourceDocumentId: row.jobOperationId,
+ attributes: {
+ "Job Operation": row.jobOperationId,
+ Employee: userId,
+ },
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
+
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values({
+ trackedActivityId: activityId,
+ trackedEntityId: trackedEntityId,
+ quantity: 1,
+ companyId,
+ createdBy: userId,
+ })
+ .execute();
await trx
.updateTable("trackedEntity")
.set({
@@ -2107,6 +2106,7 @@ serve(async (req: Request) => {
.insertInto("trackedEntity")
.values({
id: newTrackedEntityId,
+ readableId: trackedEntity.readableId,
sourceDocumentId: trackedEntity.sourceDocumentId,
sourceDocument: "Item",
sourceDocumentReadableId:
@@ -3152,6 +3152,7 @@ serve(async (req: Request) => {
.insertInto("trackedEntity")
.values({
id: newTrackedEntityId,
+ readableId: trackedEntity.readableId,
sourceDocumentId: trackedEntity.sourceDocumentId,
sourceDocument: "Item",
sourceDocumentReadableId:
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 1197a7e66f..9b743add47 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -3063,6 +3063,7 @@ export type Database = {
materialGeneratedIds: boolean
operationsDispatchNotificationGroup: string[] | null
otherDispatchNotificationGroup: string[] | null
+ printing: Json | null
productLabelSize: string | null
purchasePriceUpdateTiming: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
qualityDispatchNotificationGroup: string[] | null
@@ -3108,6 +3109,7 @@ export type Database = {
materialGeneratedIds?: boolean
operationsDispatchNotificationGroup?: string[] | null
otherDispatchNotificationGroup?: string[] | null
+ printing?: Json | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
qualityDispatchNotificationGroup?: string[] | null
@@ -3153,6 +3155,7 @@ export type Database = {
materialGeneratedIds?: boolean
operationsDispatchNotificationGroup?: string[] | null
otherDispatchNotificationGroup?: string[] | null
+ printing?: Json | null
productLabelSize?: string | null
purchasePriceUpdateTiming?: Database["public"]["Enums"]["purchasePriceUpdateTiming"]
qualityDispatchNotificationGroup?: string[] | null
@@ -26864,6 +26867,211 @@ export type Database = {
},
]
}
+ printerRoute: {
+ Row: {
+ apiKey: string | null
+ companyId: string
+ createdAt: string
+ format: string
+ id: string
+ locationId: string | null
+ mediaSizeId: string | null
+ name: string
+ printerUrl: string
+ templateId: string | null
+ updatedAt: string | null
+ }
+ Insert: {
+ apiKey?: string | null
+ companyId: string
+ createdAt?: string
+ format: string
+ id?: string
+ locationId?: string | null
+ mediaSizeId?: string | null
+ name: string
+ printerUrl: string
+ templateId?: string | null
+ updatedAt?: string | null
+ }
+ Update: {
+ apiKey?: string | null
+ companyId?: string
+ createdAt?: string
+ format?: string
+ id?: string
+ locationId?: string | null
+ mediaSizeId?: string | null
+ name?: string
+ printerUrl?: string
+ templateId?: string | null
+ updatedAt?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printerRoute_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printerRoute_locationId_fkey"
+ columns: ["locationId"]
+ isOneToOne: false
+ referencedRelation: "location"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
+ printJob: {
+ Row: {
+ attempts: number
+ companyId: string
+ completedAt: string | null
+ content: string | null
+ contentType: string | null
+ createdAt: string
+ createdBy: string
+ description: string
+ error: string | null
+ id: string
+ origin: string
+ printerUrl: string
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId: string | null
+ status: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ attempts?: number
+ companyId: string
+ completedAt?: string | null
+ content?: string | null
+ contentType?: string | null
+ createdAt?: string
+ createdBy: string
+ description: string
+ error?: string | null
+ id?: string
+ origin?: string
+ printerUrl: string
+ sourceDocument: string
+ sourceDocumentId: string
+ sourceDocumentReadableId?: string | null
+ status?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ attempts?: number
+ companyId?: string
+ completedAt?: string | null
+ content?: string | null
+ contentType?: string | null
+ createdAt?: string
+ createdBy?: string
+ description?: string
+ error?: string | null
+ id?: string
+ origin?: string
+ printerUrl?: string
+ sourceDocument?: string
+ sourceDocumentId?: string
+ sourceDocumentReadableId?: string | null
+ status?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printJob_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "printJob_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
procedure: {
Row: {
assignee: string | null
@@ -38217,7 +38425,7 @@ export type Database = {
},
]
}
- searchIndex_d8i6c9cjm0h04743p2ng: {
+ searchIndex_d8labgm360h02et7s650: {
Row: {
createdAt: string
description: string | null
@@ -38259,7 +38467,7 @@ export type Database = {
}
Relationships: []
}
- searchIndex_Vah7cNqpjARtZDhq8CcaPu: {
+ searchIndex_K26piHAY3SwCbjCHpopqjz: {
Row: {
createdAt: string
description: string | null
@@ -55853,14 +56061,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -59293,14 +59501,14 @@ export type Database = {
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["shipmentCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["shipmentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -65663,6 +65871,7 @@ export type Database = {
| "Settings"
| "Users"
| "Quality"
+ | "Printing"
month:
| "January"
| "February"
@@ -66961,6 +67170,7 @@ export const Constants = {
"Settings",
"Users",
"Quality",
+ "Printing",
],
month: [
"January",
diff --git a/packages/database/supabase/functions/post-shipment/index.ts b/packages/database/supabase/functions/post-shipment/index.ts
index 87d6eef60a..984873bd31 100644
--- a/packages/database/supabase/functions/post-shipment/index.ts
+++ b/packages/database/supabase/functions/post-shipment/index.ts
@@ -101,6 +101,8 @@ serve(async (req: Request) => {
throw new Error("Failed to fetch jobs");
}
+ const splitEntityIds: string[] = [];
+
switch (type) {
case "post": {
switch (shipment.data?.sourceDocument) {
@@ -685,6 +687,7 @@ serve(async (req: Request) => {
originalQuantity: number;
shippedQuantity: number;
remainingQuantity: number;
+ readableId: string | null;
attributes: TrackedEntityAttributes;
sourceDocument: string;
sourceDocumentId: string;
@@ -722,6 +725,7 @@ serve(async (req: Request) => {
shippedQuantity: shipmentLine.shippedQuantity,
remainingQuantity:
trackedEntity.quantity - shipmentLine.shippedQuantity,
+ readableId: trackedEntity.readableId,
attributes:
trackedEntity.attributes as TrackedEntityAttributes,
sourceDocument: trackedEntity.sourceDocument,
@@ -879,6 +883,7 @@ serve(async (req: Request) => {
const newTrackedEntity = await trx
.insertInto("trackedEntity")
.values({
+ readableId: splitInfo.readableId,
quantity: splitInfo.remainingQuantity,
status: "Available",
sourceDocument: splitInfo.sourceDocument,
@@ -896,6 +901,7 @@ serve(async (req: Request) => {
.execute();
const newTrackedEntityId = newTrackedEntity[0].id!;
+ splitEntityIds.push(newTrackedEntityId);
// Update the original entity's attributes to include the split entity ID
const originalEntity = await trx
@@ -1373,6 +1379,7 @@ serve(async (req: Request) => {
originalQuantity: number;
shippedQuantity: number;
remainingQuantity: number;
+ readableId: string | null;
attributes: TrackedEntityAttributes;
sourceDocument: string;
sourceDocumentId: string;
@@ -1410,6 +1417,7 @@ serve(async (req: Request) => {
shippedQuantity: shipmentLine.shippedQuantity,
remainingQuantity:
trackedEntity.quantity - shipmentLine.shippedQuantity,
+ readableId: trackedEntity.readableId,
attributes:
trackedEntity.attributes as TrackedEntityAttributes,
sourceDocument: trackedEntity.sourceDocument,
@@ -1515,6 +1523,7 @@ serve(async (req: Request) => {
const newTrackedEntity = await trx
.insertInto("trackedEntity")
.values({
+ readableId: splitInfo.readableId,
quantity: splitInfo.remainingQuantity,
status: "Available",
sourceDocument: splitInfo.sourceDocument,
@@ -1532,6 +1541,7 @@ serve(async (req: Request) => {
.execute();
const newTrackedEntityId = newTrackedEntity[0].id!;
+ splitEntityIds.push(newTrackedEntityId);
// Update the original entity's attributes to include the split entity ID
const originalEntity = await trx
@@ -2834,6 +2844,7 @@ serve(async (req: Request) => {
return new Response(
JSON.stringify({
success: true,
+ splitEntityIds,
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.ts
index b8d5520928..2a8eaa4b89 100644
--- a/packages/database/supabase/functions/post-stock-transfer/index.ts
+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts
@@ -131,6 +131,7 @@ serve(async (req: Request) => {
try {
const validatedPayload = payloadValidator.parse(payload);
let expiredWarning: string | undefined;
+ let splitEntityId: string | undefined;
console.log({
function: "post-stock-transfer",
@@ -454,6 +455,7 @@ serve(async (req: Request) => {
// Need to split the batch
const remainingQuantity = entityQuantity - transferQuantity;
const newTrackedEntityId = nanoid();
+ splitEntityId = newTrackedEntityId;
// Create split activity
const splitActivityId = nanoid();
@@ -492,6 +494,7 @@ serve(async (req: Request) => {
.insertInto("trackedEntity")
.values({
id: newTrackedEntityId,
+ readableId: trackedEntity.readableId,
sourceDocument: trackedEntity.sourceDocument,
sourceDocumentId: trackedEntity.sourceDocumentId,
sourceDocumentReadableId:
@@ -1062,6 +1065,7 @@ serve(async (req: Request) => {
JSON.stringify({
success: true,
warning: expiredWarning,
+ splitEntityId,
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
diff --git a/packages/database/supabase/migrations/20260326000000_print-manager.sql b/packages/database/supabase/migrations/20260326000000_print-manager.sql
new file mode 100644
index 0000000000..f8cf2dd108
--- /dev/null
+++ b/packages/database/supabase/migrations/20260326000000_print-manager.sql
@@ -0,0 +1,131 @@
+-- Print Manager: module enum, tables, indexes, RLS, and permission seeding
+
+ALTER TYPE "module" ADD VALUE IF NOT EXISTS 'Printing';
+
+COMMIT;
+
+DROP VIEW IF EXISTS "modules";
+CREATE VIEW "modules" AS
+ SELECT unnest(enum_range(NULL::module)) AS name;
+
+-- Insert Printing module permissions for Admin and Management employee types
+INSERT INTO "employeeTypePermission" ("employeeTypeId", "module", "create", "delete", "update", "view")
+SELECT
+ et.id AS "employeeTypeId",
+ 'Printing'::module AS "module",
+ ARRAY[et."companyId"] AS "create",
+ ARRAY[et."companyId"] AS "delete",
+ ARRAY[et."companyId"] AS "update",
+ ARRAY[et."companyId"] AS "view"
+FROM "employeeType" et
+WHERE et.name IN ('Admin', 'Management')
+ON CONFLICT ("employeeTypeId", "module") DO NOTHING;
+
+-- Update userPermission table to add Printing module permissions based on Settings permissions
+UPDATE "userPermission"
+SET "permissions" = "permissions" || jsonb_build_object(
+ 'printing_view', COALESCE("permissions"->'settings_view', '[]'::jsonb),
+ 'printing_create', COALESCE("permissions"->'settings_create', '[]'::jsonb),
+ 'printing_update', COALESCE("permissions"->'settings_update', '[]'::jsonb),
+ 'printing_delete', COALESCE("permissions"->'settings_delete', '[]'::jsonb)
+);
+
+-- Auto-print settings on companySettings
+ALTER TABLE "companySettings" ADD COLUMN IF NOT EXISTS "printing" jsonb;
+
+-- Printer routing: physical printer definitions
+CREATE TABLE "printerRoute" (
+ "id" text NOT NULL DEFAULT id('pr'),
+ "companyId" text NOT NULL REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ "locationId" text REFERENCES "location"("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ "name" text NOT NULL,
+ "format" text NOT NULL CHECK ("format" IN ('zpl', 'pdf')),
+ "mediaSizeId" text,
+ "printerUrl" text NOT NULL,
+ "apiKey" text,
+ "createdAt" timestamptz NOT NULL DEFAULT now(),
+ "updatedAt" timestamptz,
+ PRIMARY KEY ("id", "companyId")
+);
+
+CREATE UNIQUE INDEX "printerRoute_name_unique"
+ ON "printerRoute" ("companyId", COALESCE("locationId", ''), "name");
+
+CREATE INDEX "printerRoute_locationId_idx"
+ ON "printerRoute" ("companyId", "locationId");
+
+ALTER TABLE "printerRoute" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "printerRoute"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_view'))::text[])
+ );
+
+CREATE POLICY "INSERT" ON "printerRoute"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_create'))::text[])
+ );
+
+CREATE POLICY "UPDATE" ON "printerRoute"
+ FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_update'))::text[])
+ );
+
+CREATE POLICY "DELETE" ON "printerRoute"
+ FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_delete'))::text[])
+ );
+
+-- Print job queue/audit table
+CREATE TABLE "printJob" (
+ "id" text NOT NULL DEFAULT id('pj'),
+ "companyId" text NOT NULL REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ "status" text NOT NULL DEFAULT 'generating'
+ CHECK ("status" IN ('generating', 'queued', 'printing', 'completed', 'failed')),
+ "contentType" text CHECK ("contentType" IN ('zpl', 'pdf')),
+ "content" text,
+ "printerUrl" text NOT NULL,
+ "sourceDocument" text NOT NULL,
+ "sourceDocumentId" text NOT NULL,
+ "sourceDocumentReadableId" text,
+ "description" text NOT NULL,
+ "origin" text NOT NULL DEFAULT 'auto'
+ CHECK ("origin" IN ('auto', 'manual', 'reprint')),
+ "error" text,
+ "attempts" integer NOT NULL DEFAULT 0,
+ "createdBy" text NOT NULL REFERENCES "user"("id"),
+ "createdAt" timestamptz NOT NULL DEFAULT now(),
+ "updatedAt" timestamptz,
+ "updatedBy" text,
+ "completedAt" timestamptz,
+ PRIMARY KEY ("id", "companyId")
+);
+
+CREATE INDEX "printJob_companyId_idx" ON "printJob" ("companyId");
+CREATE INDEX "printJob_status_idx" ON "printJob" ("companyId", "status");
+CREATE INDEX "printJob_createdAt_idx" ON "printJob" ("companyId", "createdAt" DESC);
+
+ALTER TABLE "printJob" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "printJob"
+ FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_view'))::text[])
+ );
+
+CREATE POLICY "INSERT" ON "printJob"
+ FOR INSERT WITH CHECK (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_create'))::text[])
+ );
+
+CREATE POLICY "UPDATE" ON "printJob"
+ FOR UPDATE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_update'))::text[])
+ );
+
+CREATE POLICY "DELETE" ON "printJob"
+ FOR DELETE USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_permission('printing_delete'))::text[])
+ );
+
+-- Enable Realtime for Print Manager live status updates
+ALTER PUBLICATION supabase_realtime ADD TABLE "printJob";
diff --git a/packages/database/supabase/migrations/20260509000000_printer-template-id.sql b/packages/database/supabase/migrations/20260509000000_printer-template-id.sql
new file mode 100644
index 0000000000..03aa01e575
--- /dev/null
+++ b/packages/database/supabase/migrations/20260509000000_printer-template-id.sql
@@ -0,0 +1,2 @@
+ALTER TABLE "printerRoute"
+ ADD COLUMN IF NOT EXISTS "templateId" text;
diff --git a/packages/database/supabase/migrations/20260611184237_remove-avery5160-label-size.sql b/packages/database/supabase/migrations/20260611184237_remove-avery5160-label-size.sql
new file mode 100644
index 0000000000..e72894ce61
--- /dev/null
+++ b/packages/database/supabase/migrations/20260611184237_remove-avery5160-label-size.sql
@@ -0,0 +1,8 @@
+-- The avery5160 label size has been removed from the app. Move column
+-- defaults and any existing settings to avery5163 (the remaining sheet size).
+
+ALTER TABLE "companySettings" ALTER COLUMN "productLabelSize" SET DEFAULT 'avery5163';
+ALTER TABLE "companySettings" ALTER COLUMN "shelfLabelSize" SET DEFAULT 'avery5163';
+
+UPDATE "companySettings" SET "productLabelSize" = 'avery5163' WHERE "productLabelSize" = 'avery5160';
+UPDATE "companySettings" SET "shelfLabelSize" = 'avery5163' WHERE "shelfLabelSize" = 'avery5160';
diff --git a/packages/documents/src/pdf/ProductLabelPDF.tsx b/packages/documents/src/pdf/ProductLabelPDF.tsx
index a6f7f43fbf..873ee641d5 100644
--- a/packages/documents/src/pdf/ProductLabelPDF.tsx
+++ b/packages/documents/src/pdf/ProductLabelPDF.tsx
@@ -1,218 +1,100 @@
import type { LabelSize, ProductLabelItem } from "@carbon/utils";
import { Document, Image, Page, Text, View } from "@react-pdf/renderer";
-import { createTw } from "react-pdf-tailwind";
import { generateQRCode } from "../qr/qr-code";
-import Footer from "./components/Footer";
+import { getLabelPdfGeometry } from "./components/labelGeometry";
interface ProductLabelProps {
items: ProductLabelItem[];
labelSize: LabelSize;
}
-// Initialize tailwind-styled-components
-const tw = createTw({
- theme: {
- fontFamily: {
- sans: ["Helvetica", "Arial", "sans-serif"]
- },
- extend: {
- colors: {
- gray: {
- 500: "#7d7d7d"
- }
- }
- }
- }
-});
-
+/**
+ * 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) => {
- // 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;
-
- // 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;
-
- // Determine page size based on rows and columns
- let pageWidth, pageHeight;
-
- if (rows > 1 || columns > 1) {
- // Using standard letter size paper
- pageWidth = LETTER_WIDTH;
- pageHeight = LETTER_HEIGHT;
- } else {
- // Single label per page - use effective dimensions for rotated labels
- pageWidth = effectiveLabelWidthPt;
- pageHeight = effectiveLabelHeightPt;
- }
-
- // 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.8,
- effectiveLabelWidthPt * 0.4
- );
-
- // 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;
-
- // Calculate margins to center labels on the page
- // Use effective dimensions for rotated labels
- const horizontalMargin = (pageWidth - columns * effectiveLabelWidthPt) / 2;
- const availableHeight =
- rows > 1 || columns > 1 ? pageHeight - footerHeight : pageHeight;
- const verticalMargin = (availableHeight - rows * effectiveLabelHeightPt) / 2;
+ const g = getLabelPdfGeometry(labelSize);
+ const qrX = g.pageWidth - g.qrSize - g.margin;
return (
<Document>
- {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}`}
+ {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={{
- flexDirection: "row",
- marginLeft: horizontalMargin,
- marginTop: rowIndex === 0 ? verticalMargin : 0
+ fontSize: g.titleFontSize,
+ fontFamily: "Helvetica-Bold",
+ marginBottom: g.lineGap
}}
>
- {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 }}
- />
- );
-
- return (
- <View
- key={`label-${itemIndex}`}
- style={{
- ...tw("relative p-2 flex flex-col pl-[10pt]"),
- width: labelWidthPt,
- height: labelHeightPt,
- transform: rotated ? "rotate(90deg)" : undefined
- }}
- wrap={false}
- >
- <View style={tw("flex flex-row justify-between")}>
- <View
- style={tw("flex flex-col justify-center flex-1 pr-2")}
- >
- <Text
- style={{
- overflow: "hidden",
- textOverflow: "ellipsis",
- maxWidth: "100%",
- ...tw("mb-2"),
- fontWeight: "bold",
- fontSize: `${titleFontSize}pt`
- }}
- >
- {item.itemId}
- </Text>
-
- {item.revision && (
- <Text
- style={{
- ...tw("mb-1"),
- fontSize: `${descriptionFontSize}pt`
- }}
- >
- Rev: {item.revision}
- </Text>
- )}
-
- {["Serial", "Batch"].includes(item.trackingType) && (
- <Text
- style={{
- ...tw("mb-1"),
- fontSize: `${descriptionFontSize}pt`
- }}
- >
- Qty: {item.quantity}
- </Text>
- )}
-
- {item.trackingType === "Serial" && item.number && (
- <Text
- style={{
- ...tw("mb-1"),
- fontSize: `${descriptionFontSize}pt`
- }}
- >
- S/N: {item.number}
- </Text>
- )}
- {item.trackingType === "Batch" && item.number && (
- <Text
- style={{
- ...tw("mb-1"),
- fontSize: `${descriptionFontSize}pt`
- }}
- >
- Batch: {item.number}
- </Text>
- )}
- </View>
-
- <View style={tw("flex items-center justify-center")}>
- <Image
- src={generateQRCode(
- item.trackedEntityId,
- qrCodeSize / 72
- )}
- style={{
- width: qrCodeSize,
- height: qrCodeSize,
- objectFit: "contain"
- }}
- />
- </View>
- </View>
-
- {item.trackedEntityId && (
- <Text
- style={{
- ...tw("mt-1 text-center"),
- fontSize: `${descriptionFontSize - 1}pt`,
- width: "100%"
- }}
- >
- {item.trackedEntityId}
- </Text>
- )}
- </View>
- );
- })}
- </View>
- ))}
- <Footer />
+ {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
+ style={{
+ position: "absolute",
+ left: g.margin,
+ bottom: g.bottomOffset,
+ fontSize: g.smallFontSize
+ }}
+ >
+ {item.trackedEntityId}
+ </Text>
+ )}
</Page>
))}
</Document>
diff --git a/packages/documents/src/pdf/StorageUnitLabelPDF.tsx b/packages/documents/src/pdf/StorageUnitLabelPDF.tsx
new file mode 100644
index 0000000000..4393eff337
--- /dev/null
+++ b/packages/documents/src/pdf/StorageUnitLabelPDF.tsx
@@ -0,0 +1,47 @@
+import type { LabelSize } from "@carbon/utils";
+import { Document, Page, Text, View } from "@react-pdf/renderer";
+import type { StorageUnitLabelItem } from "../zpl/StorageUnitLabelZPL";
+import { getLabelPdfGeometry } from "./components/labelGeometry";
+
+interface StorageUnitLabelProps {
+ items: StorageUnitLabelItem[];
+ labelSize: LabelSize;
+}
+
+/**
+ * Renders one page per storage unit, each page exactly the label size,
+ * matching the ZPL generator: the unit name vertically centered at the
+ * left margin.
+ */
+const StorageUnitLabelPDF = ({ items, labelSize }: StorageUnitLabelProps) => {
+ const g = getLabelPdfGeometry(labelSize);
+ const titleFontSize = (40 / 25) * g.titleFontSize;
+
+ return (
+ <Document>
+ {items.map((item) => (
+ <Page key={item.id} size={[g.pageWidth, g.pageHeight]}>
+ <View
+ style={{
+ flex: 1,
+ justifyContent: "center",
+ paddingLeft: g.margin,
+ paddingRight: g.margin
+ }}
+ >
+ <Text
+ style={{
+ fontSize: titleFontSize,
+ fontFamily: "Helvetica-Bold"
+ }}
+ >
+ {item.name}
+ </Text>
+ </View>
+ </Page>
+ ))}
+ </Document>
+ );
+};
+
+export default StorageUnitLabelPDF;
diff --git a/packages/documents/src/pdf/components/labelGeometry.ts b/packages/documents/src/pdf/components/labelGeometry.ts
new file mode 100644
index 0000000000..f0324d9b64
--- /dev/null
+++ b/packages/documents/src/pdf/components/labelGeometry.ts
@@ -0,0 +1,48 @@
+import type { LabelSize } from "@carbon/utils";
+
+/**
+ * PDF geometry for a single label page, mirroring the ZPL generators'
+ * layout (baseline 2" x 1" at 203dpi) so PDF and ZPL prints look alike.
+ * All values are in PDF points (72 per inch); the page is exactly the
+ * label size.
+ */
+const POINTS_PER_DOT = 72 / 203;
+
+export type LabelPdfGeometry = {
+ pageWidth: number;
+ pageHeight: number;
+ scale: number;
+ margin: number;
+ contentTop: number;
+ titleFontSize: number;
+ descFontSize: number;
+ smallFontSize: number;
+ lineGap: number;
+ bottomOffset: number;
+ qrSize: number;
+};
+
+export function getLabelPdfGeometry(labelSize: LabelSize): LabelPdfGeometry {
+ const pageWidth = labelSize.width * 72;
+ const pageHeight = labelSize.height * 72;
+
+ const wScale = labelSize.width / 2;
+ const hScale = labelSize.height / 1;
+ const scale = Math.min(wScale, hScale);
+
+ const qrModuleSize = Math.max(2, Math.min(8, Math.round(4 * scale)));
+
+ return {
+ pageWidth,
+ pageHeight,
+ scale,
+ margin: 20 * Math.max(scale, 0.8) * POINTS_PER_DOT,
+ contentTop: 30 * hScale * POINTS_PER_DOT,
+ titleFontSize: 25 * scale * POINTS_PER_DOT,
+ descFontSize: 18 * scale * POINTS_PER_DOT,
+ smallFontSize: 12 * scale * POINTS_PER_DOT,
+ lineGap: 7 * scale * POINTS_PER_DOT,
+ bottomOffset: 10 * hScale * POINTS_PER_DOT,
+ qrSize: qrModuleSize * 29 * POINTS_PER_DOT
+ };
+}
diff --git a/packages/documents/src/pdf/index.ts b/packages/documents/src/pdf/index.ts
index 7ebb7e180f..f575c1512e 100644
--- a/packages/documents/src/pdf/index.ts
+++ b/packages/documents/src/pdf/index.ts
@@ -9,6 +9,7 @@ import QuotePDF from "./QuotePDF";
import SalesInvoicePDF from "./SalesInvoicePDF";
import SalesOrderPDF from "./SalesOrderPDF";
import StockTransferPDF from "./StockTransferPDF";
+import StorageUnitLabelPDF from "./StorageUnitLabelPDF";
export {
Footer,
IssuePDF,
@@ -21,5 +22,6 @@ export {
QuotePDF,
SalesInvoicePDF,
SalesOrderPDF,
- StockTransferPDF
+ StockTransferPDF,
+ StorageUnitLabelPDF
};
diff --git a/packages/documents/src/zpl/ProductLabelZPL.tsx b/packages/documents/src/zpl/ProductLabelZPL.tsx
index eba5dcb39d..a589eaf2b7 100644
--- a/packages/documents/src/zpl/ProductLabelZPL.tsx
+++ b/packages/documents/src/zpl/ProductLabelZPL.tsx
@@ -1,80 +1,54 @@
import type { LabelSize, ProductLabelItem } from "@carbon/utils";
+import { getZplLabelGeometry, zplLabelHeader } from "./utils";
export function generateProductLabelZPL(
item: ProductLabelItem,
labelSize: LabelSize
): 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);
-
- // Determine if this is a small or large label
- const isSmallLabel = width <= 2.5; // Consider 2x1 as small
-
- // Calculate positions based on label size
- const textStartX = 20;
- let fontSize = isSmallLabel ? 25 : 35; // Smaller font for small labels
- let descFontSize = isSmallLabel ? 18 : 25;
- let smallFontSize = isSmallLabel ? 12 : 18;
+ const geometry = getZplLabelGeometry(labelSize);
+ const { widthDots, heightDots, hScale, scale, margin } = geometry;
- // 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 titleFont = Math.round(25 * scale);
+ const descFont = Math.round(18 * scale);
+ const smallFont = Math.round(12 * scale);
+ const lineGap = Math.round(25 * scale);
- const qrStartX = isSmallLabel
- ? widthDots - qrSize - 15 // Tighter spacing on small labels
- : widthDots - qrSize - 40; // More spacing on larger labels
+ // 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);
- // Start ZPL command sequence
- let zpl = "^XA"; // Start format
+ let zpl = zplLabelHeader(geometry);
- // Set label dimensions
- zpl += `^PW${widthDots}`;
- zpl += `^LL${heightDots}`;
+ let y = Math.round(30 * hScale);
- // Item ID (larger font)
- zpl += `^FO${textStartX},30^A0N,${fontSize},${fontSize}^FD${item.itemId}^FS`;
+ zpl += `^FO${margin},${y}^A0N,${titleFont},${titleFont}^FD${item.itemId}^FS`;
+ y += titleFont + Math.round(10 * hScale);
- // Revision if available
- let yPosition = isSmallLabel ? 65 : 80;
if (item.revision) {
- zpl += `^FO${textStartX},${yPosition}^A0N,${descFontSize},${descFontSize}^FDRev: ${item.revision}^FS`;
- yPosition += isSmallLabel ? 25 : 35;
+ zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDRev: ${item.revision}^FS`;
+ y += lineGap;
}
- // Quantity
if (["Serial", "Batch"].includes(item.trackingType)) {
- zpl += `^FO${textStartX},${yPosition}^A0N,${descFontSize},${descFontSize}^FDQty: ${item.quantity}^FS`;
- yPosition += isSmallLabel ? 25 : 35;
+ zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDQty: ${item.quantity}^FS`;
+ y += lineGap;
}
- // Serial or Batch number
if (item.trackingType === "Serial") {
- zpl += `^FO${textStartX},${yPosition}^A0N,${descFontSize},${descFontSize}^FDS/N: ${item.number}^FS`;
+ zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDS/N: ${item.number}^FS`;
} else if (item.trackingType === "Batch") {
- zpl += `^FO${textStartX},${yPosition}^A0N,${descFontSize},${descFontSize}^FDBatch: ${item.number}^FS`;
+ zpl += `^FO${margin},${y}^A0N,${descFont},${descFont}^FDBatch: ${item.number}^FS`;
}
- // QR Code for tracked entity ID
- // Using proper error correction level (M) and input mode (A)
- const qrYPosition = isSmallLabel ? 30 : 40;
- zpl += `^FO${qrStartX},${qrYPosition}^BQN,2,${isSmallLabel ? 5 : 7},M,A^FD${
- item.trackedEntityId
- }^FS`;
+ zpl += `^FO${qrX},${qrY}^BQN,2,${qrModuleSize}^FDMA,${item.trackedEntityId}^FS`;
- // Tracked entity ID at bottom
- const idYPosition = isSmallLabel ? heightDots - 25 : heightDots - 35;
- zpl += `^FO${textStartX},${idYPosition}^A0N,${smallFontSize},${smallFontSize}^FD${item.trackedEntityId}^FS`;
+ const idY = heightDots - smallFont - Math.round(10 * hScale);
+ zpl += `^FO${margin},${idY}^A0N,${smallFont},${smallFont}^FD${item.trackedEntityId}^FS`;
- // End ZPL command sequence
- zpl += "^XZ"; // End format
+ zpl += "^XZ";
return zpl;
}
diff --git a/packages/documents/src/zpl/StorageUnitLabelZPL.tsx b/packages/documents/src/zpl/StorageUnitLabelZPL.tsx
new file mode 100644
index 0000000000..1b1f998072
--- /dev/null
+++ b/packages/documents/src/zpl/StorageUnitLabelZPL.tsx
@@ -0,0 +1,26 @@
+import type { LabelSize } from "@carbon/utils";
+import { getZplLabelGeometry, zplLabelHeader } from "./utils";
+
+export type StorageUnitLabelItem = {
+ name: string;
+ id: string;
+};
+
+export function generateStorageUnitLabelZPL(
+ item: StorageUnitLabelItem,
+ labelSize: LabelSize
+): string {
+ const geometry = getZplLabelGeometry(labelSize);
+ const { heightDots, scale, margin } = geometry;
+
+ const titleFont = Math.round(40 * scale);
+ const textY = Math.round((heightDots - titleFont) / 2);
+
+ let zpl = zplLabelHeader(geometry);
+
+ zpl += `^FO${margin},${textY}^A0N,${titleFont},${titleFont}^FD${item.name}^FS`;
+
+ zpl += "^XZ";
+
+ return zpl;
+}
diff --git a/packages/documents/src/zpl/index.ts b/packages/documents/src/zpl/index.ts
index 22d6477c96..c1d7a2e505 100644
--- a/packages/documents/src/zpl/index.ts
+++ b/packages/documents/src/zpl/index.ts
@@ -1,3 +1,5 @@
import { generateProductLabelZPL } from "./ProductLabelZPL";
+import { generateStorageUnitLabelZPL } from "./StorageUnitLabelZPL";
-export { generateProductLabelZPL };
+export { generateProductLabelZPL, generateStorageUnitLabelZPL };
+export type { StorageUnitLabelItem } from "./StorageUnitLabelZPL";
diff --git a/packages/documents/src/zpl/utils.ts b/packages/documents/src/zpl/utils.ts
new file mode 100644
index 0000000000..b6a7aec628
--- /dev/null
+++ b/packages/documents/src/zpl/utils.ts
@@ -0,0 +1,40 @@
+import type { LabelSize } from "@carbon/utils";
+
+export type ZplLabelGeometry = {
+ widthDots: number;
+ heightDots: number;
+ wScale: number;
+ hScale: number;
+ scale: number;
+ margin: number;
+};
+
+/**
+ * Computes label dimensions in printer dots and a scale factor relative to
+ * the 2"x1" baseline (406x203 dots at 203dpi).
+ */
+export function getZplLabelGeometry(labelSize: LabelSize): ZplLabelGeometry {
+ if (!labelSize.zpl) {
+ throw new Error("Invalid label size or missing ZPL configuration");
+ }
+ const { width, height } = labelSize.zpl;
+ const dpi = labelSize.zpl.dpi || 203;
+
+ const widthDots = Math.round(width * dpi);
+ const heightDots = Math.round(height * dpi);
+
+ const wScale = widthDots / 406;
+ const hScale = heightDots / 203;
+ const scale = Math.min(wScale, hScale);
+ const margin = Math.round(20 * Math.max(scale, 0.8));
+
+ return { widthDots, heightDots, wScale, hScale, scale, margin };
+}
+
+/** Standard label preamble: start format, set size, no media tracking, UTF-8. */
+export function zplLabelHeader({
+ widthDots,
+ heightDots
+}: ZplLabelGeometry): string {
+ return `^XA^PW${widthDots}^LL${heightDots}^MNW^CI28`;
+}
diff --git a/packages/env/src/index.ts b/packages/env/src/index.ts
index 3c76856ec2..997a4066e4 100644
--- a/packages/env/src/index.ts
+++ b/packages/env/src/index.ts
@@ -119,6 +119,10 @@ export function isAuthProviderEnabled(provider: AuthProvider) {
const AUTH_PROVIDERS_LIST = AUTH_PROVIDERS.split(",").map((p) => p.trim());
return AUTH_PROVIDERS_LIST.includes(provider);
}
+export const BINDERY_PRESS_API_KEY = getEnv("BINDERY_PRESS_API_KEY", {
+ isRequired: false,
+ isSecret: true
+});
const CARBON_EDITION = getEnv("CARBON_EDITION", {
isRequired: false,
@@ -156,6 +160,7 @@ export const CLOUDFLARE_TURNSTILE_SECRET_KEY = getEnv(
);
export const DOMAIN = getEnv("DOMAIN", { isRequired: false }); // preview environments need no domain
+
export const EXCHANGE_RATES_API_KEY = getEnv("EXCHANGE_RATES_API_KEY", {
isRequired: false,
isSecret: true
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index 8378c19412..5f13cc02f1 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -9,10 +9,12 @@
"@carbon/kv": "workspace:*",
"@carbon/lib": "workspace:*",
"@carbon/notifications": "workspace:*",
+ "@carbon/printing": "workspace:*",
"@carbon/stripe": "workspace:*",
"@carbon/utils": "workspace:*",
"@internationalized/date": "catalog:",
"@react-email/components": "catalog:",
+ "@react-pdf/renderer": "catalog:",
"@slack/web-api": "catalog:",
"@supabase/functions-js": "catalog:",
"@supabase/supabase-js": "catalog:",
@@ -22,6 +24,7 @@
"kysely": "catalog:",
"nanoid": "catalog:",
"nodemailer": "6.10.1",
+ "react": "catalog:",
"react-pdf": "catalog:",
"resend": "3.5.0",
"sst": "catalog:",
@@ -32,6 +35,7 @@
"devDependencies": {
"@carbon/config": "workspace:*",
"@types/nodemailer": "6.4.23",
+ "@types/react": "catalog:",
"tsx": "catalog:",
"typescript": "catalog:"
},
diff --git a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
index 239efc0083..fae6496e9a 100644
--- a/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/cleanup.ts
@@ -278,7 +278,44 @@ export const cleanupFunction = inngest.createFunction(
console.log("No gauges going out of calibration found");
}
- console.log(`Cleanup tasks completed: ${new Date().toISOString()}`);
+ // Clean up old print jobs:
+ // - Completed jobs older than 30 days (served their purpose)
+ // - Failed jobs older than 90 days (retained longer for diagnostics)
+ // - Jobs in generating, queued, or printing status are never cleaned up
+ console.log("Cleaning up old print jobs...");
+ const thirtyDaysAgo = new Date(
+ Date.now() - 30 * 24 * 60 * 60 * 1000
+ ).toISOString();
+ const ninetyDaysAgo = new Date(
+ Date.now() - 90 * 24 * 60 * 60 * 1000
+ ).toISOString();
+
+ const [completedCleanup, failedCleanup] = await Promise.all([
+ serviceRole
+ .from("printJob")
+ .delete()
+ .eq("status", "completed")
+ .lt("completedAt", thirtyDaysAgo),
+ serviceRole
+ .from("printJob")
+ .delete()
+ .eq("status", "failed")
+ .lt("createdAt", ninetyDaysAgo)
+ ]);
+
+ if (completedCleanup.error) {
+ console.error(
+ `Error cleaning up completed print jobs: ${JSON.stringify(completedCleanup.error)}`
+ );
+ }
+ if (failedCleanup.error) {
+ console.error(
+ `Error cleaning up failed print jobs: ${JSON.stringify(failedCleanup.error)}`
+ );
+ }
+ console.log("Print job cleanup completed");
+
+ console.log(`🧹 Cleanup tasks completed: ${new Date().toISOString()}`);
});
}
);
diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.ts
index 99070d5d73..a66740cb9e 100644
--- a/packages/jobs/src/inngest/functions/tasks/index.ts
+++ b/packages/jobs/src/inngest/functions/tasks/index.ts
@@ -1,6 +1,8 @@
export { modelThumbnailFunction } from "./model-thumbnail";
export { onboardFunction } from "./onboard";
export { postTransactionFunction } from "./post-transaction";
+export { printJobFunction } from "./print-job";
+export { printJobDeliverFunction } from "./print-job-deliver";
export { recalculateFunction } from "./recalculate";
export { rescheduleJobFunction } from "./reschedule-job";
export { updatePermissionsFunction } from "./update-permissions";
diff --git a/packages/jobs/src/inngest/functions/tasks/print-job-deliver.ts b/packages/jobs/src/inngest/functions/tasks/print-job-deliver.ts
new file mode 100644
index 0000000000..0755fd6def
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/print-job-deliver.ts
@@ -0,0 +1,95 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { updatePrintJobStatus } from "@carbon/printing";
+import { sendToProxyBox } from "@carbon/printing/printing.server";
+import { NonRetriableError } from "inngest";
+import { inngest } from "../../client";
+
+export const printJobDeliverFunction = inngest.createFunction(
+ {
+ id: "print-job-deliver",
+ retries: 0
+ },
+ { event: "carbon/print-job-deliver" },
+ async ({ event }) => {
+ const client = getCarbonServiceRole();
+ const { printJobId, companyId } = event.data;
+
+ const { data: job, error: jobError } = await client
+ .from("printJob")
+ .select("id, content, contentType, printerUrl, status, attempts")
+ .eq("id", printJobId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (jobError || !job) {
+ throw new NonRetriableError(`Print job not found: ${printJobId}`);
+ }
+
+ if (!job.content || !job.contentType) {
+ await updatePrintJobStatus(client, printJobId, companyId, "failed", {
+ error: "Print job has no content"
+ });
+ throw new NonRetriableError("Print job has no content");
+ }
+
+ const { data: route } = await client
+ .from("printerRoute")
+ .select("apiKey")
+ .eq("printerUrl", job.printerUrl)
+ .eq("companyId", companyId)
+ .limit(1)
+ .maybeSingle();
+
+ const apiKey = route?.apiKey;
+
+ await client
+ .from("printJob")
+ .update({
+ status: "printing",
+ attempts: (job.attempts ?? 0) + 1,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", printJobId)
+ .eq("companyId", companyId);
+
+ try {
+ const content =
+ job.contentType === "pdf"
+ ? Buffer.from(job.content, "base64")
+ : job.content;
+
+ await sendToProxyBox({
+ url: job.printerUrl,
+ apiKey,
+ content
+ });
+
+ await updatePrintJobStatus(client, printJobId, companyId, "completed");
+
+ return { success: true };
+ } catch (err) {
+ const errorMessage =
+ err instanceof Error ? err.message : "Unknown delivery error";
+
+ const isTimeout =
+ err instanceof Error &&
+ (err.name === "AbortError" ||
+ errorMessage.includes("aborted") ||
+ errorMessage.includes("timeout"));
+
+ await updatePrintJobStatus(client, printJobId, companyId, "failed", {
+ error: errorMessage
+ });
+
+ if (isTimeout) {
+ // Don't retry on timeout — content was likely already delivered
+ // to the print server. Retrying would print duplicate copies.
+ throw new NonRetriableError(
+ `Delivery timed out — content may have been printed. ${errorMessage}`
+ );
+ }
+
+ throw err;
+ }
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/index.tsx b/packages/jobs/src/inngest/functions/tasks/print-job/index.tsx
new file mode 100644
index 0000000000..c804391c25
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/print-job/index.tsx
@@ -0,0 +1,310 @@
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import type { Database } from "@carbon/database";
+import { BINDERY_PRESS_API_KEY } from "@carbon/env";
+import type { DocumentTypeId } from "@carbon/printing";
+import {
+ createPrintJob,
+ getDocumentType,
+ getDocumentTypesForSource,
+ getPrinterContextForSource,
+ updatePrintJobContent,
+ updatePrintJobStatus
+} from "@carbon/printing";
+import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { NonRetriableError } from "inngest";
+import { inngest } from "../../../client";
+import type { GeneratedContent, PrintableDocumentItem } from "./renderers";
+import { renderItemBuiltIn, renderItemWithTemplate } from "./renderers";
+import {
+ resolveKanbanData,
+ resolveStorageUnitData,
+ resolveTrackedEntityData
+} from "./resolvers";
+
+const DEFAULT_MEDIA_SIZE_ID = "label2x1";
+
+type Payload = {
+ sourceDocument: string;
+ sourceDocumentId: string;
+ companyId: string;
+ userId: string;
+ locationId?: string;
+ workCenterId?: string;
+ printerRouteId?: string;
+};
+
+export const printJobFunction = inngest.createFunction(
+ { id: "print-job", retries: 0 },
+ { event: "carbon/print-job" },
+ async ({ event, step }) => {
+ const client = getCarbonServiceRole();
+ const payload: Payload = event.data;
+ const {
+ sourceDocument,
+ sourceDocumentId,
+ companyId,
+ userId,
+ locationId,
+ workCenterId,
+ printerRouteId: explicitPrinterRouteId
+ } = payload;
+
+ const thirtySecondsAgo = new Date(Date.now() - 30_000).toISOString();
+ const { count: recentJobCount } = await client
+ .from("printJob")
+ .select("id", { count: "exact", head: true })
+ .eq("sourceDocumentId", sourceDocumentId)
+ .eq("companyId", companyId)
+ .eq("origin", "auto")
+ .gte("createdAt", thirtySecondsAgo);
+
+ if (recentJobCount && recentJobCount > 0) {
+ throw new NonRetriableError(
+ `Print jobs already exist for ${sourceDocument} ${sourceDocumentId}`
+ );
+ }
+
+ let printerConfig: Awaited<ReturnType<typeof getCachedPrinterConfig>> =
+ null;
+
+ if (explicitPrinterRouteId) {
+ const { data: route } = await client
+ .from("printerRoute")
+ .select("id, name, format, mediaSizeId, printerUrl, apiKey, templateId")
+ .eq("id", explicitPrinterRouteId)
+ .eq("companyId", companyId)
+ .single();
+ if (route) {
+ printerConfig = {
+ printerRouteId: route.id,
+ printerUrl: route.printerUrl,
+ format: route.format as "zpl" | "pdf",
+ mediaSizeId: route.mediaSizeId,
+ templateId: route.templateId,
+ autoPrint: true
+ };
+ }
+ } else if (locationId) {
+ printerConfig = await getCachedPrinterConfig(
+ client,
+ companyId,
+ locationId,
+ getPrinterContextForSource(sourceDocument, workCenterId),
+ workCenterId
+ );
+ }
+
+ const documentTypeIds = getDocumentTypesForSource(sourceDocument);
+ const allPrintJobIds: string[] = [];
+
+ for (const documentTypeId of documentTypeIds) {
+ const docType = getDocumentType(documentTypeId);
+ if (!docType) continue;
+
+ const printJobIds = await processDocumentType(client, step, {
+ documentTypeId,
+ hasBuiltInRenderer: docType.builtInRenderer !== null,
+ sourceDocument,
+ sourceDocumentId,
+ companyId,
+ userId,
+ printerUrl: printerConfig?.printerUrl ?? "",
+ format: printerConfig?.format ?? docType.defaultFormat,
+ mediaSizeId: printerConfig?.mediaSizeId ?? DEFAULT_MEDIA_SIZE_ID,
+ templateId: printerConfig?.templateId ?? null
+ });
+
+ allPrintJobIds.push(...printJobIds);
+ }
+
+ return { printJobIds: allPrintJobIds, count: allPrintJobIds.length };
+ }
+);
+
+async function resolveDocumentItems(
+ client: SupabaseClient<Database>,
+ documentTypeId: DocumentTypeId,
+ sourceDocument: string,
+ sourceDocumentId: string,
+ companyId: string
+): Promise<{ docs: PrintableDocumentItem[]; readableId: string | null }> {
+ switch (documentTypeId) {
+ case "productLabel": {
+ const resolved = await resolveTrackedEntityData(
+ client,
+ sourceDocument,
+ sourceDocumentId,
+ companyId
+ );
+ return {
+ docs:
+ resolved?.items.map((item) => ({
+ type: "productLabel" as const,
+ item
+ })) ?? [],
+ readableId: resolved?.readableId ?? null
+ };
+ }
+ case "kanbanCard": {
+ const resolved = await resolveKanbanData(client, sourceDocumentId);
+ return {
+ docs:
+ resolved?.items.map((item) => ({
+ type: "kanbanCard" as const,
+ item
+ })) ?? [],
+ readableId: resolved?.readableId ?? null
+ };
+ }
+ case "storageUnitLabel": {
+ const resolved = await resolveStorageUnitData(client, sourceDocumentId);
+ return {
+ docs:
+ resolved?.items.map((item) => ({
+ type: "storageUnitLabel" as const,
+ item
+ })) ?? [],
+ readableId: resolved?.readableId ?? null
+ };
+ }
+ }
+}
+
+function describeDocument(
+ doc: PrintableDocumentItem,
+ readableId: string | null,
+ sourceDocumentId: string
+): string {
+ const parts = [readableId ?? sourceDocumentId];
+
+ switch (doc.type) {
+ case "productLabel":
+ if (doc.item.itemId) parts.push(doc.item.itemId);
+ if (doc.item.number) parts.push(doc.item.number);
+ break;
+ case "kanbanCard":
+ if (doc.item.itemId) parts.push(doc.item.itemId);
+ break;
+ case "storageUnitLabel":
+ break;
+ }
+
+ return parts.join(" — ");
+}
+
+async function processDocumentType(
+ client: SupabaseClient<Database>,
+ step: {
+ sendEvent: (
+ id: string,
+ payload: { name: string; data: Record<string, unknown> }
+ ) => Promise<unknown>;
+ },
+ ctx: {
+ documentTypeId: DocumentTypeId;
+ hasBuiltInRenderer: boolean;
+ sourceDocument: string;
+ sourceDocumentId: string;
+ companyId: string;
+ userId: string;
+ printerUrl: string;
+ format: "zpl" | "pdf";
+ mediaSizeId: string;
+ templateId: string | null;
+ }
+): Promise<string[]> {
+ const {
+ documentTypeId,
+ hasBuiltInRenderer,
+ sourceDocument,
+ sourceDocumentId,
+ companyId,
+ userId,
+ printerUrl,
+ format,
+ mediaSizeId,
+ templateId
+ } = ctx;
+
+ const { docs, readableId } = await resolveDocumentItems(
+ client,
+ documentTypeId,
+ sourceDocument,
+ sourceDocumentId,
+ companyId
+ );
+ if (docs.length === 0) return [];
+
+ const printJobIds: string[] = [];
+
+ for (const doc of docs) {
+ const job = await createPrintJob(client, {
+ companyId,
+ printerUrl,
+ sourceDocument,
+ sourceDocumentId,
+ sourceDocumentReadableId: readableId ?? undefined,
+ description: describeDocument(doc, readableId, sourceDocumentId),
+ status: "generating",
+ origin: "auto",
+ createdBy: userId
+ });
+
+ if (job.error || !job.data) {
+ console.error(`Failed to create print job: ${job.error?.message}`);
+ continue;
+ }
+
+ const jobId = job.data.id;
+ printJobIds.push(jobId);
+
+ try {
+ let content: GeneratedContent;
+
+ if (templateId && BINDERY_PRESS_API_KEY) {
+ content = await renderItemWithTemplate(
+ doc,
+ templateId,
+ BINDERY_PRESS_API_KEY,
+ format
+ );
+ } else if (hasBuiltInRenderer) {
+ content = await renderItemBuiltIn(client, doc, format, mediaSizeId);
+ } else {
+ await updatePrintJobStatus(client, jobId, companyId, "failed", {
+ error: `Document type "${documentTypeId}" requires a BinderyPress template.`
+ });
+ continue;
+ }
+
+ await updatePrintJobContent(
+ client,
+ jobId,
+ companyId,
+ content.content,
+ content.contentType
+ );
+
+ if (printerUrl) {
+ await step.sendEvent(`deliver-${jobId}`, {
+ name: "carbon/print-job-deliver",
+ data: { printJobId: jobId, companyId }
+ });
+ } else {
+ await updatePrintJobStatus(client, jobId, companyId, "completed");
+ }
+ } catch (renderError) {
+ const message =
+ renderError instanceof Error
+ ? renderError.message
+ : String(renderError);
+ console.error(`Rendering failed for job ${jobId}: ${message}`);
+ await updatePrintJobStatus(client, jobId, companyId, "failed", {
+ error: `Rendering failed: ${message}`
+ });
+ }
+ }
+
+ return printJobIds;
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx b/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
new file mode 100644
index 0000000000..94b101158b
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
@@ -0,0 +1,172 @@
+// This module is .tsx because the built-in renderers render React PDF
+// components (ProductLabelPDF, StorageUnitLabelPDF, KanbanLabelPDF) via
+// renderToStream.
+
+import type { Database } from "@carbon/database";
+import {
+ KanbanLabelPDF,
+ ProductLabelPDF,
+ StorageUnitLabelPDF
+} from "@carbon/documents/pdf";
+import {
+ generateProductLabelZPL,
+ generateStorageUnitLabelZPL
+} from "@carbon/documents/zpl";
+import { ERP_URL } from "@carbon/env";
+import { renderWithBinderyPress } from "@carbon/printing/printing.server";
+import type { LabelSize, ProductLabelItem } from "@carbon/utils";
+import { labelSizes } from "@carbon/utils";
+import { renderToStream } from "@react-pdf/renderer";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { ReactElement } from "react";
+import type { KanbanCardItem, StorageUnitItem } from "./resolvers";
+
+export type GeneratedContent = {
+ content: string;
+ contentType: "zpl" | "pdf";
+};
+
+/** A single resolved item tagged with the document type that renders it. */
+export type PrintableDocumentItem =
+ | { type: "productLabel"; item: ProductLabelItem }
+ | { type: "kanbanCard"; item: KanbanCardItem }
+ | { type: "storageUnitLabel"; item: StorageUnitItem };
+
+export async function renderItemWithTemplate(
+ doc: PrintableDocumentItem,
+ templateId: string,
+ apiKey: string,
+ format: "zpl" | "pdf"
+): Promise<GeneratedContent> {
+ const result = await renderWithBinderyPress({
+ apiKey,
+ templateId,
+ data: { ...doc.item },
+ format
+ });
+
+ return {
+ content: result.content,
+ contentType: result.contentType
+ };
+}
+
+export async function renderItemBuiltIn(
+ client: SupabaseClient<Database>,
+ doc: PrintableDocumentItem,
+ format: "zpl" | "pdf",
+ mediaSizeId: string
+): Promise<GeneratedContent> {
+ switch (doc.type) {
+ case "productLabel": {
+ const mediaSize = requireMediaSize(mediaSizeId);
+ if (format === "pdf") {
+ return renderPdfContent(
+ <ProductLabelPDF items={[doc.item]} labelSize={mediaSize} />
+ );
+ }
+ requireZplCapable(mediaSize);
+ return {
+ content: generateProductLabelZPL(doc.item, mediaSize),
+ contentType: "zpl"
+ };
+ }
+ case "kanbanCard":
+ return renderKanbanCardPDF(client, doc.item, format);
+ case "storageUnitLabel": {
+ const mediaSize = requireMediaSize(mediaSizeId);
+ if (format === "pdf") {
+ return renderPdfContent(
+ <StorageUnitLabelPDF items={[doc.item]} labelSize={mediaSize} />
+ );
+ }
+ requireZplCapable(mediaSize);
+ return {
+ content: generateStorageUnitLabelZPL(doc.item, mediaSize),
+ contentType: "zpl"
+ };
+ }
+ }
+}
+
+function requireMediaSize(mediaSizeId: string): LabelSize {
+ const mediaSize = labelSizes.find((s) => s.id === mediaSizeId);
+ if (!mediaSize) {
+ throw new Error(`Unknown media size ${mediaSizeId}`);
+ }
+ return mediaSize;
+}
+
+function requireZplCapable(mediaSize: LabelSize): void {
+ if (!mediaSize.zpl) {
+ throw new Error(`Media size ${mediaSize.id} does not support ZPL`);
+ }
+}
+
+async function renderPdfContent(
+ element: ReactElement
+): Promise<GeneratedContent> {
+ const stream = await renderToStream(element);
+ const body = await streamToBuffer(stream);
+
+ return {
+ content: body.toString("base64"),
+ contentType: "pdf"
+ };
+}
+
+function streamToBuffer(stream: NodeJS.ReadableStream): Promise<Buffer> {
+ return new Promise((resolve, reject) => {
+ const buffers: Uint8Array[] = [];
+ stream.on("data", (d: Uint8Array) => buffers.push(d));
+ stream.on("end", () => resolve(Buffer.concat(buffers)));
+ stream.on("error", reject);
+ });
+}
+
+async function renderKanbanCardPDF(
+ client: SupabaseClient<Database>,
+ item: KanbanCardItem,
+ format: "zpl" | "pdf"
+): Promise<GeneratedContent> {
+ if (format === "zpl") {
+ throw new Error(
+ "Built-in kanban card generation only supports PDF printers."
+ );
+ }
+
+ let thumbnail: string | null = null;
+ if (item.thumbnailPath) {
+ const { data } = await client.storage
+ .from("private")
+ .download(item.thumbnailPath);
+ if (data) {
+ const buffer = Buffer.from(await data.arrayBuffer());
+ const ext = item.thumbnailPath.split(".").pop()?.toLowerCase();
+ const mime = ext === "jpg" || ext === "jpeg" ? "image/jpeg" : "image/png";
+ thumbnail = `data:${mime};base64,${buffer.toString("base64")}`;
+ }
+ }
+
+ return renderPdfContent(
+ <KanbanLabelPDF
+ baseUrl={ERP_URL ?? ""}
+ labels={[
+ {
+ id: item.id,
+ itemId: item.itemId,
+ itemName: item.itemName,
+ itemReadableId: item.itemId,
+ locationName: item.locationName,
+ storageUnitId: item.storageUnitId,
+ storageUnitName: item.storageUnitName,
+ supplierName: item.supplierName,
+ quantity: item.quantity,
+ unitOfMeasureCode: item.unitOfMeasureCode,
+ thumbnail
+ }
+ ]}
+ action="order"
+ />
+ );
+}
diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts b/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts
new file mode 100644
index 0000000000..302f4fb59f
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts
@@ -0,0 +1,283 @@
+import type { Database } from "@carbon/database";
+import { ERP_URL } from "@carbon/env";
+import type { ProductLabelItem } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+export type KanbanCardItem = {
+ id: string;
+ kanbanUrl: string;
+ itemId: string;
+ itemName: string;
+ locationName: string;
+ storageUnitId: string | null;
+ storageUnitName: string | null;
+ supplierName: string | null;
+ quantity: number;
+ unitOfMeasureCode: string | null;
+ thumbnailPath: string | null;
+};
+
+export type StorageUnitItem = {
+ id: string;
+ name: string;
+};
+
+export type ResolvedData<T> = {
+ items: T[];
+ readableId: string | null;
+};
+
+type TrackedEntity = Database["public"]["Tables"]["trackedEntity"]["Row"];
+
+export async function resolveTrackedEntityData(
+ client: SupabaseClient<Database>,
+ sourceDocument: string,
+ sourceDocumentId: string,
+ companyId: string
+): Promise<ResolvedData<ProductLabelItem> | null> {
+ const { trackedEntities, readableId } = await queryTrackedEntities(
+ client,
+ sourceDocument,
+ sourceDocumentId,
+ companyId
+ );
+
+ if (!trackedEntities?.length) return null;
+
+ const items = await enrichTrackedEntities(client, trackedEntities);
+ if (items.length === 0) return null;
+
+ return { items, readableId };
+}
+
+export async function resolveKanbanData(
+ client: SupabaseClient<Database>,
+ sourceDocumentId: string
+): Promise<ResolvedData<KanbanCardItem> | null> {
+ const { data: kanban } = await client
+ .from("kanbans")
+ .select("*")
+ .eq("id", sourceDocumentId)
+ .single();
+
+ if (!kanban) return null;
+
+ const kanbanUrl = `${ERP_URL ?? ""}/api/kanban/${sourceDocumentId}`;
+
+ return {
+ items: [
+ {
+ id: sourceDocumentId,
+ kanbanUrl,
+ itemId: kanban.readableIdWithRevision || kanban.itemId || "",
+ itemName: kanban.name || "",
+ locationName: kanban.locationName || "",
+ storageUnitId: kanban.storageUnitId,
+ storageUnitName: kanban.storageUnitName,
+ supplierName: kanban.supplierName,
+ quantity: kanban.quantity ?? 0,
+ unitOfMeasureCode: kanban.purchaseUnitOfMeasureCode,
+ thumbnailPath: kanban.thumbnailPath
+ }
+ ],
+ readableId: kanban.readableIdWithRevision ?? null
+ };
+}
+
+export async function resolveStorageUnitData(
+ client: SupabaseClient<Database>,
+ sourceDocumentId: string
+): Promise<ResolvedData<StorageUnitItem> | null> {
+ const { data: unit } = await client
+ .from("storageUnit")
+ .select("id, name")
+ .eq("id", sourceDocumentId)
+ .single();
+
+ if (!unit) return null;
+
+ return {
+ items: [{ name: unit.name, id: unit.id }],
+ readableId: unit.name
+ };
+}
+
+async function queryTrackedEntities(
+ client: SupabaseClient<Database>,
+ sourceDocument: string,
+ sourceDocumentId: string,
+ companyId: string
+): Promise<{
+ trackedEntities: TrackedEntity[] | null;
+ readableId: string | null;
+}> {
+ switch (sourceDocument) {
+ case "Receipt": {
+ const { data: receipt } = await client
+ .from("receipt")
+ .select("receiptId")
+ .eq("id", sourceDocumentId)
+ .single();
+
+ const { data: trackedEntities } = await client
+ .from("trackedEntity")
+ .select("*")
+ .eq("attributes ->> Receipt", sourceDocumentId)
+ .eq("companyId", companyId);
+
+ return { trackedEntities, readableId: receipt?.receiptId ?? null };
+ }
+ case "Shipment": {
+ const { data: shipment } = await client
+ .from("shipment")
+ .select("shipmentId")
+ .eq("id", sourceDocumentId)
+ .single();
+
+ const { data: trackedEntities } = await client
+ .from("trackedEntity")
+ .select("*")
+ .eq("attributes ->> Shipment", sourceDocumentId)
+ .eq("companyId", companyId);
+
+ return { trackedEntities, readableId: shipment?.shipmentId ?? null };
+ }
+ case "Operation": {
+ const { data: jobOperation } = await client
+ .from("jobOperation")
+ .select(
+ "jobMakeMethodId, ...jobMakeMethod(...item(readableIdWithRevision))"
+ )
+ .eq("id", sourceDocumentId)
+ .single();
+
+ if (!jobOperation?.jobMakeMethodId)
+ return { trackedEntities: null, readableId: null };
+
+ const { data: trackedEntities } = await client
+ .from("trackedEntity")
+ .select("*")
+ .eq("attributes->>Job Make Method", jobOperation?.jobMakeMethodId)
+ .order("createdAt", { ascending: true });
+
+ return {
+ trackedEntities,
+ readableId: jobOperation.readableIdWithRevision ?? null
+ };
+ }
+ case "Entity":
+ case "Split": {
+ const { data: trackedEntity } = await client
+ .from("trackedEntity")
+ .select("*")
+ .eq("id", sourceDocumentId)
+ .single();
+
+ return {
+ trackedEntities: trackedEntity ? [trackedEntity] : null,
+ readableId: trackedEntity?.readableId ?? null
+ };
+ }
+ case "Job": {
+ const { data: trackedEntity } = await client
+ .from("trackedEntity")
+ .select("*")
+ .eq("id", sourceDocumentId)
+ .single();
+
+ if (!trackedEntity) return { trackedEntities: null, readableId: null };
+
+ const jobId = (trackedEntity.attributes as Record<string, unknown>)
+ ?.Job as string | undefined;
+ let readableId: string | null = null;
+ if (jobId) {
+ const { data: job } = await client
+ .from("job")
+ .select("jobId")
+ .eq("id", jobId)
+ .single();
+ readableId = job?.jobId ?? null;
+ }
+
+ return {
+ trackedEntities: [trackedEntity],
+ readableId
+ };
+ }
+ case "StockTransfer": {
+ const { data: stockTransfer } = await client
+ .from("stockTransfer")
+ .select("stockTransferId")
+ .eq("id", sourceDocumentId)
+ .single();
+
+ const { data: lines } = await client
+ .from("stockTransferLine")
+ .select("trackedEntityId")
+ .eq("stockTransferId", sourceDocumentId)
+ .not("trackedEntityId", "is", null);
+
+ const entityIds = [
+ ...new Set(
+ (lines ?? [])
+ .map((l) => l.trackedEntityId)
+ .filter((id): id is string => !!id)
+ )
+ ];
+
+ if (entityIds.length === 0) {
+ return {
+ trackedEntities: null,
+ readableId: stockTransfer?.stockTransferId ?? null
+ };
+ }
+
+ const { data: trackedEntities } = await client
+ .from("trackedEntity")
+ .select("*")
+ .in("id", entityIds)
+ .eq("companyId", companyId);
+
+ return {
+ trackedEntities,
+ readableId: stockTransfer?.stockTransferId ?? null
+ };
+ }
+ default:
+ return { trackedEntities: null, readableId: null };
+ }
+}
+
+async function enrichTrackedEntities(
+ client: SupabaseClient<Database>,
+ trackedEntities: TrackedEntity[]
+): Promise<ProductLabelItem[]> {
+ const sourceDocIds = [
+ ...new Set(
+ trackedEntities
+ .map((te) => te.sourceDocumentId)
+ .filter(Boolean) as string[]
+ )
+ ];
+
+ const { data: items } = await client
+ .from("item")
+ .select("id, readableId, revision, itemTrackingType")
+ .in("id", sourceDocIds);
+
+ const itemMap = new Map(items?.map((i) => [i.id, i]) ?? []);
+
+ return trackedEntities.flatMap((te) => {
+ const item = itemMap.get(te.sourceDocumentId ?? "");
+ if (!item) return [];
+
+ return {
+ itemId: item.readableId,
+ revision: item.revision ?? "0",
+ number: te.readableId || te.id,
+ trackedEntityId: te.id,
+ quantity: te.quantity ?? 1,
+ trackingType: item.itemTrackingType
+ };
+ });
+}
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index fcda0452ae..85598ffacb 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -42,6 +42,8 @@ import {
modelThumbnailFunction,
onboardFunction,
postTransactionFunction,
+ printJobDeliverFunction,
+ printJobFunction,
recalculateFunction,
rescheduleJobFunction,
updatePermissionsFunction,
@@ -70,6 +72,8 @@ export const functions = [
postTransactionFunction,
rescheduleJobFunction,
onboardFunction,
+ printJobFunction,
+ printJobDeliverFunction,
// Scheduled
cleanupFunction,
dispatchFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 8fc91f8f41..99d4f84868 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -277,6 +277,26 @@ export type Events = {
};
};
+ // Print job events
+ "carbon/print-job": {
+ data: {
+ sourceDocument: string;
+ sourceDocumentId: string;
+ companyId: string;
+ userId: string;
+ locationId?: string;
+ workCenterId?: string;
+ printerRouteId?: string;
+ };
+ };
+
+ "carbon/print-job-deliver": {
+ data: {
+ printJobId: string;
+ companyId: string;
+ };
+ };
+
// Cleanup tasks
"carbon/cleanup": {
data: Record<string, never>;
diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.ts
index b2ccdc4ab3..6cbdd100a5 100644
--- a/packages/lib/src/trigger.ts
+++ b/packages/lib/src/trigger.ts
@@ -13,6 +13,8 @@ const taskToEvent = {
onboard: "carbon/onboard",
"paperless-parts": "carbon/paperless-parts",
"post-transactions": "carbon/post-transaction",
+ "print-job-deliver": "carbon/print-job-deliver",
+ "print-job": "carbon/print-job",
recalculate: "carbon/recalculate",
"schedule-job": "carbon/reschedule-job",
"send-email": "carbon/send-email",
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index ed946927a8..7ded89be71 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -270,6 +270,9 @@ msgstr "Fügen Sie unten eine Spalte hinzu, um die Ansicht zu sortieren"
msgid "Add a comment..."
msgstr "Einen Kommentar hinzufügen..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Fügen Sie einen Drucker in den Druckeinstellungen hinzu, um Etiketten direkt zu drucken."
+
msgid "Add Actions"
msgstr "Aktionen hinzufügen"
@@ -339,6 +342,9 @@ msgstr "Partner hinzufügen"
msgid "Add Permissions"
msgstr "Berechtigungen hinzufügen"
+msgid "Add Printer"
+msgstr "Drucker hinzufügen"
+
msgid "Add Property"
msgstr "Eigenschaft hinzufügen"
@@ -759,6 +765,10 @@ msgstr "Sind Sie sicher, dass Sie den Zahlungsbedingung {0} löschen möchten? D
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "Sind Sie sicher, dass Sie die Preisregel: {0} löschen möchten? Dies kann nicht rückgängig gemacht werden."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "Sind Sie sicher, dass Sie den Drucker \"{0}\" löschen möchten? Alle Zuweisungen, die auf diesen Drucker verweisen, werden gelöscht. Dies kann nicht rückgängig gemacht werden."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Anlageklassen"
msgid "Assets"
msgstr "Vermögenswerte"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Drucker Standorten zuweisen. Versand, Empfang und Arbeitszentren erben die Standortvorgabe, sofern nicht überschrieben."
+
msgid "Assign To"
msgstr "Zuweisen an"
@@ -2239,9 +2252,6 @@ msgstr "Standardeinheit"
msgid "Defaults"
msgstr "Standardwerte"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Definieren Sie die Standardgröße des Produktetiketts. Wird zur Verfolgung von Artikeln im Bestand verwendet."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Definieren Sie die Bedingungen für Bestellungen"
@@ -2614,6 +2624,9 @@ msgstr "Herunterladen"
msgid "Download CSV"
msgstr "CSV herunterladen"
+msgid "Download Labels"
+msgstr "Etiketten herunterladen"
+
msgid "Download PDF"
msgstr "PDF herunterladen"
@@ -2702,6 +2715,9 @@ msgstr "Dauer"
msgid "e.g. DWG-1234"
msgstr "z.B. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "z.B. Zebra 2x1"
+
msgid "Edit"
msgstr "Bearbeiten"
@@ -3878,6 +3894,9 @@ msgstr "Wenn Artikel bereits vorhanden sind"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "Wenn Sie die Teilenummern ändern möchten, klicken Sie bitte auf Abbrechen und weisen Sie die Teile für jedes Zeilenelement manuell zu, bevor Sie konvertieren."
+msgid "Imperial"
+msgstr "Imperial"
+
msgid "Implementation Support"
msgstr "Implementierungsunterstützung"
@@ -4337,6 +4356,9 @@ msgstr "Mehr erfahren"
msgid "Leave any related receipts untouched"
msgstr "Alle zugehörigen Belege unverändert lassen"
+msgid "Leave blank for built-in"
+msgstr "Leer lassen für integriert"
+
msgid "Leave empty for exact match"
msgstr "Leer lassen für exakte Übereinstimmung"
@@ -4714,6 +4736,9 @@ msgstr "Mittlere Reparaturzeit"
msgid "Measurement Standard"
msgstr "Messnorm"
+msgid "Media Size"
+msgstr "Mediengröße"
+
msgid "Members"
msgstr "Mitglieder"
@@ -5255,6 +5280,9 @@ msgstr "Kein Bild"
msgid "No issue types configured"
msgstr "Keine Problemtypen konfiguriert"
+msgid "No locations found."
+msgstr "Keine Standorte gefunden."
+
msgid "No logo uploaded"
msgstr "Kein Logo hochgeladen"
@@ -5306,6 +5334,12 @@ msgstr "Keine Preisgestaltung für die ausgewählte Menge"
msgid "No pricing options found"
msgstr "Keine Preisoptionen gefunden"
+msgid "No printer configured"
+msgstr "Kein Drucker konfiguriert"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "Keine Drucker konfiguriert. Klicken Sie auf „Drucker hinzufügen\", um einen zu erstellen."
+
msgid "No Quote"
msgstr "Kein Angebot"
@@ -5573,6 +5607,9 @@ msgstr "Bestellungen"
msgid "Orders submitted"
msgstr "Bestellungen eingereicht"
+msgid "Origin"
+msgstr "Ursprung"
+
msgid "Other Type"
msgstr "Sonstiger Typ"
@@ -5705,12 +5742,18 @@ msgstr "Zahlungsbedingungen"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Dokument)"
+
msgid "PDF downloaded"
msgstr "PDF heruntergeladen"
msgid "PDF pages"
msgstr "PDF-Seiten"
+msgid "PDF Preview"
+msgstr "PDF-Vorschau"
+
msgid "PDF Watermark"
msgstr "PDF-Wasserzeichen"
@@ -5750,6 +5793,9 @@ msgstr "Foto erfolgreich entfernt"
msgid "Photo uploaded successfully"
msgstr "Foto erfolgreich hochgeladen"
+msgid "Physical printers available for assignment."
+msgstr "Physische Drucker verfügbar zur Zuweisung."
+
msgid "Pick"
msgstr "Auswählen"
@@ -5900,6 +5946,9 @@ msgstr "Zurück"
msgid "Preview"
msgstr "Vorschau"
+msgid "Preview failed: {error}"
+msgstr "Vorschau fehlgeschlagen: {error}"
+
msgid "Preview Quantity"
msgstr "Vorschaumenge"
@@ -5942,9 +5991,35 @@ msgstr "Preisregeln"
msgid "Pricing Trace"
msgstr "Preisablauf"
+msgid "Print"
+msgstr "Drucken"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Drucke {0} Etiketten"
+
+msgid "Print Jobs"
+msgstr "Druckaufträge"
+
msgid "Print Label"
msgstr "Etikett drucken"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Druckausgabe ({0})"
+
+msgid "Printer Settings"
+msgstr "Druckereinstellungen"
+
+msgid "Printer URL"
+msgstr "Drucker-URL"
+
+msgid "Printers"
+msgstr "Drucker"
+
+msgid "Printing"
+msgstr "Druck"
+
msgid "Priorities"
msgstr "Prioritäten"
@@ -5975,9 +6050,6 @@ msgstr "Prozesstyp"
msgid "Processes"
msgstr "Prozesse"
-msgid "Product Label Size"
-msgstr "Produktetikettengröße"
-
msgid "Production"
msgstr "Produktion"
@@ -6405,6 +6477,9 @@ msgstr "Entfernen Sie diesen Speichertyp aus allen referenzierenden Speichereinh
msgid "Remove Transfer"
msgstr "Transfer entfernen"
+msgid "Rendering label preview..."
+msgstr "Label-Vorschau wird gerendert..."
+
msgid "Reopen"
msgstr "Erneut öffnen"
@@ -6462,6 +6537,9 @@ msgstr "Bericht"
msgid "Reports"
msgstr "Berichte"
+msgid "Reprint"
+msgstr "Erneut drucken"
+
msgid "Request Approval"
msgstr "Genehmigung anfordern"
@@ -6946,6 +7024,9 @@ msgstr "Elementtyp auswählen"
msgid "Select items"
msgstr "Artikel auswählen"
+msgid "Select Printer"
+msgstr "Drucker auswählen"
+
msgid "Select Quantities"
msgstr "Mengen auswählen"
@@ -7711,12 +7792,18 @@ msgstr "Steuern:"
msgid "Temperature"
msgstr "Temperatur"
+msgid "Template ID"
+msgstr "Vorlagen-ID"
+
msgid "Terms and Privacy"
msgstr "Bedingungen und Datenschutz"
msgid "Terms of Service"
msgstr "Nutzungsbedingungen"
+msgid "Test"
+msgstr "Testen"
+
msgid "Test Value"
msgstr "Testwert"
@@ -8029,9 +8116,6 @@ msgstr "Verfolgung"
msgid "Tracking ID"
msgstr "Verfolgungskennung"
-msgid "Tracking Labels"
-msgstr "Verfolgungsetiketten"
-
msgid "Tracking Number"
msgstr "Verfolgungsnummer"
@@ -8455,6 +8539,9 @@ msgstr "Offene Anfragen anzeigen"
msgid "View Permissions"
msgstr "Anzeigeberechtigungen"
+msgid "View Prints"
+msgstr "Drucke anzeigen"
+
msgid "View Production Events"
msgstr "Produktionsereignisse anzeigen"
@@ -8770,3 +8857,9 @@ msgstr "Vergrößern"
msgid "Zoom out"
msgstr "Verkleinern"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Thermisches Etikett)"
+
+msgid "ZPL Label Preview"
+msgstr "ZPL-Etikettenvorschau"
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index 520b5873ad..48a1063625 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - Satz {1}"
msgid "{0} Active"
msgstr "{0} Aktiv"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} verfügbar"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Hinzufügen"
msgid "Add & Issue"
msgstr "Hinzufügen & Ausgeben"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Fügen Sie einen Drucker in den Druckeinstellungen hinzu, um Etiketten direkt zu drucken."
+
msgid "Add Inventory"
msgstr "Bestand hinzufügen"
@@ -106,11 +105,6 @@ msgstr "Authentifizierungsfehler"
msgid "Batch"
msgstr "Charge"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Charge {0} ({1} verfügbar)"
-
msgid "Batch is not available"
msgstr "Charge ist nicht verfügbar"
@@ -272,6 +266,9 @@ msgstr "Stillstand"
msgid "Download"
msgstr "Herunterladen"
+msgid "Download Labels"
+msgstr "Etiketten herunterladen"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Datei hierher ziehen oder klicken, um eine Datei auszuwählen"
@@ -387,6 +384,9 @@ msgstr "Ideen, Vorschläge oder Probleme?"
msgid "Impact"
msgstr "Auswirkung"
+msgid "Imperial"
+msgstr "Imperiale"
+
msgid "In Progress"
msgstr "In Bearbeitung"
@@ -501,6 +501,9 @@ msgstr "Materialien"
msgid "Maximum number of records reached"
msgstr "Maximale Anzahl an Datensätzen erreicht"
+msgid "Metric"
+msgstr "Metrisch"
+
msgid "Model"
msgstr "Modell"
@@ -580,6 +583,9 @@ msgstr "Keine Option gefunden."
msgid "No options found."
msgstr "Keine Optionen gefunden."
+msgid "No printer configured"
+msgstr "Kein Drucker konfiguriert"
+
msgid "No recent operations"
msgstr "Keine kürzlichen Arbeitsgänge"
@@ -683,6 +689,12 @@ msgstr "Zurück"
msgid "Preventive"
msgstr "Vorbeugend"
+msgid "Print"
+msgstr "Drucken"
+
+msgid "Printer Settings"
+msgstr "Druckereinstellungen"
+
msgid "Priority"
msgstr "Priorität"
@@ -808,6 +820,9 @@ msgstr "Artikel auswählen..."
msgid "Select Batch {0}"
msgstr "Charge {0} auswählen"
+msgid "Select Printer"
+msgstr "Drucker auswählen"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Seriennummer {0} auswählen"
@@ -824,10 +839,6 @@ msgstr "Senden"
msgid "Serial"
msgstr "Serie"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Serie {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Seriennummer {0}"
@@ -962,9 +973,6 @@ msgstr "Gesamt: {0}"
msgid "Tracking"
msgstr "Verfolgung"
-msgid "Tracking Labels"
-msgstr "Verfolgungsetiketten"
-
msgid "Type a message..."
msgstr "Nachricht eingeben..."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index db2f7b338d..1638a5cea5 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -270,6 +270,9 @@ msgstr "Add a column below to sort the view"
msgid "Add a comment..."
msgstr "Add a comment..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Add a printer in the printing settings to print labels directly."
+
msgid "Add Actions"
msgstr "Add Actions"
@@ -339,6 +342,9 @@ msgstr "Add Partner"
msgid "Add Permissions"
msgstr "Add Permissions"
+msgid "Add Printer"
+msgstr "Add Printer"
+
msgid "Add Property"
msgstr "Add Property"
@@ -759,6 +765,10 @@ msgstr "Are you sure you want to delete the payment term: {0}? This cannot be un
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Asset Classes"
msgid "Assets"
msgstr "Assets"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+
msgid "Assign To"
msgstr "Assign To"
@@ -2239,9 +2252,6 @@ msgstr "Default Unit"
msgid "Defaults"
msgstr "Defaults"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Define the default size of the product label. Used for tracking items in inventory."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Define the terms and conditions for purchase orders"
@@ -2614,6 +2624,9 @@ msgstr "Download"
msgid "Download CSV"
msgstr "Download CSV"
+msgid "Download Labels"
+msgstr "Download Labels"
+
msgid "Download PDF"
msgstr "Download PDF"
@@ -2702,6 +2715,9 @@ msgstr "Duration"
msgid "e.g. DWG-1234"
msgstr "e.g. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "e.g. Zebra 2x1"
+
msgid "Edit"
msgstr "Edit"
@@ -3878,6 +3894,9 @@ msgstr "If items already exist"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
+msgid "Imperial"
+msgstr "Imperial"
+
msgid "Implementation Support"
msgstr "Implementation Support"
@@ -4337,6 +4356,9 @@ msgstr "Learn more"
msgid "Leave any related receipts untouched"
msgstr "Leave any related receipts untouched"
+msgid "Leave blank for built-in"
+msgstr "Leave blank for built-in"
+
msgid "Leave empty for exact match"
msgstr "Leave empty for exact match"
@@ -4714,6 +4736,9 @@ msgstr "Mean Time To Repair"
msgid "Measurement Standard"
msgstr "Measurement Standard"
+msgid "Media Size"
+msgstr "Media Size"
+
msgid "Members"
msgstr "Members"
@@ -5255,6 +5280,9 @@ msgstr "No image"
msgid "No issue types configured"
msgstr "No issue types configured"
+msgid "No locations found."
+msgstr "No locations found."
+
msgid "No logo uploaded"
msgstr "No logo uploaded"
@@ -5306,6 +5334,12 @@ msgstr "No pricing for selected quantity"
msgid "No pricing options found"
msgstr "No pricing options found"
+msgid "No printer configured"
+msgstr "No printer configured"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "No printers configured. Click \"Add Printer\" to create one."
+
msgid "No Quote"
msgstr "No Quote"
@@ -5573,6 +5607,9 @@ msgstr "Orders"
msgid "Orders submitted"
msgstr "Orders submitted"
+msgid "Origin"
+msgstr "Origin"
+
msgid "Other Type"
msgstr "Other Type"
@@ -5705,12 +5742,18 @@ msgstr "Payment Terms"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Document)"
+
msgid "PDF downloaded"
msgstr "PDF downloaded"
msgid "PDF pages"
msgstr "PDF pages"
+msgid "PDF Preview"
+msgstr "PDF Preview"
+
msgid "PDF Watermark"
msgstr "PDF Watermark"
@@ -5750,6 +5793,9 @@ msgstr "Photo removed successfully"
msgid "Photo uploaded successfully"
msgstr "Photo uploaded successfully"
+msgid "Physical printers available for assignment."
+msgstr "Physical printers available for assignment."
+
msgid "Pick"
msgstr "Pick"
@@ -5900,6 +5946,9 @@ msgstr "Prev"
msgid "Preview"
msgstr "Preview"
+msgid "Preview failed: {error}"
+msgstr "Preview failed: {error}"
+
msgid "Preview Quantity"
msgstr "Preview Quantity"
@@ -5942,9 +5991,35 @@ msgstr "Pricing Rules"
msgid "Pricing Trace"
msgstr "Pricing Trace"
+msgid "Print"
+msgstr "Print"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Print {0} Labels"
+
+msgid "Print Jobs"
+msgstr "Print Jobs"
+
msgid "Print Label"
msgstr "Print Label"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Print Output ({0})"
+
+msgid "Printer Settings"
+msgstr "Printer Settings"
+
+msgid "Printer URL"
+msgstr "Printer URL"
+
+msgid "Printers"
+msgstr "Printers"
+
+msgid "Printing"
+msgstr "Printing"
+
msgid "Priorities"
msgstr "Priorities"
@@ -5975,9 +6050,6 @@ msgstr "Process Type"
msgid "Processes"
msgstr "Processes"
-msgid "Product Label Size"
-msgstr "Product Label Size"
-
msgid "Production"
msgstr "Production"
@@ -6405,6 +6477,9 @@ msgstr "Remove this storage type from all referencing storage units and delete i
msgid "Remove Transfer"
msgstr "Remove Transfer"
+msgid "Rendering label preview..."
+msgstr "Rendering label preview..."
+
msgid "Reopen"
msgstr "Reopen"
@@ -6462,6 +6537,9 @@ msgstr "Report"
msgid "Reports"
msgstr "Reports"
+msgid "Reprint"
+msgstr "Reprint"
+
msgid "Request Approval"
msgstr "Request Approval"
@@ -6946,6 +7024,9 @@ msgstr "Select Item Type"
msgid "Select items"
msgstr "Select items"
+msgid "Select Printer"
+msgstr "Select Printer"
+
msgid "Select Quantities"
msgstr "Select Quantities"
@@ -7711,12 +7792,18 @@ msgstr "Tax:"
msgid "Temperature"
msgstr "Temperature"
+msgid "Template ID"
+msgstr "Template ID"
+
msgid "Terms and Privacy"
msgstr "Terms and Privacy"
msgid "Terms of Service"
msgstr "Terms of Service"
+msgid "Test"
+msgstr "Test"
+
msgid "Test Value"
msgstr "Test Value"
@@ -8029,9 +8116,6 @@ msgstr "Tracking"
msgid "Tracking ID"
msgstr "Tracking ID"
-msgid "Tracking Labels"
-msgstr "Tracking Labels"
-
msgid "Tracking Number"
msgstr "Tracking Number"
@@ -8455,6 +8539,9 @@ msgstr "View Open RFQs"
msgid "View Permissions"
msgstr "View Permissions"
+msgid "View Prints"
+msgstr "View Prints"
+
msgid "View Production Events"
msgstr "View Production Events"
@@ -8774,3 +8861,9 @@ msgstr "Zoom in"
msgid "Zoom out"
msgstr "Zoom out"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Thermal Label)"
+
+msgid "ZPL Label Preview"
+msgstr "ZPL Label Preview"
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index b84654316b..cd57440e0f 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - Set {1}"
msgid "{0} Active"
msgstr "{0} Active"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} available"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Add"
msgid "Add & Issue"
msgstr "Add & Issue"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Add a printer in the printing settings to print labels directly."
+
msgid "Add Inventory"
msgstr "Add Inventory"
@@ -106,11 +105,6 @@ msgstr "Authentication Error"
msgid "Batch"
msgstr "Batch"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Batch {0} ({1} available)"
-
msgid "Batch is not available"
msgstr "Batch is not available"
@@ -272,6 +266,9 @@ msgstr "Down"
msgid "Download"
msgstr "Download"
+msgid "Download Labels"
+msgstr "Download Labels"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Drag and drop a file here, or click to select a file"
@@ -387,6 +384,9 @@ msgstr "Ideas, suggestions or problems?"
msgid "Impact"
msgstr "Impact"
+msgid "Imperial"
+msgstr "Imperial"
+
msgid "In Progress"
msgstr "In Progress"
@@ -501,6 +501,9 @@ msgstr "Materials"
msgid "Maximum number of records reached"
msgstr "Maximum number of records reached"
+msgid "Metric"
+msgstr "Metric"
+
msgid "Model"
msgstr "Model"
@@ -580,6 +583,9 @@ msgstr "No option found."
msgid "No options found."
msgstr "No options found."
+msgid "No printer configured"
+msgstr "No printer configured"
+
msgid "No recent operations"
msgstr "No recent operations"
@@ -683,6 +689,12 @@ msgstr "Prev"
msgid "Preventive"
msgstr "Preventive"
+msgid "Print"
+msgstr "Print"
+
+msgid "Printer Settings"
+msgstr "Printer Settings"
+
msgid "Priority"
msgstr "Priority"
@@ -808,6 +820,9 @@ msgstr "Select an item..."
msgid "Select Batch {0}"
msgstr "Select Batch {0}"
+msgid "Select Printer"
+msgstr "Select Printer"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Select Serial {0}"
@@ -824,10 +839,6 @@ msgstr "Send"
msgid "Serial"
msgstr "Serial"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Serial {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Serial Number {0}"
@@ -962,9 +973,6 @@ msgstr "Total: {0}"
msgid "Tracking"
msgstr "Tracking"
-msgid "Tracking Labels"
-msgstr "Tracking Labels"
-
msgid "Type a message..."
msgstr "Type a message..."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index a4923131b9..64969c5f4c 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -270,6 +270,9 @@ msgstr "Añade una columna a continuación para ordenar la vista"
msgid "Add a comment..."
msgstr "Añade un comentario..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Añade una impresora en la configuración de impresión para imprimir etiquetas directamente."
+
msgid "Add Actions"
msgstr "Agregar Acciones"
@@ -339,6 +342,9 @@ msgstr "Agregar Socio"
msgid "Add Permissions"
msgstr "Agregar Permisos"
+msgid "Add Printer"
+msgstr "Agregar impresora"
+
msgid "Add Property"
msgstr "Agregar propiedad"
@@ -759,6 +765,10 @@ msgstr "¿Estás seguro de que deseas eliminar el término de pago: {0}? Esto no
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "¿Estás seguro de que deseas eliminar la regla de precios: {0}? Esto no se puede deshacer."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "¿Estás seguro de que deseas eliminar la impresora \"{0}\"? Se borrarán todas las asignaciones que hagan referencia a esta impresora. Esta acción no se puede deshacer."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Clases de Activos"
msgid "Assets"
msgstr "Activos"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Asigna impresoras a ubicaciones. Envíos, recepciones y centros de trabajo heredan la ubicación predeterminada a menos que se anulen."
+
msgid "Assign To"
msgstr "Asignar a"
@@ -2239,9 +2252,6 @@ msgstr "Unidad Predeterminada"
msgid "Defaults"
msgstr "Valores predeterminados"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Define el tamaño predeterminado de la etiqueta del producto. Se utiliza para rastrear artículos en el inventario."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Define los términos y condiciones para órdenes de compra"
@@ -2614,6 +2624,9 @@ msgstr "Descargar"
msgid "Download CSV"
msgstr "Descargar CSV"
+msgid "Download Labels"
+msgstr "Descargar Etiquetas"
+
msgid "Download PDF"
msgstr "Descargar PDF"
@@ -2702,6 +2715,9 @@ msgstr "Duración"
msgid "e.g. DWG-1234"
msgstr "p. ej. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "p. ej. Zebra 2x1"
+
msgid "Edit"
msgstr "Editar"
@@ -3878,6 +3894,9 @@ msgstr "Si los artículos ya existen"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "Si deseas cambiar los números de parte, haz clic en Cancelar y asigna manualmente las partes para cada elemento de línea antes de convertir."
+msgid "Imperial"
+msgstr "Imperial"
+
msgid "Implementation Support"
msgstr "Soporte de Implementación"
@@ -4337,6 +4356,9 @@ msgstr "Más información"
msgid "Leave any related receipts untouched"
msgstr "Dejar los recibos relacionados sin tocar"
+msgid "Leave blank for built-in"
+msgstr "Dejar en blanco para usar el integrado"
+
msgid "Leave empty for exact match"
msgstr "Dejar vacío para coincidencia exacta"
@@ -4714,6 +4736,9 @@ msgstr "Tiempo Medio de Reparación"
msgid "Measurement Standard"
msgstr "Estándar de Medición"
+msgid "Media Size"
+msgstr "Tamaño de Medio"
+
msgid "Members"
msgstr "Miembros"
@@ -5255,6 +5280,9 @@ msgstr "Sin imagen"
msgid "No issue types configured"
msgstr "No hay tipos de problemas configurados"
+msgid "No locations found."
+msgstr "No se encontraron ubicaciones."
+
msgid "No logo uploaded"
msgstr "Sin logo cargado"
@@ -5306,6 +5334,12 @@ msgstr "Sin precios para la cantidad seleccionada"
msgid "No pricing options found"
msgstr "No se encontraron opciones de precios"
+msgid "No printer configured"
+msgstr "Sin impresora configurada"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "No hay impresoras configuradas. Haz clic en \"Agregar impresora\" para crear una."
+
msgid "No Quote"
msgstr "Sin Cotización"
@@ -5573,6 +5607,9 @@ msgstr "Pedidos"
msgid "Orders submitted"
msgstr "Pedidos enviados"
+msgid "Origin"
+msgstr "Origen"
+
msgid "Other Type"
msgstr "Otro Tipo"
@@ -5705,12 +5742,18 @@ msgstr "Términos de Pago"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Documento)"
+
msgid "PDF downloaded"
msgstr "PDF descargado"
msgid "PDF pages"
msgstr "Páginas PDF"
+msgid "PDF Preview"
+msgstr "Vista previa de PDF"
+
msgid "PDF Watermark"
msgstr "Marca de agua PDF"
@@ -5750,6 +5793,9 @@ msgstr "Foto eliminada correctamente"
msgid "Photo uploaded successfully"
msgstr "Foto cargada exitosamente"
+msgid "Physical printers available for assignment."
+msgstr "Impresoras físicas disponibles para asignación."
+
msgid "Pick"
msgstr "Seleccionar"
@@ -5900,6 +5946,9 @@ msgstr "Anterior"
msgid "Preview"
msgstr "Vista previa"
+msgid "Preview failed: {error}"
+msgstr "Vista previa fallida: {error}"
+
msgid "Preview Quantity"
msgstr "Cantidad de vista previa"
@@ -5942,9 +5991,35 @@ msgstr "Reglas de Precios"
msgid "Pricing Trace"
msgstr "Seguimiento de Precios"
+msgid "Print"
+msgstr "Imprimir"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Imprimir {0} etiquetas"
+
+msgid "Print Jobs"
+msgstr "Trabajos de Impresión"
+
msgid "Print Label"
msgstr "Imprimir Etiqueta"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Salida de impresión ({0})"
+
+msgid "Printer Settings"
+msgstr "Configuración de impresora"
+
+msgid "Printer URL"
+msgstr "URL de la impresora"
+
+msgid "Printers"
+msgstr "Impresoras"
+
+msgid "Printing"
+msgstr "Impresión"
+
msgid "Priorities"
msgstr "Prioridades"
@@ -5975,9 +6050,6 @@ msgstr "Tipo de Proceso"
msgid "Processes"
msgstr "Procesos"
-msgid "Product Label Size"
-msgstr "Tamaño de Etiqueta de Producto"
-
msgid "Production"
msgstr "Producción"
@@ -6405,6 +6477,9 @@ msgstr "Elimina este tipo de almacenamiento de todas las unidades de almacenamie
msgid "Remove Transfer"
msgstr "Eliminar transferencia"
+msgid "Rendering label preview..."
+msgstr "Renderizando vista previa de etiqueta..."
+
msgid "Reopen"
msgstr "Reabrir"
@@ -6462,6 +6537,9 @@ msgstr "Informe"
msgid "Reports"
msgstr "Informes"
+msgid "Reprint"
+msgstr "Reimprimir"
+
msgid "Request Approval"
msgstr "Solicitar Aprobación"
@@ -6946,6 +7024,9 @@ msgstr "Seleccionar Tipo de Artículo"
msgid "Select items"
msgstr "Seleccionar artículos"
+msgid "Select Printer"
+msgstr "Seleccionar Impresora"
+
msgid "Select Quantities"
msgstr "Seleccionar Cantidades"
@@ -7711,12 +7792,18 @@ msgstr "Impuesto:"
msgid "Temperature"
msgstr "Temperatura"
+msgid "Template ID"
+msgstr "ID de plantilla"
+
msgid "Terms and Privacy"
msgstr "Términos y Privacidad"
msgid "Terms of Service"
msgstr "Términos de Servicio"
+msgid "Test"
+msgstr "Prueba"
+
msgid "Test Value"
msgstr "Valor de Prueba"
@@ -8029,9 +8116,6 @@ msgstr "Seguimiento"
msgid "Tracking ID"
msgstr "ID de Seguimiento"
-msgid "Tracking Labels"
-msgstr "Etiquetas de Seguimiento"
-
msgid "Tracking Number"
msgstr "Número de Seguimiento"
@@ -8455,6 +8539,9 @@ msgstr "Ver RFQs Abiertos"
msgid "View Permissions"
msgstr "Permisos de visualización"
+msgid "View Prints"
+msgstr "Ver impresiones"
+
msgid "View Production Events"
msgstr "Ver Eventos de Producción"
@@ -8770,3 +8857,9 @@ msgstr "Aumentar zoom"
msgid "Zoom out"
msgstr "Alejar"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Etiqueta térmica)"
+
+msgid "ZPL Label Preview"
+msgstr "Vista previa de etiqueta ZPL"
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index e537341c74..255d4c1948 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - Conjunto {1}"
msgid "{0} Active"
msgstr "{0} Activos"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} disponibles"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Agregar"
msgid "Add & Issue"
msgstr "Agregar y emitir"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Añade una impresora en la configuración de impresión para imprimir etiquetas directamente."
+
msgid "Add Inventory"
msgstr "Agregar inventario"
@@ -106,11 +105,6 @@ msgstr "Error de autenticación"
msgid "Batch"
msgstr "Lote"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Lote {0} ({1} disponibles)"
-
msgid "Batch is not available"
msgstr "El lote no está disponible"
@@ -272,6 +266,9 @@ msgstr "Fuera de servicio"
msgid "Download"
msgstr "Descargar"
+msgid "Download Labels"
+msgstr "Descargar Etiquetas"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Arrastre y suelte un archivo aquí, o haga clic para seleccionar un archivo"
@@ -387,6 +384,9 @@ msgstr "¿Ideas, sugerencias o problemas?"
msgid "Impact"
msgstr "Impacto"
+msgid "Imperial"
+msgstr "Imperial"
+
msgid "In Progress"
msgstr "En progreso"
@@ -501,6 +501,9 @@ msgstr "Materiales"
msgid "Maximum number of records reached"
msgstr "Se alcanzó el número máximo de registros"
+msgid "Metric"
+msgstr "Métrico"
+
msgid "Model"
msgstr "Modelo"
@@ -580,6 +583,9 @@ msgstr "No se encontró ninguna opción."
msgid "No options found."
msgstr "No se encontraron opciones."
+msgid "No printer configured"
+msgstr "Sin impresora configurada"
+
msgid "No recent operations"
msgstr "No hay operaciones recientes"
@@ -683,6 +689,12 @@ msgstr "Anterior"
msgid "Preventive"
msgstr "Preventivo"
+msgid "Print"
+msgstr "Imprimir"
+
+msgid "Printer Settings"
+msgstr "Configuración de impresora"
+
msgid "Priority"
msgstr "Prioridad"
@@ -808,6 +820,9 @@ msgstr "Seleccione un artículo..."
msgid "Select Batch {0}"
msgstr "Seleccionar lote {0}"
+msgid "Select Printer"
+msgstr "Seleccionar Impresora"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Seleccionar serie {0}"
@@ -824,10 +839,6 @@ msgstr "Enviar"
msgid "Serial"
msgstr "Serie"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Serie {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Número de serie {0}"
@@ -962,9 +973,6 @@ msgstr "Total: {0}"
msgid "Tracking"
msgstr "Seguimiento"
-msgid "Tracking Labels"
-msgstr "Etiquetas de seguimiento"
-
msgid "Type a message..."
msgstr "Escriba un mensaje..."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 2d98697573..1e57b60875 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -270,6 +270,9 @@ msgstr "Ajoutez une colonne ci-dessous pour trier la vue"
msgid "Add a comment..."
msgstr "Ajouter un commentaire..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Ajoutez une imprimante dans les paramètres d'impression pour imprimer les étiquettes directement."
+
msgid "Add Actions"
msgstr "Ajouter des actions"
@@ -339,6 +342,9 @@ msgstr "Ajouter un partenaire"
msgid "Add Permissions"
msgstr "Ajouter des autorisations"
+msgid "Add Printer"
+msgstr "Ajouter une imprimante"
+
msgid "Add Property"
msgstr "Ajouter une propriété"
@@ -759,6 +765,10 @@ msgstr "Êtes-vous sûr de vouloir supprimer le délai de paiement : {0} ? Cette
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "Êtes-vous sûr de vouloir supprimer la règle de tarification : {0}? Cette action ne peut pas être annulée."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "Êtes-vous sûr de vouloir supprimer l'imprimante « {0} » ? Toutes les affectations faisant référence à cette imprimante seront effacées. Cette action ne peut pas être annulée."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Classes d'actifs"
msgid "Assets"
msgstr "Actifs"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Attribuez des imprimantes aux emplacements. L'expédition, la réception et les centres de travail héritent de la valeur par défaut de l'emplacement sauf s'ils sont remplacés."
+
msgid "Assign To"
msgstr "Assigner à"
@@ -2239,9 +2252,6 @@ msgstr "Unité par défaut"
msgid "Defaults"
msgstr "Paramètres par défaut"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Définissez la taille par défaut de l'étiquette produit. Utilisé pour le suivi des articles en inventaire."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Définir les conditions générales pour les commandes d'achat"
@@ -2614,6 +2624,9 @@ msgstr "Télécharger"
msgid "Download CSV"
msgstr "Télécharger CSV"
+msgid "Download Labels"
+msgstr "Télécharger les étiquettes"
+
msgid "Download PDF"
msgstr "Télécharger le PDF"
@@ -2702,6 +2715,9 @@ msgstr "Durée"
msgid "e.g. DWG-1234"
msgstr "p. ex. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "p. ex. Zebra 2x1"
+
msgid "Edit"
msgstr "Modifier"
@@ -3878,6 +3894,9 @@ msgstr "Si des articles existent déjà"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "Si vous souhaitez modifier les numéros de pièce, veuillez cliquer sur Annuler et assigner manuellement les pièces pour chaque article de ligne avant de convertir."
+msgid "Imperial"
+msgstr "Impérial"
+
msgid "Implementation Support"
msgstr "Support à la mise en œuvre"
@@ -4337,6 +4356,9 @@ msgstr "En savoir plus"
msgid "Leave any related receipts untouched"
msgstr "Laisser les reçus connexes intacts"
+msgid "Leave blank for built-in"
+msgstr "Laisser vide pour utiliser le modèle intégré"
+
msgid "Leave empty for exact match"
msgstr "Laisser vide pour une correspondance exacte"
@@ -4714,6 +4736,9 @@ msgstr "Temps Moyen de Réparation"
msgid "Measurement Standard"
msgstr "Norme de Mesure"
+msgid "Media Size"
+msgstr "Taille du média"
+
msgid "Members"
msgstr "Membres"
@@ -5255,6 +5280,9 @@ msgstr "Aucune image"
msgid "No issue types configured"
msgstr "Aucun type de problème configuré"
+msgid "No locations found."
+msgstr "Aucun emplacement trouvé."
+
msgid "No logo uploaded"
msgstr "Aucun logo téléchargé"
@@ -5306,6 +5334,12 @@ msgstr "Aucun tarif pour la quantité sélectionnée"
msgid "No pricing options found"
msgstr "Aucune option de tarification trouvée"
+msgid "No printer configured"
+msgstr "Aucune imprimante configurée"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "Aucune imprimante configurée. Cliquez sur « Ajouter une imprimante » pour en créer une."
+
msgid "No Quote"
msgstr "Pas de devis"
@@ -5573,6 +5607,9 @@ msgstr "Commandes"
msgid "Orders submitted"
msgstr "Commandes soumises"
+msgid "Origin"
+msgstr "Origine"
+
msgid "Other Type"
msgstr "Autre Type"
@@ -5705,12 +5742,18 @@ msgstr "Conditions de paiement"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Document)"
+
msgid "PDF downloaded"
msgstr "PDF téléchargé"
msgid "PDF pages"
msgstr "Pages PDF"
+msgid "PDF Preview"
+msgstr "Aperçu PDF"
+
msgid "PDF Watermark"
msgstr "Filigrane PDF"
@@ -5750,6 +5793,9 @@ msgstr "Photo supprimée avec succès"
msgid "Photo uploaded successfully"
msgstr "Photo téléchargée avec succès"
+msgid "Physical printers available for assignment."
+msgstr "Imprimantes physiques disponibles pour l'attribution."
+
msgid "Pick"
msgstr "Prélever"
@@ -5900,6 +5946,9 @@ msgstr "Précédent"
msgid "Preview"
msgstr "Aperçu"
+msgid "Preview failed: {error}"
+msgstr "Aperçu échoué : {error}"
+
msgid "Preview Quantity"
msgstr "Quantité d'aperçu"
@@ -5942,9 +5991,35 @@ msgstr "Règles de tarification"
msgid "Pricing Trace"
msgstr "Traçabilité des prix"
+msgid "Print"
+msgstr "Imprimer"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Imprimer {0} étiquettes"
+
+msgid "Print Jobs"
+msgstr "Travaux d'impression"
+
msgid "Print Label"
msgstr "Imprimer l'étiquette"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Sortie d'impression ({0})"
+
+msgid "Printer Settings"
+msgstr "Paramètres d'impression"
+
+msgid "Printer URL"
+msgstr "URL de l'imprimante"
+
+msgid "Printers"
+msgstr "Imprimantes"
+
+msgid "Printing"
+msgstr "Impression"
+
msgid "Priorities"
msgstr "Priorités"
@@ -5975,9 +6050,6 @@ msgstr "Type de processus"
msgid "Processes"
msgstr "Processus"
-msgid "Product Label Size"
-msgstr "Taille de l'étiquette produit"
-
msgid "Production"
msgstr "Production"
@@ -6405,6 +6477,9 @@ msgstr "Supprimez ce type de stockage de toutes les unités de stockage qui le r
msgid "Remove Transfer"
msgstr "Supprimer le transfert"
+msgid "Rendering label preview..."
+msgstr "Rendu de l'aperçu de l'étiquette..."
+
msgid "Reopen"
msgstr "Rouvrir"
@@ -6462,6 +6537,9 @@ msgstr "Rapport"
msgid "Reports"
msgstr "Rapports"
+msgid "Reprint"
+msgstr "Réimprimer"
+
msgid "Request Approval"
msgstr "Demander l'approbation"
@@ -6946,6 +7024,9 @@ msgstr "Sélectionner le type d'article"
msgid "Select items"
msgstr "Sélectionner les articles"
+msgid "Select Printer"
+msgstr "Sélectionner l'imprimante"
+
msgid "Select Quantities"
msgstr "Sélectionner les quantités"
@@ -7711,12 +7792,18 @@ msgstr "Taxe :"
msgid "Temperature"
msgstr "Température"
+msgid "Template ID"
+msgstr "ID de modèle"
+
msgid "Terms and Privacy"
msgstr "Conditions et Confidentialité"
msgid "Terms of Service"
msgstr "Conditions d'utilisation"
+msgid "Test"
+msgstr "Tester"
+
msgid "Test Value"
msgstr "Valeur de test"
@@ -8029,9 +8116,6 @@ msgstr "Suivi"
msgid "Tracking ID"
msgstr "ID de suivi"
-msgid "Tracking Labels"
-msgstr "Étiquettes de suivi"
-
msgid "Tracking Number"
msgstr "Numéro de suivi"
@@ -8455,6 +8539,9 @@ msgstr "Afficher les demandes de devis ouvertes"
msgid "View Permissions"
msgstr "Autorisations d'affichage"
+msgid "View Prints"
+msgstr "Afficher les impressions"
+
msgid "View Production Events"
msgstr "Afficher les événements de production"
@@ -8770,3 +8857,9 @@ msgstr "Agrandir"
msgid "Zoom out"
msgstr "Réduire le zoom"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Étiquette thermique)"
+
+msgid "ZPL Label Preview"
+msgstr "Aperçu de l'étiquette ZPL"
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index a19adc14de..a132fc52e7 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - Jeu {1}"
msgid "{0} Active"
msgstr "{0} Actif(s)"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} disponible(s)"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Ajouter"
msgid "Add & Issue"
msgstr "Ajouter et distribuer"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Ajoutez une imprimante dans les paramètres d'impression pour imprimer les étiquettes directement."
+
msgid "Add Inventory"
msgstr "Ajouter au stock"
@@ -106,11 +105,6 @@ msgstr "Erreur d'authentification"
msgid "Batch"
msgstr "Lot"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Lot {0} ({1} disponible(s))"
-
msgid "Batch is not available"
msgstr "Le lot n'est pas disponible"
@@ -272,6 +266,9 @@ msgstr "En panne"
msgid "Download"
msgstr "Télécharger"
+msgid "Download Labels"
+msgstr "Télécharger les étiquettes"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Glissez-déposez un fichier ici, ou cliquez pour sélectionner un fichier"
@@ -387,6 +384,9 @@ msgstr "Des idées, suggestions ou problèmes ?"
msgid "Impact"
msgstr "Impact"
+msgid "Imperial"
+msgstr "Impérial"
+
msgid "In Progress"
msgstr "En cours"
@@ -501,6 +501,9 @@ msgstr "Matériaux"
msgid "Maximum number of records reached"
msgstr "Nombre maximum d'enregistrements atteint"
+msgid "Metric"
+msgstr "Métrique"
+
msgid "Model"
msgstr "Modèle"
@@ -580,6 +583,9 @@ msgstr "Aucune option trouvée."
msgid "No options found."
msgstr "Aucune option trouvée."
+msgid "No printer configured"
+msgstr "Aucune imprimante configurée"
+
msgid "No recent operations"
msgstr "Aucune opération récente"
@@ -683,6 +689,12 @@ msgstr "Précédent"
msgid "Preventive"
msgstr "Préventif"
+msgid "Print"
+msgstr "Imprimer"
+
+msgid "Printer Settings"
+msgstr "Paramètres d'impression"
+
msgid "Priority"
msgstr "Priorité"
@@ -808,6 +820,9 @@ msgstr "Sélectionner un article..."
msgid "Select Batch {0}"
msgstr "Sélectionner le lot {0}"
+msgid "Select Printer"
+msgstr "Sélectionner l'imprimante"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Sélectionner le numéro de série {0}"
@@ -824,10 +839,6 @@ msgstr "Envoyer"
msgid "Serial"
msgstr "Série"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Série {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Numéro de série {0}"
@@ -962,9 +973,6 @@ msgstr "Total : {0}"
msgid "Tracking"
msgstr "Suivi"
-msgid "Tracking Labels"
-msgstr "Étiquettes de suivi"
-
msgid "Type a message..."
msgstr "Saisissez un message..."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index a34e980f8a..d8b93634b3 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -270,6 +270,9 @@ msgstr "इस दृश्य को सॉर्ट करने के लि
msgid "Add a comment..."
msgstr "एक टिप्पणी जोड़ें..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "प्रिंटिंग सेटिंग्स में एक प्रिंटर जोड़ें ताकि लेबल सीधे प्रिंट कर सकें।"
+
msgid "Add Actions"
msgstr "कार्य जोड़ें"
@@ -339,6 +342,9 @@ msgstr "पार्टनर जोड़ें"
msgid "Add Permissions"
msgstr "अनुमतियां जोड़ें"
+msgid "Add Printer"
+msgstr "प्रिंटर जोड़ें"
+
msgid "Add Property"
msgstr "प्रॉपर्टी जोड़ें"
@@ -759,6 +765,10 @@ msgstr "क्या आप सुनिश्चित हैं कि आप
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "क्या आप सुनिश्चित हैं कि आप मूल्य निर्धारण नियम को हटाना चाहते हैं: {0}? यह पूर्ववत नहीं किया जा सकता।"
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "क्या आप सुनिश्चित हैं कि आप प्रिंटर \"{0}\" को हटाना चाहते हैं? इस प्रिंटर को संदर्भित करने वाले किसी भी असाइनमेंट को साफ़ किया जाएगा। इसे पूर्ववत नहीं किया जा सकता।"
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "संपत्ति वर्ग"
msgid "Assets"
msgstr "संपत्तियां"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "प्रिंटर को स्थानों को असाइन करें। शिपिंग, रिसीविंग और वर्क सेंटर स्थान डिफ़ॉल्ट को विरासत में लेते हैं जब तक कि ओवरराइड न किया जाए।"
+
msgid "Assign To"
msgstr "को असाइन करें"
@@ -2239,9 +2252,6 @@ msgstr "डिफ़ॉल्ट यूनिट"
msgid "Defaults"
msgstr "डिफ़ॉल्ट"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "उत्पाद लेबल का डिफ़ॉल्ट आकार परिभाषित करें। इन्वेंटरी में आइटम ट्रैक करने के लिए उपयोग किया जाता है।"
-
msgid "Define the terms and conditions for purchase orders"
msgstr "क्रय आदेशों के लिए शर्तें और शर्तें परिभाषित करें"
@@ -2614,6 +2624,9 @@ msgstr "डाउनलोड करें"
msgid "Download CSV"
msgstr "CSV डाउनलोड करें"
+msgid "Download Labels"
+msgstr "लेबल डाउनलोड करें"
+
msgid "Download PDF"
msgstr "PDF डाउनलोड करें"
@@ -2702,6 +2715,9 @@ msgstr "अवधि"
msgid "e.g. DWG-1234"
msgstr "उदा. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "उदाहरण के लिए Zebra 2x1"
+
msgid "Edit"
msgstr "संपादित करें"
@@ -3878,6 +3894,9 @@ msgstr "अगर आइटम पहले से मौजूद हैं"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "यदि आप भाग संख्याओं को बदलना चाहते हैं, तो कृपया Cancel पर क्लिक करें और रूपांतरण से पहले प्रत्येक लाइन आइटम के लिए भागों को मैन्युअल रूप से असाइन करें।"
+msgid "Imperial"
+msgstr "इंपीरियल"
+
msgid "Implementation Support"
msgstr "कार्यान्वयन समर्थन"
@@ -4337,6 +4356,9 @@ msgstr "और जानें"
msgid "Leave any related receipts untouched"
msgstr "किसी भी संबंधित रसीदों को अछूता छोड़ें"
+msgid "Leave blank for built-in"
+msgstr "बिल्ट-इन के लिए खाली छोड़ें"
+
msgid "Leave empty for exact match"
msgstr "सटीक मिलान के लिए खाली छोड़ें"
@@ -4714,6 +4736,9 @@ msgstr "मरम्मत के लिए औसत समय"
msgid "Measurement Standard"
msgstr "मापन मानक"
+msgid "Media Size"
+msgstr "मीडिया आकार"
+
msgid "Members"
msgstr "सदस्य"
@@ -5255,6 +5280,9 @@ msgstr "कोई छवि नहीं"
msgid "No issue types configured"
msgstr "कोई समस्या प्रकार कॉन्फ़िगर नहीं किया गया"
+msgid "No locations found."
+msgstr "कोई स्थान नहीं मिला।"
+
msgid "No logo uploaded"
msgstr "कोई लोगो अपलोड नहीं किया गया"
@@ -5306,6 +5334,12 @@ msgstr "चयनित मात्रा के लिए कोई मूल
msgid "No pricing options found"
msgstr "कोई मूल्य निर्धारण विकल्प नहीं मिला"
+msgid "No printer configured"
+msgstr "कोई प्रिंटर कॉन्फ़िगर नहीं किया गया"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "कोई प्रिंटर कॉन्फ़िगर नहीं किया गया है। एक बनाने के लिए \"प्रिंटर जोड़ें\" पर क्लिक करें।"
+
msgid "No Quote"
msgstr "कोई उद्धरण नहीं"
@@ -5573,6 +5607,9 @@ msgstr "आदेश"
msgid "Orders submitted"
msgstr "ऑर्डर जमा किए गए"
+msgid "Origin"
+msgstr "मूल"
+
msgid "Other Type"
msgstr "अन्य प्रकार"
@@ -5705,12 +5742,18 @@ msgstr "भुगतान शर्तें"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (दस्तावेज़)"
+
msgid "PDF downloaded"
msgstr "PDF डाउनलोड किया गया"
msgid "PDF pages"
msgstr "पीडीएफ पृष्ठ"
+msgid "PDF Preview"
+msgstr "PDF पूर्वावलोकन"
+
msgid "PDF Watermark"
msgstr "PDF वॉटरमार्क"
@@ -5750,6 +5793,9 @@ msgstr "फ़ोटो सफलतापूर्वक हटा दी ग
msgid "Photo uploaded successfully"
msgstr "फ़ोटो सफलतापूर्वक अपलोड हो गई"
+msgid "Physical printers available for assignment."
+msgstr "असाइनमेंट के लिए उपलब्ध भौतिक प्रिंटर।"
+
msgid "Pick"
msgstr "चुनें"
@@ -5900,6 +5946,9 @@ msgstr "पिछला"
msgid "Preview"
msgstr "पूर्वावलोकन"
+msgid "Preview failed: {error}"
+msgstr "पूर्वावलोकन विफल: {error}"
+
msgid "Preview Quantity"
msgstr "पूर्वावलोकन मात्रा"
@@ -5942,9 +5991,35 @@ msgstr "मूल्य निर्धारण नियम"
msgid "Pricing Trace"
msgstr "मूल्य निर्धारण ट्रेस"
+msgid "Print"
+msgstr "प्रिंट करें"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "{0} लेबल प्रिंट करें"
+
+msgid "Print Jobs"
+msgstr "प्रिंट जॉब्स"
+
msgid "Print Label"
msgstr "लेबल प्रिंट करें"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "प्रिंट आउटपुट ({0})"
+
+msgid "Printer Settings"
+msgstr "प्रिंटर सेटिंग्स"
+
+msgid "Printer URL"
+msgstr "प्रिंटर URL"
+
+msgid "Printers"
+msgstr "प्रिंटर"
+
+msgid "Printing"
+msgstr "मुद्रण"
+
msgid "Priorities"
msgstr "प्राथमिकताएं"
@@ -5975,9 +6050,6 @@ msgstr "प्रक्रिया प्रकार"
msgid "Processes"
msgstr "प्रक्रियाएं"
-msgid "Product Label Size"
-msgstr "उत्पाद लेबल आकार"
-
msgid "Production"
msgstr "उत्पादन"
@@ -6405,6 +6477,9 @@ msgstr "इस स्टोरेज प्रकार को सभी सं
msgid "Remove Transfer"
msgstr "ट्रांसफर हटाएं"
+msgid "Rendering label preview..."
+msgstr "लेबल पूर्वावलोकन प्रस्तुत किया जा रहा है..."
+
msgid "Reopen"
msgstr "फिर से खोलें"
@@ -6462,6 +6537,9 @@ msgstr "रिपोर्ट"
msgid "Reports"
msgstr "रिपोर्ट"
+msgid "Reprint"
+msgstr "दोबारा प्रिंट करें"
+
msgid "Request Approval"
msgstr "अनुमोदन का अनुरोध करें"
@@ -6946,6 +7024,9 @@ msgstr "आइटम प्रकार चुनें"
msgid "Select items"
msgstr "आइटम चुनें"
+msgid "Select Printer"
+msgstr "प्रिंटर चुनें"
+
msgid "Select Quantities"
msgstr "मात्रा चुनें"
@@ -7711,12 +7792,18 @@ msgstr "कर:"
msgid "Temperature"
msgstr "तापमान"
+msgid "Template ID"
+msgstr "टेम्पलेट आईडी"
+
msgid "Terms and Privacy"
msgstr "शर्तें और गोपनीयता"
msgid "Terms of Service"
msgstr "सेवा की शर्तें"
+msgid "Test"
+msgstr "परीक्षण"
+
msgid "Test Value"
msgstr "परीक्षण मान"
@@ -8029,9 +8116,6 @@ msgstr "ट्रैकिंग"
msgid "Tracking ID"
msgstr "ट्रैकिंग आईडी"
-msgid "Tracking Labels"
-msgstr "ट्रैकिंग लेबल"
-
msgid "Tracking Number"
msgstr "ट्रैकिंग नंबर"
@@ -8455,6 +8539,9 @@ msgstr "खुले RFQ देखें"
msgid "View Permissions"
msgstr "देखने की अनुमतियाँ"
+msgid "View Prints"
+msgstr "प्रिंट देखें"
+
msgid "View Production Events"
msgstr "उत्पादन घटनाएं देखें"
@@ -8770,3 +8857,9 @@ msgstr "ज़ूम इन करें"
msgid "Zoom out"
msgstr "ज़ूम आउट करें"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (थर्मल लेबल)"
+
+msgid "ZPL Label Preview"
+msgstr "ZPL लेबल पूर्वावलोकन"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 01619b0972..90470c2030 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - सेट {1}"
msgid "{0} Active"
msgstr "{0} सक्रिय"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} उपलब्ध"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "जोड़ें"
msgid "Add & Issue"
msgstr "जोड़ें और जारी करें"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "प्रिंटिंग सेटिंग्स में एक प्रिंटर जोड़ें ताकि लेबल सीधे प्रिंट कर सकें।"
+
msgid "Add Inventory"
msgstr "इन्वेंटरी जोड़ें"
@@ -106,11 +105,6 @@ msgstr "प्रमाणीकरण त्रुटि"
msgid "Batch"
msgstr "बैच"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "बैच {0} ({1} उपलब्ध)"
-
msgid "Batch is not available"
msgstr "बैच उपलब्ध नहीं है"
@@ -272,6 +266,9 @@ msgstr "डाउन"
msgid "Download"
msgstr "डाउनलोड"
+msgid "Download Labels"
+msgstr "लेबल डाउनलोड करें"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "यहाँ एक फ़ाइल को ड्रैग और ड्रॉप करें, या फ़ाइल चुनने के लिए क्लिक करें"
@@ -387,6 +384,9 @@ msgstr "विचार, सुझाव या समस्याएं?"
msgid "Impact"
msgstr "प्रभाव"
+msgid "Imperial"
+msgstr "इंपीरियल"
+
msgid "In Progress"
msgstr "प्रगति में"
@@ -501,6 +501,9 @@ msgstr "सामग्री"
msgid "Maximum number of records reached"
msgstr "रिकॉर्ड की अधिकतम संख्या तक पहुंच गई"
+msgid "Metric"
+msgstr "मीट्रिक"
+
msgid "Model"
msgstr "मॉडल"
@@ -580,6 +583,9 @@ msgstr "कोई विकल्प नहीं मिला।"
msgid "No options found."
msgstr "कोई विकल्प नहीं मिला।"
+msgid "No printer configured"
+msgstr "कोई प्रिंटर कॉन्फ़िगर नहीं किया गया"
+
msgid "No recent operations"
msgstr "कोई हाल के संचालन नहीं"
@@ -683,6 +689,12 @@ msgstr "पिछला"
msgid "Preventive"
msgstr "निवारक"
+msgid "Print"
+msgstr "प्रिंट करें"
+
+msgid "Printer Settings"
+msgstr "प्रिंटर सेटिंग्स"
+
msgid "Priority"
msgstr "प्राथमिकता"
@@ -808,6 +820,9 @@ msgstr "एक आइटम चुनें..."
msgid "Select Batch {0}"
msgstr "बैच {0} चुनें"
+msgid "Select Printer"
+msgstr "प्रिंटर चुनें"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "सीरियल {0} चुनें"
@@ -824,10 +839,6 @@ msgstr "भेजें"
msgid "Serial"
msgstr "सीरीज़"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "सीरियल {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "सीरियल नंबर {0}"
@@ -962,9 +973,6 @@ msgstr "कुल: {0}"
msgid "Tracking"
msgstr "ट्रैकिंग"
-msgid "Tracking Labels"
-msgstr "ट्रैकिंग लेबल"
-
msgid "Type a message..."
msgstr "एक संदेश लिखें..."
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index d85c80c9d3..8821f89ece 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -270,6 +270,9 @@ msgstr "Aggiungi una colonna di seguito per ordinare la visualizzazione"
msgid "Add a comment..."
msgstr "Aggiungi un commento..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Aggiungi una stampante nelle impostazioni di stampa per stampare le etichette direttamente."
+
msgid "Add Actions"
msgstr "Aggiungi Azioni"
@@ -339,6 +342,9 @@ msgstr "Aggiungi Partner"
msgid "Add Permissions"
msgstr "Aggiungi Autorizzazioni"
+msgid "Add Printer"
+msgstr "Aggiungi stampante"
+
msgid "Add Property"
msgstr "Aggiungi Proprietà"
@@ -759,6 +765,10 @@ msgstr "Sei sicuro di voler eliminare il termine di pagamento: {0}? Questa azion
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "Sei sicuro di voler eliminare la regola di prezzo: {0}? Questa azione non può essere annullata."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "Sei sicuro di voler eliminare la stampante \"{0}\"? Tutti gli incarichi che fanno riferimento a questa stampante verranno cancellati. Questa azione non può essere annullata."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Classi di Cespiti"
msgid "Assets"
msgstr "Cespiti"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Assegna stampanti alle posizioni. Spedizione, ricezione e centri di lavoro ereditano l'impostazione predefinita della posizione se non sovrascritti."
+
msgid "Assign To"
msgstr "Assegna a"
@@ -2239,9 +2252,6 @@ msgstr "Unità Predefinita"
msgid "Defaults"
msgstr "Impostazioni predefinite"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Definisci la dimensione predefinita dell'etichetta del prodotto. Utilizzato per il tracciamento degli articoli nell'inventario."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Definire i termini e le condizioni per gli ordini di acquisto"
@@ -2614,6 +2624,9 @@ msgstr "Scarica"
msgid "Download CSV"
msgstr "Scarica CSV"
+msgid "Download Labels"
+msgstr "Scarica Etichette"
+
msgid "Download PDF"
msgstr "Scarica PDF"
@@ -2702,6 +2715,9 @@ msgstr "Durata"
msgid "e.g. DWG-1234"
msgstr "es. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "ad es. Zebra 2x1"
+
msgid "Edit"
msgstr "Modifica"
@@ -3878,6 +3894,9 @@ msgstr "Se gli articoli esistono già"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "Se desideri modificare i numeri di parte, fai clic su Annulla e assegna manualmente le parti per ogni elemento di riga prima della conversione."
+msgid "Imperial"
+msgstr "Imperiale"
+
msgid "Implementation Support"
msgstr "Supporto all'implementazione"
@@ -4337,6 +4356,9 @@ msgstr "Scopri di più"
msgid "Leave any related receipts untouched"
msgstr "Lasciare le ricevute correlate intatte"
+msgid "Leave blank for built-in"
+msgstr "Lascia vuoto per built-in"
+
msgid "Leave empty for exact match"
msgstr "Lascia vuoto per una corrispondenza esatta"
@@ -4714,6 +4736,9 @@ msgstr "Tempo Medio di Riparazione"
msgid "Measurement Standard"
msgstr "Standard di Misurazione"
+msgid "Media Size"
+msgstr "Dimensione supporto"
+
msgid "Members"
msgstr "Membri"
@@ -5255,6 +5280,9 @@ msgstr "Nessuna immagine"
msgid "No issue types configured"
msgstr "Nessun tipo di problema configurato"
+msgid "No locations found."
+msgstr "Nessuna posizione trovata."
+
msgid "No logo uploaded"
msgstr "Nessun logo caricato"
@@ -5306,6 +5334,12 @@ msgstr "Nessun prezzo per la quantità selezionata"
msgid "No pricing options found"
msgstr "Nessuna opzione di prezzo trovata"
+msgid "No printer configured"
+msgstr "Nessuna stampante configurata"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "Nessuna stampante configurata. Fai clic su \"Aggiungi stampante\" per crearne una."
+
msgid "No Quote"
msgstr "Nessuna offerta"
@@ -5573,6 +5607,9 @@ msgstr "Ordini"
msgid "Orders submitted"
msgstr "Ordini inviati"
+msgid "Origin"
+msgstr "Origine"
+
msgid "Other Type"
msgstr "Altro Tipo"
@@ -5705,12 +5742,18 @@ msgstr "Condizioni di Pagamento"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Documento)"
+
msgid "PDF downloaded"
msgstr "PDF scaricato"
msgid "PDF pages"
msgstr "Pagine PDF"
+msgid "PDF Preview"
+msgstr "Anteprima PDF"
+
msgid "PDF Watermark"
msgstr "Filigrana PDF"
@@ -5750,6 +5793,9 @@ msgstr "Foto rimossa con successo"
msgid "Photo uploaded successfully"
msgstr "Foto caricata con successo"
+msgid "Physical printers available for assignment."
+msgstr "Stampanti fisiche disponibili per l'assegnazione."
+
msgid "Pick"
msgstr "Preleva"
@@ -5900,6 +5946,9 @@ msgstr "Prec"
msgid "Preview"
msgstr "Anteprima"
+msgid "Preview failed: {error}"
+msgstr "Anteprima non riuscita: {error}"
+
msgid "Preview Quantity"
msgstr "Quantità Anteprima"
@@ -5942,9 +5991,35 @@ msgstr "Regole di Prezzo"
msgid "Pricing Trace"
msgstr "Traccia Prezzi"
+msgid "Print"
+msgstr "Stampa"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Stampa {0} Etichette"
+
+msgid "Print Jobs"
+msgstr "Lavori di stampa"
+
msgid "Print Label"
msgstr "Stampa Etichetta"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Output di stampa ({0})"
+
+msgid "Printer Settings"
+msgstr "Impostazioni Stampante"
+
+msgid "Printer URL"
+msgstr "URL stampante"
+
+msgid "Printers"
+msgstr "Stampanti"
+
+msgid "Printing"
+msgstr "Stampa"
+
msgid "Priorities"
msgstr "Priorità"
@@ -5975,9 +6050,6 @@ msgstr "Tipo di Processo"
msgid "Processes"
msgstr "Processi"
-msgid "Product Label Size"
-msgstr "Dimensione Etichetta Prodotto"
-
msgid "Production"
msgstr "Produzione"
@@ -6405,6 +6477,9 @@ msgstr "Rimuovi questo tipo di archiviazione da tutte le unità di archiviazione
msgid "Remove Transfer"
msgstr "Rimuovi Trasferimento"
+msgid "Rendering label preview..."
+msgstr "Rendering dell'anteprima dell'etichetta..."
+
msgid "Reopen"
msgstr "Riapri"
@@ -6462,6 +6537,9 @@ msgstr "Rapporto"
msgid "Reports"
msgstr "Rapporti"
+msgid "Reprint"
+msgstr "Ristampa"
+
msgid "Request Approval"
msgstr "Richiedi Approvazione"
@@ -6946,6 +7024,9 @@ msgstr "Seleziona Tipo di Articolo"
msgid "Select items"
msgstr "Seleziona articoli"
+msgid "Select Printer"
+msgstr "Seleziona Stampante"
+
msgid "Select Quantities"
msgstr "Seleziona Quantità"
@@ -7711,12 +7792,18 @@ msgstr "Imposta:"
msgid "Temperature"
msgstr "Temperatura"
+msgid "Template ID"
+msgstr "ID Modello"
+
msgid "Terms and Privacy"
msgstr "Termini e Privacy"
msgid "Terms of Service"
msgstr "Termini di Servizio"
+msgid "Test"
+msgstr "Prova"
+
msgid "Test Value"
msgstr "Valore di Test"
@@ -8029,9 +8116,6 @@ msgstr "Tracciamento"
msgid "Tracking ID"
msgstr "ID Tracciamento"
-msgid "Tracking Labels"
-msgstr "Etichette di tracciamento"
-
msgid "Tracking Number"
msgstr "Numero di tracciamento"
@@ -8455,6 +8539,9 @@ msgstr "Visualizza RFQ Aperti"
msgid "View Permissions"
msgstr "Autorizzazioni di visualizzazione"
+msgid "View Prints"
+msgstr "Visualizza Stampe"
+
msgid "View Production Events"
msgstr "Visualizza Eventi di Produzione"
@@ -8770,3 +8857,9 @@ msgstr "Aumenta zoom"
msgid "Zoom out"
msgstr "Riduci zoom"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Etichetta Termica)"
+
+msgid "ZPL Label Preview"
+msgstr "Anteprima etichetta ZPL"
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index cdc9932fe3..636bcdf30d 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - Set {1}"
msgid "{0} Active"
msgstr "{0} Attivi"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} disponibili"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Aggiungi"
msgid "Add & Issue"
msgstr "Aggiungi e Preleva"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Aggiungi una stampante nelle impostazioni di stampa per stampare le etichette direttamente."
+
msgid "Add Inventory"
msgstr "Aggiungi Inventario"
@@ -106,11 +105,6 @@ msgstr "Errore di Autenticazione"
msgid "Batch"
msgstr "Lotto"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Lotto {0} ({1} disponibili)"
-
msgid "Batch is not available"
msgstr "Lotto non disponibile"
@@ -272,6 +266,9 @@ msgstr "Fermo"
msgid "Download"
msgstr "Scarica"
+msgid "Download Labels"
+msgstr "Scarica Etichette"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Trascina e rilascia un file qui, o clicca per selezionare un file"
@@ -387,6 +384,9 @@ msgstr "Idee, suggerimenti o problemi?"
msgid "Impact"
msgstr "Impatto"
+msgid "Imperial"
+msgstr "Imperiale"
+
msgid "In Progress"
msgstr "In Corso"
@@ -501,6 +501,9 @@ msgstr "Materiali"
msgid "Maximum number of records reached"
msgstr "Numero massimo di registrazioni raggiunto"
+msgid "Metric"
+msgstr "Metrico"
+
msgid "Model"
msgstr "Modello"
@@ -580,6 +583,9 @@ msgstr "Nessuna opzione trovata."
msgid "No options found."
msgstr "Nessuna opzione trovata."
+msgid "No printer configured"
+msgstr "Nessuna stampante configurata"
+
msgid "No recent operations"
msgstr "Nessuna operazione recente"
@@ -683,6 +689,12 @@ msgstr "Precedente"
msgid "Preventive"
msgstr "Preventivo"
+msgid "Print"
+msgstr "Stampa"
+
+msgid "Printer Settings"
+msgstr "Impostazioni Stampante"
+
msgid "Priority"
msgstr "Priorità"
@@ -808,6 +820,9 @@ msgstr "Seleziona un articolo..."
msgid "Select Batch {0}"
msgstr "Seleziona Lotto {0}"
+msgid "Select Printer"
+msgstr "Seleziona Stampante"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Seleziona Seriale {0}"
@@ -824,10 +839,6 @@ msgstr "Invia"
msgid "Serial"
msgstr "Seriale"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Seriale {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Numero di Serie {0}"
@@ -962,9 +973,6 @@ msgstr "Totale: {0}"
msgid "Tracking"
msgstr "Tracciamento"
-msgid "Tracking Labels"
-msgstr "Etichette di Tracciabilità"
-
msgid "Type a message..."
msgstr "Scrivi un messaggio..."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index b36b2b8051..41015ef558 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -270,6 +270,9 @@ msgstr "下のカラムを追加してビューをソートします"
msgid "Add a comment..."
msgstr "コメントを追加..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "プリンター設定にプリンターを追加して、ラベルを直接印刷します。"
+
msgid "Add Actions"
msgstr "アクションを追加"
@@ -339,6 +342,9 @@ msgstr "パートナーを追加"
msgid "Add Permissions"
msgstr "権限を追加"
+msgid "Add Printer"
+msgstr "プリンターを追加"
+
msgid "Add Property"
msgstr "プロパティを追加"
@@ -759,6 +765,10 @@ msgstr "支払い条件「{0}」を削除してもよろしいですか?この
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "本当に価格設定ルール: {0} を削除してもよろしいですか?この操作は取り消せません。"
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "このプリンター「{0}」を削除してもよろしいですか?このプリンターを参照しているすべての割り当ては削除されます。この操作は取り消せません。"
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "資産クラス"
msgid "Assets"
msgstr "資産"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "プリンターをロケーションに割り当てます。配送、受け取り、ワークセンターは、オーバーライドされない限りロケーションのデフォルトを継承します。"
+
msgid "Assign To"
msgstr "割り当て先"
@@ -2239,9 +2252,6 @@ msgstr "デフォルト単位"
msgid "Defaults"
msgstr "デフォルト"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "製品ラベルのデフォルトサイズを定義します。在庫内のアイテムを追跡するために使用されます。"
-
msgid "Define the terms and conditions for purchase orders"
msgstr "購買注文の利用規約と条件を定義します"
@@ -2614,6 +2624,9 @@ msgstr "ダウンロード"
msgid "Download CSV"
msgstr "CSVをダウンロード"
+msgid "Download Labels"
+msgstr "ラベルをダウンロード"
+
msgid "Download PDF"
msgstr "PDFをダウンロード"
@@ -2702,6 +2715,9 @@ msgstr "期間"
msgid "e.g. DWG-1234"
msgstr "例:DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "例:Zebra 2x1"
+
msgid "Edit"
msgstr "編集"
@@ -3878,6 +3894,9 @@ msgstr "アイテムが既に存在する場合"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "部品番号を変更したい場合は、[キャンセル]をクリックして、変換する前に各行アイテムの部品を手動で割り当ててください。"
+msgid "Imperial"
+msgstr "インペリアル"
+
msgid "Implementation Support"
msgstr "実装サポート"
@@ -4337,6 +4356,9 @@ msgstr "詳細を見る"
msgid "Leave any related receipts untouched"
msgstr "関連するすべての領収書はそのままにしておく"
+msgid "Leave blank for built-in"
+msgstr "組み込みの場合は空白のままにしてください"
+
msgid "Leave empty for exact match"
msgstr "正確な一致のために空のままにしてください"
@@ -4714,6 +4736,9 @@ msgstr "平均修復時間"
msgid "Measurement Standard"
msgstr "測定標準"
+msgid "Media Size"
+msgstr "メディアサイズ"
+
msgid "Members"
msgstr "メンバー"
@@ -5255,6 +5280,9 @@ msgstr "画像なし"
msgid "No issue types configured"
msgstr "問題タイプが設定されていません"
+msgid "No locations found."
+msgstr "ロケーションが見つかりません。"
+
msgid "No logo uploaded"
msgstr "ロゴがアップロードされていません"
@@ -5306,6 +5334,12 @@ msgstr "選択した数量の価格設定がありません"
msgid "No pricing options found"
msgstr "価格オプションが見つかりません"
+msgid "No printer configured"
+msgstr "プリンターが設定されていません"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "プリンターが設定されていません。「プリンターを追加」をクリックして作成してください。"
+
msgid "No Quote"
msgstr "見積なし"
@@ -5573,6 +5607,9 @@ msgstr "注文"
msgid "Orders submitted"
msgstr "注文が送信されました"
+msgid "Origin"
+msgstr "オリジン"
+
msgid "Other Type"
msgstr "その他のタイプ"
@@ -5705,12 +5742,18 @@ msgstr "支払条件"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF(ドキュメント)"
+
msgid "PDF downloaded"
msgstr "PDFをダウンロードしました"
msgid "PDF pages"
msgstr "PDFページ"
+msgid "PDF Preview"
+msgstr "PDFプレビュー"
+
msgid "PDF Watermark"
msgstr "PDF透かし"
@@ -5750,6 +5793,9 @@ msgstr "写真が正常に削除されました"
msgid "Photo uploaded successfully"
msgstr "写真が正常にアップロードされました"
+msgid "Physical printers available for assignment."
+msgstr "割り当て可能な物理プリンター。"
+
msgid "Pick"
msgstr "ピック"
@@ -5900,6 +5946,9 @@ msgstr "前へ"
msgid "Preview"
msgstr "プレビュー"
+msgid "Preview failed: {error}"
+msgstr "プレビューに失敗しました: {error}"
+
msgid "Preview Quantity"
msgstr "プレビュー数量"
@@ -5942,9 +5991,35 @@ msgstr "価格設定ルール"
msgid "Pricing Trace"
msgstr "価格トレース"
+msgid "Print"
+msgstr "印刷"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "{0}個のラベルを印刷"
+
+msgid "Print Jobs"
+msgstr "印刷ジョブ"
+
msgid "Print Label"
msgstr "ラベルを印刷"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "印刷出力 ({0})"
+
+msgid "Printer Settings"
+msgstr "プリンター設定"
+
+msgid "Printer URL"
+msgstr "プリンターURL"
+
+msgid "Printers"
+msgstr "プリンター"
+
+msgid "Printing"
+msgstr "印刷"
+
msgid "Priorities"
msgstr "優先度"
@@ -5975,9 +6050,6 @@ msgstr "プロセスタイプ"
msgid "Processes"
msgstr "プロセス"
-msgid "Product Label Size"
-msgstr "製品ラベルサイズ"
-
msgid "Production"
msgstr "生産"
@@ -6405,6 +6477,9 @@ msgstr "このストレージタイプをすべての参照ストレージユニ
msgid "Remove Transfer"
msgstr "転送を削除"
+msgid "Rendering label preview..."
+msgstr "ラベルプレビューをレンダリング中..."
+
msgid "Reopen"
msgstr "再度開く"
@@ -6462,6 +6537,9 @@ msgstr "レポート"
msgid "Reports"
msgstr "レポート"
+msgid "Reprint"
+msgstr "再印刷"
+
msgid "Request Approval"
msgstr "承認をリクエスト"
@@ -6946,6 +7024,9 @@ msgstr "アイテムタイプを選択"
msgid "Select items"
msgstr "アイテムを選択"
+msgid "Select Printer"
+msgstr "プリンターを選択"
+
msgid "Select Quantities"
msgstr "数量を選択"
@@ -7711,12 +7792,18 @@ msgstr "税:"
msgid "Temperature"
msgstr "温度"
+msgid "Template ID"
+msgstr "テンプレートID"
+
msgid "Terms and Privacy"
msgstr "利用規約とプライバシー"
msgid "Terms of Service"
msgstr "利用規約"
+msgid "Test"
+msgstr "テスト"
+
msgid "Test Value"
msgstr "テスト値"
@@ -8029,9 +8116,6 @@ msgstr "追跡"
msgid "Tracking ID"
msgstr "追跡ID"
-msgid "Tracking Labels"
-msgstr "トラッキングラベル"
-
msgid "Tracking Number"
msgstr "追跡番号"
@@ -8455,6 +8539,9 @@ msgstr "オープンなRFQを表示"
msgid "View Permissions"
msgstr "表示権限"
+msgid "View Prints"
+msgstr "プリントを表示"
+
msgid "View Production Events"
msgstr "生産イベントを表示"
@@ -8770,3 +8857,9 @@ msgstr "ズームイン"
msgid "Zoom out"
msgstr "ズームアウト"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL(サーマルラベル)"
+
+msgid "ZPL Label Preview"
+msgstr "ZPLラベルプレビュー"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index f34443ee65..698cf3146c 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - セット {1}"
msgid "{0} Active"
msgstr "{0} アクティブ"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} 利用可能"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "追加"
msgid "Add & Issue"
msgstr "追加して払出"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "印刷設定でプリンターを追加して、ラベルを直接印刷します。"
+
msgid "Add Inventory"
msgstr "在庫追加"
@@ -106,11 +105,6 @@ msgstr "認証エラー"
msgid "Batch"
msgstr "バッチ"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "バッチ {0}({1} 利用可能)"
-
msgid "Batch is not available"
msgstr "バッチは利用できません"
@@ -272,6 +266,9 @@ msgstr "停止"
msgid "Download"
msgstr "ダウンロード"
+msgid "Download Labels"
+msgstr "ラベルをダウンロード"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "ファイルをここにドラッグ&ドロップするか、クリックしてファイルを選択してください"
@@ -387,6 +384,9 @@ msgstr "アイデア、提案、または問題はありますか?"
msgid "Impact"
msgstr "影響"
+msgid "Imperial"
+msgstr "インペリアル"
+
msgid "In Progress"
msgstr "進行中"
@@ -501,6 +501,9 @@ msgstr "材料"
msgid "Maximum number of records reached"
msgstr "レコードの最大数に達しました"
+msgid "Metric"
+msgstr "メートル法"
+
msgid "Model"
msgstr "モデル"
@@ -580,6 +583,9 @@ msgstr "オプションが見つかりません。"
msgid "No options found."
msgstr "オプションが見つかりません。"
+msgid "No printer configured"
+msgstr "プリンターが設定されていません"
+
msgid "No recent operations"
msgstr "最近の工程はありません"
@@ -683,6 +689,12 @@ msgstr "前へ"
msgid "Preventive"
msgstr "予防保全"
+msgid "Print"
+msgstr "印刷"
+
+msgid "Printer Settings"
+msgstr "プリンター設定"
+
msgid "Priority"
msgstr "優先度"
@@ -808,6 +820,9 @@ msgstr "品目を選択..."
msgid "Select Batch {0}"
msgstr "バッチ {0} を選択"
+msgid "Select Printer"
+msgstr "プリンターを選択"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "シリアル {0} を選択"
@@ -824,10 +839,6 @@ msgstr "送信"
msgid "Serial"
msgstr "シリアル"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "シリアル {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "シリアル番号 {0}"
@@ -962,9 +973,6 @@ msgstr "合計: {0}"
msgid "Tracking"
msgstr "追跡"
-msgid "Tracking Labels"
-msgstr "追跡ラベル"
-
msgid "Type a message..."
msgstr "メッセージを入力..."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 4d99c30ac0..d8bcd2524f 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -270,6 +270,9 @@ msgstr "Dodaj kolumnę poniżej, aby posortować widok"
msgid "Add a comment..."
msgstr "Dodaj komentarz..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Dodaj drukarkę w ustawieniach drukowania, aby drukować etykiety bezpośrednio."
+
msgid "Add Actions"
msgstr "Dodaj Działania"
@@ -339,6 +342,9 @@ msgstr "Dodaj partnera"
msgid "Add Permissions"
msgstr "Dodaj uprawnienia"
+msgid "Add Printer"
+msgstr "Dodaj drukarkę"
+
msgid "Add Property"
msgstr "Dodaj właściwość"
@@ -759,6 +765,10 @@ msgstr "Czy na pewno chcesz usunąć termin płatności: {0}? Tej czynności nie
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "Czy na pewno chcesz usunąć regułę cenową: {0}? Tej czynności nie można cofnąć."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "Czy na pewno chcesz usunąć drukarkę „{0}\"? Wszystkie przypisania odwołujące się do tej drukarki zostaną wyczyszczone. Tej operacji nie można cofnąć."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Klasy aktywów"
msgid "Assets"
msgstr "Aktywa"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Przypisz drukarki do lokalizacji. Wysyłka, odbiór i centra pracy dziedziczą domyślne ustawienia lokalizacji, chyba że zostaną zastąpione."
+
msgid "Assign To"
msgstr "Przypisz do"
@@ -2239,9 +2252,6 @@ msgstr "Jednostka domyślna"
msgid "Defaults"
msgstr "Ustawienia domyślne"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Zdefiniuj domyślny rozmiar etykiety produktu. Używane do śledzenia przedmiotów w magazynie."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Zdefiniuj warunki i zasady dla zamówień zakupu"
@@ -2614,6 +2624,9 @@ msgstr "Pobierz"
msgid "Download CSV"
msgstr "Pobierz CSV"
+msgid "Download Labels"
+msgstr "Pobierz Etykiety"
+
msgid "Download PDF"
msgstr "Pobierz PDF"
@@ -2702,6 +2715,9 @@ msgstr "Czas trwania"
msgid "e.g. DWG-1234"
msgstr "np. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "np. Zebra 2x1"
+
msgid "Edit"
msgstr "Edytuj"
@@ -3878,6 +3894,9 @@ msgstr "Jeśli elementy już istnieją"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "Jeśli chcesz zmienić numery części, kliknij Anuluj i ręcznie przypisz części dla każdej pozycji wiersza przed konwersją."
+msgid "Imperial"
+msgstr "Imperialny"
+
msgid "Implementation Support"
msgstr "Wsparcie wdrażania"
@@ -4337,6 +4356,9 @@ msgstr "Dowiedz się więcej"
msgid "Leave any related receipts untouched"
msgstr "Pozostaw wszelkie powiązane paragony bez zmian"
+msgid "Leave blank for built-in"
+msgstr "Pozostaw puste dla wbudowanego"
+
msgid "Leave empty for exact match"
msgstr "Pozostaw puste dla dokładnego dopasowania"
@@ -4714,6 +4736,9 @@ msgstr "Średni czas naprawy"
msgid "Measurement Standard"
msgstr "Standard Pomiaru"
+msgid "Media Size"
+msgstr "Rozmiar nośnika"
+
msgid "Members"
msgstr "Członkowie"
@@ -5255,6 +5280,9 @@ msgstr "Brak obrazu"
msgid "No issue types configured"
msgstr "Brak skonfigurowanych typów problemów"
+msgid "No locations found."
+msgstr "Nie znaleziono lokalizacji."
+
msgid "No logo uploaded"
msgstr "Nie przesłano logo"
@@ -5306,6 +5334,12 @@ msgstr "Brak cen dla wybranej ilości"
msgid "No pricing options found"
msgstr "Nie znaleziono opcji cenowych"
+msgid "No printer configured"
+msgstr "Brak skonfigurowanej drukarki"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "Brak skonfigurowanych drukarek. Kliknij „Dodaj drukarkę\", aby utworzyć jedną."
+
msgid "No Quote"
msgstr "Brak oferty"
@@ -5573,6 +5607,9 @@ msgstr "Zamówienia"
msgid "Orders submitted"
msgstr "Zamówienia przesłane"
+msgid "Origin"
+msgstr "Pochodzenie"
+
msgid "Other Type"
msgstr "Inny typ"
@@ -5705,12 +5742,18 @@ msgstr "Warunki Płatności"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Dokument)"
+
msgid "PDF downloaded"
msgstr "PDF pobrany"
msgid "PDF pages"
msgstr "Strony PDF"
+msgid "PDF Preview"
+msgstr "Podgląd PDF"
+
msgid "PDF Watermark"
msgstr "Znak wodny PDF"
@@ -5750,6 +5793,9 @@ msgstr "Zdjęcie usunięte pomyślnie"
msgid "Photo uploaded successfully"
msgstr "Zdjęcie przesłane pomyślnie"
+msgid "Physical printers available for assignment."
+msgstr "Drukarki fizyczne dostępne do przypisania."
+
msgid "Pick"
msgstr "Wybierz"
@@ -5900,6 +5946,9 @@ msgstr "Poprz"
msgid "Preview"
msgstr "Podgląd"
+msgid "Preview failed: {error}"
+msgstr "Podgląd nie powiódł się: {error}"
+
msgid "Preview Quantity"
msgstr "Ilość podglądu"
@@ -5942,9 +5991,35 @@ msgstr "Reguły cenowe"
msgid "Pricing Trace"
msgstr "Śledzenie cen"
+msgid "Print"
+msgstr "Drukuj"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Drukuj {0} etykiet"
+
+msgid "Print Jobs"
+msgstr "Zadania drukowania"
+
msgid "Print Label"
msgstr "Drukuj etykietę"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Wydruk ({0})"
+
+msgid "Printer Settings"
+msgstr "Ustawienia drukarki"
+
+msgid "Printer URL"
+msgstr "URL drukarki"
+
+msgid "Printers"
+msgstr "Drukarki"
+
+msgid "Printing"
+msgstr "Drukowanie"
+
msgid "Priorities"
msgstr "Priorytety"
@@ -5975,9 +6050,6 @@ msgstr "Typ procesu"
msgid "Processes"
msgstr "Procesy"
-msgid "Product Label Size"
-msgstr "Rozmiar etykiety produktu"
-
msgid "Production"
msgstr "Produkcja"
@@ -6405,6 +6477,9 @@ msgstr "Usuń ten typ magazynu ze wszystkich jednostek magazynowych, które się
msgid "Remove Transfer"
msgstr "Usuń transfer"
+msgid "Rendering label preview..."
+msgstr "Renderowanie podglądu etykiety..."
+
msgid "Reopen"
msgstr "Ponownie otwórz"
@@ -6462,6 +6537,9 @@ msgstr "Raport"
msgid "Reports"
msgstr "Raporty"
+msgid "Reprint"
+msgstr "Wydruk ponownie"
+
msgid "Request Approval"
msgstr "Poproś o zatwierdzenie"
@@ -6946,6 +7024,9 @@ msgstr "Wybierz typ elementu"
msgid "Select items"
msgstr "Wybierz artykuły"
+msgid "Select Printer"
+msgstr "Wybierz drukarkę"
+
msgid "Select Quantities"
msgstr "Wybierz ilości"
@@ -7711,12 +7792,18 @@ msgstr "Podatek:"
msgid "Temperature"
msgstr "Temperatura"
+msgid "Template ID"
+msgstr "Identyfikator szablonu"
+
msgid "Terms and Privacy"
msgstr "Regulamin i prywatnosc"
msgid "Terms of Service"
msgstr "Warunki korzystania"
+msgid "Test"
+msgstr "Testuj"
+
msgid "Test Value"
msgstr "Wartość testowa"
@@ -8029,9 +8116,6 @@ msgstr "Śledzenie"
msgid "Tracking ID"
msgstr "ID śledzenia"
-msgid "Tracking Labels"
-msgstr "Etykiety śledzenia"
-
msgid "Tracking Number"
msgstr "Numer śledzenia"
@@ -8455,6 +8539,9 @@ msgstr "Wyświetl otwarte zapytania ofertowe"
msgid "View Permissions"
msgstr "Uprawnienia do wyświetlania"
+msgid "View Prints"
+msgstr "Wyświetl wydruki"
+
msgid "View Production Events"
msgstr "Wyświetl zdarzenia produkcji"
@@ -8770,3 +8857,9 @@ msgstr "Powiększ"
msgid "Zoom out"
msgstr "Zmniejsz"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Etykieta termiczna)"
+
+msgid "ZPL Label Preview"
+msgstr "Podgląd etykiety ZPL"
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 76c4b4054b..6b81c559c8 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - Zestaw {1}"
msgid "{0} Active"
msgstr "{0} Aktywnych"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} dostępnych"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Dodaj"
msgid "Add & Issue"
msgstr "Dodaj i wydaj"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Dodaj drukarkę w ustawieniach drukowania, aby drukować etykiety bezpośrednio."
+
msgid "Add Inventory"
msgstr "Dodaj zapasy"
@@ -106,11 +105,6 @@ msgstr "Błąd uwierzytelniania"
msgid "Batch"
msgstr "Partia"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Partia {0} ({1} dostępnych)"
-
msgid "Batch is not available"
msgstr "Partia jest niedostępna"
@@ -272,6 +266,9 @@ msgstr "Awaria"
msgid "Download"
msgstr "Pobierz"
+msgid "Download Labels"
+msgstr "Pobierz etykiety"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Przeciągnij i upuść plik tutaj lub kliknij, aby wybrać plik"
@@ -387,6 +384,9 @@ msgstr "Pomysły, sugestie lub problemy?"
msgid "Impact"
msgstr "Wpływ"
+msgid "Imperial"
+msgstr "Imperialny"
+
msgid "In Progress"
msgstr "W toku"
@@ -501,6 +501,9 @@ msgstr "Materiały"
msgid "Maximum number of records reached"
msgstr "Osiągnięto maksymalną liczbę rekordów"
+msgid "Metric"
+msgstr "Metryczny"
+
msgid "Model"
msgstr "Model"
@@ -580,6 +583,9 @@ msgstr "Nie znaleziono opcji."
msgid "No options found."
msgstr "Nie znaleziono opcji."
+msgid "No printer configured"
+msgstr "Brak skonfigurowanej drukarki"
+
msgid "No recent operations"
msgstr "Brak ostatnich operacji"
@@ -683,6 +689,12 @@ msgstr "Poprzedni"
msgid "Preventive"
msgstr "Prewencyjne"
+msgid "Print"
+msgstr "Drukuj"
+
+msgid "Printer Settings"
+msgstr "Ustawienia drukarki"
+
msgid "Priority"
msgstr "Priorytet"
@@ -808,6 +820,9 @@ msgstr "Wybierz pozycję..."
msgid "Select Batch {0}"
msgstr "Wybierz partię {0}"
+msgid "Select Printer"
+msgstr "Wybierz drukarkę"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Wybierz numer seryjny {0}"
@@ -824,10 +839,6 @@ msgstr "Wyślij"
msgid "Serial"
msgstr "Seryjny"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Seryjny {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Numer seryjny {0}"
@@ -962,9 +973,6 @@ msgstr "Razem: {0}"
msgid "Tracking"
msgstr "Śledzenie"
-msgid "Tracking Labels"
-msgstr "Etykiety śledzenia"
-
msgid "Type a message..."
msgstr "Wpisz wiadomość..."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 25a7ba2de4..f9e2ffdcc5 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -270,6 +270,9 @@ msgstr "Adicione uma coluna abaixo para ordenar a visualização"
msgid "Add a comment..."
msgstr "Adicione um comentário..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Adicione uma impressora nas configurações de impressão para imprimir etiquetas diretamente."
+
msgid "Add Actions"
msgstr "Adicionar Ações"
@@ -339,6 +342,9 @@ msgstr "Adicionar Parceiro"
msgid "Add Permissions"
msgstr "Adicionar Permissões"
+msgid "Add Printer"
+msgstr "Adicionar Impressora"
+
msgid "Add Property"
msgstr "Adicionar Propriedade"
@@ -759,6 +765,10 @@ msgstr "Tem a certeza de que deseja eliminar o termo de pagamento: {0}? Esta aç
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "Tem a certeza de que deseja eliminar a regra de preço: {0}? Esta ação não pode ser desfeita."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "Tem a certeza de que deseja eliminar a impressora \"{0}\"? Todas as atribuições que fazem referência a esta impressora serão limpas. Isto não pode ser desfeito."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Classes de Ativos"
msgid "Assets"
msgstr "Ativos"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Atribua impressoras a locais. Envio, recebimento e centros de trabalho herdam o padrão do local, a menos que sejam substituídos."
+
msgid "Assign To"
msgstr "Atribuir a"
@@ -2239,9 +2252,6 @@ msgstr "Unidade Padrão"
msgid "Defaults"
msgstr "Padrões"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Defina o tamanho padrão do rótulo do produto. Usado para rastrear itens no inventário."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Defina os termos e condições para pedidos de compra"
@@ -2614,6 +2624,9 @@ msgstr "Baixar"
msgid "Download CSV"
msgstr "Baixar CSV"
+msgid "Download Labels"
+msgstr "Baixar Etiquetas"
+
msgid "Download PDF"
msgstr "Baixar PDF"
@@ -2702,6 +2715,9 @@ msgstr "Duração"
msgid "e.g. DWG-1234"
msgstr "p.ex. DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "p.ex. Zebra 2x1"
+
msgid "Edit"
msgstr "Editar"
@@ -3878,6 +3894,9 @@ msgstr "Se os itens já existem"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "Se deseja alterar os números das peças, clique em Cancelar e atribua manualmente as peças para cada item de linha antes de converter."
+msgid "Imperial"
+msgstr "Imperial"
+
msgid "Implementation Support"
msgstr "Suporte de Implementação"
@@ -4337,6 +4356,9 @@ msgstr "Saiba mais"
msgid "Leave any related receipts untouched"
msgstr "Deixar qualquer recebimento relacionado intocado"
+msgid "Leave blank for built-in"
+msgstr "Deixe em branco para usar o padrão"
+
msgid "Leave empty for exact match"
msgstr "Deixe vazio para correspondência exata"
@@ -4714,6 +4736,9 @@ msgstr "Tempo Médio de Reparo"
msgid "Measurement Standard"
msgstr "Padrão de Medição"
+msgid "Media Size"
+msgstr "Tamanho da Mídia"
+
msgid "Members"
msgstr "Membros"
@@ -5255,6 +5280,9 @@ msgstr "Sem imagem"
msgid "No issue types configured"
msgstr "Nenhum tipo de problema configurado"
+msgid "No locations found."
+msgstr "Nenhuma localização encontrada."
+
msgid "No logo uploaded"
msgstr "Nenhum logo enviado"
@@ -5306,6 +5334,12 @@ msgstr "Sem preço para a quantidade selecionada"
msgid "No pricing options found"
msgstr "Nenhuma opção de preço encontrada"
+msgid "No printer configured"
+msgstr "Nenhuma impressora configurada"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "Nenhuma impressora configurada. Clique em \"Adicionar Impressora\" para criar uma."
+
msgid "No Quote"
msgstr "Sem Cotação"
@@ -5573,6 +5607,9 @@ msgstr "Pedidos"
msgid "Orders submitted"
msgstr "Pedidos enviados"
+msgid "Origin"
+msgstr "Origem"
+
msgid "Other Type"
msgstr "Outro Tipo"
@@ -5705,12 +5742,18 @@ msgstr "Condições de Pagamento"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Documento)"
+
msgid "PDF downloaded"
msgstr "PDF baixado"
msgid "PDF pages"
msgstr "Páginas do PDF"
+msgid "PDF Preview"
+msgstr "Visualização de PDF"
+
msgid "PDF Watermark"
msgstr "Marca d'água do PDF"
@@ -5750,6 +5793,9 @@ msgstr "Foto removida com sucesso"
msgid "Photo uploaded successfully"
msgstr "Foto enviada com sucesso"
+msgid "Physical printers available for assignment."
+msgstr "Impressoras físicas disponíveis para atribuição."
+
msgid "Pick"
msgstr "Selecionar"
@@ -5900,6 +5946,9 @@ msgstr "Anterior"
msgid "Preview"
msgstr "Visualizar"
+msgid "Preview failed: {error}"
+msgstr "Falha na visualização: {error}"
+
msgid "Preview Quantity"
msgstr "Quantidade de Visualização"
@@ -5942,9 +5991,35 @@ msgstr "Regras de Preço"
msgid "Pricing Trace"
msgstr "Rastreamento de Preços"
+msgid "Print"
+msgstr "Imprimir"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Imprimir {0} Etiquetas"
+
+msgid "Print Jobs"
+msgstr "Trabalhos de Impressão"
+
msgid "Print Label"
msgstr "Imprimir Etiqueta"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Saída de Impressão ({0})"
+
+msgid "Printer Settings"
+msgstr "Configurações de Impressora"
+
+msgid "Printer URL"
+msgstr "URL da Impressora"
+
+msgid "Printers"
+msgstr "Impressoras"
+
+msgid "Printing"
+msgstr "Impressão"
+
msgid "Priorities"
msgstr "Prioridades"
@@ -5975,9 +6050,6 @@ msgstr "Tipo de Processo"
msgid "Processes"
msgstr "Processos"
-msgid "Product Label Size"
-msgstr "Tamanho da Etiqueta do Produto"
-
msgid "Production"
msgstr "Produção"
@@ -6405,6 +6477,9 @@ msgstr "Remova este tipo de armazenamento de todas as unidades de armazenamento
msgid "Remove Transfer"
msgstr "Remover Transferência"
+msgid "Rendering label preview..."
+msgstr "Renderizando visualização de etiqueta..."
+
msgid "Reopen"
msgstr "Reabrir"
@@ -6462,6 +6537,9 @@ msgstr "Relatório"
msgid "Reports"
msgstr "Relatórios"
+msgid "Reprint"
+msgstr "Reimprimir"
+
msgid "Request Approval"
msgstr "Solicitar Aprovação"
@@ -6946,6 +7024,9 @@ msgstr "Selecionar Tipo de Item"
msgid "Select items"
msgstr "Selecionar itens"
+msgid "Select Printer"
+msgstr "Selecionar Impressora"
+
msgid "Select Quantities"
msgstr "Selecionar Quantidades"
@@ -7711,12 +7792,18 @@ msgstr "Imposto:"
msgid "Temperature"
msgstr "Temperatura"
+msgid "Template ID"
+msgstr "ID do Modelo"
+
msgid "Terms and Privacy"
msgstr "Termos e Privacidade"
msgid "Terms of Service"
msgstr "Termos de Serviço"
+msgid "Test"
+msgstr "Teste"
+
msgid "Test Value"
msgstr "Valor de Teste"
@@ -8029,9 +8116,6 @@ msgstr "Rastreamento"
msgid "Tracking ID"
msgstr "ID de Rastreamento"
-msgid "Tracking Labels"
-msgstr "Etiquetas de Rastreamento"
-
msgid "Tracking Number"
msgstr "Número de Rastreamento"
@@ -8455,6 +8539,9 @@ msgstr "Ver RFQs Abertos"
msgid "View Permissions"
msgstr "Permissões de Visualização"
+msgid "View Prints"
+msgstr "Ver Impressões"
+
msgid "View Production Events"
msgstr "Ver Eventos de Produção"
@@ -8770,3 +8857,9 @@ msgstr "Ampliar"
msgid "Zoom out"
msgstr "Reduzir zoom"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Etiqueta Térmica)"
+
+msgid "ZPL Label Preview"
+msgstr "Visualização de Etiqueta ZPL"
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index 25186b8587..5bb4a7df90 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - Conjunto {1}"
msgid "{0} Active"
msgstr "{0} Ativo(s)"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} disponível(is)"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Adicionar"
msgid "Add & Issue"
msgstr "Adicionar e Emitir"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Adicione uma impressora nas configurações de impressão para imprimir etiquetas diretamente."
+
msgid "Add Inventory"
msgstr "Adicionar Estoque"
@@ -106,11 +105,6 @@ msgstr "Erro de Autenticação"
msgid "Batch"
msgstr "Lote"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Lote {0} ({1} disponível)"
-
msgid "Batch is not available"
msgstr "Lote não disponível"
@@ -272,6 +266,9 @@ msgstr "Parado"
msgid "Download"
msgstr "Baixar"
+msgid "Download Labels"
+msgstr "Baixar Etiquetas"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Arraste e solte um arquivo aqui ou clique para selecionar um arquivo"
@@ -387,6 +384,9 @@ msgstr "Ideias, sugestões ou problemas?"
msgid "Impact"
msgstr "Impacto"
+msgid "Imperial"
+msgstr "Imperial"
+
msgid "In Progress"
msgstr "Em Andamento"
@@ -501,6 +501,9 @@ msgstr "Materiais"
msgid "Maximum number of records reached"
msgstr "Número máximo de registros atingido"
+msgid "Metric"
+msgstr "Métrico"
+
msgid "Model"
msgstr "Modelo"
@@ -580,6 +583,9 @@ msgstr "Nenhuma opção encontrada."
msgid "No options found."
msgstr "Nenhuma opção encontrada."
+msgid "No printer configured"
+msgstr "Nenhuma impressora configurada"
+
msgid "No recent operations"
msgstr "Nenhuma operação recente"
@@ -683,6 +689,12 @@ msgstr "Anterior"
msgid "Preventive"
msgstr "Preventiva"
+msgid "Print"
+msgstr "Imprimir"
+
+msgid "Printer Settings"
+msgstr "Configurações de Impressora"
+
msgid "Priority"
msgstr "Prioridade"
@@ -808,6 +820,9 @@ msgstr "Selecione um item..."
msgid "Select Batch {0}"
msgstr "Selecionar Lote {0}"
+msgid "Select Printer"
+msgstr "Selecionar Impressora"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Selecionar Série {0}"
@@ -824,10 +839,6 @@ msgstr "Enviar"
msgid "Serial"
msgstr "Série"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Série {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Número de Série {0}"
@@ -962,9 +973,6 @@ msgstr "Total: {0}"
msgid "Tracking"
msgstr "Rastreamento"
-msgid "Tracking Labels"
-msgstr "Etiquetas de Rastreamento"
-
msgid "Type a message..."
msgstr "Digite uma mensagem..."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 3eac4d65e5..28e711b563 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -270,6 +270,9 @@ msgstr "Добавьте столбец ниже для сортировки п
msgid "Add a comment..."
msgstr "Добавить комментарий..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Добавьте принтер в параметры печати, чтобы печатать этикетки напрямую."
+
msgid "Add Actions"
msgstr "Добавить действия"
@@ -339,6 +342,9 @@ msgstr "Добавить партнера"
msgid "Add Permissions"
msgstr "Добавить разрешения"
+msgid "Add Printer"
+msgstr "Добавить принтер"
+
msgid "Add Property"
msgstr "Добавить свойство"
@@ -759,6 +765,10 @@ msgstr "Вы уверены, что хотите удалить условие
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "Вы уверены, что хотите удалить правило ценообразования: {0}? Это действие невозможно отменить."
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "Вы уверены, что хотите удалить принтер \"{0}\"? Все назначения, ссылающиеся на этот принтер, будут очищены. Это действие невозможно отменить."
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "Классы активов"
msgid "Assets"
msgstr "Активы"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "Назначьте принтеры местоположениям. Доставка, получение и рабочие центры наследуют значение по умолчанию для местоположения, если не переопределено."
+
msgid "Assign To"
msgstr "Назначить"
@@ -2239,9 +2252,6 @@ msgstr "Единица по умолчанию"
msgid "Defaults"
msgstr "Значения по умолчанию"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "Определите размер этикетки продукта по умолчанию. Используется для отслеживания товаров в инвентаре."
-
msgid "Define the terms and conditions for purchase orders"
msgstr "Определите условия и положения для заказов на покупку"
@@ -2614,6 +2624,9 @@ msgstr "Скачать"
msgid "Download CSV"
msgstr "Загрузить CSV"
+msgid "Download Labels"
+msgstr "Загрузить этикетки"
+
msgid "Download PDF"
msgstr "Скачать PDF"
@@ -2702,6 +2715,9 @@ msgstr "Продолжительность"
msgid "e.g. DWG-1234"
msgstr "например, DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "например Zebra 2x1"
+
msgid "Edit"
msgstr "Редактировать"
@@ -3878,6 +3894,9 @@ msgstr "Если элементы уже существуют"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "Если вы хотите изменить номера деталей, нажмите Отмена и вручную назначьте детали для каждого элемента строки перед преобразованием."
+msgid "Imperial"
+msgstr "Имперская"
+
msgid "Implementation Support"
msgstr "Поддержка внедрения"
@@ -4337,6 +4356,9 @@ msgstr "Узнать больше"
msgid "Leave any related receipts untouched"
msgstr "Оставить все связанные квитанции без изменений"
+msgid "Leave blank for built-in"
+msgstr "Оставьте пустым для встроенного"
+
msgid "Leave empty for exact match"
msgstr "Оставьте пустым для точного совпадения"
@@ -4714,6 +4736,9 @@ msgstr "Среднее время на ремонт"
msgid "Measurement Standard"
msgstr "Стандарт измерения"
+msgid "Media Size"
+msgstr "Размер носителя"
+
msgid "Members"
msgstr "Участники"
@@ -5255,6 +5280,9 @@ msgstr "Нет изображения"
msgid "No issue types configured"
msgstr "Типы проблем не настроены"
+msgid "No locations found."
+msgstr "Локации не найдены."
+
msgid "No logo uploaded"
msgstr "Логотип не загружен"
@@ -5306,6 +5334,12 @@ msgstr "Нет цен для выбранного количества"
msgid "No pricing options found"
msgstr "Нет доступных вариантов цен"
+msgid "No printer configured"
+msgstr "Принтер не настроен"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "Принтеры не настроены. Нажмите «Добавить принтер» для создания."
+
msgid "No Quote"
msgstr "Нет предложения"
@@ -5573,6 +5607,9 @@ msgstr "Заказы"
msgid "Orders submitted"
msgstr "Заказы отправлены"
+msgid "Origin"
+msgstr "Источник"
+
msgid "Other Type"
msgstr "Другой тип"
@@ -5705,12 +5742,18 @@ msgstr "Условия платежа"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF (Документ)"
+
msgid "PDF downloaded"
msgstr "PDF загружен"
msgid "PDF pages"
msgstr "Страницы PDF"
+msgid "PDF Preview"
+msgstr "Предпросмотр PDF"
+
msgid "PDF Watermark"
msgstr "Водяной знак PDF"
@@ -5750,6 +5793,9 @@ msgstr "Фото успешно удалено"
msgid "Photo uploaded successfully"
msgstr "Фото успешно загружено"
+msgid "Physical printers available for assignment."
+msgstr "Физические принтеры, доступные для назначения."
+
msgid "Pick"
msgstr "Выбрать"
@@ -5900,6 +5946,9 @@ msgstr "Пред"
msgid "Preview"
msgstr "Предпросмотр"
+msgid "Preview failed: {error}"
+msgstr "Ошибка предпросмотра: {error}"
+
msgid "Preview Quantity"
msgstr "Предпросмотр количества"
@@ -5942,9 +5991,35 @@ msgstr "Правила цен"
msgid "Pricing Trace"
msgstr "Трассировка цен"
+msgid "Print"
+msgstr "Печать"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "Печать {0} этикеток"
+
+msgid "Print Jobs"
+msgstr "Задания печати"
+
msgid "Print Label"
msgstr "Печать этикетки"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "Вывод печати ({0})"
+
+msgid "Printer Settings"
+msgstr "Параметры принтера"
+
+msgid "Printer URL"
+msgstr "URL принтера"
+
+msgid "Printers"
+msgstr "Принтеры"
+
+msgid "Printing"
+msgstr "Печать"
+
msgid "Priorities"
msgstr "Приоритеты"
@@ -5975,9 +6050,6 @@ msgstr "Тип процесса"
msgid "Processes"
msgstr "Процессы"
-msgid "Product Label Size"
-msgstr "Размер этикетки продукта"
-
msgid "Production"
msgstr "Производство"
@@ -6405,6 +6477,9 @@ msgstr "Удалите этот тип хранилища из всех ссыл
msgid "Remove Transfer"
msgstr "Удалить передачу"
+msgid "Rendering label preview..."
+msgstr "Отрисовка предпросмотра этикетки..."
+
msgid "Reopen"
msgstr "Переоткрыть"
@@ -6462,6 +6537,9 @@ msgstr "Отчет"
msgid "Reports"
msgstr "Отчеты"
+msgid "Reprint"
+msgstr "Перепечать"
+
msgid "Request Approval"
msgstr "Запросить одобрение"
@@ -6946,6 +7024,9 @@ msgstr "Выберите тип элемента"
msgid "Select items"
msgstr "Выберите товары"
+msgid "Select Printer"
+msgstr "Выберите принтер"
+
msgid "Select Quantities"
msgstr "Выберите количества"
@@ -7711,12 +7792,18 @@ msgstr "Налог:"
msgid "Temperature"
msgstr "Температура"
+msgid "Template ID"
+msgstr "ID шаблона"
+
msgid "Terms and Privacy"
msgstr "Условия и конфиденциальность"
msgid "Terms of Service"
msgstr "Условия обслуживания"
+msgid "Test"
+msgstr "Тест"
+
msgid "Test Value"
msgstr "Тестовое значение"
@@ -8029,9 +8116,6 @@ msgstr "Отслеживание"
msgid "Tracking ID"
msgstr "ID отслеживания"
-msgid "Tracking Labels"
-msgstr "Этикетки отслеживания"
-
msgid "Tracking Number"
msgstr "Номер отслеживания"
@@ -8455,6 +8539,9 @@ msgstr "Просмотреть открытые РФП"
msgid "View Permissions"
msgstr "Разрешения на просмотр"
+msgid "View Prints"
+msgstr "Просмотр печатей"
+
msgid "View Production Events"
msgstr "Просмотр событий производства"
@@ -8770,3 +8857,9 @@ msgstr "Увеличить"
msgid "Zoom out"
msgstr "Уменьшить масштаб"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL (Термальная этикетка)"
+
+msgid "ZPL Label Preview"
+msgstr "Предпросмотр этикетки ZPL"
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index 382875a682..82706b0213 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} — Набор {1}"
msgid "{0} Active"
msgstr "{0} Активных"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} доступно"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "Добавить"
msgid "Add & Issue"
msgstr "Добавить и выдать"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "Добавьте принтер в параметры печати, чтобы печатать этикетки напрямую."
+
msgid "Add Inventory"
msgstr "Добавить запас"
@@ -106,11 +105,6 @@ msgstr "Ошибка аутентификации"
msgid "Batch"
msgstr "Партия"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "Партия {0} ({1} доступно)"
-
msgid "Batch is not available"
msgstr "Партия недоступна"
@@ -272,6 +266,9 @@ msgstr "Простой"
msgid "Download"
msgstr "Скачать"
+msgid "Download Labels"
+msgstr "Загрузить этикетки"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "Перетащите файл сюда или нажмите для выбора файла"
@@ -387,6 +384,9 @@ msgstr "Идеи, предложения или проблемы?"
msgid "Impact"
msgstr "Влияние"
+msgid "Imperial"
+msgstr "Имперская"
+
msgid "In Progress"
msgstr "В работе"
@@ -501,6 +501,9 @@ msgstr "Материалы"
msgid "Maximum number of records reached"
msgstr "Достигнуто максимальное количество записей"
+msgid "Metric"
+msgstr "Метрическая"
+
msgid "Model"
msgstr "Модель"
@@ -580,6 +583,9 @@ msgstr "Опция не найдена."
msgid "No options found."
msgstr "Варианты не найдены."
+msgid "No printer configured"
+msgstr "Принтер не настроен"
+
msgid "No recent operations"
msgstr "Нет недавних операций"
@@ -683,6 +689,12 @@ msgstr "Назад"
msgid "Preventive"
msgstr "Профилактическое"
+msgid "Print"
+msgstr "Печать"
+
+msgid "Printer Settings"
+msgstr "Параметры принтера"
+
msgid "Priority"
msgstr "Приоритет"
@@ -808,6 +820,9 @@ msgstr "Выберите номенклатуру..."
msgid "Select Batch {0}"
msgstr "Выберите партию {0}"
+msgid "Select Printer"
+msgstr "Выберите принтер"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "Выберите серийный номер {0}"
@@ -824,10 +839,6 @@ msgstr "Отправить"
msgid "Serial"
msgstr "Серийный"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "Серийный {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "Серийный номер {0}"
@@ -962,9 +973,6 @@ msgstr "Итого: {0}"
msgid "Tracking"
msgstr "Отслеживание"
-msgid "Tracking Labels"
-msgstr "Этикетки отслеживания"
-
msgid "Type a message..."
msgstr "Введите сообщение..."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index acb97347e9..14b6a6b0a1 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -270,6 +270,9 @@ msgstr "在下方添加列以对视图进行排序"
msgid "Add a comment..."
msgstr "添加评论..."
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "在打印设置中添加打印机以直接打印标签。"
+
msgid "Add Actions"
msgstr "添加操作"
@@ -339,6 +342,9 @@ msgstr "添加合作伙伴"
msgid "Add Permissions"
msgstr "添加权限"
+msgid "Add Printer"
+msgstr "添加打印机"
+
msgid "Add Property"
msgstr "添加属性"
@@ -759,6 +765,10 @@ msgstr "您确定要删除付款条款:{0}?此操作无法撤销。"
msgid "Are you sure you want to delete the pricing rule: {0}? This cannot be undone."
msgstr "您确定要删除定价规则:{0}?此操作无法撤销。"
+#. placeholder {0}: printerToDelete.name
+msgid "Are you sure you want to delete the printer \"{0}\"? Any assignments referencing this printer will be cleared. This cannot be undone."
+msgstr "你确定要删除打印机\"{0}\"吗?任何引用此打印机的分配都将被清除。此操作无法撤销。"
+
#. placeholder {0}: purchaseInvoiceLine.quantity ?? 0
#. placeholder {1}: purchaseInvoiceLine.description ?? ""
msgid "Are you sure you want to delete the purchase invoice line for {0} {1}? This cannot be undone."
@@ -928,6 +938,9 @@ msgstr "资产类别"
msgid "Assets"
msgstr "资产"
+msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
+msgstr "将打印机分配到位置。运输、接收和工作中心继承位置默认值,除非被覆盖。"
+
msgid "Assign To"
msgstr "分配给"
@@ -2239,9 +2252,6 @@ msgstr "默认单位"
msgid "Defaults"
msgstr "默认值"
-msgid "Define the default size of the product label. Used for tracking items in inventory."
-msgstr "定义产品标签的默认大小。用于跟踪库存中的物品。"
-
msgid "Define the terms and conditions for purchase orders"
msgstr "定义采购订单的条款和条件"
@@ -2614,6 +2624,9 @@ msgstr "下载"
msgid "Download CSV"
msgstr "下载 CSV"
+msgid "Download Labels"
+msgstr "下载标签"
+
msgid "Download PDF"
msgstr "下载 PDF"
@@ -2702,6 +2715,9 @@ msgstr "时长"
msgid "e.g. DWG-1234"
msgstr "例如 DWG-1234"
+msgid "e.g. Zebra 2x1"
+msgstr "例如 Zebra 2x1"
+
msgid "Edit"
msgstr "编辑"
@@ -3878,6 +3894,9 @@ msgstr "如果项目已存在"
msgid "If you wish to change the part numbers, please click Cancel and manually assign the parts for each line item before converting."
msgstr "如果您希望更改零件号,请点击\"取消\"并在转换前为每个行项目手动分配零件。"
+msgid "Imperial"
+msgstr "英制"
+
msgid "Implementation Support"
msgstr "实施支持"
@@ -4337,6 +4356,9 @@ msgstr "了解更多"
msgid "Leave any related receipts untouched"
msgstr "保留任何相关收据不变"
+msgid "Leave blank for built-in"
+msgstr "留空以使用内置"
+
msgid "Leave empty for exact match"
msgstr "留空以精确匹配"
@@ -4714,6 +4736,9 @@ msgstr "平均修复时间"
msgid "Measurement Standard"
msgstr "测量标准"
+msgid "Media Size"
+msgstr "媒体尺寸"
+
msgid "Members"
msgstr "成员"
@@ -5255,6 +5280,9 @@ msgstr "没有图像"
msgid "No issue types configured"
msgstr "未配置问题类型"
+msgid "No locations found."
+msgstr "未找到位置。"
+
msgid "No logo uploaded"
msgstr "未上传徽标"
@@ -5306,6 +5334,12 @@ msgstr "所选数量无定价"
msgid "No pricing options found"
msgstr "未找到定价选项"
+msgid "No printer configured"
+msgstr "未配置打印机"
+
+msgid "No printers configured. Click \"Add Printer\" to create one."
+msgstr "未配置打印机。点击\"添加打印机\"创建一个。"
+
msgid "No Quote"
msgstr "无报价"
@@ -5573,6 +5607,9 @@ msgstr "订单"
msgid "Orders submitted"
msgstr "订单已提交"
+msgid "Origin"
+msgstr "来源"
+
msgid "Other Type"
msgstr "其他类型"
@@ -5705,12 +5742,18 @@ msgstr "付款条款"
msgid "PDF"
msgstr "PDF"
+msgid "PDF (Document)"
+msgstr "PDF(文档)"
+
msgid "PDF downloaded"
msgstr "PDF已下载"
msgid "PDF pages"
msgstr "PDF 页面"
+msgid "PDF Preview"
+msgstr "PDF 预览"
+
msgid "PDF Watermark"
msgstr "PDF 水印"
@@ -5750,6 +5793,9 @@ msgstr "照片已成功删除"
msgid "Photo uploaded successfully"
msgstr "照片上传成功"
+msgid "Physical printers available for assignment."
+msgstr "可用于分配的物理打印机。"
+
msgid "Pick"
msgstr "拣选"
@@ -5900,6 +5946,9 @@ msgstr "上一页"
msgid "Preview"
msgstr "预览"
+msgid "Preview failed: {error}"
+msgstr "预览失败:{error}"
+
msgid "Preview Quantity"
msgstr "预览数量"
@@ -5942,9 +5991,35 @@ msgstr "定价规则"
msgid "Pricing Trace"
msgstr "定价追踪"
+msgid "Print"
+msgstr "打印"
+
+#. placeholder {0}: selectedIds.size
+msgid "Print {0} Labels"
+msgstr "打印 {0} 个标签"
+
+msgid "Print Jobs"
+msgstr "打印任务"
+
msgid "Print Label"
msgstr "打印标签"
+#. placeholder {0}: viewContent.contentType?.toUpperCase()
+msgid "Print Output ({0})"
+msgstr "打印输出 ({0})"
+
+msgid "Printer Settings"
+msgstr "打印机设置"
+
+msgid "Printer URL"
+msgstr "打印机 URL"
+
+msgid "Printers"
+msgstr "打印机"
+
+msgid "Printing"
+msgstr "打印"
+
msgid "Priorities"
msgstr "优先级"
@@ -5975,9 +6050,6 @@ msgstr "流程类型"
msgid "Processes"
msgstr "流程"
-msgid "Product Label Size"
-msgstr "产品标签尺寸"
-
msgid "Production"
msgstr "生产"
@@ -6405,6 +6477,9 @@ msgstr "从所有引用此存储类型的存储单元中移除它并将其删除
msgid "Remove Transfer"
msgstr "移除转移"
+msgid "Rendering label preview..."
+msgstr "正在渲染标签预览..."
+
msgid "Reopen"
msgstr "重新打开"
@@ -6462,6 +6537,9 @@ msgstr "报告"
msgid "Reports"
msgstr "报告"
+msgid "Reprint"
+msgstr "重新打印"
+
msgid "Request Approval"
msgstr "请求批准"
@@ -6946,6 +7024,9 @@ msgstr "选择项目类型"
msgid "Select items"
msgstr "选择项目"
+msgid "Select Printer"
+msgstr "选择打印机"
+
msgid "Select Quantities"
msgstr "选择数量"
@@ -7711,12 +7792,18 @@ msgstr "税:"
msgid "Temperature"
msgstr "温度"
+msgid "Template ID"
+msgstr "模板 ID"
+
msgid "Terms and Privacy"
msgstr "条款和隐私"
msgid "Terms of Service"
msgstr "服务条款"
+msgid "Test"
+msgstr "测试"
+
msgid "Test Value"
msgstr "测试值"
@@ -8029,9 +8116,6 @@ msgstr "追踪"
msgid "Tracking ID"
msgstr "追踪ID"
-msgid "Tracking Labels"
-msgstr "追踪标签"
-
msgid "Tracking Number"
msgstr "跟踪号码"
@@ -8455,6 +8539,9 @@ msgstr "查看未结束的询价单"
msgid "View Permissions"
msgstr "查看权限"
+msgid "View Prints"
+msgstr "查看打印"
+
msgid "View Production Events"
msgstr "查看生产事件"
@@ -8770,3 +8857,9 @@ msgstr "放大"
msgid "Zoom out"
msgstr "缩小"
+
+msgid "ZPL (Thermal Label)"
+msgstr "ZPL(热敏标签)"
+
+msgid "ZPL Label Preview"
+msgstr "ZPL 标签预览"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index d02c8f2df3..ea20db768f 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -21,10 +21,6 @@ msgstr "{0} - 组 {1}"
msgid "{0} Active"
msgstr "{0} 个活跃"
-#. placeholder {0}: batch.quantity
-msgid "{0} available"
-msgstr "{0} 可用"
-
#. placeholder {0}: operation.quantityComplete
#. placeholder {0}: serialIndex + 1
#. placeholder {1}: operation.operationQuantity
@@ -64,6 +60,9 @@ msgstr "添加"
msgid "Add & Issue"
msgstr "添加并发放"
+msgid "Add a printer in the printing settings to print labels directly."
+msgstr "在打印设置中添加打印机以直接打印标签。"
+
msgid "Add Inventory"
msgstr "添加库存"
@@ -106,11 +105,6 @@ msgstr "认证错误"
msgid "Batch"
msgstr "批次"
-#. placeholder {0}: batch.readableId
-#. placeholder {1}: batch.quantity
-msgid "Batch {0} ({1} available)"
-msgstr "批次 {0}({1} 可用)"
-
msgid "Batch is not available"
msgstr "批次不可用"
@@ -272,6 +266,9 @@ msgstr "停机"
msgid "Download"
msgstr "下载"
+msgid "Download Labels"
+msgstr "下载标签"
+
msgid "Drag and drop a file here, or click to select a file"
msgstr "拖放文件到此处,或点击选择文件"
@@ -387,6 +384,9 @@ msgstr "有想法、建议或问题?"
msgid "Impact"
msgstr "影响"
+msgid "Imperial"
+msgstr "英制"
+
msgid "In Progress"
msgstr "进行中"
@@ -501,6 +501,9 @@ msgstr "物料"
msgid "Maximum number of records reached"
msgstr "已达到最大记录数"
+msgid "Metric"
+msgstr "公制"
+
msgid "Model"
msgstr "模型"
@@ -580,6 +583,9 @@ msgstr "未找到选项。"
msgid "No options found."
msgstr "未找到选项。"
+msgid "No printer configured"
+msgstr "未配置打印机"
+
msgid "No recent operations"
msgstr "无近期工序"
@@ -683,6 +689,12 @@ msgstr "上一个"
msgid "Preventive"
msgstr "预防性"
+msgid "Print"
+msgstr "打印"
+
+msgid "Printer Settings"
+msgstr "打印机设置"
+
msgid "Priority"
msgstr "优先级"
@@ -808,6 +820,9 @@ msgstr "选择物料..."
msgid "Select Batch {0}"
msgstr "选择批次 {0}"
+msgid "Select Printer"
+msgstr "选择打印机"
+
#. placeholder {0}: index + 1
msgid "Select Serial {0}"
msgstr "选择序列号 {0}"
@@ -824,10 +839,6 @@ msgstr "发送"
msgid "Serial"
msgstr "序列号"
-#. placeholder {0}: sn.readableId
-msgid "Serial {0}"
-msgstr "序列号 {0}"
-
#. placeholder {0}: index + 1
msgid "Serial Number {0}"
msgstr "序列号 {0}"
@@ -962,9 +973,6 @@ msgstr "合计:{0}"
msgid "Tracking"
msgstr "追踪"
-msgid "Tracking Labels"
-msgstr "追踪标签"
-
msgid "Type a message..."
msgstr "输入消息..."
diff --git a/packages/printing/package.json b/packages/printing/package.json
new file mode 100644
index 0000000000..28049e3722
--- /dev/null
+++ b/packages/printing/package.json
@@ -0,0 +1,38 @@
+{
+ "name": "@carbon/printing",
+ "dependencies": {
+ "@carbon/kv": "workspace:*",
+ "@carbon/react": "workspace:*",
+ "@carbon/utils": "workspace:*",
+ "zod": "catalog:",
+ "zod-form-data": "catalog:"
+ },
+ "devDependencies": {
+ "@carbon/config": "workspace:*",
+ "@carbon/database": "workspace:*",
+ "@supabase/supabase-js": "catalog:",
+ "@types/node": "20.19.39",
+ "@types/react": "catalog:",
+ "typescript": "catalog:"
+ },
+ "peerDependencies": {
+ "@lingui/react": "catalog:",
+ "react": "catalog:",
+ "react-icons": "catalog:",
+ "react-router": "catalog:"
+ },
+ "exports": {
+ ".": "./src/index.ts",
+ "./printing.server": "./src/printing.server.ts",
+ "./ui": "./src/ui/index.ts"
+ },
+ "private": true,
+ "scripts": {
+ "clean": "rimraf .turbo node_modules dist",
+ "dev": "tsup --watch",
+ "lint": "biome lint --write ",
+ "typecheck": "tsgo --noEmit"
+ },
+ "sideEffects": false,
+ "version": "0.0.0"
+}
diff --git a/packages/printing/printing-integration.md b/packages/printing/printing-integration.md
new file mode 100644
index 0000000000..5cfa7a1a6d
--- /dev/null
+++ b/packages/printing/printing-integration.md
@@ -0,0 +1,619 @@
+# Print Manager Integration
+
+## 1. Overview
+
+The Print Manager is a centralized print job queue and management system integrated into Carbon's ERP and MES applications. It provides automated document printing triggered by business events, a persistent audit trail of all print activity, and operator-facing tools for viewing output, reprinting, and managing printer infrastructure.
+
+### The Problem
+
+Before the Print Manager, Carbon's printing infrastructure was fragmented across several disconnected systems:
+
+- **crbnos/zpl-print** was an external standalone print server in a separate repository. It required manual ngrok tunnel setup, only supported ZPL (not PDF), and managed work center to printer mappings in a local configuration file that Carbon had no awareness of.
+
+- **Hardcoded file+/ routes** generated content on demand as downloadable files. Operators had to manually navigate to these routes, download the generated ZPL or PDF, and then send the content to a printer through some external mechanism. There was no automation, no retry capability, and no record of what was printed.
+
+- **No automation or audit trail** meant that posting a receipt, shipping an order, or completing an operation required manual steps to print associated documents. There was no visibility into whether documents had been printed, no way to reprint a failed job, and no centralized log of print activity.
+
+The Print Manager replaces all of these with a single integrated system. The crbnos/zpl-print repository is retired entirely. The existing file+/ routes are superseded by the generation task, which produces content and stores it on the print job record. The work center to printer mapping that previously lived in zpl-print's configuration file is now stored in Carbon's database as printer routes, accessible through a settings UI.
+
+### What the Print Manager Provides
+
+- Automatic printing triggered by business events (receipt posting, shipment posting, kanban replenishment, operation completion) with per-event toggle controls
+- A two-task architecture that decouples content generation from printer delivery, enabling independent evolution of each layer
+- A document type registry that defines which document types are generated for each business event, with support for both built-in renderers and external template APIs (BinderyPress)
+- A persistent print job table that serves as both the processing queue and the historical audit trail
+- A Print Manager UI accessible as a top-level module in ERP, with MES linking to the same interface, providing status visibility, output viewing (including visual ZPL preview via Labelary), reprinting, and job management
+- Printer route configuration with cascading overrides: default assignments, location-specific overrides, and work center-specific overrides
+- Template assignment configuration that maps each document type to a printer and optional BinderyPress template
+- Test print capabilities through the settings UI
+
+---
+
+## 2. Architecture
+
+The Print Manager is built on two decoupled Trigger.dev tasks connected by a database table that serves as both the job queue and the audit trail.
+
+### The Two-Task Design
+
+**print-job** is the content generation task. It receives a source document type and identifier, looks up the document type registry to determine which output documents to generate, and then processes each item individually: creates a print job record immediately with `generating` status (so it appears in the Print Manager right away), renders the content for that item (via BinderyPress or built-in renderers), updates the job with the rendered content (transitioning to `queued`), and triggers the delivery task. This per-item streaming approach means the first document starts printing while later documents are still being generated.
+
+**print-job-deliver** is the printer delivery task. It reads a print job record, resolves the current API key from the printer route table, sends the stored content to the physical printer via an HTTP POST, and updates the job status to completed or failed.
+
+### Why They Are Decoupled
+
+The separation of generation from delivery provides several architectural benefits:
+
+**Delivery backend independence.** ProxyBox is the current delivery backend, but the delivery task is the only code aware of how content reaches a physical printer. Replacing ProxyBox with CUPS, PrintNode, direct IPP, or any other print server means modifying only the delivery task. The generation task, the Print Manager UI, and all business event integrations remain untouched.
+
+**Reprints skip generation.** When an operator reprints a job, the stored content is already available on the job record. The system creates a new print job with the same content and triggers only the delivery task. There is no need to re-fetch entity data or re-generate content, which could produce different results if the underlying data has changed.
+
+**Generation backend independence.** The generation task is the single point of content creation. It supports both built-in renderers and the BinderyPress external rendering API. Switching a document type from built-in to BinderyPress rendering requires only assigning a template ID in the settings UI.
+
+### Content Flow
+
+The complete flow from business event to physical printer follows this path:
+
+1. A business event occurs (for example, a receipt is posted)
+2. The action handler checks whether auto-printing is enabled for that event type in company settings
+3. If enabled, the handler triggers the print-job task with the source document type, document identifier, company identifier, user identifier, and optional location and work center identifiers
+4. The generate task reads company settings, determines which document types apply to this source document via the registry, and for each document type resolves the target printer through the cascading override system
+5. For each item to be printed, the generate task creates a print job record with `generating` status (visible in the Print Manager immediately), renders the content, updates the job with the content (transitioning to `queued`), and triggers the print-job-deliver task
+6. The deliver task reads the job, resolves the API key fresh from the printer route table, marks the job as printing, sends the content to the printer endpoint, and updates the status to completed or failed
+
+### Direct Task Triggering
+
+The Print Manager uses direct Trigger.dev task triggering rather than Carbon's PGMQ event system. The event system polls on a one-minute cron interval, which introduces unacceptable latency for printing. An operator who posts a receipt expects printing to start within seconds, not up to a minute later. Direct task triggering provides near-instant execution (typically one to five seconds). This is consistent with how other latency-sensitive operations in Carbon work, including post-transactions, schedule-job, and notify.
+
+---
+
+## 3. Database Schema
+
+The Print Manager adds a permission module, a JSONB settings column, and two new tables through a single migration.
+
+### The Printing Permission Module
+
+The migration adds a "Printing" value to the module enum, which controls Row Level Security policies on both new tables. Permissions are seeded for the Admin and Management employee types with full CRUD access. All existing users receive printing permissions mirrored from their current Settings permissions, so anyone who can manage settings can immediately manage printing.
+
+Four permission keys are used: printing_view, printing_create, printing_update, and printing_delete. These are evaluated by the standard get_companies_with_employee_permission function used across all of Carbon's RLS policies.
+
+### The companySettings.printing Column
+
+The migration adds a `printing` JSONB column to the `companySettings` table. This column stores a `PrintingSettings` object with four top-level fields:
+
+- **autoPrint** contains boolean toggles for each business event: `receiptLabels`, `shipmentLabels`, and `operationLabels`
+- **assignments** maps each document type ID (such as "productLabel" or "kanbanCard") to a `TemplateAssignment` containing a `printerRouteId` and an optional `templateId` (for BinderyPress templates)
+- **locationOverrides** maps location IDs to document type IDs to printer route IDs, providing location-specific printer routing
+- **workCenterOverrides** maps work center IDs to document type IDs to printer route IDs, providing work center-specific printer routing
+
+### The printerRoute Table
+
+The printerRoute table defines printer endpoints, optionally scoped to specific locations. Each row represents one configured printer.
+
+**Key columns:**
+
+- **id** is a text primary key with the "pr" prefix, auto-generated by Carbon's standard id() function
+- **companyId** references the company table and is part of the composite primary key, ensuring tenant isolation
+- **locationId** is an optional reference to the location table. When set, the printer is associated with a specific facility location
+- **name** is a required human-readable name for the printer (such as "Zebra 2x1" or "Shipping Printer")
+- **format** identifies the output format, constrained to "zpl" or "pdf"
+- **mediaSizeId** is an optional text field identifying the physical media size (such as "label2x1" for a two-by-one inch thermal label, "label4x2" for a four-by-two inch). Legacy identifiers "zebra2x1" and "zebra4x2" are also supported. This is used for ZPL generation to determine dimensions
+- **printerUrl** is the full HTTP endpoint URL for the print server (for example, a ProxyBox endpoint)
+- **apiKey** is an optional per-route API key that authenticates requests to the print server
+- **createdAt** and **updatedAt** are timestamp columns for record tracking
+
+**Unique constraints** are enforced through a unique index on `(companyId, COALESCE(locationId, ''), name)`, ensuring printer names are unique within a company and location scope.
+
+**Row Level Security** policies on printerRoute use the Printing permission module for all four operations (SELECT, INSERT, UPDATE, DELETE).
+
+### Printer Route Resolution Logic
+
+When the generation task needs to determine which printer to send a document to, it uses a cascading override system stored in the PrintingSettings JSONB:
+
+1. **Work center override**: If a work center ID is available (from an MES operation), the task checks `workCenterOverrides[workCenterId][documentTypeId]` for a printer route ID
+2. **Location override**: If no work center override exists and a location ID is available, the task checks `locationOverrides[locationId][documentTypeId]` for a printer route ID
+3. **Default assignment**: If neither override exists, the task uses `assignments[documentTypeId].printerRouteId` as the default
+
+Once a printer route ID is resolved through this cascade, the task fetches the full route record by ID from the printerRoute table to obtain the printer URL, format, media size, and other configuration.
+
+This design allows operators at different work centers to have output routed to their nearest printer, while locations can have their own defaults, and a company-wide default serves as the fallback.
+
+### The printJob Table
+
+The printJob table serves a dual purpose. It is the processing queue for active print jobs and the historical audit trail for completed and failed jobs.
+
+**Key columns:**
+
+- **id** uses the "pj" prefix, auto-generated
+- **companyId** is part of the composite primary key
+- **status** is constrained to five values: generating, queued, printing, completed, and failed. The default is `generating`
+- **contentType** is either "zpl" or "pdf", or null while the job is in `generating` status
+- **content** stores the generated content as text, or null while the job is in `generating` status. ZPL content is stored as-is (typically around 500 bytes). PDF content is stored as a base64-encoded string (typically 50 to 300 kilobytes). This is practical for PostgreSQL text columns and avoids the complexity of external file storage for these small payloads
+- **printerUrl** is the resolved printer endpoint URL at the time the job was created. This column is NOT NULL; when no printer route is resolved, an empty string is stored
+- **sourceDocument** identifies the type of business entity that triggered the job (Receipt, Shipment, Kanban, Operation, or Entity)
+- **sourceDocumentId** is the database identifier of that entity
+- **sourceDocumentReadableId** is the human-readable identifier (such as "R-001" for a receipt)
+- **description** is a human-readable summary displayed in the Print Manager UI (such as "R-001 -- ITEM-123 SN-456")
+- **origin** tracks how the job was created: "auto" for business event triggers, "manual" for user-initiated prints, or "reprint" for jobs created from the reprint action
+- **error** stores the error message when a job fails
+- **attempts** tracks how many delivery attempts have been made
+- **createdBy** references the user who triggered the job
+- **createdAt** records when the job was created
+- **updatedAt** and **updatedBy** track the most recent modification
+- **completedAt** records when delivery succeeded
+
+**Indexes** cover the most common query patterns: by company, by company and status, and by company and creation date (descending for most-recent-first listing in the Print Manager UI).
+
+**Row Level Security** policies on printJob also use the Printing permission module.
+
+### Realtime Subscription
+
+The printJob table is added to the Supabase Realtime publication. This enables the Print Manager UI to subscribe to live status updates. When a job transitions from generating to queued to printing to completed (or failed), the UI reflects the change without requiring a page refresh.
+
+---
+
+## 4. Shared Package (@carbon/printing)
+
+The printing system's shared logic lives in a dedicated package at packages/printing, published as @carbon/printing. This package is consumed by the ERP application, the MES application, and the Trigger.dev task package.
+
+### Relationship to @carbon/documents
+
+The `@carbon/documents` package (at packages/documents) is Carbon's established home for PDF and ZPL renderers. It contains React PDF components for invoices, kanban cards, packing slips, purchase orders, quotes, and more, as well as ZPL generators for product labels. The built-in renderers in the print-job generation task use components from `@carbon/documents` to produce content.
+
+`@carbon/printing` does not duplicate rendering logic. It owns the print job queue, delivery infrastructure, printer routing, document type registry, and settings management. When a built-in renderer is needed, the generation task calls into `@carbon/documents` for the actual content generation.
+
+### Why a Shared Package
+
+Three separate consumers need access to the same types, service functions, validators, and delivery logic:
+
+- The ERP application uses service functions in its Print Manager and Settings routes, types for casting printing settings, the document type registry for building assignment UIs, and validators for form handling
+- The MES application uses the same types for its auto-print integration in the operation completion flow
+- The Trigger.dev task package uses service functions for creating and updating print jobs, resolving printer routes, the document type registry for determining which documents to generate, and both the ProxyBox delivery function and the BinderyPress rendering function
+
+Centralizing this logic in a shared package eliminates duplication and ensures that all consumers operate on the same data access patterns, type definitions, and validation rules.
+
+### Module Structure
+
+**types** defines the TypeScript types for the printing system. This includes PrintingSettings (the full settings object with auto-print toggles, template assignments, and override maps), TemplateAssignment (linking a document type to a printer route and optional BinderyPress template), PrinterRoute (a printer configuration record), PrintJob (a print job record), and the union types for job status, origin, and content type.
+
+**registry** defines the document type registry. Each entry is a `DocumentTypeDefinition` with an ID, display name, list of source documents that trigger it, a built-in renderer identifier (or null), a default format, and a description. The current registry contains two entries: "productLabel" (ZPL, triggered by Receipt, Shipment, Operation, and Entity source documents) and "kanbanCard" (PDF, triggered by Kanban source documents). Helper functions provide lookup by ID, lookup by source document, and option list generation for UI selects. See Section 14 for how to add new entries.
+
+**service** provides all database access functions. For print jobs: paginated listing (excluding the content column for performance), single job retrieval, content-only retrieval (used for view and reprint operations), job creation (defaults to `generating` status with null content), content update (sets content and transitions to `queued`), and status updates. For printer routes: listing all routes, fetching a single route by ID, upsert (create or update), and deletion. For printing settings: reading and updating the full PrintingSettings JSONB from the companySettings table.
+
+**models** contains Zod validators for form submissions. The auto-print settings validator handles the four boolean toggle fields. The printer route validator handles route creation and update with fields for name, format, mediaSizeId, locationId, printerUrl, and apiKey. The assignment settings validator is dynamically built from the document type registry, generating `{documentTypeId}_printerRouteId` and `{documentTypeId}_templateId` fields for each registered type. The location override and work center override validators handle adding overrides with locationId/workCenterId, document type, and printer route ID fields. The reprint validator handles the reprint action with an optional printer URL override.
+
+**delivery/proxybox** provides the ProxyBox delivery function. This is the only module aware of the specific HTTP protocol for reaching a ProxyBox print server.
+
+**generation/binderypress** provides the BinderyPress rendering function. It calls the BinderyPress API (`https://api.binderypress.dev/v1/render`) with a template ID, bound data, and output format, and returns the rendered content. For ZPL responses it returns the text directly; for PDF responses it returns a base64-encoded string. This module has a 30-second request timeout.
+
+**index** is the barrel export that re-exports all public symbols from the package, including types, registry functions and types, all service functions, all validators, the ProxyBox delivery function, and the BinderyPress rendering function.
+
+---
+
+## 5. Content Generation
+
+The print-job task is responsible for determining which document types to generate, fetching entity data, generating content (via built-in renderers or BinderyPress), and creating print job records. It runs with a single attempt (no retries), because if the required data is missing from the database, retrying will not make it appear.
+
+### Task Flow
+
+1. **Read company settings** to obtain the PrintingSettings JSONB (which contains assignments, overrides, and the product label size configuration)
+2. **Determine document types** by querying the document type registry for all types triggered by this source document (for example, a "Receipt" source document triggers the "productLabel" document type)
+3. **For each document type**, resolve the target printer through the cascading override system and resolve data using the document-type-specific data resolver
+4. **For each item**, process individually in a streaming fashion:
+ a. **Create a print job** with `generating` status and no content. The job is immediately visible in the Print Manager
+ b. **Render content** by either calling BinderyPress (if a template ID is assigned and the API key is configured) or using the built-in renderer. If rendering fails, the job is marked as `failed` with the error message
+ c. **Update the job** with the rendered content and transition to `queued` status
+ d. **Trigger delivery** if a printer URL is resolved. Jobs without a printer URL (empty string) are marked as completed immediately (the content is stored and available for manual reprinting from the Print Manager)
+
+This per-item approach means the first document starts printing while later documents are still being rendered, rather than waiting for all content to be generated before any delivery begins.
+
+### Document Type Registry
+
+The generation task is driven by the document type registry (`packages/printing/src/registry.ts`), which maps source documents to the output document types that should be generated for them. The registry currently contains two entries:
+
+**productLabel** is triggered by Receipt, Shipment, Operation, and Entity source documents. Its built-in renderer generates ZPL via `@carbon/documents/zpl`. When a BinderyPress template ID is assigned, the task calls the BinderyPress API instead.
+
+**kanbanCard** is triggered by the Kanban source document. Its built-in renderer generates PDF via `@carbon/documents/pdf`. It can also be rendered via BinderyPress when a template is assigned.
+
+Adding a new document type (such as an invoice, packing slip, or routing sheet) requires adding an entry to the registry, implementing a data resolver, and optionally implementing a built-in renderer. All existing infrastructure (route resolution, job creation, delivery, settings UI) works automatically. See Section 14 for a step-by-step example.
+
+### Data Resolvers
+
+Each document type has a registered data resolver function that fetches the relevant entity data from the database.
+
+**resolveTrackedEntityData** serves the productLabel document type. It queries the trackedEntity table filtered by the source document context:
+- For **Receipt** and **Shipment**: queries tracked entities whose matching attribute (Receipt or Shipment) equals the source document ID
+- For **Operation**: looks up the job operation to find its job make method, then queries tracked entities associated with that make method
+- For **Entity**: fetches the single tracked entity by ID
+
+The resolver then enriches the tracked entities by batch-querying the item table for part numbers and revisions, returning a list of data items for rendering.
+
+**resolveKanbanData** serves the kanbanCard document type. It fetches the kanban record from the kanbans view, including item information, location, shelf, supplier, and quantity. If the kanban has a thumbnail image, the task downloads it from Supabase Storage and converts it to a base64 data URI. It also constructs a URL to the ERP kanban API route for additional card data.
+
+### Built-in Renderers
+
+**renderBuiltInProductLabel** generates ZPL content for tracked entity labels. It uses the media size configuration to determine dimensions and generates one ZPL block per item.
+
+**renderBuiltInKanban** generates PDF content using a React PDF component from `@carbon/documents`. It renders a kanban card with the item thumbnail (if available), item details, location, supplier, and quantity information. The PDF stream is converted to a base64-encoded string for storage.
+
+### BinderyPress Integration
+
+When a document type has a template ID assigned in the settings and the `BINDERY_PRESS_API_KEY` environment variable is configured, the generation task calls `renderWithBinderyPress()` instead of the built-in renderer. The BinderyPress API accepts a template ID, the resolved data items, and the desired output format (zpl or pdf), and returns rendered content. This allows document layouts to be designed through the BinderyPress visual designer rather than requiring source code changes.
+
+Carbon provides default BinderyPress templates for each document type:
+
+| Document Type | Template ID | Format | Description |
+|---|---|---|---|
+| Product Label | `carbon:product-label-2x1` | ZPL | 2x1" thermal label for tracked entities |
+| Kanban Card | `carbon:kanban-letter` | PDF | Letter-size kanban replenishment card |
+
+These template IDs are entered in the Template Assignments section of the printing settings. Custom templates can be created in the BinderyPress designer and assigned in place of the defaults.
+
+---
+
+## 6. Printer Delivery
+
+The print-job-deliver task handles the final step: sending generated content to a physical printer through a print server.
+
+### Task Configuration
+
+The delivery task is configured with three maximum attempts, exponential backoff with a factor of two, and randomized retry timing. This provides resilience against transient network issues while avoiding rapid-fire retries that could overwhelm a print server.
+
+### Delivery Flow
+
+1. **Read the print job** record from the database, including its content, content type, printer URL, current status, and attempt count
+2. **Validate content** — if content or contentType is null (which should not happen in normal operation but guards against race conditions), mark the job as `failed` and abort without retrying
+3. **Resolve the API key** fresh from the printerRoute table by matching the printer URL and company identifier. The API key is deliberately not stored on the print job itself. This means that if an administrator rotates the API key on a printer route, the new key takes effect on the very next delivery attempt without needing to update any existing job records
+4. **Mark the job as printing** and increment the attempt counter
+5. **Decode the content** if it is PDF (converting from base64 to a binary buffer). ZPL content is sent as-is since it is plain text
+6. **Send to ProxyBox** using the delivery function, which performs an HTTP POST with the content as the request body, an octet-stream content type, and the API key header if present
+7. **Update the job status** to completed on success (setting completedAt) or to failed on error (storing the error message)
+
+Note: On error, the job is marked as "failed" before the retry decision is made. If the error is retryable, the task re-throws and Trigger.dev will pick it up again, at which point it transitions back to "printing". This means there is a brief window during retries where a job shows as "failed" in the UI before switching back to "printing" on the next attempt.
+
+### The ProxyBox Delivery Backend
+
+The sendToProxyBox function is a straightforward HTTP POST. It sets the Content-Type header to application/octet-stream, optionally includes the X-API-Key header, sends the content as the request body, and enforces a thirty-second timeout using an AbortSignal. If the response status is not successful, it throws an error with the status code and any response body text.
+
+### Retry Strategy
+
+The retry behavior distinguishes between two categories of failure:
+
+**Connection errors** (such as connection refused, DNS resolution failure, or network unreachable) indicate that the content never reached the print server. These errors trigger a retry, because sending the content again is safe.
+
+**Timeout errors** indicate that the HTTP request was sent but the response was not received within the timeout window. In this scenario, the content may have already been received and printed by the print server. Retrying would risk printing duplicate copies. When a timeout is detected (identified by the AbortError name or timeout-related error messages), the task throws an AbortTaskRunError, which tells Trigger.dev to permanently fail the run without retrying.
+
+This is a conservative approach that prevents duplicate prints at the cost of occasionally requiring a manual reprint when a timeout was actually a delivery failure. A future improvement would be to use ProxyBox idempotency keys to make retries safe even after timeouts.
+
+---
+
+## 7. Business Event Integration
+
+Four business events trigger automatic printing. Each integration follows the same pattern: a small block of code inserted into the existing action handler, wrapped in a try/catch that never blocks the parent operation.
+
+### The Integration Pattern
+
+Each auto-print block:
+
+1. Reads the printing settings from companySettings using a service-role Supabase client (bypassing RLS to ensure the query succeeds regardless of the user's permission level)
+2. Checks whether the relevant auto-print toggle is enabled
+3. If enabled, triggers the print-job task with the source document type, document identifier, company and user identifiers, optional location ID, and optional work center ID
+4. Catches any error silently (logging it but not re-throwing), so that a printing failure never prevents the business operation from completing
+
+### Idempotency Keys
+
+Each trigger call includes an idempotency key with a five-minute TTL. The key is constructed from the source document type and identifier (for example, "auto-print-Receipt-abc123"). This prevents duplicate print jobs if the business event is somehow triggered twice within the five-minute window, which could happen from double-clicks, browser refreshes, or retry logic in upstream systems.
+
+### Receipt Posting
+
+The auto-print block is inserted in the receipt posting action after the successful post-receipt edge function call but before the redirect. It uses a nested try/catch that is separate from the outer try/catch. This separation is critical because the outer catch block resets the receipt status back to Draft when an error occurs. If the auto-print try/catch were merged with the outer one, a printing error would incorrectly reset the receipt to Draft even though the posting itself succeeded.
+
+Additionally, the outer catch block must re-throw Response objects. Remix/React Router redirects are thrown as Response objects. Without re-throwing them, the outer catch would swallow the redirect and the user would not be navigated to the receipt page after posting.
+
+The trigger payload includes `locationId` from the receipt record, enabling location-based printer routing.
+
+### Shipment Posting
+
+The shipment posting integration follows the same pattern as receipts: a nested try/catch after the successful post-shipment edge function call, checking the shipmentLabels toggle, with the same outer catch re-throw pattern for Response objects. The trigger payload includes `locationId` from the shipment record.
+
+### Kanban Replenishment
+
+The kanban integration triggers when a kanban order is created, in both the Make (job order) and Buy (purchase order) paths. Both paths pass the kanban's `locationId` in the trigger payload for location-based printer routing. The format determination (PDF for kanban cards) happens inside the generation task via the document type registry, not in the business event handler.
+
+### MES Operation Completion
+
+The MES operation completion flow has two auto-print integration points corresponding to the two tracking types:
+
+**Serial tracking** uses the Entity source document type with the completed entity identifier. An important detail: the MES completion flow creates a new tracked entity (the next serial number to be reserved) and returns its identifier. The auto-print must use the completed entity identifier from the form submission, not the newly created one. Printing a document for the entity that was just completed (and is now in inventory) is correct; printing one for the entity that was just reserved (and has not been manufactured yet) is not.
+
+**Batch tracking** uses the Operation source document type with the job operation identifier. This generates documents for all tracked entities associated with the operation's make method, which is appropriate for batch operations where multiple entities are created at once. The idempotency key for batch operations appends "-batch" to distinguish it from serial-tracking keys for the same operation.
+
+Both MES paths pass the `workCenterId` and `locationId` (resolved from the work center record) in the trigger payload. This enables the full cascading override resolution: work center-specific routing takes precedence over location-specific routing, which takes precedence over the default assignment.
+
+---
+
+## 8. Settings UI
+
+The printing settings page is located in the ERP application under Settings and is accessible to users with settings permissions.
+
+### Auto-Print Toggles
+
+The top section of the settings page displays four boolean toggles, one for each supported business event:
+
+- Print when receipts are posted
+- Print when shipments are posted
+- Print kanban cards when triggered
+- Print when operations complete
+
+These toggles are backed by a validated form using the autoPrintSettingsValidator. When saved, the values are stored in the `autoPrint` field of the PrintingSettings JSONB object on the companySettings table's printing column.
+
+### Printer Management
+
+The printers section displays all configured printer routes as a list of cards. Each card shows the printer name, format (ZPL or PDF), media size (if configured), location scope (if set), the printer URL, and whether an API key is configured (displayed as masked dots for security).
+
+Each route has two actions: Test Print and Delete. A form allows creating new routes by specifying the name, format, media size, location, printer URL, and optional API key. Existing routes can be updated via upsert.
+
+When a printer route is deleted, the action handler performs dangling reference cleanup: it scans the PrintingSettings JSONB for any assignments, location overrides, or work center overrides that reference the deleted route and removes them. This prevents stale references from causing errors in the generation task.
+
+### Template Assignments
+
+The template assignments section maps each document type (from the registry) to a printer route and an optional BinderyPress template ID. For each document type, the UI shows a dropdown to select the target printer and a text field for the template ID. When a template ID is assigned and the BinderyPress API key is configured, the generation task will use BinderyPress rendering instead of the built-in renderer for that document type.
+
+This section is driven entirely by the document type registry. Adding a new entry to the registry automatically adds a row here. The section is backed by the assignmentSettingsValidator, which is dynamically built from the registry.
+
+### Location Overrides
+
+The location overrides section allows configuring location-specific printer routing. Each override maps a location and document type combination to a specific printer route. When a print job is triggered from a business event associated with a particular location, the override takes precedence over the default assignment.
+
+The UI displays existing overrides as a list with delete actions and provides a form to add new overrides by selecting a location, document type, and printer route.
+
+### Work Center Overrides
+
+The work center overrides section allows configuring work center-specific printer routing. Each override maps a work center and document type combination to a specific printer route. Work center overrides take the highest precedence in the cascade: they override both location overrides and default assignments.
+
+This is particularly useful in MES operation completion flows, where the work center ID is available and operators need output printed at the printer nearest their station.
+
+### Test Print
+
+The test print feature generates a real ZPL test page and sends it directly to the configured printer endpoint from the server-side action. The generated output includes the text "Test Print", the media size ID and dimensions (calculated from the configured media size at 203 DPI), and a timestamp. This provides immediate verification that the printer route is correctly configured and the printer is reachable.
+
+Test print is only supported for ZPL-format printers that have a media size configured. PDF-format printers cannot be trivially tested from the settings action. The UI surfaces a message suggesting that document printers can be tested by triggering a kanban print.
+
+The test print looks up the route's URL and API key server-side using the route identifier, rather than accepting sensitive values like the API key from the form. This prevents API keys from being exposed in client-side form data.
+
+### Loader Data
+
+The settings loader fetches company settings, printer routes, work centers, and locations. Work centers and locations are needed to populate the override form dropdowns.
+
+---
+
+## 9. Print Manager UI
+
+### ERP Print Manager
+
+The Print Manager is a top-level module in the ERP application, accessible from the sidebar navigation. It is not nested under Settings because operators on the shop floor need quick, direct access to view and manage their print jobs.
+
+**Loader.** The route requires printing_view permission (expressed as `{ view: "printing" }` in the permission check). It fetches a paginated list of print jobs (excluding the content column for performance, with a limit of 50) and the list of printer routes. The job list supports filtering by status via URL search parameters.
+
+**Action.** The route supports three intents:
+
+- **reprint** fetches the original job's content and source document metadata, creates a new print job with origin set to "reprint" and the same content, and triggers the delivery task. The printer URL defaults to the original job's printer but can be overridden via a form field.
+- **delete** performs a hard delete of a print job record.
+- **viewContent** fetches only the content column for a specific job and returns it in the action response data, which the component uses to display the output.
+
+**Table.** The Print Manager displays jobs in a table with columns for status, description, source document type, content type (ZPL or PDF), origin (auto, manual, or reprint), creation timestamp, and actions.
+
+**Status badges** use color coding: purple for generating, yellow for queued, blue for printing, green for completed, and red for failed. Failed jobs also display their error message below the description.
+
+**View Output** loads the job's content via the viewContent action and displays it in a panel. ZPL content is rendered as a visual preview using the Labelary API: the component parses `^PW` (width) and `^LL` (height) commands from the ZPL to determine dimensions in dots, converts to inches at 203 DPI (8 dpmm), and fetches a rendered PNG from `api.labelary.com`. The raw ZPL source is also displayed below the preview image. If the Labelary request fails, only the raw ZPL text is shown. PDF content is rendered in an iframe using a base64 data URI.
+
+**Reprint** creates a new job from the stored content and triggers delivery. This does not re-generate the document -- it sends the exact same content that was generated originally. The View and Reprint buttons are disabled for jobs in `generating` status, since no content exists yet.
+
+**Status filtering** is available through a dropdown that filters the job list by status (generating, queued, printing, completed, failed, or all).
+
+### MES Print Manager Access
+
+The MES application does not have its own Print Manager route. Instead, its sidebar includes a Print Manager link that navigates to the ERP Print Manager at `${ERP_URL}/x/print-manager`. This provides MES operators with access to the same print job visibility and management tools through a single, shared interface.
+
+### Realtime Updates
+
+The Print Manager component subscribes to Supabase Realtime on the printJob table. When a job's status changes (for example, from generating to queued to printing to completed), the table updates automatically without requiring a page refresh. This gives operators live feedback on whether their documents have been printed.
+
+---
+
+## 10. Print Job Lifecycle
+
+### Status Progression
+
+A print job moves through the following statuses:
+
+**Generating** is the initial status for auto-generated jobs. The job record has been created with a description and printer URL but no content yet. The content is being rendered (via BinderyPress or a built-in renderer). The job is visible in the Print Manager with a purple badge, but the View and Reprint actions are disabled. If rendering fails, the job transitions directly to `failed` with an error message.
+
+**Queued** means content has been rendered and stored on the job. The delivery task has been triggered and the job is waiting to be picked up. In practice, jobs spend very little time in this status because the delivery task is chained immediately after content is set. Reprinted jobs start directly in `queued` status since they already carry the original content.
+
+**Printing** indicates that the delivery task has started processing the job. The task has read the job, resolved the API key, and is about to send (or is in the process of sending) the content to the print server. The attempt counter is incremented at this point.
+
+**Completed** means the content was successfully delivered to the print server, which responded with a success status. The completedAt timestamp is set, and any previous error message is cleared.
+
+**Failed** means the delivery attempt encountered an error. The error message is stored on the job. If the error was a connection-type failure, the Trigger.dev retry mechanism may attempt delivery again (up to three attempts total). Note that the job is marked as "failed" before the retry decision, so there is a brief window where a retrying job shows as "failed" in the UI before transitioning back to "printing" on the next attempt. If all retries are exhausted or the error was a timeout (which aborts retries), the job remains in failed status.
+
+### No-Route Jobs
+
+When the generation task cannot resolve a printer URL (no matching assignment or override exists for the required document type), it creates the job with an empty string as the printer URL and immediately marks it as completed. The content is stored and available for manual reprinting through the Print Manager. This ensures that jobs are never lost even when printer infrastructure is not yet configured.
+
+### Reprints
+
+When an operator triggers a reprint from the Print Manager, a new print job is created with:
+
+- The same content, content type, source document type, source document identifier, readable identifier, and description as the original job
+- Status set to `queued` (skipping `generating` since the content already exists)
+- Origin set to "reprint" to distinguish it from auto-generated jobs in the audit trail
+- The operator's user identifier as the creator
+- The printer URL from the original job (or an overridden URL if specified)
+
+The new job then follows the normal lifecycle from `queued`: the delivery task is triggered, and the job progresses through printing and completed or failed. The original job is not modified.
+
+This approach preserves the complete source document context on reprinted jobs, which means the Print Manager's source document column and description remain meaningful even for reprints.
+
+---
+
+## 11. Cleanup
+
+Print job records accumulate over time and need periodic pruning. The cleanup logic is integrated into Carbon's existing scheduled cleanup task, which runs on a cron schedule.
+
+The cleanup applies two retention rules:
+
+- **Completed jobs older than 30 days** are deleted. These jobs have served their purpose -- the documents were printed successfully and the audit record has been available for a month.
+- **Failed jobs older than 90 days** are deleted. Failed jobs are retained longer because they may be useful for diagnosing recurring printer issues or configuration problems.
+
+Both deletions are executed as parallel database operations filtering by status and the relevant timestamp column (completedAt for completed jobs, createdAt for failed jobs). Errors from either operation are logged but do not interrupt the rest of the cleanup task.
+
+Jobs in queued or printing status are never cleaned up, regardless of age. A job stuck in one of these statuses for an extended period indicates a problem that should be investigated, not silently removed.
+
+---
+
+## 12. Content Generation: Built-in Renderers, file+/ Routes, and BinderyPress
+
+Carbon currently has three ways to generate printed or printable content. Understanding how they relate -- and where they are headed -- is important context for working on the printing system.
+
+### @carbon/documents (built-in renderers)
+
+The `@carbon/documents` package (`packages/documents/`) contains React PDF components and ZPL generators. These include `SalesInvoicePDF`, `QuotePDF`, `PurchaseOrderPDF`, `PackingSlipPDF`, `KanbanLabelPDF`, `ProductLabelZPL`, and others. They are hardcoded React templates that accept data props and produce rendered output.
+
+Within the Print Manager, the built-in renderers in the print-job generation task use these components to produce content when no BinderyPress template is assigned. They exist so the printing system works out of the box without requiring a BinderyPress account. Once a BinderyPress template ID is assigned to a document type in settings, the built-in renderer for that type becomes unused -- the generation task calls BinderyPress instead.
+
+Outside of printing, `@carbon/documents` is also used for email templates (user invitations, verification emails), PDF attachments sent with business transactions (sales order confirmations, purchase order emails to suppliers), and the `file+/` download routes described below.
+
+### file+/ routes (legacy download approach)
+
+The `file+/` routes in the ERP and MES applications (such as `file+/sales-invoice+/$id[.]pdf.tsx`, `file+/receipt+/$id.labels[.]zpl.tsx`) are the old approach to printing. They render content on demand using `@carbon/documents` components and serve it as a downloadable file. Operators had to navigate to these routes, download the file, and manually send it to a printer.
+
+The Print Manager supersedes these routes for printing purposes. The `file+/` routes may still be useful as a direct-download or preview mechanism, but for actual printing they are replaced by the generation task, which creates print jobs and delivers content to printers automatically.
+
+### BinderyPress (target generation backend)
+
+BinderyPress is an external label and document design API that accepts a template ID, bound data, and output format, and returns rendered content (ZPL or PDF). The Print Manager already integrates with it: when a document type has a template ID assigned and the `BINDERY_PRESS_API_KEY` environment variable is set, the generation task calls `renderWithBinderyPress()` instead of the built-in renderer.
+
+BinderyPress is the intended long-term replacement for all of Carbon's hardcoded React templates -- not just for printing. Any place in the system that generates a document from data could use BinderyPress instead of a `@carbon/documents` component:
+
+- **Print Manager document types** (product labels, kanban cards, invoices, etc.) -- already supported via template assignments in settings
+- **PDF attachments on business transactions** (sales order confirmations emailed to customers, purchase orders emailed to suppliers) -- could call BinderyPress to render the PDF instead of the React component
+- **Email templates** (invitation emails, verification emails) -- could be designed in BinderyPress rather than maintained as React email components
+- **file+/ download routes** -- could be converted to call BinderyPress for on-demand rendering
+
+This would give Carbon users the ability to customize the layout and branding of all generated documents through a visual designer, without requiring source code changes. The React templates in `@carbon/documents` would remain as fallbacks for environments without a BinderyPress account.
+
+---
+
+## 13. Future Considerations
+
+### ProxyBox Idempotency Keys
+
+The current delivery task uses an AbortTaskRunError to prevent retrying after timeouts, because a timeout may mean the content was already delivered and printed. This is conservative but occasionally requires a manual reprint when a timeout was genuinely a delivery failure. ProxyBox could support an idempotency key header that allows the print server to deduplicate requests. With this in place, the delivery task could safely retry after timeouts, because the print server would recognize and discard the duplicate request. This would eliminate the need for the timeout-specific abort logic.
+
+### Work Center Filtering in the Print Manager
+
+The Print Manager currently shows all print jobs for the company. In a large manufacturing facility with many work centers and printers, it would be useful to filter jobs by work center or location, showing operators only the jobs relevant to their station. This would require storing the work center or location identifier on the print job record (they are currently only used during printer route resolution and not persisted on the job).
+
+### Additional Delivery Backends
+
+The delivery architecture is designed for multiple backends. The current ProxyBox integration is one module under the delivery directory in the printing package. Additional backends could include:
+
+- **CUPS** for direct printing to network printers on Linux-based systems without a ProxyBox device
+- **PrintNode** as a cloud-hosted print relay service
+- **Direct IPP** for printers that expose an Internet Printing Protocol endpoint on the local network
+
+Each backend would be implemented as a sibling module in the delivery directory, and the delivery task would select the appropriate backend based on the printer route configuration.
+
+---
+
+## 14. Adding a New Document Type
+
+This section walks through adding a new printable document type to the Print Manager, using a sales invoice as the example. The system is designed so that most infrastructure (settings UI, route resolution, delivery, Print Manager) works automatically once a registry entry exists.
+
+### Step 1: Add a registry entry
+
+In `packages/printing/src/registry.ts`, add an entry to the `documentTypeRegistry` array:
+
+```typescript
+{
+ id: "salesInvoice",
+ displayName: "Sales Invoice",
+ sourceDocuments: ["SalesInvoice"],
+ builtInRenderer: "pdf" as const,
+ defaultFormat: "pdf" as const,
+ description: "Invoices for completed sales orders"
+}
+```
+
+The fields mean:
+
+- **id** is the key used in PrintingSettings assignments and overrides. It must be unique across the registry.
+- **displayName** is what appears in the Settings UI (Template Assignments, Location Overrides, Work Center Overrides dropdowns).
+- **sourceDocuments** lists which source document values trigger this document type. When the print-job task receives `sourceDocument: "SalesInvoice"`, it queries the registry and finds this entry. A document type can be triggered by multiple source documents (productLabel is triggered by Receipt, Shipment, Operation, and Entity).
+- **builtInRenderer** is `"zpl"`, `"pdf"`, or `null`. This tells the generation task which built-in rendering path to use when no BinderyPress template is assigned. Set to `null` if there is no built-in renderer (BinderyPress-only).
+- **defaultFormat** is used when no printer route is resolved (for example, for no-route jobs). It determines the contentType stored on the print job.
+
+Once this entry exists, the Settings UI automatically shows "Sales Invoice" in the Template Assignments section and in the Location/Work Center Override dropdowns. No UI changes needed.
+
+### Step 2: Add a data resolver
+
+In `packages/jobs/trigger/print-job.tsx`, add a resolver function and register it in the resolver map.
+
+The resolver receives the Supabase client and the source document ID, and returns a `ResolvedData` object: an array of items (the data that will be passed to the renderer) and an optional human-readable ID for the source document.
+
+For a sales invoice, the resolver would query the sales invoice table for the invoice details (customer, line items, totals, etc.) and return them as the items array. The readable ID would be the invoice number (e.g., "INV-001").
+
+Register it in the resolver map keyed by the document type ID:
+
+```typescript
+const resolvers: Record<string, ResolverFn> = {
+ productLabel: resolveTrackedEntityData,
+ kanbanCard: resolveKanbanData,
+ salesInvoice: resolveInvoiceData, // new
+};
+```
+
+### Step 3: Add a built-in renderer (optional)
+
+If `builtInRenderer` is set to `"pdf"` or `"zpl"`, the generation task needs a corresponding render function. For a PDF invoice, this would use a React PDF component from `@carbon/documents` (e.g., the existing `SalesInvoicePDF` component at `packages/documents/src/pdf/SalesInvoicePDF.tsx`).
+
+The render function receives the resolved data items and returns an array of `GeneratedContent` objects, each containing:
+- `content`: the rendered output (ZPL string or base64-encoded PDF)
+- `contentType`: `"zpl"` or `"pdf"`
+- `description`: human-readable text shown in the Print Manager (e.g., "INV-001 -- Acme Corp")
+- `sourceDocumentReadableId`: the human-readable ID (e.g., "INV-001")
+
+For document types that produce a single output per source document (like an invoice), the array will have one element. For types that produce multiple outputs (like productLabel, which creates one per tracked entity), the array will have many.
+
+If `builtInRenderer` is `null`, the generation task will only use BinderyPress rendering for this document type. A template ID must be assigned in settings for it to produce output.
+
+### Step 4: Add a trigger point
+
+There are two ways to trigger printing for the new document type:
+
+**Auto-print (business event trigger):** Add an auto-print block in the relevant action handler, following the pattern in Section 7. This requires adding a new toggle to the `autoPrint` settings (update the `PrintingSettings` type, the `autoPrintSettingsValidator`, and the Settings UI toggle list).
+
+**Manual print (button on a form):** Add a "Print" button to the document's UI route. In the action handler, trigger the print-job task directly:
+
+```typescript
+await tasks.trigger("print-job", {
+ sourceDocument: "SalesInvoice",
+ sourceDocumentId: invoiceId,
+ companyId,
+ userId,
+ locationId: invoice.locationId ?? undefined,
+});
+```
+
+Both approaches can coexist -- a document type can have auto-print on a business event and a manual print button on its form.
+
+### What works automatically
+
+Once the registry entry and resolver exist, the following require zero additional code:
+
+- **Settings UI:** The document type appears in Template Assignments, Location Overrides, and Work Center Overrides
+- **Printer route resolution:** The cascading override system resolves the printer for the new type using the same logic as all other types
+- **Print job creation and delivery:** Jobs are created and delivered through the same pipeline
+- **Print Manager UI:** Jobs appear in the table with the correct source document context
+- **Reprints:** Operators can reprint the document from the Print Manager
+- **Cleanup:** Old jobs are pruned on the same schedule as all other types
diff --git a/packages/printing/src/assignments.ts b/packages/printing/src/assignments.ts
new file mode 100644
index 0000000000..2d247b8b58
--- /dev/null
+++ b/packages/printing/src/assignments.ts
@@ -0,0 +1,120 @@
+import type {
+ ContextAssignment,
+ LocationAssignment,
+ PrintingSettings
+} from "./types";
+
+export const printerContexts = [
+ "default",
+ "shipping",
+ "receiving",
+ "inventory",
+ "workCenter"
+] as const;
+
+export type PrinterContext = (typeof printerContexts)[number];
+
+const sourceDocumentContexts: Record<string, PrinterContext> = {
+ Shipment: "shipping",
+ Receipt: "receiving",
+ StockTransfer: "inventory",
+ StorageUnit: "inventory"
+};
+
+/**
+ * Maps a print job's source document to the printer context whose
+ * assignment should be used.
+ */
+export function getPrinterContextForSource(
+ sourceDocument: string,
+ workCenterId?: string
+): PrinterContext {
+ return (
+ sourceDocumentContexts[sourceDocument] ??
+ (workCenterId ? "workCenter" : "default")
+ );
+}
+
+/**
+ * Resolves the effective printer assignment for a context within a location.
+ *
+ * - "default" returns the location default.
+ * - "workCenter" with no explicit entry inherits the location default outright.
+ * - Other contexts fall back to the location's default printer when they have
+ * no printer of their own, but keep their own autoPrint flag.
+ */
+export function resolveContextAssignment(
+ assignment: LocationAssignment,
+ context: PrinterContext,
+ workCenterId?: string
+): ContextAssignment {
+ const fallback: ContextAssignment = {
+ printerRouteId: assignment.defaultPrinterRouteId ?? null,
+ autoPrint: assignment.defaultAutoPrint ?? true
+ };
+
+ if (context === "default") return fallback;
+
+ const explicit =
+ context === "workCenter"
+ ? workCenterId
+ ? assignment.workCenters?.[workCenterId]
+ : undefined
+ : assignment[context];
+
+ if (context === "workCenter" && !explicit) return fallback;
+
+ return {
+ printerRouteId: explicit?.printerRouteId ?? fallback.printerRouteId,
+ autoPrint: explicit?.autoPrint ?? true
+ };
+}
+
+export function emptyLocationAssignment(): LocationAssignment {
+ return {
+ defaultPrinterRouteId: null,
+ defaultAutoPrint: true,
+ shipping: { printerRouteId: null, autoPrint: true },
+ receiving: { printerRouteId: null, autoPrint: true },
+ inventory: { printerRouteId: null, autoPrint: true },
+ workCenters: {}
+ };
+}
+
+/**
+ * Returns a copy of the settings with one context assignment replaced.
+ */
+export function setContextAssignment(
+ settings: PrintingSettings,
+ locationId: string,
+ context: PrinterContext,
+ value: ContextAssignment,
+ workCenterId?: string
+): PrintingSettings {
+ const assignment: LocationAssignment = settings.assignments[locationId]
+ ? { ...settings.assignments[locationId] }
+ : emptyLocationAssignment();
+
+ switch (context) {
+ case "default":
+ assignment.defaultPrinterRouteId = value.printerRouteId;
+ assignment.defaultAutoPrint = value.autoPrint;
+ break;
+ case "workCenter":
+ if (!workCenterId) {
+ throw new Error("workCenterId is required for workCenter assignments");
+ }
+ assignment.workCenters = {
+ ...assignment.workCenters,
+ [workCenterId]: value
+ };
+ break;
+ default:
+ assignment[context] = value;
+ }
+
+ return {
+ ...settings,
+ assignments: { ...settings.assignments, [locationId]: assignment }
+ };
+}
diff --git a/packages/printing/src/cache.server.ts b/packages/printing/src/cache.server.ts
new file mode 100644
index 0000000000..c0ee11de91
--- /dev/null
+++ b/packages/printing/src/cache.server.ts
@@ -0,0 +1,143 @@
+import type { Database } from "@carbon/database";
+import { redis } from "@carbon/kv";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type { PrinterContext } from "./assignments";
+import { resolveContextAssignment } from "./assignments";
+import type { PrintingSettings } from "./types";
+
+const CACHE_TTL_SECONDS = 3600;
+const KEY_PREFIX = "printing";
+
+export type CachedPrinterConfig = {
+ printerRouteId: string | null;
+ printerUrl: string;
+ format: "zpl" | "pdf";
+ mediaSizeId: string | null;
+ templateId: string | null;
+ autoPrint: boolean;
+};
+
+function buildCacheKey(
+ companyId: string,
+ locationId: string,
+ context: PrinterContext,
+ contextId?: string
+): string {
+ const suffix =
+ context === "workCenter" && contextId ? `wc:${contextId}` : context;
+ return `${KEY_PREFIX}:${companyId}:${locationId}:${suffix}`;
+}
+
+export async function getCachedPrinterConfig(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ locationId: string,
+ context: PrinterContext,
+ contextId?: string
+): Promise<CachedPrinterConfig | null> {
+ const key = buildCacheKey(companyId, locationId, context, contextId);
+
+ try {
+ const cached = await redis.get(key);
+ if (cached && typeof cached === "string") {
+ return JSON.parse(cached) as CachedPrinterConfig;
+ }
+ } catch {
+ // Redis unavailable — fall through to DB
+ }
+
+ const config = await resolvePrinterConfig(
+ client,
+ companyId,
+ locationId,
+ context,
+ contextId
+ );
+
+ if (config) {
+ try {
+ await redis.set(key, JSON.stringify(config), "EX", CACHE_TTL_SECONDS);
+ } catch {
+ // Cache write failed — non-fatal
+ }
+ }
+
+ return config;
+}
+
+async function resolvePrinterConfig(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ locationId: string,
+ context: PrinterContext,
+ contextId?: string
+): Promise<CachedPrinterConfig | null> {
+ const { data: settings } = await client
+ .from("companySettings")
+ .select("printing")
+ .eq("id", companyId)
+ .single();
+
+ const printing = settings?.printing as PrintingSettings | null;
+ const assignment = printing?.assignments?.[locationId];
+ if (!assignment) return null;
+
+ const { printerRouteId, autoPrint } = resolveContextAssignment(
+ assignment,
+ context,
+ contextId
+ );
+
+ if (!printerRouteId) {
+ return {
+ printerRouteId: null,
+ printerUrl: "",
+ format: "zpl",
+ mediaSizeId: null,
+ templateId: null,
+ autoPrint
+ };
+ }
+
+ const { data: route } = await client
+ .from("printerRoute")
+ .select("id, format, mediaSizeId, printerUrl, apiKey, templateId")
+ .eq("id", printerRouteId)
+ .eq("companyId", companyId)
+ .single();
+
+ if (!route) {
+ return {
+ printerRouteId,
+ printerUrl: "",
+ format: "zpl",
+ mediaSizeId: null,
+ templateId: null,
+ autoPrint
+ };
+ }
+
+ return {
+ printerRouteId: route.id,
+ printerUrl: route.printerUrl,
+ format: route.format as "zpl" | "pdf",
+ mediaSizeId: route.mediaSizeId,
+ templateId: route.templateId,
+ autoPrint
+ };
+}
+
+export async function invalidatePrinterCache(companyId: string): Promise<void> {
+ try {
+ const keys = await redis.keys(`${KEY_PREFIX}:${companyId}:*`);
+ if (keys.length > 0) {
+ const pipeline = redis.pipeline();
+ for (const key of keys) {
+ pipeline.del(key);
+ }
+ await pipeline.exec();
+ }
+ } catch {
+ // Cache invalidation failed — entries will expire via TTL
+ }
+}
diff --git a/packages/printing/src/delivery/proxybox.ts b/packages/printing/src/delivery/proxybox.ts
new file mode 100644
index 0000000000..da4642f9e0
--- /dev/null
+++ b/packages/printing/src/delivery/proxybox.ts
@@ -0,0 +1,35 @@
+export async function sendToProxyBox({
+ url,
+ apiKey,
+ content
+}: {
+ url: string;
+ apiKey?: string | null;
+ content: string | Buffer;
+}) {
+ const headers: Record<string, string> = {
+ "Content-Type": "application/octet-stream"
+ };
+
+ if (apiKey) {
+ headers["X-API-Key"] = apiKey;
+ }
+
+ const body = typeof content === "string" ? content : new Uint8Array(content);
+
+ const response = await fetch(url, {
+ method: "POST",
+ headers,
+ body,
+ signal: AbortSignal.timeout(30_000)
+ });
+
+ if (!response.ok) {
+ const text = await response.text().catch(() => "");
+ throw new Error(
+ `ProxyBox delivery failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ""}`
+ );
+ }
+
+ return { success: true };
+}
diff --git a/packages/printing/src/generation/binderypress.ts b/packages/printing/src/generation/binderypress.ts
new file mode 100644
index 0000000000..adf4bd0e6c
--- /dev/null
+++ b/packages/printing/src/generation/binderypress.ts
@@ -0,0 +1,51 @@
+type RenderFormat = "zpl" | "pdf";
+
+type RenderRequest = {
+ apiKey: string;
+ templateId: string;
+ data: Record<string, unknown>;
+ format: RenderFormat;
+};
+
+type RenderResponse = {
+ content: string;
+ contentType: "zpl" | "pdf";
+};
+
+export async function renderWithBinderyPress({
+ apiKey,
+ templateId,
+ data,
+ format
+}: RenderRequest): Promise<RenderResponse> {
+ const response = await fetch("https://api.binderypress.dev/v1/render", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${apiKey}`
+ },
+ body: JSON.stringify({
+ templateId,
+ data,
+ format,
+ delivery: "inline"
+ }),
+ signal: AbortSignal.timeout(30_000)
+ });
+
+ if (!response.ok) {
+ const body = await response.text().catch(() => "");
+ throw new Error(
+ `BinderyPress render failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ""}`
+ );
+ }
+
+ if (format === "zpl") {
+ const text = await response.text();
+ return { content: text, contentType: "zpl" };
+ }
+
+ // PDF/PNG come back as binary
+ const buffer = Buffer.from(await response.arrayBuffer());
+ return { content: buffer.toString("base64"), contentType: "pdf" };
+}
diff --git a/packages/printing/src/index.ts b/packages/printing/src/index.ts
new file mode 100644
index 0000000000..8e61b195ca
--- /dev/null
+++ b/packages/printing/src/index.ts
@@ -0,0 +1,50 @@
+export type { PrinterContext } from "./assignments";
+export {
+ emptyLocationAssignment,
+ getPrinterContextForSource,
+ printerContexts,
+ resolveContextAssignment,
+ setContextAssignment
+} from "./assignments";
+export {
+ manualPrintValidator,
+ printerRouteValidator,
+ reprintValidator,
+ updateAssignmentValidator
+} from "./models";
+export type {
+ DocumentTypeDefinition,
+ DocumentTypeId,
+ SourceDocument
+} from "./registry";
+export {
+ documentTypeRegistry,
+ getDocumentType,
+ getDocumentTypeOptions,
+ getDocumentTypesForSource
+} from "./registry";
+
+export {
+ createPrintJob,
+ deletePrinterRoute,
+ getPrinterRoute,
+ getPrinterRoutes,
+ getPrintingSettings,
+ getPrintJob,
+ getPrintJobContent,
+ getPrintJobs,
+ updatePrintingSettings,
+ updatePrintJobContent,
+ updatePrintJobStatus,
+ upsertPrinterRoute
+} from "./service";
+export type {
+ ContextAssignment,
+ LocationAssignment,
+ PrinterRoute,
+ PrintingSettings,
+ PrintJob,
+ PrintJobContentType,
+ PrintJobOrigin,
+ PrintJobStatus
+} from "./types";
diff --git a/packages/printing/src/models.ts b/packages/printing/src/models.ts
new file mode 100644
index 0000000000..c25f80ff4f
--- /dev/null
+++ b/packages/printing/src/models.ts
@@ -0,0 +1,40 @@
+import { z } from "zod";
+import { zfd } from "zod-form-data";
+import { printerContexts } from "./assignments";
+
+export const manualPrintValidator = z.object({
+ sourceDocument: z.string().min(1),
+ sourceDocumentId: z.string().min(1),
+ locationId: z.string().optional(),
+ workCenterId: z.string().optional(),
+ printerRouteId: z.string().optional()
+});
+
+export const printerRouteValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ locationId: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ format: z.enum(["zpl", "pdf"]),
+ mediaSizeId: z.string().min(1, { message: "Media size is required" }),
+ printerUrl: z.string().url({ message: "Must be a valid URL" }),
+ apiKey: zfd.text(z.string().optional()),
+ templateId: zfd.text(z.string().optional())
+});
+
+export const updateAssignmentValidator = z
+ .object({
+ locationId: z.string().min(1),
+ context: z.enum(printerContexts),
+ contextId: zfd.text(z.string().optional()),
+ printerRouteId: zfd.text(z.string().optional()),
+ autoPrint: zfd.checkbox()
+ })
+ .refine((data) => data.context !== "workCenter" || !!data.contextId, {
+ message: "contextId is required for workCenter assignments",
+ path: ["contextId"]
+ });
+
+export const reprintValidator = z.object({
+ printJobId: z.string().min(1, { message: "Print job ID is required" }),
+ printerUrl: zfd.text(z.string().optional())
+});
diff --git a/packages/printing/src/printing.server.ts b/packages/printing/src/printing.server.ts
new file mode 100644
index 0000000000..9b15c4876c
--- /dev/null
+++ b/packages/printing/src/printing.server.ts
@@ -0,0 +1,7 @@
+export type { CachedPrinterConfig } from "./cache.server";
+export {
+ getCachedPrinterConfig,
+ invalidatePrinterCache
+} from "./cache.server";
+export { sendToProxyBox } from "./delivery/proxybox";
+export { renderWithBinderyPress } from "./generation/binderypress";
diff --git a/packages/printing/src/registry.ts b/packages/printing/src/registry.ts
new file mode 100644
index 0000000000..f8ac61365f
--- /dev/null
+++ b/packages/printing/src/registry.ts
@@ -0,0 +1,73 @@
+export type DocumentTypeDefinition = {
+ id: string;
+ displayName: string;
+ sourceDocuments: string[];
+ builtInRenderer: "zpl" | "pdf" | null;
+ defaultFormat: "zpl" | "pdf";
+ description: string;
+};
+
+export const documentTypeRegistry = [
+ {
+ id: "productLabel",
+ displayName: "Product Label",
+ sourceDocuments: [
+ "Receipt",
+ "Shipment",
+ "Operation",
+ "Entity",
+ "Job",
+ "Split",
+ "StockTransfer"
+ ],
+ builtInRenderer: "zpl" as const,
+ defaultFormat: "zpl" as const,
+ description: "Labels for tracked entities (serial/batch numbers)"
+ },
+ {
+ id: "kanbanCard",
+ displayName: "Kanban Card",
+ sourceDocuments: ["Kanban"],
+ builtInRenderer: "pdf" as const,
+ defaultFormat: "pdf" as const,
+ description: "Replenishment cards for kanban bins"
+ },
+ {
+ id: "storageUnitLabel",
+ displayName: "Storage Unit Label",
+ sourceDocuments: ["StorageUnit"],
+ builtInRenderer: "zpl" as const,
+ defaultFormat: "zpl" as const,
+ description: "Labels for shelves, bins, and storage locations"
+ }
+] as const satisfies readonly DocumentTypeDefinition[];
+
+export type DocumentTypeId = (typeof documentTypeRegistry)[number]["id"];
+export type SourceDocument =
+ (typeof documentTypeRegistry)[number]["sourceDocuments"][number];
+
+export function getDocumentTypesForSource(
+ sourceDocument: string
+): DocumentTypeId[] {
+ return documentTypeRegistry
+ .filter((dt) =>
+ (dt.sourceDocuments as readonly string[]).includes(sourceDocument)
+ )
+ .map((dt) => dt.id) as DocumentTypeId[];
+}
+
+export function getDocumentType(
+ id: string
+): DocumentTypeDefinition | undefined {
+ return documentTypeRegistry.find((dt) => dt.id === id);
+}
+
+export function getDocumentTypeOptions(): {
+ value: string;
+ label: string;
+}[] {
+ return documentTypeRegistry.map((dt) => ({
+ value: dt.id,
+ label: dt.displayName
+ }));
+}
diff --git a/packages/printing/src/service.ts b/packages/printing/src/service.ts
new file mode 100644
index 0000000000..8673c05ff5
--- /dev/null
+++ b/packages/printing/src/service.ts
@@ -0,0 +1,289 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type {
+ PrinterRoute,
+ PrintingSettings,
+ PrintJobContentType,
+ PrintJobOrigin,
+ PrintJobStatus
+} from "./types";
+
+// -- Print Jobs --
+
+export async function getPrintJobs(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: {
+ status?: string;
+ origin?: string;
+ sourceDocument?: string;
+ contentType?: string;
+ search?: string | null;
+ limit?: number;
+ offset?: number;
+ }
+) {
+ let query = client
+ .from("printJob")
+ .select(
+ "id, companyId, status, contentType, printerUrl, sourceDocument, sourceDocumentId, sourceDocumentReadableId, description, origin, error, attempts, createdBy, createdAt, updatedAt, updatedBy, completedAt",
+ { count: "exact" }
+ )
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: false });
+
+ if (args?.status) {
+ query = query.eq("status", args.status);
+ }
+
+ if (args?.origin) {
+ query = query.eq("origin", args.origin);
+ }
+
+ if (args?.sourceDocument) {
+ query = query.eq("sourceDocument", args.sourceDocument);
+ }
+
+ if (args?.contentType) {
+ query = query.eq("contentType", args.contentType);
+ }
+
+ if (args?.search) {
+ query = query.or(
+ `description.ilike.%${args.search}%,sourceDocumentReadableId.ilike.%${args.search}%`
+ );
+ }
+
+ const limit = args?.limit ?? 100;
+ const offset = args?.offset ?? 0;
+ query = query.range(offset, offset + limit - 1);
+
+ return query;
+}
+
+export async function getPrintJob(
+ client: SupabaseClient<Database>,
+ printJobId: string,
+ companyId: string
+) {
+ return client
+ .from("printJob")
+ .select(
+ "id, companyId, status, contentType, printerUrl, sourceDocument, sourceDocumentId, sourceDocumentReadableId, description, origin, error, attempts, createdBy, createdAt, updatedAt, updatedBy, completedAt"
+ )
+ .eq("id", printJobId)
+ .eq("companyId", companyId)
+ .single();
+}
+
+export async function getPrintJobContent(
+ client: SupabaseClient<Database>,
+ printJobId: string,
+ companyId: string
+) {
+ return client
+ .from("printJob")
+ .select("id, content, contentType")
+ .eq("id", printJobId)
+ .eq("companyId", companyId)
+ .single();
+}
+
+export async function createPrintJob(
+ client: SupabaseClient<Database>,
+ job: {
+ companyId: string;
+ contentType?: PrintJobContentType;
+ content?: string;
+ printerUrl: string;
+ sourceDocument: string;
+ sourceDocumentId: string;
+ sourceDocumentReadableId?: string;
+ description: string;
+ status?: PrintJobStatus;
+ origin?: PrintJobOrigin;
+ createdBy: string;
+ }
+) {
+ return client
+ .from("printJob")
+ .insert({
+ companyId: job.companyId,
+ contentType: job.contentType ?? null,
+ content: job.content ?? null,
+ printerUrl: job.printerUrl,
+ sourceDocument: job.sourceDocument,
+ sourceDocumentId: job.sourceDocumentId,
+ sourceDocumentReadableId: job.sourceDocumentReadableId,
+ description: job.description,
+ status: job.status ?? "generating",
+ origin: job.origin ?? "auto",
+ createdBy: job.createdBy
+ })
+ .select("id")
+ .single();
+}
+
+export async function updatePrintJobContent(
+ client: SupabaseClient<Database>,
+ printJobId: string,
+ companyId: string,
+ content: string,
+ contentType: PrintJobContentType
+) {
+ return client
+ .from("printJob")
+ .update({
+ content,
+ contentType,
+ status: "queued",
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", printJobId)
+ .eq("companyId", companyId);
+}
+
+export async function updatePrintJobStatus(
+ client: SupabaseClient<Database>,
+ printJobId: string,
+ companyId: string,
+ status: PrintJobStatus,
+ opts?: { error?: string }
+) {
+ const update: Record<string, unknown> = {
+ status,
+ updatedAt: new Date().toISOString()
+ };
+
+ if (status === "failed") {
+ update.error = opts?.error ?? null;
+ } else {
+ update.error = null;
+ }
+
+ if (status === "completed") {
+ update.completedAt = new Date().toISOString();
+ }
+
+ return client
+ .from("printJob")
+ .update(update)
+ .eq("id", printJobId)
+ .eq("companyId", companyId);
+}
+
+// -- Printer Routes --
+
+export async function getPrinterRoutes(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ const result = await client
+ .from("printerRoute")
+ .select("*")
+ .eq("companyId", companyId)
+ .order("name");
+
+ return {
+ ...result,
+ // "format" is text in the DB but constrained to 'zpl' | 'pdf' by a CHECK
+ data: result.data as PrinterRoute[] | null
+ };
+}
+
+export async function getPrinterRoute(
+ client: SupabaseClient<Database>,
+ routeId: string,
+ companyId: string
+) {
+ return client
+ .from("printerRoute")
+ .select(
+ "id, locationId, name, format, mediaSizeId, printerUrl, apiKey, templateId"
+ )
+ .eq("id", routeId)
+ .eq("companyId", companyId)
+ .single();
+}
+
+export async function upsertPrinterRoute(
+ client: SupabaseClient<Database>,
+ route: {
+ id?: string;
+ companyId: string;
+ locationId?: string | null;
+ name: string;
+ format: string;
+ mediaSizeId?: string | null;
+ printerUrl: string;
+ apiKey?: string | null;
+ templateId?: string | null;
+ }
+) {
+ if (route.id) {
+ return client
+ .from("printerRoute")
+ .update({
+ locationId: route.locationId ?? null,
+ name: route.name,
+ format: route.format,
+ mediaSizeId: route.mediaSizeId ?? null,
+ printerUrl: route.printerUrl,
+ apiKey: route.apiKey ?? null,
+ templateId: route.templateId ?? null,
+ updatedAt: new Date().toISOString()
+ })
+ .eq("id", route.id)
+ .eq("companyId", route.companyId);
+ }
+
+ return client.from("printerRoute").insert({
+ companyId: route.companyId,
+ locationId: route.locationId ?? null,
+ name: route.name,
+ format: route.format,
+ mediaSizeId: route.mediaSizeId ?? null,
+ printerUrl: route.printerUrl,
+ apiKey: route.apiKey ?? null,
+ templateId: route.templateId ?? null
+ });
+}
+
+export async function deletePrinterRoute(
+ client: SupabaseClient<Database>,
+ routeId: string,
+ companyId: string
+) {
+ return client
+ .from("printerRoute")
+ .delete()
+ .eq("id", routeId)
+ .eq("companyId", companyId);
+}
+
+// -- Printing Settings --
+
+export async function getPrintingSettings(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("companySettings")
+ .select("printing")
+ .eq("id", companyId)
+ .single();
+}
+
+export async function updatePrintingSettings(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ settings: PrintingSettings
+) {
+ return client
+ .from("companySettings")
+ .update({
+ printing:
+ settings as unknown as Database["public"]["Tables"]["companySettings"]["Update"]["printing"]
+ })
+ .eq("id", companyId);
+}
diff --git a/packages/printing/src/types.ts b/packages/printing/src/types.ts
new file mode 100644
index 0000000000..02dbc446ea
--- /dev/null
+++ b/packages/printing/src/types.ts
@@ -0,0 +1,59 @@
+export type ContextAssignment = {
+ printerRouteId: string | null;
+ autoPrint: boolean;
+};
+
+export type LocationAssignment = {
+ defaultPrinterRouteId: string | null;
+ defaultAutoPrint: boolean;
+ shipping: ContextAssignment;
+ receiving: ContextAssignment;
+ inventory: ContextAssignment;
+ workCenters: Record<string, ContextAssignment>;
+};
+
+export type PrintingSettings = {
+ assignments: Record<string, LocationAssignment>;
+};
+
+export type PrinterRoute = {
+ id: string;
+ companyId: string;
+ locationId: string | null;
+ name: string;
+ format: "zpl" | "pdf";
+ mediaSizeId: string | null;
+ printerUrl: string;
+ apiKey: string | null;
+ templateId: string | null;
+};
+
+export type PrintJobStatus =
+ | "generating"
+ | "queued"
+ | "printing"
+ | "completed"
+ | "failed";
+export type PrintJobOrigin = "auto" | "manual" | "reprint";
+export type PrintJobContentType = "zpl" | "pdf";
+
+export type PrintJob = {
+ id: string;
+ companyId: string;
+ status: PrintJobStatus;
+ contentType: PrintJobContentType | null;
+ content: string | null;
+ printerUrl: string;
+ sourceDocument: string;
+ sourceDocumentId: string;
+ sourceDocumentReadableId: string | null;
+ description: string;
+ origin: PrintJobOrigin;
+ error: string | null;
+ attempts: number;
+ createdBy: string;
+ createdAt: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+ completedAt: string | null;
+};
diff --git a/packages/printing/src/ui/LabelDownloadModal.tsx b/packages/printing/src/ui/LabelDownloadModal.tsx
new file mode 100644
index 0000000000..52ea1ce203
--- /dev/null
+++ b/packages/printing/src/ui/LabelDownloadModal.tsx
@@ -0,0 +1,153 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+ Badge,
+ Button,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalHeader,
+ ModalTitle,
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger
+} from "@carbon/react";
+import type { LabelSize } from "@carbon/utils";
+import { getLabelSizeLabel, labelSizes } from "@carbon/utils";
+import { Trans } from "@lingui/react/macro";
+import { LuDownload, LuInfo } from "react-icons/lu";
+import { Link } from "react-router";
+import { usePrinting } from "./PrintingProvider";
+
+type FileRoutes = {
+ pdf: (id: string, opts?: { labelSize?: string }) => string;
+ zpl: (id: string, opts?: { labelSize?: string }) => string;
+};
+
+export function LabelDownloadModal({
+ sourceDocumentId,
+ fileRoutes,
+ isOpen,
+ onClose
+}: {
+ sourceDocumentId: string;
+ fileRoutes: FileRoutes;
+ isOpen: boolean;
+ onClose: () => void;
+}) {
+ const { useMetric, settingsPath, settingsExternal } = usePrinting();
+
+ if (!isOpen) return null;
+
+ const openFile = (url: string) => {
+ window.open(window.location.origin + url, "_blank");
+ onClose();
+ };
+
+ const renderSizes = (sizes: LabelSize[]) => (
+ <div className="flex flex-col gap-1">
+ {sizes
+ .filter((s) => s.zpl)
+ .map((size) => (
+ <button
+ type="button"
+ key={`zpl-${size.id}`}
+ className="flex items-center gap-3 rounded-lg border border-border p-3 hover:bg-muted transition-colors text-left"
+ onClick={() =>
+ openFile(fileRoutes.zpl(sourceDocumentId, { labelSize: size.id }))
+ }
+ >
+ <LuDownload className="size-4 text-muted-foreground shrink-0" />
+ <div className="flex-1 min-w-0">
+ <span className="text-sm font-medium">
+ {getLabelSizeLabel(size)}
+ </span>
+ </div>
+ <Badge variant="green">ZPL</Badge>
+ </button>
+ ))}
+ {sizes.map((size) => (
+ <button
+ type="button"
+ key={`pdf-${size.id}`}
+ className="flex items-center gap-3 rounded-lg border border-border p-3 hover:bg-muted transition-colors text-left"
+ onClick={() =>
+ openFile(fileRoutes.pdf(sourceDocumentId, { labelSize: size.id }))
+ }
+ >
+ <LuDownload className="size-4 text-muted-foreground shrink-0" />
+ <div className="flex-1 min-w-0">
+ <span className="text-sm font-medium">
+ {getLabelSizeLabel(size)}
+ </span>
+ </div>
+ <Badge variant="blue">PDF</Badge>
+ </button>
+ ))}
+ </div>
+ );
+
+ const metricSizes = labelSizes.filter((s) => s.metric);
+ const imperialSizes = labelSizes.filter((s) => !s.metric);
+
+ return (
+ <Modal open onOpenChange={(open) => !open && onClose()}>
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Download Labels</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-4 pb-4">
+ <Alert variant="info">
+ <LuInfo className="size-4" />
+ <AlertTitle>
+ <Trans>No printer configured</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <div className="flex items-center justify-between gap-4">
+ <span>
+ <Trans>
+ Add a printer in the printing settings to print labels
+ directly.
+ </Trans>
+ </span>
+ <Button variant="secondary" size="sm" asChild>
+ {settingsExternal ? (
+ <a href={settingsPath} target="_blank" rel="noreferrer">
+ <Trans>Printer Settings</Trans>
+ </a>
+ ) : (
+ <Link to={settingsPath}>
+ <Trans>Printer Settings</Trans>
+ </Link>
+ )}
+ </Button>
+ </div>
+ </AlertDescription>
+ </Alert>
+ <Tabs defaultValue={useMetric ? "metric" : "imperial"}>
+ <TabsList className="grid w-full grid-cols-2">
+ <TabsTrigger value="imperial">
+ <Trans>Imperial</Trans>
+ </TabsTrigger>
+ <TabsTrigger value="metric">
+ <Trans>Metric</Trans>
+ </TabsTrigger>
+ </TabsList>
+ <TabsContent className="mt-2" value="imperial">
+ {renderSizes(imperialSizes)}
+ </TabsContent>
+ <TabsContent className="mt-2" value="metric">
+ {renderSizes(metricSizes)}
+ </TabsContent>
+ </Tabs>
+ </div>
+ </ModalBody>
+ </ModalContent>
+ </Modal>
+ );
+}
diff --git a/packages/printing/src/ui/PrintButton.tsx b/packages/printing/src/ui/PrintButton.tsx
new file mode 100644
index 0000000000..2f1e784f2a
--- /dev/null
+++ b/packages/printing/src/ui/PrintButton.tsx
@@ -0,0 +1,170 @@
+import {
+ Button,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ toast,
+ useDisclosure
+} from "@carbon/react";
+import { Trans } from "@lingui/react/macro";
+import { useEffect, useState } from "react";
+import { LuCheck, LuPrinter } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import type { PrinterContext } from "../assignments";
+import { LabelDownloadModal } from "./LabelDownloadModal";
+import { usePrinting } from "./PrintingProvider";
+
+type FileRoutes = {
+ pdf: (id: string, opts?: { labelSize?: string }) => string;
+ zpl: (id: string, opts?: { labelSize?: string }) => string;
+};
+
+export function PrintButton({
+ sourceDocument,
+ sourceDocumentId,
+ locationId,
+ context,
+ workCenterId,
+ fileRoutes,
+ disabled
+}: {
+ sourceDocument: string;
+ sourceDocumentId: string;
+ locationId: string | undefined;
+ context: PrinterContext;
+ workCenterId?: string;
+ fileRoutes: FileRoutes;
+ disabled?: boolean;
+}) {
+ const { printerRoutes, resolvePrinterRoute, printPath } = usePrinting();
+ const modal = useDisclosure();
+ const downloadModal = useDisclosure();
+ const fetcher = useFetcher<{ success: boolean; message: string }>();
+
+ const defaultPrinter = resolvePrinterRoute(locationId, context, workCenterId);
+ const [selectedPrinterId, setSelectedPrinterId] = useState<string>(
+ defaultPrinter?.id ?? ""
+ );
+
+ useEffect(() => {
+ if (modal.isOpen) {
+ setSelectedPrinterId(defaultPrinter?.id ?? printerRoutes[0]?.id ?? "");
+ }
+ }, [modal.isOpen, defaultPrinter?.id, printerRoutes]);
+
+ useEffect(() => {
+ if (fetcher.data?.success) {
+ toast.success(fetcher.data.message);
+ modal.onClose();
+ } else if (fetcher.data?.success === false) {
+ toast.error(fetcher.data.message);
+ }
+ }, [fetcher.data, modal.onClose]);
+
+ const handleClick = () => {
+ if (printerRoutes.length > 0) {
+ modal.onOpen();
+ } else {
+ downloadModal.onOpen();
+ }
+ };
+
+ const handlePrint = () => {
+ fetcher.submit(
+ {
+ sourceDocument,
+ sourceDocumentId,
+ ...(locationId ? { locationId } : {}),
+ ...(workCenterId ? { workCenterId } : {}),
+ printerRouteId: selectedPrinterId
+ },
+ {
+ method: "POST",
+ action: printPath,
+ encType: "application/json"
+ }
+ );
+ };
+
+ return (
+ <>
+ <Button
+ leftIcon={<LuPrinter />}
+ variant="secondary"
+ disabled={disabled}
+ onClick={handleClick}
+ >
+ <Trans>Print</Trans>
+ </Button>
+
+ {modal.isOpen && (
+ <Modal open onOpenChange={(open) => !open && modal.onClose()}>
+ <ModalContent>
+ <ModalHeader>
+ <ModalTitle>
+ <Trans>Select Printer</Trans>
+ </ModalTitle>
+ </ModalHeader>
+ <ModalBody>
+ <div className="flex flex-col gap-1">
+ {printerRoutes.map((route) => (
+ <button
+ type="button"
+ key={route.id}
+ className={`flex items-center gap-3 rounded-lg border p-3 text-left transition-colors ${
+ selectedPrinterId === route.id
+ ? "border-primary bg-primary/5"
+ : "border-border hover:bg-muted"
+ }`}
+ onClick={() => setSelectedPrinterId(route.id)}
+ >
+ <LuPrinter className="size-4 text-muted-foreground shrink-0" />
+ <div className="flex-1 min-w-0">
+ <span className="text-sm font-medium">{route.name}</span>
+ <span className="text-xs text-muted-foreground ml-2 uppercase">
+ {route.format}
+ </span>
+ {route.mediaSizeId && (
+ <span className="text-xs text-muted-foreground ml-2">
+ {route.mediaSizeId}
+ </span>
+ )}
+ </div>
+ {selectedPrinterId === route.id && (
+ <LuCheck className="size-4 text-primary shrink-0" />
+ )}
+ </button>
+ ))}
+ </div>
+ </ModalBody>
+ <ModalFooter>
+ <div className="flex gap-2">
+ <Button
+ variant="primary"
+ leftIcon={<LuPrinter />}
+ disabled={!selectedPrinterId || fetcher.state !== "idle"}
+ onClick={handlePrint}
+ >
+ <Trans>Print</Trans>
+ </Button>
+ <Button variant="solid" onClick={modal.onClose}>
+ <Trans>Cancel</Trans>
+ </Button>
+ </div>
+ </ModalFooter>
+ </ModalContent>
+ </Modal>
+ )}
+
+ <LabelDownloadModal
+ sourceDocumentId={sourceDocumentId}
+ fileRoutes={fileRoutes}
+ isOpen={downloadModal.isOpen}
+ onClose={downloadModal.onClose}
+ />
+ </>
+ );
+}
diff --git a/packages/printing/src/ui/PrintingProvider.tsx b/packages/printing/src/ui/PrintingProvider.tsx
new file mode 100644
index 0000000000..738957a9c4
--- /dev/null
+++ b/packages/printing/src/ui/PrintingProvider.tsx
@@ -0,0 +1,85 @@
+import type { ReactNode } from "react";
+import { createContext, useCallback, useContext, useMemo } from "react";
+import type { PrinterContext } from "../assignments";
+import { resolveContextAssignment } from "../assignments";
+import type { PrinterRoute, PrintingSettings } from "../types";
+
+export type PrintingProviderValue = {
+ printing: PrintingSettings | null;
+ printerRoutes: PrinterRoute[];
+ useMetric: boolean;
+ /** POST target for queueing a manual print job */
+ printPath: string;
+ /** href for the printer settings page */
+ settingsPath: string;
+ /** open printer settings in a new tab (e.g. MES links to ERP) */
+ settingsExternal?: boolean;
+};
+
+const PrintingContext = createContext<PrintingProviderValue | null>(null);
+
+export function PrintingProvider({
+ value,
+ children
+}: {
+ value: PrintingProviderValue;
+ children: ReactNode;
+}) {
+ return (
+ <PrintingContext.Provider value={value}>
+ {children}
+ </PrintingContext.Provider>
+ );
+}
+
+export function usePrinting() {
+ const context = useContext(PrintingContext);
+ if (!context) {
+ throw new Error("usePrinting must be used within a PrintingProvider");
+ }
+
+ const { printing, printerRoutes } = context;
+
+ const routeMap = useMemo(
+ () => new Map(printerRoutes.map((r) => [r.id, r])),
+ [printerRoutes]
+ );
+
+ const resolvePrinterRoute = useCallback(
+ (
+ locationId: string | undefined,
+ printerContext: PrinterContext,
+ workCenterId?: string
+ ): PrinterRoute | null => {
+ if (!locationId || !printing) return null;
+
+ const assignment = printing.assignments?.[locationId];
+ if (!assignment) return null;
+
+ const { printerRouteId } = resolveContextAssignment(
+ assignment,
+ printerContext,
+ workCenterId
+ );
+
+ if (!printerRouteId) return null;
+ return routeMap.get(printerRouteId) ?? null;
+ },
+ [printing, routeMap]
+ );
+
+ const hasPrinter = useCallback(
+ (
+ locationId: string | undefined,
+ printerContext: PrinterContext,
+ workCenterId?: string
+ ): boolean => {
+ return (
+ resolvePrinterRoute(locationId, printerContext, workCenterId) !== null
+ );
+ },
+ [resolvePrinterRoute]
+ );
+
+ return { ...context, resolvePrinterRoute, hasPrinter };
+}
diff --git a/packages/printing/src/ui/index.ts b/packages/printing/src/ui/index.ts
new file mode 100644
index 0000000000..1674abbd24
--- /dev/null
+++ b/packages/printing/src/ui/index.ts
@@ -0,0 +1,4 @@
+export { LabelDownloadModal } from "./LabelDownloadModal";
+export { PrintButton } from "./PrintButton";
+export type { PrintingProviderValue } from "./PrintingProvider";
+export { PrintingProvider, usePrinting } from "./PrintingProvider";
diff --git a/packages/printing/tsconfig.json b/packages/printing/tsconfig.json
new file mode 100644
index 0000000000..e9cdbe7191
--- /dev/null
+++ b/packages/printing/tsconfig.json
@@ -0,0 +1,8 @@
+{
+ "extends": "@carbon/config/tsconfig/base.json",
+ "compilerOptions": {
+ "types": ["node"]
+ },
+ "include": ["src"],
+ "exclude": ["dist", "build", "node_modules"]
+}
diff --git a/packages/react/src/Badge.tsx b/packages/react/src/Badge.tsx
index 09ea8f2f75..7c3a146167 100644
--- a/packages/react/src/Badge.tsx
+++ b/packages/react/src/Badge.tsx
@@ -32,7 +32,7 @@ const badgeVariants = cva(
blue: "bg-blue-100 text-blue-800 dark:bg-blue-500/15 dark:text-blue-400 border-blue-500/20",
gray: "bg-[#e3e2e080] text-[#32302c] dark:bg-[#373737] dark:text-white hover:bg-[#e3e2e0] dark:hover:bg-[#5a5a5a] ",
purple:
- "bg-violet-100 text-violet-800 dark:bg-violet-500/15 dark:text-violet-400"
+ "bg-violet-100 text-violet-800 dark:bg-violet-500/15 dark:text-violet-400 border-violet-500/20"
}
},
defaultVariants: {
diff --git a/packages/react/src/Select.tsx b/packages/react/src/Select.tsx
index 6e79028315..da74743583 100644
--- a/packages/react/src/Select.tsx
+++ b/packages/react/src/Select.tsx
@@ -111,7 +111,7 @@ const SelectContent = forwardRef<
<SelectPrimitive.Content
ref={ref}
className={cn(
- "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
diff --git a/packages/utils/src/labels.ts b/packages/utils/src/labels.ts
index 37334d6166..eb10ff4568 100644
--- a/packages/utils/src/labels.ts
+++ b/packages/utils/src/labels.ts
@@ -12,10 +12,7 @@ export type LabelSize = {
name: string;
width: number;
height: number;
- description: string;
- rows?: number;
- columns?: number;
- rotated?: boolean;
+ metric?: boolean;
zpl?: {
dpi: number;
width: number;
@@ -23,34 +20,34 @@ export type LabelSize = {
};
};
+/** Dimensions as `2" x 1"` or `100mm x 50mm` (width x height). */
+export function getLabelSizeDimensions(size: LabelSize): string {
+ if (size.metric) {
+ const widthMm = Math.round(size.width * 25.4);
+ const heightMm = Math.round(size.height * 25.4);
+ return `${widthMm}mm x ${heightMm}mm`;
+ }
+ return `${size.width}" x ${size.height}"`;
+}
+
+/** Display label as `2" x 1"` for thermal sizes or `Avery 5163 4" x 2"` for sheets. */
+export function getLabelSizeLabel(size: LabelSize): string {
+ const dimensions = getLabelSizeDimensions(size);
+ return size.zpl ? dimensions : `${size.name} ${dimensions}`;
+}
+
export const labelSizes: LabelSize[] = [
- {
- id: "avery5160",
- name: "Avery 5160",
- width: 2.625, // inches to points (72 points per inch)
- height: 1,
- description: 'Address Labels (1" x 2.625")',
- rows: 10,
- columns: 3,
- rotated: false
- },
{
id: "avery5163",
name: "Avery 5163",
width: 4,
- height: 2,
- description: 'Shipping Labels (2" x 4")',
- rows: 5,
- columns: 2,
- rotated: false
+ height: 2
},
{
- id: "zebra2x1",
- name: "Zebra 2x1",
+ id: "label2x1",
+ name: "Label 2x1",
width: 2,
height: 1,
- description: 'Thermal Transfer Labels (1" x 2")',
- rotated: false,
zpl: {
dpi: 203,
width: 2,
@@ -58,16 +55,38 @@ export const labelSizes: LabelSize[] = [
}
},
{
- id: "zebra4x2",
- name: "Zebra 4x2",
+ id: "label4x2",
+ name: "Label 4x2",
width: 4,
height: 2,
- description: 'Thermal Transfer Labels (2" x 4")',
- rotated: false,
zpl: {
dpi: 203,
width: 4,
height: 2
}
+ },
+ {
+ id: "label100x50mm",
+ name: "Label 100x50mm",
+ width: 3.937,
+ height: 1.969,
+ metric: true,
+ zpl: {
+ dpi: 203,
+ width: 3.937,
+ height: 1.969
+ }
+ },
+ {
+ id: "label50x25mm",
+ name: "Label 50x25mm",
+ width: 1.969,
+ height: 0.984,
+ metric: true,
+ zpl: {
+ dpi: 203,
+ width: 1.969,
+ height: 0.984
+ }
}
];
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 3158480a6b..960cc3d2b8 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -586,6 +586,9 @@ importers:
'@carbon/notifications':
specifier: workspace:*
version: link:../../packages/notifications
+ '@carbon/printing':
+ specifier: workspace:*
+ version: link:../../packages/printing
'@carbon/react':
specifier: workspace:*
version: link:../../packages/react
@@ -651,7 +654,7 @@ importers:
version: 3.4.5([email protected])
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -696,7 +699,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@visx/responsive':
specifier: 2.17.0
version: 2.17.0([email protected])
@@ -741,7 +744,7 @@ importers:
inngest:
specifier: ^3.52.7
intl-parse-accept-language:
specifier: 'catalog:'
version: 1.0.0
@@ -922,16 +925,16 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@react-router/dev':
specifier: 'catalog:'
'@tailwindcss/typography':
specifier: 'catalog:'
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@types/d3':
specifier: 7.4.3
version: 7.4.3
@@ -988,13 +991,13 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
vitest:
specifier: 'catalog:'
apps/mes:
dependencies:
@@ -1028,6 +1031,9 @@ importers:
'@carbon/notifications':
specifier: workspace:*
version: link:../../packages/notifications
+ '@carbon/printing':
+ specifier: workspace:*
+ version: link:../../packages/printing
'@carbon/react':
specifier: workspace:*
version: link:../../packages/react
@@ -1069,7 +1075,7 @@ importers:
'@lingui/vite-plugin':
specifier: 'catalog:'
'@nanostores/react':
specifier: 'catalog:'
@@ -1081,10 +1087,10 @@ importers:
version: 3.4.5([email protected])
'@react-router/dev':
specifier: 'catalog:'
'@react-router/remix-routes-option-adapter':
specifier: 'catalog:'
'@react-router/serve':
specifier: 'catalog:'
@@ -1105,7 +1111,7 @@ importers:
version: 0.5.19([email protected])
'@tailwindcss/vite':
specifier: 'catalog:'
'@tiptap/core':
specifier: 'catalog:'
version: 2.27.2(@tiptap/[email protected])
@@ -1147,7 +1153,7 @@ importers:
'@vercel/react-router':
specifier: 'catalog:'
'@xyflow/react':
specifier: 12.10.2
@@ -1265,10 +1271,10 @@ importers:
version: 5.8.3
vite:
specifier: 'catalog:'
vite-plugin-babel-macros:
specifier: 'catalog:'
wait-on:
specifier: 'catalog:'
version: 7.2.0
@@ -2172,6 +2178,9 @@ importers:
'@carbon/notifications':
specifier: workspace:*
version: link:../notifications
+ '@carbon/printing':
+ specifier: workspace:*
+ version: link:../printing
'@carbon/stripe':
specifier: workspace:*
version: link:../stripe
@@ -2184,6 +2193,9 @@ importers:
'@react-email/components':
specifier: 'catalog:'
+ '@react-pdf/renderer':
+ specifier: 'catalog:'
+ version: 3.4.5([email protected])
'@slack/web-api':
specifier: 'catalog:'
version: 7.10.0
@@ -2211,6 +2223,9 @@ importers:
nodemailer:
specifier: 6.10.1
version: 6.10.1
+ react:
+ specifier: 'catalog:'
+ version: 18.3.1
react-pdf:
specifier: 'catalog:'
@@ -2236,6 +2251,9 @@ importers:
'@types/nodemailer':
specifier: 6.4.23
version: 6.4.23
+ '@types/react':
+ specifier: 'catalog:'
+ version: 18.3.28
tsx:
specifier: 'catalog:'
version: 4.21.0
@@ -2396,6 +2414,55 @@ importers:
specifier: 'catalog:'
version: 5.8.3
+ packages/printing:
+ dependencies:
+ '@carbon/kv':
+ specifier: workspace:*
+ version: link:../kv
+ '@carbon/react':
+ specifier: workspace:*
+ version: link:../react
+ '@carbon/utils':
+ specifier: workspace:*
+ version: link:../utils
+ '@lingui/react':
+ specifier: 'catalog:'
+ react:
+ specifier: 'catalog:'
+ version: 18.3.1
+ react-icons:
+ specifier: 'catalog:'
+ version: 5.6.0([email protected])
+ react-router:
+ specifier: 'catalog:'
+ zod:
+ specifier: 'catalog:'
+ version: 3.25.76
+ zod-form-data:
+ specifier: 'catalog:'
+ version: 2.0.8([email protected])
+ devDependencies:
+ '@carbon/config':
+ specifier: workspace:*
+ version: link:../config
+ '@carbon/database':
+ specifier: workspace:*
+ version: link:../database
+ '@supabase/supabase-js':
+ specifier: 'catalog:'
+ version: 2.80.0
+ '@types/node':
+ specifier: 20.19.39
+ version: 20.19.39
+ '@types/react':
+ specifier: 'catalog:'
+ version: 18.3.28
+ typescript:
+ specifier: 'catalog:'
+ version: 5.8.3
+
packages/react:
dependencies:
'@carbon/database':
@@ -8528,10 +8595,6 @@ packages:
resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==}
engines: {node: '>=10'}
- resolution: {integrity: sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==}
engines: {node: '>=12'}
@@ -12384,10 +12447,6 @@ packages:
resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ==}
- engines: {node: '>=12'}
-
resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==}
engines: {node: '>=12'}
@@ -19652,6 +19711,14 @@ snapshots:
optionalDependencies:
+ dependencies:
+ '@vitest/spy': 4.1.6
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+
dependencies:
'@vitest/spy': 4.1.6
@@ -19789,8 +19856,6 @@ snapshots:
-
@@ -21545,6 +21610,44 @@ snapshots:
+ dependencies:
+ '@bufbuild/protobuf': 2.11.0
+ '@inngest/ai': 0.1.7
+ '@jpwilliams/waitgroup': 2.1.1
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/auto-instrumentations-node': 0.72.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))
+ '@opentelemetry/context-async-hooks': 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/exporter-trace-otlp-http': 0.214.0(@opentelemetry/[email protected])
+ '@opentelemetry/instrumentation': 0.214.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.6.1(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.6.1(@opentelemetry/[email protected])
+ '@standard-schema/spec': 1.1.0
+ '@traceloop/instrumentation-anthropic': 0.20.0
+ '@types/debug': 4.1.13
+ '@types/ms': 2.1.0
+ canonicalize: 1.0.8
+ chalk: 4.1.2
+ cross-fetch: 4.1.0
+ debug: 4.4.3([email protected])
+ hash.js: 1.1.7
+ json-stringify-safe: 5.0.1
+ ms: 2.1.3
+ serialize-error-cjs: 0.1.4
+ strip-ansi: 5.2.0
+ temporal-polyfill: 0.2.5
+ ulid: 2.4.0
+ zod: 3.25.76
+ optionalDependencies:
+ express: 4.22.1
+ hono: 4.12.14
+ typescript: 5.8.3
+ transitivePeerDependencies:
+ - '@opentelemetry/core'
+ - encoding
+ - supports-color
+
dependencies:
'@bufbuild/protobuf': 2.11.0
@@ -22121,7 +22224,7 @@ snapshots:
ansi-escapes: 7.3.0
cli-cursor: 5.0.0
slice-ansi: 7.1.2
- strip-ansi: 7.1.0
+ strip-ansi: 7.2.0
wrap-ansi: 9.0.2
@@ -24355,7 +24458,7 @@ snapshots:
dependencies:
emoji-regex: 10.6.0
get-east-asian-width: 1.5.0
- strip-ansi: 7.1.0
+ strip-ansi: 7.2.0
dependencies:
@@ -24409,10 +24512,6 @@ snapshots:
dependencies:
ansi-regex: 5.0.1
- dependencies:
- ansi-regex: 6.2.2
-
dependencies:
ansi-regex: 6.2.2
@@ -25178,6 +25277,34 @@ snapshots:
transitivePeerDependencies:
- msw
+ dependencies:
+ '@vitest/expect': 4.1.6
+ '@vitest/pretty-format': 4.1.6
+ '@vitest/runner': 4.1.6
+ '@vitest/snapshot': 4.1.6
+ '@vitest/spy': 4.1.6
+ '@vitest/utils': 4.1.6
+ es-module-lexer: 2.0.0
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ obug: 2.1.1
+ pathe: 2.0.3
+ picomatch: 4.0.4
+ std-env: 4.0.0
+ tinybench: 2.9.0
+ tinyexec: 1.1.1
+ tinyglobby: 0.2.16
+ tinyrainbow: 3.1.0
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.0
+ '@types/node': 24.12.2
+ transitivePeerDependencies:
+ - msw
+
dependencies:
'@vitest/expect': 4.1.6
@@ -25339,9 +25466,9 @@ snapshots:
dependencies:
- ansi-styles: 6.2.1
+ ansi-styles: 6.2.3
string-width: 7.2.0
- strip-ansi: 7.1.0
+ strip-ansi: 7.2.0