Skip to content

armgit / spree

Public Imported from GitHub
0

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.

54.1 KB
Raw Blame

Inventory Operations (Transfers + Purchase Orders + Lots + Variant History)

Status: In Progress — the 6.0 half (transfers, purchase orders, suppliers, history screens) implemented 2026-09-07; Phase 7 (stock-level counters + the Inventory page) being built 2026-09-10; lot capture stays 6.1 Target: Spree 6.0 (transfers, purchase orders, history) / 6.1 (simple lot capture). Tier split 2026-09-07: the lot LIBRARY — received-lot inventory, quantities, expiry, FIFO/FEFO auto-allocation — moved to Enterprise (ee/docs/plans/inventory-lots.md); OSS keeps the traceability capture below. Depends on: Typed Stock Movements (6.0-typed-stock-movements.md), Fulfillment & Delivery (6.0-fulfillment-and-delivery.md), Stock Reservations (6.0-stock-reservations.md) Author: Damian + Claude Last updated: 2026-09-10 (Phase 7 open questions settled: close-short is an incoming writer, the Inventory page opens on every location, the recount is a 6.0 upgrade step) Tracking: Linear V-3628 · GitHub spree/spree#14616

Naming note (2026-07-14): the procurement-source model this plan introduces is Spree::Supplier (spree_suppliers, prefix sup_, /api/v3/admin/suppliers). An earlier draft called it Spree::Seller, which collided with the marketplace seller model of 6.0-multi-vendor-marketplace.md — Spree::Seller is reserved for marketplace sellers (see decisions.md 2026-07-14). "Supplier" also matches Shopify's purchase-order vocabulary.

Summary

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 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.

  5. An Inventory page, and the two counters it reads (added 2026-09-10). A list of stock levels under the Inventory section with Shopify's columns — on hand, committed, reserved, available, incoming — per location. On hand and committed were already persisted; reserved and incoming become counter-cache columns on spree_stock_levels, each with exactly one writer path and a recount task that doubles as the backfill.

This plan is the UX surface for inventory ops. The data primitives (typed StockMovement, kind, concrete FKs to Order/Fulfillment/Return/Exchange/StockTransfer/PurchaseOrder) come from 6.0-typed-stock-movements.md and the Fulfillment rename. Those two plans must land first.

Problem

1. Stock transfers don't model reality

A box moves from warehouse A to warehouse B over multiple days. Today's StockTransfer collapses the entire trip into one transaction:

source.unstock(variant, qty, self)
destination.restock(variant, qty, self)

This means:

  • A merchant cannot record "5 units left warehouse A today, arriving tomorrow" — the destination's count_on_hand jumps the moment the source decrements, so availability is wrong for the intervening period.
  • There is no partial-receive workflow. If 10 went out and 8 arrived (2 damaged in transit), there's no model for the discrepancy.
  • There is no "draft" state — a transfer can't be planned and edited before it ships.
  • There is no per-line-item record. A transfer of 5 SKUs becomes 5 independent rows whose only link is stock_movements.originator_id = transfer.id.

2. "External receive" is a hack

Today, receiving stock from a supplier is implemented as StockTransfer.transfer(nil, destination, variants) — passing a nil source. There is no supplier identity, no PO number, no unit cost, no expected-arrival date, no audit of who placed the order. The legacy admin's "Receive" screen is a StockTransfer form with the source dropdown hidden.

Suppliers and merchant warehouses are different things. A PO has unit cost (drives COGS / margin reporting), an expected date (drives replenishment scheduling), and a supplier (drives accounts payable). A transfer has none of those — it's internal logistics. Folding them together costs us margin reporting and replenishment UX forever.

3. Movement history has no UI surface

Once 6.0-typed-stock-movements.md lands, every change to count_on_hand carries a typed reason (received | allocated | shipped | released | adjusted) and a concrete FK to its cause. That data is invisible without screens. The legacy admin had a "Stock Movements" page that listed +5 from T-123, but it was an undifferentiated firehose across all SKUs and all locations — the question merchants actually ask is per-SKU ("why is this on-hand 47?") or per-location ("what changed in the Brooklyn warehouse this week?"). The destination is the question, not the dataset.

Current State

What How it works (5.5)
Spree::StockTransfer One-shot atomic transfer. Columns: source_location_id (nullable for receives), destination_location_id, number, reference, type (STI column, unused), created_at. No status, no expected/received-at, no line items.
External receive StockTransfer.transfer(nil, destination, variants) — no supplier, no cost.
Movement audit Spree::StockMovement with polymorphic originator — a Fulfillment (stock leaves at order placement, not at dispatch), a StockTransfer, a Return/Exchange, or nothing. Manual corrections and backordered restocks write no movement at all.
Admin SPA Products → Transfers (single page) with create-transfer sheet. No history view, no PO concept.

