Skip to content

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.

43.2 KB
Raw Blame

Items Module

Master data for all item types (Parts, Materials, Tools, Consumables, Services), bill of materials (make methods), unit of measure management, material taxonomy, item costing, shelf life, configurations, supersessions, pick methods, and item posting groups.

Key Domain Concepts

  • Item Types — Parts (manufactured/purchased goods), Materials (raw materials with taxonomy), Tools, Consumables, Services. All share the item table; type-specific tables (part, material, tool, consumable, service) extend it.
  • Make Method — versioned manufacturing method on an item: BOM (methodMaterial) + routing (methodOperation). Statuses: Draft/Active/Archived. MUST create a new version instead of editing Active methods.
  • Material Taxonomy — structured properties via FK relationships: materialSubstance (steel, aluminum), materialForm (sheet, plate, roundbar), materialType, materialGrade, materialFinish, materialDimension. Global rows (companyId IS NULL) are system-seeded.
  • Item Tracking Type — Inventory (quantity only), Serial (unique per unit), Batch (lot-tracked), Non-Inventory (not stocked). Drives behavior in inventory, receipts, and picking.
  • Replenishment System — Buy, Make, or Buy and Make. Drives MRP planning and method availability. sourcingType (Specified/Drop Ship/Ship from Inventory) is item-level and cascades to methodMaterial rows.
  • Shelf Life — batch/serial items can have expiry tracking. Modes: Fixed Duration, Calculated, Set on Receipt.
  • Supersession — item replacement chain for obsolete parts via itemSupersession.

Safety

Always

  • MUST use upsertMaterial for material creation — it handles both item and material table inserts with readableId linkage.
  • MUST remember: material.id = item.readableId, NOT item.id. Join via readableId + companyId.
  • MUST use assertMethodOperationIsDraft before deleting method operations — Active/Archived methods are protected.
  • MUST use updateItemMethodAndSourcing when changing replenishmentSystem, defaultMethodType, or sourcingType — it cascades to Draft method materials.

Ask First

  • Deleting items that have inventory, open POs, or active jobs — blocked at the DB by FKs to item: trackedEntity (serial/batch) via ON DELETE RESTRICT, and itemLedger/costLedger (any inventory movement or cost history) via ON DELETE NO ACTION. Deactivate the item instead. NO ACTION (not RESTRICT) is deliberate so whole-company cascade deletes still work.
  • Changing how a unit of measure is deleted — prevent_unit_of_measure_deletion_when_in_use_trigger refuses any delete whose code is still referenced, across all 33 UoM columns including the ten that have no foreign key. It reads the referencing columns from information_schema at runtime, so a new table is covered without a migration. For those ten columns the guarantee is not concurrency-safe: a write takes no lock on the unitOfMeasure row, so one that commits between the trigger's check and the delete's commit can still leave a dangling code.
  • Changing itemTrackingType on items that already have tracked entities — use cascadeItemTrackingType.
  • Modifying Active method versions — create a new version instead.

Never

  • Directly insert material rows without corresponding item rows.
  • Assume material has an itemId column — it was dropped; linkage is material.id = item.readableId.
  • Delete global taxonomy rows (companyId IS NULL) — they're system-seeded and shared across companies.
  • Edit methodMaterial.sourcingType/methodType per-row — they're derived from the component item. Change sourcing on the item instead.

Validation Commands

pnpm exec turbo run typecheck --filter=erp --concurrency=1   # the package is "erp", not "@carbon/erp"
pnpm --filter erp test

Key Data Model

