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.
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::StockLevelrename (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 readsStockLevel/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(nevershipment_id),return_idandexchange_id(neverreturn_authorization_id: the legacy returns chain is gone, see6.0-returns-exchanges-claims.md), plusorder_idandstock_transfer_id.6.0-inventory-operations.mdaddspurchase_order_idon top of the same set. The data migration still reads the legacyoriginator_typestrings, including'Spree::Shipment'for installs whose rows were never rewritten byspree: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 whyrestock_backorderedexists: an escape hatch that writes stock withupdate_columnsand 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
kindcolumn (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.kindis 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_idarrives with6.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_idandorder_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 ordershipped— promised stock physically leftreleased— 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
allocatedmovement, which raisesallocated_countand leavescount_on_handuntouched. Dispatch writes ashippedmovement, and that is the row that decrementscount_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::Fulfillwritesshippedfor 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 negativecount_on_hand. The signed arithmetic is identical (count_on_hand - allocated_countis the same number as today's negative on-hand), sobackorder_limitand pre-order caps keep working unchanged.restock_backorderedandStockMovement#min_quantityboth 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_handbecomes internal to the movement callback; every other caller writes anadjustedmovement instead. That is what makes the audit trail complete rather than merely detailed. adjustedrequires a reason, and the admin API supplies a default.PATCH /stock_levelskeeps accepting a barecount_on_hand, permits an optionalreason, 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_handsemantics after this plan:count_on_hand— physical units at the location, changed only byreceived,shippedandadjustedallocated_count— denormalized column onStockLevel, changed byallocated,releasedandshippedavailable_count—count_on_hand - allocated_count, and purchasable availability is that minus active reservations
StockLevel#allocated_countis a real column, so the 5.5 shim disappears by itself. The Rails attribute takes precedence over the method; theQuantifier.allocated_count_column?schema check is deleted at the same time rather than left as a permanent branch.- Keep
StockLocation.restock/unstockas the physical-stock verbs, and addallocate/release/adjustbeside them. Extensions call these, notStockMovement.create!. StockItembecomesStockLevelfirst, 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 onceallocated_countexists: 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::StockItemstays 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 patternSpree::ShipmentandSpree::Taxonalready follow. The prefixed ID movessi_→sl_with no bridge, because prefixed IDs are computed from the primary key rather than stored anddecode_own_prefixed_iddeliberately rejects a foreign prefix; every other 6.0 rename took the same break. Thestock_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:
- 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. - Delivery step or address change (
Checkout::Advance→rebuild_fulfillments!) — fulfillments proposed per origin, each unit labelled on-hand or backordered againstavailable_count. No stock write. - Cart abandoned — reservations lapse on their TTL and get swept. Nothing else.
- Placement (
Orders::Complete#finalize_fulfillments, inside the placement lock) —allocatedper fulfillment.allocated_countup,count_on_handuntouched. Draft orders enter here directly, which is why the write lives in this workflow and not inCarts::Complete. - 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. - Label bought (
Fulfillments::PurchaseLabel) — no stock effect. - Dispatch (
Fulfillments::Fulfill) —shippedfor the allocated quantity.count_on_handdown,allocated_countdown. - 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::StockLevelwithhas_prefix_id :sl.Spree::StockItem = Spree::StockLevelsurvives as a deprecated constant alias in its own file, the same shapespree/core/app/models/spree/shipment.rbalready uses forSpree::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, plusStockLocation#stock_level_or_createand#set_up_stock_level. - The service and job namespace becomes
Spree::StockLocations::StockLevels, and the old one survives as deprecated shims the waySpree::Taxons::AddProductsandSpree::Products::TouchTaxonsJobalready 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_idon movements and reservations, so an integration still writing the old key keeps working through 6.0.Spree::StockLevel::CustomEventswrapspublish_eventso the three lifecycle events dual-emit under both names, exactly asFulfillment::CustomEventsalready dual-emitsshipment.*(decision revised 2026-08-17). The earlier draft put alegacy_event_prefix:option onpublishes_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 theSpree::StockItemalias file either, tempting as that is for keeping the bridges together:app/is autoloaded lazily, so witheager_load = falsethe file would go untouched and the legacy events would fire in production and silently not in development. Wrappingpublish_eventrather than the three callbacks keeps Publishable's touch-only guard authoritative — the legacy twin follows whatever the real name did.- The Ransack allowlists, the
:stockpermission subject list, the factory (:stock_level, with:stock_itemkept as an alias for external specs), and theactiverecord.modelsand admin-label i18n keys.
API and TypeScript side:
/api/v3/admin/stock_itemsbecomes/stock_levels, withStockLevelSerializerandAdmin::StockLevelSerializer; thestock_item_serializer/admin_stock_item_serializerregistry keys stay settable for one release through the same legacy-key map that already bridgesorder_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'suse-stock-itemshook, 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; deletemin_quantity, and move the movement factory and the Ransack allowlist offactionontokind. - Add
allocated_counthandling toStockLevel, delete the 5.5 shim, movein_stock?ontoavailable_count. - Add
StockLocation#allocate/#release/#adjust; deleterestock_backordered. - Convert every writer in the call-site table, and every reader in the readers table.
- Point
StockTransferatstock_transfer_idinstead ofas: :originator, and update the nested-attribute allowlist inSpree::PermittedAttributes. - Route the admin
PATCH /stock_levelscount edit andVariant#set_stockthroughadjustedmovements. - 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_movementsadmin endpoint with the Ransack allowlist above;kindand the FKs on the serializer,originator_*off it. reasonpermitted onPATCH /stock_levels.- The variant and stock-location history panels that
6.0-inventory-operations.mdspecifies 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
StockMovementrecords directly. Go throughStockLocation#restock/unstock(andallocate/release/adjustonce they exist) so rows come out typed when this plan lands. - Don't write
count_on_handoutside a movement. No new callers ofadjust_count_on_hand,set_count_on_hand,set_stockorupdate_all(count_on_hand:), and no new callers ofrestock_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 asallocated_countabovecount_on_handinstead. - Don't build business logic on
originator_type. It is gone in 6.1. Anything that needs to know why stock moved is waiting onkind. - Read availability through
Stock::Quantifier,StockLevel#available_countor#allocated_count— never rawcount_on_hand. The shims already return correct answers today (allocated_countis 0), so code written against them keeps working unchanged when the column arrives. New rawcount_on_handreads 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 thecount_on_handof 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
:stockpermission resource already coversStockMovement— a new stock endpoint needs no catalog entry, and must not ridesettings. - 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
Allocation timing. Stock is allocated at order placement, in
Orders::Complete— the one workflow both entry points converge on: checkout (Carts::Completedelegates its FINALIZE phase to it) and admin or B2B draft completion (which halts the cart pipeline immediately and hands the whole job over). Allocating inCarts::Completeitself would skip every draft order, leaving admin-placed orders with no allocation at all. The write belongs in thefinalize_fulfillmentsstep, 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.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.
Stock transfer movements. Reuse
shippedandreceivedwith astock_transfer_id. A transfer is a departure and an arrival; no new kinds.Purchase orders. Also
received, withpurchase_order_id. The kind says what happened to stock, the FK says why — so a new cause never needs a new kind.Phase order. Model before data task before originator drop, per the note at the top of the migration path.
Oversell representation.
allocated_countabovecount_on_hand, replacing negativecount_on_hand. Same arithmetic, sobackorder_limitand pre-orders are unaffected, and therestock_backorderedescape hatch is no longer needed.The
StockItem→StockLevelrename 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; thesi_→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_idrejects 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)