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 } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { getDocumentApprovalState } from "@carbon/ee/approvals/document.server";
import { getLogger } from "@carbon/logger";
import type { JSONContent } from "@carbon/react";
import { RecordOutlet } from "@carbon/react";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import { useLingui } from "@lingui/react/macro";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
import {
getChangeNotice,
getChangeNoticeActions,
getChangeNoticeAffectedItems,
getChangeNoticeDiff,
getChangeNoticeRequiredActionsList,
getChangeNoticeTypesList,
getConfigurationRules,
getItemFiles,
getItemManufacturing,
getMakeMethodById,
getMakeMethods,
getMethodMaterialsByMakeMethod,
getMethodOperationsByMakeMethodId,
getPart,
getPartUsedIn,
getPickMethods,
getRevisionLock,
getSupplierParts
} from "~/modules/items/items.service";
import { getConfigurationParameters } from "~/modules/items/items.utils";
import type { AffectedItemDraft } from "~/modules/items/ui/ChangeNotice";
import {
ChangeNoticeExplorer,
ChangeNoticeHeader,
ChangeNoticeProperties
} from "~/modules/items/ui/ChangeNotice";
import { getIssue, getIssues } from "~/modules/quality/quality.service";
import { getLocationsList } from "~/modules/resources/resources.service";
import { getTagsList } from "~/modules/shared/shared.service";
import type { MethodItemType, MethodType } from "~/modules/shared/types";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
const logger = getLogger("erp", "change-notice");
export const handle: Handle = {
// Leaf crumb: show the CO's readable number (from loader data), not a second
// static "Change Notices" (the parent _layout already renders the list crumb).
breadcrumb: (
_params: unknown,
data?: { changeNotice?: { changeOrderId?: string } }
) => data?.changeNotice?.changeOrderId ?? msg`Change Notice`,
module: "parts",
// The CO detail workspace has its own left affected-items sidebar — hide the
// Items module sidebar here so two left sidebars don't stack.
hideModuleSidebar: true
};
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
view: "parts"
});
const { id } = params;
if (!id) throw new Error("Could not find id");
const [
changeNotice,
types,
affected,
diff,
actions,
nonConformances,
locationsList,
requiredActionsList,
partTags,
operationTags
] = await Promise.all([
getChangeNotice(client, id, companyId),
getChangeNoticeTypesList(client, companyId),
getChangeNoticeAffectedItems(client, id, companyId),
getChangeNoticeDiff(client, id, companyId),
getChangeNoticeActions(client, id, companyId),
// NCR cross-link picker options (4a).
getIssues(client, companyId),
// Company locations feed the embedded PartProperties pick-method editor.
getLocationsList(client, companyId),
// Active default-action templates for the "Add Actions" picker.
getChangeNoticeRequiredActionsList(client, companyId),
getTagsList(client, companyId, "part"),
getTagsList(client, companyId, "operation")
]);
const locations = locationsList.data ?? [];
const requiredActions = requiredActionsList.data ?? [];
if (changeNotice.error) {
throw redirect(
path.to.changeNotices,
await flash(
request,
error(changeNotice.error, "Failed to load change notice")
)
);
}
// Human label for the currently-linked NCR (so the sidebar link shows the
// readable id/name, not the raw id).
const linkedNonConformanceId = changeNotice.data?.nonConformanceId ?? null;
const linkedNonConformancePromise = linkedNonConformanceId
? getIssue(client, linkedNonConformanceId).then((issue) => issue.data)
: null;
const affectedRows = affected.data ?? [];
// Impact = where each affected item is used across the system (jobs, POs,
// sales, receipts, methods, NCRs, …) — the same "Used In" data the part detail
// page loads, one entry per affected item. Streamed: only the impact panel
// reads it.
const impactUsedIn = Promise.all(
affectedRows.map(async (a) => ({
itemId: a.itemId,
readableIdWithRevision: a.item?.readableIdWithRevision ?? a.itemId,
itemName: a.item?.name ?? null,
usedIn: await getPartUsedIn(client, a.itemId, companyId)
}))
).catch((error) => {
logger.error("Failed to load change notice impact", {
companyId,
changeNoticeId: id,
error
});
return [];
});
const diffByAffectedId = new Map(
(diff.data?.items ?? []).map((entry) => [entry.affectedItemId, entry])
);
// Per affected item: load its CO-owned Draft make method's real rows shaped
// exactly as the embedded BillOfMaterial / BillOfProcess editors expect (same
// assembly as x+/part+/$itemId.make.$makeMethodId). The draft lives on the
// same item for a Version, or on the new item (newItemId) for Revision/New Part.
const affectedItems: AffectedItemDraft[] = await Promise.all(
affectedRows.map(async (affectedItem) => {
const draftItemId = affectedItem.newItemId ?? affectedItem.itemId;
const draftMakeMethodId = affectedItem.draftMakeMethodId;
if (!draftMakeMethodId) {
return {
affectedItem,
draftItemId,
makeMethod: null,
methodMaterials: [],
methodOperations: [],
tags: [],
configurable: false,
configurationRules: [],
parameters: [],
revisionStatus: null,
releaseControl: null,
partData: null,
diff: diffByAffectedId.get(affectedItem.id)
};
}
// Revision / Replacement Part / New Part edit the item's attributes + files
// on the draft item — load the same bundle the part detail route feeds
// PartProperties, embedded on the CO card. Parts only (Tool attribute
// editing is a follow-up); Version has no attribute editing (Q2 matrix).
const needsAttributes =
(affectedItem.changeType === "Revision" ||
affectedItem.changeType === "Replacement Part" ||
affectedItem.changeType === "New Part") &&
affectedItem.item?.type === "Part";
const partDataPromise = needsAttributes
? Promise.all([
getPart(client, draftItemId, companyId),
getSupplierParts(client, draftItemId, companyId),
getPickMethods(client, draftItemId, companyId)
]).then(([partSummary, supplierParts, pickMethods]) =>
partSummary.data
? {
itemId: draftItemId,
locations,
partSummary: partSummary.data,
files: getItemFiles(client, draftItemId, companyId),
supplierParts: supplierParts.data ?? [],
pickMethods: pickMethods.data ?? [],
makeMethods: getMakeMethods(client, draftItemId, companyId),
tags: partTags.data ?? []
}
: null
)
: null;
const [
makeMethod,
methodMaterials,
methodOperations,
manufacturing,
revisionLock,
partData
] = await Promise.all([
getMakeMethodById(client, draftMakeMethodId, companyId),
getMethodMaterialsByMakeMethod(client, draftMakeMethodId),
getMethodOperationsByMakeMethodId(client, draftMakeMethodId),
getItemManufacturing(client, draftItemId, companyId),
getRevisionLock(client, { itemId: draftItemId, companyId }),
partDataPromise
]);
const config = manufacturing.data?.requiresConfiguration
? await Promise.all([
getConfigurationParameters(client, draftItemId, companyId),
getConfigurationRules(client, draftItemId, companyId)
]).then(([{ parameters }, configurationRules]) => ({
parameters,
configurationRules
}))
: {
parameters: [] as Awaited<
ReturnType<typeof getConfigurationParameters>
>["parameters"],
configurationRules: [] as Awaited<
ReturnType<typeof getConfigurationRules>
>
};
return {
affectedItem,
draftItemId,
makeMethod: makeMethod.data ?? null,
methodMaterials:
methodMaterials.data?.map((m) => ({
...m,
description: m.item?.name ?? "",
methodOperationId: m.methodOperationId ?? undefined,
methodType: m.methodType as MethodType,
itemType: m.itemType as MethodItemType
})) ?? [],
methodOperations:
methodOperations.data?.map((operation) => ({
...operation,
description: operation.description ?? "",
procedureId: operation.procedureId ?? undefined,
assemblyInstructionId: operation.assemblyInstructionId ?? undefined,
inspectionDocumentId: operation.inspectionDocumentId ?? undefined,
operationSupplierProcessId:
operation.operationSupplierProcessId ?? undefined,
operationMinimumCost: operation.operationMinimumCost ?? 0,
operationLeadTime: operation.operationLeadTime ?? 0,
operationUnitCost: operation.operationUnitCost ?? 0,
tags: operation.tags ?? [],
workCenterId: operation.workCenterId ?? undefined,
workInstruction: operation.workInstruction as JSONContent | null
})) ?? [],
tags: operationTags.data ?? [],
configurable: manufacturing.data?.requiresConfiguration ?? false,
configurationRules: config.configurationRules,
parameters: config.parameters,
revisionStatus: revisionLock.revisionStatus,
releaseControl: revisionLock.releaseControl,
partData,
diff: diffByAffectedId.get(affectedItem.id)
};
})
);
// Minimal, explicit option shape (cheap type — avoids widening the loader's
// instantiation surface with the full issues-view row).
const nonConformanceOptions: {
id: string;
nonConformanceId: string;
name: string;
}[] = (nonConformances.data ?? []).flatMap((nc) =>
nc.id && nc.nonConformanceId
? [
{
id: nc.id,
nonConformanceId: nc.nonConformanceId,
name: nc.name ?? ""
}
]
: []
);
// Approval only gates Engineering Complete → Implementation.
const [linkedNonConformance, approval] = await Promise.all([
linkedNonConformancePromise,
changeNotice.data?.status === "Engineering Complete"
? getDocumentApprovalState(getCarbonServiceRole(), {
documentType: "changeOrder",
documentId: id,
companyId,
userId
})
: null
]);
return {
changeNotice: changeNotice.data,
types: types.data ?? [],
affectedItems,
diff: diff.data ?? { items: [] },
actions: actions.data ?? [],
requiredActions,
impactUsedIn,
nonConformanceOptions,
approval,
linkedNonConformance: linkedNonConformance
? {
id: linkedNonConformance.id,
nonConformanceId: linkedNonConformance.nonConformanceId,
name: linkedNonConformance.name
}
: null
};
}
export default function ChangeNoticeIdRoute() {
const { t } = useLingui();
const { id } = useParams();
if (!id) throw new Error("Could not find id");
// Surfaced to child routes + header/explorer/properties via useRouteData.
useLoaderData<typeof loader>();
return (
// Standard 3-pane detail workspace (matches sales-order / job): the explorer
// is the affected-items list, the content is the selected affected item's
// detail (the $id.details Outlet, with the CO-wide stage flow + actions on
// top), and the properties panel holds the CO-centric fields, details,
// actions, impact, and the release dialog.
<PanelProvider>
<div className="flex flex-col h-[calc(100dvh-var(--topbar-height)-var(--content-inset))] overflow-hidden w-full">
<ChangeNoticeHeader />
<div className="flex h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] overflow-hidden w-full">
<div className="flex flex-grow overflow-hidden">
<ResizablePanels
explorerLabel={t`Affected Items`}
explorer={<ChangeNoticeExplorer />}
content={
<div className="bg-card h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent w-full">
<RecordOutlet />
</div>
}
properties={<ChangeNoticeProperties key={id} />}
/>
</div>
</div>
</div>
</PanelProvider>
);
}