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/ui/{Shipments,Receipts}/** - apps/erp/app/routes/x+/{shipment,receipt}+/** - apps/erp/app/modules/shared/shared.service.ts - apps/erp/app/modules/inventory/inventory.{server,service}.ts
Shipments & Receipts UI + Posting Flow
Outbound (shipment) and inbound (receipt) documents are header + lines. They mirror
each other closely. UI lives in apps/erp/app/modules/inventory/ui/{Shipments,Receipts}/;
routes in apps/erp/app/routes/x+/{shipment,receipt}+/ (NOT under inventory+/ — that
only holds the two list routes shipments.tsx / receipts.tsx, and receiving.tsx).
Inventory → Receiving (inventory+/receiving.tsx, ui/Receiving/ReceivingTable.tsx)
is how a clerk finds the purchase order a delivery belongs to: the open lines of the
purchaseOrderLinesToReceive view, grouped by order and searched by anything on the
packing slip. Its Receive button posts to receipt+/new.tsx exactly as the PO header's
does; an order with a Draft receipt opens that receipt instead. See the inventory
module's AGENTS.md (Key Service Functions).
Routes (per document, e.g. shipment+/)
Every action below makes ONE call to an operation in
apps/erp/app/modules/inventory/inventory.server.ts (api.inventory.<name> through
carbon(request); the names are flat, such as createShipment, updateReceipt,
setReceiptLineBatch); the logic described here lives in that operation, so the API and MCP
run the same checks. The route only parses the form, and takes the document id from the URL.
new.tsx— action only (createShipment/createReceipt). Creates the doc by calling thecreateposting (invokeCreate(ctx, { type, locationId, ...sourceIds }), which runscreateDocumentinshared.service.ts), thenthrow redirect(path.to.shipmentDetails(id)). There is noupserton create — the posting allocates the human ID and copies source-document lines. For the'Rental Agreement'source it first redirects to the agreement's existing Draft (one Draft rental shipment and one Draft rental receipt per agreement, enforced by the partial unique indexesshipment_oneOpenDraftPerRentalAgreement_idx/receipt_oneOpenDraftPerRentalAgreement_idx), else invokescreatewithshipmentFromRentalAgreement/receiptFromRentalAgreement. A receipt's lines start at the quantity still to receive, or at 0 whencompanySettings.receiptQuantitiesStartAtZerois on (Settings → Inventory → Receiving — every sourcecreatebuilds lines for: Purchase Order, Inbound Transfer, Sales Return Order; a PO's fixed-asset lines then start unticked). Shipments are not affected.$id.tsx— layout loader: parallelgetShipment/getShipmentLines/getShipmentTracking, plus fixed-asset lines (shipmentFixedAssetLine) and related items. Receipt also loadsgetReceiptFiles,getBatchProperties,getShelfLifeForItems,companySettings. Renders<Outlet/>.$id._index.tsx— redirects to…/details.$id.details.tsx— renders Form + Lines + Notes. Action (updateShipment/updateReceipt): ifsourceDocumentor the location changed it re-invokescreate, else the building blockupsertShipment/upsertReceipt(Supabase update, setsupdatedBy). A rental document refuses a change of source ("A rental shipment keeps its rental agreement. Create it from the agreement.").$id.post.tsx— see posting flow below.$id.void.tsx(voidShipment/voidReceipt) — guards status, invokes the posting withtype: "void".$id.delete.tsx(deleteShipment/deleteReceipt) — guard: blocked oncepostingDateis set.lines.update.tsx(updateShipmentLines/updateReceiptLines) — one field on the selected lines; onlystorageUnitId+shippedQuantity(receipt:receivedQuantity). Item/storage rules are NOT evaluated here, only at post.lines.tracking.tsx(assignShipmentLineEntity; receipt:setReceiptLineBatch/setReceiptLineSerial/assignReceiptReturnEntity/removeReceiptReturnEntity, one pertrackingType) — writestrackedEntity.attributes("Shipment Line",Shipment, serial"Shipment Line Index"); guards entity status withshippableEntityStatuses(inventory.utils.ts) —"Available"normally,"On Hold"when the shipment's source is a Sales Return Order (returned stock ships back from hold),"Available"or"Rejected"when it is a Purchase Return Order (rejected units go back to the supplier — a Rejected unit only when itsReceiptattribute is a posted receipt from the shipment's supplier); clears stale attrs off prior entities. Receipt tracking additionally has areturnEntitytype for sales-return receipts (same-serial re-entry, guarded by provenance: the entity must be the return line's item and shipped to that return's customer on a posted shipment). A receipt serial write is keyed by its box (Receipt Line+Receipt Line Index), not by the serial number, and planned by the pureplanSerialBoxWrite(inventory.models.ts): an empty value clears the box, a new value renames the box's unposted entity, and a refused value (a serial of a unit withitemLedgerhistory, checked first; a serial held by another box or by any other record, such as a job's reserved serial; or a failed write) empties the box, so a box showing an error never posts its previous serial. Only this box's record, or one from a voided receipt, is ever taken over. Typed serials only exist on purchase receipts of new units (outside-processing lines ask for none, inbound transfers never touch serials), so writing into an existing unit is never right: it wiped a shipped unit'sShipmentlink, which the RMA provenance check reads.ReceiptLinessends every blur as typed, an empty value included, and shows the server's error: the server, not the page, decides a duplicate, so a box is never cleared because another box holds the same text. Enter only moves focus (data-serial-boxes) so the blur is the one save.setReceiptLineSerialrunssaveReceiptSerialBox(inventory.service.ts): the reads, the write (update_receipt_line_serial_tracking, called through Kysely) and the release in one transaction, holding the receipt lineFOR UPDATEso two saves of one line run one after the other; a failed write empties the box in a second one (clearReceiptSerialBox). Refused unless the receipt is Draft. ThepostReceiptoperation refuses a Posted or Voided receipt before any write, and refuses the post (back to Draft) whenreconcileReceiptSerialEntitiesreports a line still missing serials ("Serial numbers are missing"). LoweringreceivedQuantity(updateReceiptLines) runs the same cleanup on a Draft receipt, in one Kysely transaction with the quantity update, and refuses a non-numeric quantity. Every removal goes throughreleaseReceiptSerialEntities(@carbon/database/receipt-serials, Kysely, set-based; the line split uses it too): an entity with noitemLedgerhistory is deleted, one with history only loses its receipt attributes — a sales return re-tags real shipped units.lines.return-entitiesreports a failed read as an error, andReturnEntityFormshows it instead of falling back to typed serials (whose empty save would unlink an assigned unit).lines.split.tsx(splitShipmentLine/splitReceiptLine) — invokescreatewithtype: "shipmentLineSplit"/receiptLineSplit. A serialreceiptLineSplitdrops the line's serials, deleting only entities with noitemLedgerhistory; a unit with history (a sales return) only loses its receipt link.lines.$id.delete.tsx—deleteShipmentLine/deleteReceiptLine.fixed-asset-lines.update.tsx(updateShipmentFixedAssetLine/updateReceiptFixedAssetLine) — update one field of ashipmentFixedAssetLine/receiptFixedAssetLine, parsed byshipmentFixedAssetLineUpdateValidator/receiptFixedAssetLineUpdateValidator(inventory.models.ts):shipped/received,serialNumber,meter; the receipt also takesnotes,outOfService("" clears the tick, any other text is the reason, so tick and reason save together) andresidualDestination. It refuses a line whose document is not Draft ("A posted shipment can no longer be changed" / "A posted receipt can no longer be changed"): a posted document is a record, the meter included._layout.tsx— breadcrumb handle back topath.to.inventory.
Navigate via the typed path.to.* helpers (shipmentDetails, shipment, shipmentPost,
shipmentVoid, shipmentLineSplit, …) in apps/erp/app/utils/path.ts — never hardcode URLs.
Components
- Page (
$id.tsx):DocumentPage(components/DocumentPage/) with{Shipment,Receipt}Header(ID, status, created/posted line, ⋯ Void/Delete, labelsPrintButton, Invoice, Post) and aDocumentSidebarwhose Documents tab is{Shipment,Receipt}Documents— the customer/supplier, the source document, invoices (shipment:getShipmentRelatedItems; receipt:getReceiptRelatedItems, which also resolves a sales return's customer), receipt inspections and line attachments, the shipment's packing slip (only for the sources its PDF route renders: Sales Order, Sales Invoice, Purchase Order, Outbound Transfer, Rental Agreement —PACKING_SLIP_SOURCES; a rental shipment prints as a "Delivery Ticket", one row per shipped unit with its serial number, through thetitlefield ofPackingSlipData) — and whose Activity tab is the audit log. - Form (
ShipmentForm.tsx,ReceiptForm/ReceiptForm.tsx): flatValidatedForm(no Card), source-documentSelect+ dependentCombobox(ID),Location, custom fields. Theuse{Shipment,Receipt}Formhook fetches selectable source documents (filtered by status) when not posted. Posted lockslocation,sourceDocument,sourceDocumentId. Shipment extra fieldtrackingNumber+ShippingMethod; receipt extraexternalDocumentId. - Lines (
ShipmentLines.tsx,ReceiptLines.tsx): card-row list (a bordered div, not a table), one…LineItemper line. InlineNumberFieldfor shipped/received qty and a storage-unitCombobox(disabled for PO/Job fulfillment), each persisting via a fetcher tolines.update. Per-line dropdown = Split / Delete. Optimistic updates merge pending fetcher submissions. Batch/serial sub-forms render only whenline.requiresBatchTracking/requiresSerialTracking. Receipt batch/serial forms add an expiration date (batch date shows only when item shelf-life mode is "Set on Receipt") and a per-line FileDropzone; shipment forms do not. A receipt line that is inspected shows a small red clipboard beside the item name (ReceiptLineInspectionMark): on an unposted Purchase Order receipt when the item has a Receipt-usage inspection plan (getReceiptInspectedItemIds, loaderinspectedItemIds), and once posted when the line has a lot (receiptInspectionsbysourceDocumentLineId), which the mark links to for aqualityviewer. - Rental lines: on a
'Rental Agreement'document the loader readsgetRentalShipmentLines/getRentalReceiptLinesintorentalLines, rendered by the siblingsShipmentRentalLineItem/ReceiptRentalLineItem(no storage unit picker, no serial tracking). Both render the unit through the sharedRentalUnitRow(ui/Shipments/RentalUnitRow.tsx: tick, item thumbnail, unit name, asset id and serial, and Meter — aNumberFieldwhile Draft, plain text once posted; laid out on the row's own@container). Shipment: the shipped tick and Meter. Receipt adds Notes, the Take out of service switch (a@carbon/formBooleaninside a field-context-onlyValidatedForm, saved through the same per-field update) with its reason, and Return To (Fleet / Inventory) for a unit treated as a sale. The loaders sortrentalLinesby asset id so the list holds still across edits. The existing fixed-asset components need an order line id, which a rental line does not have. - Notes: shipment uses
ShipmentNotes(Card with internal + external tabbed editors). Receipt details reusesSupplierInteractionNotes(internal notes only) — there is noReceiptNotescomponent. - Status (
ShipmentStatus.tsx,ReceiptStatus.tsx):Draft(gray)Pending(orange)Posted(green)Voided(red). Shipment additionally showsInvoiced(blue) wheninvoicedand not voided. - Modals:
ReceiptPostModal(validates lines on mount — batch lines need a batch number, serials reconciled across indices0..receivedQuantity; usesuseRuleViolations),ShipmentVoidModal/ReceiptVoidModal(destructiveAlert+ bulleted consequences, submit viafetcher.Formto the void route). Shipment posting is gated byShipmentPostModal.tsx. On a rental document the post modals show a date field, Delivered on / Returned on (default company today, no future date), sent aspostingDate;ReceiptPostModalalso blocks a ticked unit treated as a sale that has no Return To. Both post modals are source-aware for return flows, and must stay in step withlines.tracking's guard or they reject what tracking accepted:ReceiptPostModalcounts a serial slot as filled when the entity is merely ASSIGNED on aSales Return Orderreceipt (returned units are picked, not typed, so they carry noreadableIdof their own);ShipmentPostModal,ShipmentLines' batch/serial inputs andlines.trackingall readshippableEntityStatuses(inventory.utils.ts, pinned byinventory.utils.test.ts), so the three cannot drift.
Posting flow ($id.post.tsx → api.inventory.postShipment / postReceipt → posting body)
The operation (postShipment / postReceipt in inventory.server.ts): evaluates storage/sales
rules (@carbon/ee/rules.server) over the relevant surfaces — a blocking rule returns
{ violations, ruleNames }, which the route hands to useRuleViolations — optimistically sets
status: "Pending", then
invokePosting(ctx, "post-shipment", { type: "post", shipmentId, postingDate }, service.postShipment)
(receipt: invokePosting(ctx, "post-receipt", { receiptId, postingDate }, service.postReceipt),
whose type defaults to "post").
On error it reverts status to Draft. May then auto-print and (sales shipment, before the post)
save a packing slip PDF through renderPackingSlip (inventory/packing-slip.pdf.tsx, the
same renderer file+/shipment+/$id[.]pdf.tsx serves); receipt may call
updatePurchasedPrices (purchasing.service.ts) when updateLeadTimesOnReceipt is set.
postReceipt and postShipment (inventory.service.ts, ported from the post-receipt and post-shipment server functions) take
{ type: "post" | "void", {receipt,shipment}Id, postingDate? } (the context carries companyId / userId;
postingDate is read only by the rental source, and $id.post.tsx passes it from the modal to the operation), run
the service-role client + Kysely db.transaction(), and branch on sourceDocument:
post-receipt handles
Purchase Order,Inbound Transfer,Rental Agreement(returns each ticked unit throughreturnRentalUnitand moves itsfixedAsset.locationIdto the receipt's location;returnRentalUnitinsales.service.ts), andSales Return Order(customer RMA re-entry at original outbound cost, entities to On Hold). The PO, transfer and RMA branches skip a line received at 0 — it books noitemLedger, cost layer or journal line. In the PO path a line received at 0 is also left out ofreceiptLinesByPurchaseOrderLineId(its PO line keeps itsreceivedDate, an outside-processing operation its status) and out oftrackedEntityUpdates(a batch or serial still on it is not set Available and gets no Receive activity). PO path: insertsitemLedger(entry typesPositive/Negative Adjmt.by sign), GR/IR + inventoryjournalLines for every company (the journal is Provisional before the accounting cutover, Posted after it), advances PO linequantityReceived/receivedCompleteand POstatus, flips tracked entities toAvailable(On Holdif the item has a Receipt-usage inspection document assignment), and creates oneinspectionlot per inspected line (seeinspection-system.md). The PO and sales return journal lines are built by pure builders ininventory.service.ts(buildPurchaseReceiptJournalLines,buildSalesReturnReceiptJournalLines;purchaseReceiptLineCostsvalues each PO line: shipping share, invoice-first claim; a negative line books whatcalculateCOGSrelieved inside the transaction); the legacy backfill (activateAccounting,accounting.service.ts) calls the same builders with the stored cost rows.post-shipment handles
Rental Agreement(puts each ticked unit On Rent on the delivery date; noitemLedger,costLedgeror journal),Sales Order,Purchase Order,Outbound Transfer,Sales Return Order(return-to-customer), andPurchase Return Order(supplier return, Cr Inventory / Dr GR/IR; thecreateposting seeds the shipment's tracked entities frompurchaseReturnOrderLineTrackedEntity, and this path splits a batch when the returned quantity is less than the entity's — samebuildBatchSplitRecordsmechanism as SO). SO path: COGSjournalLines viacalculateCOGS+costLedger, negativeitemLedger, advances SO linequantitySent/sentCompleteand SOstatus, updatesjob.quantityShipped/status for Job fulfillment, and splits batch tracked entities when shipped qty < entity qty. A serial or batch is taken from the bin it actually holds stock in (getTrackedEntityBins, null = no storage unit), notshipmentLine.storageUnitId; the split is booked in that same bin, a unit with no stock anywhere refuses the post, and the void restores each unit to the bin its posting used. The shipment journal lines (SO pairs, fixed asset sale lines, return pairs) are built by pure builders ininventory.service.ts(buildSalesShipmentJournal,buildReturnShipmentJournal) from facts the posting gathers; the accounting cutover's legacy backfill (activateAccounting,accounting.service.ts) calls the same builders with the stored cost rows. GL dimensions on return journals. Every return-flow journal (post-shipmentSales Return Order+Purchase Return Order, post-receiptSales Return Order) attaches automaticjournalLineDimensionrows — item, item posting group (itemCost.itemPostingGroupId), party (supplier/customer + type), and location — built index-parallel to the journal lines, gated by the company group's configureddimensionrows. post-shipment and post-receipt carry them on each built line (dimensions, by entity type) and write them withjournalLineDimensionRows(shared.service.ts). The journalLine insert must.returning(["id"])so dimension #i binds to line #i. The void cases copy the original lines' dimensions onto the reversing lines (readjournalLineDimensionbyjournalLineId, re-attach by position) so a void mirrors the posting.post-memoalready carries the party dimensions; its legs are aggregate so no per-item dimension applies.void(post fn,type: "void"): requiresstatus === "Posted"; receipt also blocks ifinvoiced(and only PO-sourced receipts can void). Posts reversingitemLedger+journalLines, rolls back source-document quantities, setsstatus: "Voided". A purchase receipt's void drains its tracked entities to quantity 0 /Consumed(Scrapped/Rejectedkept) — they were never received, so no picker may offer them; a sales-return receipt's void flips the returned units back toConsumed. Inside the transaction (lockPostedReceipt,assertReceivedStockOnHand,assertNoRejectedUntrackedLotininventory.service.ts) the void locks the receipt and re-checksPosted(two voids at once cannot both reverse it), refuses when the reversal would take a bin below zero — a serial or batch is checked on its own, so a unit that was moved, picked or shipped after posting is caught even when the bin holds other stock — and refuses a purchase receipt whose untracked inspection lot was rejected (the reject route already wrote that stock off).ReceiptVoidModalshows a refusedvoidReceiptin place and stays open. A serial from a voided receipt can be entered on a new receipt:saveReceiptSerialBoxreuses the same tracked entity (idsWithLiveStockHistoryignores the ledger rows of voided receipts,onVoidedReceiptlifts the "taken by another box" refusal), so one unit keeps one history. The function's update keeps quantity and status, so the save resets that record to 1 / On Hold, as a new draft serial starts.voidReceiptandpostReceiptshow a posting refusal (status below 500) in the posting's own words; the refusals inpostReceiptareInvalidInputError, never a plainError(which the posting reads as a 500 and the dialog would show as "Failed to void receipt"). A rental shipment voids while every unit is still On Rent and noAccrualrow of its lines is Posted or held by a Draft run: the units go back to Pending.post-receiptrefuses a rental receipt void ("A rental return cannot be voided. Correct the unit by hand."). The rental lifecycle itself is inapps/erp/app/modules/sales/AGENTS.md→ Rentals.
Gotchas
Pendingis a transient posting state, not a workflow stage. The action sets it before the posting call and the action reverts it toDrafton failure.- Status enums are only
Draft / Pending / Postedin the base migrations;Voidedwas added later (20250828142122_void-shipment.sql,20260422100000_receipt-status-voided.sql). Read newest first. - The
sourceDocumentenums list many values (Sales/Purchase Invoice, Return Orders, Manufacturing Consumption/Output for receipts), but the post fns only implement the handful above — other source documents fall through with no posting effect. - Lines persist directly through
lines.updateon edit; the form's submit only saves the header. create, post-shipment, and post-receipt run service-role + Kysely (RLS bypassed) — the operation'spermission(update: "inventory",createforcreateShipment/createReceipt) is the auth gate, for every caller.