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
fix(items): refuse to activate or consume an item its change notice still holds
Raulb97590799903
diff --git a/apps/erp/app/modules/items/AGENTS.md b/apps/erp/app/modules/items/AGENTS.mdindex 1fa1408885..7a6907d3ea 100644--- a/apps/erp/app/modules/items/AGENTS.md+++ b/apps/erp/app/modules/items/AGENTS.md@@ -115,6 +115,7 @@ Change-order code follows the one-service/models/server-per-module convention- MUST gate every CO mutation route with `requireChangeNoticeEditable(client, { changeNoticeId, companyId, scope })` from `items.server.ts` — `scope: "engineering"` for affected items / BOM / BOP / cutover / reason / description, `scope: "workflow"` for action tasks and header fields. A UI-only `isDisabled` is not a lock.- MUST add affected items through `addChangeNoticeAffectedItem` — it spins the CO-owned Draft method and writes the draft refs back; a bare `changeOrderAffectedItem` insert leaves the diff/release with no draft to activate.- MUST use `applyChangeNotice` (the Implementation → Done "release") for the release lifecycle — never re-implement `activateMethodVersion`/`itemSupersession` inline. It orchestrates canonical helpers via edge-function calls, so it is **not** one transaction (G2); only the final flip to Done is a Kysely CAS. It is idempotent per affected item (a Draft whose `changeOrderId` is already cleared is skipped) and CO-wide (the closing CAS on `status='Implementation'`).+- MUST route any write that puts an item into circulation through `getUnreleasedChangeOrderItems` (or its single-item forms `getUnreleasedChangeOrderForItem` / `getUnreleasedChangeOrderIssue`) in `items.server.ts`. Release is what activates a CO-minted item (`applyChangeNotice` flips `active`), but nothing stops a user switching the Active toggle by hand first — the item then reaches the pickers, MRP and job creation carrying the CO's un-approved draft BOM. The item bulk-update action refuses to activate such an item, and the sales order line / purchase order line / job creation actions refuse to consume one. `item.changeOrderId` alone is NOT the test: release leaves it in place as a provenance back-link, so the owning CO's status decides. Pass a service-role client — reading `changeOrder` needs `parts_view`, which a sales or purchasing user need not have.- `findChangeNoticesForItem` (in `items.service.ts`) is G6 — the single canonical "change orders referencing this item" query (spans affected items, BOM components on CO-owned draft methods, manual supersession predecessor/successor, and the `item.changeOrderId` reverse link on released revisions), scoped by `readableId`. Flat queries + JS union (no PostgREST embeds — TS2589 budget). Powers the part/tool detail history + open-CO alert. Do not add a second query for this.- Never split CO code into separate `changeNotice.*` service/models/server files — it lives in the module's canonical `items.service.ts` / `items.models.ts` / `items.server.ts` (the one-service/models/server-per-module convention). Add CO functions there, alongside the rest of the items module.diff --git a/apps/erp/app/modules/items/items.server.test.ts b/apps/erp/app/modules/items/items.server.test.tsindex 599c52a1a6..f364842918 100644--- a/apps/erp/app/modules/items/items.server.test.ts+++ b/apps/erp/app/modules/items/items.server.test.ts@@ -16,9 +16,12 @@ vi.mock("@carbon/glossary", () => ({termSlug: vi.fn()}));-const { getLockVerdict, LOCKED_REVISION_MESSAGE } = await import(- "./items.server"-);+const {+ getLockVerdict,+ LOCKED_REVISION_MESSAGE,+ getUnreleasedChangeOrderItems,+ getUnreleasedChangeOrderIssue+} = await import("./items.server");describe("getLockVerdict", () => {it("allows edits when the revision is not locked", () => {@@ -55,3 +58,186 @@ describe("getLockVerdict", () => {});});});++type Row = Record<string, unknown> | null;++// Stands in for the two list reads the batch guard makes. Supabase builders are+// thenables, so the chain resolves on await without a terminal method.+function fakeListClient(+ rows: { item?: Row[]; changeOrder?: Row[] },+ errors: { item?: boolean; changeOrder?: boolean } = {}+) {+ return {+ from(table: string) {+ const failed = errors[table as keyof typeof errors] === true;+ const result = {+ data: failed ? null : (rows[table as keyof typeof rows] ?? []),+ error: failed ? { message: `failed to read ${table}` } : null+ };+ const builder = {+ select: () => builder,+ in: () => builder,+ eq: () => builder,+ then: (resolve: (value: typeof result) => unknown) => resolve(result)+ };+ return builder;+ }+ } as never;+}++const companyId = "company_1";+const args = { itemId: "item_1", companyId };++describe("getUnreleasedChangeOrderItems", () => {+ it("reads nothing when given no ids", async () => {+ const client = fakeListClient({ item: [{ id: "item_1" }] });++ expect(+ await getUnreleasedChangeOrderItems(client, { itemIds: [], companyId })+ ).toEqual({ data: [], error: null });+ });++ it("passes items that no change order owns", async () => {+ const client = fakeListClient({+ item: [+ {+ id: "item_1",+ readableIdWithRevision: "P000001",+ changeOrderId: null+ }+ ]+ });++ expect(+ await getUnreleasedChangeOrderItems(client, {+ itemIds: ["item_1"],+ companyId+ })+ ).toEqual({ data: [], error: null });+ });++ // Release leaves changeOrderId in place as a provenance link, so the column+ // alone cannot answer "is this still a draft" — the status decides.+ it("returns only the items whose change order is unreleased", async () => {+ const client = fakeListClient({+ item: [+ {+ id: "item_1",+ readableIdWithRevision: "P000001.A",+ changeOrderId: "co_open"+ },+ {+ id: "item_2",+ readableIdWithRevision: "P000002.B",+ changeOrderId: "co_done"+ }+ ],+ changeOrder: [+ {+ id: "co_open",+ changeOrderId: "ECO-000001",+ status: "Implementation"+ },+ { id: "co_done", changeOrderId: "ECO-000002", status: "Done" }+ ]+ });++ expect(+ await getUnreleasedChangeOrderItems(client, {+ itemIds: ["item_1", "item_2"],+ companyId+ })+ ).toEqual({+ data: [+ {+ itemId: "item_1",+ itemName: "P000001.A",+ changeOrderReadableId: "ECO-000001"+ }+ ],+ error: null+ });+ });++ // A read that did not answer says nothing about the items, so callers block+ // rather than wave the write through on a database blip.+ it("reports an error when the item read fails", async () => {+ const client = fakeListClient({}, { item: true });++ expect(+ await getUnreleasedChangeOrderItems(client, {+ itemIds: ["item_1"],+ companyId+ })+ ).toEqual({+ data: [],+ error: "These items could not be checked against their change orders."+ });+ });++ it("reports an error when the change order read fails", async () => {+ const client = fakeListClient(+ {+ item: [+ {+ id: "item_1",+ readableIdWithRevision: "P000001.A",+ changeOrderId: "co_open"+ }+ ]+ },+ { changeOrder: true }+ );++ expect(+ await getUnreleasedChangeOrderItems(client, {+ itemIds: ["item_1"],+ companyId+ })+ ).toEqual({+ data: [],+ error: "These items could not be checked against their change orders."+ });+ });+});++describe("getUnreleasedChangeOrderIssue", () => {+ it("names the change order still holding the item", async () => {+ const client = fakeListClient({+ item: [+ {+ id: "item_1",+ readableIdWithRevision: "P000001.A",+ changeOrderId: "co_open"+ }+ ],+ changeOrder: [+ { id: "co_open", changeOrderId: "ECO-000001", status: "Draft" }+ ]+ });++ expect(await getUnreleasedChangeOrderIssue(client, args)).toBe(+ "P000001.A was created by change order ECO-000001, which has not been released yet."+ );+ });++ // Narrow on purpose — the guard does not judge `active`. Inactive items are+ // allowed onto these documents today, and that is a separate decision.+ it("passes an inactive item that no change order owns", async () => {+ const client = fakeListClient({+ item: [+ { id: "item_1", readableIdWithRevision: "P000001", changeOrderId: null }+ ]+ });++ expect(await getUnreleasedChangeOrderIssue(client, args)).toBeNull();+ });++ it("blocks when the check could not be made", async () => {+ const client = fakeListClient({}, { item: true });++ expect(await getUnreleasedChangeOrderIssue(client, args)).toBe(+ "These items could not be checked against their change orders."+ );+ });+});diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.tsindex c9c99902aa..f934ce67d0 100644--- a/apps/erp/app/modules/items/items.server.ts+++ b/apps/erp/app/modules/items/items.server.ts@@ -679,3 +679,153 @@ function normalizeSupersessionMode(? (mode as Database["public"]["Enums"]["supersessionMode"]): "Consume First";}++// -----------------------------------------------------------------------------+// Unreleased-change-order guard.+//+// Release is what activates a change notice's items: `applyChangeNotice` flips+// `active` on the revisions and parts the notice minted. Nothing stops a user+// switching the Active toggle on by hand first, and once it is on the item is+// selectable everywhere — carrying the notice's un-approved draft BOM, since a+// minted revision's only make method is that Draft and `activeMakeMethods` falls+// back to it when no Active version exists.+//+// So two kinds of write ask this question: one that would ACTIVATE such an item,+// and one that would CONSUME it (a sales order line, a purchase order line, a+// job).+//+// `item.changeOrderId` is NOT a draft marker on its own — release leaves it in+// place as a provenance back-link, so the owning change order's status decides.+// Release IS the Implementation -> Done transition, so every other status means+// the item is still a draft.+//+// Pass a service-role client: reading `changeOrder` requires `parts_view`, which+// the caller need not have.+// -----------------------------------------------------------------------------+const RELEASED_CHANGE_ORDER_STATUS = "Done";++export type UnreleasedChangeOrderItem = {+ itemId: string;+ itemName: string;+ changeOrderReadableId: string;+};++// Two queries regardless of how many ids come in — the bulk item update can+// carry a whole table selection.+//+// `error` is a message to show the user, not a thrown failure — a read that did+// not answer says nothing about the items, so callers block on it rather than+// wave the write through on a database blip.+export async function getUnreleasedChangeOrderItems(+ client: SupabaseClient<Database>,+ args: { itemIds: string[]; companyId: string }+): Promise<{ data: UnreleasedChangeOrderItem[]; error: string | null }> {+ if (args.itemIds.length === 0) return { data: [], error: null };++ const items = await client+ .from("item")+ .select("id, readableIdWithRevision, changeOrderId")+ .in("id", args.itemIds)+ .eq("companyId", args.companyId);++ if (items.error) {+ logger.error("Failed to read items for change order check", {+ error: items.error,+ itemIds: args.itemIds+ });+ return {+ data: [],+ error: "These items could not be checked against their change orders."+ };+ }++ const owned = (items.data ?? []).filter(+ (item): item is typeof item & { changeOrderId: string } =>+ !!item.changeOrderId+ );+ if (owned.length === 0) return { data: [], error: null };++ const changeOrders = await client+ .from("changeOrder")+ .select("id, changeOrderId, status")+ .in("id", [...new Set(owned.map((item) => item.changeOrderId))])+ .eq("companyId", args.companyId);++ if (changeOrders.error) {+ logger.error("Failed to read change orders for change order check", {+ error: changeOrders.error,+ itemIds: args.itemIds+ });+ return {+ data: [],+ error: "These items could not be checked against their change orders."+ };+ }++ const unreleased = new Map(+ (changeOrders.data ?? [])+ .filter((co) => co.status !== RELEASED_CHANGE_ORDER_STATUS)+ .map((co) => [co.id, co.changeOrderId])+ );++ return {+ data: owned.flatMap((item) => {+ const changeOrderReadableId = unreleased.get(item.changeOrderId);+ if (!changeOrderReadableId) return [];+ return [+ {+ itemId: item.id,+ itemName: item.readableIdWithRevision ?? "This item",+ changeOrderReadableId+ }+ ];+ }),+ error: null+ };+}++// Single-item form for the loaders that only need to know whether to lock the+// Active toggle on this one item's page. Best-effort: a failed read leaves the+// toggle unlocked, and the action behind it still refuses the write.+export async function getUnreleasedChangeOrderForItem(+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+): Promise<UnreleasedChangeOrderItem | null> {+ const unreleased = await getUnreleasedChangeOrderItems(client, {+ itemIds: [args.itemId],+ companyId: args.companyId+ });+ return unreleased.data[0] ?? null;+}++// Single-item form for the actions that put an item into circulation. Returns+// the reason to refuse, or null. Unlike the loader form this fails closed: a+// read that did not answer says nothing about the item.+//+// Deliberately does NOT judge `active`. Plain inactive items are allowed onto+// these documents today, and changing that is a separate decision from closing+// the change order hole.+export async function getUnreleasedChangeOrderIssue(+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+): Promise<string | null> {+ const unreleased = await getUnreleasedChangeOrderItems(client, {+ itemIds: [args.itemId],+ companyId: args.companyId+ });+ if (unreleased.error) return unreleased.error;+ if (unreleased.data.length === 0) return null;+ return unreleasedChangeOrderItemsMessage(unreleased.data);+}++// Names every offending item so a bulk edit says which row to fix.+export function unreleasedChangeOrderItemsMessage(+ unreleased: UnreleasedChangeOrderItem[]+) {+ return unreleased+ .map(+ (item) =>+ `${item.itemName} was created by change order ${item.changeOrderReadableId}, which has not been released yet.`+ )+ .join(" ");+}diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ItemChangeNoticeLock.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ItemChangeNoticeLock.tsxindex 2a7df42cd7..4433735601 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ItemChangeNoticeLock.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ItemChangeNoticeLock.tsx@@ -35,15 +35,19 @@ export function useItemOpenChangeNotices(}// Tooltip wrapper for disabled controls (the div anchors hover since disabled elements don't fire it).+// `reason` overrides the default "release it to create new versions" wording for+// callers locking something else — the Active toggle, say.export function ItemChangeNoticeLock({changeNotices,isLocked,className,+ reason,children}: {changeNotices: ChangeNoticeForItem[];isLocked: boolean;className?: string;+ reason?: ReactNode;children: ReactNode;}) {const { t } = useLingui();@@ -62,11 +66,12 @@ export function ItemChangeNoticeLock({</div></TooltipTrigger><TooltipContent>- {changeNotices.length === 0- ? t`Change notices could not be loaded, so new versions and revisions are blocked. Reload to try again.`- : changeNotices.length === 1- ? t`Open in change notice ${ids}. Release it to create new versions or revisions.`- : t`Open in change notices ${ids}. Release them to create new versions or revisions.`}+ {reason ??+ (changeNotices.length === 0+ ? t`Change notices could not be loaded, so new versions and revisions are blocked. Reload to try again.`+ : changeNotices.length === 1+ ? t`Open in change notice ${ids}. Release it to create new versions or revisions.`+ : t`Open in change notices ${ids}. Release them to create new versions or revisions.`)}</TooltipContent></Tooltip>);diff --git a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsxindex c6aeb032ba..2cbb171f13 100644--- a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx@@ -46,6 +46,7 @@ import {itemReplenishmentSystems,itemTrackingTypes} from "../../items.models";+import type { UnreleasedChangeOrderItem } from "../../items.server";import type {ItemFile,MakeMethod,@@ -53,6 +54,7 @@ import type {PickMethod,SupplierPart} from "../../types";+import { ItemChangeNoticeLock } from "../ChangeNotice/ItemChangeNoticeLock";import { FileBadge, ItemDescription, SourcingTypeProperty } from "../Item";export type PartPropertiesData = {@@ -135,6 +137,8 @@ const PartProperties = ({name: string;} | null;}>;+ // Set while the change notice that minted this item is still open.+ unreleasedChangeOrder?: UnreleasedChangeOrderItem | null;}>(path.to.part(itemId));const routeData = data ?? routeDataFromRoute;@@ -228,6 +232,14 @@ const PartProperties = ({[routeData?.partSummary?.readableId]);+ // The change notice that minted this part activates it at release. Until then+ // the toggle is locked: an unreleased revision switched Active by hand reaches+ // the item pickers, MRP and job creation carrying the notice's draft BOM.+ // An already-active part is left alone so it can still be switched off.+ const activationLockId = routeDataFromRoute?.partSummary?.active+ ? undefined+ : routeDataFromRoute?.unreleasedChangeOrder?.changeOrderReadableId;+const [suppliers] = useSuppliers();// Image + files, factored so they can render inline ("all") or as the sole@@ -726,25 +738,40 @@ const PartProperties = ({{/* Active is a lifecycle flag the change notice controls at release — not auser-editable attribute in the CO card. Keep it on the part page only. */}{!embedded && (- <ValidatedForm- defaultValues={{- active: routeData?.partSummary?.active ?? undefined- }}- validator={z.object({- active: zfd.checkbox()- })}+ <ItemChangeNoticeLock+ changeNotices={[]}+ isLocked={!!activationLockId}className="w-full"- isReadOnly={isReadOnly}+ reason={+ activationLockId ? (+ <Trans>+ This part is activated when change notice {activationLockId} is+ released.+ </Trans>+ ) : undefined+ }>- <Boolean- label={t`Active`}- name="active"- variant="small"- onChange={(value) => {- onUpdate("active", value ? "on" : "off");+ <ValidatedForm+ defaultValues={{+ active: routeData?.partSummary?.active ?? undefined}}- />- </ValidatedForm>+ validator={z.object({+ active: zfd.checkbox()+ })}+ className="w-full"+ isReadOnly={isReadOnly}+ >+ <Boolean+ label={t`Active`}+ name="active"+ variant="small"+ isDisabled={!!activationLockId}+ onChange={(value) => {+ onUpdate("active", value ? "on" : "off");+ }}+ />+ </ValidatedForm>+ </ItemChangeNoticeLock>)}{/* Manufacturer Part Number is a purchasing attribute — hidden on the COaffected-item card; it stays editable on the part page (non-embedded),diff --git a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsxindex 4775c44acc..4a159ab45e 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx@@ -38,6 +38,7 @@ import {itemReplenishmentSystems,itemTrackingTypes} from "../../items.models";+import type { UnreleasedChangeOrderItem } from "../../items.server";import type {ItemFile,MakeMethod,@@ -45,6 +46,7 @@ import type {SupplierPart,Tool} from "../../types";+import { ItemChangeNoticeLock } from "../ChangeNotice/ItemChangeNoticeLock";import { FileBadge, ItemDescription, SourcingTypeProperty } from "../Item";type ToolPropertiesProps = {@@ -94,6 +96,8 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {name: string;} | null;}>;+ // Set while the change notice that minted this item is still open.+ unreleasedChangeOrder?: UnreleasedChangeOrderItem | null;}>(path.to.tool(itemId));const routeData = data ?? routeDataFromRoute;@@ -185,6 +189,14 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {[routeData?.toolSummary?.readableId]);+ // The change notice that minted this tool activates it at release. Until then+ // the toggle is locked: an unreleased revision switched Active by hand reaches+ // the item pickers, MRP and job creation carrying the notice's draft BOM.+ // An already-active tool is left alone so it can still be switched off.+ const activationLockId = routeDataFromRoute?.toolSummary?.active+ ? undefined+ : routeDataFromRoute?.unreleasedChangeOrder?.changeOrderReadableId;+const [suppliers] = useSuppliers();return (@@ -555,24 +567,39 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {/>))}</VStack>- <ValidatedForm- defaultValues={{- active: routeData?.toolSummary?.active ?? undefined- }}- validator={z.object({- active: zfd.checkbox()- })}+ <ItemChangeNoticeLock+ changeNotices={[]}+ isLocked={!!activationLockId}className="w-full"+ reason={+ activationLockId ? (+ <Trans>+ This tool is activated when change notice {activationLockId} is+ released.+ </Trans>+ ) : undefined+ }>- <Boolean- label={t`Active`}- name="active"- variant="small"- onChange={(value) => {- onUpdate("active", value ? "on" : "off");+ <ValidatedForm+ defaultValues={{+ active: routeData?.toolSummary?.active ?? undefined}}- />- </ValidatedForm>+ validator={z.object({+ active: zfd.checkbox()+ })}+ className="w-full"+ >+ <Boolean+ label={t`Active`}+ name="active"+ variant="small"+ isDisabled={!!activationLockId}+ onChange={(value) => {+ onUpdate("active", value ? "on" : "off");+ }}+ />+ </ValidatedForm>+ </ItemChangeNoticeLock>{routeData?.toolSummary?.replenishmentSystem?.includes("Buy") && (<ValidatedFormdefaultValues={{diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsxindex 6c0c05ca52..c189b793d1 100644--- a/apps/erp/app/routes/x+/items+/update.tsx+++ b/apps/erp/app/routes/x+/items+/update.tsx@@ -1,10 +1,15 @@import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";import { getMaterialDescription, getMaterialId } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import type { InventoryItemType } from "~/modules/items";import { deriveItemMethodUpdate } from "~/modules/items";+import {+ getUnreleasedChangeOrderItems,+ unreleasedChangeOrderItemsMessage+} from "~/modules/items/items.server";import {cascadeItemTrackingType,updateItemMethodAndSourcing@@ -312,7 +317,32 @@ export async function action({ request }: ActionFunctionArgs) {.in("id", materialIds as string[]).eq("companyId", companyId);}- case "active":+ case "active": {+ // Activating is the change notice's job: applyChangeNotice flips the+ // revisions and parts it minted when it reaches Done. Switching one on by+ // hand beforehand puts an unreleased item into the pickers, MRP and job+ // creation carrying the notice's un-approved draft BOM. Deactivating is+ // always allowed — that takes an item out of circulation, never into it.+ if (value === "on") {+ const unreleased = await getUnreleasedChangeOrderItems(+ getCarbonServiceRole(),+ { itemIds: items as string[], companyId }+ );+ if (unreleased.error) {+ return { error: { message: unreleased.error }, data: null };+ }+ if (unreleased.data.length > 0) {+ return {+ error: {+ message: `${unreleasedChangeOrderItemsMessage(+ unreleased.data+ )} Release the change notice to activate it.`+ },+ data: null+ };+ }+ }+return await client.from("item").update({@@ -322,6 +352,7 @@ export async function action({ request }: ActionFunctionArgs) {}).in("id", items as string[]).eq("companyId", companyId);+ }case "itemPostingGroupId":// Update itemCost table for all selected itemsdiff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsxindex 48cc46a9f2..eb4d259307 100644--- a/apps/erp/app/routes/x+/job+/new.tsx+++ b/apps/erp/app/routes/x+/job+/new.tsx@@ -7,6 +7,7 @@ import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { useUrlParams, useUser } from "~/hooks";+import { getUnreleasedChangeOrderIssue } from "~/modules/items/items.server";import { insertJob, jobValidator } from "~/modules/production";import { JobForm } from "~/modules/production/ui/Jobs";import type { MethodItemType } from "~/modules/shared";@@ -45,6 +46,24 @@ export async function action({ request }: ActionFunctionArgs) {}}+ // A job pulls the item's active make method, and for an item a change notice+ // still holds that is the notice's un-approved draft BOM. Refuse the job until+ // the notice releases. Checked here rather than only in the picker because this+ // action is also reached by the API and the MCP tools.+ if (data.itemId) {+ const unreleasedIssue = await getUnreleasedChangeOrderIssue(+ getCarbonServiceRole(),+ { itemId: data.itemId, companyId }+ );+ if (unreleasedIssue) {+ return validationError({+ fieldErrors: {+ itemId: `${unreleasedIssue} A job cannot be made for it.`+ }+ });+ }+ }+const result = await insertJob(getCarbonServiceRole(),{diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsxindex 573c94589f..dfe38492bd 100644--- a/apps/erp/app/routes/x+/part+/$itemId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx@@ -42,6 +42,7 @@ import {getSupplierParts,isChangeNoticeOpen} from "~/modules/items";+import { getUnreleasedChangeOrderForItem } from "~/modules/items/items.server";import type { Method } from "~/modules/items/types";import {BoMActions,@@ -83,7 +84,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {tags,supersession,supersededBy,- allChangeNotices+ allChangeNotices,+ unreleasedChangeOrder] = await Promise.all([getPart(client, itemId, companyId),getSupplierParts(client, itemId, companyId),@@ -93,7 +95,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getItemSupersededBy(client, itemId, companyId),// Every CO, any status; the open subset (which locks manual version/revision// creation) is derived below.- findChangeNoticesForItem(client, { itemId, companyId })+ findChangeNoticesForItem(client, { itemId, companyId }),+ // Locks the Active toggle while the change notice that minted this item is+ // still open — release is what activates it.+ getUnreleasedChangeOrderForItem(client, { itemId, companyId })]);if (partSummary.data?.companyId !== companyId) {@@ -168,7 +173,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {changeNotices,openChangeNotices,// Fail closed: a lookup we couldn't read can't prove the item is CO-free.- changeNoticesUnavailable: allChangeNotices.error !== null+ changeNoticesUnavailable: allChangeNotices.error !== null,+ unreleasedChangeOrder};}diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsxindex 46cbcc4de6..e89c48c694 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.new.tsx@@ -1,9 +1,11 @@import { assertIsPost, 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 { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect, useParams } from "react-router";+import { getUnreleasedChangeOrderIssue } from "~/modules/items/items.server";import {getPurchaseOrder,isPurchaseOrderLocked,@@ -61,6 +63,21 @@ export async function action({ request, params }: ActionFunctionArgs) {// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migrationconst { id, ...d } = validation.data;+ // An item a change notice is still holding is not purchasable — it is a draft+ // revision the supplier has never been shown. Checked here rather than only in+ // the picker because this action is also reached by the API and the MCP tools.+ if (d.itemId) {+ const unreleasedIssue = await getUnreleasedChangeOrderIssue(+ getCarbonServiceRole(),+ { itemId: d.itemId, companyId }+ );+ if (unreleasedIssue) {+ return validationError({+ fieldErrors: { itemId: `${unreleasedIssue} It cannot be purchased.` }+ });+ }+ }+const createPurchaseOrderLine = await upsertPurchaseOrderLine(client, {...d,companyId,diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsxindex 53cafd98fb..24f7dcd54f 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.new.tsx@@ -1,10 +1,12 @@import { assertIsPost, 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 { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { redirect, useParams } from "react-router";import { useRouteData, useUser } from "~/hooks";+import { getUnreleasedChangeOrderIssue } from "~/modules/items/items.server";import type { Customer, SalesOrder, SalesOrderLineType } from "~/modules/sales";import {getSalesOrder,@@ -62,6 +64,21 @@ export async function action({ request, params }: ActionFunctionArgs) {d.assetId = undefined;}+ // An item a change notice is still holding is not sellable — it is a draft+ // revision whose BOM has not been approved. Checked here rather than only in+ // the picker because this action is also reached by the API and the MCP tools.+ if (d.itemId) {+ const unreleasedIssue = await getUnreleasedChangeOrderIssue(+ getCarbonServiceRole(),+ { itemId: d.itemId, companyId }+ );+ if (unreleasedIssue) {+ return validationError({+ fieldErrors: { itemId: `${unreleasedIssue} It cannot be ordered.` }+ });+ }+ }+const createSalesOrderLine = await upsertSalesOrderLine(client, {...d,companyId,diff --git a/apps/erp/app/routes/x+/tool+/$itemId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.tsxindex f64ae5d869..befcec445e 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.tsx@@ -42,6 +42,7 @@ import {getTool,isChangeNoticeOpen} from "~/modules/items";+import { getUnreleasedChangeOrderForItem } from "~/modules/items/items.server";import { BoMActions, BoMExplorer } from "~/modules/items/ui/Item";import type { UsedInNode } from "~/modules/items/ui/Item/UsedIn";import {@@ -78,7 +79,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {tags,supersession,supersededBy,- allChangeNotices+ allChangeNotices,+ unreleasedChangeOrder] = await Promise.all([getTool(client, itemId, companyId),getSupplierParts(client, itemId, companyId),@@ -88,7 +90,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getItemSupersededBy(client, itemId, companyId),// Every CO, any status; the open subset (which locks manual version/revision// creation) is derived below.- findChangeNoticesForItem(client, { itemId, companyId })+ findChangeNoticesForItem(client, { itemId, companyId }),+ // Locks the Active toggle while the change notice that minted this item is+ // still open — release is what activates it.+ getUnreleasedChangeOrderForItem(client, { itemId, companyId })]);if (toolSummary.error) {@@ -152,7 +157,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {changeNotices,openChangeNotices,// Fail closed: a lookup we couldn't read can't prove the item is CO-free.- changeNoticesUnavailable: allChangeNotices.error !== null+ changeNoticesUnavailable: allChangeNotices.error !== null,+ unreleasedChangeOrder};}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex d12a73faee..29538a27a8 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -15463,6 +15463,9 @@ msgstr "Diese Seite deines Implementation Hub wird gerade aufgebaut. Starten Siemsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Dieses Teil hat {quantityOnHand} auf Lager an diesem Standort. „Kein Bestand\" bedeutet, dass es weder geplant noch verbraucht wird."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Dieses Teil wird schrittweise eingestellt."@@ -15512,6 +15515,9 @@ msgstr "Dieser Speichertyp wird derzeit von {usageCount} Speichereinheit{0} verwmsgid "this supplier"msgstr "dieser Lieferant"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "Dies aktualisiert das Design für alle Benutzer der Anwendung"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex d5cb14a7ca..cf8056a57d 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -15463,6 +15463,9 @@ msgstr "This page of your Implementation Hub is being built. Start from the commmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr "This part is activated when change notice {activationLockId} is released."+msgid "This part is being phased out."msgstr "This part is being phased out."@@ -15512,6 +15515,9 @@ msgstr "This storage type is currently used by {usageCount} storage unit{0}."msgid "this supplier"msgstr "this supplier"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr "This tool is activated when change notice {activationLockId} is released."+msgid "This updates the theme for all users of the application"msgstr "This updates the theme for all users of the application"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 14b070cfb7..ec02e44b1e 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -15463,6 +15463,9 @@ msgstr "Esta página de tu Centro de Implementación está en construcción. Commsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Esta pieza tiene {quantityOnHand} disponible en esta ubicación. Sin Stock significa que no será ni planificada ni consumida."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Esta pieza se está descontinuando."@@ -15512,6 +15515,9 @@ msgstr "Este tipo de almacenamiento está siendo utilizado actualmente por {usagmsgid "this supplier"msgstr "este proveedor"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "Esto actualiza el tema para todos los usuarios de la aplicación"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 95551e1bad..29c583d1f9 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -15463,6 +15463,9 @@ msgstr "Cette page de votre Implementation Hub est en cours de construction. Commsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Cette pièce a {quantityOnHand} en stock à cet endroit. Aucun stock signifie qu'elle ne sera ni planifiée ni consommée."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Cette pièce est en cours de suppression."@@ -15512,6 +15515,9 @@ msgstr "Ce type de stockage est actuellement utilisé par {usageCount} unité demsgid "this supplier"msgstr "ce fournisseur"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "Cela met à jour le thème pour tous les utilisateurs de l'application"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex be3be7c275..00628747b4 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -15463,6 +15463,9 @@ msgstr "आपके Implementation Hub का यह पृष्ठ बनाmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "यह पार्ट इस स्थान पर {quantityOnHand} की मात्रा में उपलब्ध है। No Stock का अर्थ है कि इसकी न तो योजना बनाई जाएगी और न ही इसका उपयोग किया जाएगा।"+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "यह पार्ट चरणबद्ध तरीके से बंद किया जा रहा है।"@@ -15512,6 +15515,9 @@ msgstr "यह स्टोरेज प्रकार वर्तमानmsgid "this supplier"msgstr "यह आपूर्तिकर्ता"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "यह एप्लिकेशन के सभी उपयोगकर्ताओं के लिए थीम को अपडेट करता है"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 594f2aa7c4..776a9acb67 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -15463,6 +15463,9 @@ msgstr "Questa pagina del tuo Implementation Hub è in fase di costruzione. Inizmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Questo pezzo ha {quantityOnHand} disponibile in questa ubicazione. No Stock significa che non sarà né pianificato né consumato."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Questa parte è in fase di eliminazione."@@ -15512,6 +15515,9 @@ msgstr "Questo tipo di archiviazione è attualmente utilizzato da {usageCount} umsgid "this supplier"msgstr "questo fornitore"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "Questo aggiorna il tema per tutti gli utenti dell'applicazione"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 65c363eee2..8a57316f7a 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -15463,6 +15463,9 @@ msgstr "このページのImplementation Hubは現在構築中です。完成すmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "このパーツはこの場所に{quantityOnHand}個あります。「在庫なし」は計画にも消費にも含まれないことを意味します。"+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "このパーツは段階的に廃止されています。"@@ -15512,6 +15515,9 @@ msgstr "このストレージタイプは現在{usageCount}個のストレージmsgid "this supplier"msgstr "このサプライヤー"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "これはアプリケーションのすべてのユーザーのテーマを更新します"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex a009a4302a..2d6c40f3c2 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -15463,6 +15463,9 @@ msgstr "구현 허브의 이 페이지는 준비 중입니다. 완성될 때까msgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "이 품목은 이 위치에 {quantityOnHand}개가 보유되어 있습니다. 재고 없음으로 설정하면 계획 및 소비 대상에서 제외됩니다."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "이 품목은 단계적으로 단종되는 중입니다."@@ -15512,6 +15515,9 @@ msgstr "이 저장 유형은 현재 저장 단위 {usageCount}개{0}에서 사msgid "this supplier"msgstr "이 공급업체"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "이 설정은 애플리케이션의 모든 사용자에 대한 테마를 업데이트합니다"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 5953ddfb62..eb584352b3 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -15463,6 +15463,9 @@ msgstr "Ta strona Twojego Implementation Hub jest w trakcie budowy. Zacznij od cmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Ta część ma {quantityOnHand} na stanie w tej lokalizacji. Brak zapasów oznacza, że nie będzie ani planowana, ani zużywana."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Ta część jest wycofywana."@@ -15512,6 +15515,9 @@ msgstr "Ten typ magazynu jest obecnie używany przez {usageCount} jednostkę magmsgid "this supplier"msgstr "ten dostawca"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "To aktualizuje motyw dla wszystkich użytkowników aplikacji"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex e23cc0e02e..2b4df615a0 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -15463,6 +15463,9 @@ msgstr "Esta página do seu Implementation Hub está sendo construída. Comece pmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Esta peça tem {quantityOnHand} em mãos nesta localização. Sem Estoque significa que não será planejada nem consumida."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Esta peça está sendo descontinuada."@@ -15512,6 +15515,9 @@ msgstr "Este tipo de armazenamento está sendo usado por {usageCount} unidade demsgid "this supplier"msgstr "este fornecedor"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "Isto atualiza o tema para todos os utilizadores da aplicação"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex f1f7700c70..d5dc72b17d 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -15463,6 +15463,9 @@ msgstr "Эта страница вашего Implementation Hub находитсmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Эта деталь имеет {quantityOnHand} на складе в этом месте. Режим \"No Stock\" означает, что она не будет ни планироваться, ни использоваться."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Эта деталь снимается с производства."@@ -15512,6 +15515,9 @@ msgstr "Этот тип хранилища в настоящее время исmsgid "this supplier"msgstr "этот поставщик"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "Это обновляет тему для всех пользователей приложения"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 85ab4d51c4..db8f70b5ce 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -15463,6 +15463,9 @@ msgstr "Bu Implementation Hub sayfası şu anda inşa edilmektedir. Biz bitirirkmsgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "Bu parça bu konumda {quantityOnHand} adet stokta bulunmaktadır. Stok Yok, bunun ne planlanacağı ne de tüketileceği anlamına gelir."+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "Bu parça aşamalı olarak kullanımdan kaldırılıyor."@@ -15512,6 +15515,9 @@ msgstr "Bu depolama türü şu anda {usageCount} depolama birimi{0} tarafındanmsgid "this supplier"msgstr "bu tedarikçi"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "Bu, uygulamanın tüm kullanıcıları için temayı günceller"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 6b2c1f76f4..c613a29ab3 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -15463,6 +15463,9 @@ msgstr "您的实现中心的此页面正在构建中。请从命令中心开始msgid "This part has {quantityOnHand} on hand at this location. No Stock means it will be neither planned nor consumed."msgstr "此零件在此位置有 {quantityOnHand} 件现货。\"无库存\"意味着它既不会被计划也不会被消耗。"+msgid "This part is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This part is being phased out."msgstr "这个零件正在逐步淘汰。"@@ -15512,6 +15515,9 @@ msgstr "此存储类型当前被 {usageCount} 个存储单元{0}使用。"msgid "this supplier"msgstr "此供应商"+msgid "This tool is activated when change notice {activationLockId} is released."+msgstr ""+msgid "This updates the theme for all users of the application"msgstr "这会更新应用程序所有用户的主题"