Key Decisions (do not deviate without discussion)

Transfers

  • 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, 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.
  • 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 | 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.

Simple lot capture (reshaped 2026-09-07 · 6.1)

  • Spree::FulfillmentLot — the capture row: fulfillment_item_id, lot_number (string, required), quantity (nullable — nil = the whole line; multiple rows express a split batch, e.g. 80 × LOT-001 + 20 × LOT-002). Entered in the fulfill dialog or added/corrected afterwards on the fulfillment card; lot_number is ransackable, and the dashboard's order search gains a lot-number mode so an accountant or QA manager can paste a batch number and see every affected fulfillment, order and customer.
  • lot_tracked boolean on the variant is an advisory prompt: the fulfill dialog requires lot entry for flagged variants (dashboard-level, the advisory-required precedent from product types); the server accepts lot rows on any item, flagged or not.
  • No quantities, no expiry, no allocation in OSS — the capture answers traceability, not inventory. The Enterprise lot library (received-lot rows per variant + location, expires_at/manufactured_on/supplier reference, manual | fifo | fefo allocation) writes these same capture rows automatically at dispatch, so the recall search reads one surface regardless of tier.
  • Store API: nothing — lots are back-office data.

Implementation decisions (2026-09-07)

Settled interactively before implementation; they replace the parts of this plan written against 5.x idioms that 6.0 has since retired.

  • No state machines — Spree::HasStatus plus workflows. state_machines-activerecord is not a dependency of 6.0 (6.0-normalize-state-to-status.md, 6.0-service-workflows.md decision 11), so the state_machine :status do … end blocks below are read as intent, not as code. Both models include Spree::HasStatus and declare has_status …, default: :draft; every transition is a workflow in app/workflows/spree/stock_transfers/ and app/workflows/spree/purchase_orders/, registered on Spree::Dependencies as stock_transfer_*_workflow / purchase_order_*_workflow. This is what makes a receive able to carry the quantities the warehouse counted and a cancellation able to carry the merchant's restock-or-write-off choice — arguments a transition callback could not take. The guards the state machine expressed (from: :in_transit) become the workflows' own status checks.
  • The one-shot StockTransfer.transfer / .receive class methods are removed outright. 6.0 is the breaking window (decisions.md 2026-08-30 left the choice to this grooming), and a deprecation shim would keep a second write path into count_on_hand alive for a release — precisely the thing typed movements exist to prevent. Spree::StockTransfers::Create + MarkInTransit + Receive replace them, and the admin POST /stock_transfers now persists a draft instead of moving stock. The unused type STI column and the dead persist: false movement path go with them.
  • Legacy source-less transfers are soft-deleted after migration, with a purge task for a later release. spree:upgrade:migrate_external_receives_to_purchase_orders mints the PO-…, points the existing movements at it and stamps the T-… transfer deleted_at, so the old number stays findable for historical reporting without the same receive appearing twice in the admin. spree:upgrade:purge_migrated_external_receives removes them when a merchant is ready.
  • Suppliers and purchase orders are one new permission-catalog resource, :purchasing. read_purchasing / write_purchasing, registered in PermissionConfiguration::DefaultCatalog.register alongside :stock. The plan's earlier read_inventory / write_inventory would have put "Stock" and "Inventory" side by side on the roles screen with nothing to tell a merchant which is which. Transfers stay under stock, whose subject list gains Spree::StockTransferItem.
  • spree_stock_transfers gains its own store_id. Today the table has none, Spree::Store has no stock_transfers association, and so Spree::Base.for_store falls through to self — the admin transfers endpoint is not store-scoped at all. The column, Spree::SingleStoreResource and a Store#stock_transfers association close that, and make transfers obey the same tenancy rule as purchase orders rather than a second one derived from destination_location. #number_store keeps working and now simply reads store.
  • source_location_id stays nullable in the database, with presence enforced on the model. A change_column_null … false would fail on any install still holding external-receive rows, and data transformations belong in rake tasks (CLAUDE.md), so the upgrade task is what empties the column of nulls.
  • Money is a decimal(10, 2) column, not _cents + monetize. Spree has no money-rails dependency; PurchaseOrderItem#unit_cost follows Spree::Variant#cost_price, and the currency comes from the purchase order rather than being repeated per line.
  • A supplier's address is inline columns, mirroring Spree::StockLocation — the closest precedent for a non-customer entity with a postal address, and the shape a flat v3 payload and a flat dashboard form both want. No belongs_to :address.
  • Suppliers are per store (spree_suppliers.store_id, Spree::SingleStoreResource, unique on (store_id, name)), settling open question 2. Promoting them to installation-wide later means adding a join table, backfilling one row per existing supplier and keeping store_id as the owner — worth knowing, not worth building against.
  • A receive stamps what the units cost onto the movement. spree_stock_movements.unit_cost (nullable decimal(10, 2)) records the price each unit actually landed at, so the rolling average-cost feature of open question 3 has a ledger to read instead of a reconstruction to attempt — including across two partial receives at different prices. StockLocation#restock and #move take an optional unit_cost:; transfers and returns leave it null, because moving stock a merchant already owns is not a purchase.
  • A soft-deleted supplier keeps its name (found in review). The obvious shape — a unique index narrowed to deleted_at IS NULL, matching a validation narrowed the same way — is not portable: MySQL has no partial indexes and Rails drops the WHERE silently, so the same delete-and-recreate would save on PostgreSQL and raise a constraint violation on MySQL. The index is therefore plain and the validation reads through soft-deleted rows to match it, which costs the ability to reuse a deleted supplier's name and buys identical behaviour on all three databases.
  • Status transitions are PATCH member routes, matching orders/:id/cancel, returns/:id/receive and every other transition already in the Admin API. The plan's claim that these 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.

