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.

fix(mes): auto-print the first-operation label on every completion path (#2047)

Brad Barbin79cb3619f989
diff --git a/.claude/rules/printing-system.md b/.claude/rules/printing-system.md
index 9a05018deb..2f684c5e40 100644
--- a/.claude/rules/printing-system.md
+++ b/.claude/rules/printing-system.md
@@ -126,7 +126,12 @@ After a business event, code checks `getCachedPrinterConfig(...).autoPrint` (def
wrapped in try/catch that never blocks the parent op, then `trigger("print-job", ...)`:
- Receipt post `postReceipt` (receiving); Shipment post `postShipment` (shipping; also prints
`Split` entities); Stock-transfer split, from the line pick operations (Split + Entity reprint) —
- all in `apps/erp/app/modules/inventory/inventory.server.ts`; MES first-operation completion `apps/mes/app/routes/x+/complete.tsx` (workCenter).
+ all in `apps/erp/app/modules/inventory/inventory.server.ts`; MES first-operation completion of a serial or batch unit,
+ `autoPrintFirstOperationLabel` (`apps/mes/app/services/printing.server.ts`, workCenter), called by
+ every completion path: the Complete form (`x+/complete.tsx`), the QR / kanban Complete scan
+ (`x+/end.$operationId.tsx`), and inspection lots (`postSerialCompletions` / `postBulkCompletion`
+ in `services/quality.server.ts`). A new path that completes a tracked unit must call it too, or that
+ path mints serials with no label.
## Gotchas
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 942dfc41ea..a6d4704793 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -7,9 +7,7 @@ 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 { getLogger } from "@carbon/logger";
-import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
import { redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
@@ -20,78 +18,13 @@ import {
finishJobOperation,
insertProductionQuantity
} from "~/services/operations.service";
+import { autoPrintFirstOperationLabel } from "~/services/printing.server";
import { checkStrictBackflush } from "~/services/quality.server";
import { readOrigin, withOrigin } from "~/utils/origin";
import { path } from "~/utils/path";
const log = getLogger("mes");
-/**
- * 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)
- .eq("companyId", companyId)
- .maybeSingle();
- // Service-role read: an entity outside the caller's company prints nothing.
- if (!entity) return;
-
- 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)
- .eq("companyId", companyId)
- .maybeSingle();
- 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) {
- log.error("Auto-print failed", { error: e });
- }
-}
-
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {});
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsx
index b12206606a..2d8697b021 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -20,6 +20,7 @@ import {
insertProductionQuantity,
isSerialEntityIncompleteForOperation
} from "~/services/operations.service";
+import { autoPrintFirstOperationLabel } from "~/services/printing.server";
import { checkStrictBackflush } from "~/services/quality.server";
import { path } from "~/utils/path";
@@ -226,7 +227,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
- const newTrackedEntityId = response.data?.newTrackedEntityId;
+ const newTrackedEntityId = response.data?.newTrackedEntityId as
+ | string
+ | undefined;
+
+ // Auto-print label on first operation only (entity was just minted).
+ // Print the unit just completed, not the new reserved one.
+ const printEntityId = trackedEntityId || newTrackedEntityId;
+ if (printEntityId) {
+ await autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId: printEntityId,
+ workCenterId: jobOperation.data.workCenterId ?? undefined,
+ companyId,
+ userId
+ });
+ }
if (newTrackedEntityId) {
return redirect(
@@ -306,6 +322,17 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
})
);
}
+
+ // Auto-print label on first operation only (batch entity was just minted)
+ if (trackedEntityId) {
+ await autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId,
+ workCenterId: jobOperation.data.workCenterId ?? undefined,
+ companyId,
+ userId
+ });
+ }
}
} else {
const check = await checkStrictBackflush({
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
index 46319ebc8a..bd61e9c94b 100644
--- a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
@@ -129,6 +129,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const completions = await postSerialCompletions(serviceRole, {
candidates,
jobOperationId: state.jobOperationId,
+ workCenterId: state.operation.workCenterId,
inspectionId: id,
eventIds,
companyId,
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
index 9ba34e5cc4..fabc33f61d 100644
--- a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
@@ -258,6 +258,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const completions = await postSerialCompletions(serviceRole, {
candidates: completionCandidates,
jobOperationId: state.jobOperationId,
+ workCenterId: state.operation.workCenterId,
inspectionId: id,
eventIds,
companyId,
diff --git a/apps/mes/app/services/printing.server.ts b/apps/mes/app/services/printing.server.ts
new file mode 100644
index 0000000000..56c3ec4864
--- /dev/null
+++ b/apps/mes/app/services/printing.server.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { trigger } from "@carbon/jobs";
+import { getLogger } from "@carbon/logger";
+import { getCachedPrinterConfig } from "@carbon/printing/printing.server";
+
+type ServiceRole = Awaited<ReturnType<typeof getCarbonServiceRole>>;
+
+const log = getLogger("mes", "printing");
+
+/**
+ * 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.
+ *
+ * Shared by every MES path that completes a tracked unit — the Complete
+ * form (`x+/complete.tsx`) and the QR/kanban scan (`x+/end.$operationId.tsx`)
+ * — so a label prints however the operator completes it.
+ */
+export async function autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId,
+ workCenterId,
+ companyId,
+ userId
+}: {
+ serviceRole: ServiceRole;
+ trackedEntityId: string;
+ workCenterId: string | undefined;
+ companyId: string;
+ userId: string;
+}) {
+ try {
+ const { data: entity } = await serviceRole
+ .from("trackedEntity")
+ .select("attributes")
+ .eq("id", trackedEntityId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ // Service-role read: an entity outside the caller's company prints nothing.
+ if (!entity) return;
+
+ 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)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ 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) {
+ log.error("Auto-print failed", { companyId, trackedEntityId, error: e });
+ }
+}
diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.ts
index 93a06cdcb7..2eb58dfce1 100644
--- a/apps/mes/app/services/quality.server.ts
+++ b/apps/mes/app/services/quality.server.ts
@@ -16,6 +16,7 @@ import {
getTrackedEntitiesByMakeMethodId,
insertProductionQuantity
} from "~/services/operations.service";
+import { autoPrintFirstOperationLabel } from "~/services/printing.server";
import {
getInspection,
getInspectionMeasurements,
@@ -506,13 +507,16 @@ export async function postSerialCompletions(
inspectionSampleId: string | null;
}[];
jobOperationId: string;
+ // The operation's work center, for the first-operation label auto-print.
+ workCenterId: string | null;
inspectionId: string;
eventIds: ProductionEventIds;
companyId: string;
userId: string;
}
): Promise<{ completed: number; error: unknown | null }> {
- let completed = 0;
+ const completedEntityIds: string[] = [];
+ let error: unknown | null = null;
for (const candidate of args.candidates) {
const response = await erpPosting(
"issue",
@@ -529,10 +533,27 @@ export async function postSerialCompletions(
...args.eventIds
}
);
- if (response.error) return { completed, error: response.error };
- completed += 1;
+ if (response.error) {
+ error = response.error;
+ break;
+ }
+ completedEntityIds.push(candidate.trackedEntityId);
}
- return { completed, error: null };
+
+ // Labels go out after the postings, so a slow print enqueue never delays
+ // a unit's completion. Units completed before a failure still get theirs.
+ for (const trackedEntityId of completedEntityIds) {
+ // Auto-print label on first operation only (entity was just minted)
+ await autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId,
+ workCenterId: args.workCenterId ?? undefined,
+ companyId: args.companyId,
+ userId: args.userId
+ });
+ }
+
+ return { completed: completedEntityIds.length, error };
}
// Non-serial completion: one bulk Production posting (batch entities
@@ -575,6 +596,14 @@ export async function postBulkCompletion(
message: response.error.message || "Failed to complete units"
};
}
+ // Auto-print label on first operation only (batch entity was just minted)
+ await autoPrintFirstOperationLabel({
+ serviceRole,
+ trackedEntityId: state.batchTrackedEntityId,
+ workCenterId: state.operation.workCenterId ?? undefined,
+ companyId: args.companyId,
+ userId: args.userId
+ });
return { error: null, message: null };
}