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.

Rework the typed stock movements plan for the shipped 6.0 core

Łukasz Adamczyk162e91b91818
diff --git a/CLAUDE.md b/CLAUDE.md
index 9363b18444..bb047dc515 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -19,7 +19,7 @@ Active plans (6.0 target, work pending):
- `6.0-admin-rbac.md` — First-class admin RBAC (spree/spree#14164; design finalized 2026-08-07): **one grant system, staff-only**. The permission catalog IS the API-key scope vocabulary (`read_*`/`write_*` per resource; `ApiKey::SCOPES` derives from the catalog; new `staff` pair split from `settings`); **permission sets are deleted at 6.0 with NO bridge** (recorded exception to the bridges convention — `assign` raises an upgrade tripwire; record-level custom rules → `register_ability`). **Roles are pure data** — no code-managed roles, no runtime merge; roles-as-code = seeds or Admin API; extensions register catalog resources, never roles. Enforcement unifies on the key gate for JWT staff AND secret keys (`ScopedAuthorization` generalized); CanCanCan demoted to internal plumbing. DB: JSON key array + `description` + `mutable` on `spree_roles` (admin seeded immutable — NamedType pattern; hosts can lock compliance roles the same way); roles CRUD + `GET /admin/permissions` + `/me.permission_keys` + 403 `details.required_permission`; full-page role editor (`/settings/roles/$roleId`) sharing one PermissionPicker with the API-keys page (client-side templates, no seeds). Storefront has NO roles — customer baseline is internal ability code, scope-fetching is the enforcement; B2B company roles are a separate future Enterprise system (never share the vocabulary); catalog visibility per group/company is data scoping, never a permission key. **Constraints now:** no new `PermissionSets::` classes or `Spree.permissions.assign` calls; models authorized by new admin controllers must be covered by a catalog entry; new sensitive resources get their own catalog resource, never ride `settings`; storefront code never consults `Spree::Role` or the catalog.
- `6.0-product-types.md` — Prototype → ProductType rename, custom-field schema enforcement. **Creation-time template (2026-08-06):** type edits never mutate existing products (custom-field form/validation + `fulfillment_types` are live by reference; option types/categories seed additively at attach; explicit previewed `ApplyToProducts` job is the only bulk path); per-product type detach/reassign allowed (non-destructive), `required` on a type's custom field is **advisory only** (dashboard marker; no server validation — Spree writes product + fields in two steps), no Store API exposure. **Fully shipped** (all phases, Phase 2 rescoped + delivered 2026-08-06)
- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product. **Shipped to 6-0-dev (PR #14265):** is_master removed from all models, default_variant_id + `spree:remove_master_variant` data-migration rake landed; only the physical is_master column drop remains (6.1 cleanup).
-- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs
+- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds (`received`/`allocated`/`shipped`/`released`/`adjusted`) + concrete FKs (`order_id`/`fulfillment_id`/`return_id`/`exchange_id`/`stock_transfer_id`; `purchase_order_id` rides with inventory operations). **Stock leaves the shelf at fulfillment, not at order placement (2026-08-13):** placement writes `allocated` (raising `allocated_count`, `count_on_hand` untouched), dispatch writes `shipped` (decrementing `count_on_hand` and retiring the allocation); allocation is keyed to the fulfillment (never the line item), oversell becomes `allocated_count > count_on_hand` instead of a negative on-hand (so `restock_backordered` and the movement `min_quantity` guard are deleted), and shipping only ever converts an allocation — which is what makes pre-upgrade fulfillments safe. **Also owns the `StockItem` → `StockLevel` rename** (decisions.md 2026-03-17, pulled in 2026-08-13) as Phase 0 — table/prefix (`si_`→`sl_`)/FK (`stock_level_id`)/endpoint (`/stock_levels`)/SDK resource all move, with constant + association + column aliases and dual-emitted `stock_item.*` events for one release. Phases: rename → schema → model/call sites → data task (`spree:migrate_stock_movements_to_typed_rows`, after `migrate_shipping_to_delivery` **and** `migrate_returns`) → API; the polymorphic `originator` drop waits for 6.1 because the task reads it. **Constraints now:** never write `count_on_hand` outside a movement (no new `adjust_count_on_hand`/`set_stock`/`update_all` callers, none of `restock_backordered`), never create `StockMovement` rows directly (use the `StockLocation` verbs), read availability through `Stock::Quantifier` / `StockItem#available_count` rather than raw `count_on_hand`, and build nothing on `originator_type`.
- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard
- `6.0-document-numbers.md` — Document number customization (**implemented 2026-08-13**): `Spree::Core::NumberGenerator` module factory → **`has_spree_number prefix: 'R'`** (macro from `Spree::HasNumber`, included into `Spree::Base` — no per-model include) + runtime `Spree.number_generators` registry (`Sequential` | `Random` strategies). **Sequential is the 6.0 default** (per-`(store, resource_type)` `spree_number_sequences` counter, `with_lock`, start 1001), random opt-in; merchant settings = one "Order numbers" card (prefix/suffix/format/start as Store preferences) — orders only. Fulfillment + Payment numbers become **derived methods** (`R1001-F1`/`R1001-P1`; stored value honored on legacy rows, columns frozen — never write them; gateway `order_id` = `payment.number`); every other numbered model keeps its stored number (Import/Export mail theirs, so they stayed numbered too), and `Spree::PurchaseOrder` must be born with `has_spree_number prefix: 'PO'`. Saving a numbered record with `validate: false` requires calling `generate_number` first. Never parse/regex a `number`; mostly-gapless, never legal invoice numbering.
- `6.0-delivery-profiles.md` — **Implemented in PR #14404 (2026-08-09).** `Spree::DeliveryProfile` = ShippingCategory promoted via table rename (`spree_shipping_categories`→`spree_delivery_profiles`, `products.shipping_category_id`→`delivery_profile_id`): store-scoped STI (kinds `DeliveryProfiles::Shipping`/`::Digital` via `Spree.delivery_profile_types`), one default per store, products reference it directly and it's required (auto-assigned: type template else store default; ProductType stamps at creation only — template doctrine). Profile ↔ stock locations (origins, empty=all) + profile→zones + profile→methods; method binds ≤1 zone (m:n join dropped), optional ships-from narrowing per method (no location-group layer — considered, dropped). **Classes only, NO string vocabularies:** method `fulfillment_type` column dropped, `Spree.fulfillment_types` registry + ProductType array deleted; behavior = `FulfillmentProvider` class predicates (`digital?`/`pickup?`/`pickup_point?`/`requires_address?`), rate-provider `requires_address?`, profile kind `digital?`/`requires_shipping_address?` + composition validations. Carts split per profile (`Splitter::DeliveryProfile`); Coordinator allocates only from profile-covered locations. `spree:migrate_delivery_profiles` (5.6→6.0 manifest) does store assignment/kind detection/non-narrowing fold-in/method m:n collapse (`spree_shipping_method_categories` survives to 6.1 as source). ShippingCategory/ShippingMethodCategory classes + associations deleted. Supersedes the string-registry + "named groups 6.1" decisions.
diff --git a/docs/plans/6.0-inventory-operations.md b/docs/plans/6.0-inventory-operations.md
index a084df14ca..15169f2c5d 100644
--- a/docs/plans/6.0-inventory-operations.md
+++ b/docs/plans/6.0-inventory-operations.md
@@ -16,7 +16,7 @@ Lift inventory operations from "atomic decrement + log" to a first-class workflo
2. **New `Spree::PurchaseOrder` model** for supplier receives. Today's "external receive" hack (a `StockTransfer` with `source_location_id: nil`) is replaced by a proper `PurchaseOrder` with `supplier`, `expected_at`, `line_items[]` with `unit_cost`, and the same receive flow as transfers.
3. **Variant + Location stock history.** Surfaces the audit feed introduced by `6.0-typed-stock-movements.md` as inline timelines in the admin SPA — answering "why is on-hand 47?" in the place users always ask: on a SKU or a warehouse.
-This plan is the **UX surface** for inventory ops. The data primitives (typed `StockMovement`, `kind`, concrete FKs to Order/Fulfillment/StockTransfer/ReturnAuthorization/PurchaseOrder) come from `6.0-typed-stock-movements.md` and the Fulfillment rename. Those two plans must land first.
+This plan is the **UX surface** for inventory ops. The data primitives (typed `StockMovement`, `kind`, concrete FKs to Order/Fulfillment/Return/Exchange/StockTransfer/PurchaseOrder) come from `6.0-typed-stock-movements.md` and the Fulfillment rename. Those two plans must land first.
## Problem
@@ -51,7 +51,7 @@ Once `6.0-typed-stock-movements.md` lands, every change to `count_on_hand` carri
|---|---|
| `Spree::StockTransfer` | One-shot atomic transfer. Columns: `source_location_id` (nullable for receives), `destination_location_id`, `number`, `reference`, `type` (STI column, unused), `created_at`. No status, no expected/received-at, no line items. |
| External receive | `StockTransfer.transfer(nil, destination, variants)` — no supplier, no cost. |
-| Movement audit | `Spree::StockMovement` with polymorphic `originator`. Only `StockTransfer`, `ReturnAuthorization`, and `nil` show up in practice. Shipment fulfillment does **not** write movements (lives on `InventoryUnit` instead). |
+| Movement audit | `Spree::StockMovement` with polymorphic `originator` — a `Fulfillment` (stock leaves at order placement, not at dispatch), a `StockTransfer`, a `Return`/`Exchange`, or nothing. Manual corrections and backordered restocks write no movement at all. |
| Admin SPA | `Products → Transfers` (single page) with create-transfer sheet. No history view, no PO concept. |
## Key Decisions (do not deviate without discussion)
@@ -77,8 +77,8 @@ Once `6.0-typed-stock-movements.md` lands, every change to `count_on_hand` carri
These additions live in `6.0-typed-stock-movements.md`; this plan only consumes them.
-- Add `purchase_order_id` FK to `Spree::StockMovement` (typed-movements plan currently lists `shipment_id`/`fulfillment_id`, `order_id`, `return_authorization_id`, `stock_transfer_id` — extend with `purchase_order_id`).
-- Add `Spree::StockMovement::KINDS += ['purchase_order_received']` — **actually no**, reuse `received` with `purchase_order_id` set. Same shape as RMA receive. The `kind` is *what happened to stock*; the FK is *why*.
+- Add `purchase_order_id` FK to `Spree::StockMovement` (typed-movements plan lists `order_id`, `fulfillment_id`, `return_id`, `exchange_id`, `stock_transfer_id` — extend with `purchase_order_id`).
+- Add `Spree::StockMovement::KINDS += ['purchase_order_received']` — **actually no**, reuse `received` with `purchase_order_id` set. Same shape as a return receive. The `kind` is *what happened to stock*; the FK is *why*.
### Admin SPA UX
diff --git a/docs/plans/6.0-typed-stock-movements.md b/docs/plans/6.0-typed-stock-movements.md
index 45ac83b539..dd2f36aeb1 100644
--- a/docs/plans/6.0-typed-stock-movements.md
+++ b/docs/plans/6.0-typed-stock-movements.md
@@ -1,73 +1,93 @@
# Typed Stock Movements
-**Status:** Draft
-**Target:** Spree 6.0
-**Depends on:** Stock Reservations (6.0-stock-reservations.md), Remove Master Variant (6.0-remove-master-variant.md), Cart/Order Split (6.0-cart-order-split.md)
+**Status:** Design Finalized
+**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-07-27
+**Last updated:** 2026-08-13
-> **Vocabulary note (2026-07-27):** the new `spree_stock_movements` columns are born with **`fulfillment_id`** (never `shipment_id`) per `6.0-fulfillment-and-delivery.md` — same born-correct rule as the split-adjustments tables. Every `shipment_id` below reads as `fulfillment_id`; the backfill still matches legacy rows on `originator_type IN ('Spree::Shipment', 'Spree::Fulfillment')`.
+> **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 ship_xyz, 2 units returned via RA ra_456") instead of today's opaque list of positive/negative numbers.
+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::Shipment', originator_id: 42 }`. You can't answer "how many units are allocated to pending orders?" or "how many units were returned this month?" without parsing originator types and guessing the business meaning of positive vs negative quantities.
+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` — same problem as polymorphic Adjustment. Can't eager load, can't JOIN cleanly. Originator can be `Shipment`, `ReturnAuthorization`, `StockTransfer`, or `nil` (manual adjustment).
+`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** (reserved for fulfillment) before it's **shipped** (physically removed). Today there's no allocation concept — stock decrements happen at various points (shipment creation, shipment shipping) depending on configuration, with no clear audit of the transition.
+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:
-### 4. No movement lifecycle
+- 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.
-There's no way to trace the lifecycle of a unit: received → allocated → shipped. Or: received → allocated → released (order canceled). Each step is just an anonymous +/- on count_on_hand.
+### 4. Several writers, no audit
-## Current State
+`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.
-| What | How it works |
-|------|-------------|
-| `StockMovement` | `quantity` (int) + `originator` (polymorphic) + `stock_item_id` |
-| Shipment ships | `stock_location.unstock(variant, qty, shipment)` → creates movement with negative qty |
-| Return received | `StockMovement.create!(stock_item_id:, quantity: +qty, originator: return_authorization)` |
-| Stock transfer | `source.unstock(...)` + `destination.restock(...)` → two movements, linked by StockTransfer originator |
-| Manual adjustment | `stock_item.adjust_count_on_hand(value)` → no movement record (!) |
-| Fulfillment change | `current_location.restock(...)` + `desired_location.unstock(...)` |
-| After create | `update_stock_item_quantity` → calls `stock_item.adjust_count_on_hand` |
-| Immutable | `readonly?` returns true after persist — movements can't be edited |
+## Current State
-Originator types in practice: `Spree::Shipment`, `Spree::ReturnAuthorization`, `Spree::StockTransfer`, `nil`.
+| 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 `kind` column** (not separate tables per type). Stock movements are all the same shape (stock_item, quantity, timestamp, reason) — splitting into 5 tables would add complexity without benefit. The `kind` column is an indexed string, not a polymorphic type.
-- **Concrete FKs replace polymorphic originator.** Separate nullable FKs: `shipment_id`, `order_id`, `return_authorization_id`, `stock_transfer_id`. Each movement has at most one set.
-- **Five defined kinds:**
- - `received` — stock added (purchase order, manual receipt, return restock)
- - `allocated` — stock earmarked for an order (on order completion or payment authorization)
- - `shipped` — allocated stock physically sent (on shipment ship)
- - `released` — allocated stock returned to available (order canceled, fulfillment changed)
- - `adjusted` — manual correction (admin inventory count, shrinkage, damage)
-- **Movements are immutable.** Existing `readonly?` pattern stays. To reverse a movement, create a counterpart (e.g., `released` reverses `allocated`).
-- **`count_on_hand` semantics change.** Today it's the only number. After:
- - `count_on_hand` = physical stock at location (unchanged by allocation, only by receipt/ship/adjust)
- - `allocated_quantity` = derived from movements (`SUM of allocated - shipped - released`)
- - `available_quantity` = `count_on_hand - allocated_quantity - reserved_quantity` (from StockReservations plan)
-- **`StockItem` gets `allocated_count` denormalized column** — updated on allocation/release/ship movements. Avoids SUM query on every availability check.
-- **Keep `StockLocation.restock/unstock` methods** but they create typed movements instead of generic ones.
+- **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 (rewritten)
+### StockMovement model
```ruby
class Spree::StockMovement < Spree.base_class
@@ -79,32 +99,26 @@ class Spree::StockMovement < Spree.base_class
publishes_lifecycle_events
- belongs_to :stock_item, class_name: 'Spree::StockItem', inverse_of: :stock_movements
+ belongs_to :stock_level, class_name: 'Spree::StockLevel', inverse_of: :stock_movements
- # Concrete FKs — at most one is set per movement
+ # The cause. A fulfillment-driven row carries its order too.
belongs_to :order, class_name: 'Spree::Order', optional: true
- belongs_to :shipment, class_name: 'Spree::Shipment', optional: true
- belongs_to :return_authorization, class_name: 'Spree::ReturnAuthorization', 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_item, :quantity, :kind, presence: 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: -> { kind == 'adjusted' }
+ validates :reason, presence: true, if: :adjusted?
- after_create :update_stock_item_quantities
+ after_create :apply_to_stock_level
scope :recent, -> { order(created_at: :desc) }
- scope :by_kind, ->(kind) { where(kind: kind) }
- scope :received, -> { by_kind('received') }
- scope :allocated, -> { by_kind('allocated') }
- scope :shipped, -> { by_kind('shipped') }
- scope :released, -> { by_kind('released') }
- scope :adjusted, -> { by_kind('adjusted') }
- scope :for_order, ->(order) { where(order: order) }
- scope :for_shipment, ->(shipment) { where(shipment: shipment) }
+ KINDS.each { |kind| scope kind, -> { where(kind: kind) } }
- delegate :variant, :variant_id, to: :stock_item, allow_nil: true
+ delegate :variant, :variant_id, to: :stock_level, allow_nil: true
def readonly?
persisted?
@@ -112,300 +126,377 @@ class Spree::StockMovement < Spree.base_class
private
- def update_stock_item_quantities
- return unless stock_item.should_track_inventory?
+ # The single place count_on_hand and allocated_count change.
+ def apply_to_stock_level
+ return unless stock_level.should_track_inventory?
case kind
- when 'received', 'adjusted'
- # Changes physical count
- stock_item.adjust_count_on_hand(quantity)
- when 'allocated'
- # Earmarks stock — no count_on_hand change, increment allocated_count
- stock_item.increment!(:allocated_count, quantity.abs)
+ 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.adjust_allocated_count(-quantity.abs)
when 'shipped'
- # Physically removed — decrement count_on_hand, decrement allocated_count
- stock_item.adjust_count_on_hand(-quantity.abs)
- stock_item.decrement!(:allocated_count, quantity.abs)
- when 'released'
- # Returns to available — decrement allocated_count only
- stock_item.decrement!(:allocated_count, quantity.abs)
+ stock_level.adjust_count_on_hand(-quantity.abs)
+ stock_level.adjust_allocated_count(-quantity.abs)
end
end
end
```
-### StockItem changes
+`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`.
-```ruby
-class Spree::StockItem < Spree.base_class
- # Existing
- # count_on_hand — physical stock at location
+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.
- # New denormalized column
- # allocated_count — units earmarked for pending orders
+**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` or a `validate` hook waving the guard 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).
- def available_count
- count_on_hand - allocated_count
- end
+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.
- # Used by Quantifier (replaces raw count_on_hand)
- def available?
- available_count > 0 || backorderable?
- end
-end
-```
+This is why the non-negative guard keys off the movement kind rather than off `backorderable?` / `preorder?` as `verify_count_on_hand?` does today: `shipped` may go negative (departure is a fact), `received` cannot by construction, and `adjusted` keeps the guard — a hand-typed count landing below zero is a typo, not a fact.
-### Quantifier changes
+### StockLevel
-```ruby
-class Spree::Stock::Quantifier
- def total_on_hand
- @total_on_hand ||= if variant.should_track_inventory?
- available_stock - reserved_quantity
- else
- BigDecimal::INFINITY
- end
- end
+`allocated_count` becomes a real column, so the 5.5 shim and its comment are deleted.
- # Physical stock minus allocated (pending fulfillment)
- def available_stock
- if association_loaded?
- stock_items.sum(&:available_count)
- else
- stock_items.sum('count_on_hand - allocated_count')
- end
- end
+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:
- # From StockReservations plan
- def reserved_quantity
- return 0 unless Spree::Config[:stock_reservations_enabled]
+```ruby
+def adjust_allocated_count(value)
+ value.negative? ? decrement!(:allocated_count, value.abs) : increment!(:allocated_count, value)
+end
- Spree::StockReservation.active.where(stock_item: stock_items).sum(:quantity)
- end
+def in_stock?
+ available_count.positive?
end
```
-**Full availability formula:**
+`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:
+
```
-available = count_on_hand - allocated_count - reserved_quantity
+purchasable = count_on_hand - allocated_count - active reservations
```
-Where:
-- `count_on_hand` = physical units at location
-- `allocated_count` = units earmarked for orders awaiting shipment
-- `reserved_quantity` = units held during checkout (from StockReservations plan)
+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.
-### StockLocation changes
+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.
-```ruby
-class Spree::StockLocation < Spree.base_class
- # Restock: units received at location
- def restock(variant, quantity, originator = nil)
- stock_item = stock_item_or_create(variant)
- stock_item.stock_movements.create!(
- quantity: quantity,
- kind: 'received',
- stock_transfer: originator.is_a?(Spree::StockTransfer) ? originator : nil,
- return_authorization: originator.is_a?(Spree::ReturnAuthorization) ? originator : nil
- )
- end
+### Readers that must subtract allocations
- # Unstock: units physically leaving location (shipped)
- def unstock(variant, quantity, shipment)
- stock_item = stock_item_or_create(variant)
- stock_item.stock_movements.create!(
- quantity: quantity,
- kind: 'shipped',
- shipment: shipment,
- order: shipment.order
- )
- end
+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:
- # Allocate: earmark units for an order
- def allocate(variant, quantity, order)
- stock_item = stock_item_or_create(variant)
- stock_item.stock_movements.create!(
- quantity: quantity,
- kind: 'allocated',
- order: order
- )
- end
+| 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 |
- # Release: return allocated units to available
- def release(variant, quantity, order)
- stock_item = stock_item_or_create(variant)
- stock_item.stock_movements.create!(
- quantity: quantity,
- kind: 'released',
- order: order
- )
- end
+### Writers: today's call site to tomorrow's kind
- # Adjust: manual inventory correction
- def adjust(variant, quantity, reason:)
- stock_item = stock_item_or_create(variant)
- stock_item.stock_movements.create!(
- quantity: quantity,
- kind: 'adjusted',
- reason: reason
- )
- end
-end
-```
+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
-### Order lifecycle integration
+The table above is keyed by call site; this is the same thing in the order it happens, for the ordinary path:
-With the Cart/Order split (6.0-cart-order-split.md), the order state machine is gone. `cart.complete!` calls `Spree::Carts::Complete` which creates a new Order. Stock allocation happens at this point — when the cart converts to an order.
+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:
```ruby
-# On cart completion (Spree::Carts::Complete):
-# Reservation (from StockReservations plan) is released, allocation created
-order.line_items.each do |li|
- stock_location = select_stock_location(li.variant)
- stock_location.allocate(li.variant, li.quantity, order)
+# 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
+
+def unstock(variant, quantity, cause = nil, persist: true)
+ move(variant, quantity, kind: 'shipped', cause: cause, persist: persist)
+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
-# Release checkout reservation (reservation plan handles this)
-# On shipment ship:
-# Convert allocation to shipped (count_on_hand decremented, allocated_count decremented)
-shipment.inventory_units.each do |iu|
- shipment.stock_location.unstock(iu.variant, iu.quantity, shipment)
+# Manual correction. Signed, so a negative writes stock off.
+def adjust(variant, quantity, reason:)
+ move(variant, quantity, kind: 'adjusted', reason: reason)
end
-# On order cancellation:
-# Release allocated stock
-order.line_items.each do |li|
- stock_location.release(li.variant, li.quantity, order)
+private
+
+def move(variant, quantity, kind:, cause: nil, reason: nil, persist: true)
+ 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
-# On return received:
-# Restock units
-stock_location.restock(variant, quantity, return_authorization)
+# 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?filter[stock_item_id]=si_xxx
-GET /api/v3/admin/stock_movements?filter[kind]=allocated&filter[order_id]=or_abc
+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:
+
```json
{
"id": "sm_k5nR8xLq",
"kind": "allocated",
"quantity": 3,
- "stock_item_id": "si_xyz",
+ "reason": null,
+ "stock_level_id": "sl_xyz",
"order_id": "or_abc",
- "shipment_id": null,
- "return_authorization_id": null,
+ "fulfillment_id": "ful_xyz",
+ "return_id": null,
+ "exchange_id": null,
"stock_transfer_id": null,
- "reason": null,
- "created_at": "2026-03-16T14:30:00Z"
+ "created_at": "2026-08-13T14:30:00Z"
}
```
-StockItem response gains `allocated_count` and `available_count`:
-```json
-{
- "id": "si_xyz",
- "count_on_hand": 50,
- "allocated_count": 8,
- "available_count": 42,
- "backorderable": false
-}
-```
+`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 1: Schema changes
+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`
+
+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.
```ruby
-class AddTypedStockMovements < ActiveRecord::Migration[7.2]
+class RenameStockItemsToStockLevels < ActiveRecord::Migration[8.1]
def change
- # Add kind and concrete FKs to existing table
- add_column :spree_stock_movements, :kind, :string
- add_column :spree_stock_movements, :order_id, :bigint
- add_column :spree_stock_movements, :shipment_id, :bigint
- add_column :spree_stock_movements, :return_authorization_id, :bigint
- add_column :spree_stock_movements, :stock_transfer_id, :bigint
- add_column :spree_stock_movements, :reason, :string
+ 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`.
+- `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.
+- `publishes_lifecycle_events` learns a `legacy_event_prefix:` option, and StockLevel declares `stock_item` — the three lifecycle events dual-emit under both names, mirroring how `Fulfillment::CustomEvents` dual-emits `shipment.*`. A declarative option rather than three hand-written twins, because the next rename needs the same thing.
+- 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)
+
+```ruby
+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_index :spree_stock_movements, :order_id
- add_index :spree_stock_movements, :shipment_id
- # Add allocated_count to stock_items
- add_column :spree_stock_items, :allocated_count, :integer, null: false, default: 0
+ add_column :spree_stock_levels, :allocated_count, :integer, null: false, default: 0
end
end
```
-### Phase 2: Data migration (rake task)
+`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.
-```ruby
-# rake spree:type_stock_movements
-#
-# For each existing StockMovement:
-# originator_type == 'Spree::Shipment' && quantity < 0
-# → kind: 'shipped', shipment_id: originator_id, order_id: shipment.order_id
-# originator_type == 'Spree::Shipment' && quantity > 0
-# → kind: 'released', shipment_id: originator_id (fulfillment change restock)
-# originator_type == 'Spree::ReturnAuthorization'
-# → kind: 'received', return_authorization_id: originator_id
-# originator_type == 'Spree::StockTransfer' && quantity > 0
-# → kind: 'received', stock_transfer_id: originator_id
-# originator_type == 'Spree::StockTransfer' && quantity < 0
-# → kind: 'shipped', stock_transfer_id: originator_id
-# originator_type == nil
-# → kind: 'adjusted', reason: 'Legacy manual adjustment'
-#
-# Note: No historical 'allocated' movements exist (allocation didn't exist before).
-# allocated_count on StockItems starts at 0 — only new orders create allocations.
-```
+### Phase 2: Model and call sites
+
+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`)
+
+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 | `shipped`, `fulfillment_id` + the fulfillment's `order_id` |
+| `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.
+
+**Reconcile open fulfillments.** Under the old model, an unfulfilled fulfillment on a placed order has already taken its units off the shelf. Under the new one, those units are on the shelf and allocated. For every open fulfillment on a placed order the task therefore adds its quantity back to `count_on_hand`, adds the same quantity to `allocated_count`, and writes the matching `allocated` movement so the jump has a visible cause. Availability is unchanged by construction — both sides of `count_on_hand - allocated_count` move together — and the write is deliberately a direct column update rather than a `received` movement, because no goods arrived.
+
+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.
-### Phase 3: Model update
+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.
-- Add `kind` validation, concrete FK associations
-- Update `update_stock_item_quantities` callback with kind-based logic
-- Update `StockLocation.restock/unstock` to create typed movements
-- Add `StockLocation.allocate/release/adjust` methods
-- Update `Quantifier` to use `available_count`
-- Wire allocation into order completion flow
-- Wire release into order cancellation flow
+### Phase 4: API, serializer, dashboard
-### Phase 4: Remove polymorphic originator
+- 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:**
```ruby
-class RemoveOriginatorFromStockMovements < ActiveRecord::Migration[7.2]
+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
- # kind is now required
change_column_null :spree_stock_movements, :kind, false
end
end
```
-### Phase 5: API + serializer updates
+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` | Drop `legacy_event_prefix:` from `StockLevel`'s `publishes_lifecycle_events` call. 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`. |
+
+The `legacy_event_prefix:` option itself stays. It is generic machinery for the next rename, not scaffolding for this one, and removing the declaration is what stops the twins.
-- Add `kind`, concrete FK IDs to StockMovement serializer
-- Add `allocated_count`, `available_count` to StockItem serializer
-- Admin dashboard: stock movement history with kind filters
+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 StockMovements directly.** Use `StockLocation.restock/unstock/allocate/release/adjust` methods which will create properly typed movements.
-- **Don't rely on `originator_type` for business logic.** Use the `kind` column / scopes instead.
-- **Use `Quantifier#total_on_hand` for availability.** Don't query `count_on_hand` directly — the quantifier accounts for allocations and reservations.
+- **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 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.
+- **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 on **cart completion** — when `cart.complete!` creates the Order (see 6.0-cart-order-split.md). The checkout reservation (from 6.0-stock-reservations.md) is released at the same time. Flow: customer in checkout → reservation holds stock → cart completes → reservation released, allocation created → shipment ships → allocation converted to shipped.
+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.
-2. **Stock transfer movements.** Reuse `shipped`/`received` with a `stock_transfer_id` FK. A transfer is just shipping from one location and receiving at another. No new kinds 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
@@ -413,9 +504,14 @@ None at this time.
## References
-- Current stock movement: `spree/core/app/models/spree/stock_movement.rb`
-- Current stock location restock/unstock: `spree/core/app/models/spree/stock_location.rb:96-114`
-- Current shipment unstock: `spree/core/app/models/spree/shipment.rb:491`
-- Current return restock: `spree/core/app/models/spree/return_item.rb:201`
-- Related plan: `6.0-stock-reservations.md` (reservations layer on top of availability)
-- Related plan: `6.0-6.1-split-adjustments.md` (same pattern: replace polymorphic with concrete FKs)
+- 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)
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index b3eeb39a9f..a0e5e45571 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -217,6 +217,43 @@ permission-catalog entries, Country/State's zone associations, and Store's
releases overdue). `6.0-delivery-zones.md` still owns dropping the classes
and tables in 6.1; what remains for it is deletion, not untangling.
+## 2026-08-13: Stock leaves the shelf at fulfillment, not at order placement
+
+Spree has always decremented `count_on_hand` when an order is placed, so a
+warehouse's on-hand number in Spree never matched what a picker could count,
+and the one event a warehouse cares about — the parcel leaving — wrote nothing
+to the stock ledger at all. Typed Stock Movements splits the two: placement
+writes an `allocated` movement that raises `allocated_count` and leaves
+`count_on_hand` untouched, and dispatch writes a `shipped` movement that
+decrements `count_on_hand` and retires the allocation with it. On-hand becomes what is on the shelf and
+`StockItem#allocated_count` carries what is promised, which is the model every
+other commerce platform ships.
+
+Three consequences worth naming, because they change existing behavior rather
+than adding to it. Oversell is now `allocated_count > count_on_hand` instead of
+a negative `count_on_hand` — the same signed arithmetic, so `backorder_limit`
+and pre-orders are untouched, but `restock_backordered` and the movement's
+`min_quantity` guard both existed only to service the negative representation
+and are deleted with it. Availability must be read through
+`Stock::Quantifier` / `available_count` everywhere, since a raw `count_on_hand`
+read now offers units already promised to another customer. And allocation is
+keyed to the **fulfillment**, not the line item: the fulfillment already owns
+the origin location and the on-hand/backordered split, so allocating anywhere
+else would re-decide what the Coordinator already decided.
+
+Shipping only ever converts an allocation, which is also how the upgrade stays
+safe: a fulfillment carrying no allocation is one created before the upgrade,
+whose units already left under the old rules, so it ships without a movement
+and its stock is never decremented twice. The manifest task reconciles the open
+fulfillments it finds — on-hand and `allocated_count` move up together, leaving
+availability unchanged by construction.
+
+Plan: `6.0-typed-stock-movements.md` (phases reordered the same day: model
+update before the data task, and the polymorphic `originator` drop held to 6.1
+like every other 6.0 cleanup, since the task reads those columns). Consumers:
+`6.0-stock-reservations.md` (the reservation term in the same formula),
+`6.0-inventory-operations.md` (transfers, purchase orders, history screens).
+
## 2026-08-13: Document numbers — sequential by default, store-configurable orders, derived child numbers
`Spree::Core::NumberGenerator` (the boot-frozen `Module` factory) is replaced
@@ -2020,6 +2057,12 @@ sales-channel apps, and the category mapper. New plan:
rebuilt as native core models on top of the 6.0 Cart/Order split.
## 2026-03-17: Rename StockItem → StockLevel
+**Owned by `6.0-typed-stock-movements.md` as of 2026-08-13** — it ships as that
+plan's Phase 0, ahead of the new movement columns, so they are born beside a
+final name. Bridges: constant, association and column aliases plus dual-emitted
+`stock_item.*` events for one release; the prefix change and the endpoint rename
+take the break.
+
`Spree::StockItem` → `Spree::StockLevel`, `spree_stock_items` → `spree_stock_levels`.
Prefix ID: `si_` → `sl_`.