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.
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
itemtable; 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, orBuy and Make. Drives MRP planning and method availability.sourcingType(Specified/Drop Ship/Ship from Inventory) is item-level and cascades tomethodMaterialrows. - 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
upsertMaterialfor material creation — it handles bothitemandmaterialtable inserts withreadableIdlinkage. - MUST remember:
material.id=item.readableId, NOTitem.id. Join viareadableId + companyId. - MUST use
assertMethodOperationIsDraftbefore deleting method operations — Active/Archived methods are protected. - MUST use
updateItemMethodAndSourcingwhen changingreplenishmentSystem,defaultMethodType, orsourcingType— 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) viaON DELETE RESTRICT, anditemLedger/costLedger(any inventory movement or cost history) viaON DELETE NO ACTION. Deactivate the item instead.NO ACTION(notRESTRICT) 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_triggerrefuses 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 frominformation_schemaat 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 theunitOfMeasurerow, so one that commits between the trigger's check and the delete's commit can still leave a dangling code. - Changing
itemTrackingTypeon items that already have tracked entities — usecascadeItemTrackingType. - Modifying Active method versions — create a new version instead.
Never
- Directly insert
materialrows without correspondingitemrows. - Assume
materialhas anitemIdcolumn — it was dropped; linkage ismaterial.id = item.readableId. - Delete global taxonomy rows (
companyId IS NULL) — they're system-seeded and shared across companies. - Edit
methodMaterial.sourcingType/methodTypeper-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 (RPCsget_part_details,get_material_details,get_service_details, etc.)upsertService— creates/updates a Service item; alwaysitemTrackingType = 'Non-Inventory'(never shipped/received/stocked), replenishmentBuyorMakeonly. Theservicerow is keyed byitem.readableId(like tool/material). Legacyservice.serviceTypeis defaulted and no longer read.upsertPart/upsertTool/upsertConsumable/upsertService— an update takescompanyIdand anidthat is the item uuid or the readable id; it writes the item row by uuid and the typed row byreadableId + 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 anditem/materiallinkage; an update writes only the keys sent and never touchesactive. Over MCPname,replenishmentSystem,defaultMethodType,itemTrackingTypeandunitOfMeasureCodeare required, so they are always sent; with generated material IDs a sentnameis ignoredupdateMaterialProperties(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.mdgetMakeMethods/getMethodMaterials/getMethodOperations/getMethodTreeArray— BOM/routing readscopyItem/copyMakeMethod— duplicates viagetMethod(production.service.ts, ported from theget-methodserver function)createMakeMethodVersion(client, db, args)— a new Draft version of a make method, behindcreateMethodVersion(the New Version route, the API and MCP), aVersionchange notice's draft and the Onshape panel's Draft. One Kysely transaction inserts the Draft (withargs.changeOrderId, else the source's), sets a Draft source Active whenargs.activateis set (an Active or Archived source is left alone), and copies the BoM/BoP throughcopyMakeMethod. 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 checksparts_create(andparts_updatewhen it activates) through the caller's client, then copies as the system: the method line policies ask for no more thanparts_create, while get-method's own gate asks for production update. A refused copy comes back as the posting'sServerFnError;createMethodVersionrefuses anactiveVersionIdother thancopyFromIdbefore it calls itcreateRevision(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 byassert_company_access(companyId, 'parts_create')through the caller's clientupdateItemMethodAndSourcing— cascades replenishment/sourcing changes to Draft method materialsgetItemCost/getItemQuantities/getItemDemand— cost and planning readsitems.utils.ts—getNextRevision,getConfigurationParameters,getItemStorageUnitQuantities, and the supplier pricing readsgetSupplierPriceBreaksForItems,lookupBuyPrice,getSupplierPartPricing,getSupplierPartPriceBreaks. Import them from this file, not the servicegetSupplierParts/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, forresolveSupplierPriceon a purchase documentgetSupplierPartsBySupplier— 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 (SupplierPartFormwithselectItem), so every item-type create and edit route returns thecreateSupplierPart/updateSupplierPartresult instead of redirectingupsertPickMethodWithShelfLife— pick method with shelf life configurationgetConfigurationParameters/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 (configuredMadeChildinproduction.service.ts, all fourgetMethodpaths); a configured item with no make method leaves the line with no sub-assembly.
- A rule on
createItemDocumentUploadUrl— MCP file upload (step 1): presigned URL for an item document (parts/{itemId}folder); pair withdocuments_insertUploadedDocument. See.claude/rules/mcp-tools-reference.md→ "File uploads"createModelUploadUrl/insertModelUpload— the API/MCP CAD model upload, and the one path the browser'sapi+/model.upload.tsshares: step 1 signs an upload intotemp-staging(2.5 GB, where the dropzone stages raw CAD) at${companyId}/models/${modelId}.${ext}; step 2 records themodelUploadrow, links it to any ofitemId/jobId/salesRfqLineId/quoteLineId/salesOrderLineId(each checked first, all scoped bycompanyId), and startsassembly-convertfor a STEP file withconvert. The insert itself startsmodel-optimize: thequeue_model_pipelinestatement handler onmodelUploadsends 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, thencascadeItemTrackingType),setItemFields(name, description, MPN, unit of measure),setItemSourcing(exactly one of replenishment system, default method type, sourcing type;deriveItemMethodUpdatethenupdateItemMethodAndSourcing),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).updateItemwrites the item row only: it refuses areadableIdthat differs from the item's and atypethe item is not, since the type row is keyed by the readable id. createPart,updatePart,updateTool,setMaterialProperties(updateMaterialPropertiesper material),renameService.updateItemManufacturingandupdateItemPlanning(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 asrule, 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, behindcheckRevisionLock),createMethodVersion,syncOnshapeMethod(the Onshape panel's Sync,api+/integrations.onshape.sync.ts:syncMakeMethod(items.service.ts, ported from thesyncserver function) rewrites the bill of materials, then the item is mapped to its Onshape document).deleteMethodOperation(behindcheckRevisionLock).deleteMethodMaterials/deleteMethodOperations(unpublished; the bill of material and bill of process Delete Selected,methods+/material.delete.tsxandoperation.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 itsmethods+/route checks: material, operation, parameter, tool and step create / update / delete,activateMethodVersion(checkRevisionLockschecks 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 asnotice(withLockNotice).updateMaterialOrder/updateOperationOrder(themethods+/*.order.tsxroutes) take rows of ONE make method and write the order withupdateSortOrder. Step, slide and step-link writes also need a Draft method (methodStepRefusal);assertMethodOperationIsDraftreturns that refusal asrule.recalculateItemCost(the costing card's Recalculate).createChangeNotice(with the picked parts),createChangeNoticeForItem,setChangeNoticeStatus(the approval gate, the release throughapplyChangeNotice, the stage notifications),decideChangeNoticeApproval. The notice and child writes (updateChangeNotice, the affected-item and action-task operations) holdrequireChangeNoticeEditablethemselves: 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 throughrequireChangeNoticeChildEditable.
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 aCancelledoff-ramp. Table-driven, one step forward (changeNoticeStatusTransitions/isAllowedChangeNoticeTransition— the check is purelyallowed.includes(to), NOT directional), with two backward reopen edges:Implementation → Engineering CompleteandCancelled → Draft. Both are ⋮-menu items inChangeNoticeHeader.Doneis terminal — releasing already activated methods and wrote supersessions, so it cannot be reopened. The reopen edge must stay LAST in theImplementationarray: the header readstransitions[status]?.[0]for its advance/release action.changeNoticeOpenStatuses= every stage before Done.Start/Implementation/Donenotify the CO assignee + action-task assignees (changeNoticeNotifyStages;notifyChangeNoticeTransitionresolves the recipients — not a company-wide broadcast). - Two lock scopes (
items.models.ts) —isChangeNoticeLocked(status)is true atDone/Cancelled(fully closed). On top of that:canEditChangeNoticeEngineering(status)additionally excludesImplementationand gates affected items (add/remove/change-type), the staged BOM/BOP drafts, cutover config, andreasonForChange/description;canEditChangeNoticeWorkflow(status)is the closed-only test and gates action tasks, assignee, dates and priority — those stay editable atImplementation, which is the whole point of that stage. (canEditChangeNoticewas split into these two and no longer exists.) Server enforcement isrequireChangeNoticeEditable(client, { changeNoticeId, companyId, scope })initems.service.ts; the UIisDisabledis cosmetic on top of it. BOM/BOP mutations are covered centrally —checkRevisionLockalso resolves the owning CO's status, so all ~17methods+/routes inherit the lock without their own guard. Noteitem.changeOrderIdis a PERMANENT back-link (unlikemakeMethod.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 tovalidItemTypes={["Part"]}and the New Part mini-form always mints a Part — no Tool path in the UI (the service'saddChangeNoticeAffectedItem/createChangeNoticeDraftMethodstill technically accept Tools, but no route surfaces them). The modal's two branches (New Part vs existing-item) are separateValidatedForms that MUST carry distinctkeyprops — 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 embeddedBillOfMaterial/BillOfProcess, and the draft item's attributes + files via the embeddedPartProperties(embeddedvariant) 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 arevisiontext input for a Revision change so the user can name the revision (e.g.A); blank →createChangeNoticeDraftMethodauto-computes the next revision viagetNextRevision. (The optionalrevisionthreads validator →$id.affectedroute →addChangeNoticeAffectedItem→createChangeNoticeDraftMethod.)Replacement Part— a new part number derived from the affected part, BoM/BoP and attributes (embeddedPartProperties); 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'snewPartpath mints the item with the chosenitemTrackingType). 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).Versionis hidden from the change-type picker for Buy items, andaddChangeNoticeAffectedItemcoerces a Buy item's defaultVersion→Revisionon add. Complementarily, the Add Affected Item item picker restricts to Make parts (ItemreplenishmentSystem="Make"→MakeorBuy and Make) whenever the selected change type isVersion, 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 byaddChangeNoticeAffectedItem) — per change type:Version→createMakeMethodVersionon the same item, which writes the CO'schangeOrderIdin 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 numericreadableIdderived from the source (getNextItemIdFromSource) +copyItem;New Part→ the item is minted byaddChangeNoticeAffectedItem'snewPartpath (net-new, no source copy), and this just stamps its trigger-created Draft method CO-owned (baseMakeMethodIdnull). For Revision/Replacement Part/New Part the resulting Draft method'schangeOrderId(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 numberedmax(all versions)+1, notactive+1(with a unique-violation retry) so parallel COs on the same part get distinct versions instead of colliding onmakeMethod (itemId, version). Switching change type discards + recreates the draft (updateChangeNoticeAffectedItemChangeType), resetting edits — but aNew Partcannot be switched to/from. Removing an affected item (or deleting the notice) discards its draft throughdiscardChangeNoticeDrafts(client, db, drafts, companyId): one Kysely transaction, gated byparts_delete, that deletes the draft items' supplier price breaks before the items (supplierPartPrice → supplierPartisON DELETE RESTRICTand 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+ purediffMethod(unit-tested initems.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 → componentitemId, 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'sbaseSupplierParts/targetSupplierParts, paired bysupplierId). 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 bycopyItem), so the base is null and everysupplierPartrow isadded; aVersionshares the live item's suppliers and shows none. Rendered read-only byChangeNoticeDiffViewer— the single diff renderer, reused by the affected-item "Changes" card (AffectedItemDetail), the CO-wideChangeNoticeChangesrollup 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/reconcileDraftWithLivewere removed. - Release (
applyChangeNotice→releaseAffectedItem) — the Implementation → Done action. Dispatch by change type per affected item:Versionactivates the Draft (prior Active → Archived), no new item, no supersession;Revision/Replacement Partactivate the Draft, reveal the new item (item.active = true, stampitem.changeOrderId), and auto-write the affected→newitemSupersession;New Partactivates the Draft + reveals the net-new item but writes no supersession (no predecessor).applyChangeNoticereleases 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 itsmakeMethod.changeOrderIdcleared, 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-assemblyVersion/Revisionchange whose draft BOM removes the old component lines and adds aNew Partline — surfaced bydiffMethodas removed + added, not as supersessions.item.changeOrderIdis 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
getPartUsedIndata + the sharedUsedInItemtree rows (ImpactPanelmaps one where-used group per affected item; empty categories are dropped). Always shown in the properties panel. Loaded per affected item in the CO$idloader viagetPartUsedIn(client, affectedItem.itemId, companyId)→impactUsedIn. (The oldgetChangeNoticeImpactopen-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 thechangeOrdersview. 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 (isArraystatic filter →filter=itemIds:contains:<id>→.overlaps("itemIds", …)) narrows COs to those affecting the selected items. TheitemIdscolumn 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 throughapplyChangeNoticeand notifies. Its guarded writerupdateChangeNoticeStatus(forward-only + compare-and-swap onfromStatus) refuses Done, andupdateChangeNoticenever writesstatus. A refused transition comes back asrule, a stale page asconflict. - MUST gate every CO mutation route with
requireChangeNoticeEditable(client, { changeNoticeId, companyId, scope })fromitems.service.ts—scope: "engineering"for affected items / BOM / BOP / cutover / reason / description,scope: "workflow"for action tasks and header fields. A UI-onlyisDisabledis not a lock. - MUST add affected items through
addChangeNoticeAffectedItem— it spins the CO-owned Draft method and writes the draft refs back; a barechangeOrderAffectedIteminsert leaves the diff/release with no draft to activate. - MUST use
applyChangeNotice(the Implementation → Done "release") for the release lifecycle — never re-implementactivateMethodVersion/itemSupersessioninline. 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 whosechangeOrderIdis already cleared is skipped) and CO-wide (the closing CAS onstatus='Implementation'). - MUST route any write that puts an item into circulation through
getUnreleasedChangeOrderItems(or its single-item formsgetUnreleasedChangeOrderForItem/getUnreleasedChangeOrderIssue) initems.service.ts. Release is what activates a CO-minted item (applyChangeNoticeflipsactive), 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.changeOrderIdalone 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 — readingchangeOrderneedsparts_view, which a sales or purchasing user need not have. findChangeNoticesForItem(initems.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 theitem.changeOrderIdreverse link on released revisions), scoped byreadableId. 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 canonicalitems.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;
conversionFactoronsupplierPart; 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 theget-methodserver function) - sales — quote lines and sales order lines reference items;
itemUnitSalePriceis 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 withitemRentalRateValidatorfrom~/modules/sales/sales.models(intentrentalRate→upsertItemRentalRate), andui/Item/CustomerRentalRates.tsx+CustomerRentalRateForm.tsx(the "Customer Rental Rates" card below it, drawers atx+/part+/$itemId.sales.rental-rates.*) editcustomerItemRentalRate. 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 —
itemPostingGroupmaps 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 thematerial.id = item.readableIdgotcha.claude/rules/method-material-sourcing.md— how methods determine Buy/Make/Pull sourcing and cascade rules