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: print tracking labels for jobs

Brad Barbin1b19e45c13e3
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index a7ee62b6e7..a288ffe516 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -510,6 +510,39 @@ export async function getTrackedEntities(
return query;
}
+export async function getTrackedEntitiesByMakeMethodId(
+ client: SupabaseClient<Database>,
+ jobMakeMethodId: string
+) {
+ return client
+ .from("trackedEntity")
+ .select("*")
+ .eq("attributes->>Job Make Method", jobMakeMethodId)
+ .order("createdAt", { ascending: true });
+}
+
+export async function getTrackedEntitiesByOperationId(
+ client: SupabaseClient<Database>,
+ operationId: string
+) {
+ const jobOperation = await client
+ .from("jobOperation")
+ .select("jobMakeMethodId")
+ .eq("id", operationId)
+ .single();
+
+ if (jobOperation.error || !jobOperation.data.jobMakeMethodId)
+ return {
+ data: null,
+ error: jobOperation.error,
+ };
+
+ return getTrackedEntitiesByMakeMethodId(
+ client,
+ jobOperation.data.jobMakeMethodId
+ );
+}
+
export async function insertManualInventoryAdjustment(
client: SupabaseClient<Database>,
inventoryAdjustment: z.infer<typeof inventoryAdjustmentValidator> & {
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
index 041ee97dad..e3e0c965eb 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptHeader.tsx
@@ -1,4 +1,10 @@
-import { Button, HStack, Heading, useDisclosure } from "@carbon/react";
+import {
+ Button,
+ HStack,
+ Heading,
+ SplitButton,
+ useDisclosure,
+} from "@carbon/react";
import { labelSizes } from "@carbon/utils";
import { Link, useParams } from "@remix-run/react";
import {
@@ -7,7 +13,7 @@ import {
LuQrCode,
LuShoppingCart,
} from "react-icons/lu";
-import { SplitButton } from "~/components/SplitButton";
+
import { usePermissions, useRouteData } from "~/hooks";
import type { ItemTracking, Receipt, ReceiptLine } from "~/modules/inventory";
import { ReceiptPostModal, ReceiptStatus } from "~/modules/inventory";
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 03401789a3..a39827b240 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -20,6 +20,7 @@ import {
ModalTitle,
NumberField,
NumberInput,
+ SplitButton,
toast,
Tooltip,
TooltipContent,
@@ -65,7 +66,6 @@ import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
import { BatchPropertiesFields } from "../Batches/BatchPropertiesFields";
import { labelSizes } from "@carbon/utils";
-import { SplitButton } from "~/components/SplitButton";
import BatchPropertiesConfig from "../Batches/BatchPropertiesConfig";
const ReceiptLines = () => {
@@ -986,7 +986,7 @@ function Shelf({
isReadOnly: boolean;
onChange: (shelf: string) => void;
}) {
- const { options, data } = useShelves(locationId ?? undefined);
+ const { options } = useShelves(locationId ?? undefined);
const newShelfModal = useDisclosure();
const [created, setCreated] = useState<string>("");
const triggerRef = useRef<HTMLButtonElement>(null);
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
index 745d1508d3..28c0ad0bb8 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentHeader.tsx
@@ -1,4 +1,10 @@
-import { Button, HStack, Heading, useDisclosure } from "@carbon/react";
+import {
+ Button,
+ HStack,
+ Heading,
+ SplitButton,
+ useDisclosure,
+} from "@carbon/react";
import { Link, useParams } from "@remix-run/react";
import { LuCheckCheck, LuBarcode, LuQrCode } from "react-icons/lu";
import { usePermissions, useRouteData } from "~/hooks";
@@ -9,7 +15,6 @@ import ShipmentPostModal from "./ShipmentPostModal";
import { RiProgress8Line } from "react-icons/ri";
import type { TrackedEntityAttributes } from "@carbon/utils";
import ShipmentStatus from "./ShipmentStatus";
-import { SplitButton } from "~/components/SplitButton";
import { labelSizes } from "@carbon/utils";
const ShipmentHeader = () => {
diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
index 6e3817f5f8..a66296feb8 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx
@@ -14,6 +14,7 @@ import {
Modal,
NumberField,
NumberInput,
+ SplitButton,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -62,7 +63,6 @@ import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { ValidatedForm, Submit, Number } from "@carbon/form";
import type { TrackedEntityAttributes } from "@carbon/utils";
-import { SplitButton } from "~/components/SplitButton";
import { labelSizes } from "@carbon/utils";
import { useCarbon } from "@carbon/auth";
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 4a7ee0eb40..eefe8448ae 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -229,6 +229,17 @@ export async function getJobsList(
.order("jobId");
}
+export async function getJobMakeMethodById(
+ client: SupabaseClient<Database>,
+ jobMakeMethodId: string
+) {
+ return client
+ .from("jobMakeMethod")
+ .select("*")
+ .eq("id", jobMakeMethodId)
+ .single();
+}
+
export async function getJobMaterialsWithQuantityOnHand(
client: SupabaseClient<Database>,
jobId: string,
diff --git a/apps/erp/app/modules/production/types.ts b/apps/erp/app/modules/production/types.ts
index 5a04348cc6..d040d45d72 100644
--- a/apps/erp/app/modules/production/types.ts
+++ b/apps/erp/app/modules/production/types.ts
@@ -1,6 +1,7 @@
import type {
getActiveProductionEvents,
getJob,
+ getJobMakeMethodById,
getJobMaterialsWithQuantityOnHand,
getJobMethodTree,
getJobOperations,
@@ -19,6 +20,10 @@ export type ActiveProductionEvent = NonNullable<
export type Job = NonNullable<Awaited<ReturnType<typeof getJob>>["data"]>;
+export type JobMakeMethod = NonNullable<
+ Awaited<ReturnType<typeof getJobMakeMethodById>>["data"]
+>;
+
export type JobMaterial = NonNullable<
Awaited<ReturnType<typeof getJobMaterialsWithQuantityOnHand>>["data"]
>[number];
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index 181a25c784..e51748523d 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -15,6 +15,7 @@ import {
ModalFooter,
ModalHeader,
ModalTitle,
+ SplitButton,
Tabs,
TabsContent,
TabsList,
@@ -31,12 +32,16 @@ import {
useLocation,
useParams,
} from "@remix-run/react";
-import type { PostgrestResponse } from "@supabase/supabase-js";
+import type {
+ PostgrestResponse,
+ PostgrestSingleResponse,
+} from "@supabase/supabase-js";
import { Suspense, useEffect, useMemo, useState } from "react";
import {
LuGitBranch,
LuGitFork,
LuGitMerge,
+ LuQrCode,
LuSquareStack,
LuTriangleAlert,
} from "react-icons/lu";
@@ -59,9 +64,14 @@ import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType } from "~/modules/shared/types";
import { path } from "~/utils/path";
import { getJobMethodValidator } from "../../production.models";
-import type { Job, JobMaterial, JobMethod } from "../../types";
-
-const JobBreadcrumbs = () => {
+import type { Job, JobMakeMethod, JobMaterial, JobMethod } from "../../types";
+import { labelSizes } from "@carbon/utils";
+
+const JobMakeMethodTools = ({
+ makeMethod,
+}: {
+ makeMethod?: Promise<PostgrestSingleResponse<JobMakeMethod>>;
+}) => {
const permissions = usePermissions();
const { jobId, methodId, materialId } = useParams();
if (!jobId) throw new Error("jobId not found");
@@ -156,6 +166,36 @@ const JobBreadcrumbs = () => {
});
};
+ 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"
+ );
+ }
+ };
+
return (
<>
{permissions.can("update", "production") &&
@@ -205,6 +245,40 @@ const JobBreadcrumbs = () => {
</Link>
</MenubarItem>
)}
+ {makeMethod && (
+ <Suspense fallback={null}>
+ <Await resolve={makeMethod}>
+ {(resolvedMakeMethod) =>
+ resolvedMakeMethod.data?.requiresSerialTracking ||
+ resolvedMakeMethod.data?.requiresBatchTracking ? (
+ <SplitButton
+ dropdownItems={labelSizes.map((size) => ({
+ label: size.name,
+ onClick: () =>
+ navigateToTrackingLabels(
+ resolvedMakeMethod.data?.id,
+ !!size.zpl,
+ {
+ labelSize: size.id,
+ }
+ ),
+ }))}
+ leftIcon={<LuQrCode />}
+ variant="ghost"
+ onClick={() =>
+ navigateToTrackingLabels(
+ resolvedMakeMethod.data?.id,
+ false
+ )
+ }
+ >
+ Tracking Labels
+ </SplitButton>
+ ) : null
+ }
+ </Await>
+ </Suspense>
+ )}
</HStack>
</HStack>
</Menubar>
@@ -419,7 +493,7 @@ const JobBreadcrumbs = () => {
);
};
-export default JobBreadcrumbs;
+export default JobMakeMethodTools;
function QuoteLineForm() {
const quoteFetcher =
diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
new file mode 100644
index 0000000000..daf50532a2
--- /dev/null
+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
@@ -0,0 +1,106 @@
+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 { redirect, type LoaderFunctionArgs } from "@vercel/remix";
+
+import type { TrackedEntityAttributes } from "@carbon/utils";
+import { path } from "~/utils/path";
+
+import { getCompanySettings } from "~/modules/settings/settings.service";
+import { getTrackedEntitiesByMakeMethodId } from "~/modules/inventory";
+
+export const config = { runtime: "nodejs" };
+
+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 [companySettings, trackedEntities] = await Promise.all([
+ getCompanySettings(client, companyId),
+ getTrackedEntitiesByMakeMethodId(client, id),
+ ]);
+
+ // Get the label size from query params or default to avery5160
+ 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";
+
+ // Find the label size configuration
+ let labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ 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
+ if (trackedEntityIdParam) {
+ filteredTracking =
+ filteredTracking?.filter(
+ (tracking) => tracking.id === trackedEntityIdParam
+ ) ?? [];
+ }
+
+ const items = filteredTracking
+ ?.map((tracking) => ({
+ itemId: tracking.sourceDocumentReadableId ?? "",
+ revision: "0",
+ number:
+ (tracking.attributes as TrackedEntityAttributes)?.["Serial Number"] ??
+ (tracking.attributes as TrackedEntityAttributes)?.["Batch Number"] ??
+ "",
+ trackedEntityId: tracking.id,
+ quantity: tracking.quantity,
+ trackingType: tracking.quantity > 1 ? "Batch" : "Serial",
+ }))
+ .sort((a, b) => {
+ if (a.itemId === b.itemId) {
+ return a.number.localeCompare(b.number);
+ }
+ return a.itemId.localeCompare(b.itemId);
+ });
+
+ if (!Array.isArray(items) || items.length === 0) {
+ return new Response(
+ `No items found for operation ${id}${
+ trackedEntityIdParam
+ ? ` and tracked entity ${trackedEntityIdParam}`
+ : ""
+ }`,
+ { 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);
+ });
+
+ const headers = new Headers({ "Content-Type": "application/pdf" });
+ return new Response(body, { status: 200, headers });
+}
diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
new file mode 100644
index 0000000000..c4c3392839
--- /dev/null
+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
@@ -0,0 +1,103 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { generateProductLabelZPL } from "@carbon/documents/zpl";
+import { labelSizes } from "@carbon/utils";
+import type { TrackedEntityAttributes } from "@carbon/utils";
+import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import { getTrackedEntitiesByMakeMethodId } from "~/modules/inventory";
+import { getCompanySettings } from "~/modules/settings";
+
+import { path } from "~/utils/path";
+
+export const config = { runtime: "nodejs" };
+
+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 [companySettings, trackedEntities] = await Promise.all([
+ getCompanySettings(client, companyId),
+ 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";
+
+ // Find the label size configuration
+ let labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ throw new Error("Invalid label size");
+ }
+
+ if (!labelSize.zpl) {
+ throw redirect(
+ path.to.file.operationLabelsPdf(id, {
+ labelSize: labelSize.id,
+ trackedEntityId: trackedEntityIdParam ?? undefined,
+ })
+ );
+ }
+
+ let filteredTracking = trackedEntities.data;
+
+ // Filter by trackedEntityId if provided
+ if (trackedEntityIdParam) {
+ filteredTracking =
+ filteredTracking?.filter(
+ (tracking) => tracking.id === trackedEntityIdParam
+ ) ?? [];
+ }
+
+ const items = filteredTracking
+ ?.map((tracking) => ({
+ itemId: tracking.sourceDocumentReadableId ?? "",
+ revision: "0",
+ number:
+ (tracking.attributes as TrackedEntityAttributes)?.["Serial Number"] ??
+ (tracking.attributes as TrackedEntityAttributes)?.["Batch Number"] ??
+ "",
+ trackedEntityId: tracking.id,
+ quantity: tracking.quantity,
+ trackingType: tracking.quantity > 1 ? "Batch" : "Serial",
+ }))
+ .sort((a, b) => {
+ if (a.itemId === b.itemId) {
+ return a.number.localeCompare(b.number);
+ }
+ return a.itemId.localeCompare(b.itemId);
+ });
+
+ if (!Array.isArray(items) || items.length === 0) {
+ return new Response(
+ `No items found for operation ${id}${
+ trackedEntityIdParam
+ ? ` and tracked entity ${trackedEntityIdParam}`
+ : ""
+ }`,
+ { status: 404 }
+ );
+ }
+
+ if (!labelSize?.zpl) {
+ throw new Error("Invalid label size or missing ZPL configuration");
+ }
+
+ // Generate ZPL for each item
+ const zplCommands = items.map((item) =>
+ generateProductLabelZPL(item, labelSize)
+ );
+ const zplOutput = zplCommands.join("\n");
+
+ 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/x+/job+/$jobId.make.$methodId.$materialId.tsx b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
index 0bff0cd77b..af43b87795 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
@@ -17,6 +17,7 @@ import { CadModel } from "~/components";
import { usePermissions, useRouteData } from "~/hooks";
import type { Job } from "~/modules/production";
import {
+ getJobMakeMethodById,
getJobMaterial,
getJobMaterialsByMethodId,
getJobOperationsByMethodId,
@@ -36,6 +37,7 @@ import { usePanels } from "~/components/Layout";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "production",
+ bypassRls: true,
});
const { jobId, methodId, materialId } = params;
@@ -111,6 +113,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
jobMakeMethodId: o.jobMakeMethodId ?? methodId,
workInstruction: o.workInstruction as JSONContent | null,
})) ?? [],
+ makeMethod: getJobMakeMethodById(client, methodId),
productionData: getProductionDataByOperations(
client,
operations?.data?.map((o) => o.id)
@@ -121,6 +124,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function JobMakeMethodRoute() {
+ const { makeMethod } = useLoaderData<typeof loader>();
const permissions = usePermissions();
const { methodId, jobId } = useParams();
if (!methodId) throw new Error("Could not find methodId");
@@ -139,7 +143,7 @@ export default function JobMakeMethodRoute() {
return (
<VStack spacing={2} className="p-2">
- <JobMakeMethodTools />
+ <JobMakeMethodTools makeMethod={makeMethod} />
<JobMaterialForm
key={material.id}
initialValues={material}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx b/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
index 6f85dce072..75f2a538fe 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
@@ -17,6 +17,7 @@ import { CadModel } from "~/components";
import { usePermissions, useRouteData } from "~/hooks";
import type { Job } from "~/modules/production";
import {
+ getJobMakeMethodById,
getJobMaterialsByMethodId,
getJobOperationsByMethodId,
getProductionDataByOperations,
@@ -34,6 +35,7 @@ import { usePanels } from "~/components/Layout";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "production",
+ bypassRls: true,
});
const { jobId, methodId } = params;
@@ -85,6 +87,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
jobMakeMethodId: o.jobMakeMethodId ?? methodId,
workInstruction: o.workInstruction as JSONContent,
})) ?? [],
+ makeMethod: getJobMakeMethodById(client, methodId),
productionData: getProductionDataByOperations(
client,
operations?.data?.map((o) => o.id)
@@ -94,6 +97,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function JobMakeMethodRoute() {
+ const { makeMethod } = useLoaderData<typeof loader>();
const permissions = usePermissions();
const { methodId, jobId } = useParams();
if (!methodId) throw new Error("Could not find methodId");
@@ -114,7 +118,7 @@ export default function JobMakeMethodRoute() {
return (
<div className="h-[calc(100dvh-49px)] w-full items-start overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
<VStack spacing={2} className="p-2">
- <JobMakeMethodTools />
+ <JobMakeMethodTools makeMethod={makeMethod} />
<JobBillOfProcess
key={`bop:${methodId}`}
jobMakeMethodId={methodId}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 3ca8088a30..247400338d 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -95,6 +95,42 @@ export const path = {
},
file: {
cadModel: (id: string) => generatePath(`${file}/model/${id}`),
+ operationLabelsPdf: (
+ id: string,
+ {
+ labelSize,
+ trackedEntityId,
+ }: { labelSize?: string; trackedEntityId?: string } = {}
+ ) => {
+ let url = `${file}/operation/${id}/labels.pdf`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+ if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
+ operationLabelsZpl: (
+ id: string,
+ {
+ labelSize,
+ trackedEntityId,
+ }: { labelSize?: string; trackedEntityId?: string } = {}
+ ) => {
+ let url = `${file}/operation/${id}/labels.zpl`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+ if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
previewImage: (bucket: string, path: string) =>
generatePath(`${file}/preview/image?file=${bucket}/${path}`),
previewFile: (path: string) => generatePath(`${file}/preview/${path}`),
diff --git a/apps/mes/app/components/JobOperation.tsx b/apps/mes/app/components/JobOperation.tsx
index f2179bccee..683341b553 100644
--- a/apps/mes/app/components/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation.tsx
@@ -64,6 +64,7 @@ import {
NumberInputStepper,
Copy,
Switch,
+ SplitButton,
} from "@carbon/react";
import { generateHTML } from "@carbon/react/Editor";
import {
@@ -134,6 +135,7 @@ import {
formatDateTime,
formatDurationMilliseconds,
formatRelativeTime,
+ labelSizes,
} from "@carbon/utils";
import {
getLocalTimeZone,
@@ -168,6 +170,7 @@ import {
LuHardHat,
LuList,
LuPaperclip,
+ LuPrinter,
LuQrCode,
LuSend,
LuTimer,
@@ -317,6 +320,37 @@ 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"
+ );
+ }
+ };
+
return (
<>
<Tabs
@@ -969,14 +1003,27 @@ export const JobOperation = ({
<div className="flex flex-col gap-4 p-4 lg:p-6 w-full">
<HStack className="justify-between w-full">
<Heading size="h3">Serial Numbers</Heading>
- <HStack>
- <Button variant="secondary" leftIcon={<LuQrCode />}>
- Tracking Labels
- </Button>
- <Button variant="secondary" leftIcon={<LuBarcode />}>
- Scan
- </Button>
- </HStack>
+ {trackedEntities?.length > 0 && (
+ <HStack>
+ <SplitButton
+ leftIcon={<LuQrCode />}
+ 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)}
+ >
+ Tracking Labels
+ </SplitButton>
+ <Button variant="secondary" leftIcon={<LuBarcode />}>
+ Scan
+ </Button>
+ </HStack>
+ )}
</HStack>
<Table className="w-full">
@@ -991,8 +1038,9 @@ export const JobOperation = ({
<Tr>
<Td
colSpan={24}
- className="py-8 text-red-500 text-center"
+ className="py-8 text-muted-foreground text-center"
>
+ <LuTriangleAlert className="text-red-500 size-4" />
No serial numbers
</Td>
</Tr>
@@ -1004,11 +1052,22 @@ export const JobOperation = ({
{entity.id === trackedEntityId && (
<LuCheck className="text-emerald-500 size-4" />
)}
+ <Copy text={entity.id} />
</Td>
<Td className="text-right">
<div className="flex justify-end gap-2">
- <Copy text={entity.id} />
+ <IconButton
+ aria-label="Print Label"
+ size="sm"
+ icon={<LuPrinter />}
+ variant="secondary"
+ onClick={() => {
+ navigateToTrackingLabels(false, {
+ trackedEntityId: entity.id,
+ });
+ }}
+ />
<Button
variant="secondary"
size="sm"
diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
new file mode 100644
index 0000000000..2c8bbea902
--- /dev/null
+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
@@ -0,0 +1,105 @@
+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 { redirect, type LoaderFunctionArgs } from "@vercel/remix";
+
+import type { TrackedEntityAttributes } from "@carbon/utils";
+import { path } from "~/utils/path";
+import { getCompanySettings } from "~/services/inventory.service";
+import { getTrackedEntitiesByOperationId } from "~/services/operations.service";
+
+export const config = { runtime: "nodejs" };
+
+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 [companySettings, trackedEntities] = await Promise.all([
+ getCompanySettings(client, companyId),
+ getTrackedEntitiesByOperationId(client, id),
+ ]);
+
+ // Get the label size from query params or default to avery5160
+ 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";
+
+ // Find the label size configuration
+ let labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ 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
+ if (trackedEntityIdParam) {
+ filteredTracking =
+ filteredTracking?.filter(
+ (tracking) => tracking.id === trackedEntityIdParam
+ ) ?? [];
+ }
+
+ const items = filteredTracking
+ ?.map((tracking) => ({
+ itemId: tracking.sourceDocumentReadableId ?? "",
+ revision: "0",
+ number:
+ (tracking.attributes as TrackedEntityAttributes)?.["Serial Number"] ??
+ (tracking.attributes as TrackedEntityAttributes)?.["Batch Number"] ??
+ "",
+ trackedEntityId: tracking.id,
+ quantity: tracking.quantity,
+ trackingType: tracking.quantity > 1 ? "Batch" : "Serial",
+ }))
+ .sort((a, b) => {
+ if (a.itemId === b.itemId) {
+ return a.number.localeCompare(b.number);
+ }
+ return a.itemId.localeCompare(b.itemId);
+ });
+
+ if (!Array.isArray(items) || items.length === 0) {
+ return new Response(
+ `No items found for operation ${id}${
+ trackedEntityIdParam
+ ? ` and tracked entity ${trackedEntityIdParam}`
+ : ""
+ }`,
+ { 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);
+ });
+
+ const headers = new Headers({ "Content-Type": "application/pdf" });
+ return new Response(body, { status: 200, headers });
+}
diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
new file mode 100644
index 0000000000..b6b56cc92e
--- /dev/null
+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
@@ -0,0 +1,102 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { generateProductLabelZPL } from "@carbon/documents/zpl";
+import { labelSizes } from "@carbon/utils";
+import type { TrackedEntityAttributes } from "@carbon/utils";
+import { redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import { getCompanySettings } from "~/services/inventory.service";
+import { getTrackedEntitiesByMakeMethodId } from "~/services/operations.service";
+import { path } from "~/utils/path";
+
+export const config = { runtime: "nodejs" };
+
+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 [companySettings, trackedEntities] = await Promise.all([
+ getCompanySettings(client, companyId),
+ 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";
+
+ // Find the label size configuration
+ let labelSize = labelSizes.find((size) => size.id === labelSizeId);
+
+ if (!labelSize) {
+ throw new Error("Invalid label size");
+ }
+
+ if (!labelSize.zpl) {
+ throw redirect(
+ path.to.file.operationLabelsPdf(id, {
+ labelSize: labelSize.id,
+ trackedEntityId: trackedEntityIdParam ?? undefined,
+ })
+ );
+ }
+
+ let filteredTracking = trackedEntities.data;
+
+ // Filter by trackedEntityId if provided
+ if (trackedEntityIdParam) {
+ filteredTracking =
+ filteredTracking?.filter(
+ (tracking) => tracking.id === trackedEntityIdParam
+ ) ?? [];
+ }
+
+ const items = filteredTracking
+ ?.map((tracking) => ({
+ itemId: tracking.sourceDocumentReadableId ?? "",
+ revision: "0",
+ number:
+ (tracking.attributes as TrackedEntityAttributes)?.["Serial Number"] ??
+ (tracking.attributes as TrackedEntityAttributes)?.["Batch Number"] ??
+ "",
+ trackedEntityId: tracking.id,
+ quantity: tracking.quantity,
+ trackingType: tracking.quantity > 1 ? "Batch" : "Serial",
+ }))
+ .sort((a, b) => {
+ if (a.itemId === b.itemId) {
+ return a.number.localeCompare(b.number);
+ }
+ return a.itemId.localeCompare(b.itemId);
+ });
+
+ if (!Array.isArray(items) || items.length === 0) {
+ return new Response(
+ `No items found for operation ${id}${
+ trackedEntityIdParam
+ ? ` and tracked entity ${trackedEntityIdParam}`
+ : ""
+ }`,
+ { status: 404 }
+ );
+ }
+
+ if (!labelSize?.zpl) {
+ throw new Error("Invalid label size or missing ZPL configuration");
+ }
+
+ // Generate ZPL for each item
+ const zplCommands = items.map((item) =>
+ generateProductLabelZPL(item, labelSize)
+ );
+ const zplOutput = zplCommands.join("\n");
+
+ 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/mes/app/services/inventory.service.ts b/apps/mes/app/services/inventory.service.ts
index 849f766c94..631cfc1872 100644
--- a/apps/mes/app/services/inventory.service.ts
+++ b/apps/mes/app/services/inventory.service.ts
@@ -28,6 +28,17 @@ export async function getBatchNumbersForItem(
.gte("quantity", 1);
}
+export async function getCompanySettings(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("companySettings")
+ .select("*")
+ .eq("id", companyId)
+ .single();
+}
+
export async function getSerialNumbersForItem(
client: SupabaseClient<Database>,
args: {
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index a138bee210..cb465e2e1e 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -414,6 +414,28 @@ export async function getTrackedEntitiesByMakeMethodId(
.order("createdAt", { ascending: true });
}
+export async function getTrackedEntitiesByOperationId(
+ client: SupabaseClient<Database>,
+ operationId: string
+) {
+ const jobOperation = await client
+ .from("jobOperation")
+ .select("jobMakeMethodId")
+ .eq("id", operationId)
+ .single();
+
+ if (jobOperation.error || !jobOperation.data.jobMakeMethodId)
+ return {
+ data: null,
+ error: jobOperation.error,
+ };
+
+ return getTrackedEntitiesByMakeMethodId(
+ client,
+ jobOperation.data.jobMakeMethodId
+ );
+}
+
export async function getTrackedInputs(
client: SupabaseClient<Database>,
trackedEntityId?: string
diff --git a/apps/mes/app/utils/path.ts b/apps/mes/app/utils/path.ts
index 176d7845cb..c3f7ea3528 100644
--- a/apps/mes/app/utils/path.ts
+++ b/apps/mes/app/utils/path.ts
@@ -17,6 +17,42 @@ export const path = {
generatePath(`${api}/serial-numbers?itemId=${itemId}`),
},
file: {
+ operationLabelsPdf: (
+ id: string,
+ {
+ labelSize,
+ trackedEntityId,
+ }: { labelSize?: string; trackedEntityId?: string } = {}
+ ) => {
+ let url = `${file}/operation/${id}/labels.pdf`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+ if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
+ operationLabelsZpl: (
+ id: string,
+ {
+ labelSize,
+ trackedEntityId,
+ }: { labelSize?: string; trackedEntityId?: string } = {}
+ ) => {
+ let url = `${file}/operation/${id}/labels.zpl`;
+ const params = new URLSearchParams();
+
+ if (labelSize) params.append("labelSize", labelSize);
+ if (trackedEntityId) params.append("trackedEntityId", trackedEntityId);
+
+ const queryString = params.toString();
+ if (queryString) url += `?${queryString}`;
+
+ return generatePath(url);
+ },
previewImage: (bucket: string, path: string) =>
generatePath(`${file}/preview/image?file=${bucket}/${path}`),
previewFile: (path: string) => generatePath(`${file}/preview/${path}`),
diff --git a/apps/mes/vite.config.ts b/apps/mes/vite.config.ts
index fd0fa7156c..5421b2e974 100644
--- a/apps/mes/vite.config.ts
+++ b/apps/mes/vite.config.ts
@@ -52,10 +52,6 @@ export default defineConfig({
],
resolve: {
alias: {
- "@carbon/documents": path.resolve(
- __dirname,
- "../../packages/documents/src/index.tsx"
- ),
"@carbon/utils": path.resolve(
__dirname,
"../../packages/utils/src/index.ts"
@@ -64,10 +60,6 @@ export default defineConfig({
__dirname,
"../../packages/form/src/index.tsx"
),
- "@carbon/logger": path.resolve(
- __dirname,
- "../../packages/logger/src/index.ts"
- ),
},
},
});
diff --git a/apps/starter/vite.config.ts b/apps/starter/vite.config.ts
index 55b0f9ed01..ad371e1985 100644
--- a/apps/starter/vite.config.ts
+++ b/apps/starter/vite.config.ts
@@ -52,10 +52,6 @@ export default defineConfig({
],
resolve: {
alias: {
- "@carbon/documents": path.resolve(
- __dirname,
- "../../packages/documents/src/index.tsx"
- ),
"@carbon/utils": path.resolve(
__dirname,
"../../packages/utils/src/index.ts"
@@ -64,10 +60,6 @@ export default defineConfig({
__dirname,
"../../packages/form/src/index.tsx"
),
- "@carbon/logger": path.resolve(
- __dirname,
- "../../packages/logger/src/index.ts"
- ),
},
},
});
diff --git a/packages/auth/src/lib/supabase/client.ts b/packages/auth/src/lib/supabase/client.ts
index 0f40d013e5..e63e2f5c76 100644
--- a/packages/auth/src/lib/supabase/client.ts
+++ b/packages/auth/src/lib/supabase/client.ts
@@ -30,22 +30,22 @@ const getCarbonClient = (supabaseKey: string, accessToken?: string) => {
return client;
};
-/**
- * Provides a Carbon Client for the logged in user or get back a public and safe client without admin privileges
- *
- * It's a per request scoped client to prevent access token leaking over multiple concurrent requests and from different users.
- *
- */
+export const getCarbonAPIKeyClient = (apiKey: string) => {
+ const client = createClient<Database>(SUPABASE_API_URL, SUPABASE_ANON_PUBLIC, {
+ global: {
+ headers: {
+ "carbon-key": apiKey,
+ },
+ },
+ });
+
+ return client;
+};
+
export const getCarbon = (accessToken?: string) => {
return getCarbonClient(SUPABASE_ANON_PUBLIC, accessToken);
};
-/**
- * Provides a Carbon Admin Client with full admin privileges
- *
- * It's a per request scoped client, to prevent access token leaking`.
- *
- */
export const getCarbonServiceRole = () => {
if (isBrowser)
throw new Error(
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index 7db9b5b3a9..0fa4270278 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -17,6 +17,7 @@ import { getUserClaims } from "./users.server";
import type { AuthSession } from "../types";
import { error } from "../utils/result";
+import { getCarbonAPIKeyClient } from "../lib/supabase/client";
export async function createEmailAuthAccount(
email: string,
@@ -61,6 +62,11 @@ export async function getAuthAccountByAccessToken(accessToken: string) {
return data.user;
}
+function getCompanyIdFromAPIKey(apiKey: string) {
+ const serviceRole = getCarbonServiceRole();
+ return serviceRole.from("apiKey").select("companyId, createdBy").eq("key", apiKey).single();
+}
+
function makeAuthSession(
supabaseSession: SupabaseAuthSession | null,
companyId: string
@@ -101,6 +107,23 @@ export async function requirePermissions(
email: string;
userId: string;
}> {
+ const apiKey = request.headers.get("carbon-key");
+ if (apiKey) {
+ const company = await getCompanyIdFromAPIKey(apiKey);
+ if (company.data) {
+ const companyId = company.data.companyId;
+ const userId = company.data.createdBy;
+ const client = getCarbonAPIKeyClient(apiKey);
+
+ return {
+ client,
+ companyId,
+ userId,
+ email: "",
+ };
+ }
+ }
+
const { accessToken, companyId, email, userId } = await requireAuthSession(
request
);
diff --git a/packages/documents/src/pdf/ProductLabelPDF.tsx b/packages/documents/src/pdf/ProductLabelPDF.tsx
index f2dd0851fe..98f47f2956 100644
--- a/packages/documents/src/pdf/ProductLabelPDF.tsx
+++ b/packages/documents/src/pdf/ProductLabelPDF.tsx
@@ -152,7 +152,7 @@ const ProductLabelPDF = ({ items, labelSize }: ProductLabelProps) => {
</Text>
)}
- {item.trackingType === "Serial" && (
+ {item.trackingType === "Serial" && item.number && (
<Text
style={{
...tw("mb-1"),
@@ -162,7 +162,7 @@ const ProductLabelPDF = ({ items, labelSize }: ProductLabelProps) => {
S/N: {item.number}
</Text>
)}
- {item.trackingType === "Batch" && (
+ {item.trackingType === "Batch" && item.number && (
<Text
style={{
...tw("mb-1"),
diff --git a/apps/erp/app/components/SplitButton.tsx b/packages/react/src/SplitButton.tsx
similarity index 91%
rename from apps/erp/app/components/SplitButton.tsx
rename to packages/react/src/SplitButton.tsx
index 848e912855..f1d2b083b6 100644
--- a/apps/erp/app/components/SplitButton.tsx
+++ b/packages/react/src/SplitButton.tsx
@@ -1,14 +1,9 @@
-import {
- Button,
- cn,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuIcon,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@carbon/react";
+
import { LuChevronDown } from "react-icons/lu";
import { forwardRef } from "react";
+import { Button } from "./Button";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuIcon, DropdownMenuItem, DropdownMenuTrigger } from "./Dropdown";
+import { cn } from "./utils/cn";
interface SplitButtonProps {
children: React.ReactNode;
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index 6e578df3e8..bd32d241bb 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -294,6 +294,7 @@ import type {
import { cn } from "./utils/cn";
import { getValidChildren, reactNodeToString } from "./utils/react";
import Copy from "./Copy";
+import { SplitButton } from "./SplitButton";
export * from "./hooks";
export {
@@ -520,6 +521,7 @@ export {
Skeleton,
Slider,
Spinner,
+ SplitButton,
Status,
Switch,
Table,