Stock levels, counters and the Inventory page (2026-09-10)

Settled while adding the page merchants expect beside transfers and purchase orders: what do I have, where, and what is committed, held or on its way. Shopify's inventory grid is the reference for the columns; Medusa's inventory module (persisted stocked/reserved/incoming, derived available) is the reference for the storage shape.

  • Counters, not computes. spree_stock_levels gains reserved_count and incoming_count, integer, default: 0, null: false. The page is a paginated list read many times a day and the inputs change through a handful of workflows; the repo already trusts allocated_count, fee_total and commission_total the same way. (The 2026-09-07 ruling "availability is never denormalized" is about product market availability, not stock — it does not apply here.)
  • Each counter has exactly one writer path, mirroring the movement callback that alone writes allocated_count. Reserved: the reservation row itself — after_create (+), after_update (± the quantity change), after_destroy (−) — plus StockReservation.withdraw for the batch deletes Release and ExpireJob make (settled 2026-09-10 in review: Reserve writing the counter by hand left every cascade — a cart emptied, a line item removed, dependent: :destroy on a level — holding units forever). Extend only moves expires_at and is not a writer. The invariant is the sum of the rows that exist; expired rows leave it when the sweep or the recount deletes them. Incoming: PurchaseOrders::MarkOrdered (+ every line's incoming), ::MarkDraft (−), ::Cancel (−), ::Close (−), StockTransfers::MarkInTransit (+), ::Cancel (−), ::Close (−), and StockReceipts::Recording (−) for both — it already runs inside receivable.with_lock, so the incoming decrement is atomic with the on-hand increment and no mid-receipt read shows the units twice or not at all. Update is not a writer after all: it refuses anything past draft, and a draft contributes nothing.
  • Closing short is a writer (settled 2026-09-10). Close takes a document out of the open set the recount reads, so the units still owed on its lines leave the counter when it closes — the merchant has just said they are not coming. Without it, every close-short drifted the page the moment it ran and only the recount put it right.
  • The Inventory page opens on every location (settled 2026-09-10). One row per stock level with a Location column; the location switcher narrows the list rather than being required to see it. Nothing is summed across locations — a single-warehouse store sees one row per variant and a multi-warehouse one sees each shelf on its own line.
  • The recount is a 6.0 upgrade step (settled 2026-09-10). spree:stock:recount_levels is listed in the 5_6_to_6_0 manifest, so the same spree:upgrade that runs the other backfills fills the two counters on existing installs. It stays runnable by hand to repair drift.
  • Incoming is [expected − received − rejected, 0].max per line, as Spree::ReceivableItem#incoming shared by both item models. outstanding is not it: quantity_settled is received alone, so outstanding still counts rejected units as awaited, and they are not coming.
  • A transfer counts as incoming from in_transit, when MarkInTransit writes quantity_shipped. A ready_to_ship transfer contributes zero — nothing is moving yet. Shopify counts from creation; the divergence is deliberate and avoids inventing a planned-quantity column.
  • spree:stock:recount_levels recomputes both counters from their sources — active reservations; open PO lines (ordered | partially_received) and in-flight transfer lines (in_transit | partially_received) at their destination — logs every row whose stored value differed, and is the backfill. allocated_count has no such task; these two have eleven writers between them and get one.
  • Available on the page is count_on_hand − allocated_count − reserved_count — the figure Stock::Quantifier already produces, now readable from columns.
  • Unavailable is out of scope. Rejected delivery units are not it: they "exist only on the receipt" (above) and were never in the building, whereas Shopify's Unavailable is on-site stock held back (damaged, QC, safety stock). A true bucket is a fourth counter with its own adjust action and reason vocabulary; no reference validates it yet, so it is a separate plan item. Rejections are surfaced where they live — on the purchase order and the receipt.
  • Dashboard only. The stock permission already carries audiences: %i[store seller]; the seller panel gets the same table under a forced seller scope as a follow-up, per the dashboard-is-the-reference rule. The counters and the endpoint are shared, so that follow-up is a route and a scope, not a second implementation.

Typed Stock Movements wiring

These additions live in 6.0-typed-stock-movements.md; this plan only consumes them.

  • Add purchase_order_id FK to Spree::StockMovement (typed-movements plan lists order_id, fulfillment_id, return_id, exchange_id, stock_transfer_id — extend with purchase_order_id).
  • Add Spree::StockMovement::KINDS += ['purchase_order_received'] — actually no, reuse received with purchase_order_id set. Same shape as a return receive. The kind is what happened to stock; the FK is why.

Admin SPA UX

  • 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 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.
  • An Inventory list page at /inventory (2026-09-10), first in the Inventory section — the section's parent path moves here from /transfers. One row per stock level: product + variant (thumbnail, SKU), On hand, Committed (allocated_count), Reserved, Available, Incoming; a location switcher on the existing q[stock_location_id_eq]; SKU/name search on the existing variant association ransack; each row links to the variant. Reads the existing GET /admin/stock_levels — no new endpoint. Every figure is a column read; nothing on this page is summed at request time.

Design Details

StockTransfer (updated)

class Spree::StockTransfer < Spree.base_class
  has_prefix_id :st
  # Transfers have no store column; #number_store resolves through
  # destination_location.store — see 6.0-document-numbers.md
  has_spree_number prefix: 'T'
  include Spree::NumberIdentifier
  include Spree::Metafields
  include Spree::Metadata

  publishes_lifecycle_events

  belongs_to :source_location, class_name: 'Spree::StockLocation'
  belongs_to :destination_location, class_name: 'Spree::StockLocation'

  has_many :items, class_name: 'Spree::StockTransferItem',
           inverse_of: :stock_transfer, dependent: :destroy
  has_many :stock_movements, class_name: 'Spree::StockMovement',
           inverse_of: :stock_transfer
  accepts_nested_attributes_for :items, allow_destroy: true

  validates :source_location, :destination_location, presence: true
  validate :source_differs_from_destination
  validate :has_items, on: :submit

  state_machine :status, initial: :draft do
    event :mark_ready do
      transition from: :draft, to: :ready_to_ship
    end
    event :mark_in_transit do
      transition from: %i[draft ready_to_ship], to: :in_transit
    end
    event :receive_partial do
      transition from: :in_transit, to: :partially_received,
                 if: ->(t) { t.items.any?(&:short?) }
    end
    event :receive do
      transition from: %i[in_transit partially_received], to: :received,
                 unless: ->(t) { t.items.any?(&:short?) }
    end
    event :cancel do
      transition from: %i[draft ready_to_ship in_transit], to: :cancelled
    end

    after_transition to: :in_transit,     do: :write_shipped_movements
    after_transition to: :partially_received, do: :write_received_deltas
    after_transition to: :received,       do: :write_received_deltas
  end

  scope :open,   -> { where(status: %w[draft ready_to_ship in_transit partially_received]) }
  scope :closed, -> { where(status: %w[received cancelled]) }
end

StockTransferItem (new)

class Spree::StockTransferItem < Spree.base_class
  has_prefix_id :sti

  belongs_to :stock_transfer, class_name: 'Spree::StockTransfer', inverse_of: :items
  belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'

  validates :quantity_shipped, 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_shipped

  attribute :discrepancy_reason, :string

  def short?
    quantity_received < quantity_shipped
  end

  def outstanding
    quantity_shipped - quantity_received
  end
end

PurchaseOrder (new)

class Spree::PurchaseOrder < Spree.base_class
  has_prefix_id :po
  include Spree::SingleStoreResource
  has_spree_number prefix: 'PO'   # see 6.0-document-numbers.md
  include Spree::NumberIdentifier
  include Spree::HasStatus
  include Spree::Receivable          # lines, totals, receipts, open/closed
  include Spree::HasCustomFields
  include Spree::Metadata

  publishes_lifecycle_events

  has_status :draft, :ordered, :partially_received, :received, :over_received, :canceled,
             default: :draft

  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

  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'

  # currency (defaults from the store), expected_at, cancel_by, reference,
  # notes, ordered_at, received_at, closed_short_at, close_reason
end

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)

