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 ability to assign readable id and print labels from inventory shelves component

Brad Barbine3c5f6e0b872
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index 07e5535b91..54dbd8a315 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -103,7 +103,8 @@ export const inventoryAdjustmentValidator = z.object({
shelfId: zfd.text(z.string().optional()),
adjustmentType: z.enum([...itemLedgerTypes, "Set Quantity"]),
quantity: zfd.numeric(z.number()),
- trackedEntityId: zfd.text(z.string().optional())
+ trackedEntityId: zfd.text(z.string().optional()),
+ readableId: zfd.text(z.string().optional())
});
export const itemLedgerValidator = z.object({
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 647984cfbf..24e2ebc2cf 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -804,6 +804,17 @@ export async function getTrackedEntitiesByMakeMethodId(
.order("createdAt", { ascending: true });
}
+export async function getTrackedEntity(
+ client: SupabaseClient<Database>,
+ trackedEntityId: string
+) {
+ return client
+ .from("trackedEntity")
+ .select("*")
+ .eq("id", trackedEntityId)
+ .single();
+}
+
export async function getTrackedEntitiesByOperationId(
client: SupabaseClient<Database>,
operationId: string
@@ -902,7 +913,7 @@ export async function insertManualInventoryAdjustment(
createdBy: string;
}
) {
- const { adjustmentType, ...rest } = inventoryAdjustment;
+ const { adjustmentType, readableId, ...rest } = inventoryAdjustment;
const data = {
...rest,
entryType:
@@ -960,7 +971,8 @@ export async function insertManualInventoryAdjustment(
const trackedEntityUpdate = await client
.from("trackedEntity")
.update({
- quantity: data.quantity + currentQuantityOnHand
+ quantity: data.quantity + currentQuantityOnHand,
+ readableId: readableId
})
.eq("id", inventoryAdjustment.trackedEntityId);
@@ -983,6 +995,7 @@ export async function insertManualInventoryAdjustment(
sourceDocument: "Item",
sourceDocumentId: data.itemId,
sourceDocumentReadableId: item.data?.readableIdWithRevision,
+ readableId: readableId,
quantity: data.quantity,
status: "Available",
companyId: data.companyId,
diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
index bdd91efde5..3c3e24f51c 100644
--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryShelves.tsx
@@ -10,7 +10,12 @@ import {
Copy,
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuPortal,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
DropdownMenuTrigger,
HStack,
IconButton,
@@ -29,9 +34,15 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
+import { labelSizes } from "@carbon/utils";
import { nanoid } from "nanoid";
import { useMemo, useState } from "react";
-import { LuEllipsisVertical, LuQrCode } from "react-icons/lu";
+import {
+ LuEllipsisVertical,
+ LuPencil,
+ LuPrinter,
+ LuQrCode
+} from "react-icons/lu";
import { Outlet } from "react-router";
import type { z } from "zod/v3";
import { Enumerable } from "~/components/Enumerable";
@@ -76,12 +87,37 @@ const InventoryShelves = ({
const [quantity, setQuantity] = useState(1);
const [selectedShelfId, setSelectedShelfId] = useState<string | null>(null);
+ const [selectedTrackedEntityId, setSelectedTrackedEntityId] = useState<
+ string | null
+ >(null);
- const openAdjustmentModal = (shelfId?: string) => {
+ const openAdjustmentModal = (shelfId?: string, trackedEntityId?: string) => {
setSelectedShelfId(shelfId || null);
+ setSelectedTrackedEntityId(trackedEntityId || null);
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"
+ );
+ } else {
+ window.open(
+ window.location.origin +
+ path.to.file.trackedEntityLabelPdf(trackedEntityId, { labelSize }),
+ "_blank"
+ );
+ }
+ };
+
return (
<>
<Card className="w-full">
@@ -130,11 +166,14 @@ const InventoryShelves = ({
</Td>
<Td>
{item.trackedEntityId && (
- <Copy
- icon={<LuQrCode />}
- text={item.trackedEntityId}
- withTextInTooltip
- />
+ <HStack>
+ {item.readableId && <span>{item.readableId}</span>}
+ <Copy
+ icon={<LuQrCode />}
+ text={item.trackedEntityId}
+ withTextInTooltip
+ />
+ </HStack>
)}
</Td>
<Td className="flex flex-shrink-0 justify-end items-center">
@@ -148,10 +187,42 @@ const InventoryShelves = ({
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
- onClick={() => openAdjustmentModal(item.shelfId)}
+ onClick={() =>
+ openAdjustmentModal(
+ item.shelfId,
+ item.trackedEntityId
+ )
+ }
>
+ <DropdownMenuIcon icon={<LuPencil />} />
Update Quantity
</DropdownMenuItem>
+ {item.trackedEntityId && (
+ <DropdownMenuSub>
+ <DropdownMenuSubTrigger>
+ <LuPrinter className="mr-2 h-4 w-4" />
+ Print Label
+ </DropdownMenuSubTrigger>
+ <DropdownMenuPortal>
+ <DropdownMenuSubContent>
+ {labelSizes.map((size) => (
+ <DropdownMenuItem
+ key={size.id}
+ onClick={() =>
+ navigateToLabel(
+ item.trackedEntityId!,
+ !!size.zpl,
+ size.id
+ )
+ }
+ >
+ {size.name}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuSubContent>
+ </DropdownMenuPortal>
+ </DropdownMenuSub>
+ )}
</DropdownMenuContent>
</DropdownMenu>
</Td>
@@ -180,8 +251,8 @@ const InventoryShelves = ({
quantity: quantity,
locationId: pickMethod.locationId,
shelfId: selectedShelfId || undefined,
- adjustmentType: "Set Quantity",
- trackedEntityId: nanoid()
+ adjustmentType: isSerial ? "Positive Adjmt." : "Set Quantity",
+ trackedEntityId: selectedTrackedEntityId || nanoid()
}}
onSubmit={adjustmentModal.onClose}
>
@@ -216,11 +287,14 @@ const InventoryShelves = ({
]}
/>
{(isBatch || isSerial) && (
- <Input
- name="trackedEntityId"
- label="Tracking ID"
- helperText="Globally unique identifier for the item"
- />
+ <>
+ <Hidden name="trackedEntityId" />
+ <Input
+ name="readableId"
+ label={isSerial ? "Serial Number" : "Batch Number"}
+ helperText="A globally unique identifier is generated behind the scenes"
+ />
+ </>
)}
<NumberControlled
name="quantity"
diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
new file mode 100644
index 0000000000..f3baae0b42
--- /dev/null
+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
@@ -0,0 +1,57 @@
+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, redirect } from "react-router";
+import { path } from "~/utils/path";
+import { getEntityLabelData } from "./labels.server";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const result = await getEntityLabelData(client, companyId, id);
+
+ if (result.error) {
+ return new Response(result.error, { status: 404 });
+ }
+
+ const { companySettings, labelItem } = result;
+
+ const url = new URL(request.url);
+ const labelParam = url.searchParams.get("labelSize");
+ const labelSizeId =
+ labelParam || companySettings.data?.productLabelSize || "avery5160";
+
+ const labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ 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} />
+ );
+
+ 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);
+ });
+
+ const headers = new Headers({ "Content-Type": "application/pdf" });
+ return new Response(body, { status: 200, headers });
+}
diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
new file mode 100644
index 0000000000..cfb0590e56
--- /dev/null
+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
@@ -0,0 +1,47 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { generateProductLabelZPL } from "@carbon/documents/zpl";
+import { labelSizes } from "@carbon/utils";
+import { type LoaderFunctionArgs, redirect } from "react-router";
+import { path } from "~/utils/path";
+import { getEntityLabelData } from "./labels.server";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {});
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const result = await getEntityLabelData(client, companyId, id);
+
+ if (result.error) {
+ return new Response(result.error, { status: 404 });
+ }
+
+ const { companySettings, labelItem } = result;
+
+ const url = new URL(request.url);
+ const labelParam = url.searchParams.get("labelSize");
+ const labelSizeId =
+ labelParam || companySettings.data?.productLabelSize || "zebra2x1";
+
+ const labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ throw new Error("Invalid label size");
+ }
+
+ if (!labelSize.zpl) {
+ throw redirect(
+ path.to.file.trackedEntityLabelPdf(id, { labelSize: labelSize.id })
+ );
+ }
+
+ const zplOutput = generateProductLabelZPL(labelItem, labelSize);
+
+ const headers = new Headers({
+ "Content-Type": "application/zpl",
+ "Content-Disposition": `attachment; filename="labels-${id}.zpl"`
+ });
+
+ return new Response(zplOutput, { status: 200, headers });
+}
diff --git a/apps/erp/app/routes/file+/entity+/labels.server.ts b/apps/erp/app/routes/file+/entity+/labels.server.ts
new file mode 100644
index 0000000000..f897111bf8
--- /dev/null
+++ b/apps/erp/app/routes/file+/entity+/labels.server.ts
@@ -0,0 +1,44 @@
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { getTrackedEntity } from "~/modules/inventory";
+import { getCompanySettings } from "~/modules/settings/settings.service";
+
+export async function getEntityLabelData(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ trackedEntityId: string
+) {
+ const [companySettings, trackedEntity] = await Promise.all([
+ getCompanySettings(client, companyId),
+ getTrackedEntity(client, trackedEntityId)
+ ]);
+
+ if (!trackedEntity.data) {
+ return { error: "Tracked entity not found" };
+ }
+
+ const item = await client
+ .from("item")
+ .select("readableId, revision")
+ .eq("id", trackedEntity.data.sourceDocumentId ?? "")
+ .single();
+
+ if (!item.data) {
+ return { error: "Item not found" };
+ }
+
+ const labelItem = {
+ itemId: item.data.readableId,
+ revision: item.data.revision ?? "0",
+ number: trackedEntity.data.readableId ?? "",
+ trackedEntityId: trackedEntityId,
+ quantity: trackedEntity.data.quantity ?? 1,
+ trackingType: trackedEntity.data.quantity > 1 ? "Batch" : "Serial"
+ };
+
+ return {
+ companySettings,
+ labelItem,
+ error: null
+ };
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index e3028b765a..887ddfe173 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -311,6 +311,34 @@ export const path = {
return generatePath(url);
},
+ trackedEntityLabelPdf: (
+ id: string,
+ { labelSize }: { labelSize?: string } = {}
+ ) => {
+ let url = `${file}/entity/${id}/labels.pdf`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
+ trackedEntityLabelZpl: (
+ id: string,
+ { labelSize }: { labelSize?: string } = {}
+ ) => {
+ let url = `${file}/entity/${id}/labels.zpl`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
stockTransfer: (id: string) =>
generatePath(`${file}/stock-transfer/${id}.pdf`),
quote: (id: string) => generatePath(`${file}/quote/${id}.pdf`)
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 9fd0841565..d44d5bd3ae 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -45275,14 +45275,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -49182,14 +49182,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49725,14 +49725,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52880,6 +52880,7 @@ export type Database = {
Returns: {
itemId: string
quantity: number
+ readableId: string
shelfId: string
shelfName: string
trackedEntityId: string
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 9fd0841565..d44d5bd3ae 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -45275,14 +45275,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -49182,14 +49182,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -49725,14 +49725,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["paymentCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["paymentCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -52880,6 +52880,7 @@ export type Database = {
Returns: {
itemId: string
quantity: number
+ readableId: string
shelfId: string
shelfName: string
trackedEntityId: string
diff --git a/packages/database/supabase/migrations/20260101163400_add-readable-id-to-item-quantities-by-tracking-id.sql b/packages/database/supabase/migrations/20260101163400_add-readable-id-to-item-quantities-by-tracking-id.sql
new file mode 100644
index 0000000000..ca5e68e12e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260101163400_add-readable-id-to-item-quantities-by-tracking-id.sql
@@ -0,0 +1,36 @@
+DROP FUNCTION IF EXISTS get_item_quantities_by_tracking_id;
+CREATE OR REPLACE FUNCTION get_item_quantities_by_tracking_id (item_id TEXT, company_id TEXT, location_id TEXT) RETURNS TABLE (
+ "itemId" TEXT,
+ "shelfId" TEXT,
+ "shelfName" TEXT,
+ "trackedEntityId" TEXT,
+ "readableId" TEXT,
+ quantity NUMERIC
+) AS $$
+BEGIN
+ RETURN QUERY
+ SELECT
+ il."itemId",
+ il."shelfId",
+ s."name" AS "shelfName",
+ il."trackedEntityId",
+ te."readableId",
+ SUM(il."quantity") AS "quantity"
+ FROM
+ "itemLedger" il
+ LEFT JOIN
+ "shelf" s ON il."shelfId" = s."id"
+ LEFT JOIN
+ "trackedEntity" te ON il."trackedEntityId" = te."id"
+ WHERE
+ il."itemId" = item_id
+ AND il."companyId" = company_id
+ AND il."locationId" = location_id
+ GROUP BY
+ il."itemId",
+ il."shelfId",
+ s."name",
+ il."trackedEntityId",
+ te."readableId";
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;