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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: end operation via url
Brad Barbin0fa511e3df6a
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsxnew file mode 100644index 0000000000..6522e409cd--- /dev/null+++ b/apps/mes/app/routes/x+/end.$operationId.tsx@@ -0,0 +1,202 @@+import { error, getCarbonServiceRole } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { redirect, type LoaderFunctionArgs } from "@vercel/remix";+import {+ endProductionEventsForJobOperation,+ finishJobOperation,+ getTrackedEntitiesByMakeMethodId,+ insertProductionQuantity,+} from "~/services/operations.service";+import { path } from "~/utils/path";++export async function loader({ request, params }: LoaderFunctionArgs) {+ const { userId, companyId } = await requirePermissions(request, {});+ const { operationId } = params;+ if (!operationId) throw new Error("Operation ID is required");++ const url = new URL(request.url);+ let trackedEntityId = url.searchParams.get("trackedEntityId");++ const serviceRole = await getCarbonServiceRole();+ const [jobOperation, productionQuantities] = await Promise.all([+ serviceRole+ .from("jobOperation")+ .select("*")+ .eq("id", operationId)+ .maybeSingle(),+ serviceRole+ .from("productionQuantity")+ .select("*")+ .eq("jobOperationId", operationId),+ ]);++ if (+ jobOperation.error ||+ !jobOperation.data ||+ !jobOperation.data.jobMakeMethodId+ ) {+ throw redirect(+ path.to.operations,+ await flash(+ request,+ error(jobOperation.error, "Failed to fetch job operation")+ )+ );+ }++ if (jobOperation.data?.companyId !== companyId) {+ throw redirect(+ path.to.operations,+ await flash(+ request,+ error("You are not authorized to start this operation", "Unauthorized")+ )+ );+ }++ const endEvents = await endProductionEventsForJobOperation(serviceRole, {+ jobOperationId: jobOperation.data.id,+ employeeId: userId,+ companyId,+ });++ if (endEvents.error) {+ throw redirect(+ path.to.operations,+ await flash(request, error(endEvents.error, "Failed to end event"))+ );+ }++ const [jobMakeMethod] = await Promise.all([+ serviceRole+ .from("jobMakeMethod")+ .select("*")+ .eq("id", jobOperation.data.jobMakeMethodId)+ .maybeSingle(),+ ]);++ if (jobMakeMethod.error || !jobMakeMethod.data) {+ throw redirect(+ path.to.operations,+ await flash(+ request,+ error(jobMakeMethod.error, "Failed to fetch job make method")+ )+ );+ }++ const currentQuantity =+ productionQuantities.data?.reduce((acc, curr) => acc + curr.quantity, 0) ??+ 0;++ const quantityToComplete =+ (jobOperation.data.operationQuantity ?? 0) - currentQuantity;++ const isTrackedEntity =+ jobMakeMethod.data.requiresSerialTracking ||+ jobMakeMethod.data.requiresBatchTracking;++ if (quantityToComplete > 0) {+ if (isTrackedEntity) {+ if (!trackedEntityId) {+ const trackedEntities = await getTrackedEntitiesByMakeMethodId(+ serviceRole,+ jobOperation.data.jobMakeMethodId+ );++ if (trackedEntities.data && trackedEntities.data.length > 0) {+ // Use the last tracked entity if available+ trackedEntityId =+ trackedEntities.data[trackedEntities.data.length - 1].id;+ }+ }++ if (jobMakeMethod.data.requiresSerialTracking) {+ const response = await serviceRole.functions.invoke("issue", {+ body: {+ type: "jobOperationSerialComplete",+ quantity: 1,+ jobOperationId: jobOperation.data.id,+ trackedEntityId,+ trackingType: "Serial",+ notes: "Generated by QR code",+ companyId,+ userId,+ },+ });++ const newTrackedEntityId = response.data?.newTrackedEntityId;++ if (newTrackedEntityId) {+ throw redirect(+ `${path.to.operation(+ operationId+ )}?trackedEntityId=${newTrackedEntityId}`+ );+ }+ } else if (jobMakeMethod.data.requiresBatchTracking) {+ const response = await serviceRole.functions.invoke("issue", {+ body: {+ type: "jobOperationBatchComplete",+ quantity: quantityToComplete,+ jobOperationId: jobOperation.data.id,+ trackedEntityId,+ trackingType: "Batch",+ notes: "Generated by QR code",+ companyId,+ userId,+ },+ });++ if (response.error) {+ throw redirect(+ path.to.operation(operationId),+ await flash(+ request,+ error(response.error, "Failed to complete job operation")+ )+ );+ }+ }+ } else {+ const insertProduction = await insertProductionQuantity(serviceRole, {+ quantity: quantityToComplete,+ jobOperationId: jobOperation.data.id,+ notes: "Generated by QR code",+ companyId,+ createdBy: userId,+ });++ if (insertProduction.error) {+ throw redirect(+ path.to.operation(operationId),+ await flash(+ request,+ error(+ insertProduction.error,+ "Failed to record production quantity"+ )+ )+ );+ }+ }+ }++ const finishOperation = await finishJobOperation(serviceRole, {+ jobOperationId: jobOperation.data.id,+ userId,+ });++ if (finishOperation.error) {+ throw redirect(+ path.to.operation(operationId),+ await flash(+ request,+ error(finishOperation.error, "Failed to finish operation")+ )+ );+ }++ throw redirect(path.to.operations);+}diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsxindex 52690a6a92..e7d0d86a32 100644--- a/apps/mes/app/routes/x+/start.$operationId.tsx+++ b/apps/mes/app/routes/x+/start.$operationId.tsx@@ -16,6 +16,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (!operationId) throw new Error("Operation ID is required");const url = new URL(request.url);+ let trackedEntityId = url.searchParams.get("trackedEntityId");+let type = (url.searchParams.get("type") ?? "Labor") as| "Setup"| "Labor"@@ -23,7 +25,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (!["Setup", "Labor", "Machine"].includes(type)) {type = "Labor";}- let trackedEntityId = url.searchParams.get("trackedEntityId");const serviceRole = await getCarbonServiceRole();const [jobOperation, productionEvents] = await Promise.all([diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex fb8acd292a..11da9fa174 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -663,6 +663,23 @@ export async function endProductionEvent(.select("*");}+export async function endProductionEventsForJobOperation(+ client: SupabaseClient<Database>,+ args: {+ jobOperationId: string;+ employeeId: string;+ companyId: string;+ }+) {+ return client+ .from("productionEvent")+ .update({ endTime: new Date().toISOString(), updatedBy: args.employeeId })+ .eq("jobOperationId", args.jobOperationId)+ .is("endTime", null)+ .eq("employeeId", args.employeeId)+ .eq("companyId", args.companyId);+}+export async function endProductionEvents(client: SupabaseClient<Database>,args: { companyId: string; employeeId: string; endTime: string }