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 { carbon, respond } from "@carbon/api/carbon.server";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import { Menubar, VStack } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { Suspense } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Await, useLoaderData, useParams } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
import { CadModel, DeferredFiles } from "~/components";
import { ExternalSourceCard } from "~/components/ExternalSource";
import { usePermissions, useRouteData } from "~/hooks";
import {
itemManufacturingValidator,
partValidator
} from "~/modules/items/items.models";
import {
getConfigurationRules,
getItemChangeNoticeDataOnce,
getItemManufacturing,
getMakeMethodByIdOnce,
getMakeMethodsOnce,
getMethodMaterialsByMakeMethod,
getMethodOperationsByMakeMethodId,
getRevisionLock
} from "~/modules/items/items.service";
import { getConfigurationParameters } from "~/modules/items/items.utils";
import type { ItemFile, MakeMethod, PartSummary } from "~/modules/items/types";
import {
ChangeNoticeDraftLockReason,
getChangeNoticeDraftLock,
ItemChangeNotices,
ItemOpenChangeNoticeAlert,
LockedHint
} from "~/modules/items/ui/ChangeNotice";
import {
BillOfMaterial,
BillOfProcess,
ItemDocuments,
ItemNotes,
ItemRiskRegister,
MakeMethodTools
} from "~/modules/items/ui/Item";
import ItemManufacturingForm from "~/modules/items/ui/Item/ItemManufacturingForm";
import { methodVersionSlot } from "~/modules/items/ui/Item/MakeMethodTools";
import { ConfigurationParametersForm } from "~/modules/items/ui/Parts";
import { getTagsList } from "~/modules/shared/shared.service";
import type { MethodItemType, MethodType } from "~/modules/shared/types";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "parts",
bypassRls: true
});
const { itemId } = params;
if (!itemId) throw new Error("Could not find itemId");
const url = new URL(request.url);
const requestedMethodId = url.searchParams.get("methodId");
// Two waves, not four: everything that needs only the item id goes here, and
// everything that needs only the chosen method's id goes in the next. Read
// one after another, this loader took the sum of its queries (about half a
// second) instead of the slowest of them.
const [makeMethods, revisionLock, changeNoticeData, tags, partManufacturing] =
await Promise.all([
getMakeMethodsOnce(client, itemId, companyId),
getRevisionLock(client, { itemId, companyId }),
// Part → CO traceability (4b): CO history for this part + type labels.
getItemChangeNoticeDataOnce(client, itemId, companyId),
getTagsList(client, companyId, "operation"),
getItemManufacturing(client, itemId, companyId)
]);
const revisionStatus = revisionLock.revisionStatus;
const releaseControl = revisionLock.releaseControl;
// Include CO-owned draft methods so a revision/new-part item created by an open
// Change Notice still shows its BOM/BOP on the item master. The draft is the same
// makeMethod the CO edits, so the two surfaces stay in sync. Active is still
// preferred below, so a Version CO's item keeps its live method as the default.
const selectable = makeMethods.data ?? [];
const makeMethod = requestedMethodId
? (selectable.find((m) => m.id === requestedMethodId) ??
selectable.find((m) => m.status === "Active") ??
selectable[0])
: (selectable.find((m) => m.status === "Active") ?? selectable[0]);
if (!makeMethod) {
return {
methodData: null,
tags: [],
revisionStatus,
releaseControl,
...changeNoticeData
};
}
const [fullMethod, methodMaterials, methodOperations, configData] =
await Promise.all([
getMakeMethodByIdOnce(client, makeMethod.id, companyId),
getMethodMaterialsByMakeMethod(client, makeMethod.id),
getMethodOperationsByMakeMethodId(client, makeMethod.id),
partManufacturing.data?.requiresConfiguration
? Promise.all([
getConfigurationParameters(client, itemId, companyId),
getConfigurationRules(client, itemId, companyId)
]).then(([configurationParametersAndGroups, configurationRules]) => ({
configurationParametersAndGroups,
configurationRules
}))
: {
configurationParametersAndGroups: { groups: [], parameters: [] },
configurationRules: []
}
]);
if (fullMethod.error || !fullMethod.data) {
return {
methodData: null,
tags: [],
revisionStatus,
releaseControl,
...changeNoticeData
};
}
return {
methodData: {
makeMethod: fullMethod.data,
methodMaterials:
methodMaterials.data?.map((m) => ({
...m,
description: m.item?.name ?? "",
methodType: m.methodType as MethodType,
itemType: m.itemType as MethodItemType
})) ?? [],
methodOperations:
methodOperations.data?.map((operation) => ({
...operation,
workCenterId: operation.workCenterId ?? undefined,
operationSupplierProcessId:
operation.operationSupplierProcessId ?? undefined,
workInstruction: operation.workInstruction as JSONContent | null
})) ?? [],
partManufacturing: partManufacturing.data,
...configData
},
tags: tags.data ?? [],
revisionStatus,
releaseControl,
...changeNoticeData
};
}
// The details form, and the manufacturing card (`intent=manufacturing`).
const intentForm = z.object({ intent: zfd.text(z.string().optional()) });
export async function action(args: ActionFunctionArgs) {
const input = await validator(intentForm).request(args, {
params: ["itemId"]
});
if ("invalid" in input) return input.invalid;
const { itemId } = input.params;
const formData = input.formData ?? new FormData();
const api = await carbon(args.request);
if (input.data.intent === "manufacturing") {
const validation = await validator(itemManufacturingValidator).validate(
formData
);
if (validation.error) return validationError(validation.error);
const result = await api.items.updateItemManufacturing({
...validation.data,
requiresConfiguration: validation.data.requiresConfiguration ?? false,
itemId,
customFields: setCustomFields(formData)
});
return respond(args.request, result).redirect(path.to.partDetails(itemId), {
message: "Updated part manufacturing",
onError: path.to.part(itemId)
});
}
const validation = await validator(partValidator).validate(formData);
if (validation.error) return validationError(validation.error);
const result = await api.items.updatePart({
...validation.data,
id: itemId,
customFields: setCustomFields(formData)
});
return respond(args.request, result).redirect(path.to.part(itemId), {
message: "Updated part"
});
}
export default function PartDetailsRoute() {
const { t } = useLingui();
const { itemId } = useParams();
if (!itemId) throw new Error("Could not find itemId");
const permissions = usePermissions();
const {
methodData,
tags,
revisionStatus,
releaseControl,
changeNotices,
changeNoticeTypes
} = useLoaderData<typeof loader>();
const draftLock = getChangeNoticeDraftLock(
methodData?.makeMethod.changeOrderId,
changeNotices
);
const lockReason = draftLock ? (
<ChangeNoticeDraftLockReason lock={draftLock} />
) : undefined;
const lockHint = lockReason ? <LockedHint reason={lockReason} /> : undefined;
const partData = useRouteData<{
partSummary: PartSummary;
files: Promise<ItemFile[]>;
makeMethods: Promise<PostgrestResponse<MakeMethod>>;
}>(path.to.part(itemId));
if (!partData) throw new Error("Could not find part data");
const manufacturingInitialValues = methodData?.partManufacturing
? {
...methodData.partManufacturing,
lotSize: methodData.partManufacturing.lotSize ?? 0,
...getCustomFields(methodData.partManufacturing.customFields)
}
: null;
return (
<VStack spacing={4} className="p-4">
{permissions.is("employee") &&
methodData &&
["Make", "Buy and Make"].includes(
partData.partSummary?.replenishmentSystem ?? ""
) && (
<Suspense fallback={<Menubar />}>
<Await resolve={partData?.makeMethods}>
{(makeMethods) => (
<MakeMethodTools
itemId={methodData.makeMethod.itemId}
makeMethods={makeMethods?.data ?? []}
type="Part"
currentMethodId={methodData.makeMethod.id}
versionInSlot
/>
)}
</Await>
</Suspense>
)}
{permissions.is("employee") && (
<ItemOpenChangeNoticeAlert changeNotices={changeNotices ?? []} />
)}
{permissions.is("employee") && methodData && (
<>
{["Make", "Buy and Make"].includes(
partData.partSummary?.replenishmentSystem ?? ""
) && (
<>
{manufacturingInitialValues && (
<ItemManufacturingForm
key={itemId}
initialValues={manufacturingInitialValues}
/>
)}
{methodData.partManufacturing?.requiresConfiguration && (
<ConfigurationParametersForm
key={`options:${itemId}`}
parameters={
methodData.configurationParametersAndGroups.parameters
}
groups={methodData.configurationParametersAndGroups.groups}
/>
)}
</>
)}
<ItemNotes
id={partData.partSummary?.id ?? null}
title={partData.partSummary?.name ?? ""}
subTitle={partData.partSummary?.readableIdWithRevision ?? ""}
notes={partData.partSummary?.notes as JSONContent}
/>
{["Make", "Buy and Make"].includes(
partData.partSummary?.replenishmentSystem ?? ""
) && (
<>
{/* Phones: the method version chip, right above the method. */}
<methodVersionSlot.Target className="flex md:hidden [&_button]:h-9 [&_button]:rounded-full [&_button]:border [&_button]:border-border [&_button]:bg-card [&_button]:px-3" />
<BillOfProcess
key={`bop:${itemId}`}
makeMethod={methodData.makeMethod}
// @ts-expect-error
operations={methodData.methodOperations ?? []}
configurable={
methodData.partManufacturing?.requiresConfiguration
}
materials={methodData.methodMaterials ?? []}
configurationRules={methodData.configurationRules}
parameters={
methodData.configurationParametersAndGroups.parameters
}
tags={tags}
revisionStatus={revisionStatus}
releaseControl={releaseControl}
isDisabled={!!draftLock}
disabledReason={lockReason}
/>
<BillOfMaterial
key={`bom:${itemId}`}
makeMethod={methodData.makeMethod}
// @ts-expect-error
materials={methodData.methodMaterials ?? []}
// @ts-expect-error
operations={methodData.methodOperations}
configurable={
methodData.partManufacturing?.requiresConfiguration
}
configurationRules={methodData.configurationRules}
parameters={
methodData.configurationParametersAndGroups.parameters
}
replenishmentSystem={partData.partSummary?.replenishmentSystem}
revisionStatus={revisionStatus}
releaseControl={releaseControl}
isDisabled={!!draftLock}
disabledReason={lockReason}
/>
</>
)}
</>
)}
{permissions.is("employee") && (
<>
<DeferredFiles resolve={partData?.files}>
{(resolvedFiles) => (
<ItemDocuments
files={resolvedFiles}
itemId={itemId}
modelUpload={partData.partSummary ?? undefined}
type="Part"
isReadOnly={!!draftLock}
titleExtras={lockHint}
/>
)}
</DeferredFiles>
{/* <DefaultAttachmentsPanel
files={defaultAttachments ?? []}
storagePathPrefix={`default-attachments/item/${itemId}`}
title={t`Default Attachments on Purchase Orders`}
description={t`Files attached here ride along whenever this item appears on a purchase order email.`}
/> */}
<CadModel
isReadOnly={!permissions.can("update", "parts") || !!draftLock}
metadata={{ itemId }}
modelUpload={partData?.partSummary ?? null}
title={t`CAD Model`}
titleExtras={lockHint}
/>
<ExternalSourceCard
itemId={itemId}
canDetach={permissions.can("update", "parts")}
/>
<ItemRiskRegister itemId={itemId} />
<ItemChangeNotices
changeNotices={changeNotices ?? []}
types={changeNoticeTypes ?? []}
/>
</>
)}
</VStack>
);
}