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.
paths: - "apps/erp/app/modules/inventory/" - "packages/database/supabase/migrations/"
Inventory System
Carbon's inventory tracks item/material quantities across locations and storage units, plus serial/batch/lot tracking, receipts/shipments, transfers, and picking.
Code (real paths)
All inventory service code lives in a single module: apps/erp/app/modules/inventory/
inventory.server.ts— the module'sdefineServiceFnoperations (see.claude/rules/module-files.md)inventory.service.ts— the building blocks, including the traceability graph (fetchLineageSubgraph,fetchJobScopedLineage,toGraphData)inventory.models.ts— Zod validators + exported enums/helpersinventory.utils.ts— browser-safe helperssupersession-pick.ts,types.tsui/— feature folders:Inventory/,Receipts/,Shipments/,StockTransfers/,WarehouseTransfers/,StorageUnits/,StorageTypes/,Kanbans/,PickingLists/,Batches/,ShippingMethods/,Traceability/
Key service functions (verified):
getInventoryItems/getInventoryItemsCount— call theget_inventory_quantitiesRPC (args{ location_id, company_id },count: "exact"); supports search + generic filters.getItemLedgerPage— paginated item-ledger history for an item at a location.insertManualInventoryAdjustment— thin wrapper over thepost-inventory-adjustmentposting (postInventoryAdjustment,inventory.service.ts; MES has a matching wrapper inapps/mes/app/services/inventory.service.ts). The posting owns positive/negative/set-quantity plus Scrap/Unscrap (.ai/specs/2026-08-06-scrap-unscrap-flow.md) resolution, tracked-entity storage-unit transfers, expiry override, batch/serial assignment — and, in one Kysely transaction, maintainscostLedgerlayers (consume viacalculateCOGSon decreases, new layer at current cost on increases) and posts a journal (Dr/CrresolveInventoryAccountvsaccountDefault.inventoryAdjustmentVarianceAccount) for every company — Provisional before the accounting cutover, Posted after it.post-inventory-countbooks its variances through the same shared core (bookAdjustment,shared.service.ts). Storage-unit transfers post no GL. Serial units are costed by specific identification.costLedger.trackedEntityId(migration20261006220601) stamps a layer booked for ONE serial unit — every layerbookAdjustmentwrites for aSerialitem (a fixed asset returned to stock at NBV, a sales-type lease residual, an unscrap, a positive adjustment).calculateCOGStakes optionaltrackedEntityIdsand orders FIFO / LIFO layers throughorderLayersForConsumption(@carbon/database/cost-relief): the leaving unit's own layer first, then unstamped layers, then another unit's stamped layer as the last resort (so nothing else eats a returned unit's value). Callers passing the ids:bookAdjustmentdecreases, the threepost-shipmentCOGS calls (leavingTrackedEntityIdsover the shipment's ledger rows) andissue'screateMaterialWipEntries. Receipt and job-output layers cover many units and stay unstamped, so a received serial is still FIFO-costed. Pinned byapps/erp/test/database/lib/cost-layer-order.test.tsand the database testapps/erp/test/database/lib/calculate-cogs.test.ts. Serial unit cost and Recost.previewSerialUnitCosts(inventory.service.ts, ported from thepreview-serial-unit-costsserver function;{ itemId, locationId? },view: accounting) values every on-hand serial of an item with the pureserialUnitCost(shared.service.ts): calculateCOGS's arithmetic for a quantity of one (own layer, then unstamped, with price correction children; Standard / Average at the item cost), from one read of the item's layers. ERP: theinventory.getSerialUnitCostsoperation → cachedapi+/items.$itemId.serial-costs.ts(also returnscostingMethodandretainedEarningsAccountId), read byInventoryStorageUnitsonly when the user can view accounting; a zero cost reads "No cost". Recost (row action,update: accounting, FIFO / LIFO only) →x+/inventory+/quantities+/$itemId.recost.tsx→ theinventory.recostSerialUnitoperation →service.recostSerialUnit({ trackedEntityId, unitCost, offsetAccountId?, postingDate },update: accounting): exactly one unit on hand at one location; relieves it viacalculateCOGS(its own layer first) and books −1 at the old cost / +1 stamped at the new, bothcostLedgerType 'Revaluation'(the only writer of that type; noitemLedgerrow — nothing moves); posts an'Inventory Adjustment'journal (Provisional before the accounting cutover) of the difference, inventory account vs the offset account (getOffsetAccount,shared.service.ts, signed by the offset account's own class viabuildOffsetLines). The valuation report's FIFO / LIFO layer average moves by exactly the difference, so the tie-out holds. The valuation workbench tie-out offers a Reconcile action (createInventoryReconciliationJournal) that drafts an adjusting journal for any residual pre-feature variance. Scrap = aNegative Adjmt.movement withdocumentType='Scrap'+itemLedger.scrapReasonId, offset toaccountDefault.scrapAccount(fallbackinventoryAdjustmentVarianceAccount), tracked entity →Scrapped(keeps its quantity; partial batch scrap splits per the identity-flip convention). Unscrap (Oracle Return-from-Scrap) restores aScrappedentity toAvailableat the original scrapped cost (resolved from the scrap movement'scostLedgerviaresolveUnscrapUnitCost,inventory.service.ts) and bin, linked bycorrectionOfItemLedgerId; ERP UI = the Unscrap row action on the tracked- entities table (UnscrapModal, no location and no scrap reason submitted — both resolved server-side; the reason is inherited from the original scrap movement so unscrap can't be mis-classified, and the UI collects only an optional comment). Scrap journals carry ScrapReason/WorkCenter/Employee dimensions; the singlescrapAccount+ dimensions replaces per-reason account mapping by design. The ScrapReason dimension is seeded active by default (adimensionrow per company group, frompackages/database/src/seed-data.ts; backfilled to existing groups by20260808114732_backfill-scrap-reason-dimension.sql). Like CustomerType/ItemPostingGroup it is entity-backed — its values resolve live from thescrapReasontable viagetEntityDimensionValues/getEntityValuesByIds(accounting.service.ts), so adding a scrap reason immediately makes it a selectable/taggable dimension value with no sync step. A tag is only written when the entity type has an activedimensionrow — a scrap posting's ScrapReasonextraDimensionis dropped inshared.service.tsif the dimension was deleted/deactivated for that company group.correctStockMovement(operation) — settlespostStockMovementCorrection(inventory.service.ts, ported from thecorrect-stock-movementserver function): fixes any posteditemLedgerrow by booking ONE opposite (delta) movement linked to the original's correction root viaitemLedger.correctionOfItemLedgerId, carrying the ORIGINAL'spostingDateand posting its journal: after the accounting cutover into the period containing that date viagetAccountingPeriodForDate(throws on Locked/Closed); before it the journal is Provisional and has no period. The delta iscorrectedQuantity − effective(effective = root + all prior corrections in the group), so repeat corrections converge.documentType/documentIdare copied from the original so document-scoped movement views keep including the fix. Entry point: "Correct Quantity" context action onStockMovementsTable→stock-movements/$ledgerId/correctroute (whose loader returns the authoritative effective quantity for the modal pre-fill). Corrections render as normal flat rows with anisCorrectionbadge — no nesting/expandable grouping. Inventory counts have NO count-level rectify; Posted is terminal.- Storage units:
getStorageUnit(s),getStorageUnitRoots,getStorageUnitChildren,getStorageUnitTree,getStorageUnitsTreeForLocation,getDefaultStorageUnitOrStorageUnitWithHighestQuantity, andgetDefaultStorageUnitForJob(inventory.utils.ts) — these are the picking/job defaults. - Tracking:
getTrackedEntities,getAvailableTrackedEntities(RPCget_available_tracked_entities),getSerialNumbersForItem,getBatchNumbersForItem,getShelfLifeForItems,getPickOrder(FEFO/FIFO). - Picking:
generatePickingList,getPickingListAvailability(RPCget_picking_list_availability),getPickingSchedule(RPCget_picking_schedule). These honoritemSupersession(20260730143512_picking-supersession.sql+inventory/supersession-pick.tsresolvePickTarget):Prefer New/Stock Onlyredirect a pick to the effective successor (×conversionFactor);Consume Firstredirects only when the predecessor is out of warehouse stock;No Stock(andStock Onlywithout an effective successor) is dropped from the schedule and skipped in generation. Note picking's redirect rules differ from the MRP/job-creation map (packages/database/src/supersession-pick.ts, which redirects onlyConsume First/Prefer New) — for picking,Stock Onlymust not be picked for production. A substituted line'sitemIddiffers from itsjobMaterial.itemId(no new column); the availability RPC reports the line's OWN pick item's warehouse on-hand with NO successor fold-in — a substituted line already targets the successor, and folding successor stock into a line still targeting the predecessor would mask a real shortage and double-count the successor.
Validators in inventory.models.ts: inventoryAdjustmentValidator, receiptValidator,
shipmentValidator, stockTransferValidator, warehouseTransferValidator, storageUnitValidator,
storageTypeValidator, kanbanValidator, pickingListValidator, pickingListLineValidator,
shippingMethodValidator, batchPropertyValidator. Also exports itemLedgerTypes etc.
Database (current schema)
itemLedger— source of truth for on-hand quantity. Key cols:entryType(itemLedgerType),documentType(itemLedgerDocumentType),postingDate,itemId,locationId,storageUnitId,quantity,trackedEntityId, andtrackedEntityStatus(denormalized fromtrackedEntity.status— added20260420112047, lets reads filter status without a JOIN).itemLedgerSnapshot(matview,20260713235406) — snapshot of the immutable UNTRACKED ledger rows (trackedEntityId IS NULL,createdAtolder than 1h) per item/company/location:quantity,consumed30/90,storageUnitIds,snapshotCutoff. pg_cron refresh every 30 min. Read only inside the SECURITY DEFINER quantity functions (REVOKEd from PostgREST roles); live reads add rows pastsnapshotCutoffplus ALL tracked rows, so results stay exact. Distinct fromitemStockQuantities— since20260812002454a real TABLE maintained transactionally by a statement-level handler onitemLedger(apply_item_stock_quantities, attached viaattach_statement_handler), no longer an approximate matview. ExcludesRejectedtracked stock; exact, with a nightlyreconcile-item-stock-quantitiescron as drift backstop. Read by RealtimeDataProvider (with realtime push), the workflow engine'sitem.quantityOnHandoperation, and MRP's on-hand input. The olditemInventoryrollup table is DEAD — its maintaining trigger was dropped in20250209170952_shipment.sql; don't read or write it.storageUnit— bins/locations. Renamed fromshelf(20260417000100); supports nesting viaparentIdandstorageTypeIds TEXT[](20260417000200). Cols:id,name,locationId,warehouseId,parentId,storageTypeIds,active.storageType— storage-unit type definitions (20260417000000).trackedEntity— serial/batch/lot tracking (20250225145619). Cols:id,quantity,status(trackedEntityStatus),sourceDocument(Id),attributes JSONB(batch/serial #, supplier…),expirationDate. CompaniontrackedActivity+trackedActivityInput/Outputrecord movements.warehouseTransfer/warehouseTransferLine— inter-location moves (20250726000000). Status enumwarehouseTransferStatus. Lines carry from/to location + storage unit, shipped/received qty.stockTransfer*— intra-location moves (separate from warehouse transfers).pickMethod— default storage unit for picking an item at a location (defaultStorageUnitId).itemPlanning/itemReplenishment— reorder/planning params and replenishment strategy.enforcementRule+ assignment tables — ONE table for storage and sales rules, discriminated byfamily(20260817143022/20260817143512). Storage-family reads must filterfamily = 'storage'. Lineage:itemRule→customRule→storageRule→ merged intoenforcementRule.
get_inventory_quantities(company_id TEXT, location_id TEXT, item_id TEXT DEFAULT NULL) — the central
read. Newest definition is 20261006130001_demand-forecast-consumption.sql (the
20260713235406_item-ledger-snapshot.sql body — snapshot + delta via itemLedgerSnapshot,
item_id restricts to one item for detail-page loads — plus a net-projection demand arm:
GREATEST("forecastQuantity" - "consumedQuantity", 0) of demandProjection). Returns ~52 cols:
item identity + material props, planning fields, and quantities quantityOnHand, quantityOnHold,
quantityRejected (status-aware: excludes Rejected, surfaces On Hold), quantityOnSalesOrder,
quantityOnPurchaseOrder, quantityOnProductionOrder, quantityOnProductionDemand, demandForecast,
usageLast30Days, usageLast90Days, daysRemaining, plus storageTypeIds/storageUnitIds arrays.
Aggregates from itemLedger, open purchaseOrder(Line), salesOrder(Line), job/jobMaterial,
demandForecast/demandActual, and demandProjection net of consumedQuantity.
Relevant enums: itemLedgerType, itemLedgerDocumentType (includes Scrap,
20260807090400), trackedEntityStatus
(Available, Reserved, On Hold, Consumed, Rejected, Scrapped), warehouseTransferStatus,
itemTrackingType, itemReplenishmentSystem, itemReorderingPolicy.
Gotchas
- Migrations are timestamp-ordered; tables get renamed.
shelf→storageUnit/shelfId→storageUnitId,customRule→storageRule→enforcementRule(merged withsalesRule). Grep the NEWEST migration for the real name; never trust an older one or the old cache. Theshelf→storageUnitrename was split across paired migrations20260417000100(rename, M2) +..000300(recreate dependents, M4) — they must apply together. - Short-closed PO lines don't count as incoming supply.
get_inventory_quantities,get_job_quantity_on_hand, and theopenPurchaseOrderLinesview (MRP) all filter open-PO supply withpol."receivedComplete" = false(20260708204214). A line short-closed viashortClosePurchaseOrderLine("Stop Receiving") keepsquantityToReceive > 0but is excluded fromquantityOnPurchaseOrder. get_inventory_quantitieshas many revisions. Always read the newest (20261006130001), not the first match.quantityOnHandis status-aware:Rejectedtracked entities are excluded, and tracked rows are always computed live (never fromitemLedgerSnapshot) so status flips are never stale.- On-hand math comes from
itemLedger(and theget_inventory_quantitiesRPC), not from summingtrackedEntitydirectly. The olditemInventorytable is orphaned (trigger dropped20250209170952) — never read or write it.