class Spree::PurchaseOrderItem < Spree.base_class
  has_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', touch: true

  validates :quantity_ordered, numericality: { greater_than: 0, only_integer: true }
  validates :unit_cost, numericality: { greater_than_or_equal_to: 0 }   # decimal(10, 2)

  def total_cost = unit_cost.to_d * quantity_ordered.to_i
end

StockReceipt (new, 2026-09-10)

class Spree::StockReceipt < Spree.base_class
  has_prefix_id :sr
  include Spree::SingleStoreResource
  has_spree_number prefix: 'SR'
  include Spree::NumberIdentifier
  include Spree::Metadata

  publishes_lifecycle_events

  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, notes
end

Supplier (new)

class Spree::Supplier < Spree.base_class
  has_prefix_id :sup
  include Spree::SingleStoreResource
  include Spree::HasCustomFields
  include Spree::Metadata
  acts_as_paranoid

  has_many :purchase_orders, class_name: 'Spree::PurchaseOrder', dependent: :restrict_with_error

  # 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: true
end

StockLevel counters (2026-09-10)

# migration — no index: read per row, never filtered
add_column :spree_stock_levels, :reserved_count, :integer, default: 0, null: false
add_column :spree_stock_levels, :incoming_count, :integer, default: 0, null: false
module Spree::ReceivableItem
  # Units still on their way. Not `outstanding`: settled means received, so
  # outstanding keeps counting units the dock refused, and those never arrive.
  def incoming
    [quantity_expected - quantity_received.to_i - quantity_rejected.to_i, 0].max
  end
