Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Plan how a delivery is recorded, and what the dock can say about it
Damian Legawiec416bc21ba66c
diff --git a/docs/plans/6.0-inventory-operations.md b/docs/plans/6.0-inventory-operations.mdindex 0c5ca912c7..5e343d5288 100644--- a/docs/plans/6.0-inventory-operations.md+++ b/docs/plans/6.0-inventory-operations.md@@ -12,7 +12,7 @@Lift inventory operations from "atomic decrement + log" to a first-class workflow on par with Shopify. Three coordinated changes:-1. **`Spree::StockTransfer` gains a lifecycle.** Today a transfer is one-shot — source decrements and destination increments in the same transaction. After this plan: `draft → ready_to_ship → in_transit → received` (with `cancelled` as a terminal escape hatch), plus line items, partial receive support, and a discrepancy column. Source units leave on `mark_in_transit`, destination units land on `receive` — not at the same instant.+1. **`Spree::StockTransfer` gains a lifecycle.** Today a transfer is one-shot — source decrements and destination increments in the same transaction. After this plan: `draft → ready_to_ship → in_transit → received` (with `over_received` and `canceled` as the other terminal states), plus line items and partial receive support. Source units leave on `mark_in_transit`, destination units land on each **stock receipt** — not at the same instant.2. **New `Spree::PurchaseOrder` model** for supplier receives. Today's "external receive" hack (a `StockTransfer` with `source_location_id: nil`) is replaced by a proper `PurchaseOrder` with `supplier`, `expected_at`, `line_items[]` with `unit_cost`, and the same receive flow as transfers.3. **Variant + Location stock history.** Surfaces the audit feed introduced by `6.0-typed-stock-movements.md` as inline timelines in the admin SPA — answering "why is on-hand 47?" in the place users always ask: on a SKU or a warehouse.4. **Simple lot capture** (reshaped 2026-09-07 — the tier split): OSS records **which lot/batch a fulfillment actually shipped** — entered at fulfillment time, split across batches when needed — and makes the lot number searchable in both directions (customer → order → lot; lot → every order/customer that received it — the recall question). The full lot **library** (received-lot inventory with quantities, expiry, FIFO/FEFO auto-allocation) is the Enterprise layer that fills these same capture rows automatically.@@ -59,18 +59,18 @@ Once `6.0-typed-stock-movements.md` lands, every change to `count_on_hand` carri### Transfers-- **`Spree::StockTransfer` gets a `status` column** with values `draft | ready_to_ship | in_transit | partially_received | received | canceled`, declared with `Spree::HasStatus` and moved by workflows (see the 2026-09-07 decisions below). No state machine.+- **`Spree::StockTransfer` gets a `status` column** with values `draft | ready_to_ship | in_transit | partially_received | received | over_received | canceled`, declared with `Spree::HasStatus` and moved by workflows (see the 2026-09-07 decisions below). No state machine.- **Two-phase stock movement**, mirroring Shopify. Source's `count_on_hand` decrements on `mark_in_transit`. Destination's `count_on_hand` increments on `receive` (potentially partial). Between those two events, the units are in flight — physically gone from the source, not yet at the destination.-- **First-class line items.** New table `spree_stock_transfer_items` with `(stock_transfer_id, variant_id, quantity_shipped, quantity_received, condition)`. Replaces today's "implicit line item via stock_movement.stock_item.variant".-- **Partial receive is the default model.** The receive screen edits `quantity_received` per item. If `SUM(quantity_received) < SUM(quantity_shipped)`, status becomes `partially_received`; when equal, `received`. A `discrepancy_reason` column on the line item captures "damaged in transit / lost / undercount" for the gap.+- **First-class line items.** New table `spree_stock_transfer_items` with `(stock_transfer_id, variant_id, quantity_shipped, quantity_received, quantity_rejected)`. Replaces today's "implicit line item via stock_movement.stock_item.variant".+- **Every delivery is a `Spree::StockReceipt`** (2026-09-10). A receive records what *this* delivery brought — accepted and rejected counts per line, with a rejection reason — as a numbered document with its own reference (the packing slip) and date. Lines carry the running totals; the receipt is the record of each arrival. `partially_received` while any line is short, `received` once every line has what it expected, `over_received` once any line has more.- **Cancelled is terminal.** Cancelling a `draft` is a no-op for stock. Cancelling an `in_transit` transfer requires the merchant to choose: write the source back to its `count_on_hand` (treat as if it never shipped), or write off the units (shrinkage; `adjusted` movement with reason). No silent reversal.-- **`receive` writes typed `received` stock movements with `stock_transfer_id`.** `mark_in_transit` writes typed `shipped` movements with `stock_transfer_id`. Two-way reconciliation through the `kind` + `stock_transfer_id` columns of `6.0-typed-stock-movements.md`.+- **A receipt writes typed `received` stock movements with `stock_transfer_id` and `stock_receipt_id`.** `mark_in_transit` writes typed `shipped` movements with `stock_transfer_id`. Two-way reconciliation through the `kind` + FK columns of `6.0-typed-stock-movements.md`.### Purchase Orders- **New model `Spree::PurchaseOrder`**, not an STI subclass of `StockTransfer`. The two share a UX rhythm (line items → receive flow) but their domains are distinct (supplier vs warehouse, unit cost vs no cost, AP vs internal logistics). STI would force one table to carry both vocabularies. Better to have parallel models with a shared `Receivable` concern that owns the line-items + receive-flow + status machine.- **`Spree::Supplier` is the supplier identity.** Minimal: `name`, `contact_name`, `email`, `phone`, `address`, `notes`, `metadata`. Stores manage their own supplier list — suppliers are not shared across stores in 6.0.-- **Statuses**: `draft | ordered | partially_received | received | canceled`. No `in_transit` — a PO doesn't track in-flight stock from the supplier; the merchant only knows about it when units land. (Future enhancement: optional `shipped` state if the supplier provides tracking, but not in 6.0.)+- **Statuses**: `draft | ordered | partially_received | received | over_received | canceled`. No `in_transit` — a PO doesn't track in-flight stock from the supplier; the merchant only knows about it when units land. (Future enhancement: optional `shipped` state if the supplier provides tracking, but not in 6.0.)- **`PurchaseOrderItem` has `unit_cost` (Money) and `quantity_ordered` / `quantity_received`.** Currency comes from the PO's `currency` column (defaults to the store's). Receiving units writes typed `received` stock movements with `purchase_order_id`.- **PO does not affect `count_on_hand` until receive.** Ordered units are visible to the merchant as "on order" (computed: `SUM(quantity_ordered - quantity_received)` per variant), but never count toward availability.@@ -165,6 +165,48 @@ plan written against 5.x idioms that 6.0 has since retired.`returns/:id/receive` and every other transition already in the Admin API. The plan's claim thatthese are POSTs describes no existing endpoint.+### Receipts, discrepancies and the rest of the dock (2026-09-10)++Settled against a comparison with a multi-location omnichannel merchant's own purchasing+implementation. Six additions, one model.++- **`Spree::StockReceipt` is one delivery.** `number` (`SR-…`), polymorphic `receivable`+ (purchase order or transfer), `reference` (the supplier's delivery note or packing slip),+ `received_at`, `received_by`, `notes`, `metadata`, store-scoped. `Spree::StockReceiptItem` is+ one line of it: polymorphic `line` (the PO or transfer item), `quantity_accepted`,+ `quantity_rejected`, `rejection_reason` (`damaged | wrong_item | expired | other`), `notes`.+ Named *stock* receipt on purpose — a customer-facing sales receipt will want the plain word.+- **A receive payload carries this delivery's counts, not running totals.** "40 arrived, 2+ rejected" is what a receipt is and what a warehouse types; the screen shows received-so-far+ beside it. `PATCH …/receive` is replaced by `POST …/stock_receipts` (a nested resource, per the+ API conventions) — nothing had shipped, so no bridge.+- **Rejected units are never stocked.** They write no movement and exist only on the receipt.+ Stocking damaged goods into a quarantine location is a different feature.+- **Over-receipt is allowed and is its own status.** The "may not exceed expected" validation+ goes. A document settles `over_received` — terminal, closed — when any line has accepted more+ than it expected; the extra units are on the shelf, because they are. `quantity_over` and+ `quantity_rejected` are exposed per line. Lines keep `quantity_received` (accepted running+ total) and gain `quantity_rejected`; `discrepancy_reason` leaves `stock_transfer_items`.+- **Close short.** `Close` workflows take `partially_received → received`, stamping+ `closed_short_at` and `close_reason`. No stock moves: on a PO the units never came, on a+ transfer they already left the source. The outstanding count stays on each line. The same+ `close_reason` column records why a cancelled transfer's in-flight units were written off,+ which used to live on the line.+- **`cancel_by` date on the PO**, informational plus two list filters — *Overdue* (`expected_at`+ passed, still open) and *Past cancel-by*. Nothing cancels automatically: that is a call to+ confirm with the supplier, not a job.+- **Back to draft.** `MarkDraft`: transfers `ready_to_ship → draft`; POs `ordered → draft` only+ while no receipt exists, clearing `ordered_at`.+- **CSV through the existing frameworks.** `Spree::Exports::PurchaseOrders` — one row per line+ (number, status, supplier, destination, expected, cancel-by, currency, SKU, name, ordered,+ received, rejected, unit cost) — is the file a merchant sends a supplier; one order is an+ export filtered to its number. `Spree::Imports::PurchaseOrders` groups rows by `reference` into+ one **draft** per group; supplier and destination are named by name; the SKU must exist+ (catalog-less lines stay out of scope). Both gate on `purchasing`.+- **Out of scope, deliberately:** PO lines for products not yet in the catalog (a pre-season+ buying feature that drags product creation into purchasing), dropship, consignment, and a+ quarantine location for rejected units.+### Typed Stock Movements wiringThese additions live in `6.0-typed-stock-movements.md`; this plan only consumes them.@@ -174,13 +216,13 @@ These additions live in `6.0-typed-stock-movements.md`; this plan only consumes### Admin SPA UX-- **Top-level Products subnav**: `Transfers`, `Purchase Orders`. Each is a list page with status filters (Draft / Ready / In transit / Received / All).+- **An `Inventory` section of its own** in the sidebar, after Products: `Transfers`, `Purchase orders`, `Suppliers` — at top-level routes (`/transfers`, `/purchase-orders`, `/suppliers`), because the sidebar marks a section active by URL prefix and anything under `/products` lights Products up too. Each list has status filters, and purchase orders add *Overdue* and *Past cancel-by*.- **Transfer detail page** has three modes by status:- `draft` → editable line items, "Mark as ready to ship" / "Cancel" actions.- `ready_to_ship` → frozen line items, "Mark in transit" (writes source `shipped` movements) / "Back to draft" / "Cancel".- - `in_transit` / `partially_received` → receive screen: per-item `quantity_received` input with running totals, optional `discrepancy_reason` per item, "Receive" submit (writes destination `received` movements for the deltas).- - `received` / `cancelled` → read-only summary + activity log.-- **Purchase Order detail** mirrors transfer detail. `draft` → editable line items + costs. `ordered` → frozen line items, "Receive" enabled. Same partial-receive screen.+ - `in_transit` / `partially_received` → receive screen: per-item *accepted* and *rejected* inputs for this delivery (with a rejection reason), received-so-far beside them, the delivery's reference and date, "Receive" submit (creates a stock receipt, writes destination `received` movements for the accepted units). `partially_received` also offers "Close short".+ - `received` / `over_received` / `canceled` → read-only summary, the receipts, and the activity log.+- **Purchase Order detail** mirrors transfer detail. `draft` → editable line items + costs. `ordered` → frozen line items, "Receive" enabled, "Back to draft" while nothing has arrived. Same receive screen. The list offers CSV import and export.- **Variant Inventory tab (on Product detail) gains a History panel.** Reads `GET /api/v3/admin/stock_movements?q[stock_level_variant_id_eq]=…` (the typed-movements admin endpoint), renders `date · location · qty before → after · kind · cause` with the cause linking to the underlying entity (Transfer T-…, PO PO-…, RMA RA-…, Order #…, "Manual adjustment").- **Stock Location detail page (settings) gains an Activity tab.** Same data shape, scoped via `q[stock_level_stock_location_id_eq]`. Useful for warehouse reconciliation.- **No standalone "Stock Movements" page.** Movements are always read in the context of a variant or a location. The legacy admin's firehose list is gone.@@ -273,89 +315,81 @@ end```rubyclass Spree::PurchaseOrder < Spree.base_classhas_prefix_id :po+ include Spree::SingleStoreResourcehas_spree_number prefix: 'PO' # see 6.0-document-numbers.mdinclude Spree::NumberIdentifier- include Spree::SingleStoreResource- include Spree::Metafields+ include Spree::HasStatus+ include Spree::Receivable # lines, totals, receipts, open/closed+ include Spree::HasCustomFieldsinclude Spree::Metadatapublishes_lifecycle_events- belongs_to :supplier, class_name: 'Spree::Supplier'- belongs_to :destination_location, class_name: 'Spree::StockLocation'- belongs_to :store, class_name: 'Spree::Store'-- has_many :items, class_name: 'Spree::PurchaseOrderItem',- inverse_of: :purchase_order, dependent: :destroy- has_many :stock_movements, class_name: 'Spree::StockMovement',- inverse_of: :purchase_order- accepts_nested_attributes_for :items, allow_destroy: true-- attribute :currency, :string- attribute :expected_at, :date- attribute :notes, :text+ has_status :draft, :ordered, :partially_received, :received, :over_received, :canceled,+ default: :draft- # Currency defaults from the store before validation — creation paths never- # need to pass it explicitly, but may override for foreign-currency POs.- before_validation { self.currency ||= store&.default_currency }+ belongs_to :supplier, class_name: 'Spree::Supplier', counter_cache: true+ belongs_to :destination_location, class_name: 'Spree::StockLocation'+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true- validates :supplier, :destination_location, :currency, presence: true- validate :has_items, on: :submit+ has_many :items, class_name: 'Spree::PurchaseOrderItem', dependent: :destroy+ has_many :stock_receipts, as: :receivable, class_name: 'Spree::StockReceipt'+ has_many :stock_movements, class_name: 'Spree::StockMovement'- state_machine :status, initial: :draft do- event :mark_ordered do- transition from: :draft, to: :ordered- end- event :receive_partial do- transition from: :ordered, to: :partially_received,- if: ->(po) { po.items.any?(&:short?) }- end- event :receive do- transition from: %i[ordered partially_received], to: :received,- unless: ->(po) { po.items.any?(&:short?) }- end- event :cancel do- transition from: %i[draft ordered partially_received], to: :cancelled- end-- after_transition to: :partially_received, do: :write_received_deltas- after_transition to: :received, do: :write_received_deltas- end+ # currency (defaults from the store), expected_at, cancel_by, reference,+ # notes, ordered_at, received_at, closed_short_at, close_reasonend```+Every transition is a workflow under `Spree::PurchaseOrders::` — `Create`, `Update`,+`MarkOrdered`, `MarkDraft`, `Receive` (creates a stock receipt), `Close`, `Cancel` — registered+on `Spree::Dependencies`.+### PurchaseOrderItem (new)```rubyclass Spree::PurchaseOrderItem < Spree.base_classhas_prefix_id :poi+ include Spree::ReceivableItem # variant, quantity_received/rejected, outstanding, over+ expects_quantity_in :quantity_ordered- belongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', inverse_of: :items- belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'+ belongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', touch: true- attribute :quantity_ordered, :integer- attribute :quantity_received, :integer, default: 0- attribute :unit_cost_cents, :integer- attribute :unit_cost_currency, :string+ validates :quantity_ordered, numericality: { greater_than: 0, only_integer: true }+ validates :unit_cost, numericality: { greater_than_or_equal_to: 0 } # decimal(10, 2)- monetize :unit_cost_cents+ def total_cost = unit_cost.to_d * quantity_ordered.to_i+end+```- validates :quantity_ordered, numericality: { greater_than: 0, only_integer: true }- validates :quantity_received, numericality: { greater_than_or_equal_to: 0, only_integer: true }- validate :received_does_not_exceed_ordered- validate :unit_cost_present_when_required+### StockReceipt (new, 2026-09-10)- def short?- quantity_received < quantity_ordered- end+```ruby+class Spree::StockReceipt < Spree.base_class+ has_prefix_id :sr+ include Spree::SingleStoreResource+ has_spree_number prefix: 'SR'+ include Spree::NumberIdentifier+ include Spree::Metadata- def outstanding- quantity_ordered - quantity_received- end+ publishes_lifecycle_events- def total_cost- unit_cost * quantity_ordered- end+ belongs_to :receivable, polymorphic: true # PurchaseOrder | StockTransfer+ belongs_to :received_by, class_name: Spree.admin_user_class.to_s, optional: true+ has_many :items, class_name: 'Spree::StockReceiptItem', dependent: :destroy+ has_many :stock_movements, class_name: 'Spree::StockMovement'++ # reference (the delivery note), received_at, notes+end++class Spree::StockReceiptItem < Spree.base_class+ has_prefix_id :sri+ REJECTION_REASONS = %w[damaged wrong_item expired other].freeze++ belongs_to :stock_receipt, class_name: 'Spree::StockReceipt'+ belongs_to :line, polymorphic: true # PurchaseOrderItem | StockTransferItem++ # quantity_accepted, quantity_rejected, rejection_reason, notesend```@@ -365,17 +399,15 @@ endclass Spree::Supplier < Spree.base_classhas_prefix_id :supinclude Spree::SingleStoreResource- include Spree::Metafields+ include Spree::HasCustomFieldsinclude Spree::Metadataacts_as_paranoid- belongs_to :store, class_name: 'Spree::Store'- belongs_to :address, class_name: 'Spree::Address', optional: true-- has_many :purchase_orders, class_name: 'Spree::PurchaseOrder'+ has_many :purchase_orders, class_name: 'Spree::PurchaseOrder', dependent: :restrict_with_error- validates :name, presence: true,- uniqueness: { scope: spree_base_uniqueness_scope }+ # name (unique per store, read through soft-deleted rows), contact_name, email,+ # phone, notes, and the address as inline columns — see the 2026-09-07 decisions.+ validates :name, presence: trueend```@@ -669,6 +701,7 @@ All other existing transfers (with a real source location) become `status: 'rece`source_location_id` or a `variant_id` out of a payload.- **Don't add receive flows to `StockTransfer` without `source_location_id`.** Supplier receives move to `PurchaseOrder`. If a 5.5 feature needs to record a supplier receive, scope it minimally and flag it for migration.- **Don't create a separate "Stock Movements" admin SPA page.** Movement history is always inline on variant + stock location.+- **Don't receive without a stock receipt.** `Receive` is the only writer of `quantity_received` and of `received` movements against a transfer or an order; a delivery that is not a `Spree::StockReceipt` cannot be reconciled, corrected or audited.- **Don't fold cost data onto `StockTransfer`.** Transfers don't have a unit cost — they move existing inventory between owned locations. Cost lives on `PurchaseOrderItem.unit_cost`.- **Lot capture lives only on `Spree::FulfillmentLot` rows** — no `lot_number` strings on line items, orders, or movements. The Enterprise library layers on these rows (its allocation fills them); OSS never grows lot quantities, expiry, or allocation of its own.@@ -689,7 +722,7 @@ All other existing transfers (with a real source location) become `status: 'rece- Current StockTransfer model: `spree/core/app/models/spree/stock_transfer.rb`- Current StockTransfer admin controller: `spree/api/app/controllers/spree/api/v3/admin/stock_transfers_controller.rb`-- Admin SPA routes: `packages/dashboard/src/routes/_authenticated/$storeId/products/transfers/`, `…/products/purchase-orders/` and `…/settings/suppliers.tsx`+- Admin SPA routes: `packages/dashboard/src/routes/_authenticated/$storeId/transfers/`, `…/purchase-orders/` and `…/suppliers.tsx`- Depends on: `docs/plans/6.0-typed-stock-movements.md` (movement primitives)- Depends on: `docs/plans/6.0-fulfillment-and-delivery.md` (Fulfillment writes `shipped`/`allocated`/`released` movements that show up alongside transfer/PO movements in the variant history)- Related: `docs/plans/6.0-stock-reservations.md` (reservations are checkout-time holds, orthogonal to operational receives)diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 86d16313a3..0287495c57 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,38 @@+## 2026-09-10: A delivery is a stock receipt — discrepancies get quantities, over-receipt gets a status, and a short order can be closed++**Context:** Comparing the shipped inventory operations against a multi-location omnichannel+merchant's own purchasing code showed what a warehouse dock records that ours could not: a+delivery with two damaged units out of ten, a delivery of twelve against ten ordered, and a+supplier confirming the last two will never come. Ours held one running total per line, a+single free-text discrepancy on transfer lines only, refused any receive above the expected+quantity, and left a short order in `partially_received` forever. The same review found no way+back from `ready_to_ship`, no cancel-by date, and no CSV in either direction.++**Decision:** One new model and five additions, recorded in `6.0-inventory-operations.md`+under "Receipts, discrepancies and the rest of the dock". `Spree::StockReceipt` is one+delivery against a purchase order or a transfer — numbered `SR-…`, carrying the packing-slip+reference and date — and `Spree::StockReceiptItem` is one line of it with `quantity_accepted`,+`quantity_rejected` and a `rejection_reason`. Named *stock* receipt because a customer-facing+sales receipt will want the plain word. A receive payload now carries this delivery's counts+rather than running totals, and `PATCH …/receive` becomes `POST …/stock_receipts`. Rejected+units are never stocked. Over-receipt is allowed and is a terminal `over_received` status of+its own (chosen over a badge: a list should say it at a glance). `Close` takes+`partially_received → received` with `closed_short_at` and a `close_reason`, which also+records why a cancelled transfer's in-flight units were written off. `cancel_by` is a date+on the order with *Overdue* and *Past cancel-by* filters and no automatic cancelling.+`MarkDraft` returns a `ready_to_ship` transfer, or an `ordered` order with no receipt, to+`draft`. CSV export and import ride the existing `Spree::Export` / `Spree::Import` frameworks+under the `purchasing` scope; the import groups rows by reference into drafts and requires+the SKU to exist.++**Consequences:** Every `received` movement against these documents now also names its+`stock_receipt_id`, so a delivery can be reconciled, and the upgrade task mints one receipt+per migrated 5.x receive so history reads the same way. `discrepancy_reason` leaves+`spree_stock_transfer_items`. Out of scope on purpose: purchase-order lines for products not+yet in the catalog, dropship, consignment, and a quarantine location for rejected units —+the first is a buying feature that drags product creation into purchasing, and the rest are+their own plans.+## 2026-09-07: Inventory operations grooming — transfers get a status and workflows, supplier receives become purchase orders, and a receive records what the units cost**Context:** `6.0-inventory-operations.md` was written before three things