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.

Planned the Inventory page and the stock-level counters behind it

Damian Legawiec835e1ed43f98
diff --git a/docs/plans/6.0-inventory-operations.md b/docs/plans/6.0-inventory-operations.md
index 5e343d5288..4233895746 100644
--- a/docs/plans/6.0-inventory-operations.md
+++ b/docs/plans/6.0-inventory-operations.md
@@ -4,7 +4,8 @@
**Target:** Spree 6.0 (transfers, purchase orders, history) / 6.1 (simple lot capture). **Tier split 2026-09-07:** the lot LIBRARY — received-lot inventory, quantities, expiry, FIFO/FEFO auto-allocation — moved to Enterprise (`ee/docs/plans/inventory-lots.md`); OSS keeps the traceability capture below.
**Depends on:** Typed Stock Movements (6.0-typed-stock-movements.md), Fulfillment & Delivery (6.0-fulfillment-and-delivery.md), Stock Reservations (6.0-stock-reservations.md)
**Author:** Damian + Claude
-**Last updated:** 2026-09-07 (grooming: open questions 1-3 settled, implementation decisions recorded below)
+**Last updated:** 2026-09-10 (Phase 7 added: stock-level counters + the Inventory page; counters-not-computes, single-writer rule and Unavailable-out-of-scope recorded)
+**Tracking:** Linear V-3628 · GitHub spree/spree#14616
> **Naming note (2026-07-14):** the procurement-source model this plan introduces is **`Spree::Supplier`** (`spree_suppliers`, prefix `sup_`, `/api/v3/admin/suppliers`). An earlier draft called it `Spree::Seller`, which collided with the marketplace seller model of `6.0-multi-vendor-marketplace.md` — `Spree::Seller` is reserved for marketplace sellers (see `decisions.md` 2026-07-14). "Supplier" also matches Shopify's purchase-order vocabulary.
@@ -17,6 +18,8 @@ Lift inventory operations from "atomic decrement + log" to a first-class workflo
3. **Variant + Location stock history.** Surfaces the audit feed introduced by `6.0-typed-stock-movements.md` as inline timelines in the admin SPA — answering "why is on-hand 47?" in the place users always ask: on a SKU or a warehouse.
4. **Simple lot capture** (reshaped 2026-09-07 — the tier split): OSS records **which lot/batch a fulfillment actually shipped** — entered at fulfillment time, split across batches when needed — and makes the lot number searchable in both directions (customer → order → lot; lot → every order/customer that received it — the recall question). The full lot **library** (received-lot inventory with quantities, expiry, FIFO/FEFO auto-allocation) is the Enterprise layer that fills these same capture rows automatically.
+5. **An Inventory page, and the two counters it reads** (added 2026-09-10). A list of stock levels under the Inventory section with Shopify's columns — on hand, committed, reserved, available, incoming — per location. On hand and committed were already persisted; **reserved and incoming become counter-cache columns on `spree_stock_levels`**, each with exactly one writer path and a recount task that doubles as the backfill.
+
This plan is the **UX surface** for inventory ops. The data primitives (typed `StockMovement`, `kind`, concrete FKs to Order/Fulfillment/Return/Exchange/StockTransfer/PurchaseOrder) come from `6.0-typed-stock-movements.md` and the Fulfillment rename. Those two plans must land first.
## Problem
@@ -207,6 +210,49 @@ implementation. Six additions, one model.
buying feature that drags product creation into purchasing), dropship, consignment, and a
quarantine location for rejected units.
+### Stock levels, counters and the Inventory page (2026-09-10)
+
+Settled while adding the page merchants expect beside transfers and purchase orders: what do I
+have, where, and what is committed, held or on its way. Shopify's inventory grid is the reference
+for the columns; Medusa's inventory module (persisted `stocked`/`reserved`/`incoming`, derived
+`available`) is the reference for the storage shape.
+
+- **Counters, not computes.** `spree_stock_levels` gains `reserved_count` and `incoming_count`,
+ integer, `default: 0, null: false`. The page is a paginated list read many times a day and the
+ inputs change through a handful of workflows; the repo already trusts `allocated_count`,
+ `fee_total` and `commission_total` the same way. (The 2026-09-07 ruling "availability is never
+ denormalized" is about product *market* availability, not stock — it does not apply here.)
+- **Each counter has exactly one writer path**, mirroring the movement callback that alone writes
+ `allocated_count`. Reserved: `StockReservations::Reserve` (+), `::Release` (−),
+ `StockReservations::ExpireJob` (−) — `Extend` only moves `expires_at` and is not a writer.
+ Incoming: `PurchaseOrders::MarkOrdered` (+ every line's incoming), `::MarkDraft` (−),
+ `::Cancel` (−), `::Update` while ordered (±), `StockTransfers::MarkInTransit` (+), `::Cancel`
+ (−), and `StockReceipts::Recording` (−) for both — it already runs inside `receivable.with_lock`,
+ so the incoming decrement is atomic with the on-hand increment and no mid-receipt read shows the
+ units twice or not at all.
+- **Incoming is `[expected − received − rejected, 0].max` per line**, as `Spree::ReceivableItem#incoming`
+ shared by both item models. `outstanding` is not it: `quantity_settled` is received alone, so
+ `outstanding` still counts rejected units as awaited, and they are not coming.
+- **A transfer counts as incoming from `in_transit`**, when `MarkInTransit` writes `quantity_shipped`.
+ A `ready_to_ship` transfer contributes zero — nothing is moving yet. Shopify counts from
+ creation; the divergence is deliberate and avoids inventing a planned-quantity column.
+- **`spree:stock:recount_levels`** recomputes both counters from their sources — active reservations;
+ open PO lines (`ordered | partially_received`) and in-flight transfer lines
+ (`in_transit | partially_received`) at their destination — logs every row whose stored value
+ differed, and is the backfill. `allocated_count` has no such task; these two have eleven writers
+ between them and get one.
+- **Available on the page is `count_on_hand − allocated_count − reserved_count`** — the figure
+ `Stock::Quantifier` already produces, now readable from columns.
+- **Unavailable is out of scope.** Rejected delivery units are not it: they "exist only on the
+ receipt" (above) and were never in the building, whereas Shopify's Unavailable is on-site stock
+ held back (damaged, QC, safety stock). A true bucket is a fourth counter with its own adjust
+ action and reason vocabulary; no reference validates it yet, so it is a separate plan item.
+ Rejections are surfaced where they live — on the purchase order and the receipt.
+- **Dashboard only.** The `stock` permission already carries `audiences: %i[seller]`; the seller
+ panel gets the same table under a forced seller scope as a follow-up, per the
+ dashboard-is-the-reference rule. The counters and the endpoint are shared, so that follow-up is
+ a route and a scope, not a second implementation.
+
### Typed Stock Movements wiring
These additions live in `6.0-typed-stock-movements.md`; this plan only consumes them.
@@ -226,6 +272,7 @@ These additions live in `6.0-typed-stock-movements.md`; this plan only consumes
- **Variant Inventory tab (on Product detail) gains a History panel.** Reads `GET /api/v3/admin/stock_movements?q[stock_level_variant_id_eq]=…` (the typed-movements admin endpoint), renders `date · location · qty before → after · kind · cause` with the cause linking to the underlying entity (Transfer T-…, PO PO-…, RMA RA-…, Order #…, "Manual adjustment").
- **Stock Location detail page (settings) gains an Activity tab.** Same data shape, scoped via `q[stock_level_stock_location_id_eq]`. Useful for warehouse reconciliation.
- **No standalone "Stock Movements" page.** Movements are always read in the context of a variant or a location. The legacy admin's firehose list is gone.
+- **An `Inventory` list page at `/inventory`** (2026-09-10), first in the Inventory section — the section's parent path moves here from `/transfers`. One row per stock level: product + variant (thumbnail, SKU), *On hand*, *Committed* (`allocated_count`), *Reserved*, *Available*, *Incoming*; a location switcher on the existing `q[stock_location_id_eq]`; SKU/name search on the existing `variant` association ransack; each row links to the variant. Reads the existing `GET /admin/stock_levels` — no new endpoint. Every figure is a column read; nothing on this page is summed at request time.
## Design Details
@@ -411,6 +458,35 @@ class Spree::Supplier < Spree.base_class
end
```
+### StockLevel counters (2026-09-10)
+
+```ruby
+# migration — no index: read per row, never filtered
+add_column :spree_stock_levels, :reserved_count, :integer, default: 0, null: false
+add_column :spree_stock_levels, :incoming_count, :integer, default: 0, null: false
+```
+
+```ruby
+module Spree::ReceivableItem
+ # Units still on their way. Not `outstanding`: settled means received, so
+ # outstanding keeps counting units the dock refused, and those never arrive.
+ def incoming
+ [quantity_expected - quantity_received.to_i - quantity_rejected.to_i, 0].max
+ end
+end
+```
+
+Both `PurchaseOrderItem` (`expects_quantity_in :quantity_ordered`) and `StockTransferItem`
+(`expects_quantity_in :quantity_shipped`) already include the concern.
+
+| Counter | Source of truth | Writers (each adjusts by delta, inside the workflow's transaction) |
+|---|---|---|
+| `reserved_count` | `SUM(quantity)` over `StockReservation.active` per `stock_level_id` | `Reserve` +, `Release` −, `ExpireJob` − |
+| `incoming_count` | `SUM(item.incoming)` over open PO lines + in-flight transfer lines, keyed by (`variant_id`, `destination_location_id`) | PO `MarkOrdered` +, `MarkDraft` −, `Cancel` −, `Update` ±; transfer `MarkInTransit` +, `Cancel` −; `StockReceipts::Recording` − for both |
+
+`spree:stock:recount_levels` computes the two sources above per stock level, `update_all`s any
+row that differs, and prints the corrected rows. It is idempotent and is the Phase 7 backfill.
+
### Stock movement extensions
Added to `Spree::StockMovement` (extends what `6.0-typed-stock-movements.md` introduces):
@@ -467,6 +543,11 @@ Each status change is its own member action rather than a `PATCH` that mass-assi
`GET /stock_movements` (the audit feed introduced by `6.0-typed-stock-movements.md`) gains support for `q[purchase_order_id_eq]` automatically once the FK is in the ransackable list.
+`GET /stock_levels` (existing) gains `reserved_count` and `incoming_count` on the admin serializer
+beside the `allocated_count` and `available_count` it already emits (2026-09-10). No new endpoint;
+the index already ransacks `stock_location_id`, `variant_id` and the `variant`/`stock_location`
+associations, which is all the Inventory page needs.
+
### Serializer shapes
```json
@@ -688,6 +769,20 @@ All other existing transfers (with a real source location) become `status: 'rece
- Remove the `StockTransfer.receive` / `StockTransfer.transfer` no-source code path (already deprecated).
- Drop the unused `type` STI column on `spree_stock_transfers` after confirming no plugin set it.
+### Phase 7: Stock level counters + Inventory page (2026-09-10)
+
+Self-contained; another session can take it over from here. In order:
+
+1. **Migration** — `reserved_count` and `incoming_count` on `spree_stock_levels` (shape above), then `pnpm wt:template` so other worktrees inherit it.
+2. **`Spree::ReceivableItem#incoming`** with a model spec proving `ordered 40, received 38, rejected 2 → incoming 0` (the case `outstanding` gets wrong).
+3. **Writers.** `StockLevel#adjust_reserved_count(delta)` / `#adjust_incoming_count(delta)` (locked `increment!`/`decrement!`, clamped at zero like `release_allocated_count`), called from exactly the workflows in the table above and nowhere else. Each workflow spec asserts the counter before and after; `Recording`'s asserts that on-hand up and incoming down land in one transaction.
+4. **`spree:stock:recount_levels`** rake task + spec seeding a drifted row and asserting it is corrected; run it once as the backfill.
+5. **Serializer** — the two attributes on `Admin::StockLevelSerializer`; typelizer → zod → rswag → `docs/api-reference`.
+6. **SPA** — route `_authenticated/$storeId/inventory/index.tsx` on `ResourceTable`, nav entry first in the Inventory group with the parent path moved from `/transfers` to `/inventory`, locales in all six files. A list spec asserting the row count of `SELECT` statements does not grow with the page size (no N+1 guard runs in this repo yet — assert it in the spec).
+7. **E2E** — one Playwright spec: seed a reservation and an in-transit transfer, open `/inventory`, assert the Reserved and Incoming cells.
+
+Out of scope for this phase, recorded above: an Unavailable bucket; the seller-panel page.
+
## Constraints on Current Work
- **Don't call `StockTransfer.transfer` or `.receive`.** Both are gone. Moving stock between
@@ -703,6 +798,14 @@ All other existing transfers (with a real source location) become `status: 'rece
- **Don't create a separate "Stock Movements" admin SPA page.** Movement history is always inline on variant + stock location.
- **Don't receive without a stock receipt.** `Receive` is the only writer of `quantity_received` and of `received` movements against a transfer or an order; a delivery that is not a `Spree::StockReceipt` cannot be reconciled, corrected or audited.
- **Don't fold cost data onto `StockTransfer`.** Transfers don't have a unit cost — they move existing inventory between owned locations. Cost lives on `PurchaseOrderItem.unit_cost`.
+- **Never write `reserved_count` or `incoming_count` outside their named writers** (the table
+ under *StockLevel counters*). A workflow that changes a reservation, a purchase order or a
+ transfer and does not adjust the counter in the same transaction has desynchronized the page
+ from the ledger; `spree:stock:recount_levels` repairs it, but the writer is the bug.
+- **Never sum reserved or incoming at request time on a list.** Read the columns. The Quantifier
+ may keep computing reserved for a single variant's availability check; a list reads counters.
+- **Never present rejected delivery units as unavailable stock.** They are on the receipt, not
+ on the shelf.
- **Lot capture lives only on `Spree::FulfillmentLot` rows** — no `lot_number` strings on line items, orders, or movements. The Enterprise library layers on these rows (its allocation fills them); OSS never grows lot quantities, expiry, or allocation of its own.
## Open Questions
@@ -726,3 +829,4 @@ All other existing transfers (with a real source location) become `status: 'rece
- Depends on: `docs/plans/6.0-typed-stock-movements.md` (movement primitives)
- Depends on: `docs/plans/6.0-fulfillment-and-delivery.md` (Fulfillment writes `shipped`/`allocated`/`released` movements that show up alongside transfer/PO movements in the variant history)
- Related: `docs/plans/6.0-stock-reservations.md` (reservations are checkout-time holds, orthogonal to operational receives)
+- Phase 7 touch points: `spree/api/app/controllers/spree/api/v3/admin/stock_levels_controller.rb`, `…/serializers/…/admin/stock_level_serializer.rb`, `spree/core/app/models/concerns/spree/receivable_item.rb`, `spree/core/app/services/spree/stock_reservations/{reserve,release}.rb`, `spree/core/app/jobs/spree/stock_reservations/expire_job.rb`, `spree/core/app/workflows/spree/stock_receipts/recording.rb`
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 0287495c57..d03070b5ac 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,11 @@
+## 2026-09-10: Stock levels carry reserved and incoming as counters, and the Inventory page reads them
+
+**Context:** The dashboard's Inventory section (transfers, purchase orders, suppliers) had no view of the stock itself — no page answering "what do I have, where, and what is committed, held or on its way". The columns a merchant expects are Shopify's: on hand, committed, available, incoming. Spree already persists on hand (`count_on_hand`) and committed (`allocated_count`) but computed reserved at read time in `Stock::Quantifier` and had no notion of incoming at all, even though every purchase order and transfer now carries a `destination_location_id`.
+
+**Decision:** Two new counter-cache columns on `spree_stock_levels` — `reserved_count` and `incoming_count` — and a new phase in `6.0-inventory-operations.md` for the page that reads them. Counters, not computes: the page is a paginated list read many times a day, the inputs change through a small number of workflows, and the repo already trusts `allocated_count`, `fee_total` and `commission_total` the same way. **Each counter has exactly one writer path** — `Reserve`/`Release`/`ExpireJob` for reserved; `MarkOrdered`/`MarkDraft`/`Cancel`/`Update` on purchase orders, `MarkInTransit`/`Cancel` on transfers, and `StockReceipts::Recording` for both, for incoming — mirroring the movement-callback discipline that keeps `allocated_count` honest. A `spree:stock:recount_levels` task recomputes both from their sources, reports drift, and is the backfill. `Available` on the page is `count_on_hand − allocated_count − reserved_count`, the same figure the Quantifier already produces.
+
+**Consequences:** *Incoming* is `[expected − received − rejected, 0].max` per line, added to `Spree::ReceivableItem` as `#incoming` so the counter and the recount share one definition — `outstanding` alone still counts rejected units as awaited, and they are not coming. A transfer counts as incoming from **`in_transit`**, when `quantity_shipped` is written, not from `ready_to_ship`; that diverges from Shopify, which counts from creation, and is deliberate: nothing is moving yet. The receipt recorder already runs inside `receivable.with_lock`, so the incoming decrement is atomic with the on-hand increment. **Unavailable is out of scope.** Rejected delivery units are not it — they "exist only on the receipt" (the 2026-09-10 dock decision) and were never in the building, whereas Shopify's Unavailable is on-site stock held back; a true bucket would be a fourth counter with its own adjust action and reason vocabulary, and no reference validates it yet. The page is dashboard-only; the seller panel gets the same table under a forced seller scope as a follow-up, per the dashboard-is-the-reference rule. The earlier note that "rejected receipt units have no backing" was half right: the *count* is recorded, the *stock* is not.
+
## 2026-09-10: A delivery is a stock receipt — discrepancies get quantities, over-receipt gets a status, and a short order can be closed
**Context:** Comparing the shipped inventory operations against a multi-location omnichannel