end

Both PurchaseOrderItem (expects_quantity_in :quantity_ordered) and StockTransferItem (expects_quantity_in :quantity_shipped) already include the concern.

Counter Source of truth Writers (each adjusts by delta, inside the workflow's transaction)
reserved_count SUM(quantity) over the reservation rows per stock_level_id, after expired rows are swept the row's own after_create +, after_update ±, after_destroy −; StockReservation.withdraw − for Release and ExpireJob
incoming_count SUM(item.incoming) over open PO lines + in-flight transfer lines, keyed by (variant_id, destination_location_id) PO MarkOrdered +, MarkDraft −, Cancel −, Close −; transfer MarkInTransit +, Cancel −, Close −; StockReceipts::Recording − for both

spree:stock:recount_levels computes the two sources above per stock level, update_alls any row that differs, and prints the corrected rows. It is idempotent, is the Phase 7 backfill, and is a step of the 5_6_to_6_0 upgrade manifest so spree:upgrade runs it.

Stock movement extensions

Added to Spree::StockMovement (extends what 6.0-typed-stock-movements.md introduces):

belongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', optional: true
class AddPurchaseOrderToStockMovements < ActiveRecord::Migration[7.2]
  def change
    add_column :spree_stock_movements, :purchase_order_id, :bigint
    add_index  :spree_stock_movements, :purchase_order_id
  end
end

The kind stays received (already defined). PO is just a new cause flavor — the purchase_order_id FK is set, others are null.

Admin API

New endpoints; all CRUD-shaped, all under /api/v3/admin/:

GET    /stock_transfers
POST   /stock_transfers
GET    /stock_transfers/:id
PATCH  /stock_transfers/:id
DELETE /stock_transfers/:id                          # only when status == draft

POST   /stock_transfers/:id/mark_ready
POST   /stock_transfers/:id/mark_in_transit
POST   /stock_transfers/:id/receive                  # body: { items: [{ id, quantity_received, discrepancy_reason }] }
POST   /stock_transfers/:id/cancel                   # body: { on_in_transit: 'restock' | 'write_off' } when needed

GET    /suppliers
POST   /suppliers
GET    /suppliers/:id
PATCH  /suppliers/:id
DELETE /suppliers/:id

GET    /purchase_orders
POST   /purchase_orders
GET    /purchase_orders/:id
PATCH  /purchase_orders/:id
DELETE /purchase_orders/:id                          # only when status == draft

POST   /purchase_orders/:id/mark_ordered
POST   /purchase_orders/:id/receive                  # body: { items: [{ id, quantity_received }] }
POST   /purchase_orders/:id/cancel

Each status change is its own member action rather than a PATCH that mass-assigns status, because each one is a workflow with its own arguments. The verb is PATCH, matching orders/:id/cancel, returns/:id/receive and every other transition already in the Admin API.

GET /stock_movements (the audit feed introduced by 6.0-typed-stock-movements.md) gains support for q[purchase_order_id_eq] automatically once the FK is in the ransackable list.

GET /stock_levels (existing) gains reserved_count and incoming_count on the admin serializer beside the allocated_count and available_count it already emits (2026-09-10). No new endpoint; the index already ransacks stock_location_id, variant_id and the variant/stock_location associations, which is all the Inventory page needs.

Serializer shapes

// StockTransfer (admin)
{
  "id": "st_xxx",
  "number": "T-12345",
  "status": "in_transit",
  "reference": "PO from supplier A",
  "source_location_id": "sl_aaa",
  "destination_location_id": "sl_bbb",
  "shipped_at": "2026-05-10T12:00:00Z",   // set by mark_in_transit
  "received_at": null,                     // set by terminal `received`
  "items_count": 3,
  "quantity_shipped_total": 17,
  "quantity_received_total": 12,
  "created_at": "...",
  "updated_at": "..."
}

// StockTransferItem (admin)
{
  "id": "sti_xxx",
  "stock_transfer_id": "st_xxx",
  "variant_id": "variant_xxx",
  "quantity_shipped": 10,
  "quantity_received": 7,
  "outstanding": 3,
  "discrepancy_reason": "damaged_in_transit"
}

// PurchaseOrder (admin)
{
  "id": "po_xxx",
  "number": "PO-00042",
  "status": "partially_received",
  "supplier_id": "sup_xxx",
  "destination_location_id": "sl_bbb",
  "currency": "USD",
  "expected_at": "2026-06-01",
  "ordered_at": "2026-05-15T09:00:00Z",
  "items_count": 5,
  "quantity_ordered_total": 100,
  "quantity_received_total": 60,
  "subtotal": "1250.00",
  "display_subtotal": "$1,250.00",
  "created_at": "...",
  "updated_at": "..."
}

// PurchaseOrderItem (admin) — includes unit_cost
{
  "id": "poi_xxx",
  "purchase_order_id": "po_xxx",
  "variant_id": "variant_xxx",
  "quantity_ordered": 20,
  "quantity_received": 12,
  "outstanding": 8,
  "unit_cost": "12.50",
  "display_unit_cost": "$12.50",
  "currency": "USD"
}

Migration Path

Phase 0 (prerequisite)

6.0-typed-stock-movements.md lands first — the kind column, concrete FKs, allocated_count column on StockLevel, and StockMovement model rewrite. Without this, transfers and POs can't write typed audit rows.

Phase 1: Schema

class AddInventoryOperations < ActiveRecord::Migration[7.2]
  def change
    # StockTransfer gains status + timestamps
    add_column :spree_stock_transfers, :status,      :string, null: false, default: 'draft'
    add_column :spree_stock_transfers, :shipped_at,  :datetime
    add_column :spree_stock_transfers, :received_at, :datetime
    add_index  :spree_stock_transfers, :status
    # source_location_id becomes required — receives move to PurchaseOrder.
    change_column_null :spree_stock_transfers, :source_location_id, false

    create_table :spree_stock_transfer_items do |t|
      t.references :stock_transfer, null: false
      t.references :variant,        null: false
      t.integer    :quantity_shipped,  null: false
      t.integer    :quantity_received, null: false, default: 0
      t.string     :discrepancy_reason
      t.timestamps
    end
    add_index :spree_stock_transfer_items,
              [:stock_transfer_id, :variant_id],
              unique: true,
              name: 'idx_stock_transfer_items_unique'

    create_table :spree_suppliers do |t|
      t.string  :name,         null: false
      t.string  :contact_name
      t.string  :email
      t.string  :phone
      t.text    :notes
      t.references :store,     null: false
      t.references :address
      if t.respond_to?(:jsonb)
        t.jsonb :private_metadata
        t.jsonb :public_metadata
      else
        t.json  :private_metadata
        t.json  :public_metadata
      end
      t.datetime :deleted_at
      t.timestamps
    end
    add_index :spree_suppliers, [:store_id, :name], unique: true

    create_table :spree_purchase_orders do |t|
      t.string   :number, null: false
      t.string   :status, null: false, default: 'draft'
      t.references :supplier, null: false
      t.references :store,  null: false
      t.references :destination_location, null: false
      t.string   :currency, null: false
      t.date     :expected_at
      t.datetime :ordered_at
      t.datetime :received_at
      t.text     :notes
      if t.respond_to?(:jsonb)
        t.jsonb :private_metadata
        t.jsonb :public_metadata
      else
        t.json  :private_metadata
        t.json  :public_metadata
      end
      t.timestamps
    end
    add_index :spree_purchase_orders, :number, unique: true
    add_index :spree_purchase_orders, :status

    create_table :spree_purchase_order_items do |t|
      t.references :purchase_order, null: false
      t.references :variant,        null: false
      t.integer  :quantity_ordered,  null: false
      t.integer  :quantity_received, null: false, default: 0
      t.integer  :unit_cost_cents,   null: false, default: 0
      t.string   :unit_cost_currency, null: false
      t.timestamps
    end
    add_index :spree_purchase_order_items,
              [:purchase_order_id, :variant_id],
              unique: true,
              name: 'idx_purchase_order_items_unique'

    # Typed-movements extension
    add_column :spree_stock_movements, :purchase_order_id, :bigint
    add_index  :spree_stock_movements, :purchase_order_id

    # Simple lot capture (6.1)
    add_column :spree_variants, :lot_tracked, :boolean, default: false, null: false

    create_table :spree_fulfillment_lots do |t|
      t.references :fulfillment_item, null: false
      t.string  :lot_number, null: false
      t.integer :quantity
      t.timestamps
    end
    add_index :spree_fulfillment_lots, :lot_number
  end
end

Phase 2: Data migration (rake task spree:migrate_external_receives_to_purchase_orders)

For each existing StockTransfer with source_location_id IS NULL:

  1. Find-or-create a Spree::Supplier named "Migrated receives" for the relevant store.
  2. Create a Spree::PurchaseOrder with status: 'received', received_at: transfer.created_at, currency from store default, ordered_at: nil.
  3. Migrate the transfer's stock_movements into the PO via purchase_order_id (set, leave stock_transfer_id for historical lineage if desired, or null it). The migration leaves count_on_hand untouched — the movements already affected stock at the time.
  4. Create PurchaseOrderItem rows from the underlying movements with unit_cost_cents: 0 (historical cost is unknown).
  5. Mark the original StockTransfer as deleted_at-stamped + status: 'received' for audit, or hard-delete it after a release of soft-deprecation. Open question — see below.

All other existing transfers (with a real source location) become status: 'received' with received_at = created_at. They retroactively look like instantaneous transfers, which matches today's reality.

Phase 3: Model & service code

  • New models: Supplier, PurchaseOrder, PurchaseOrderItem, StockTransferItem.
  • StockTransfer gains a declared status + line items; the old atomic transfer/receive class methods are removed.
  • New services under Spree::Inventory:::
    • Spree::Inventory::SubmitTransfer (draft → ready_to_ship → in_transit, writes shipped movements)
    • Spree::Inventory::ReceiveTransfer (params: { items: [{ id, quantity_received, discrepancy_reason }] }, writes received movements for deltas)
    • Spree::Inventory::CancelTransfer
    • Parallel Spree::Inventory::SubmitPurchaseOrder / Spree::Inventory::ReceivePurchaseOrder / Spree::Inventory::CancelPurchaseOrder
  • Each service returns a ServiceModule::Result (success/error) — same pattern as existing checkout services.
  • Permissions: Supplier, PurchaseOrder and PurchaseOrderItem register as the :purchasing catalog resource (read_purchasing / write_purchasing); Spree::StockTransferItem joins the existing :stock resource's subject list.

Phase 4: Admin API + serializers

  • Register dependencies (admin_supplier_serializer, admin_purchase_order_serializer, admin_purchase_order_item_serializer, admin_stock_transfer_item_serializer).
  • Register API scopes: read_inventory / write_inventory for POs and suppliers. Transfers stay under read_stock / write_stock (existing).
  • Controllers under Spree::Api::V3::Admin:::
    • SuppliersController (standard CRUD)
    • PurchaseOrdersController (standard CRUD + transition actions)
    • StockTransfersController rewritten — no more create doing source/dest decrement; create persists a draft. Transitions are explicit actions.
  • New integration specs in spree/api/spec/integration/spree/api/v3/admin/.

Phase 5: SDK + admin SPA

  • Run typelizer + rswag + admin-client generators.
  • useTransfers, useTransfer, useTransition<Transfer> hooks (consolidate the action endpoints behind a single hook with action: 'mark_ready' | 'receive' | 'cancel').
  • Same shape for purchase orders.
  • useSuppliers.
  • Admin SPA routes: _authenticated/$storeId/products/transfers.{index,$id}.tsx, _authenticated/$storeId/products/purchase-orders.{index,$id}.tsx, _authenticated/$storeId/settings/suppliers.tsx.
  • Variant detail page gets a <StockMovementsHistory variantId> panel; stock-location detail page gets a <StockMovementsHistory stockLocationId> panel. Both read /admin/stock_movements with the relevant q[...] filter and render the timeline with RelativeTime.

Phase 6: Cleanup

  • Remove the StockTransfer.receive / StockTransfer.transfer no-source code path (already deprecated).
  • Drop the unused type STI column on spree_stock_transfers after confirming no plugin set it.

Phase 7: Stock level counters + Inventory page (2026-09-10)

Self-contained; another session can take it over from here. In order:

  1. Migration — reserved_count and incoming_count on spree_stock_levels (shape above), then pnpm wt:template so other worktrees inherit it.
  2. Spree::ReceivableItem#incoming with a model spec proving ordered 40, received 38, rejected 2 → incoming 0 (the case outstanding gets wrong).
  3. Writers. StockLevel#adjust_reserved_count(delta) / #adjust_incoming_count(delta) (locked increment!/decrement!, clamped at zero like release_allocated_count), called from exactly the workflows in the table above and nowhere else. Each workflow spec asserts the counter before and after; Recording's asserts that on-hand up and incoming down land in one transaction.
  4. spree:stock:recount_levels rake task + spec seeding a drifted row and asserting it is corrected; run it once as the backfill.
  5. Serializer — the two attributes on Admin::StockLevelSerializer; typelizer → zod → rswag → docs/api-reference.
  6. SPA — route _authenticated/$storeId/inventory/index.tsx on ResourceTable, opening on every location with a Location column and the location switcher as a filter; nav entry first in the Inventory group with the parent path moved from /transfers to /inventory, locales in all six files. A list spec asserting the row count of SELECT statements does not grow with the page size (no N+1 guard runs in this repo yet — assert it in the spec).
  7. E2E — one Playwright spec: seed a reservation and an in-transit transfer, open /inventory, assert the Reserved and Incoming cells.

Out of scope for this phase, recorded above: an Unavailable bucket; the seller-panel page.

Constraints on Current Work

  • Don't call StockTransfer.transfer or .receive. Both are gone. Moving stock between warehouses is Spree::StockTransfers::Create → MarkInTransit → Receive; receiving from a supplier is a Spree::PurchaseOrder.
  • Don't transition a transfer or a purchase order by writing status. update(status: …) passes the inclusion validation and writes no stock movement, which silently desynchronizes the ledger from the shelf. Call the workflow.
  • Don't reach Spree::StockTransfer unscoped. It carries store_id now, so current_store.stock_transfers is the lookup — including for the incidental resolution of a 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.
  • Never write reserved_count or incoming_count outside their named writers (the table under StockLevel counters). A workflow that changes a reservation, a purchase order or a transfer and does not adjust the counter in the same transaction has desynchronized the page from the ledger; spree:stock:recount_levels repairs it, but the writer is the bug.
  • Never sum reserved or incoming at request time on a list. Read the columns. The Quantifier may keep computing reserved for a single variant's availability check; a list reads counters.
  • Never present rejected delivery units as unavailable stock. They are on the receipt, not on the shelf.
  • 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.

Open Questions

  1. Historical "external receive" transfers — keep or hard-delete after migration? Settled 2026-09-07: soft-delete plus a purge task — see Implementation decisions.
  2. Suppliers shared across stores? Settled 2026-09-07: per store. Promotion path recorded in Implementation decisions if a multi-storefront merchant ever asks.
  3. Average / weighted-average cost on Variant? Partly settled 2026-09-07. The feature itself is still a separate plan — Variant#average_cost, and what returns, write-offs and foreign-currency receives do to it, are not scoped here. What this plan now ships is the ledger it will read: every received movement carries the unit_cost the units landed at.
  4. Pickup transfers (ship-to-store). 6.0-fulfillment-and-delivery.md mentions pickup_stock_policy: 'any' as enabling ship-to-store. The natural implementation is auto-creating a StockTransfer when a pickup order's items aren't local at the chosen pickup location. Reviewed 2026-09-07 and deliberately left open: the mechanism is straightforward, but it hangs on a storefront promise ("ready in 3 days" instead of "ready in 2 hours") that belongs to the fulfillment plan, and nothing in the 6.0 transfer lifecycle either enables or forbids it. Unblocked by: a decision on what the pickup date range says when stock has to travel.
  5. Server-side enforcement of lot_tracked — should the fulfill workflow refuse (not just prompt) when a flagged variant ships without lot rows? Advisory in v1 (dashboard requires, server accepts); revisit if merchants report gaps. The library-tier questions (expired lots, flag flips over existing stock) moved to the Enterprise plan.

References

  • 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/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)
  • Phase 7 touch points: spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb, …/serializers/…/admin/stock_level_serializer.rb, spree/core/app/models/concerns/spree/receivable_item.rb, spree/core/app/services/spree/stock_reservations/{reserve,release}.rb, spree/core/app/jobs/spree/stock_reservations/expire_job.rb, spree/core/app/workflows/spree/stock_receipts/recording.rb