Table / View Purpose
item Universal item master: readableId, name, type, tracking, replenishment, UoM
part / material / tool / consumable / service Type-specific extensions
materialForm / materialSubstance / materialType / materialGrade / materialFinish / materialDimension Material taxonomy (global or company-scoped)
makeMethod Versioned manufacturing method header (Draft/Active/Archived)
methodMaterial / methodOperation / methodOperationStep / methodOperationParameter / methodOperationTool BOM lines, routing steps, and work instruction details
itemCost / costLedger Standard/average costs and cost history
itemReplenishment / itemPlanning Manufacturing settings (lot size, lead time, scrap %) and planning params — per location: the reorder policy and its sizing parameters, planningHorizonDays (the item's time fence on the planning pages; empty = inherit the company default, 0 = no fence) and responsibleEmployee (the leaf rung of the MRP action owner ladder), all on itemPlanningValidator / ItemPlanningForm. ItemReorderPolicy sizes the tab's suggested orders with computePlanningOrders (@carbon/utils), the same sizing MRP uses; api+/items.$id.$locationId.forecast.ts nets demandProjection.consumedQuantity so the chart matches the planning grids
itemPostingGroup Maps item categories to GL accounts
unitOfMeasure UoM definitions
configurationParameter / configurationRule / configurationParameterGroup Product configurator
supplierPart / supplierPartPrice Supplier-item pricing with conversion factors and price breaks. supplierUnitPrice is per purchase unit in supplierPart.currencyCode (NULL = base); readers convert at today's rate (.claude/rules/purchasing-conversion-factors.md)
pickMethod Default storage unit and pick strategy per item/location
itemShelfLife Shelf life tracking configuration per item
itemSupersession Item replacement chains

Key Service Functions

  • getItem / getPart / getMaterial / getConsumable / getTool / getService — item reads by type (RPCs get_part_details, get_material_details, get_service_details, etc.)
  • upsertService — creates/updates a Service item; always itemTrackingType = 'Non-Inventory' (never shipped/received/stocked), replenishment Buy or Make only. The service row is keyed by item.readableId (like tool/material). Legacy service.serviceType is defaulted and no longer read.
  • upsertPart / upsertTool / upsertConsumable / upsertService — an update takes companyId and an id that is the item uuid or the readable id; it writes the item row by uuid and the typed row by readableId + companyId (updateTypedItem), and an update that matches no row returns an error. A readable id shared by several revisions is refused.
  • upsertMaterial(client, db, material) — creates/updates material with taxonomy FKs and item/material linkage; an update writes only the keys sent and never touches active. Over MCP name, replenishmentSystem, defaultMethodType, itemTrackingType and unitOfMeasureCode are required, so they are always sent; with generated material IDs a sent name is ignored
  • updateMaterialProperties(client, db, material) — the one path for substance/form/type/finish/grade/dimension changes (properties panel, upsertMaterial, MCP): dependent resets, pick-list checks, generated-ID renames in one transaction. See .claude/rules/material-tables.md
  • getMakeMethods / getMethodMaterials / getMethodOperations / getMethodTreeArray — BOM/routing reads
  • copyItem / copyMakeMethod — duplicates via getMethod (production.service.ts, ported from the get-method server function)
  • createMakeMethodVersion(client, db, args) — a new Draft version of a make method, behind createMethodVersion (the New Version route, the API and MCP), a Version change notice's draft and the Onshape panel's Draft. One Kysely transaction inserts the Draft (with args.changeOrderId, else the source's), sets a Draft source Active when args.activate is set (an Active or Archived source is left alone), and copies the BoM/BoP through copyMakeMethod. A failed copy therefore leaves no empty version and no source set Active. Handed a transaction, it joins it (withTransaction, @carbon/database/client), so a caller can add its own writes to the same commit; get-method joins the same way. Kysely bypasses RLS, so it first checks parts_create (and parts_update when it activates) through the caller's client, then copies as the system: the method line policies ask for no more than parts_create, while get-method's own gate asks for production update. A refused copy comes back as the posting's ServerFnError; createMethodVersion refuses an activeVersionId other than copyFromId before it calls it
  • createRevision(client, db, args) / activateMethodVersion — revision and version management; the revision's item row and the planning and purchasing setup it inherits from the source are written in one Kysely transaction, gated by assert_company_access(companyId, 'parts_create') through the caller's client
  • updateItemMethodAndSourcing — cascades replenishment/sourcing changes to Draft method materials
  • getItemCost / getItemQuantities / getItemDemand — cost and planning reads
  • items.utils.ts — getNextRevision, getConfigurationParameters, getItemStorageUnitQuantities, and the supplier pricing reads getSupplierPriceBreaksForItems, lookupBuyPrice, getSupplierPartPricing, getSupplierPartPriceBreaks. Import them from this file, not the service
  • getSupplierParts / getSupplierPriceBreaksForItems / lookupBuyPrice — vendor pricing (the latter two in base per inventory unit, for costing); getSupplierPartPricing — a part's price + breaks with its currency's current rate, for resolveSupplierPrice on a purchase document
  • getSupplierPartsBySupplier — every active supplier part naming one supplier, with its item embedded, paged past the 1000-row cap (fetchAllRecords); backs the supplier's Parts tab (x+/supplier+/$supplierId.parts.tsx, purchasing/ui/Supplier/SupplierParts.tsx, client-side search). Its New / edit drawers post to the picked item's own purchasing routes (SupplierPartForm with selectItem), so every item-type create and edit route returns the createSupplierPart / updateSupplierPart result instead of redirecting
  • upsertPickMethodWithShelfLife — pick method with shelf life configuration
  • getConfigurationParameters / getConfigurationRules — product configurator
    • A rule on itemId:<methodMaterialId> returns an item id (not a readable id). On a Make to Order line the job or quote explodes the configured item's active make method, not the BOM item's (configuredMadeChild in production.service.ts, all four getMethod paths); a configured item with no make method leaves the line with no sub-assembly.
  • createItemDocumentUploadUrl — MCP file upload (step 1): presigned URL for an item document (parts/{itemId} folder); pair with documents_insertUploadedDocument. See .claude/rules/mcp-tools-reference.md → "File uploads"
  • createModelUploadUrl / insertModelUpload — the API/MCP CAD model upload, and the one path the browser's api+/model.upload.ts shares: step 1 signs an upload into temp-staging (2.5 GB, where the dropzone stages raw CAD) at ${companyId}/models/${modelId}.${ext}; step 2 records the modelUpload row, links it to any of itemId / jobId / salesRfqLineId / quoteLineId / salesOrderLineId (each checked first, all scoped by companyId), and starts assembly-convert for a STEP file with convert. The insert itself starts model-optimize: the queue_model_pipeline statement handler on modelUpload sends it for every new row, whoever inserts it, so no caller sends it. No transaction spans the row and the links: a failed link returns an error, the model row stands and is still processed

Operations (items.server.ts)

Each is a defineServiceFn const in items.server.ts. The route calls it as api.items.<name>(input); the API and MCP publish the ones tagged @mcp as items_<name>. It holds every check the route made. Routes validate the request, call one, and answer with respond(request, result).redirect(…) (a flash) or the result. Permission is parts throughout; where a function's permission differs from its old route's, it holds both the route's gate and the policy its write runs under (updateMethodMaterial / updateMethodOperation need create and update, removeChangeNoticeAffectedItem delete).

  • Items — the bulk actions of the items tables and the properties panels (x+/items+/update.tsx, one field per post): setItemTrackingType (the item, then cascadeItemTrackingType), setItemFields (name, description, MPN, unit of measure), setItemSourcing (exactly one of replenishment system, default method type, sourcing type; deriveItemMethodUpdate then updateItemMethodAndSourcing), setItemActive (activating refuses an item an unreleased change notice created), setItemPostingGroup (on the item's cost row, created when missing), setItemReadableId (every revision and the type row). updateItem writes the item row only: it refuses a readableId that differs from the item's and a type the item is not, since the type row is keyed by the readable id.
  • createPart, updatePart, updateTool, setMaterialProperties (updateMaterialProperties per material), renameService.
  • updateItemManufacturing and updateItemPlanning (the four item types' planning tabs) save, then re-plan the item (replanAfterItemChange, production.server.ts); planning refuses a responsible employee who is not an active employee.
  • setItemSupersession (the part's own supersession), addItemPredecessor (written on the predecessor). Both return a loop as rule, which the planning route shows as a field error.
  • createSupplierPart, updateSupplierPart (with the drawer's price breaks, replaced in one transaction).
  • copyMethod (Get Method and Save Method, behind checkRevisionLock), createMethodVersion, syncOnshapeMethod (the Onshape panel's Sync, api+/integrations.onshape.sync.ts: syncMakeMethod (items.service.ts, ported from the sync server function) rewrites the bill of materials, then the item is mapped to its Onshape document). deleteMethodOperation (behind checkRevisionLock). deleteMethodMaterials / deleteMethodOperations (unpublished; the bill of material and bill of process Delete Selected, methods+/material.delete.tsx and operation.delete.tsx) take rows of ONE make method (getSingleMakeMethodId) and check that method's lock once. Every other published bill of materials / process write holds the same lock its methods+/ route checks: material, operation, parameter, tool and step create / update / delete, activateMethodVersion (checkRevisionLocks checks both the row's own method and the one an update names). With release control on warn the write goes ahead and returns the lock's message as notice (withLockNotice). updateMaterialOrder / updateOperationOrder (the methods+/*.order.tsx routes) take rows of ONE make method and write the order with updateSortOrder. Step, slide and step-link writes also need a Draft method (methodStepRefusal); assertMethodOperationIsDraft returns that refusal as rule. recalculateItemCost (the costing card's Recalculate).
  • createChangeNotice (with the picked parts), createChangeNoticeForItem, setChangeNoticeStatus (the approval gate, the release through applyChangeNotice, the stage notifications), decideChangeNoticeApproval. The notice and child writes (updateChangeNotice, the affected-item and action-task operations) hold requireChangeNoticeEditable themselves: engineering scope for affected items and the narrative, workflow scope for action tasks and header fields; a child row addressed by its own id resolves its notice through requireChangeNoticeChildEditable.

The building blocks they call are in items.service.ts (upsertPart, upsertItemPlanning, upsertItemManufacturing, upsertItemSupersession, upsertSupplierPart, copyItem, copyMakeMethod, createMakeMethodVersion, insertChangeNotice, updateChangeNoticeStatus, cascadeItemTrackingType, updateItemMethodAndSourcing). A building block is never a tool. Import other modules' code from the file that defines it (*.service.ts, *.models.ts).

Key Exports

import { getItem, upsertMaterial, getMakeMethods } from "~/modules/items/items.service";
import { itemValidator, itemTrackingTypes, itemReplenishmentSystems } from "~/modules/items/items.models";

Change Orders (sub-area)

Engineering-change-order (ECO) workflow — a top-to-bottom, affected-items-first process: the user picks the parts/tools to change, sets a per-item change type (Version / Revision / Replacement Part / New Part), edits each item's BOM/BOP/attributes directly on a real CO-owned Draft makeMethod (via the normal embedded editors), and releases the CO — which activates each draft and propagates via supersession (except a net-new New Part, which has no predecessor). Lives inside the Items module (not a standalone module). Permission key is parts — loaders/actions use requirePermissions(request, { view | update | delete | create: "parts" }). Routes live under apps/erp/app/routes/x+/items+/change-notice+/ (detail + affected/action child mutations) and x+/items+/change-notices+/ (list + Types config); URLs are /x/items/change-notice(s)…. The create form is the exception: it lives at a top-level apps/erp/app/routes/x+/change-notice+/new.tsx (URL /x/change-notice/new, path helper path.to.newChangeNotice) so it renders with the app sidebar like /x/part/new and /x/sales-order/new, not nested under the Items module layout. Navigation is a "Change Notices" group in the Items sidebar (useItemsSubmodules). The $id detail page uses the standard 3-pane detail convention (PanelProvider + ResizablePanels from ~/components/Layout/Panels, like sales-order / job): ChangeNoticeExplorer (affected-items list) is the explorer, the content is a URL-addressed Outlet, and ChangeNoticeProperties (header fields + affected assemblies + impact + release dialog, self-contained via useRouteData) is the properties panel. $id.tsx keeps hideModuleSidebar: true so the Items grouped sidebar doesn't stack next to the explorer. The content follows the sales-order top-level-detail + line-route split: $id.details.tsx is the CO overview (the ChangeNoticeStatusFlow state bar + the two rich-text narrative fields reasonForChange / description via ChangeNoticeContent, debounced 2.5s then POSTed to the $id.content action (NOT a direct carbon.from("changeOrder").update like the quality issue — that had no server-side place to enforce the engineering lock) — plus the CO-wide Changes rollup (ChangeNoticeChanges — every affected item's authoring diff, rendered between the description and the actions, same label+ChangeNoticeDiffViewer list as the release dialog) and the action tasks via the shared ActionTaskList + "Add Actions" modal, reconciled through $id.action); each affected item is its own line route $id.$affectedId.details.tsx (URL /x/items/change-notice/$id/$affectedId/details, path.to.changeNoticeAffectedItem, rendering AffectedItemDetail), linked from the explorer (Revision / Replacement Part rows show "OLD → NEW" with the minted item's number, resolved from the items store; a New Part shows a single id — it is net-new, so its newItemId equals its itemId and there is no predecessor to arrow from, guarded by newItemId !== itemId). Purchasable draft items get supplier-part management on the line: a Revision/New Part line whose draft part is Buy/Buy and Make renders the embedded SupplierParts grid (data from partData.supplierParts, already in the $id loader); its create/edit drawers are child routes $id.$affectedId.details.new.tsx / $id.$affectedId.details.$supplierPartId.tsx (the SupplierPartForm posts to the PART purchasing actions — the part create and edit actions return the createSupplierPart / updateSupplierPart result instead of redirecting so embedded callers stay put, and a duplicate supplier shows as a field error under Supplier), and delete is the action-only $id.$affectedId.details.$supplierPartId.delete.tsx (path.to.changeNoticeDeleteSupplierPart). $id._index redirects to the overview; the header CO-id links back to it. Reason and description are taken as Markdown or a Tiptap document and stored as a document (optionalTiptapDoc, shared.models.ts), on create and update.

No staged mirror tables. The v1 changeOrderStaged* tables were deleted. A CO's per-affected-item edits now live on a real Draft makeMethod whose makeMethod.changeOrderId points at the CO, edited via the embedded real BillOfMaterial / BillOfProcess editors on the CO detail page. The same draft method also surfaces on the affected item's own master page (/x/part|tool/$itemId/details): the item-detail loaders (x+/part+/$itemId{.,}.tsx, x+/tool+/$itemId.details.tsx) select it like any other method and no longer exclude changeOrderId-stamped drafts, so a revision/new-part item created by an open CO shows its BOM/BOP on the item master too — the two surfaces edit the same rows and stay in sync. (Active is still preferred as the default selection, so a Version CO's existing item keeps its live method by default.) changeOrderId is cleared at release.

Change-order code follows the one-service/models/server-per-module convention — it lives in the module's canonical files, NOT separate changeNotice.* files: items.service.ts holds header CRUD + guarded stage transition + Types config + affected-item CRUD + the CO-owned Draft orchestration (createChangeNoticeDraftMethod / addChangeNoticeAffectedItem / updateChangeNoticeAffectedItemChangeType / cutover) + the diffMethod pure engine + getChangeNoticeDiff authoring-diff wrapper + item↔CO traceability reads (findChangeNoticesForItem, linked-NCR reverse) + freeform action-task CRUD + the release path (applyChangeNotice orchestration + releaseAffectedItem + notifications); items.server.ts holds the change-notice service functions (createChangeNotice, setChangeNoticeStatus, addChangeNoticeAffectedItem, …); items.models.ts holds the validators + state machine + changeNoticeChangeTypes + diff types. There is no barrel: import from ~/modules/items/items.models or ~/modules/items/items.service, and call the service functions through carbon(request).

Approval gate (optional, APPROVAL_RULES plan feature). When the company has an enabled changeOrder approval rule (Settings → Approval Rules → Change Notices; amount-less, at most one rule), Engineering Complete → Implementation is gated. The CO code is wiring only; the lifecycle lives in the shared @carbon/ee/approvals/document.server helpers. setChangeNoticeStatus ($id.status.tsx) calls openApprovalRequests and notifies the approvers instead of moving the status. decideChangeNoticeApproval ($id.approval.tsx) calls decideApprovalRequest; approving runs the CAS Engineering Complete → Implementation inside approveRequest, rejecting leaves the status. Cancelling (setChangeNoticeStatus) and deleting (deleteChangeNotice) call cancelPendingApprovals. The $id loader returns approval (getDocumentApprovalState, only at Engineering Complete). While a request is pending, engineering-scope edits are locked: getChangeNoticeEngineeringLock (items.service.ts) backs both requireChangeNoticeEditable and checkRevisionLock, and useChangeNoticeEngineeringLock (ui/ChangeNotice/lock-ui.tsx) is the UI half. Workflow scope stays editable. Without a rule, stages advance freely; a CO reaches Done via applyChangeNotice. Same-part parallel COs are allowed: there is no one-open-CO-per-part guard.

Key CO concepts

  • Stage flow — changeOrderStatus: Draft → Start → Engineering Complete → Implementation → Done, plus a Cancelled off-ramp. Table-driven, one step forward (changeNoticeStatusTransitions / isAllowedChangeNoticeTransition — the check is purely allowed.includes(to), NOT directional), with two backward reopen edges: Implementation → Engineering Complete and Cancelled → Draft. Both are ⋮-menu items in ChangeNoticeHeader. Done is terminal — releasing already activated methods and wrote supersessions, so it cannot be reopened. The reopen edge must stay LAST in the Implementation array: the header reads transitions[status]?.[0] for its advance/release action. changeNoticeOpenStatuses = every stage before Done. Start/Implementation/Done notify the CO assignee + action-task assignees (changeNoticeNotifyStages; notifyChangeNoticeTransition resolves the recipients — not a company-wide broadcast).
  • Two lock scopes (items.models.ts) — isChangeNoticeLocked(status) is true at Done/Cancelled (fully closed). On top of that: canEditChangeNoticeEngineering(status) additionally excludes Implementation and gates affected items (add/remove/change-type), the staged BOM/BOP drafts, cutover config, and reasonForChange/description; canEditChangeNoticeWorkflow(status) is the closed-only test and gates action tasks, assignee, dates and priority — those stay editable at Implementation, which is the whole point of that stage. (canEditChangeNotice was split into these two and no longer exists.) Server enforcement is requireChangeNoticeEditable(client, { changeNoticeId, companyId, scope }) in items.service.ts; the UI isDisabled is cosmetic on top of it. BOM/BOP mutations are covered centrally — checkRevisionLock also resolves the owning CO's status, so all ~17 methods+/ routes inherit the lock without their own guard. Note item.changeOrderId is a PERMANENT back-link (unlike makeMethod.changeOrderId, cleared at release), so it must never be used to resolve ownership.
  • Change type (capability matrix) — changeOrderAffectedItem.changeType ∈ Version | Revision | Replacement Part | New Part (changeNoticeChangeTypes) drives both the editable surface and the release action. Two axes: is there a predecessor and same part number. The Add Affected Item modal (AffectedItemForm) is Parts-only: the existing-item picker filters to validItemTypes={["Part"]} and the New Part mini-form always mints a Part — no Tool path in the UI (the service's addChangeNoticeAffectedItem/createChangeNoticeDraftMethod still technically accept Tools, but no route surfaces them). The modal's two branches (New Part vs existing-item) are separate ValidatedForms that MUST carry distinct key props — same-slot same-type reconciliation would otherwise share one RVF store, hydrating controlled-field defaults only for whichever branch mounts first (New Part's replenishment/tracking Selects would then submit "" → enum error).
    • Version — a new Draft method version on the same item (BoM/BoP edits); no supersession.
    • Revision — a new inactive revision item (same #, new rev) with both BoM/BoP and attributes/docs; the draft method is edited via the embedded BillOfMaterial/BillOfProcess, and the draft item's attributes + files via the embedded PartProperties (embedded variant) on the CO card; auto oldRev→newRev supersession at release. (BoM/BoP on a Revision was a client ask — a revision can carry a manufacturing change, not just a doc/spec change.) The Add Affected Item modal shows a revision text input for a Revision change so the user can name the revision (e.g. A); blank → createChangeNoticeDraftMethod auto-computes the next revision via getNextRevision. (The optional revision threads validator → $id.affected route → addChangeNoticeAffectedItem → createChangeNoticeDraftMethod.)
    • Replacement Part — a new part number derived from the affected part, BoM/BoP and attributes (embedded PartProperties); auto affected→new supersession at release. The 1:1 replacement (renamed from the old "New Part"). Restricted to Parts. Embedded attribute editing is currently wired for Parts only.
    • New Part — a net-new part (no predecessor, no supersession) minted + released under the CO (Make or Buy). Used to introduce a part under change control, including the consolidated "1" in an N→1 assembly BOM change. Added via the "Add Affected Item" modal's change-type Select → create-new-part mini-form (changeNoticeNewPartValidator — Part Number, Name, Replenishment System, Tracking Type; no Part/Tool choice — always a Part; addChangeNoticeAffectedItem's newPart path mints the item with the chosen itemTrackingType). Its type cannot be switched (net-new by construction), and it shows no cutover card. Restricted to Parts.
    • Buy (purchased) items have no BoM/BoP — isManufactured = replenishmentSystem !== "Buy" gates the embedded editors (mirrors the part page). Version is hidden from the change-type picker for Buy items, and addChangeNoticeAffectedItem coerces a Buy item's default Version → Revision on add. Complementarily, the Add Affected Item item picker restricts to Make parts (Item replenishmentSystem="Make" → Make or Buy and Make) whenever the selected change type is Version, so a Buy part can't be picked for a Version in the first place; other change types show all Parts.
  • Draft creation (createChangeNoticeDraftMethod, called by addChangeNoticeAffectedItem) — per change type: Version → createMakeMethodVersion on the same item, which writes the CO's changeOrderId in the Draft's own insert; Revision → createRevision(active:false), which also copies the source revision's planning and purchasing setup (batch size, scrap, lead time, per-location reorder policy, item group, preferred supplier, supplier parts + price breaks — see .claude/rules/revision-system.md); Replacement Part → mint a new numeric readableId derived from the source (getNextItemIdFromSource) + copyItem; New Part → the item is minted by addChangeNoticeAffectedItem's newPart path (net-new, no source copy), and this just stamps its trigger-created Draft method CO-owned (baseMakeMethodId null). For Revision/Replacement Part/New Part the resulting Draft method's changeOrderId (and the new item's) is stamped to the CO afterwards. The draft refs (draftMakeMethodId, baseMakeMethodId, newItemId) are written back onto the affected-item row. The Version draft is numbered max(all versions)+1, not active+1 (with a unique-violation retry) so parallel COs on the same part get distinct versions instead of colliding on makeMethod (itemId, version). Switching change type discards + recreates the draft (updateChangeNoticeAffectedItemChangeType), resetting edits — but a New Part cannot be switched to/from. Removing an affected item (or deleting the notice) discards its draft through discardChangeNoticeDrafts(client, db, drafts, companyId): one Kysely transaction, gated by parts_delete, that deletes the draft items' supplier price breaks before the items (supplierPartPrice → supplierPart is ON DELETE RESTRICT and would otherwise block the item delete) and the Version draft methods. It returns the error, and the callers stop on it rather than remove the affected row or notice and orphan the draft.
  • Authoring diff (git-style end-state) — getChangeNoticeDiff + pure diffMethod (unit-tested in items.service.test.ts) diffs the CO-owned Draft method against the base Active method the draft was copied from (both real methods), correlating rows by natural key (material → component itemId, operation → order, operation children → name/key/toolId) since the copied draft carries no back-pointer ids. Classifies each material/operation/attribute added/removed/modified/unchanged. For a Revision/Replacement Part/New Part draft item it also diffs the draft's supplier parts (diffMethod's baseSupplierParts/targetSupplierParts, paired by supplierId). A Revision draft starts with a copy of its source revision's supplier parts, so it is diffed against the source item's and shows only what was added, changed or removed on the CO line. A Replacement Part / New Part draft starts with none (the source's suppliers are NOT copied by copyItem), so the base is null and every supplierPart row is added; a Version shares the live item's suppliers and shows none. Rendered read-only by ChangeNoticeDiffViewer — the single diff renderer, reused by the affected-item "Changes" card (AffectedItemDetail), the CO-wide ChangeNoticeChanges rollup on the overview, and the release dialog (shown during authoring, not just at release).
  • Release confirmation — ChangeNoticeReleaseMerge (properties panel, at Implementation) is a plain review-then-confirm dialog: it shows each affected item's authoring diff (getChangeNoticeDiff) and posts Implementation → Done. No merge/conflict step — releasing a Version just appends a new Active version and archives the prior one, so a same-part parallel CO that released first is not clobbered (its version stays as method history). The old 2-way merge / conflict-resolver UI + getChangeNoticeReleaseDiff / reconcileDraftWithLive were removed.
  • Release (applyChangeNotice → releaseAffectedItem) — the Implementation → Done action. Dispatch by change type per affected item: Version activates the Draft (prior Active → Archived), no new item, no supersession; Revision/Replacement Part activate the Draft, reveal the new item (item.active = true, stamp item.changeOrderId), and auto-write the affected→new itemSupersession; New Part activates the Draft + reveals the net-new item but writes no supersession (no predecessor). applyChangeNotice releases New Part items first (stable sort) so a parent assembly's BOM line resolves to an already-active new part. Final Kysely CAS flip to Done. Idempotent: a released draft has its makeMethod.changeOrderId cleared, so a re-run skips it.
  • Supersession propagation (no parent cascade) — changing a component does not re-BOM its parents. Propagation is via supersession chains (itemSupersession): the auto affected→new cutover per Revision/Replacement Part affected item (a net-new New Part has no predecessor, so no supersession). N→1 consolidation ("3 parts become 1") is modeled as a parent-assembly Version/Revision change whose draft BOM removes the old component lines and adds a New Part line — surfaced by diffMethod as removed + added, not as supersessions. item.changeOrderId is the revision→CO back-link powering the "Created by CO-…" chip and part-side change history.
  • Impact panel — read-only "where used" view: for each affected item, where it is referenced across the system (jobs, job materials, POs, receipts, sales orders, shipments, quotes, methods, NCRs, …), reusing the part detail page's getPartUsedIn data + the shared UsedInItem tree rows (ImpactPanel maps one where-used group per affected item; empty categories are dropped). Always shown in the properties panel. Loaded per affected item in the CO $id loader via getPartUsedIn(client, affectedItem.itemId, companyId) → impactUsedIn. (The old getChangeNoticeImpact open-PO/jobs/sales table was removed.)
  • Linked NCR — a CO may reference a non-conformance (changeOrder.nonConformanceId), cross-linked both ways with the Issue detail.
  • Change-orders list (ChangeNoticesTable, x+/items+/change-notices+/_index.tsx) — reads the changeOrders view. Rows are expandable (renderExpandedRow/canExpandRow, storage-units spine style) to reveal each affected item (readableId + ChangeTypeBadge + OLD→NEW for Revision/Replacement Part; a New Part shows a single id — net-new, newItemId === itemId), and an Item filter (isArray static filter → filter=itemIds:contains:<id> → .overlaps("itemIds", …)) narrows COs to those affecting the selected items. The itemIds column is hidden by default (defaultColumnVisibility) — it still drives the filter and CSV export.

Deferred (not yet built): Tool affected items — the Add Affected Item modal is Parts-only, so there is no UI path to add a Tool (or edit Tool attributes) under a CO today, even though the service layer still accepts Tools.

CO Safety

  • MUST move stages only through setChangeNoticeStatus — the operation that holds the approval gate, releases through applyChangeNotice and notifies. Its guarded writer updateChangeNoticeStatus (forward-only + compare-and-swap on fromStatus) refuses Done, and updateChangeNotice never writes status. A refused transition comes back as rule, a stale page as conflict.
  • MUST gate every CO mutation route with requireChangeNoticeEditable(client, { changeNoticeId, companyId, scope }) from items.service.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 posting calls (get-method / convert, each committing its own transaction), 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.service.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.

CO data model

Table / Column Purpose
changeOrder Header: changeOrderId, name, status, changeOrderTypeId, type (legacy), priority, nonConformanceId, dates, assignee, reasonForChange/description
changeOrders (view) List-view rollup of changeOrder + itemIds (text[] of affected item ids — powers the list's Item filter via .overlaps) + affectedItems (jsonb {id,itemId,changeType,newItemId}[] — powers the list's expandable rows). getChangeNotices reads this view (not the base table); the single-CO getChangeNotice still reads the base table, so the list shape (nullable view cols) and the detail shape are distinct types (ChangeNoticeListItem vs ChangeNotice)
changeOrderType The "Category" lookup (configured like Issue Types)
changeOrderAffectedItem The items the CO changes — user-selected first (or minted, for a net-new New Part). Carries changeType (Version/Revision/Replacement Part/New Part), the CO-owned Draft refs draftMakeMethodId + baseMakeMethodId (the source Active method; null for a net-new New Part), the revealed item newItemId (Revision/Replacement Part/New Part; also the release idempotency marker), and cutover config (supersessionMode, discontinuationDate, successorEffectivityDate — not used by New Part)
makeMethod.changeOrderId Draft-method → CO link: a Draft makeMethod with a non-null changeOrderId is CO-owned. Shown/edited both in the CO workspace and on the affected item's own master page (item-detail loaders select it in sync — they do not exclude changeOrderId drafts); cleared at release
changeOrderSupersession MANUAL different-part obsolescence declarations (predecessorItemId → successorItemId). Table retained (still read by findChangeNoticesForItem) but the create UI + CRUD were removed — no v2 path writes rows; the auto affected→new cutover covers same-part supersession
changeOrderActionTask Freeform non-gating tasks (Actions)
item.changeOrderId Revision/new-part → CO back-link, stamped at release; powers change history + revision-centric audit

Related Modules

  • purchasing — supplier parts pricing; PO lines reference items; conversionFactor on supplierPart; CO impact panel reads open PO lines (openPurchaseOrderLines) for deleted parts
  • inventory — quantities tracked per item/location; tracking type drives receipt/picking behavior
  • production — jobs manufacture items; make methods copied to jobs via getMethod (production.service.ts, ported from the get-method server function)
  • sales — quote lines and sales order lines reference items; itemUnitSalePrice is base price; ui/Item/ItemRentalRateForm.tsx ("Rental Rates" card on the part Sales tab, x+/part+/$itemId.sales.tsx, shown only for serial-tracked parts, base currency) edits the item's rental day / week / month rates with itemRentalRateValidator from ~/modules/sales/sales.models (intent rentalRate → upsertItemRentalRate), and ui/Item/CustomerRentalRates.tsx + CustomerRentalRateForm.tsx (the "Customer Rental Rates" card below it, drawers at x+/part+/$itemId.sales.rental-rates.*) edit customerItemRentalRate. Both are the DEFAULT for a rental line's own rates (customer → customer type → item); editing them never touches a line that has rates. The Sales tab route owns the one <Outlet /> for the customer-part and rental-rate drawers
  • accounting — itemPostingGroup maps items to GL accounts
  • quality — inbound inspection is driven by the item's Receipt-usage inspection-document assignment (itemInspectionDocumentAssignment), configured on the item Quality tab; inspection documents reference parts

Rules References

  • .claude/rules/material-tables.md — material taxonomy schema, linkage, and the material.id = item.readableId gotcha
  • .claude/rules/method-material-sourcing.md — how methods determine Buy/Make/Pull sourcing and cascade rules