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.

51.4 KB
Raw Blame

Typed Stock Movements

Status: Implemented for 6.0 — Phases 0–4 (2026-08-19); Phase 5 is 6.1 cleanup Target: Spree 6.0 (polymorphic originator dropped in 6.1) Depends on: Fulfillment & Delivery (6.0-fulfillment-and-delivery.md), Cart/Order Split (6.0-cart-order-split.md), Returns/Exchanges/Claims (6.0-returns-exchanges-claims.md), Stock Reservations (6.0-stock-reservations.md), Store-Scoped Configuration (6.0-store-scoped-configuration.md) Author: Damian + Claude Last updated: 2026-08-19

Scope note (2026-08-13): this plan now owns the Spree::StockItem → Spree::StockLevel rename (decisions.md 2026-03-17), which had no owning plan. It ships as Phase 0, ahead of the new columns, so they are born beside a final name instead of needing a second pass. Everything from Phase 0 onward reads StockLevel / stock_level_id / spree_stock_levels; the Current State table and the data migration's legacy references keep today's names.

Vocabulary note (2026-08-13, replaces the 2026-07-27 note): every cause this plan names has since shipped under its final name, so the new columns are born correct — fulfillment_id (never shipment_id), return_id and exchange_id (never return_authorization_id: the legacy returns chain is gone, see 6.0-returns-exchanges-claims.md), plus order_id and stock_transfer_id. 6.0-inventory-operations.md adds purchase_order_id on top of the same set. The data migration still reads the legacy originator_type strings, including 'Spree::Shipment' for installs whose rows were never rewritten by spree:migrate_shipping_to_delivery.

Summary

Replace the generic Spree::StockMovement (quantity + polymorphic originator) with typed movement records that explicitly describe what happened to stock and why. Each type has concrete FKs to its cause — no polymorphic originator.

This gives merchants a full audit trail ("10 units allocated to order or_abc, 3 units shipped in ful_xyz, 2 units returned via ret_456") instead of today's opaque list of positive and negative numbers.

It also separates two quantities that Spree currently conflates: how much stock is physically on the shelf, and how much of it is already promised to placed orders. Today the shelf count drops the moment an order is placed, so a warehouse's on-hand number never matches what a picker can count. After this plan, on-hand means on-hand and allocated_count carries the promise — the model every other commerce platform uses.

Problem

1. No semantic meaning

Today's StockMovement is just { quantity: -3, originator_type: 'Spree::Fulfillment', originator_id: 42 }. You can't answer "how many units are promised to placed orders?" or "how many units were returned this month?" without parsing originator types and guessing the business meaning of positive versus negative quantities.

2. Polymorphic originator

belongs_to :originator, polymorphic: true — the same problem as the polymorphic Adjustment that 6.0-6.1-split-adjustments.md removed. It can't be eager loaded or joined cleanly, and it can't be filtered on in the API without leaking class names. In practice the originator is a Fulfillment, a StockTransfer, a legacy ReturnAuthorization, or nothing at all.

3. No allocation tracking

When an order is placed, stock should be allocated — promised to that order — before it is shipped. Today placement calls Fulfillment#finalize!, which decrements count_on_hand immediately, so:

  • On-hand understates the shelf for as long as orders sit unfulfilled. A picker counting 40 shirts sees 33 in Spree.
  • Shipping writes nothing at all. The one event a warehouse cares about leaves no trace in the stock ledger.
  • Oversell is encoded as a negative count_on_hand, which is why restock_backordered exists: an escape hatch that writes stock with update_columns and deliberately skips the movement log to avoid inventing units.

4. Several writers, no audit

count_on_hand is written by movements, by restock_backordered, by StockItem#adjust_count_on_hand called directly (variant stock forms, the admin API's PATCH /stock_items), and by update_all when a variant stops tracking inventory. Only the first leaves a record. A merchant asking "why is this 47?" cannot be answered from the data.

Current State

What How it works today (6.0-dev)
StockMovement quantity + action (unused) + polymorphic originator + stock_item_id. after_create calls stock_item.adjust_count_on_hand. Read-only once persisted.
Order placed Orders::Complete#finalize_fulfillments → Fulfillment#finalize! → after_resume (a deprecated shell) → manifest_unstock → count_on_hand drops here
Fulfillment shipped Fulfillments::Fulfill writes no movement — stock already left at placement
Fulfillment canceled Fulfillments::Cancel#restock_units — restock for on-hand units, restock_backordered (no movement) for backordered ones
Fulfillment resumed Fulfillments::Resume unstocks again
Fulfillment split / relocated Fulfillments::Create and FulfillmentChanger restock at the old location and unstock at the new one
Line item changed after placement OrderInventory#add_to_shipment / #remove_from_shipment unstock and restock
Return / exchange received Returns::Receive and Exchanges::Receive call stock_location.restock(variant, quantity, record) — the originator is a Spree::Return or Spree::Exchange
Stock transfer StockTransfer#transfer unstocks the source and restocks the destination in one transaction, both rows pointing at the transfer
Manual correction StockItem#adjust_count_on_hand / set_stock / update_all — no movement record
allocated_count / available_count Already exist on StockItem as shims (allocated_count returns 0), and Stock::Quantifier already subtracts them behind a column_exists? check. Shipped with Stock Reservations in 5.5 precisely so this plan only has to add the column.
Admin API stock_items and stock_transfers endpoints exist. There is no stock_movements endpoint — only a serializer, which still exposes originator_type/originator_id.
Naming Spree::StockItem on spree_stock_items, prefix si_, referenced as stock_item_id by spree_stock_movements and spree_stock_reservations, and as stock_items by Variant, StockLocation and Store. Roughly 250 references in gem code, 750 in specs, plus the SDK type, four dashboard hooks and components, and the stock_item.* webhook events.

