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
// 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 { error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { rejectCrossSiteNavigation } from "@carbon/auth/middleware/security.server";
import { flash } from "@carbon/auth/session.server";
import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";
import { getLogger } from "@carbon/logger";
import { redirect } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
import { erpPosting } from "~/services/erp";
import {
abilityBlockRefusal,
finishJobOperation,
getNextIncompleteSerialEntity,
getTrackedEntitiesByMakeMethodId,
insertProductionQuantity,
isFirstOperationOfMakeMethod,
isSerialEntityIncompleteForOperation
} from "~/services/operations.service";
import { autoPrintFirstOperationLabel } from "~/services/printing.server";
import { checkStrictBackflush } from "~/services/quality.server";
import { path } from "~/utils/path";
const logger = getLogger("mes", "end-operation");
export async function loader({ request, params }: LoaderFunctionArgs) {
// Writes on GET: a link on another site must not trigger it.
rejectCrossSiteNavigation(request);
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("*, ...process(completeAllOnScan)")
.eq("id", operationId)
.maybeSingle(),
serviceRole
.from("productionQuantity")
.select("*")
.eq("type", "Production")
.eq("jobOperationId", operationId)
]);
if (
jobOperation.error ||
!jobOperation.data ||
!jobOperation.data.jobMakeMethodId
) {
return redirect(
path.to.operations,
await flash(request, {
...error(jobOperation.error, "Failed to fetch job operation"),
flash: "error"
})
);
}
if (jobOperation.data?.companyId !== companyId) {
logger.warn("Job operation does not belong to company", {
companyId,
operationId
});
return redirect(
path.to.operations,
await flash(request, {
...error(
"You are not authorized to start this operation",
"Unauthorized"
),
flash: "error"
})
);
}
const abilityRefusal = await abilityBlockRefusal(serviceRole, {
operationId,
employeeId: userId,
companyId
});
if (abilityRefusal) {
return redirect(
path.to.operation(operationId),
await flash(request, error(null, abilityRefusal))
);
}
const completeAll = jobOperation.data?.completeAllOnScan ?? false;
const [jobMakeMethod] = await Promise.all([
serviceRole
.from("jobMakeMethod")
.select("*")
.eq("id", jobOperation.data.jobMakeMethodId)
.maybeSingle()
]);
if (jobMakeMethod.error || !jobMakeMethod.data) {
return 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 = completeAll
? Math.max(
0,
(jobOperation.data.operationQuantity ?? 0) -
currentQuantity -
(jobOperation.data.quantityReworked ?? 0)
)
: 1;
const willBeFinished =
quantityToComplete + currentQuantity >=
(jobOperation.data.targetQuantity ??
jobOperation.data.operationQuantity ??
0);
const isTrackedEntity =
jobMakeMethod.data.requiresSerialTracking ||
jobMakeMethod.data.requiresBatchTracking;
// Business-rule pre-flight on operationFinish. Only fires when this scan
// actually closes the operation (`willBeFinished`); transient quantity
// events don't trigger finish rules.
if (willBeFinished && jobOperation.data.workCenterId) {
const acknowledged = url.searchParams.get("acknowledged") === "true";
const ruleEval = await evaluateLinesForSurface({
client: serviceRole,
companyId,
userId,
targetType: "workCenter",
surface: "operationFinish",
lines: [
{
lineId: operationId,
itemId: jobMakeMethod.data.itemId as string | null,
workCenterId: jobOperation.data.workCenterId,
operation: {
id: operationId,
itemId: jobMakeMethod.data.itemId as string | null,
quantity: jobOperation.data.operationQuantity ?? null,
workInstructionId:
(jobOperation.data as { workInstructionId?: string | null })
.workInstructionId ?? null
},
quantity: quantityToComplete
}
]
});
if (
ruleEval.violations.length > 0 &&
isBlocked(ruleEval.violations, acknowledged)
) {
return redirect(
path.to.operation(operationId),
await flash(
request,
error(
ruleEval.violations[0]?.message ?? "Rule violation",
"Cannot finish operation"
)
)
);
}
}
if (quantityToComplete > 0) {
if (isTrackedEntity) {
const trackedEntities = await getTrackedEntitiesByMakeMethodId(
serviceRole,
jobOperation.data.jobMakeMethodId,
companyId
);
if (!trackedEntityId) {
// No unit named (a scan from outside the MES, or the first operation,
// where units flow in order): complete the next incomplete unit for
// this operation (createdAt asc), falling back to the last entity when
// every unit is complete.
const nextTrackedEntity = getNextIncompleteSerialEntity(
trackedEntities.data ?? [],
operationId
);
if (nextTrackedEntity) {
trackedEntityId = nextTrackedEntity.id;
}
} else if (jobMakeMethod.data.requiresSerialTracking) {
// The operation and assembly views send the unit the operator scanned
// or selected. Completing it twice would record a second production
// quantity for one unit.
const heldEntity = (trackedEntities.data ?? []).find(
(entity) => entity.id === trackedEntityId
);
if (
!heldEntity ||
!isSerialEntityIncompleteForOperation(heldEntity, operationId)
) {
return redirect(
`${path.to.operation(operationId)}?trackedEntityId=${trackedEntityId}`,
await flash(
request,
error(null, "This unit is already complete at this operation")
)
);
}
}
if (jobMakeMethod.data.requiresSerialTracking) {
// Units flow in order through the first operation; at a later one the
// operator scans or selects each unit, so the scan never moves the view
// to a unit of its own choosing.
const isFirstOperation = await isFirstOperationOfMakeMethod(
serviceRole,
operationId,
jobOperation.data.jobMakeMethodId
);
const response = await erpPosting(
"issue",
{ companyId, userId },
{
type: "jobOperationSerialComplete",
quantity: 1,
jobOperationId: jobOperation.data.id,
trackedEntityId: trackedEntityId!,
notes: "Generated by QR code"
}
);
if (response.error) {
return redirect(
path.to.operation(operationId),
await flash(request, {
...error(
response.error,
response.error.message || "Failed to complete job operation"
),
flash: "error"
})
);
}
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,
jobOperationId: jobOperation.data.id,
jobMakeMethodId: jobOperation.data.jobMakeMethodId,
workCenterId: jobOperation.data.workCenterId ?? undefined,
companyId,
userId
});
}
if (newTrackedEntityId && isFirstOperation) {
return redirect(
`${path.to.operation(
operationId
)}?trackedEntityId=${newTrackedEntityId}`
);
}
if (willBeFinished) {
const finishOperation = await finishJobOperation(serviceRole, {
jobOperationId: jobOperation.data.id,
userId,
companyId
});
if (finishOperation.error) {
return redirect(
path.to.operation(operationId),
await flash(
request,
error(finishOperation.error, "Failed to finish operation")
)
);
}
return redirect(
path.to.operations,
await flash(request, {
...success("Operation finished successfully"),
flash: "success"
})
);
}
// Later operation: stay on the unit just completed. The view sees it
// complete and asks for the next unit (scan or select).
if (!isFirstOperation) {
return redirect(
`${path.to.operation(operationId)}?trackedEntityId=${trackedEntityId}`,
await flash(request, {
...success("Completed"),
flash: "success"
})
);
}
// Pre-split flow: the issue function did not spawn a new entity (all
// units already exist), so advance to the next incomplete serial unit
// for this operation. When none remain, fall through to the shared
// "operation complete" redirect below.
const remainingTrackedEntities = await getTrackedEntitiesByMakeMethodId(
serviceRole,
jobOperation.data.jobMakeMethodId,
companyId
);
const nextTrackedEntity = (remainingTrackedEntities.data ?? []).find(
(entity) => isSerialEntityIncompleteForOperation(entity, operationId)
);
if (nextTrackedEntity) {
return redirect(
`${path.to.operation(
operationId
)}?trackedEntityId=${nextTrackedEntity.id}`
);
}
} else if (jobMakeMethod.data.requiresBatchTracking) {
const response = await erpPosting(
"issue",
{ companyId, userId },
{
type: "jobOperationBatchComplete",
quantity: quantityToComplete,
jobOperationId: jobOperation.data.id,
trackedEntityId: trackedEntityId!,
notes: "Generated by QR code"
}
);
if (response.error) {
return redirect(
path.to.operation(operationId),
await flash(request, {
...error(
response.error,
response.error.message || "Failed to complete job operation"
),
flash: "error"
})
);
}
// Auto-print label on first operation only (batch entity was just minted)
if (trackedEntityId) {
await autoPrintFirstOperationLabel({
serviceRole,
trackedEntityId,
jobOperationId: jobOperation.data.id,
jobMakeMethodId: jobOperation.data.jobMakeMethodId,
workCenterId: jobOperation.data.workCenterId ?? undefined,
companyId,
userId
});
}
}
} else {
const check = await checkStrictBackflush({
jobOperationId: operationId,
quantity: quantityToComplete,
companyId,
userId
});
if (check.error) {
return redirect(
path.to.operation(operationId),
await flash(request, {
...error(check.error, check.message!),
flash: "error"
})
);
}
const insertProduction = await insertProductionQuantity(
serviceRole,
{
quantity: quantityToComplete,
jobOperationId: jobOperation.data.id,
notes: "Generated by QR code",
companyId,
createdBy: userId
},
"mes_qr"
);
if (insertProduction.error) {
return redirect(
path.to.operation(operationId),
await flash(request, {
...error(
insertProduction.error,
"Failed to record production quantity"
),
flash: "error"
})
);
}
const issued = await erpPosting(
"issue",
{ companyId, userId },
{
id: operationId,
type: "jobOperation",
quantity: quantityToComplete
}
);
if (issued.error) {
return redirect(
path.to.operation(operationId),
await flash(request, {
...error(
issued.error,
`Units completed, but ${issued.error.message || "failed to issue materials"}`
),
flash: "error"
})
);
}
}
}
if (willBeFinished) {
const finishOperation = await finishJobOperation(serviceRole, {
jobOperationId: jobOperation.data.id,
userId,
companyId
});
if (finishOperation.error) {
return redirect(
path.to.operation(operationId),
await flash(request, {
...error(finishOperation.error, "Failed to finish operation"),
flash: "error"
})
);
}
return redirect(
path.to.operations,
await flash(request, {
...success("Operation finished successfully"),
flash: "success"
})
);
}
return redirect(
path.to.operation(operationId),
await flash(request, {
...success("Successfully completed part"),
flash: "success"
})
);
}