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.
Inventory Module
Tracks item quantities across locations and storage units. Manages receipts, shipments, stock transfers, warehouse transfers, kanbans, picking lists, serial/batch/lot tracking, storage types, and traceability (lineage graphs).
Key Domain Concepts
- Storage Unit — hierarchical container (bin, shelf, rack, zone) within a location. Tree structure via
parentId. Renamed fromshelfin migration20260417000100. MUST usestorageUnitnaming, nevershelf. Bulk CSV import is wired via the shared import system (table: "storageUnit", permissioninventory): fieldsid,name,locationId,parentName,storageTypeNames,active; matched on(locationId, lower(name))since names are unique per location, parents linked in a second pass. See.claude/rules/csv-import-system.md. - Tracked Entity — serial/batch/lot-tracked item instance with
readableId(serial or batch number),status(Available/Reserved/On Hold/Consumed/Rejected/Scrapped),quantity, andexpirationDate.Scrappedis terminal but recoverable via the Unscrap adjustment. Batch items havebatchPropertydefinitions. A serialized unit can leave stock as a fixed asset: the storage-unit row action Capitalize as Fixed Asset (ui/Inventory/InventoryStorageUnits.tsx, rows with atrackedEntityId, needscreate: accounting) openspath.to.fixedAssetCapitalizewithitemId,trackedEntityId,locationIdandstorageUnitIdas search params;postAssetTransfer(accounting.service.ts, ported from thepost-asset-transferserver function) then consumes the unit (Consumed,attributes["Fixed Asset"], a'Capitalize'trackedActivity,itemLedger−1'Asset Transfer') at its carrying cost, and Return to Inventory on the asset brings the same unit backAvailableat net book value. See.claude/rules/fixed-asset-lifecycle.md. - Item Ledger — append-only log of every inventory movement (
itemLedgertable). Source of truth for on-hand quantities. MUST never INSERT directly — always go through service functions. - Receipt — inbound inventory from POs, transfers, customer RMAs (source "Sales Return Order"), or rental units coming back (source "Rental Agreement"). Lines link to
purchaseOrderLine, jobs, orsalesReturnOrderLine. Posting creates ledger entries and tracked entities; RMA receipts re-enter at the original outbound cost (shipment consumption rows), current cost for blind returns, or zero when the return reason flagsinventoryValueZero, and reactivate the SAME tracked entity On Hold (ReturnEntityForm re-tags the Consumed entity instead of minting a new serial). A rental receipt holds noreceiptLine: each unit is areceiptFixedAssetLinewithrentalAgreementLineId, and posting returns the unit on its agreement and moves itsfixedAsset.locationIdto the receipt's location, with noitemLedgerrow or journal for aRentalline (see sales AGENTS → Rentals → Deliver and return). A rental receipt cannot be voided. - Shipment — outbound inventory to customers, or return flows: source "Purchase Return Order" ships supplier returns (Cr Inventory / Dr GRNI at carried cost; a line linked to an issue whose inspection reject wrote off a non-tracked lot first puts those units back —
getReturnLineWriteOffs, a Positive Adjmt. under the shipment at the write-off's own cost, Dr Inventory / Cr Scrap — so they are relieved once, and the void writes them off again), source "Sales Return Order" ships rejected RMA claims back to the customer (On Hold entities allowed in lines.tracking for that source only), source "Rental Agreement" delivers rental units: each unit is ashipmentFixedAssetLinewithrentalAgreementLineId, posting puts it On Rent and writes noitemLedger,costLedgeror journal row, and its PDF prints as a "Delivery Ticket". - Stock Transfer — moves inventory between storage units within the same location. A transfer with
kanbanIdset is a kanban replenishment (written byreplenishKanban(inventory.service.ts, ported from thekanban-replenishserver function)); the list shows it as Source "Kanban". - Warehouse Transfer — moves inventory between locations (inter-location).
- Picking List — generated pick instructions with FEFO/FIFO ordering and tracked entity allocation.
- Kanban — pull-based replenishment signal (Buy, Make, or Transfer between storage units). A Transfer kanban with
replenishmentLevelalso fires automatically when the projected quantity at its To storage unit drops below the level. See.claude/rules/kanban-system.md. - Inventory Count — physical/cycle count. Posted is terminal (there is no count-level "Rectify" — fixing a posted movement happens per-movement via
correctStockMovement). Created with an optional scope (storageUnitIds+itemType) recorded in the header'sscopeJSONB (written at create; not yet read back).generateInventoryCountLinessnapshots on-hand intoinventoryCountLinerows, excluding Rejected AND Consumed tracked lots. The count detail table filters lines by item type / storage unit / storage type / tags / material attributes via theinventoryCountLinesview (line → item → subtype tables → storageUnit, flattened) — the same generic column-filter set the quantities screen uses. There is no material-attribute scope at create time.
Safety
Always
- MUST use
adjustInventoryfor quantity changes — it runs the storage rules, theninsertManualInventoryAdjustment, which creates proper ledger entries and handles tracked entity updates. - MUST scope by
companyIdandlocationId— inventory is location-scoped. - MUST use
getInventoryItems(callsget_inventory_quantitiesRPC) for current quantities — never sum ledger entries manually. - MUST use
generatePickingListfor pick operations — it handles FEFO/FIFO ordering and tracked entity allocation.
Ask First
- Deleting storage units (
deleteStorageUnitCascadecascade-deletes all children). - Manual adjustments on tracked (serial/batch) items — these create/modify tracked entities.
- Changing
warehouseTransferStatus— it triggers inventory movements.
Never
- Directly INSERT into
itemLedger— always go through service functions. - Delete receipt lines that have posted tracked entities without cleaning up entities first.
- Reference
shelforshelfId— always usestorageUnit/storageUnitId.
Validation Commands
pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp", not "@carbon/erp"
Key Data Model
| Table / View | Purpose |
|---|---|
itemLedger / itemLedgers (view) |
Append-only movement log: item, location, quantity, document ref, trackedEntityId |
itemStockQuantities |
On-hand per (item, company, location) — a real TABLE maintained transactionally by a statement-level event handler on itemLedger (apply_item_stock_quantities, attached via attach_statement_handler; was a 30-min-refresh matview until 20260812002454). Excludes Rejected tracked stock. Never write to it directly — it is derived state; the nightly reconcile-item-stock-quantities cron repairs any drift. Read by the item-dropdown store (with realtime push), the workflow engine's item.quantityOnHand, and MRP's on-hand input |
storageUnit |
Hierarchical bins/shelves via parentId; scoped to location |
storageType |
Storage unit type definitions (capacity, constraints) |
trackedEntity |
Serial/batch/lot instances with readableId, status, quantity, expirationDate |
receipt / receiptLine |
Inbound documents from POs or production |
purchaseOrderLinesToReceive (view) |
The item lines (Part, Material, Tool, Fixture, Consumable — what receiptFromPurchaseOrder builds a receipt from) of purchase orders in To Receive / To Receive and Invoice, with supplier, reference, tracking number, item and supplier part. searchText holds each searchable value lower-cased with everything but letters and digits removed, joined with |, so a search word never spans two values. Read by Inventory → Receiving |
receiptFixedAssetLine |
One fixed asset per row on a receipt: purchaseOrderLineId (a PO receipt) XOR rentalAgreementLineId (a rental receipt; CHECK receiptFixedAssetLine_source_check), received, serialNumber. The rental return fields: meter, notes, takeOutOfService + outOfServiceReason (CHECK: a tick needs a reason; the UI saves both as one outOfService field), residualDestination (Fleet / Inventory, a Sale line only). Edited through updateReceiptFixedAssetLine (receiptFixedAssetLineUpdateValidator), which refuses a line on a non-Draft receipt |
shipment / shipmentLine |
Outbound documents to customers |
shipmentFixedAssetLine |
One fixed asset per row on a shipment: salesOrderLineId (a sales order shipment) XOR rentalAgreementLineId (a rental shipment; CHECK shipmentFixedAssetLine_source_check), shipped, serialNumber, and meter (a rental unit's meter out). Edited through updateShipmentFixedAssetLine (shipmentFixedAssetLineUpdateValidator), which refuses a line on a non-Draft shipment. A reader that means a sales order line filters salesOrderLineId IS NOT NULL |
stockTransfer / stockTransferLine |
Intra-location moves between storage units; stockTransfer.kanbanId marks a kanban replenishment |
warehouseTransfer / warehouseTransferLine |
Inter-location moves |
kanban |
Pull-based replenishment signals; replenishmentLevel arms a Transfer kanban |
batchProperty |
Custom property definitions for batch-tracked items |
pickingList / pickingListLine |
Pick instructions with tracked entity allocation |
pickMethod |
Default storage unit and pick strategy per item at a location |
Operations (inventory.server.ts)
Each operation is one defineServiceFn const in inventory.server.ts. A route action calls it through carbon(request) as api.inventory.<name>(input) and makes no other write (one route is left: api+/kanban.collision.$id.tsx still clears the job with updateKanbanJob from production.service.ts). A document id comes from the URL, never the form body; the API and MCP publish the ones tagged @mcp as inventory_<name>. Every check the route used to make is in the function.
| Operation | Route | What it holds |
|---|---|---|
createReceipt / createShipment |
receipt+/new.tsx, shipment+/new.tsx |
The create posting for the source document; a return order or rental agreement with a Draft document returns that one. A purchase order shipment needs the caller's default location; a sales order shipment ships from the order's location, or the caller's default location when one of its lines ships from there |
updateReceipt / updateShipment |
$receiptId.details.tsx, $shipmentId.details.tsx |
A changed source or location rebuilds the lines; a rental document keeps its agreement |
postReceipt / postShipment |
$receiptId.post.tsx, $shipmentId.post.tsx |
Storage rules (and over-receipt, and the order's sales rules), Pending, the posting, back to Draft on failure, labels, lead times, the workflow moment. A shipment also applies the expired-batch policy and saves the packing slip (packing-slip.pdf.tsx, shared with file+/shipment+/$id[.]pdf.tsx) |
voidReceipt / voidShipment |
$receiptId.void.tsx, $shipmentId.void.tsx |
Posted only; not a receipt a purchase invoice created. A receipt void also refuses stock that has left its bin since posting and an untracked lot an inspection rejected; the refusal reaches the caller in its own words |
splitReceiptLine, updateReceiptLines, updateReceiptFixedAssetLine (and the shipment twins) |
lines.split.tsx, lines.update.tsx, fixed-asset-lines.update.tsx |
A fixed-asset line changes only on a Draft document |
setReceiptLineBatch / setReceiptLineSerial / assignReceiptReturnEntity / removeReceiptReturnEntity |
receipt+/lines.tracking.tsx (one per trackingType / intent) |
Batch and serial numbers; a sales return re-tags the Consumed entity the customer sent back |
assignShipmentLineEntity |
shipment+/lines.tracking.tsx |
The line's item, in a status shippableEntityStatuses (inventory.utils.ts) allows: Available; On Hold, received on this return order, for a return-to-customer shipment; Available, or Rejected and received on a posted receipt from the return's supplier, for a return-to-supplier shipment |
createStockTransfer / setStockTransferStatus |
stock-transfer+/new.tsx, $id.status.tsx |
Storage rules on stockTransfer; reopening a Completed transfer needs delete: inventory |
pickStockTransferLine / unpickStockTransferLine / pickStockTransferLineEntity, updateStockTransferLines |
$id.line.quantity.tsx (0 unpicks), $id.scan.$lineId.tsx, lines.update.tsx |
postStockTransfer (inventory.service.ts, ported from post-stock-transfer); a Completed transfer is refused; a scanned pick never exceeds what is left |
setWarehouseTransferStatus, createWarehouseTransferLine / updateWarehouseTransferLine / removeWarehouseTransferLine |
$transferId.status.tsx, $transferId.details.new.tsx, $transferId.details.$id.tsx |
Storage rules on warehouseTransfer; lines change only on a Draft transfer |
createInventoryCount / postInventoryCount |
inventory+/inventory-count.new.tsx, inventory-count+/$id.post.tsx |
A failed snapshot deletes the count; service.postInventoryCount (ported from post-inventory-count) posts it, and lines that cannot post come back as invalidLineIds |
adjustInventory |
inventory+/quantities+/$itemId.adjustment.tsx |
Storage rules on inventoryAdjustment, plus pick or place at a bin; a serial item (read from the item) moves at most one unit |
removeStorageUnit |
inventory+/storage-units.delete.$storageUnitId.tsx |
cascade deletes the subtree |
deleteReceipt / deleteShipment, deleteReceiptLine / deleteShipmentLine |
$receiptId.delete.tsx, $shipmentId.delete.tsx, lines.$id.delete.tsx |
A document is refused once posted (postingDate set). Deleting a shipment line also needs delete: sales (the shipmentLine RLS) |
insertWarehouseTransfer / updateWarehouseTransfer / deleteWarehouseTransfer |
warehouse-transfer+/new.tsx, $transferId.details.tsx, $transferId.delete.tsx |
A transfer is created Draft and an edit never writes its status (only setWarehouseTransferStatus moves it); an edit needs a Draft transfer |
createStockTransferLine / updateStockTransferLine / deleteStockTransferLine / deleteStockTransfer |
stock-transfer+/$id.line.*, delete.$id.tsx |
Draft transfer only (the transfer in the URL); a line's picked quantity moves only by picking. An update needs create and update: inventory, as the old route did |
updateInventoryCountStatus |
inventory-count+/$id.confirm.tsx, $id.reopen.tsx |
Draft → Pending or Pending → Draft; only postInventoryCount posts |
updateInventoryCountLine / deleteInventoryCount |
inventory-count+/lines.update.tsx, $id.delete.tsx |
A line changes only on a Draft count (else conflict), counted by the caller; a Posted count is not deleted |
setPickingListStatus / updatePickingList |
picking-list+/$pickingListId.status.tsx, $pickingListId.update.tsx |
Reopening a closed list needs delete: inventory; finishing applies finishPickingList (the incomplete-list policy: refuse, or needsAcknowledgement until acknowledged; Partial when anything is left or short). Details change only on a Draft list |
pickPickingListLineChecked / pickPickingListLineEntity |
$pickingListId.line.quantity.tsx, $pickingListId.tracked.$lineId.tsx |
The line must be on the list; then pickPickingListLine / setPickingListLineTrackedEntity as the system |
createKanban / updateKanban / deleteKanban, createStorageUnit / updateStorageUnit, createShippingMethod / updateShippingMethod / deleteShippingMethod |
inventory+/kanbans.*, storage-units.*, shipping-methods.* |
Row edits. A modal create returns the new row; a drawer redirects to its list |
createStorageType / updateStorageType / deleteStorageTypeWithCascade |
inventory+/storage-types.* |
parts permissions (the storageType RLS). A type storage units still have is deleted only with cascade, which needs update: parts and takes it off them in one transaction |
upsertBatchProperty / updateBatchPropertyOrder / deleteBatchProperty |
inventory+/batch-property+/* |
update: inventory; a new property also needs create on parts or inventory (RLS) |
generatePickingList / deletePickingList |
picking-list+/new.tsx, $pickingListId.delete.tsx |
— |
correctStockMovement, updateTrackedEntityExpiry, createInventoryReconciliationJournal |
stock-movements+/$ledgerId.correct.tsx, tracked-entity.expiry.tsx, reports+/inventory-valuation.reconcile.tsx |
See Key Service Functions; the reconcile journal needs create: accounting |
scanKanban |
api+/kanban.$id.tsx (the card's QR code; a GET, employees only) |
Make: a job (auto-release: the release checks, then releaseCheckedJobs and the schedule; a refused job stays Draft and the scan returns a message); Buy: a line on the supplier's open Draft / Planned PO or a new one; Transfer: kanban-replenish as the scanner. Returns what it made; the route picks the page |
A blocking rule is data, not an error: post, create, setStatus and adjust return { violations, ruleNames } and change nothing; the route returns it to useRuleViolations, which re-sends with acknowledged: true. The primitives they replaced are no longer published (insertManualInventoryAdjustment, insertInventoryCount, upsertReceipt, updatePickingListStatus, upsertPickingList, pickPickingListLine, setPickingListLineTrackedEntity, upsertShipment, insertStockTransfer, updateStockTransferStatus, updateWarehouseTransferStatus, upsertWarehouseTransferLine, deleteWarehouseTransferLine, deleteStorageUnit, deleteStorageUnitCascade).
Key Service Functions
getInventoryItems/getInventoryItemsCount— callsget_inventory_quantitiesRPC for on-hand quantitiesgetItemLedgerPage(inventory.service.ts) /getItemLedgerActivity(inventory.utils.ts) — paginated ledger historygetItemLedgerBalance—get_item_ledger_balanceRPC: on-hand right after one ledger entry, on thequantityOnHanddefinition (Rejected tracked stock counts zero). The item Activity feed fetches it ONCE for its newest loaded row;withRunningBalance(ui/Inventory/ledgerFeed.ts) derives every row's before → after from it as pages load, so paging adds no queries. Run it on raw rows, beforecollapseTransferPairsinsertManualInventoryAdjustment— adjustments with tracked entity handling (called byadjustInventoryafter the storage rules); wraps thepost-inventory-adjustmentposting, which maintains cost layers and posts the journal (inventoryAdjustmentVarianceAccount, seeded 5310, against the raw materials or finished goods account) in one transaction for every company. The journal is Provisional before the accounting cutover and Posted after it (journalPostingStatus). An increase with no value posts no journal; a decrease always writes its pair, at zero too, so the enable's re-cost can find it. Storage-unit transfers post no journalgetSerialUnitCosts/recostSerialUnit(operations ininventory.server.ts) — runservice.previewSerialUnitCosts(each on-hand serial's carrying cost,view: accounting; read by the Storage Units card throughapi+/items.$itemId.serial-costs.ts) andservice.recostSerialUnit(re-book ONE serial's FIFO / LIFO layer at a new cost, journal vs an offset account,update: accounting; routex+/inventory+/quantities+/$itemId.recost.tsx), both ported from server functions. See.claude/rules/inventory-system.md→ Serial unit cost and RecostcorrectStockMovement— the operation settlespostStockMovementCorrection(inventory.service.ts, ported from thecorrect-stock-movementserver function) directly, so its refusal keeps its message: fixes a posteditemLedgerrow by booking ONE opposite (delta) movement linked viacorrectionOfItemLedgerId, dated with the original'spostingDateand posted into the original's accounting period (fails if Locked/Closed). The delta is derived against the movement's current effective quantity (original + prior corrections), so repeat corrections convergegetStorageUnit(s)/getStorageUnitTree/getStorageUnitsTreeForLocation— storage hierarchygetAvailableTrackedEntities— callsget_available_tracked_entitiesRPCgetReceipts/getReceiptLines/reconcileReceiptSerialEntities— receipt management.reconcileReceiptSerialEntities(Kysely, its own transaction;reconcileReceiptSerialsInTransactioninside a caller's) drops serials beyond the received quantity (run on post, and in the same transaction as a quantity change inupdateReceiptLines) and returns the lines still missing serials, which the post refusesgetPurchaseOrderLinesToReceive/getOpenPurchaseOrdersForItems/getDraftReceiptsForPurchaseOrders— Inventory → Receiving (x+/inventory+/receiving.tsx,ui/Receiving/ReceivingTable.tsx): find the purchase order a delivery belongs to by anything on the packing slip. Every search word must occur insearchText(receivingSearchTerms,inventory.utils.ts, normalizes the same way;receivingSearchMatcheshighlights what matched). The table is one row per order, oldest first, with its lines in the expanded row, which is always open (expandRowsFor), so the list's sort is fixed and the CSV is one row per order (its lines in aLinescolumn). The loader reads up toSINGLE_LOAD_LIMITlines at once (a page of lines could cut an order in two); at the limit it leaves out the last order, which may be missing lines, and the table says only the oldest orders are shown (rowLimitNote). Receive posts tocreateReceipt(receipt+/new.tsx) like the PO header; an order with a Draft receipt offers that receipt instead. The route needsviewon inventory AND purchasing: the view's rows are RLS-gated bypurchasing_viewreleaseReceiptSerialEntities(@carbon/database/receipt-serials, shared with the receipt line split,receiptLineSplitinshared.service.ts) — the one way a receipt serial is removed, run inside a Kysely transaction: an entity with noitemLedgerhistory is deleted, one with history only loses its receipt link in one set-based update. A serial box save is planned by the pureplanSerialBoxWrite(inventory.models.ts)getShipments/getShipmentLines/getShipmentRelatedItems— shipment managementgetRentalShipmentLines/getRentalReceiptLines— a rental document's asset lines with their rental line, fleet asset, item and tracked entity; the$shipmentId.tsx/$receiptId.tsxloaders call them for the'Rental Agreement'source and pass them asrentalLines(sorted by asset id, else unit name) toShipmentRentalLineItem/ReceiptRentalLineItem. Both readers order bycreatedAt, id: a document's units are inserted in one statement and share acreatedAtgetReceiptRelatedItems/getWarehouseTransferRelatedItems/getPickingListRelatedItems— theDocumentPageDocuments panels (receipt invoices + a sales return's customer; a transfer's shipments and receipts; a picking list's jobs). Query errors are logged and degrade to empty listsgeneratePickingList/getPickingListAvailability/getPickingSchedule— picking operationsgetDefaultStorageUnitOrStorageUnitWithHighestQuantity— picking defaultsgetTrackedEntities/getTrackedEntityExpirations/getShelfLifeForItems— tracking and expirygenerateInventoryCountLines— Kysely; aggregatesitemLedgeron-hand intoinventoryCountLinerows, scoped by the optionalstorageUnitIds+itemType. ExcludesRejectedandConsumedtracked lots (status-aware, matchingquantityOnHand); non-tracked rows (NULL status) always included.getInventoryCountLinesreads theinventoryCountLinesview (joins item + subtype tables onid = item."readableId"— the same predicateget_inventory_quantitiesuses, all LEFT — +storageUnit) so the detail table can apply generic column filters on flat columns.
Key Exports
import { getInventoryItems, insertManualInventoryAdjustment } from "~/modules/inventory/inventory.service";
import { inventoryAdjustmentValidator, receiptValidator } from "~/modules/inventory/inventory.models";
Storage Rules (sub-area)
Configurable if-condition-then-error/warn rules evaluated on warehouse/MES transaction surfaces (the storage-legal subset of enforcementRuleSurface: receipt, shipment, stockTransfer, warehouseTransfer, inventoryAdjustment, place, pick, operationStart, operationFinish, materialIssue, materialReceive). Lives inside this module: validators in inventory.models.ts, UI in ui/StorageRules/; the admin CRUD is the family-parametrized implementation in shared.service.ts (see "Service functions" below). There is no modules/storage-rules directory — a rule feature is not its own domain.
Sibling feature to sales rules (~/modules/sales, sales-document surfaces). Both share the engine in @carbon/utils (rules.ts + field-registry.ts + the zod AST mirror in rules-schema.ts), the evaluator/violation UI in @carbon/ee/rules(.server), AND the enforcementRule table — one table for both families, discriminated by family.
- Rule —
enforcementRulerow (family = 'storage'; the table is shared with sales rules, so every read/write here MUST filterfamily = 'storage'):conditionAstJSONB,severity(errorblocks;warnblocks until acknowledged),targetType(item|workCenter, enumenforcementRuleTargetType),surfaces,appliesToAll(workCenter broadcast gate) and thefilteredItem*columns (item scoping). Assignments are polymorphic acrossenforcementRuleItemAssignment/enforcementRuleWorkCenterAssignment—targetTypepicks the table. The item table is shared with the sales family: resolve pinned rules against a family-filtered fetch, never a PostgREST embed. - Evaluator —
@carbon/ee/rules.server:evaluateLinesForSurface,isBlocked,dedupeViolations, plan gateisStorageRulesEnabledForCompany. Its item load swallows query errors, which silently skips every broadcast rule — a known gap kept for behavior compatibility (see the comment at the call site). New evaluators must throw instead. - One modal — posting actions return
{ violations, ruleNames }; callers submit viauseRuleViolationsand renderRuleViolationModal. Do not fork a second violation UI.
Storage Rules safety
- The
ui/StorageRules/components are the shared rule-builder surface — sales rules importsRuleBuilder,SurfacesField,MessageWithTokens,SeveritySelect, andItemFilterSelectorfrom here by deep path. Changes must stay backward-compatible; parameterize additively rather than rewriting. - These components import other modules' code from the file that defines it (
~/modules/items/items.models, …); modules have no barrel.inventoryalready depends onitems, and the sales module imports these components for its SalesRules UI.StorageRulesis deliberately not re-exported fromui/index.ts, so that import cannot create a cycle through the inventory UI. getEnforcementRuleAssignmentCounts(shared.service.ts) spans BOTH assignment tables — a rule lives in exactly one, so the union of single-table counts is correct. Rule ids are globally unique, so counting by id needs no family predicate even though the item table is shared.- Never widen the
enforcementRule_storage_surfacesCHECK to admit sales-document surfaces — that CHECK is what replaced the old per-family enum typing.
Service functions: the admin CRUD is NOT in inventory.service.ts. The read helpers (getEnforcementRules / getEnforcementRule / getEnforcementRuleAssignmentCounts) share one parametrized implementation in shared.service.ts, called with "storage" as the family. The entitlement-gated WRITES (upsertEnforcementRule / deleteEnforcementRule) moved to @carbon/ee/rules.server (packages/ee/src/rules/service.server.ts) — they embed requireEntitlement("STORAGE_RULES"). Cross-app READ queries getActiveRulesForTargets / getRuleAssignmentsForTarget / getStorageRulesList are imported from @carbon/ee/rules DIRECTLY at the call site; the gated writes assignStorageRule / unassignStorageRule are imported from @carbon/ee/rules.server at the call site too. Routes: x+/inventory+/storage-rules*, plus assignment routes under x+/items+/rules.* (item targets) and x+/resources+/work-centers.rules.* (work-center targets).
Related Modules
- purchasing — receipts consume PO lines; receipt posting updates
purchaseOrderLine.quantityReceived - production — job completion posts finished goods; materials issued from inventory (a Make to Asset job completes to
fixedAssetrows and writes noitemLedger) - accounting — a serialized unit moves between stock and the fixed asset register through
post-asset-transfer(Capitalize as Fixed Asset / Return to Inventory); thefleetAssetsview joinsfixedAssettoitemandtrackedEntity - items —
itemTrackingType(Inventory/Serial/Batch/Non-Inventory) determines tracking behavior - sales — shipments fulfill sales order lines
- quality — inbound inspections triggered on receipt for items with a Receipt-usage inspection-document assignment
Rules References
.claude/rules/inventory-system.md— comprehensive guide to inventory code, RPCs, storage units, and gotchas.claude/rules/traceability-model.md— serial/batch lineage graph model (trackedEntity/trackedActivity)