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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add stock reservations to prevent overselling during checkout (#13978)
Damian Legawiec1594cab82b41
diff --git a/docs/developer/core-concepts/inventory.mdx b/docs/developer/core-concepts/inventory.mdxindex d250f59943..f496a3f72f 100644--- a/docs/developer/core-concepts/inventory.mdx+++ b/docs/developer/core-concepts/inventory.mdx@@ -3,6 +3,8 @@ title: Inventorydescription: Stock locations, stock items, stock movements, and inventory tracking---+import { Since } from '/snippets/since.mdx';+## OverviewEach [Variant](/developer/core-concepts/products#variants) has a `StockItem` that tracks its inventory at a specific location. A variant can have multiple stock items if it's available at multiple stock locations.@@ -11,6 +13,8 @@ When products are sold or returned, individual `InventoryUnit` records track eacAdding new inventory to an out-of-stock product that has backorders will first fill the backorders, then update the available count with the remainder.+During checkout, Spree holds stock with time-limited [Stock Reservations](#stock-reservations) to prevent two customers from buying the same last unit simultaneously.+### Inventory Model Diagram```mermaid@@ -52,14 +56,24 @@ erDiagraminteger shipment_id}+ StockReservation {+ integer quantity+ datetime expires_at+ integer stock_item_id+ integer line_item_id+ integer order_id+ }+StockLocation ||--o{ StockItem : "has many"StockLocation ||--o{ StockTransfer : "source"StockLocation ||--o{ StockTransfer : "destination"Variant ||--o{ StockItem : "has many"Variant ||--o{ InventoryUnit : "has many"StockItem ||--o{ StockMovement : "has many"+ StockItem ||--o{ StockReservation : "has many"StockTransfer ||--o{ StockMovement : "has many"Order ||--o{ InventoryUnit : "has many"+ Order ||--o{ StockReservation : "has many"Shipment ||--o{ InventoryUnit : "has many"```@@ -69,6 +83,7 @@ erDiagram- **Stock Movement** → Records changes to Stock Item quantities (purchases, returns, transfers)- **Stock Transfer** → Moves inventory between Stock Locations, creating Stock Movements at source and destination- **Inventory Unit** → Represents individual units in [Orders](/developer/core-concepts/orders) and [Shipments](/developer/core-concepts/shipments)+- **Stock Reservation** → Time-limited soft hold on a Stock Item during checkout, scoped to a specific Order and Line Item## Inventory Management@@ -153,6 +168,47 @@ Here's the list of attributes for the Stock Movement model:Stock Movements are crucial for maintaining accurate inventory levels and for historical tracking of inventory adjustments.+## Stock Reservations <Since version="5.5" />++Stock Reservations are a time-limited soft hold on stock during checkout. When a customer enters checkout, Spree holds the items in their cart for a limited time so other shoppers see reduced availability immediately. Two customers can no longer both pass the availability check on the same last unit only to have one of them fail at order completion.++### What changes for the storefront++Availability now subtracts the units other customers are holding in active checkouts. Whenever you read whether a variant is in stock — whether for a product page, cart line, or checkout summary — Spree returns the post-reservation number automatically. There's nothing for the storefront to compute and physical stock counts on each `StockItem` are never modified by reservations; reservations are an independent layer that's consulted at read time and cleaned up by background jobs.++### Lifecycle++| Trigger | Action |+|---|---|+| Customer enters checkout | A reservation is created for each line item with an expiry timestamp |+| Customer continues mutating the cart while in checkout | The expiry is pushed forward |+| Customer completes the order | The reservation is released; physical stock is decremented as before |+| Customer empties or abandons the cart | The reservation is released or expires automatically |++Reservations attach to each line item; when a line item or order is removed, the reservation goes with it.++### Configuration++| Setting | Default | Purpose |+|---|---|---|+| `Spree::Config[:stock_reservations_enabled]` | `true` | Global kill switch. When `false`, reservations are not created and availability ignores them — behavior matches pre-5.5. |+| `Spree::Config[:default_stock_reservation_ttl_minutes]` | `10` | Fallback hold duration when a Store doesn't override. |+| `store.preferred_stock_reservation_ttl_minutes` | inherits global | Per-Store override. |++TTL is a Store-level setting — it's a checkout-experience policy, not a warehouse property. A multi-location cart never has to merge conflicting TTLs from different warehouses.++### Insufficient stock during checkout++When a cart change in checkout would push the order beyond available stock, the change is rejected up front. The customer sees a validation error immediately, instead of progressing through payment only to fail at the final submit.++### Background expiry++Abandoned checkouts leave behind expired reservation rows. Spree provides a job to clean them up but does **not** auto-schedule it — your application's job runner needs to invoke it periodically (every minute is typical). See the [5.4 to 5.5 upgrade guide](/developer/upgrades/5.4-to-5.5#schedule-the-stock-reservations-expiry-job) for sidekiq-cron, solid_queue, and good_job snippets.++### Backorderable items++If a stock item is marked backorderable, it represents unlimited supply, so reservations are skipped entirely for that item. Availability is unaffected.+## Inventory UnitsAs we mentioned above, back-ordered, sold, or shipped products are stored as individual `InventoryUnit` objects so they can have relevant information attached to them.diff --git a/docs/developer/upgrades/5.4-to-5.5.mdx b/docs/developer/upgrades/5.4-to-5.5.mdxnew file mode 100644index 0000000000..7c4047ffdb--- /dev/null+++ b/docs/developer/upgrades/5.4-to-5.5.mdx@@ -0,0 +1,101 @@+---+title: Upgrading to Spree 5.5+description: This guide covers upgrading a Spree 5.4 application to Spree 5.5.+---++<Info>+ Before proceeding to upgrade, please ensure you're at [Spree 5.4](/developer/upgrades/5.3-to-5.4).+</Info>++## Upgrade steps++### Update gems++ ```bash+ bundle update+ ```++### Fetch and run missing migrations++ ```bash+ bin/rake spree:install:migrations && bin/rails db:migrate+ ```++### Schedule the Stock Reservations expiry job++Spree 5.5 introduces time-limited stock reservations during checkout to prevent two customers from buying the same last unit at the same time. Abandoned checkouts leave behind expired reservation rows, and Spree does **not** auto-schedule the cleanup — your application's job runner must run `Spree::StockReservations::ExpireJob` periodically (every minute is the recommended cadence).++If you skip this step, expired reservations accumulate in the table indefinitely. The Quantifier still ignores them at availability-check time (so customers see correct stock), but the table grows unbounded.++#### sidekiq-cron++```yaml+# config/sidekiq_cron.yml+expire_stock_reservations:+ cron: "* * * * *"+ class: "Spree::StockReservations::ExpireJob"+ queue: default+```++#### solid_queue++```yaml+# config/recurring.yml+expire_stock_reservations:+ schedule: every minute+ class: Spree::StockReservations::ExpireJob+```++#### good_job++```ruby+# config/initializers/good_job.rb+Rails.application.configure do+ config.good_job.cron = {+ expire_stock_reservations: {+ cron: '* * * * *',+ class: 'Spree::StockReservations::ExpireJob'+ }+ }+end+```++### (Optional) Tune the reservation TTL++The default reservation TTL is **10 minutes**. To override globally:++```ruby+# config/initializers/spree.rb+Spree::Config[:default_stock_reservation_ttl_minutes] = 15+```++To override per Store, set the preference on the Store record:++```ruby+store.update!(preferred_stock_reservation_ttl_minutes: 20)+```++The per-Store value, when set, takes precedence over the global default.++### (Optional) Disable Stock Reservations++Stock reservations are enabled by default. To opt out and revert to pre-5.5 behavior (no holds during checkout, Quantifier returns raw `count_on_hand`):++```ruby+# config/initializers/spree.rb+Spree::Config[:stock_reservations_enabled] = false+```++The Quantifier short-circuits before any reservation query when this is `false`, so there's no runtime cost and no table growth.++## Behavior changes worth knowing++### Cart changes during checkout can now fail with insufficient stock++When a customer is in checkout and tries to add an item, increase a quantity, or remove a line item, Spree now re-checks whether the cart still fits in available stock (subtracting what other customers are holding in their own active checkouts). If it doesn't, the change is rejected up front instead of silently completing and failing later at order submission.++Storefronts and custom integrations that act on the cart should expect this new failure path and surface the error to the customer.++### Storefront availability drops faster under contention++Other customers now see availability reduced by all active reservations, not just by completed orders. This is the intended fix to overselling — but if you have a real-time inventory dashboard that reads `count_on_hand` directly (rather than going through Spree's availability checks), you'll want to expose a "Reserved" axis to merchants so they can see in-checkout demand.diff --git a/docs/docs.json b/docs/docs.jsonindex 22e41a421d..beba20fa1d 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -358,6 +358,7 @@{"group": "Upgrade Guides","pages": [+ "developer/upgrades/5.4-to-5.5","developer/upgrades/5.3-to-5.4","developer/upgrades/5.2-to-5.3","developer/upgrades/5.1-to-5.2",diff --git a/docs/plans/6.0-stock-reservations.md b/docs/plans/6.0-stock-reservations.mdindex 5d3647d6ef..e3930f5e18 100644--- a/docs/plans/6.0-stock-reservations.md+++ b/docs/plans/6.0-stock-reservations.md@@ -1,10 +1,10 @@# Stock Reservations-**Status:** Design finalized, implementation not started-**Target:** Spree 6.0-**Depends on:** Cart/Order split (6.0-cart-order-split.md)+**Status:** Implementation in progress (5.5)+**Target:** Spree 5.5 (Store API + Admin API), refined in 6.0 (Cart/Order split integration, allocated_count term)+**Depends on:** None for 5.5. In 6.0: Cart/Order split (6.0-cart-order-split.md), Typed Stock Movements (6.0-typed-stock-movements.md)**Author:** Damian + Claude-**Last updated:** 2026-03-22+**Last updated:** 2026-05-01## Summary@@ -27,9 +27,10 @@ Every modern commerce platform solves this with time-limited reservations.- **New model `Spree::StockReservation`** — concrete FKs to `stock_item`, `line_item`, `order`. No polymorphism.- **`StockItem.count_on_hand` is never modified by reservations.** It only changes on order completion (decrement) or stock adjustment. Reservations are a soft hold computed at query time.-- **Available quantity = `count_on_hand - allocated_count - active_reservations`** — the `Quantifier` is updated to subtract both allocations (from 6.0-typed-stock-movements.md) and active reservations from physical stock. When Typed Stock Movements ships, `allocated_count` is included; before that, it's zero.+- **Available quantity = `count_on_hand - allocated_count - active_reservations`** — the `Quantifier` is updated to subtract both allocations (from 6.0-typed-stock-movements.md) and active reservations from physical stock. **In 5.5 the `allocated_count` term is omitted** — it lands with Typed Stock Movements in 6.0. The 5.5 formula is `count_on_hand - active_reservations`.+- **Store API only in 5.5.** Reservation create/extend/release hooks fire from Store API endpoints (`Spree::Api::V3::Storefront::*`) only. Legacy Rails storefront (`Spree::CheckoutController`) and v2 API are intentionally not wired. Other customers' availability still reflects reservations (Quantifier subtracts them globally) — they just can't create their own from non-v3 paths. Release-note this clearly.- **Configurable trigger** — `Spree::Config[:reserve_stock_on]` controls when reservations are created: `:checkout` (when entering checkout, default) or `:cart` (when adding to cart). Cart-level is more aggressive, checkout-level is the standard.-- **Configurable TTL per store** — `store.preferred_stock_reservation_ttl` (default: 10 minutes). Merchants can tune this based on their checkout complexity.+- **Configurable TTL per store, with global default** — `store.preferred_stock_reservation_ttl_minutes` overrides `Spree::Config[:default_stock_reservation_ttl_minutes]` (default: 10). Resolved by `Spree::StockReservation.ttl_for(order)`. **TTL deliberately lives on Store, not StockLocation** — it's a checkout-experience policy, not a warehouse property. A multi-location cart never has to merge conflicting TTLs from different warehouses. If future merchants need differentiation, the natural next move is splitting TTL by guest vs authenticated customer on the Store, not by location. BOPIS lead time belongs on `StockLocation#pickup_ready_in_minutes` (see `6.0-fulfillment-and-delivery.md`), which is a different concept.- **Reservations extend on activity** — each checkout interaction (address update, shipping selection, payment) resets `expires_at` to prevent expiry during active checkout.- **Background job expires reservations** — `Spree::StockReservations::ExpireJob` runs periodically, deletes expired records. Simple `DELETE WHERE expires_at < NOW()`.- **On order completion: reservation deleted, `count_on_hand` decremented** — the existing stock decrement logic stays, reservation is just cleaned up.@@ -66,7 +67,7 @@ class Spree::StockReservation < Spree.base_classenddef extend!(duration = nil)- duration ||= order.store.preferred_stock_reservation_ttl.minutes+ duration ||= order.store.preferred_stock_reservation_ttl_minutes.minutesupdate!(expires_at: Time.current + duration)end@@ -78,42 +79,40 @@ end### Quantifier changes+The same shape works for both 5.5 and 6.0. `Spree::StockItem#allocated_count` is a Ruby shim returning 0 in 5.5; 6.0 Typed Stock Movements (`6.0-typed-stock-movements.md`) replaces the shim with a real column updated by typed movements, and the Rails column accessor takes precedence over the method automatically. The formulas below continue to mean exactly what their names say through the transition.+```rubyclass Spree::Stock::Quantifier+ # Purchasable now: physical pool minus already-allocated units minus+ # active checkout reservations. Clamped at zero. Returns infinity for+ # variants that don't track inventory.def total_on_hand@total_on_hand ||= if variant.should_track_inventory?- available_stock - reserved_quantity- else- BigDecimal::INFINITY- end+ [available_stock - reserved_quantity, 0].max+ else+ BigDecimal::INFINITY+ endend- # Physical stock minus allocated (pending fulfillment)- # allocated_count comes from 6.0-typed-stock-movements.md (zero until that ships)+ # Physical pool minus already-allocated units, summed across the+ # variant's active stock items.def available_stockif association_loaded?stock_items.sum(&:available_count)- else+ elsif self.class.allocated_count_column?stock_items.sum('count_on_hand - allocated_count')+ else+ stock_items.sum(:count_on_hand)endend+ # Units currently held by active checkout reservations across the variant's+ # stock items. EXISTS-guarded so non-checkout traffic stays one query.def reserved_quantityreturn 0 unless Spree::Config[:stock_reservations_enabled]- @reserved_quantity ||= Spree::StockReservation- .active- .where(stock_item: stock_items)- .sum(:quantity)- end-- # Physical count without reservations or allocations (for admin/reporting)- def raw_count_on_hand- if association_loaded?- stock_items.sum(&:count_on_hand)- else- stock_items.sum(:count_on_hand)- end+ active_reservations = Spree::StockReservation.active.where(stock_item_id: stock_items.map(&:id))+ active_reservations.exists? ? active_reservations.sum(:quantity) : 0endend```@@ -129,7 +128,7 @@ module Spreedef call(order:)return success(order) unless Spree::Config[:stock_reservations_enabled]- ttl = order.store.preferred_stock_reservation_ttl.minutes+ ttl = order.store.preferred_stock_reservation_ttl_minutes.minutesexpires_at = Time.current + ttlApplicationRecord.transaction do@@ -207,7 +206,7 @@ module Spreedef call(order:)return success(order) unless Spree::Config[:stock_reservations_enabled]- ttl = order.store.preferred_stock_reservation_ttl.minutes+ ttl = order.store.preferred_stock_reservation_ttl_minutes.minutesexpires_at = Time.current + ttlSpree::StockReservation@@ -239,60 +238,55 @@ endScheduled via `sidekiq-cron` or `solid_queue` recurring task — runs every 1 minute.-### Integration points+### Integration points (5.5 — Store API only)-#### Checkout service (reserve on entering checkout)+**Hooks live in Store API controllers, not in core services.** Legacy `Spree::CheckoutController` and v2 API are not wired in 5.5.-```ruby-# In Spree::Checkout::Next or Spree::Checkout::Update-# When order transitions from 'cart' to 'address' (first checkout step):+#### Reserve on entering checkout-after_transition from: :cart do |order|- Spree::StockReservations::Reserve.call(order: order)-end+In `Spree::Api::V3::Storefront::CheckoutController#next` (or wherever the cart→address transition happens via Store API), after the successful state transition:++```ruby+Spree::StockReservations::Reserve.call(order: @order)```-With the Cart/Order split (6.0-cart-order-split.md), this happens in `Spree::Carts::Complete` when the cart converts to an order.+#### Extend on checkout activity-#### Checkout activity (extend on each step)+In every Store API checkout endpoint that mutates the order during checkout (`#update`, address selection, shipping selection, payment selection):```ruby-# In Spree::Carts::Update, after any successful step update:-Spree::StockReservations::Extend.call(order: order)+Spree::StockReservations::Extend.call(order: @order)```-#### Order completion (release reservation, decrement stock)+#### Release on order completion++In `Spree::Api::V3::Storefront::CheckoutController#complete` (or after the existing completion service), after the standard `count_on_hand` decrement runs:```ruby-# In Spree::Carts::Complete, after order is finalized:-# Existing stock decrement logic runs (InventoryUnit creation, count_on_hand decrement)-# Then clean up the reservation:-Spree::StockReservations::Release.call(order: order)+Spree::StockReservations::Release.call(order: @order)```-#### Cart emptied / order canceled+#### Release on cart empty / order cancel++In `Spree::Api::V3::Storefront::CartController#empty` and the order cancel endpoint:```ruby-# In Spree::Carts::Empty and order cancellation:-Spree::StockReservations::Release.call(order: order)+Spree::StockReservations::Release.call(order: @order)```-#### Line item quantity changed+#### Re-reserve on cart line item changes++In `Spree::Api::V3::Storefront::CartItemsController#create`, `#update`, `#destroy` — only **if** the order is past the `cart` state (i.e., a reservation already exists or should exist):```ruby-# In Spree::Cart::SetQuantity, after quantity update:-# Re-run reservation to adjust quantities-Spree::StockReservations::Reserve.call(order: order)+Spree::StockReservations::Reserve.call(order: @order) unless @order.cart? || @order.complete? || @order.canceled?```-#### Line item removed+`LineItem` destroy auto-cleans the reservation via the `has_many :stock_reservations, dependent: :destroy` association added to `LineItem`, `Order`, and `StockItem` in Phase 1.-```ruby-# In Spree::Cart::RemoveLineItem:-# Reservation for that line item auto-deleted via dependent: :destroy on LineItem-# Or explicit release:-Spree::StockReservation.where(line_item: line_item).delete_all-```+### Integration points (6.0)++With the Cart/Order split (6.0-cart-order-split.md), reserve fires from `Spree::Carts::Complete` when the cart converts to an order, extend fires from `Spree::Carts::Update`, and release fires from `Spree::Carts::Empty` and order cancellation. This consolidates the per-controller hooks above into core services.### Store API@@ -335,7 +329,7 @@ Spree::Config[:stock_reservations_enabled] = true # default: trueSpree::Config[:reserve_stock_on] = :checkout # :checkout or :cart# Per-store TTL (minutes)-store.preferred_stock_reservation_ttl = 10 # default: 10+store.preferred_stock_reservation_ttl_minutes = 10 # default: 10```### Database schema@@ -365,30 +359,35 @@ endThis is purely additive — no existing tables or models are modified (beyond Quantifier logic).-### Phase 1: Model + migration + services+### Spree 5.5++#### Phase 1: Model + migration + services- Create `StockReservation` model and table- Create `Reserve`, `Release`, `Extend`, `ExpireJob` services-- Update `Quantifier` to subtract reservations+- Update `Quantifier` to subtract reservations (5.5 formula: `count_on_hand - reserved_quantity`)- Add configuration options+- Add `dependent: :destroy` from `LineItem` and `Order` to clean up reservations-### Phase 2: Checkout integration+#### Phase 2: Store API integration-- Wire `Reserve` into checkout entry-- Wire `Extend` into checkout step updates-- Wire `Release` into order completion and cancellation-- Add `ExpireJob` to recurring job schedule+- Wire `Reserve` into Store API checkout next/transition endpoint+- Wire `Extend` into Store API checkout update endpoints+- Wire `Release` into Store API order complete + cart empty + order cancel endpoints+- Re-`Reserve` on cart item create/update/destroy when order is in checkout+- Add `ExpireJob` to the standard Spree job schedule (sidekiq-cron / solid_queue)-### Phase 3: API + admin visibility+#### Phase 3: API surface-- Add `reserved_quantity` / `available_quantity` to variant serializer-- Add admin API for stock reservations-- Admin dashboard: show reservations on stock management page+- Add `reserved_quantity` / `available_quantity` to Store variant serializer+- Add `Spree::Api::V3::Admin::StockReservationsController` (read-only index/show)+- Admin SPA consumes the Admin API; legacy Rails admin gets nothing in 5.5-### Phase 4: Cart-level reservation (optional)+### Spree 6.0-- If `reserve_stock_on: :cart`, wire `Reserve` into `Cart::AddItem` and `Cart::SetQuantity`-- More aggressive but prevents add-to-cart for truly out-of-stock items+- Move integration hooks from Store API controllers into `Spree::Carts::Complete`, `Spree::Carts::Update`, `Spree::Carts::Empty`+- Update Quantifier formula to include `allocated_count` (depends on Typed Stock Movements)+- Cart-level reservation option: if `reserve_stock_on: :cart`, wire `Reserve` into `Cart::AddItem` and `Cart::SetQuantity`## Constraints on Current Workdiff --git a/packages/admin-sdk/src/types/generated/StockItem.ts b/packages/admin-sdk/src/types/generated/StockItem.tsindex 2c185094a1..f26d39bca5 100644--- a/packages/admin-sdk/src/types/generated/StockItem.ts+++ b/packages/admin-sdk/src/types/generated/StockItem.ts@@ -1,4 +1,4 @@-// Typelizer digest 53765d02650cb44b65558ad8ba2da6ab+// Typelizer digest 16c2fb7a45f1b9afef6032d5fd441d1c//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {StockLocation, Variant} from '@/types'@@ -12,6 +12,8 @@ interface StockItem {metadata: Record<string, unknown>;created_at: string;updated_at: string;+ allocated_count: number;+ available_count: number;stock_location?: StockLocation;variant?: Variant;}diff --git a/packages/admin-sdk/src/types/generated/StockReservation.ts b/packages/admin-sdk/src/types/generated/StockReservation.tsnew file mode 100644index 0000000000..1faec8fd92--- /dev/null+++ b/packages/admin-sdk/src/types/generated/StockReservation.ts@@ -0,0 +1,19 @@+// Typelizer digest 1e93f4cccfef1a17e1cf1c9a519c28ee+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface StockReservation {+ id: string;+ stock_item_id: string;+ line_item_id: string;+ order_id: string;+ variant_id: string | null;+ stock_location_id: string | null;+ quantity: number;+ expires_at: string;+ active: boolean;+ created_at: string;+ updated_at: string;+}++export default StockReservation;diff --git a/packages/admin-sdk/src/types/generated/Variant.ts b/packages/admin-sdk/src/types/generated/Variant.tsindex 2feae447c7..284d999846 100644--- a/packages/admin-sdk/src/types/generated/Variant.ts+++ b/packages/admin-sdk/src/types/generated/Variant.ts@@ -1,4 +1,4 @@-// Typelizer digest 050e17e8f5983d79e65407dd4a655f96+// Typelizer digest c145cf72cb6896a450381b78fe593340//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {Price, PriceHistory, Media, OptionValue, CustomField} from '@/types'@@ -27,13 +27,15 @@ interface Variant {prior_price?: PriceHistory | null;metadata: Record<string, unknown>;position: number;- total_on_hand: number | null;tax_category_id: string | null;cost_price: string | null;cost_currency: string | null;deleted_at: string | null;created_at: string;updated_at: string;+ available_stock: number | null;+ reserved_quantity: number;+ total_on_hand: number | null;product_name: string;display_price: string | null;prices?: Array<Price>;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex 73176f42f6..e7994c53d7 100644--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@ -39,6 +39,7 @@ export type { default as Role } from './Role'export type { default as State } from './State'export type { default as StockItem } from './StockItem'export type { default as StockLocation } from './StockLocation'+export type { default as StockReservation } from './StockReservation'export type { default as StoreCreditCategory } from './StoreCreditCategory'export type { default as StoreCredit } from './StoreCredit'export type { default as Store } from './Store'diff --git a/packages/sdk/src/types/generated/StockReservation.ts b/packages/sdk/src/types/generated/StockReservation.tsnew file mode 100644index 0000000000..cda7e6425c--- /dev/null+++ b/packages/sdk/src/types/generated/StockReservation.ts@@ -0,0 +1,9 @@+// Typelizer digest c0f825e5e4198b0f39d2cf85d90a37af+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface StockReservation {+ id: string;+}++export default StockReservation;diff --git a/packages/sdk/src/types/generated/index.ts b/packages/sdk/src/types/generated/index.tsindex fe870afe33..daef84dbef 100644--- a/packages/sdk/src/types/generated/index.ts+++ b/packages/sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest a5578d45f5defe3852c905a88af3d772+// Typelizer digest 9c49cd3dee2c09b5c1574d5f2758064e//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'@@ -42,6 +42,7 @@ export type { default as ReturnAuthorization } from './ReturnAuthorization'export type { default as ReturnItem } from './ReturnItem'export type { default as State } from './State'export type { default as StockLocation } from './StockLocation'+export type { default as StockReservation } from './StockReservation'export type { default as StoreCredit } from './StoreCredit'export type { default as Variant } from './Variant'export type { default as WishlistItem } from './WishlistItem'diff --git a/packages/sdk/src/zod/generated/StockReservation.ts b/packages/sdk/src/zod/generated/StockReservation.tsnew file mode 100644index 0000000000..cb2b2dfec7--- /dev/null+++ b/packages/sdk/src/zod/generated/StockReservation.ts@@ -0,0 +1,8 @@+// This file is auto-generated. Do not edit directly.+import { z } from 'zod';++export const StockReservationSchema = z.object({+ id: z.string(),+});++export type StockReservation = z.infer<typeof StockReservationSchema>;diff --git a/packages/sdk/src/zod/generated/index.ts b/packages/sdk/src/zod/generated/index.tsindex f9d1395a1e..9089727062 100644--- a/packages/sdk/src/zod/generated/index.ts+++ b/packages/sdk/src/zod/generated/index.ts@@ -40,6 +40,7 @@ export { ReturnAuthorizationSchema, type ReturnAuthorization } from './ReturnAutexport { ReturnItemSchema, type ReturnItem } from './ReturnItem';export { StateSchema, type State } from './State';export { StockLocationSchema, type StockLocation } from './StockLocation';+export { StockReservationSchema, type StockReservation } from './StockReservation';export { StoreCreditSchema, type StoreCredit } from './StoreCredit';export { VariantSchema, type Variant } from './Variant';export { WishlistSchema, type Wishlist } from './Wishlist';diff --git a/spree/api/app/controllers/spree/api/v3/admin/stock_reservations_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/stock_reservations_controller.rbnew file mode 100644index 0000000000..b52f86325d--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/stock_reservations_controller.rb@@ -0,0 +1,29 @@+module Spree+ module Api+ module V3+ module Admin+ class StockReservationsController < ResourceController+ scoped_resource :stock++ protected++ def model_class+ Spree::StockReservation+ end++ def serializer_class+ Spree.api.admin_stock_reservation_serializer+ end++ def scope+ Spree::StockReservation.for_store(current_store)+ end++ def collection_includes+ [{ stock_item: [:variant, :stock_location], line_item: [], order: [] }]+ end+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_item_serializer.rbindex 91d544501b..3ff1aa572e 100644--- a/spree/api/app/serializers/spree/api/v3/admin/stock_item_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_item_serializer.rb@@ -3,11 +3,23 @@ module Spreemodule V3module Adminclass StockItemSerializer < V3::StockItemSerializer- typelize metadata: 'Record<string, unknown>'+ typelize metadata: 'Record<string, unknown>',+ allocated_count: :number, available_count: :numberattributes :metadata,created_at: :iso8601, updated_at: :iso8601+ # Units already allocated to pending shipments. Always 0 in 5.5;+ # 6.0 Typed Stock Movements wires it up.+ attribute :allocated_count do |stock_item|+ stock_item.allocated_count.to_i+ end++ # Physical stock minus allocated units (per stock_item).+ attribute :available_count do |stock_item|+ stock_item.available_count.to_i+ end+one :stock_location,resource: Spree.api.admin_stock_location_serializer,if: proc { expand?('stock_location') }diff --git a/spree/api/app/serializers/spree/api/v3/admin/stock_reservation_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/stock_reservation_serializer.rbnew file mode 100644index 0000000000..a361b7de43--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/stock_reservation_serializer.rb@@ -0,0 +1,46 @@+module Spree+ module Api+ module V3+ module Admin+ class StockReservationSerializer < V3::StockReservationSerializer+ typelize stock_item_id: :string,+ line_item_id: :string,+ order_id: :string,+ variant_id: [:string, nullable: true],+ stock_location_id: [:string, nullable: true],+ quantity: :number,+ expires_at: :string,+ active: :boolean++ attribute :stock_item_id do |reservation|+ reservation.stock_item.prefixed_id+ end++ attribute :line_item_id do |reservation|+ reservation.line_item.prefixed_id+ end++ attribute :order_id do |reservation|+ reservation.order.prefixed_id+ end++ attribute :variant_id do |reservation|+ reservation.stock_item&.variant&.prefixed_id+ end++ attribute :stock_location_id do |reservation|+ reservation.stock_item&.stock_location&.prefixed_id+ end++ attributes :quantity, expires_at: :iso8601++ attribute :active do |reservation|+ reservation.active?+ end++ attributes created_at: :iso8601, updated_at: :iso8601+ end+ end+ end+ end+enddiff --git a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rbindex 99cd877ddc..fdc65de4b3 100644--- a/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/variant_serializer.rb@@ -10,14 +10,30 @@ module Spreetypelize product_name: :string, display_price: [:string, nullable: true],position: :number, tax_category_id: [:string, nullable: true],cost_price: [:string, nullable: true], cost_currency: [:string, nullable: true],- total_on_hand: [:number, nullable: true],+ available_stock: [:number, nullable: true],+ reserved_quantity: :number, total_on_hand: [:number, nullable: true],deleted_at: [:string, nullable: true],metadata: 'Record<string, unknown>'# Admin-only attributes- attributes :metadata, :position, :total_on_hand, :tax_category_id, :cost_price, :cost_currency, deleted_at: :iso8601,+ attributes :metadata, :position, :tax_category_id, :cost_price, :cost_currency, deleted_at: :iso8601,created_at: :iso8601, updated_at: :iso8601+ # Physical pool minus already-allocated units. In 5.5 allocated_count+ # is always 0, so this equals SUM(stock_items.count_on_hand).+ attribute :available_stock do |variant|+ variant.available_stock.to_i if variant.should_track_inventory?+ end++ attribute :reserved_quantity do |variant|+ variant.reserved_quantity.to_i+ end++ # Purchasable now: available_stock minus active reservations.+ attribute :total_on_hand do |variant|+ variant.total_on_hand.to_i if variant.should_track_inventory?+ end+attribute :product_name do |variant|variant.product&.nameenddiff --git a/spree/api/app/serializers/spree/api/v3/stock_reservation_serializer.rb b/spree/api/app/serializers/spree/api/v3/stock_reservation_serializer.rbnew file mode 100644index 0000000000..4142c83221--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/stock_reservation_serializer.rb@@ -0,0 +1,10 @@+module Spree+ module Api+ module V3+ # Minimal base; admin extends with full fields. Reservations have no+ # customer-facing exposure today.+ class StockReservationSerializer < BaseSerializer+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex a4ca083805..adc6a58dd8 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -171,6 +171,9 @@ Spree::Core::Engine.add_routes do# Stock Locationsresources :stock_locations++ # Stock Reservations+ resources :stock_reservations, only: [:index, :show]# Payment Methodsresources :payment_methods, only: [:index, :show]diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 3182ec2e68..5a7fa59eca 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -153,6 +153,7 @@ module Spreereturn_item_serializer: 'Spree::Api::V3::ReturnItemSerializer',stock_item_serializer: 'Spree::Api::V3::StockItemSerializer',stock_movement_serializer: 'Spree::Api::V3::StockMovementSerializer',+ stock_reservation_serializer: 'Spree::Api::V3::StockReservationSerializer',stock_transfer_serializer: 'Spree::Api::V3::StockTransferSerializer',# v3 admin serializers (API v3 Admin)@@ -189,6 +190,7 @@ module Spreeadmin_shipping_method_serializer: 'Spree::Api::V3::Admin::DeliveryMethodSerializer',admin_delivery_method_serializer: 'Spree::Api::V3::Admin::DeliveryMethodSerializer',admin_stock_location_serializer: 'Spree::Api::V3::Admin::StockLocationSerializer',+ admin_stock_reservation_serializer: 'Spree::Api::V3::Admin::StockReservationSerializer',admin_shipping_rate_serializer: 'Spree::Api::V3::Admin::DeliveryRateSerializer',admin_delivery_rate_serializer: 'Spree::Api::V3::Admin::DeliveryRateSerializer',admin_payment_method_serializer: 'Spree::Api::V3::Admin::PaymentMethodSerializer',diff --git a/spree/api/spec/controllers/spree/api/v3/admin/stock_reservations_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/stock_reservations_controller_spec.rbnew file mode 100644index 0000000000..97fd05a531--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/stock_reservations_controller_spec.rb@@ -0,0 +1,70 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::StockReservationsController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:order) { create(:order, store: store) }+ let(:other_order) { create(:order, store: create(:store)) }++ let!(:reservation) { create(:stock_reservation, order: order, expires_at: 5.minutes.from_now) }+ let!(:other_store_reservation) { create(:stock_reservation, order: other_order, expires_at: 5.minutes.from_now) }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ subject { get :index, as: :json }++ it 'returns reservations scoped to the current store' do+ subject+ expect(response).to have_http_status(:ok)+ ids = json_response['data'].map { |r| r['id'] }+ expect(ids).to include(reservation.prefixed_id)+ expect(ids).not_to include(other_store_reservation.prefixed_id)+ end++ it 'serializes reservation with prefixed associations and active flag' do+ subject+ record = json_response['data'].find { |r| r['id'] == reservation.prefixed_id }+ expect(record['stock_item_id']).to eq(reservation.stock_item.prefixed_id)+ expect(record['line_item_id']).to eq(reservation.line_item.prefixed_id)+ expect(record['order_id']).to eq(reservation.order.prefixed_id)+ expect(record['variant_id']).to eq(reservation.stock_item.variant.prefixed_id)+ expect(record['stock_location_id']).to eq(reservation.stock_item.stock_location.prefixed_id)+ expect(record['quantity']).to eq(reservation.quantity)+ expect(record['active']).to be(true)+ end+ end++ describe 'GET #show' do+ subject { get :show, params: { id: reservation.prefixed_id }, as: :json }++ it 'returns the reservation' do+ subject+ expect(response).to have_http_status(:ok)+ expect(json_response['id']).to eq(reservation.prefixed_id)+ end++ it 'returns 404 for a reservation in another store' do+ get :show, params: { id: other_store_reservation.prefixed_id }, as: :json+ expect(response).to have_http_status(:not_found)+ end+ end++ describe 'write actions are not routed' do+ it 'POST #create has no route' do+ expect { post :create, as: :json }.to raise_error(ActionController::UrlGenerationError)+ end++ it 'PATCH #update has no route' do+ expect { patch :update, params: { id: reservation.prefixed_id }, as: :json }+ .to raise_error(ActionController::UrlGenerationError)+ end++ it 'DELETE #destroy has no route' do+ expect { delete :destroy, params: { id: reservation.prefixed_id }, as: :json }+ .to raise_error(ActionController::UrlGenerationError)+ end+ end+enddiff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rbindex 0badeb47c9..26cf600db4 100644--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb@@ -576,6 +576,55 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller doexpect(response).to have_http_status(:ok)expect(json_response['current_step']).to eq('payment')end++ context 'stock reservations' do+ let(:address_params) do+ {+ first_name: 'Buyer', last_name: 'McGee',+ address1: '1 Test St', city: 'New York',+ postal_code: '10001', country_iso: 'US', state_abbr: 'NY',+ phone: '555-0100'+ }+ end++ before do+ order.line_items.first.variant.stock_items.first.update!(backorderable: false)+ order.line_items.first.variant.stock_items.first.set_count_on_hand(20)+ end++ it 'creates a reservation when the cart leaves the cart state' do+ order.update!(email: '[email protected]')++ expect {+ patch :update, params: { id: order.prefixed_id, shipping_address: address_params }+ }.to change { Spree::StockReservation.where(order_id: order.id).count }.by_at_least(1)+ end++ it 'extends an existing reservation on subsequent in-checkout updates' do+ order.update!(email: '[email protected]')+ patch :update, params: { id: order.prefixed_id, shipping_address: address_params }+ original_expiry = Spree::StockReservation.where(order_id: order.id).maximum(:expires_at)++ Timecop.freeze(2.minutes.from_now) do+ patch :update, params: { id: order.prefixed_id, customer_note: 'please ring bell' }+ end++ expect(Spree::StockReservation.where(order_id: order.id).maximum(:expires_at)).to be > original_expiry+ end++ context 'when stock_reservations_enabled is false' do+ before { Spree::Config[:stock_reservations_enabled] = false }+ after { Spree::Config[:stock_reservations_enabled] = true }++ it 'does not create reservations' do+ order.update!(email: '[email protected]')++ expect {+ patch :update, params: { id: order.prefixed_id, shipping_address: address_params }+ }.not_to change { Spree::StockReservation.count }+ end+ end+ endenddescribe 'PATCH #associate' do@@ -688,6 +737,23 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller doexpect(response).to have_http_status(:no_content)end++ it 'removes any stock reservations belonging to the cart' do+ line_item = cart.line_items.first+ line_item.variant.stock_items.first.update!(backorderable: false)+ line_item.variant.stock_items.first.set_count_on_hand(20)+ create(+ :stock_reservation,+ stock_item: line_item.variant.stock_items.first,+ line_item: line_item,+ order: cart,+ quantity: line_item.quantity,+ expires_at: 5.minutes.from_now+ )++ expect { delete :destroy, params: { id: cart.prefixed_id } }+ .to change { Spree::StockReservation.where(order_id: cart.id).count }.from(1).to(0)+ endendcontext 'with JWT authentication' do@@ -723,6 +789,25 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller doexpect(order.reload.state).to eq('complete')end+ it 'releases stock reservations on successful completion' do+ create(:payment, order: order, amount: order.total, state: 'checkout')+ order.shipments.each { |s| s.update_column(:state, 'ready') }+ line_item = order.line_items.first+ line_item.variant.stock_items.first.update!(backorderable: false)+ line_item.variant.stock_items.first.set_count_on_hand(20)+ create(+ :stock_reservation,+ stock_item: line_item.variant.stock_items.first,+ line_item: line_item,+ order: order,+ quantity: line_item.quantity,+ expires_at: 5.minutes.from_now+ )++ expect { post :complete, params: { id: order.prefixed_id } }+ .to change { Spree::StockReservation.where(order_id: order.id).count }.from(1).to(0)+ end+context 'when order cannot be completed' dolet(:incomplete_order) { create(:order_with_line_items, user: user, store: store, state: 'address') }diff --git a/spree/core/app/jobs/spree/stock_reservations/expire_job.rb b/spree/core/app/jobs/spree/stock_reservations/expire_job.rbnew file mode 100644index 0000000000..1996318720--- /dev/null+++ b/spree/core/app/jobs/spree/stock_reservations/expire_job.rb@@ -0,0 +1,11 @@+module Spree+ module StockReservations+ class ExpireJob < Spree::BaseJob+ queue_as Spree.queues.stock_reservations++ def perform+ Spree::StockReservation.expired.in_batches(of: 1_000).delete_all+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/api_key.rb b/spree/core/app/models/spree/api_key.rbindex d7d720f0f2..d31e125c18 100644--- a/spree/core/app/models/spree/api_key.rb+++ b/spree/core/app/models/spree/api_key.rb@@ -18,6 +18,7 @@ module Spreeread_refunds write_refundsread_gift_cards write_gift_cardsread_store_credits write_store_credits+ read_stock write_stockread_categories write_categoriesread_custom_field_definitions write_custom_field_definitionsread_exports write_exportsdiff --git a/spree/core/app/models/spree/line_item.rb b/spree/core/app/models/spree/line_item.rbindex 639292ab57..bdc64d6d1a 100644--- a/spree/core/app/models/spree/line_item.rb+++ b/spree/core/app/models/spree/line_item.rb@@ -24,6 +24,7 @@ module Spreehas_many :inventory_units, class_name: 'Spree::InventoryUnit', inverse_of: :line_item, dependent: :destroyhas_many :shipments, through: :inventory_units, source: :shipmenthas_many :digital_links, dependent: :destroy+ has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :line_item, dependent: :destroybefore_validation :copy_pricebefore_validation :copy_tax_categorydiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 72d28bc483..3dd45d065e 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -174,6 +174,7 @@ module Spreehas_many :customer_returns, class_name: 'Spree::CustomerReturn', through: :return_authorizationshas_many :line_item_adjustments, through: :line_items, source: :adjustmentshas_many :inventory_units, inverse_of: :order, class_name: 'Spree::InventoryUnit'+ has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :order, dependent: :destroyhas_many :return_items, through: :inventory_units, class_name: 'Spree::ReturnItem'has_many :variants, through: :line_itemshas_many :products, through: :variants@@ -369,6 +370,13 @@ module Spreecompleted_at.present?end+ # True when the order is mid-checkout: past the `cart` state but not yet+ # completed or canceled. Used by stock reservation hooks and any flow+ # that should only run during the active checkout phase.+ def in_checkout?+ !cart? && !complete? && !canceled?+ end+def draft?status == 'draft'enddiff --git a/spree/core/app/models/spree/stock/quantifier.rb b/spree/core/app/models/spree/stock/quantifier.rbindex b0c24a1e02..9690a06078 100644--- a/spree/core/app/models/spree/stock/quantifier.rb+++ b/spree/core/app/models/spree/stock/quantifier.rb@@ -8,18 +8,57 @@ module Spree@stock_location = stock_locationend+ # Units a customer can purchase right now: physical pool minus+ # already-allocated units minus active checkout reservations. Clamped+ # at zero so callers never see a negative count.+ #+ # Returns +BigDecimal::INFINITY+ when the variant does not track+ # inventory (effectively unlimited supply).+ #+ # @return [Integer, BigDecimal] purchasable quantity, or +INFINITY+def total_on_hand@total_on_hand ||= if variant.should_track_inventory?- if association_loaded?- stock_items.sum(&:count_on_hand)- else- stock_items.sum(:count_on_hand)- end+ [available_stock - reserved_quantity, 0].maxelseBigDecimal::INFINITYendend+ # Physical pool minus already-allocated units, summed across the+ # variant's active stock items.+ #+ # In Spree 5.5 {Spree::StockItem#allocated_count} is a Ruby shim that+ # always returns 0, so this equals +SUM(count_on_hand)+. In 6.0+ # (Typed Stock Movements) +allocated_count+ becomes a real column and+ # the SQL path subtracts it natively.+ #+ # @return [Integer] units available before checkout reservations+ def available_stock+ if association_loaded?+ stock_items.sum(&:available_count)+ elsif self.class.allocated_count_column?+ stock_items.sum('count_on_hand - allocated_count')+ else+ stock_items.sum(:count_on_hand)+ end+ end++ # Units currently held by active checkout reservations across the+ # variant's stock items. Returns 0 when stock reservations are+ # globally disabled.+ #+ # Short-circuits the SUM query with an EXISTS check so non-checkout+ # product list traffic stays at one query per variant.+ #+ # @return [Integer]+ def reserved_quantity+ return @reserved_quantity if defined?(@reserved_quantity)+ return @reserved_quantity = 0 unless Spree::Config[:stock_reservations_enabled]++ active_reservations = Spree::StockReservation.active.where(stock_item_id: stock_item_ids)+ @reserved_quantity = active_reservations.exists? ? active_reservations.sum(:quantity) : 0+ end+def backorderable?@backorderable ||= stock_items.any?(&:backorderable)end@@ -32,8 +71,23 @@ module Spree@stock_items ||= scope_to_location(variant.stock_items)end+ # Memoized schema check so {#available_stock} doesn't introspect the+ # column list on every call. Flips from false → true when 6.0 Typed+ # Stock Movements adds the `allocated_count` column.+ #+ # @return [Boolean]+ def self.allocated_count_column?+ return @allocated_count_column if defined?(@allocated_count_column)++ @allocated_count_column = Spree::StockItem.connection.column_exists?(:spree_stock_items, :allocated_count)+ end+private+ def stock_item_ids+ @stock_item_ids ||= association_loaded? ? stock_items.map(&:id) : stock_items.pluck(:id)+ end+def association_loaded?variant.association(:stock_items).loaded?enddiff --git a/spree/core/app/models/spree/stock_item.rb b/spree/core/app/models/spree/stock_item.rbindex 6df57dc51c..a89ccd8ddf 100644--- a/spree/core/app/models/spree/stock_item.rb+++ b/spree/core/app/models/spree/stock_item.rb@@ -15,6 +15,7 @@ module Spreebelongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'endhas_many :stock_movements, inverse_of: :stock_item+ has_many :stock_reservations, class_name: 'Spree::StockReservation', inverse_of: :stock_item, dependent: :destroyvalidates :stock_location, :variant, presence: truevalidates :variant_id, uniqueness: { scope: :stock_location_id }, unless: :deleted_at@@ -64,6 +65,28 @@ module Spreein_stock? || backorderable?end+ # Units already allocated to pending shipments at this stock item.+ #+ # Always returns 0 in Spree 5.5. The 6.0 Typed Stock Movements plan+ # (see docs/plans/6.0-typed-stock-movements.md) adds an indexed+ # `allocated_count` column updated by typed movements (`allocated`,+ # `released`, `shipped`); the Rails column accessor then takes+ # precedence over this method automatically.+ #+ # @return [Integer]+ def allocated_count+ 0+ end++ # Physical stock minus allocated units at this stock item. Distinct from+ # {Spree::Stock::Quantifier#available_stock}, which sums this across all+ # stock items belonging to a variant.+ #+ # @return [Integer]+ def available_count+ count_on_hand - allocated_count+ end+def reduce_count_on_hand_to_zeroset_count_on_hand(0) if count_on_hand > 0enddiff --git a/spree/core/app/models/spree/stock_reservation.rb b/spree/core/app/models/spree/stock_reservation.rbnew file mode 100644index 0000000000..7dc9f86132--- /dev/null+++ b/spree/core/app/models/spree/stock_reservation.rb@@ -0,0 +1,38 @@+module Spree+ class StockReservation < Spree.base_class+ has_prefix_id :res++ publishes_lifecycle_events++ belongs_to :stock_item, class_name: 'Spree::StockItem', inverse_of: :stock_reservations+ belongs_to :line_item, class_name: 'Spree::LineItem', inverse_of: :stock_reservations+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :stock_reservations++ validates :stock_item, :line_item, :order, :quantity, :expires_at, presence: true+ validates :quantity, numericality: { greater_than: 0, only_integer: true }+ validates :line_item_id, uniqueness: { scope: :stock_item_id }++ scope :active, -> { where('spree_stock_reservations.expires_at > ?', Time.current) }+ scope :expired, -> { where('spree_stock_reservations.expires_at <= ?', Time.current) }+ scope :for_order, ->(order) { where(order_id: order.id) }+ scope :for_store, ->(store) {+ joins(:order).where(spree_orders: { store_id: store.id })+ }++ self.whitelisted_ransackable_attributes = %w[stock_item_id line_item_id order_id quantity expires_at]+ self.whitelisted_ransackable_associations = %w[stock_item line_item order]++ def active?+ expires_at > Time.current+ end++ # Resolves the reservation TTL: per-Store preference if set, otherwise+ # the global Spree::Config[:default_stock_reservation_ttl_minutes]. Falls+ # back to 10 minutes if both are unset (e.g. early-boot / fixture state).+ def self.ttl_for(order)+ minutes = order&.store&.preferred_stock_reservation_ttl_minutes+ minutes = Spree::Config[:default_stock_reservation_ttl_minutes] if minutes.blank?+ minutes.to_i.then { |m| m > 0 ? m : 10 }.minutes+ end+ end+enddiff --git a/spree/core/app/models/spree/stock_reservations/insufficient_stock_error.rb b/spree/core/app/models/spree/stock_reservations/insufficient_stock_error.rbnew file mode 100644index 0000000000..2a11b76035--- /dev/null+++ b/spree/core/app/models/spree/stock_reservations/insufficient_stock_error.rb@@ -0,0 +1,12 @@+module Spree+ module StockReservations+ class InsufficientStockError < StandardError+ attr_reader :line_item++ def initialize(line_item, message)+ @line_item = line_item+ super(message)+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex eb2e76ae7a..3da8bba78c 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -46,6 +46,7 @@ module Spree# Checkout preferencespreference :guest_checkout, :boolean, default: truepreference :special_instructions_enabled, :boolean, default: false+ preference :stock_reservation_ttl_minutes, :integer, default: 10# Address preferencespreference :company_field_enabled, :boolean, default: false# digital assets preferences@@ -121,6 +122,7 @@ module Spreeendvalidates :preferred_digital_asset_authorized_clicks, numericality: { only_integer: true, greater_than: 0 }validates :preferred_digital_asset_authorized_days, numericality: { only_integer: true, greater_than: 0 }+ validates :preferred_stock_reservation_ttl_minutes, numericality: { only_integer: true, greater_than: 0 }validates :mail_from_address, email: { allow_blank: false }# FIXME: we should remove this condition in v5if !ENV['SPREE_DISABLE_DB_CONNECTION'] &&diff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex 8c92fb028b..9c4481a974 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -583,7 +583,7 @@ module Spree@on_sale ||= price_in(currency)&.discounted?end- delegate :total_on_hand, :can_supply?, to: :quantifier+ delegate :total_on_hand, :available_stock, :reserved_quantity, :can_supply?, to: :quantifieralias is_backorderable? backorderable?diff --git a/spree/core/app/services/spree/cart/add_item.rb b/spree/core/app/services/spree/cart/add_item.rbindex 86ebc137ed..092fbbbe3c 100644--- a/spree/core/app/services/spree/cart/add_item.rb+++ b/spree/core/app/services/spree/cart/add_item.rb@@ -6,6 +6,7 @@ module Spreedef call(order:, variant:, quantity: nil, metadata: {}, public_metadata: {}, private_metadata: {}, options: {})ApplicationRecord.transaction dorun :add_to_line_item+ run :handle_stock_reservationsrun Spree.cart_recalculate_serviceendend@@ -48,6 +49,15 @@ module Spree::Spree::TaxRate.adjust(order, [line_item]) if line_item_createdsuccess(order: order, line_item: line_item, line_item_created: line_item_created, options: options)end++ def handle_stock_reservations(order:, line_item:, line_item_created:, options:)+ if order.in_checkout?+ result = Spree::StockReservations::Reserve.call(order: order)+ return failure(line_item, result.error) if result.failure?+ end++ success(order: order, line_item: line_item, line_item_created: line_item_created, options: options)+ endendendenddiff --git a/spree/core/app/services/spree/cart/empty.rb b/spree/core/app/services/spree/cart/empty.rbindex ac097d2d10..567e746965 100644--- a/spree/core/app/services/spree/cart/empty.rb+++ b/spree/core/app/services/spree/cart/empty.rb@@ -28,6 +28,8 @@ module Spreeorder.persist_totalsorder.restart_checkout_flow+ Spree::StockReservations::Release.call(order: order)+success(order)endenddiff --git a/spree/core/app/services/spree/cart/remove_line_item.rb b/spree/core/app/services/spree/cart/remove_line_item.rbindex 9dfc602f47..54f5f5ccaf 100644--- a/spree/core/app/services/spree/cart/remove_line_item.rb+++ b/spree/core/app/services/spree/cart/remove_line_item.rb@@ -7,11 +7,21 @@ module Spreeoptions ||= {}ActiveRecord::Base.transaction doorder.line_items.destroy(line_item)++ # LineItem dependent: :destroy removes its own reservation row;+ # remaining items may need a fresh reservation pass when in checkout.+ if order.in_checkout? && order.line_items.any?+ result = Spree::StockReservations::Reserve.call(order: order)+ raise Spree::StockReservations::InsufficientStockError.new(nil, result.error.to_s) if result.failure?+ end+Spree.cart_recalculate_service.new.call(order: order,line_item: line_item,options: options)endsuccess(line_item)+ rescue Spree::StockReservations::InsufficientStockError => e+ failure(line_item, e.message)endendenddiff --git a/spree/core/app/services/spree/cart/set_quantity.rb b/spree/core/app/services/spree/cart/set_quantity.rbindex bd1e3c6349..305eab3060 100644--- a/spree/core/app/services/spree/cart/set_quantity.rb+++ b/spree/core/app/services/spree/cart/set_quantity.rb@@ -6,6 +6,7 @@ module Spreedef call(order:, line_item:, quantity: nil)ActiveRecord::Base.transaction dorun :change_item_quantity+ run :handle_stock_reservationsrun Spree.cart_recalculate_serviceendend@@ -17,6 +18,15 @@ module Spreesuccess(order: order, line_item: line_item)end++ def handle_stock_reservations(order:, line_item:)+ if order.in_checkout?+ result = Spree::StockReservations::Reserve.call(order: order)+ return failure(line_item, result.error) if result.failure?+ end++ success(order: order, line_item: line_item)+ endendendenddiff --git a/spree/core/app/services/spree/carts/complete.rb b/spree/core/app/services/spree/carts/complete.rbindex ca2bbed42c..68744caedb 100644--- a/spree/core/app/services/spree/carts/complete.rb+++ b/spree/core/app/services/spree/carts/complete.rb@@ -19,6 +19,7 @@ module Spreeadvance_to_complete!(cart)if cart.reload.complete?+ Spree::StockReservations::Release.call(order: cart)success(cart)elsefailure(cart, cart.errors.full_messages.to_sentence.presence || 'Could not complete checkout')diff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rbindex cc52efec2c..00b378ce8d 100644--- a/spree/core/app/services/spree/carts/update.rb+++ b/spree/core/app/services/spree/carts/update.rb@@ -6,6 +6,7 @@ module Spreedef call(cart:, params:)@cart = cart@params = params.to_h.deep_symbolize_keys+ was_in_cart = cart.cart?ApplicationRecord.transaction doassign_cart_attributes@@ -16,10 +17,10 @@ module Spreecart.save!process_items+ try_advance+ sync_stock_reservations(was_in_cart: was_in_cart)end- try_advance-success(cart)rescue ActiveRecord::RecordNotFoundraise@@ -110,6 +111,21 @@ module Spreecart.state = 'address'end+ # Three-way dispatch on the cart→checkout transition:+ # entering checkout → Reserve, mid-checkout mutation → Extend, reverting to cart → Release.+ # A failed Reserve raises so the enclosing transaction rolls back and the+ # outer rescue surfaces the error to the API caller.+ def sync_stock_reservations(was_in_cart:)+ if cart.cart?+ Spree::StockReservations::Release.call(order: cart) unless was_in_cart+ elsif was_in_cart+ result = Spree::StockReservations::Reserve.call(order: cart)+ raise Spree::StockReservations::InsufficientStockError.new(nil, result.error.to_s) if result.failure?+ else+ Spree::StockReservations::Extend.call(order: cart)+ end+ end+# Auto-advance as far as the checkout state machine allows, but never# to complete. The complete transition must always be explicit via# the /carts/:id/complete endpoint — otherwise gift cards or storediff --git a/spree/core/app/services/spree/stock_reservations/extend.rb b/spree/core/app/services/spree/stock_reservations/extend.rbnew file mode 100644index 0000000000..5691e4d2e0--- /dev/null+++ b/spree/core/app/services/spree/stock_reservations/extend.rb@@ -0,0 +1,19 @@+module Spree+ module StockReservations+ class Extend+ prepend Spree::ServiceModule::Base++ def call(order:)+ return success(order) unless Spree::Config[:stock_reservations_enabled]++ expires_at = Time.current + Spree::StockReservation.ttl_for(order)++ Spree::StockReservation+ .where(order_id: order.id)+ .update_all(expires_at: expires_at, updated_at: Time.current)++ success(order)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/stock_reservations/release.rb b/spree/core/app/services/spree/stock_reservations/release.rbnew file mode 100644index 0000000000..12646bee37--- /dev/null+++ b/spree/core/app/services/spree/stock_reservations/release.rb@@ -0,0 +1,12 @@+module Spree+ module StockReservations+ class Release+ prepend Spree::ServiceModule::Base++ def call(order:)+ Spree::StockReservation.where(order_id: order.id).delete_all+ success(order)+ end+ end+ end+enddiff --git a/spree/core/app/services/spree/stock_reservations/reserve.rb b/spree/core/app/services/spree/stock_reservations/reserve.rbnew file mode 100644index 0000000000..df2da064e8--- /dev/null+++ b/spree/core/app/services/spree/stock_reservations/reserve.rb@@ -0,0 +1,103 @@+module Spree+ module StockReservations+ class Reserve+ prepend Spree::ServiceModule::Base++ def call(order:)+ return success(order) unless Spree::Config[:stock_reservations_enabled]++ expires_at = Time.current + Spree::StockReservation.ttl_for(order)++ ApplicationRecord.transaction do+ targets = build_targets(order)+ break if targets.empty?++ # Pessimistic lock + fresh read of count_on_hand. The lock serializes+ # concurrent checkouts and we use the locked rows below so we never+ # check stock against a stale association cache.+ locked_stock_items = Spree::StockItem+ .where(id: targets.map { |_, si| si.id })+ .lock+ .index_by(&:id)++ held = held_by_others(locked_stock_items.keys, order.id)+ existing = existing_reservations_for(targets)++ this_order_used = Hash.new(0)++ targets.each do |line_item, stock_item|+ stock_item = locked_stock_items.fetch(stock_item.id)+ available = stock_item.count_on_hand - held.fetch(stock_item.id, 0) - this_order_used[stock_item.id]++ if available < line_item.quantity+ raise InsufficientStockError.new(+ line_item,+ Spree.t(+ :insufficient_stock_for_reservation,+ default: '%{item} has only %{available} available',+ item: line_item.variant.name,+ available: [available, 0].max+ )+ )+ end++ this_order_used[stock_item.id] += line_item.quantity++ reservation = existing[[stock_item.id, line_item.id]] ||+ Spree::StockReservation.new(stock_item: stock_item, line_item: line_item)+ reservation.order = order+ reservation.quantity = line_item.quantity+ reservation.expires_at = expires_at+ reservation.save!+ end+ end++ success(order)+ rescue InsufficientStockError => e+ failure(e.line_item, e.message)+ end++ private++ def build_targets(order)+ order.line_items.includes(variant: { stock_items: :stock_location }).filter_map do |line_item|+ variant = line_item.variant+ next unless variant&.should_track_inventory?++ stock_item = select_stock_item(variant)+ next if stock_item.nil? || stock_item.backorderable?++ [line_item, stock_item]+ end+ end++ def select_stock_item(variant)+ variant.stock_items.detect { |si| si.stock_location&.active? && si.available? }+ end++ def held_by_others(stock_item_ids, exclude_order_id)+ return {} if stock_item_ids.empty?++ Spree::StockReservation+ .active+ .where(stock_item_id: stock_item_ids)+ .where.not(order_id: exclude_order_id)+ .group(:stock_item_id)+ .sum(:quantity)+ end++ # One SELECT for all (stock_item_id, line_item_id) pairs we need to+ # upsert. Returns a hash keyed by [stock_item_id, line_item_id].+ def existing_reservations_for(targets)+ return {} if targets.empty?++ stock_item_ids = targets.map { |_, si| si.id }+ line_item_ids = targets.map { |li, _| li.id }++ Spree::StockReservation+ .where(stock_item_id: stock_item_ids, line_item_id: line_item_ids)+ .index_by { |r| [r.stock_item_id, r.line_item_id] }+ end+ end+ end+enddiff --git a/spree/core/db/migrate/20260501000001_create_spree_stock_reservations.rb b/spree/core/db/migrate/20260501000001_create_spree_stock_reservations.rbnew file mode 100644index 0000000000..337801e9d9--- /dev/null+++ b/spree/core/db/migrate/20260501000001_create_spree_stock_reservations.rb@@ -0,0 +1,19 @@+class CreateSpreeStockReservations < ActiveRecord::Migration[7.2]+ def change+ create_table :spree_stock_reservations do |t|+ t.references :stock_item, null: false, index: false+ t.references :line_item, null: false+ t.references :order, null: false+ t.integer :quantity, null: false+ t.datetime :expires_at, null: false+ t.timestamps+ end++ # Composite (stock_item_id, expires_at) is the hot-path Quantifier query;+ # leading on stock_item_id makes it cover the standalone-by-stock-item lookup too.+ add_index :spree_stock_reservations, [:stock_item_id, :expires_at]+ add_index :spree_stock_reservations, [:stock_item_id, :line_item_id], unique: true,+ name: 'idx_stock_reservations_item_line_item'+ add_index :spree_stock_reservations, :expires_at+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 65ec598147..8d61e2d218 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -112,7 +112,8 @@ module Spreewebhooks: :default,payment_webhooks: :default,api_keys: :default,- search: :default+ search: :default,+ stock_reservations: :default)enddiff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rbindex d0ada2ba25..c8fe2847ff 100644--- a/spree/core/lib/spree/core/configuration.rb+++ b/spree/core/lib/spree/core/configuration.rb@@ -92,6 +92,9 @@ module Spreepreference :require_master_price, :boolean, default: falsepreference :restock_inventory, :boolean, default: true # Determines if a return item is restocked automatically once it has been receivedpreference :return_eligibility_number_of_days, :integer, default: 365+ preference :reserve_stock_on, :string, default: 'checkout' # 'checkout' (default) or 'cart' — landing in 6.0 alongside Cart/Order split+ preference :stock_reservations_enabled, :boolean, default: true # Hold stock during checkout to prevent overselling+ preference :default_stock_reservation_ttl_minutes, :integer, default: 10 # Fallback TTL when a Store doesn't overridepreference :send_core_emails, :boolean, default: true, deprecated: true # Default mail headers settingspreference :shipping_instructions, :boolean, deprecated: truepreference :show_only_complete_orders_by_default, :boolean, deprecated: truediff --git a/spree/core/lib/spree/testing_support/factories/stock_reservation_factory.rb b/spree/core/lib/spree/testing_support/factories/stock_reservation_factory.rbnew file mode 100644index 0000000000..21474a6f96--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/stock_reservation_factory.rb@@ -0,0 +1,31 @@+FactoryBot.define do+ factory :stock_reservation, class: Spree::StockReservation do+ quantity { 1 }+ expires_at { 10.minutes.from_now }++ transient do+ order { nil }+ end++ # Build the order first (with at least one line_item), then derive+ # stock_item from that line_item's variant so the three FKs reference the+ # same variant. Callers can override stock_item:/line_item:/order: to wire+ # up a specific scenario.+ after(:build) do |reservation, evaluator|+ reservation.order ||= evaluator.order || create(:order_with_line_items, line_items_count: 1)++ if reservation.line_item.nil?+ reservation.line_item = reservation.order.line_items.first ||+ create(:line_item, order: reservation.order)+ reservation.order.line_items.reload+ end++ reservation.stock_item ||= reservation.line_item.variant.stock_items.first ||+ create(:stock_item, variant: reservation.line_item.variant)+ end++ trait :expired do+ expires_at { 1.minute.ago }+ end+ end+enddiff --git a/spree/core/spec/jobs/spree/stock_reservations/expire_job_spec.rb b/spree/core/spec/jobs/spree/stock_reservations/expire_job_spec.rbnew file mode 100644index 0000000000..4926bae897--- /dev/null+++ b/spree/core/spec/jobs/spree/stock_reservations/expire_job_spec.rb@@ -0,0 +1,13 @@+require 'spec_helper'++describe Spree::StockReservations::ExpireJob do+ it 'removes expired reservations and leaves active ones in place' do+ expired_a = create(:stock_reservation, :expired)+ expired_b = create(:stock_reservation, :expired)+ active = create(:stock_reservation, expires_at: 5.minutes.from_now)++ expect { described_class.perform_now }.to change(Spree::StockReservation, :count).by(-2)+ expect(Spree::StockReservation.where(id: [expired_a.id, expired_b.id])).to be_empty+ expect(Spree::StockReservation.find(active.id)).to be_present+ end+enddiff --git a/spree/core/spec/models/spree/stock/quantifier_spec.rb b/spree/core/spec/models/spree/stock/quantifier_spec.rbindex e84e3fe078..5445e05df3 100644--- a/spree/core/spec/models/spree/stock/quantifier_spec.rb+++ b/spree/core/spec/models/spree/stock/quantifier_spec.rb@@ -121,6 +121,84 @@ module Spreeit { expect(subject.can_supply?).to be false }endend++ context 'with active stock reservations' do+ before { stock_item.update(backorderable: false) }++ let(:other_order) { create(:order) }+ let(:other_line_item) { create(:line_item, order: other_order, variant: stock_item.variant) }++ context 'when stock_reservations_enabled is true' do+ before { Spree::Config[:stock_reservations_enabled] = true }++ it 'subtracts active reservations from total_on_hand' do+ create(+ :stock_reservation,+ stock_item: stock_item,+ line_item: other_line_item,+ order: other_order,+ quantity: 4,+ expires_at: 5.minutes.from_now+ )+ expect(subject.total_on_hand).to eq(stock_item.count_on_hand - 4)+ end++ it 'ignores expired reservations' do+ create(+ :stock_reservation,+ :expired,+ stock_item: stock_item,+ line_item: other_line_item,+ order: other_order,+ quantity: 4+ )+ expect(subject.total_on_hand).to eq(stock_item.count_on_hand)+ end++ it 'clamps total_on_hand at zero when reservations exceed physical stock' do+ stock_item.set_count_on_hand(2)+ create(+ :stock_reservation,+ stock_item: stock_item,+ line_item: other_line_item,+ order: other_order,+ quantity: 5,+ expires_at: 5.minutes.from_now+ )+ expect(subject.total_on_hand).to eq(0)+ end++ it 'reserved_quantity returns the sum of active reservations' do+ create(+ :stock_reservation,+ stock_item: stock_item,+ line_item: other_line_item,+ order: other_order,+ quantity: 3,+ expires_at: 5.minutes.from_now+ )+ expect(subject.reserved_quantity).to eq(3)+ end+ end++ context 'when stock_reservations_enabled is false' do+ before { Spree::Config[:stock_reservations_enabled] = false }+ after { Spree::Config[:stock_reservations_enabled] = true }++ it 'returns raw count_on_hand even when reservations exist' do+ create(+ :stock_reservation,+ stock_item: stock_item,+ line_item: other_line_item,+ order: other_order,+ quantity: 4,+ expires_at: 5.minutes.from_now+ )+ expect(subject.total_on_hand).to eq(stock_item.count_on_hand)+ expect(subject.reserved_quantity).to eq(0)+ end+ end+ endendendenddiff --git a/spree/core/spec/models/spree/stock_reservation_spec.rb b/spree/core/spec/models/spree/stock_reservation_spec.rbnew file mode 100644index 0000000000..882b9b18b7--- /dev/null+++ b/spree/core/spec/models/spree/stock_reservation_spec.rb@@ -0,0 +1,114 @@+require 'spec_helper'++describe Spree::StockReservation, type: :model do+ describe 'associations' do+ it { is_expected.to belong_to(:stock_item).class_name('Spree::StockItem').without_validating_presence }+ it { is_expected.to belong_to(:line_item).class_name('Spree::LineItem').without_validating_presence }+ it { is_expected.to belong_to(:order).class_name('Spree::Order').without_validating_presence }+ end++ describe 'validations' do+ let(:reservation) { build(:stock_reservation) }++ it { is_expected.to validate_presence_of(:quantity) }+ it { is_expected.to validate_presence_of(:expires_at) }++ it 'requires positive integer quantity' do+ reservation.quantity = 0+ expect(reservation).to be_invalid+ expect(reservation.errors[:quantity]).to be_present++ reservation.quantity = -1+ expect(reservation).to be_invalid++ reservation.quantity = 1+ expect(reservation).to be_valid+ end++ it 'enforces uniqueness of line_item per stock_item' do+ reservation.save!+ duplicate = build(+ :stock_reservation,+ stock_item: reservation.stock_item,+ line_item: reservation.line_item,+ order: reservation.order+ )+ expect(duplicate).to be_invalid+ expect(duplicate.errors[:line_item_id]).to be_present+ end+ end++ describe 'scopes' do+ let!(:active) { create(:stock_reservation, expires_at: 5.minutes.from_now) }+ let!(:expired) { create(:stock_reservation, :expired) }++ describe '.active' do+ it 'returns only reservations with future expires_at' do+ expect(Spree::StockReservation.active).to include(active)+ expect(Spree::StockReservation.active).not_to include(expired)+ end+ end++ describe '.expired' do+ it 'returns only reservations with past expires_at' do+ expect(Spree::StockReservation.expired).to include(expired)+ expect(Spree::StockReservation.expired).not_to include(active)+ end+ end++ describe '.for_order' do+ it 'returns reservations for the given order' do+ expect(Spree::StockReservation.for_order(active.order)).to include(active)+ expect(Spree::StockReservation.for_order(active.order)).not_to include(expired)+ end+ end+ end++ describe 'lifecycle helpers' do+ let(:reservation) { create(:stock_reservation, expires_at: 5.minutes.from_now) }++ describe '#active?' do+ it { expect(reservation).to be_active }++ it 'is false once expires_at passes' do+ reservation.update!(expires_at: 1.minute.ago)+ expect(reservation).not_to be_active+ end+ end+ end++ describe '.ttl_for' do+ it 'reads the order store preference when set' do+ order = create(:order)+ order.store.update!(preferred_stock_reservation_ttl_minutes: 15)+ expect(described_class.ttl_for(order)).to eq(15.minutes)+ end++ it 'falls back to the global default_stock_reservation_ttl_minutes' do+ Spree::Config[:default_stock_reservation_ttl_minutes] = 7+ expect(described_class.ttl_for(nil)).to eq(7.minutes)+ ensure+ Spree::Config[:default_stock_reservation_ttl_minutes] = 10+ end+ end++ describe 'cleanup via dependent: :destroy' do+ let(:reservation) { create(:stock_reservation) }++ it 'is destroyed when its order is destroyed' do+ reservation+ order = reservation.order+ expect { order.destroy }.to change(Spree::StockReservation, :count).by(-1)+ end++ it 'is destroyed when its line item is destroyed' do+ reservation+ expect { reservation.line_item.destroy }.to change(Spree::StockReservation, :count).by(-1)+ end++ it 'is destroyed when its stock item is destroyed' do+ reservation+ expect { reservation.stock_item.destroy }.to change(Spree::StockReservation, :count).by(-1)+ end+ end+enddiff --git a/spree/core/spec/services/spree/cart/add_item_spec.rb b/spree/core/spec/services/spree/cart/add_item_spec.rbindex 9a22287f6c..6ab99f136c 100644--- a/spree/core/spec/services/spree/cart/add_item_spec.rb+++ b/spree/core/spec/services/spree/cart/add_item_spec.rb@@ -257,5 +257,53 @@ module Spreeexpect(call_service.error).not_to be_nilendend++ context 'stock reservations' do+ let(:variant) { create(:variant, price: 20) }++ before do+ variant.stock_items.first.update!(backorderable: false)+ variant.stock_items.first.set_count_on_hand(10)+ end++ context 'when the order is mid-checkout' do+ let(:order) { create(:order, total: 100, state: 'address') }++ it 'creates a reservation for the new line item' do+ expect { execute }.to change { Spree::StockReservation.where(order_id: order.id).count }.by(1)+ expect(execute).to be_success+ end++ it 'fails when adding more than available and rolls back the line item' do+ variant.stock_items.first.set_count_on_hand(0)++ result = subject.call(order: order, variant: variant, quantity: 1)++ expect(result).to be_failure+ expect(order.reload.line_items).to be_empty+ end+ end++ context 'when the order is in the cart state' do+ let(:order) { create(:order, total: 100, state: 'cart') }++ it 'does not create a reservation' do+ expect { execute }.not_to change { Spree::StockReservation.count }+ expect(execute).to be_success+ end+ end++ context 'when stock_reservations_enabled is false' do+ let(:order) { create(:order, total: 100, state: 'address') }++ before { Spree::Config[:stock_reservations_enabled] = false }+ after { Spree::Config[:stock_reservations_enabled] = true }++ it 'does not create a reservation' do+ expect { execute }.not_to change { Spree::StockReservation.count }+ expect(execute).to be_success+ end+ end+ endendenddiff --git a/spree/core/spec/services/spree/cart/destroy_spec.rb b/spree/core/spec/services/spree/cart/destroy_spec.rbindex f9965072db..148b62aa75 100644--- a/spree/core/spec/services/spree/cart/destroy_spec.rb+++ b/spree/core/spec/services/spree/cart/destroy_spec.rb@@ -50,6 +50,28 @@ module Spreeexpect(Spree::Address.where(id: address_ids)).to be_emptyend+ context 'with stock reservations' do+ let(:line_item) { order.line_items.first }+ let!(:reservation) do+ line_item.variant.stock_items.first.update!(backorderable: false)+ line_item.variant.stock_items.first.set_count_on_hand(10)+ create(+ :stock_reservation,+ stock_item: line_item.variant.stock_items.first,+ line_item: line_item,+ order: order,+ quantity: line_item.quantity,+ expires_at: 5.minutes.from_now+ )+ end++ it 'destroys the reservations via dependent: :destroy on the order' do+ reservation_id = reservation.id+ subject+ expect(Spree::StockReservation.where(id: reservation_id)).to be_empty+ end+ end+context 'when addresses are assigned to other orders' dolet!(:other_order) { create(:order_ready_to_ship, ship_address: ship_address, bill_address: bill_address) }diff --git a/spree/core/spec/services/spree/cart/empty_spec.rb b/spree/core/spec/services/spree/cart/empty_spec.rbindex 8c8e62e51b..f73a17aef6 100644--- a/spree/core/spec/services/spree/cart/empty_spec.rb+++ b/spree/core/spec/services/spree/cart/empty_spec.rb@@ -53,5 +53,28 @@ module Spreeexpect(subject.value).to eq Spree.t(:cannot_empty)endend++ context 'with stock reservations' do+ let(:order) { create(:order_with_line_items, line_items_count: 1) }+ let(:line_item) { order.line_items.first }++ before do+ line_item.variant.stock_items.first.update!(backorderable: false)+ line_item.variant.stock_items.first.set_count_on_hand(10)+ create(+ :stock_reservation,+ stock_item: line_item.variant.stock_items.first,+ line_item: line_item,+ order: order,+ quantity: line_item.quantity,+ expires_at: 5.minutes.from_now+ )+ end++ it 'releases all reservations belonging to the order' do+ expect { described_class.call(order: order) }+ .to change { Spree::StockReservation.where(order_id: order.id).count }.from(1).to(0)+ end+ endendenddiff --git a/spree/core/spec/services/spree/cart/remove_line_item_spec.rb b/spree/core/spec/services/spree/cart/remove_line_item_spec.rbindex f0eb268e40..86b2c47185 100644--- a/spree/core/spec/services/spree/cart/remove_line_item_spec.rb+++ b/spree/core/spec/services/spree/cart/remove_line_item_spec.rb@@ -56,5 +56,89 @@ module Spreeexpect(execute).to be_successendend++ context 'stock reservations' do+ let(:order) { create(:order_with_line_items, line_items_count: 2) }+ let(:line_item) { order.line_items.first }+ let(:other_line_item) { order.line_items.last }++ before do+ order.line_items.each do |li|+ li.variant.stock_items.first.update!(backorderable: false)+ li.variant.stock_items.first.set_count_on_hand(10)+ end+ end++ context 'when the order is mid-checkout' do+ before { order.update_column(:state, 'address') }++ it 'reservation for the removed line item is destroyed via dependent: :destroy' do+ create(+ :stock_reservation,+ stock_item: line_item.variant.stock_items.first,+ line_item: line_item,+ order: order,+ quantity: line_item.quantity,+ expires_at: 5.minutes.from_now+ )++ expect { subject.call(order: order, line_item: line_item) }+ .to change { Spree::StockReservation.where(order_id: order.id, line_item_id: line_item.id).count }+ .from(1).to(0)+ end++ it 'remaining line items get a fresh reservation pass' do+ create(+ :stock_reservation,+ stock_item: other_line_item.variant.stock_items.first,+ line_item: other_line_item,+ order: order,+ quantity: other_line_item.quantity,+ expires_at: 1.minute.from_now+ )+ original_expiry = Spree::StockReservation.find_by(line_item_id: other_line_item.id).expires_at++ Timecop.freeze(2.minutes.from_now) do+ subject.call(order: order, line_item: line_item)+ end++ new_expiry = Spree::StockReservation.find_by(line_item_id: other_line_item.id).expires_at+ expect(new_expiry).to be > original_expiry+ end++ it 'leaves no orphaned reservations after removing every line item' do+ # Removing the second-to-last item still triggers a Reserve pass over+ # the remaining one. Removing the last item must not leave any+ # reservation rows behind for this order.+ subject.call(order: order, line_item: line_item)+ subject.call(order: order, line_item: other_line_item.reload)++ expect(Spree::StockReservation.where(order_id: order.id)).to be_empty+ end++ it 'returns failure and rolls back the destroy when re-reservation fails' do+ # Bump the remaining item's quantity above its stock so re-reservation+ # after the destroy fails. count_on_hand stays > 0 so select_stock_item+ # still picks the row.+ other_line_item.update_column(:quantity, 5)+ other_line_item.variant.stock_items.first.set_count_on_hand(2)+ line_item_count_before = order.line_items.count++ result = subject.call(order: order, line_item: line_item)++ expect(result).to be_failure+ expect(result.error.to_s).to include('available')+ expect(order.reload.line_items.count).to eq(line_item_count_before)+ end+ end++ context 'when the order is in the cart state' do+ it 'does not run a reservation pass' do+ expect {+ subject.call(order: order, line_item: line_item)+ }.not_to change { Spree::StockReservation.count }+ end+ end+ endendenddiff --git a/spree/core/spec/services/spree/cart/set_quantity_spec.rb b/spree/core/spec/services/spree/cart/set_quantity_spec.rbindex 8187103a67..a84063773b 100644--- a/spree/core/spec/services/spree/cart/set_quantity_spec.rb+++ b/spree/core/spec/services/spree/cart/set_quantity_spec.rb@@ -44,5 +44,51 @@ module Spreeexpect(result.value.quantity).to eq(5)endend++ context 'stock reservations' do+ before do+ line_item.variant.stock_items.first.update!(backorderable: false)+ line_item.variant.stock_items.first.set_count_on_hand(20)+ end++ context 'when the order is mid-checkout' do+ before { order.update_column(:state, 'address') }++ it 'reserves the new quantity' do+ subject.call(order: order, line_item: line_item, quantity: 4)++ reservation = Spree::StockReservation.where(order_id: order.id, line_item_id: line_item.id).first+ expect(reservation).to be_present+ expect(reservation.quantity).to eq(4)+ end++ it 'updates an existing reservation in place rather than duplicating' do+ subject.call(order: order, line_item: line_item, quantity: 2)+ subject.call(order: order, line_item: line_item, quantity: 4)++ reservations = Spree::StockReservation.where(order_id: order.id, line_item_id: line_item.id)+ expect(reservations.count).to eq(1)+ expect(reservations.first.quantity).to eq(4)+ end++ it 'fails when the new quantity exceeds available stock and rolls back' do+ subject.call(order: order, line_item: line_item, quantity: 2)+ line_item.variant.stock_items.first.set_count_on_hand(3)++ result = subject.call(order: order, line_item: line_item, quantity: 5)++ expect(result).to be_failure+ expect(line_item.reload.quantity).to eq(2)+ end+ end++ context 'when the order is in the cart state' do+ it 'does not create a reservation' do+ expect {+ subject.call(order: order, line_item: line_item, quantity: 4)+ }.not_to change { Spree::StockReservation.count }+ end+ end+ endendenddiff --git a/spree/core/spec/services/spree/carts/complete_spec.rb b/spree/core/spec/services/spree/carts/complete_spec.rbindex a583284344..498a4da707 100644--- a/spree/core/spec/services/spree/carts/complete_spec.rb+++ b/spree/core/spec/services/spree/carts/complete_spec.rb@@ -101,5 +101,38 @@ RSpec.describe Spree::Carts::Complete doexpect(result).to be_successendend++ context 'with stock reservations' do+ let(:line_item) { order.line_items.first }+ let!(:reservation) do+ line_item.variant.stock_items.first.update!(backorderable: false)+ line_item.variant.stock_items.first.set_count_on_hand(20)+ create(+ :stock_reservation,+ stock_item: line_item.variant.stock_items.first,+ line_item: line_item,+ order: order,+ quantity: line_item.quantity,+ expires_at: 5.minutes.from_now+ )+ end++ it 'releases the reservation on successful completion' do+ expect { subject.call(cart: order) }+ .to change { Spree::StockReservation.where(order_id: order.id).count }.from(1).to(0)+ end++ it 'does not release the reservation when completion fails' do+ order.update_column(:state, 'cart')+ # cart can't complete from cart state without going through checkout flow++ expect {+ # call from this canceled-ish setup will fail; the reservation should stick around+ allow_any_instance_of(Spree::Order).to receive(:reload).and_return(order)+ allow(order).to receive(:complete?).and_return(false)+ subject.call(cart: order)+ }.not_to change { Spree::StockReservation.where(order_id: order.id).count }+ end+ endendenddiff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rbindex 890241ac27..47f4eb87bc 100644--- a/spree/core/spec/services/spree/carts/update_spec.rb+++ b/spree/core/spec/services/spree/carts/update_spec.rb@@ -551,6 +551,82 @@ module Spreeendend+ describe 'stock reservations' do+ let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }+ let!(:us_state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }+ let!(:zone) { create(:zone, zone_members: [Spree::ZoneMember.new(zoneable: country)]) }+ let!(:shipping_method) { create(:shipping_method, zones: [zone]) }+ let(:address_params) do+ {+ first_name: 'Buyer', last_name: 'McGee',+ address1: '1 Test St', city: 'New York',+ postal_code: '10001', country_iso: 'US', state_abbr: 'NY',+ phone: '555-0100'+ }+ end++ before do+ order.line_items.first.variant.stock_items.first.update!(backorderable: false)+ order.line_items.first.variant.stock_items.first.set_count_on_hand(20)+ order.update!(email: '[email protected]')+ end++ context 'cart → checkout transition' do+ let(:params) { { shipping_address: address_params } }++ it 'creates reservations when leaving the cart state' do+ expect(order.cart?).to be(true)+ expect { subject }.to change { Spree::StockReservation.where(order_id: order.id).count }.by_at_least(1)+ end+ end++ context 'in-checkout mutation' do+ before do+ described_class.call(cart: order, params: { shipping_address: address_params })+ end++ let(:params) { { customer_note: 'please ring bell' } }++ it 'extends existing reservations' do+ original_expiry = Spree::StockReservation.where(order_id: order.id).maximum(:expires_at)++ Timecop.freeze(2.minutes.from_now) do+ described_class.call(cart: order, params: params)+ end++ expect(Spree::StockReservation.where(order_id: order.id).maximum(:expires_at)).to be > original_expiry+ end+ end++ # Reverting to the `cart` state from inside Update isn't reachable via+ # the public params shape — `revert_to_address_state` only goes back to+ # `address`, never all the way to `cart`. The `cart?` branch of+ # sync_stock_reservations (Release) is exercised by Cart::Empty and+ # Cart::Destroy specs.++ context 'when Reserve fails with insufficient stock' do+ let(:params) { { shipping_address: address_params } }++ before do+ # Bump line_item quantity above what stock_item can satisfy so that+ # select_stock_item still picks the item (count_on_hand > 0) but+ # the availability check fails.+ order.line_items.first.update_column(:quantity, 5)+ order.line_items.first.variant.stock_items.first.set_count_on_hand(2)+ end++ it 'returns failure and rolls back the cart update' do+ previous_email = order.email+ result = described_class.call(cart: order, params: params.merge(email: '[email protected]'))++ expect(result).to be_failure+ expect(result.error.to_s).to include('available')+ expect(order.reload.email).to eq(previous_email)+ expect(Spree::StockReservation.where(order_id: order.id)).to be_empty+ end+ end+ end+endendenddiff --git a/spree/core/spec/services/spree/stock_reservations/extend_spec.rb b/spree/core/spec/services/spree/stock_reservations/extend_spec.rbnew file mode 100644index 0000000000..c9b6146434--- /dev/null+++ b/spree/core/spec/services/spree/stock_reservations/extend_spec.rb@@ -0,0 +1,40 @@+require 'spec_helper'++describe Spree::StockReservations::Extend do+ let(:store) { create(:store, preferred_stock_reservation_ttl_minutes: 12) }+ let(:order) { create(:order, store: store) }+ let!(:reservation) { create(:stock_reservation, order: order, expires_at: 1.minute.from_now) }++ context 'when stock_reservations_enabled is true' do+ before { Spree::Config[:stock_reservations_enabled] = true }+ after { Spree::Config[:stock_reservations_enabled] = true }++ it 'pushes expires_at out by the store TTL' do+ Timecop.freeze do+ described_class.call(order: order)+ expect(reservation.reload.expires_at).to be_within(1.second).of(12.minutes.from_now)+ end+ end++ it 'updates only this order\'s reservations' do+ other_order = create(:order, store: store)+ other_reservation = create(:stock_reservation, order: other_order, expires_at: 1.minute.from_now)+ original_other_expires_at = other_reservation.expires_at++ described_class.call(order: order)++ expect(other_reservation.reload.expires_at).to be_within(1.second).of(original_other_expires_at)+ end+ end++ context 'when stock_reservations_enabled is false' do+ before { Spree::Config[:stock_reservations_enabled] = false }+ after { Spree::Config[:stock_reservations_enabled] = true }++ it 'leaves expires_at untouched' do+ original = reservation.expires_at+ described_class.call(order: order)+ expect(reservation.reload.expires_at).to be_within(1.second).of(original)+ end+ end+enddiff --git a/spree/core/spec/services/spree/stock_reservations/release_spec.rb b/spree/core/spec/services/spree/stock_reservations/release_spec.rbnew file mode 100644index 0000000000..ba6a4240a0--- /dev/null+++ b/spree/core/spec/services/spree/stock_reservations/release_spec.rb@@ -0,0 +1,22 @@+require 'spec_helper'++describe Spree::StockReservations::Release do+ let(:order) { create(:order) }++ it 'deletes every reservation belonging to the order' do+ other_order = create(:order)+ reservation_a = create(:stock_reservation, order: order)+ line_item_b = create(:line_item, order: order)+ reservation_b = create(:stock_reservation, order: order, line_item: line_item_b)+ untouched = create(:stock_reservation, order: other_order)++ expect { described_class.call(order: order) }.to change(Spree::StockReservation, :count).by(-2)+ expect(Spree::StockReservation.where(id: [reservation_a.id, reservation_b.id])).to be_empty+ expect(Spree::StockReservation.find(untouched.id)).to be_present+ end++ it 'returns success even when no reservations exist' do+ result = described_class.call(order: order)+ expect(result).to be_success+ end+enddiff --git a/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb b/spree/core/spec/services/spree/stock_reservations/reserve_spec.rbnew file mode 100644index 0000000000..0ddba5c9c3--- /dev/null+++ b/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb@@ -0,0 +1,96 @@+require 'spec_helper'++describe Spree::StockReservations::Reserve do+ let(:store) { create(:store) }+ let(:variant) { create(:variant) }+ let!(:stock_location) { variant.stock_items.first.stock_location.tap { |sl| sl.update!(active: true) } }+ let!(:stock_item) { variant.stock_items.first.tap { |si| si.update!(backorderable: false); si.set_count_on_hand(10) } }+ let(:order) { create(:order, store: store) }+ let!(:line_item) { create(:line_item, order: order, variant: variant, quantity: 3) }++ subject(:result) { described_class.call(order: order) }++ context 'when stock_reservations_enabled is true' do+ before { Spree::Config[:stock_reservations_enabled] = true }+ after { Spree::Config[:stock_reservations_enabled] = true }++ it 'creates a reservation for each tracked line item' do+ expect { result }.to change(Spree::StockReservation, :count).by(1)+ expect(result).to be_success++ reservation = Spree::StockReservation.last+ expect(reservation.stock_item).to eq(stock_item)+ expect(reservation.line_item).to eq(line_item)+ expect(reservation.order).to eq(order)+ expect(reservation.quantity).to eq(3)+ end++ it 'sets expires_at according to the store TTL' do+ store.update!(preferred_stock_reservation_ttl_minutes: 7)+ Timecop.freeze do+ result+ expect(Spree::StockReservation.last.expires_at).to be_within(1.second).of(7.minutes.from_now)+ end+ end++ it 'is idempotent — calling twice updates the same reservation, not creating a new one' do+ described_class.call(order: order)+ expect { described_class.call(order: order) }.not_to change(Spree::StockReservation, :count)+ end++ it 'fails when stock is insufficient and rolls back' do+ stock_item.set_count_on_hand(1)+ expect { result }.not_to change(Spree::StockReservation, :count)+ expect(result).to be_failure+ expect(result.error.to_s).to include('available')+ end++ it 'subtracts other orders\' reservations when checking availability' do+ stock_item.set_count_on_hand(5)+ other_order = create(:order, store: store)+ other_line_item = create(:line_item, order: other_order, variant: variant, quantity: 4)+ create(+ :stock_reservation,+ stock_item: stock_item,+ line_item: other_line_item,+ order: other_order,+ quantity: 4,+ expires_at: 5.minutes.from_now+ )++ # Only 1 unit free; line_item wants 3+ expect(result).to be_failure+ end++ it 'accumulates per stock_item across line items so the same SKU twice cannot oversell' do+ # 5 units on hand, two line items each wanting 3 → total demand 6, must fail.+ stock_item.set_count_on_hand(5)+ create(:line_item, order: order, variant: variant, quantity: 3)++ expect(result).to be_failure+ expect(result.error.to_s).to include('available')+ end++ it 'skips backorderable stock items' do+ stock_item.update!(backorderable: true)+ expect { result }.not_to change(Spree::StockReservation, :count)+ expect(result).to be_success+ end++ it 'skips variants that do not track inventory' do+ variant.update!(track_inventory: false)+ expect { result }.not_to change(Spree::StockReservation, :count)+ expect(result).to be_success+ end+ end++ context 'when stock_reservations_enabled is false' do+ before { Spree::Config[:stock_reservations_enabled] = false }+ after { Spree::Config[:stock_reservations_enabled] = true }++ it 'is a no-op' do+ expect { result }.not_to change(Spree::StockReservation, :count)+ expect(result).to be_success+ end+ end+end