Skip to content

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

feat: add qr code for kanban route

Brad Barbin9781adaaab61
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
index 680765eac9..078dd0366e 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx
@@ -131,6 +131,14 @@ const InventoryTable = memo(
icon: <LuClock />,
},
},
+ {
+ accessorKey: "leadTime",
+ header: "Lead Time",
+ cell: ({ row }) => numberFormatter.format(row.original.leadTime),
+ meta: {
+ icon: <LuClock />,
+ },
+ },
{
accessorKey: "reorderingPolicy",
header: "Reorder Policy",
@@ -176,14 +184,7 @@ const InventoryTable = memo(
icon: <LuLoaderCircle />,
},
},
- {
- accessorKey: "leadTime",
- header: "Lead Time",
- cell: ({ row }) => numberFormatter.format(row.original.leadTime),
- meta: {
- icon: <LuClock />,
- },
- },
+
{
accessorKey: "usageLast30Days",
header: "Usage/Day (30d)",
diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
index 459018bd85..cd152a1fcf 100644
--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
@@ -1,4 +1,13 @@
-import { Combobox, HStack, MenuItem, VStack } from "@carbon/react";
+import {
+ Combobox,
+ HStack,
+ IconButton,
+ MenuItem,
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+ VStack,
+} from "@carbon/react";
import { Link } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -8,6 +17,7 @@ import {
LuMapPin,
LuPackage,
LuPencil,
+ LuQrCode,
LuRefreshCw,
LuTrash,
LuUser,
@@ -70,6 +80,35 @@ const KanbansTable = memo(({ data, count, locationId }: KanbansTableProps) => {
icon: <LuPackage />,
},
},
+ {
+ id: "links",
+ header: "",
+ cell: ({ row }) => (
+ <HStack>
+ <Popover>
+ <PopoverTrigger>
+ <IconButton
+ aria-label="QR Code"
+ variant="secondary"
+ icon={<LuQrCode />}
+ />
+ </PopoverTrigger>
+ <PopoverContent
+ align="center"
+ className="size-[236px] overflow-hidden z-[100] bg-white p-4"
+ >
+ <iframe
+ seamless
+ title={"Kanban QR Code"}
+ width="198"
+ height="198"
+ src={path.to.file.kanbanQrCode(row.original.id!)}
+ />
+ </PopoverContent>
+ </Popover>
+ </HStack>
+ ),
+ },
{
accessorKey: "quantity",
header: "Reorder Qty.",
diff --git a/apps/erp/app/routes/file+/kanban+/$id[.]png.tsx b/apps/erp/app/routes/file+/kanban+/$id[.]png.tsx
new file mode 100644
index 0000000000..057012ec4d
--- /dev/null
+++ b/apps/erp/app/routes/file+/kanban+/$id[.]png.tsx
@@ -0,0 +1,34 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { generateQRCodeBuffer } from "@carbon/documents/qr";
+import { json, type LoaderFunctionArgs } from "@vercel/remix";
+import { getKanban } from "~/modules/inventory/inventory.service";
+
+export const config = { runtime: "nodejs" };
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "inventory",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find kanban id");
+
+ const kanban = await getKanban(client, id);
+
+ if (kanban.error) {
+ return json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const url = new URL(request.url);
+ const baseUrl = `${url.protocol}//${url.host}`;
+ const kanbanUrl = `${baseUrl}/api/kanban/${id}`;
+
+ const buffer = await generateQRCodeBuffer(kanbanUrl, 36);
+
+ return new Response(buffer, {
+ headers: {
+ "Content-Type": "image/png",
+ "Cache-Control": "public, max-age=31536000, immutable",
+ },
+ });
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 3983848f0d..14d830fb8a 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -159,6 +159,7 @@ export const path = {
},
file: {
cadModel: (id: string) => generatePath(`${file}/model/${id}`),
+ kanbanQrCode: (id: string) => generatePath(`${file}/kanban/${id}.png`),
jobTraveler: (id: string) => generatePath(`${file}/traveler/${id}.pdf`),
nonConformance: (id: string) => generatePath(`${file}/issue/${id}.pdf`),
operationLabelsPdf: (
diff --git a/llm/cache/pdf-generation-patterns.md b/llm/cache/pdf-generation-patterns.md
new file mode 100644
index 0000000000..99bcb44124
--- /dev/null
+++ b/llm/cache/pdf-generation-patterns.md
@@ -0,0 +1,153 @@
+# PDF Generation and QR Code Patterns
+
+## Overview
+
+The Carbon codebase uses React PDF for generating PDFs with asynchronous patterns for QR code generation and image preprocessing.
+
+## PDF Components
+
+### Core Components
+
+- **PackingSlipPDF** (`/Users/barbinbrad/Code/carbon/packages/documents/src/pdf/PackingSlipPDF.tsx`)
+- **ProductLabelPDF** (`/Users/barbinbrad/Code/carbon/packages/documents/src/pdf/ProductLabelPDF.tsx`)
+- **JobTravelerPDF** (`/Users/barbinbrad/Code/carbon/packages/documents/src/pdf/JobTravelerPDF.tsx`)
+
+## Async Patterns
+
+### QR Code Generation
+
+All QR code generation is asynchronous using the `bwip-js/node` library:
+
+#### QR Code Utility (`/Users/barbinbrad/Code/carbon/packages/documents/src/qr/qr-code.ts`)
+
+```typescript
+export async function generateQRCode(
+ text: string,
+ size: number
+): Promise<string> {
+ const buffer = await bwipjs.toBuffer({
+ bcid: "qrcode",
+ text,
+ scale: 2,
+ height: size,
+ width: size,
+ });
+ return `data:image/png;base64,${buffer.toString("base64")}`;
+}
+```
+
+#### In-Component QR/Barcode Generation
+
+- **JobTravelerPDF**: Has its own `generateQRCode` function that creates QR codes for operation tracking URLs
+- **PackingSlipPDF**: Has `generateBarcode` function for Code128 barcodes and uses imported `generateQRCode` for tracked entities
+- **ProductLabelPDF**: Uses `await generateQRCode(item.trackedEntityId, qrCodeSize / 72)` directly in JSX
+
+### Image Preprocessing
+
+#### Thumbnail Processing
+
+All PDF routes use async preprocessing for thumbnails via `getBase64ImageFromSupabase`:
+
+```typescript
+// From shared.service.ts
+export async function getBase64ImageFromSupabase(
+ client: SupabaseClient<Database>,
+ path: string
+) {
+ const { data, error } = await client.storage.from("private").download(path);
+ if (error) return null;
+
+ const arrayBuffer = await data.arrayBuffer();
+ const base64String = arrayBufferToBase64(arrayBuffer);
+
+ const fileExtension = path.split(".").pop()?.toLowerCase();
+ const mimeType =
+ fileExtension === "jpg" || fileExtension === "jpeg"
+ ? "image/jpeg"
+ : "image/png";
+
+ return `data:${mimeType};base64,${base64String}`;
+}
+```
+
+#### Thumbnail Batch Processing Pattern
+
+Routes use `Promise.all` to process multiple thumbnails:
+
+```typescript
+const thumbnails: Record<string, string | null> =
+ (thumbnailPaths
+ ? await Promise.all(
+ Object.entries(thumbnailPaths).map(([id, path]) => {
+ if (!path) return null;
+ return getBase64ImageFromSupabase(client, path).then((data) => ({
+ id,
+ data,
+ }));
+ })
+ )
+ : []
+ )?.reduce<Record<string, string | null>>((acc, thumbnail) => {
+ if (thumbnail) acc[thumbnail.id] = thumbnail.data;
+ return acc;
+ }, {}) ?? {};
+```
+
+## Route-Level Async Patterns
+
+### Data Fetching with Promise.all
+
+All PDF routes use `Promise.all` for parallel data fetching:
+
+```typescript
+const [company, shipment, shipmentLines, terms] = await Promise.all([
+ getCompany(client, companyId),
+ getShipment(client, id),
+ getShipmentLinesWithDetails(client, id),
+ getSalesTerms(client, companyId),
+]);
+```
+
+### PDF Streaming Pattern
+
+All routes use the same streaming pattern:
+
+```typescript
+const stream = await renderToStream(<PDFComponent {...props} />);
+
+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(body, {
+ status: 200,
+ headers: new Headers({ "Content-Type": "application/pdf" }),
+});
+```
+
+## Key Insights
+
+### Pre-processing Strategy
+
+1. **Database queries**: All data fetched before PDF generation using `Promise.all`
+2. **Images**: Converted to base64 data URLs before passing to PDF components
+3. **QR codes**: Generated synchronously within PDF components during render
+4. **Barcodes**: Generated asynchronously in helper functions
+
+### Performance Optimizations
+
+- Parallel data fetching with `Promise.all`
+- Batch thumbnail processing
+- Base64 image encoding done once per image
+- QR codes generated on-demand during PDF render
+
+### Error Handling
+
+- Individual error checking for each Promise.all result
+- Null checks for optional images/thumbnails
+- Graceful degradation when images fail to load
+
+The system efficiently pre-processes all external data (database queries, images) while generating codes (QR/barcodes) during the PDF render phase for optimal performance.
diff --git a/packages/documents/package.json b/packages/documents/package.json
index 881da8eb2f..4554d106ff 100644
--- a/packages/documents/package.json
+++ b/packages/documents/package.json
@@ -28,7 +28,8 @@
"exports": {
"./email": "./src/email/index.ts",
"./pdf": "./src/pdf/index.ts",
- "./zpl": "./src/zpl/index.ts"
+ "./zpl": "./src/zpl/index.ts",
+ "./qr": "./src/qr/qr-code.ts"
},
"jest": {
"preset": "@carbon/jest/node"
diff --git a/packages/documents/src/pdf/JobTravelerPDF.tsx b/packages/documents/src/pdf/JobTravelerPDF.tsx
index 543e57ee6c..b74253f7f8 100644
--- a/packages/documents/src/pdf/JobTravelerPDF.tsx
+++ b/packages/documents/src/pdf/JobTravelerPDF.tsx
@@ -1,8 +1,8 @@
-import bwipjs from "@bwip-js/node";
import type { Database } from "@carbon/database";
import type { JSONContent } from "@carbon/react";
import { Image, StyleSheet, Text, View } from "@react-pdf/renderer";
import { createTw } from "react-pdf-tailwind";
+import { generateQRCode } from "../qr/qr-code";
import type { Company, PDF } from "../types";
import { Header, Note, Template } from "./components";
@@ -284,17 +284,26 @@ const JobTravelerPDF = ({
.map((operation, index) => {
const setupQrCode =
operation.setupTime > 0
- ? generateQRCode(`${getStartPath(operation.id)}?type=Setup`)
+ ? generateQRCode(
+ `${getStartPath(operation.id)}?type=Setup`,
+ 10
+ )
: null;
let laborQrCode =
operation.laborTime > 0
- ? generateQRCode(`${getStartPath(operation.id)}?type=Labor`)
+ ? generateQRCode(
+ `${getStartPath(operation.id)}?type=Labor`,
+ 10
+ )
: null;
let machiningQrCode =
operation.machineTime > 0
- ? generateQRCode(`${getStartPath(operation.id)}?type=Machine`)
+ ? generateQRCode(
+ `${getStartPath(operation.id)}?type=Machine`,
+ 10
+ )
: null;
- let completeQrCode = generateQRCode(getEndPath(operation.id));
+ let completeQrCode = generateQRCode(getEndPath(operation.id), 10);
if (
setupQrCode === null &&
@@ -302,7 +311,8 @@ const JobTravelerPDF = ({
machiningQrCode === null
) {
laborQrCode = generateQRCode(
- `${getStartPath(operation.id)}?type=Labor`
+ `${getStartPath(operation.id)}?type=Labor`,
+ 10
);
}
@@ -373,17 +383,6 @@ const JobTravelerPDF = ({
);
};
-async function generateQRCode(text: string): Promise<string> {
- const buffer = await bwipjs.toBuffer({
- bcid: "qrcode",
- text,
- scale: 2,
- height: 10,
- width: 10,
- });
- return `data:image/png;base64,${buffer.toString("base64")}`;
-}
-
export default JobTravelerPDF;
type Operation = Database["public"]["Tables"]["jobOperation"]["Row"];
diff --git a/packages/documents/src/pdf/PackingSlipPDF.tsx b/packages/documents/src/pdf/PackingSlipPDF.tsx
index 93dd4cb05c..a2f3d39db4 100644
--- a/packages/documents/src/pdf/PackingSlipPDF.tsx
+++ b/packages/documents/src/pdf/PackingSlipPDF.tsx
@@ -5,6 +5,7 @@ import type { TrackedEntityAttributes } from "@carbon/utils";
import { formatCityStatePostalCode } from "@carbon/utils";
import { Image, Text, View } from "@react-pdf/renderer";
import { createTw } from "react-pdf-tailwind";
+import { generateQRCode } from "../qr/qr-code";
import type { PDF } from "../types";
import { Header, Note, Summary, Template } from "./components";
@@ -224,7 +225,7 @@ const PackingSlipPDF = ({
{trackedEntitiesForLine.length > 0 && (
<View>
{trackedEntitiesForLine.map((entity) => {
- const qrCodeDataUrl = generateQRCode(entity.id);
+ const qrCodeDataUrl = generateQRCode(entity.id, 8);
return (
<View
key={entity.id}
@@ -280,17 +281,6 @@ function getLineDescriptionDetails(
return line.description;
}
-async function generateQRCode(text: string): Promise<string> {
- const buffer = await bwipjs.toBuffer({
- bcid: "qrcode",
- text,
- scale: 2, // Reduced scale for smaller QR code
- height: 8, // Reduced height
- width: 8, // Reduced width
- });
- return `data:image/png;base64,${buffer.toString("base64")}`;
-}
-
async function generateBarcode(text: string): Promise<string> {
const buffer = await bwipjs.toBuffer({
bcid: "code128", // Barcode type
@@ -302,5 +292,4 @@ async function generateBarcode(text: string): Promise<string> {
});
return `data:image/png;base64,${buffer.toString("base64")}`;
}
-
export default PackingSlipPDF;
diff --git a/packages/documents/src/pdf/ProductLabelPDF.tsx b/packages/documents/src/pdf/ProductLabelPDF.tsx
index 98f47f2956..f19df6cef3 100644
--- a/packages/documents/src/pdf/ProductLabelPDF.tsx
+++ b/packages/documents/src/pdf/ProductLabelPDF.tsx
@@ -1,7 +1,7 @@
-import { Document, Page, View, Text, Image } from "@react-pdf/renderer";
-import bwipjs from "@bwip-js/node";
+import type { LabelSize, ProductLabelItem } from "@carbon/utils";
+import { Document, Image, Page, Text, View } from "@react-pdf/renderer";
import { createTw } from "react-pdf-tailwind";
-import { LabelSize, ProductLabelItem } from "@carbon/utils";
+import { generateQRCode } from "../qr/qr-code";
interface ProductLabelProps {
items: ProductLabelItem[];
@@ -176,7 +176,10 @@ const ProductLabelPDF = ({ items, labelSize }: ProductLabelProps) => {
<View style={tw("flex items-center justify-center")}>
<Image
- src={generateQRCode(item.trackedEntityId)}
+ src={generateQRCode(
+ item.trackedEntityId,
+ qrCodeSize / 72
+ )}
style={{
width: qrCodeSize,
height: qrCodeSize,
@@ -208,14 +211,4 @@ const ProductLabelPDF = ({ items, labelSize }: ProductLabelProps) => {
);
};
-async function generateQRCode(text: string): Promise<string> {
- const buffer = await bwipjs.toBuffer({
- bcid: "qrcode", // QR code type
- text: text, // Text to encode
- scale: 3, // Scaling factor
- includetext: false, // No human-readable text for QR codes
- });
- return `data:image/png;base64,${buffer.toString("base64")}`;
-}
-
export default ProductLabelPDF;
diff --git a/packages/documents/src/qr/qr-code.ts b/packages/documents/src/qr/qr-code.ts
new file mode 100644
index 0000000000..562a5e348c
--- /dev/null
+++ b/packages/documents/src/qr/qr-code.ts
@@ -0,0 +1,38 @@
+import bwipjs from "@bwip-js/node";
+
+export async function generateQRCode(
+ text: string,
+ size: number
+): Promise<string> {
+ const buffer = await bwipjs.toBuffer({
+ bcid: "qrcode",
+ text,
+ scale: 2,
+ height: size,
+ width: size,
+ });
+ return `data:image/png;base64,${buffer.toString("base64")}`;
+}
+
+export async function generateQRCodeBuffer(
+ text: string,
+ size: number
+): Promise<Buffer> {
+ const buffer = await bwipjs.toBuffer({
+ bcid: "qrcode",
+ text,
+ scale: 2,
+ height: size,
+ width: size,
+ });
+ return buffer;
+}
+
+export function generateQRCodeSync(text: string, size: number): string {
+ // bwipjs.toBuffer returns a Promise, but when called without await
+ // in a synchronous context, we need to handle it differently
+ // For now, keeping the existing async implementation
+ throw new Error(
+ "Synchronous QR code generation not supported. Use async version or inline implementation."
+ );
+}