Key Decisions (do not deviate without discussion)

  • Single table with a kind column (not a table per type). Movements are all the same shape — stock level, quantity, timestamp, reason — so five tables would add joins without adding meaning. kind is an indexed string, never an STI or polymorphic type column.
  • Concrete FKs replace the polymorphic originator: order_id, fulfillment_id, return_id, exchange_id, stock_transfer_id (purchase_order_id arrives with 6.0-inventory-operations.md).
  • The FKs describe the cause, and a cause can be more than one row deep. A fulfillment-driven movement carries both fulfillment_id and order_id, because "which order was this for?" is the question merchants ask and a join through fulfillments to answer it is wasteful. What is forbidden is two unrelated causes on one row.
  • Five kinds:
    • received — stock arrived (purchase order, transfer receipt, return or exchange restock)
    • allocated — stock promised to a placed order
    • shipped — promised stock physically left
    • released — a promise was withdrawn (fulfillment canceled, relocated, line item removed)
    • adjusted — a manual correction (inventory count, shrinkage, damage)
  • Physical stock stops moving at order placement. This is the headline behavior change. Placement writes an allocated movement, which raises allocated_count and leaves count_on_hand untouched. Dispatch writes a shipped movement, and that is the row that decrements count_on_hand — retiring the allocation on the same pass. On-hand becomes what a picker can count, which is what the number has always claimed to mean.
  • Allocation is keyed to fulfillments, not to line items. A fulfillment already knows its origin location and its unit split, so allocating per fulfillment reuses the allocation the Coordinator already made instead of re-deciding it per line item. Every allocation therefore carries a fulfillment_id, and releasing is a fulfillment-level act.
  • Shipping only ever converts an allocation. Fulfillments::Fulfill writes shipped for the quantity actually allocated to that fulfillment. Units with no allocation ship without a movement — which is exactly the state of every fulfillment created before the upgrade, so the transition needs no flag column and no deploy-window choreography.
  • Oversell becomes allocated_count > count_on_hand, not a negative count_on_hand. The signed arithmetic is identical (count_on_hand - allocated_count is the same number as today's negative on-hand), so backorder_limit and pre-order caps keep working unchanged. restock_backordered and StockMovement#min_quantity both exist only to service the negative-on-hand representation and are deleted with it. On-hand can still go below zero, but only through a forced dispatch, and it then means something different and much narrower — goods left that were never recorded as arriving (see "Shipping from an empty shelf").
  • Movements are the only writer of count_on_hand. adjust_count_on_hand becomes internal to the movement callback; every other caller writes an adjusted movement instead. That is what makes the audit trail complete rather than merely detailed.
  • adjusted requires a reason, and the admin API supplies a default. PATCH /stock_levels keeps accepting a bare count_on_hand, permits an optional reason, and falls back to a translated "Manual adjustment" — an audit requirement must not turn an existing endpoint into a 422.
  • Movements stay immutable. readonly? after persist. Reversing a movement means writing its counterpart, never editing history.
  • count_on_hand semantics after this plan:
    • count_on_hand — physical units at the location, changed only by received, shipped and adjusted
    • allocated_count — denormalized column on StockLevel, changed by allocated, released and shipped
    • available_count — count_on_hand - allocated_count, and purchasable availability is that minus active reservations
  • StockLevel#allocated_count is a real column, so the 5.5 shim disappears by itself. The Rails attribute takes precedence over the method; the Quantifier.allocated_count_column? schema check is deleted at the same time rather than left as a permanent branch.
  • Keep StockLocation.restock / unstock as the physical-stock verbs, and add allocate / release / adjust beside them. Extensions call these, not StockMovement.create!.
  • StockItem becomes StockLevel first, in its own phase. The rename is mechanical and the typed-movement work is not, so they ship as separate reviewable commits — but in this order, because the alternative is adding five FKs and a counter to a table that is about to be renamed and then renaming them all again. "Level" is also the word the concept needs once allocated_count exists: a row that carries on-hand, allocated and reserved quantities is a level, not an item.
  • The rename carries one-release bridges, and the prefix does not. Spree::StockItem stays as a constant alias and the old association and column names stay as aliases (variant.stock_items, movement.stock_item_id), all removed in 6.1 — the pattern Spree::Shipment and Spree::Taxon already follow. The prefixed ID moves si_ → sl_ with no bridge, because prefixed IDs are computed from the primary key rather than stored and decode_own_prefixed_id deliberately rejects a foreign prefix; every other 6.0 rename took the same break. The stock_item.* webhook events are dual-emitted for one release, since those are configured in a merchant's account and breaking them silently is worse than a duplicate delivery.

Design Details

StockMovement model

class Spree::StockMovement < Spree.base_class
  has_prefix_id :sm

  KINDS = %w[received allocated shipped released adjusted].freeze

  include Spree::StockMovement::CustomEvents

  publishes_lifecycle_events

  belongs_to :stock_level, class_name: 'Spree::StockLevel', inverse_of: :stock_movements

  # The cause. A fulfillment-driven row carries its order too.
  belongs_to :order, class_name: 'Spree::Order', optional: true
  belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true
  belongs_to :return, class_name: 'Spree::Return', optional: true
  belongs_to :exchange, class_name: 'Spree::Exchange', optional: true
  belongs_to :stock_transfer, class_name: 'Spree::StockTransfer', optional: true

  validates :stock_level, :quantity, :kind, presence: true
  validates :kind, inclusion: { in: KINDS }
  validates :quantity, numericality: { other_than: 0, only_integer: true }
  validates :reason, presence: true, if: :adjusted?

  after_create :apply_to_stock_level

  scope :recent, -> { order(created_at: :desc) }
  KINDS.each { |kind| scope kind, -> { where(kind: kind) } }

  delegate :variant, :variant_id, to: :stock_level, allow_nil: true

  def readonly?
    persisted?
  end

  private

  # The single place count_on_hand and allocated_count change. A correction
  # applies even to a variant that stopped tracking inventory — that is how
  # turning tracking off writes its stock away.
  def apply_to_stock_level
    return unless adjusted? || stock_level.should_track_inventory?

    case kind
    when 'received', 'adjusted' then stock_level.adjust_count_on_hand(quantity)
    when 'allocated'            then stock_level.adjust_allocated_count(quantity.abs)
    when 'released'             then stock_level.release_allocated_count(quantity.abs)
    when 'shipped'              then apply_departure
    end
  end

  # A forced dispatch is the only write allowed below zero, and retiring the
  # promise keys off the cause: only a dispatch has one to retire.
  def apply_departure
    stock_level.adjust_count_on_hand(-quantity.abs, force: force.present?)
    stock_level.release_allocated_count(quantity.abs) if fulfillment_id.present?
  end
end

quantity keeps its signed meaning for received and adjusted (positive adds, negative removes). For the three order-driven kinds the sign carries no information — the kind already says which direction stock moves — so they are written positive and read through abs.

The min_quantity validation goes away. It exists to stop a movement from driving a non-backorderable item negative, a check that belongs at allocation time against available_count (where Stock::Quantifier and StockReservations::Reserve already do it) rather than at ship time, when the units have physically gone whatever the ledger says.

Shipping from an empty shelf. Three ways a dispatch can meet count_on_hand: 0, and they resolve differently. A backordered unit is stopped before any of this by Fulfillments::Fulfill#ensure_ready_to_hand_over, which already refuses backordered items and stays as it is; the unit ships once a received movement arrives and process_backorders fills the backorder. A shelf that really does hold the goods is a ledger error, fixed with an adjusted movement and then shipped normally. And a genuinely forced dispatch — force: true, which is the only route: a validate hook can only reject!, never wave ensure_ready_to_hand_over through — writes shipped and takes count_on_hand to −1, because a parcel that physically left must be recordable whatever the ledger says (6.0-fulfillment-and-delivery.md, the same rule that lets a carrier outage not block a dispatch).

A negative count_on_hand therefore stops meaning "oversold" — that is allocated_count > count_on_hand now — and comes to mean something narrower: goods left that Spree never saw arrive. A receiving gap, visible as a number, and self-healing the moment the missing received movement lands. Availability is unaffected on the way through: on-hand 0 / allocated 1 / available −1 becomes on-hand −1 / allocated 0 / available −1, because the promise had already been subtracted and only the shelf changed.

The non-negative guard keys off the write, not off the variant (decided 2026-08-17, and an addition to what this plan originally asked for). verify_count_on_hand? exempts a backorderable or pre-order level from the check today, because a negative shelf was how an oversell was written down and those are the levels allowed to oversell. This plan deletes that representation, so the exemption loses its only purpose and both clauses come out. What replaces them is force (revised from the shipped kind on the same date): the kind alone would hand the same freedom to a stock transfer, which moves goods nobody promised and cannot send what the warehouse does not have — and did, until the transfer's own precondition was tightened to compare against the quantity being moved rather than merely against zero. received cannot go negative by construction, and adjusted keeps the guard — a hand-typed count landing below zero is a typo, not a fact.

Dropping the exemptions is a behaviour change in its own right, so it is recorded rather than folded in silently: Variant#set_stock(-5) and PATCH /stock_levels with a negative count against a backorderable level used to persist, and now raise. No gem code writes a negative count any more except a forced dispatch, so what this reaches is host-app scripts and hand edits, and what they lose is the ability to record a number no warehouse can hold. The specs asserting the old permission — the backorderable and pre-order arms of stock_item_spec.rb's count_on_hand matrix — were inverted on purpose.

force reaches the write as a transient attribute on the movement, threaded Fulfill(force:) → StockLocation#unstock(force:) → move(force:), never persisted — the shape Fulfillment#notify_customer already uses for an instruction about one dispatch. And because a merchant needs to be told rather than 500'd, Fulfillments::Fulfill refuses a dispatch the shelf cannot cover before writing anything, with a message saying to correct the count or force it. Note the ordering that makes this work: a canceled fulfillment re-allocates on its way out, so the check reads its manifest rather than the nothing it currently holds.

StockLevel

allocated_count becomes a real column, so the 5.5 shim and its comment are deleted.

The two counters are written differently, on purpose. count_on_hand keeps its locked read-modify-write (adjust_count_on_hand → set_count_on_hand) because process_backorders needs the delta and the numericality validation has to see the new value. allocated_count has neither, so it takes the atomic counter path the draft already used — increment! / decrement! compile to a single SET allocated_count = allocated_count + n, which is exactly right when two fulfillments allocate the same level concurrently and neither should read the other's value first:

def adjust_allocated_count(value)
  value.negative? ? decrement!(:allocated_count, value.abs) : increment!(:allocated_count, value)
end

def in_stock?
  available_count.positive?
end

available? needs no edit of its own: it is already in_stock? || backorderable?, so it inherits the new meaning through in_stock?, and so does every caller of it — including StockReservations::Reserve#select_stock_item. The 2026-07-27 draft rewrote it as available_count > 0 || backorderable?, which is the same predicate written out longhand.

available_count (already present) stays count_on_hand - allocated_count. in_stock? moves onto it — that is the whole point of the column, and leaving it on count_on_hand would keep offering units already promised to somebody else.

Stock::Quantifier

The canonical availability reader, and the one place the full formula lives:

purchasable = count_on_hand - allocated_count - active reservations

Where count_on_hand is physical units at the location, allocated_count is units promised to placed orders, and reservations are checkout holds from 6.0-stock-reservations.md. total_on_hand clamps the result at zero; can_supply? is the one caller allowed past zero, because that is where backorder_limit decides how far an oversell may go.

Almost nothing to do here. available_stock already sums count_on_hand - allocated_count and reserved_quantity already reads the store preference — the whole shape shipped with Stock Reservations in 5.5, deliberately, so that this plan only supplies the column. The single edit is deleting the self.class.allocated_count_column? branch and the memoized schema check behind it, which exists only to tolerate a schema without allocated_count. Left in place it would be a permanent column_exists? call guarding a condition that can no longer be false.

Readers that must subtract allocations

Availability is asked in more places than the Quantifier, and every raw count_on_hand read becomes wrong the moment allocation exists. Each of these bypasses the Quantifier for a reason — a SQL scope, a bulk pluck, a locked read — so none of them inherit the fix. The full inventory:

Reader Change
StockLevel#in_stock? available_count.positive?
Variant.in_stock scope, ProductScopes.in_stock_or_backorderable_condition compare count_on_hand - allocated_count
Product#total_on_hand (unloaded branch) sum the difference, matching Quantifier#available_stock
Order#backordered_variants count_on_hand - allocated_count <= 0
StockLocation#fill_status split on-hand versus backordered against available_count
StockReservations::Reserve available_count - held_by_others - this_order_used
OrderRouting::Rules::MinimizeSplits pluck both columns and compare the difference
StockTransfer#variants_available_in_source_location? require available_count > 0
FulfillmentChanger read available_count at the desired location
Stock::Quantifier drop the allocated_count_column? branch; the column is always there

Writers: today's call site to tomorrow's kind

The call sites do not move. What changes is the kind of movement each one writes, and whether it touches physical stock at all.

Today Becomes Why
Orders::Complete#finalize_fulfillments → Fulfillment#finalize! → manifest_unstock allocated (order_id + fulfillment_id) Placement promises stock; it does not move it. finalize! stops touching stock and stops calling the deprecated after_resume; allocation becomes a step in Orders::Complete.
Fulfillments::Fulfill (writes nothing) shipped for the allocated quantity The shelf empties when the parcel leaves.
Fulfillments::Cancel#restock_units (restock + restock_backordered) released Nothing physical comes back, so nothing is invented and the backordered special case disappears.
Fulfillments::Resume (unstock) allocated Reinstating a fulfillment re-promises its units.
Fulfill#unstock_if_resuming_from_canceled allocated then shipped The release is undone and the units leave, in that order, so the ledger reads as what happened.
Fulfillments::Create split (restock + unstock, cross-location only) released at the source, allocated at the target — including a same-location split Re-pointing a promise between warehouses moves no goods. And because allocation is keyed to the fulfillment, a split has to carry its allocation across even when the location doesn't change: allocated_count would stay correct either way, but the quantity Fulfillments::Fulfill reads to decide what shipped would sit on the wrong fulfillment.
FulfillmentChanger released + allocated Same reason.
OrderInventory#add_to_shipment / #remove_from_shipment (the order.completed? branches) allocated / released Editing a placed order changes what is promised.
Returns::Receive#restock_resellable_items received + return_id Goods arrive at the dock.
Exchanges::Receive#restock_resellable_items received + exchange_id Same.
StockTransfer#transfer shipped (source) + received (destination), both with stock_transfer_id Real movement in both directions. Splitting the two events across the trip lands with 6.0-inventory-operations.md.
StockLevel#adjust_count_on_hand / Variant#set_stock called directly, PATCH /stock_levels adjusted with a reason The correction becomes visible instead of silent.
Variant#handle_track_inventory_change's update_all(count_on_hand: 0) adjusted per stock item Turning inventory tracking off is a stock decision and belongs in the log.

Stock through one order's life

The table above is keyed by call site; this is the same thing in the order it happens, for the ordinary path:

  1. Cart mutations (Carts::AddItem, SetQuantity, RemoveLineItem, Carts::Update) — reservations created or refreshed with a TTL, backorderable and pre-order variants skipped. No movement, no counter change.
  2. Delivery step or address change (Checkout::Advance → rebuild_fulfillments!) — fulfillments proposed per origin, each unit labelled on-hand or backordered against available_count. No stock write.
  3. Cart abandoned — reservations lapse on their TTL and get swept. Nothing else.
  4. Placement (Orders::Complete#finalize_fulfillments, inside the placement lock) — allocated per fulfillment. allocated_count up, count_on_hand untouched. Draft orders enter here directly, which is why the write lives in this workflow and not in Carts::Complete.
  5. Same request, just outside that lock (Orders::Complete#release_stock_reservations) — reservations deleted. The brief overlap where a unit is both reserved and allocated understates availability, never overstates it.
  6. Label bought (Fulfillments::PurchaseLabel) — no stock effect.
  7. Dispatch (Fulfillments::Fulfill) — shipped for the allocated quantity. count_on_hand down, allocated_count down.
  8. Delivered, tracking updates (MarkDelivered, UpdateTracking) — no stock effect.

Everything between step 4 and step 7 changes the promise, not the shelf. The branches off this path — cancel, resume, split, relocate, post-placement edits, returns, exchanges, transfers, manual corrections — are the remaining rows of the writers table.

StockLocation

The five verbs are the public surface — extensions call these, never StockMovement.create!. Each one names a kind and hands the cause to one resolver:

# Physical arrival and departure keep their names and their callers.
def restock(variant, quantity, cause = nil, persist: true)
  move(variant, quantity, kind: 'received', cause: cause, persist: persist)
end

# `force` is an instruction about this one write, threaded from
# Fulfillments::Fulfill and never persisted on the row.
def unstock(variant, quantity, cause = nil, persist: true, force: false)
  move(variant, quantity, kind: 'shipped', cause: cause, persist: persist, force: force)
end

# Promises against placed orders. The cause is the fulfillment, never the
# order: it owns the origin location and the unit split, and the order comes
# along with it.
def allocate(variant, quantity, fulfillment)
  move(variant, quantity, kind: 'allocated', cause: fulfillment)
end

def release(variant, quantity, fulfillment)
  move(variant, quantity, kind: 'released', cause: fulfillment)
end

# Manual correction. Signed, so a negative writes stock off.
def adjust(variant, quantity, reason:)
  move(variant, quantity, kind: 'adjusted', reason: reason)
end

private

def move(variant, quantity, kind:, cause: nil, reason: nil, persist: true, force: false)
  stock_level = stock_level_or_create(variant)
  attributes = { quantity: quantity, kind: kind, reason: reason, **cause_attributes(cause) }

  if persist
    stock_level.stock_movements.create!(attributes)
  else
    # StockTransfer builds its movements before it is saved, so they ride
    # along on its own association rather than being created here.
    cause.stock_movements << stock_level.stock_movements.build(attributes)
  end
end

# One cause in, the FKs it implies out. A fulfillment brings its order with
# it because "which order was this for?" must not cost a join.
def cause_attributes(cause)
  case cause
  when Spree::Fulfillment   then { fulfillment: cause, order: cause.order }
  when Spree::Return        then { return: cause, order: cause.order }
  when Spree::Exchange      then { exchange: cause, order: cause.order }
  when Spree::StockTransfer then { stock_transfer: cause }
  when Spree::Order         then { order: cause }
  else {}
  end
end

cause_attributes dispatches on class (when Spree::Fulfillment is is_a?, spelled the idiomatic way), which is deliberate rather than a fallback. The cause set is closed and core-owned — 6.0-inventory-operations.md adds its purchase_order_id entry in core, and provider gems never introduce causes — so one method that shows the whole mapping beats a stock_movement_attributes method on each of five models that would each have to know movement column names. Spree::Cart is a sibling of Spree::Order rather than a subclass, so the Spree::Order branch cannot match a cart; if extensions ever need to register their own causes, that is the point to switch to double dispatch.

Two things the bodies make visible that the signatures hid. unstock stops negating the quantity — today it calls move(variant, -quantity), because the sign was the only thing distinguishing a departure from an arrival; now kind says it and the three order-driven kinds are written positive. And cause resolution lives in exactly one method, so adding purchase_order_id for 6.0-inventory-operations.md is one when clause rather than a hunt through five verbs.

restock_backordered is deleted. The persist: false path stays, now building against a real FK instead of the polymorphic pair, but it is carried rather than endorsed: its only caller is StockTransfer#transfer, which must attach both movements to an unsaved transfer because stock_movements_not_empty validates their presence before the row exists. 6.0-inventory-operations.md retires that caller — with first-class transfer items, movements are written at mark_in_transit and receive, after the transfer exists — so the flag and the validation behind it both go with it. Don't add new callers.

Events

StockMovement::CustomEvents publishes product.out_of_stock and product.back_in_stock around save, reading Product#any_variant_in_stock_or_backorderable?. Once the in-stock scopes subtract allocations (above), those events fire when the last purchasable unit goes — at allocation — rather than weeks later when the parcel ships. That is the useful moment for a back-in-stock list, and it needs no change here beyond the scopes.

Admin API

The endpoint does not exist yet and this plan adds it, read-only:

GET /api/v3/admin/stock_movements?q[stock_level_variant_id_eq]=variant_xxx
GET /api/v3/admin/stock_movements?q[kind_eq]=allocated&q[order_id_eq]=…

It rides the existing :stock permission resource (Spree::StockMovement is already listed there), so RBAC needs no new catalog entry. The concrete FKs go on whitelisted_ransackable_attributes — the reason 6.0-inventory-operations.md can filter by purchase_order_id for free once it adds the column.

Response:

{
  "id": "sm_k5nR8xLq",
  "kind": "allocated",
  "quantity": 3,
  "reason": null,
  "stock_level_id": "sl_xyz",
  "order_id": "or_abc",
  "fulfillment_id": "ful_xyz",
  "return_id": null,
  "exchange_id": null,
  "stock_transfer_id": null,
  "created_at": "2026-08-13T14:30:00Z"
}

originator_type and originator_id leave the serializer, and with them Spree::Base.polymorphic_api_type for this resource. kind is nullable in the response for the lifetime of 6.0, because a legacy row on an install that has not run the data task has no kind yet.

StockLevelSerializer (renamed from StockItemSerializer in Phase 0) keeps allocated_count and available_count unchanged — they already ship, they simply start returning real numbers.

Migration Path

Phase order follows the repo convention: schema first, then behavior, then the data transformation, and every destructive drop waits for 6.1. The data task reads originator_type/originator_id, so dropping those columns before it runs would leave installs with no way to type their history — that is why the drop is last rather than second.

Phase 0: StockItem → StockLevel ✅ shipped

A pure rename, shipped on its own so the review is a diff of names rather than a diff of names tangled with new stock semantics. No data is transformed, so there is no rake task and nothing for the manifest.

class RenameStockItemsToStockLevels < ActiveRecord::Migration[8.1]
  def change
    rename_table :spree_stock_items, :spree_stock_levels
    rename_column :spree_stock_movements, :stock_item_id, :stock_level_id
    rename_column :spree_stock_reservations, :stock_item_id, :stock_level_id
    # …plus the four index names that spell out stock_item
  end
end

Ruby side:

  • Spree::StockLevel with has_prefix_id :sl. Spree::StockItem = Spree::StockLevel survives as a deprecated constant alias in its own file, the same shape spree/core/app/models/spree/shipment.rb already uses for Spree::Shipment = Fulfillment, with a comment naming 6.1 as its removal. Phase 5 deletes it.
  • Associations renamed with deprecated aliases for one release: Variant#stock_levels, StockLocation#stock_levels, Store#stock_levels, StockMovement#stock_level, StockReservation#stock_level, plus StockLocation#stock_level_or_create and #set_up_stock_level.
  • The service and job namespace becomes Spree::StockLocations::StockLevels, and the old one survives as deprecated shims the way Spree::Taxons::AddProducts and Spree::Products::TouchTaxonsJob already do: the service warns and delegates, the job subclasses the renamed job so a job enqueued under the old class name before the deploy still deserializes and runs (added 2026-08-17 — the first pass dropped these, which would have failed those in-flight jobs).
  • alias_attribute :stock_item_id, :stock_level_id on movements and reservations, so an integration still writing the old key keeps working through 6.0.
  • Spree::StockLevel::CustomEvents wraps publish_event so the three lifecycle events dual-emit under both names, exactly as Fulfillment::CustomEvents already dual-emits shipment.* (decision revised 2026-08-17). The earlier draft put a legacy_event_prefix: option on publishes_lifecycle_events; that is generic machinery on a concern every Spree model includes, bought for a single rename, so it was reverted. The twins do not live in the Spree::StockItem alias file either, tempting as that is for keeping the bridges together: app/ is autoloaded lazily, so with eager_load = false the file would go untouched and the legacy events would fire in production and silently not in development. Wrapping publish_event rather than the three callbacks keeps Publishable's touch-only guard authoritative — the legacy twin follows whatever the real name did.
  • The Ransack allowlists, the :stock permission subject list, the factory (:stock_level, with :stock_item kept as an alias for external specs), and the activerecord.models and admin-label i18n keys.

API and TypeScript side:

  • /api/v3/admin/stock_items becomes /stock_levels, with StockLevelSerializer and Admin::StockLevelSerializer; the stock_item_serializer / admin_stock_item_serializer registry keys stay settable for one release through the same legacy-key map that already bridges order_complete_service.
  • No legacy route alias. The v3 API is still Developer Preview and the taxons → categories rename took the same clean break.
  • @spree/admin-sdk: StockItem → StockLevel, client.stockItems → client.stockLevels, with a changeset calling the break out. Then the dashboard's use-stock-items hook, the stock-coverage hook, the inventory and variants sections, the stock-locations route and the inventory e2e spec.
  • The 5.6 → 6.0 upgrade guide gains a rename section covering the class, the endpoint, the SDK resource, the prefix change and the dual-emitted events, and every bridge goes into its "Deprecated in 6.0, removed in 6.1" list so nobody has to read this plan to find out what disappears next release.

Phase 1: Schema (additive) ✅ shipped

class AddTypedStockMovements < ActiveRecord::Migration[8.1]
  def change
    change_table :spree_stock_movements, bulk: true do |t|
      t.string :kind
      t.string :reason
      t.references :order
      t.references :fulfillment
      t.references :return
      t.references :exchange
      t.references :stock_transfer
    end

    add_index :spree_stock_movements, :kind

    add_column :spree_stock_levels, :allocated_count, :integer, null: false, default: 0
  end
end

kind is nullable here and gains its NOT NULL in 6.1, once the data task has had a release to run — the same pattern as the store-ownership columns added earlier in 6.0. The model validates its presence regardless, so every row written by 6.0 code is typed.

Phase 2: Model and call sites ✅ shipped

The behavior change, shipped as one unit because a half-converted call site double-counts stock:

  • Rewrite StockMovement — kind, the concrete FKs, the kind-based stock-level callback; delete min_quantity, and move the movement factory and the Ransack allowlist off action onto kind.
  • Add allocated_count handling to StockLevel, delete the 5.5 shim, move in_stock? onto available_count.
  • Add StockLocation#allocate / #release / #adjust; delete restock_backordered.
  • Convert every writer in the call-site table, and every reader in the readers table.
  • Point StockTransfer at stock_transfer_id instead of as: :originator, and update the nested-attribute allowlist in Spree::PermittedAttributes.
  • Route the admin PATCH /stock_levels count edit and Variant#set_stock through adjusted movements.
  • Drop Quantifier.allocated_count_column?.

Phase 3: Data migration (spree:migrate_stock_movements_to_typed_rows) ✅ shipped

Two jobs in one idempotent task, added to the 5.6 → 6.0 manifest.

Type the history. Every legacy row gets a kind and an FK from its originator:

Legacy row Becomes
Spree::Fulfillment (or Spree::Shipment) originator, negative quantity, fulfillment closed shipped, fulfillment_id + the fulfillment's order_id
Spree::Fulfillment (or Spree::Shipment) originator, negative quantity, fulfillment still open allocated, same FKs — and the counters move with it (see below)
Spree::Fulfillment originator, positive quantity released, same FKs (a cancellation or relocation restock)
Spree::ReturnAuthorization originator received, return_id or exchange_id
Spree::StockTransfer originator, positive quantity received, stock_transfer_id
Spree::StockTransfer originator, negative quantity shipped, stock_transfer_id
No originator adjusted, reason "Legacy manual adjustment"

Ordering is load-bearing in two directions. The task runs after migrate_shipping_to_delivery, which rewrites 'Spree::Shipment' originator strings, and after migrate_returns, because a legacy ReturnAuthorization id says nothing about the new record: the returns migrator preserves the number, not the id, and can turn one authorization into either a Return or an Exchange. Resolving return_id/exchange_id therefore means reading the legacy authorization table by name (the same anonymous-reader pattern Spree::ReturnsMigrator uses) and matching on number. Rows whose cause cannot be resolved are typed by sign and left with null FKs rather than skipped — a movement with no cause is still a true statement about stock.

Whether a fulfillment had shipped decides how its history reads (2026-08-19, after Damian's review of the implementation). A closed fulfillment's departure was a departure. An open one's departure was the promise it still holds — under the old model, taking the units off the shelf at placement was the allocation — so it types as allocated. Typing it shipped instead is not a cosmetic mislabel: allocated_quantities subtracts shipped from allocated, so the reconciliation below would net to zero for every open fulfillment, leaving it reporting no promise at all. The consequences are permanent and silent in both directions — dispatch never takes the units off the shelf, and cancelling never returns them to availability, stranding real stock at zero.

Because the typing is a update_all relabel that skips callbacks, an open fulfillment's row carries the counters itself: count_on_hand and allocated_count each move by the row's negated legacy quantity, applied as database-side increments. Both counters moving together is what leaves availability unchanged, and doing it per row rather than per fulfillment is what makes a partially restocked fulfillment come out right — legacy rows conserve unstock − restock = held quantity, so the sum lands on the quantity still held.

Reconcile open fulfillments. That leaves reconciliation holding only the open fulfillments that recorded no movement at all: for each it adds the quantity back to count_on_hand, adds the same to allocated_count, and writes the matching allocated movement so the jump has a visible cause. Availability is unchanged by construction here too, and the write is deliberately a direct column update rather than a received movement, because no goods arrived. Fulfillments whose rows were typed above already hold an allocation, so the existing idempotency predicate skips them.

Backordered units need no special case: the pair of increments cancels out the negative on-hand that used to represent them, which is precisely the representation change this plan makes.

Idempotency comes from the data itself. Typing skips rows that already have a kind; reconciliation skips fulfillments that already have an allocated movement. That same predicate is what makes the deploy window safe: a fulfillment shipped before the task runs never gets an allocation, and Fulfillments::Fulfill writes shipped only for allocated units, so its stock is not decremented twice.

Phase 4: API, serializer, dashboard ✅ shipped

  • New read-only stock_movements admin endpoint with the Ransack allowlist above; kind and the FKs on the serializer, originator_* off it.
  • reason permitted on PATCH /stock_levels.
  • The variant and stock-location history panels that 6.0-inventory-operations.md specifies consume this endpoint. That plan owns the screens; this one owns the data and the endpoint.

Phase 5: Cleanup (6.1)

Drops the polymorphic originator and every bridge the earlier phases left standing.

The polymorphic columns:

class RemoveOriginatorFromStockMovements < ActiveRecord::Migration[8.1]
  def change
    remove_column :spree_stock_movements, :originator_type
    remove_column :spree_stock_movements, :originator_id
    remove_column :spree_stock_movements, :action

    change_column_null :spree_stock_movements, :kind, false
  end
end

Held to 6.1 for the reason every other 6.0 cleanup is: the columns are the data task's source and its rollback path. An install that upgrades to 6.0 and discovers a mis-typed row can re-derive it from the originator for a full release. action goes with them — no application code has written or read it in years, and kind is what it was reaching for.

Everything Phase 0 left standing for one release. Each of these is deprecated on arrival in 6.0 and deleted here:

Bridge Removal
Spree::StockItem = Spree::StockLevel constant alias Delete spree/core/app/models/spree/stock_item.rb. Host apps and extensions still naming the old constant break at boot, which is the point — a NameError at boot beats a silent reference to a class that no longer describes the data.
Dual-emitted stock_item.created / .updated / .deleted Delete spree/core/app/models/spree/stock_level/custom_events.rb and its include. Endpoints still subscribed to the legacy names stop receiving deliveries, so the 6.1 upgrade guide has to say so plainly and the 6.0 guide has to have said it a release earlier.
stock_items / stock_item association aliases, stock_item_or_create, set_up_stock_item Delete the aliases and their deprecation warnings.
alias_attribute :stock_item_id, :stock_level_id on movements and reservations Delete. Writes using the old key start raising instead of resolving.
stock_item_serializer / admin_stock_item_serializer registry keys Drop from the legacy-key map.
:stock_item factory alias Delete — external specs move to :stock_level.
Spree::StockLocations::StockItems::Create / ::CreateJob shims Delete both files. By 6.1 no queue can still hold a job enqueued under the old name.

Nothing generic survives this bridge: the twins are three lines in a model-owned concern, so deleting that file is the whole removal. A future rename writes its own, the way Fulfillment::CustomEvents did before it — one rename is not enough evidence to design an abstraction every Spree model carries.

Two things that are not bridges and therefore have nothing to remove here: the si_ → sl_ prefix and the /stock_items endpoint both broke cleanly in Phase 0.

Constraints on Current Work

  • Don't create StockMovement records directly. Go through StockLocation#restock / unstock (and allocate / release / adjust once they exist) so rows come out typed when this plan lands.
  • Don't write count_on_hand outside a movement. No new callers of adjust_count_on_hand, set_count_on_hand, set_stock or update_all(count_on_hand:), and no new callers of restock_backordered — it is being deleted.
  • Don't write a negative count_on_hand. A level is held at or above zero whatever the variant's backorder or pre-order settings say, and only a forced dispatch is exempt. Code that expressed an oversell as a negative shelf expresses it as allocated_count above count_on_hand instead.
  • Don't build business logic on originator_type. It is gone in 6.1. Anything that needs to know why stock moved is waiting on kind.
  • Read availability through Stock::Quantifier, StockLevel#available_count or #allocated_count — never raw count_on_hand. The shims already return correct answers today (allocated_count is 0), so code written against them keeps working unchanged when the column arrives. New raw count_on_hand reads are the main way this plan can regress. The one exception is a figure written back to the shelf — set_stock, or a file meant to be re-imported such as the products CSV — which reads the count_on_hand of the stock level it will be written back to, since subtracting allocations there removes them from the shelf (decisions.md, 2026-10-06).
  • Don't assume stock leaves at placement. Anything that reconciles on-hand against a warehouse, or reports "units removed", should key off fulfillment rather than order placement.
  • The :stock permission resource already covers StockMovement — a new stock endpoint needs no catalog entry, and must not ride settings.
  • Don't add public surface named stock_item. Phase 0 renames the class, the table, the endpoint, the SDK resource and the ID prefix, so a new endpoint, event name or SDK method carrying the old word ships already-deprecated. Internal references are fine until Phase 0 lands — that phase renames them wholesale.

Resolved Questions

  1. Allocation timing. Stock is allocated at order placement, in Orders::Complete — the one workflow both entry points converge on: checkout (Carts::Complete delegates its FINALIZE phase to it) and admin or B2B draft completion (which halts the cart pipeline immediately and hands the whole job over). Allocating in Carts::Complete itself would skip every draft order, leaving admin-placed orders with no allocation at all. The write belongs in the finalize_fulfillments step, inside the placement lock, for two reasons: fulfillments exist by then — and allocation is keyed to them — and it is exactly where the placement-time unstock lives today. The checkout reservation (6.0-stock-reservations.md) is released two steps later, just outside that lock, so a unit is briefly both reserved and allocated; the overlap understates availability for a moment, which is the safe direction to be wrong in.

  2. Allocation granularity. Per fulfillment, not per line item — the fulfillment already carries the origin location and the on-hand/backordered split, so allocating anywhere else would duplicate the Coordinator's decision.

  3. Stock transfer movements. Reuse shipped and received with a stock_transfer_id. A transfer is a departure and an arrival; no new kinds.

  4. Purchase orders. Also received, with purchase_order_id. The kind says what happened to stock, the FK says why — so a new cause never needs a new kind.

  5. Phase order. Model before data task before originator drop, per the note at the top of the migration path.

  6. Oversell representation. allocated_count above count_on_hand, replacing negative count_on_hand. Same arithmetic, so backorder_limit and pre-orders are unaffected, and the restock_backordered escape hatch is no longer needed.

  7. The StockItem → StockLevel rename rides with this plan (2026-08-13), as Phase 0, ahead of the new columns. It had sat in decisions.md since 2026-03-17 with no owner, and this is the plan that would otherwise have to add five FKs and a counter to a table due for renaming. Bridges: constant, association and column aliases plus dual-emitted events for one release; the si_ → sl_ prefix change and the endpoint rename take the break, as every other 6.0 rename did.

Open Questions

None at this time.

References

  • Current movement model: spree/core/app/models/spree/stock_movement.rb
  • Current counters and shims: spree/core/app/models/spree/stock_item.rb, spree/core/app/models/spree/stock/quantifier.rb
  • Rename mechanics: spree/core/app/models/concerns/spree/prefixed_id.rb (decode_own_prefixed_id rejects a foreign prefix), spree/core/app/models/concerns/spree/publishable.rb (event_prefix), spree/core/app/models/spree/fulfillment/custom_events.rb (the dual-emit precedent), spree/core/app/models/spree/shipment.rb (the constant-alias precedent)
  • Physical stock verbs: spree/core/app/models/spree/stock_location.rb
  • Placement-time unstock: spree/core/app/workflows/spree/orders/complete.rb, spree/core/app/models/spree/fulfillment.rb (finalize!, manifest_unstock)
  • Cancel / resume / split: spree/core/app/workflows/spree/fulfillments/{cancel,resume,create,fulfill}.rb, spree/core/app/models/spree/fulfillment_changer.rb
  • Return and exchange restock: spree/core/app/workflows/spree/{returns,exchanges}/receive.rb
  • Reservation availability: spree/core/app/services/spree/stock_reservations/reserve.rb
  • Related plan: 6.0-stock-reservations.md (the reservation term in the same availability formula)
  • Related plan: 6.0-inventory-operations.md (transfers, purchase orders, and the history screens over this data)
  • Related plan: 6.0-6.1-split-adjustments.md (same pattern: polymorphic replaced by typed rows, legacy columns dropped a release later)