Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add Order Routing — pluggable strategy + STI rules

Damian Legawiec3edb26957f9a
diff --git a/CLAUDE.md b/CLAUDE.md
index 8c4d942977..8549cba3ad 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,6 +31,7 @@ Current plans:
- `6.0-rich-text-descriptions.md` — Drop ActionText storage, store HTML in text columns, sanitize on write, serve `description` + `description_html` in API
- `5.4-store-api-naming-standardization.md` — Standardize API naming against industry (address fields, discounts, customer_note, label, brand/last4, etc.)
- `5.4-6.0-eu-legal-compliance.md` — GDPR (data export/anonymization, consent timestamps), Omnibus (PriceHistory, lowest-in-30-days), Consumer Rights (withdrawal period). Core primitives + enterprise hooks.
+- `6.0-order-routing.md` — Two-tier extension: pluggable `Spree::OrderRouting::Strategy::Base` (whole algorithms) + STI subclasses of `Spree::OrderRoutingRule` (signals consumed by `Rules` strategy). Adds `Spree::Order.preferred_stock_location_id`, `Spree::Order.channel_id` (FK replacing the deprecated string column), `Spree::Channel`, `Spree::OrderRoutingRule`. Phase 1 (5.5) ships channel-scoped rules + minimal `Spree::Channel`; Phase 2 (6.0) layers ProductListing/Catalog/Company on top via `6.0-channels-catalogs-b2b.md`.
- `5.5-6.0-order-cancellation-and-approval.md` — First-class `OrderCancellation` + `OrderApproval` models, capture reasons/restock/refund decisions, polymorphic actor; 6.0 drops denormalized columns
- `5.5-admin-api-key-scopes.md` — Shopify-style `read_*`/`write_*` scopes on `Spree::ApiKey` for Admin API authorization (apps), independent of CanCanCan (which stays for JWT users)
- `5.4-disjunctive-option-faceting.md` — Per-option-type filter params with disjunctive facet counts (OR within option type, AND across)
@@ -103,6 +104,7 @@ Per-request context available in models, controllers, jobs, and services:
- Never cast IDs to integer — always treat as strings (UUID support)
- Uniqueness validations: always use `scope: spree_base_uniqueness_scope`, should be also enforced by database index
- If needed use paranoia gem for soft delete support (via `acts_as_paranoid`)
+- For configuration / options always use [Model Preferences](docs/developer/customization/model-preferences.mdx)
```ruby
class Spree::Product < Spree.base_class
diff --git a/docs/.mintlifyignore b/docs/.mintlifyignore
new file mode 100644
index 0000000000..8bf7cc27a1
--- /dev/null
+++ b/docs/.mintlifyignore
@@ -0,0 +1 @@
+plans/
diff --git a/docs/developer/core-concepts/orders.mdx b/docs/developer/core-concepts/orders.mdx
index 0782b75271..7573492159 100644
--- a/docs/developer/core-concepts/orders.mdx
+++ b/docs/developer/core-concepts/orders.mdx
@@ -322,6 +322,8 @@ When a variant is added to an order, the price is locked on the line item. If th
For more details, see [Shipments](/developer/core-concepts/shipments) and [Payments](/developer/core-concepts/payments).
+When an order transitions from cart to checkout, Spree picks the [stock location](/developer/core-concepts/inventory#stock-locations) for each shipment using configurable [Order Routing](/developer/core-concepts/shipments#order-routing) rules — see Shipments for the full details.
+
## Related Documentation
- [Payments](/developer/core-concepts/payments) — Payment processing and payment sessions
@@ -329,4 +331,5 @@ For more details, see [Shipments](/developer/core-concepts/shipments) and [Payme
- [Addresses](/developer/core-concepts/addresses) — Billing and shipping addresses
- [Promotions](/developer/core-concepts/promotions) — Discounts and coupon codes
- [Checkout Customization](/developer/customization/checkout) — Customizing the checkout flow
+- [Build Custom Order Routing](/developer/how-to/custom-order-routing) — Custom rules and strategies for fulfillment-location decisions
- [Events](/developer/core-concepts/events) — Subscribe to order events (e.g., `order.completed`)
diff --git a/docs/developer/core-concepts/shipments.mdx b/docs/developer/core-concepts/shipments.mdx
index 4d04cd84a7..759ecf7a65 100644
--- a/docs/developer/core-concepts/shipments.mdx
+++ b/docs/developer/core-concepts/shipments.mdx
@@ -3,6 +3,8 @@ title: Shipments
description: Shipping methods, rates, split shipments, and fulfillment
---
+import { Since } from '/snippets/since.mdx';
+
## Overview
A shipment represents a package being sent to a customer from a [Stock Location](/developer/core-concepts/inventory#stock-locations). Each order can have one or more shipments — Spree automatically splits orders into multiple shipments when items need to ship from different locations or require different shipping methods.
@@ -151,33 +153,115 @@ Each shipping method uses a [Calculator](/developer/core-concepts/calculators) t
You can create custom calculators for more complex pricing. See the [Calculators guide](/developer/core-concepts/calculators).
+## Order Routing <Since version="5.5" />
+
+When an order moves from cart to checkout, Spree decides which [Stock Location](/developer/core-concepts/inventory#stock-locations) fulfills it. **Order Routing** is the system that makes that decision — driven by configurable rules so merchants can express preferences like "fulfill from the customer's preferred warehouse first," "minimize the number of split shipments," or "always pick the closest location."
+
+```mermaid
+flowchart LR
+ Order[Order entering checkout] --> Strategy
+ Strategy[Routing strategy] --> Rules[(Rules,<br/>per channel)]
+ Strategy --> Locations[(Eligible<br/>stock locations)]
+ Rules --> Reducer
+ Locations --> Reducer
+ Reducer[Reducer:<br/>full ranking,<br/>best-first] --> Ordered[Locations<br/>in rank order]
+ Ordered --> Shipments[Shipments created<br/>top location first]
+```
+
+### How the decision is made
+
+Each Channel (the distribution surface — online storefront, POS, wholesale portal) has an ordered list of **routing rules**. When the customer enters checkout, Spree walks the rules from highest priority to lowest and asks each rule to rank the candidate locations. The result is a full best-to-worst ordering of every eligible location. The top-ranked location packs as much of the cart as it can; anything it can't cover spills over to the next-ranked location, and so on.
+
+The default rules every channel ships with:
+
+| Order | Rule | What it does |
+|---|---|---|
+| 1 | **Preferred Location** | If the order has a preferred location set (e.g. by an admin staff member), that location ranks first. Otherwise abstains. |
+| 2 | **Minimize Splits** | Prefers locations that can fulfill the most line items single-handedly. The location that covers the most cart on its own ranks higher. |
+| 3 | **Default Location** | Tie-breaker: ranks the store default first, then other active locations. Always ranks every candidate so there's always a complete order. |
+
+Reorder them, deactivate them, or add new rules without touching code — they're just rows in `spree_order_routing_rules`.
+
+### Channels
+
+Every order belongs to a Channel. Routing rules are scoped to the channel, so the wholesale channel can have completely different fulfillment logic from the online storefront. New channels seed their own three default rules automatically.
+
+A channel can also override the routing **strategy** entirely — useful when one channel needs an algorithmic shape that's different from rules-walking, e.g. a POS channel that always picks the brick-and-mortar location, or a wholesale channel that delegates routing to an external warehouse management system.
+
+### When it fires
+
+Routing fires once, when the order transitions from `cart` to `address` (the start of checkout). It produces one or more `Shipment`s, each tied to a chosen stock location. The decision is sticky — once the shipments are created, their locations stay fixed unless the merchant edits them in the admin or the cart is cleared and re-routed.
+
+Routing happens **after** stock reservations: by the time routing runs, the cart has already reserved the units it needs. Reservations and routing make their decisions at different layers — reservations protect the variant's total inventory across all locations, routing picks which location ships. They coexist correctly today, with a small inefficiency around location-pinning that's planned to be tightened in 6.0.
+
+### Extending routing
+
+For business-specific logic — proximity to the shipping address, customer-tier-aware fulfillment, refrigerated SKUs, day-of-week dispatch — you write a custom **rule** that plugs into the existing pipeline. For replacing the algorithm entirely (OMS delegation, ML-based routing, multi-order optimization solvers), you write a custom **strategy**.
+
+See the [Build Custom Order Routing](/developer/how-to/custom-order-routing) guide for both.
+
## Split Shipments
-When items in an order ship from different stock locations or have different shipping categories, Spree automatically splits the order into multiple shipments.
+An order's allocation can split along two independent axes:
+
+| Axis | Decided by | Question it answers |
+|---|---|---|
+| **Across stock locations** | [Order Routing](#order-routing) | _Which_ locations fulfill this order? |
+| **Within a stock location** | [Stock Splitters](#stock-splitters) | _How_ do we break each location's allocation into separate packages? |
+
+The two layers compose cleanly — routing picks and ranks the locations, then each chosen location is independently broken down by the splitter chain. The Prioritizer then walks all the resulting packages in rank order and decides which package fulfills each inventory unit.
```mermaid
flowchart TB
- A[Order with 3 items] --> B{Stock check}
- B --> C["Item A & B: NYC Warehouse"]
- B --> D["Item C: LA Warehouse"]
- C --> E["Shipment 1: UPS Ground"]
- D --> F["Shipment 2: FedEx 2Day"]
+ A[Order with 3 items] --> R[Routing strategy]
+ R --> NYC[NYC Warehouse<br/>covers 2 items]
+ R --> LA[LA Warehouse<br/>covers 1 item]
+ NYC --> P1[Packer + splitters]
+ LA --> P2[Packer + splitters]
+ P1 --> S1["Shipment 1: Light items<br/>UPS Ground from NYC"]
+ P1 --> S2["Shipment 2: Heavy items<br/>FedEx Freight from NYC"]
+ P2 --> S3["Shipment 3: Backup item<br/>UPS Ground from LA"]
```
### How Splitting Works
-1. When an order reaches the delivery step, Spree evaluates where each item is in stock
-2. Items are grouped by stock location and shipping category
-3. Each group becomes a separate shipment with its own shipping rates
-4. The customer selects a shipping rate for each shipment independently
+1. **Order Routing** produces a ranked list of stock locations (best first).
+2. **Per-location packing**: each location's units pass through `Spree::Stock::Packer` plus the configured splitter chain (`Spree.stock_splitters`), producing one or more packages per location — broken out by shipping category, on-hand vs backorder, digital vs physical, and so on.
+3. **Prioritizer**: walks all resulting packages in rank order and assigns each inventory unit to the first package that has it on hand. Units the top-ranked location can't cover spill into lower-ranked location packages; unfilled units are flagged backordered.
+4. **Shipment creation**: each remaining package becomes a `Shipment`. The customer selects a shipping rate for each shipment independently.
+
+## Stock Splitters
+
+Splitters are the per-location half of the split-shipment story. Each splitter takes the packages produced so far for one location and decides whether to break them further along its own axis. Splitters are chained — every splitter's output feeds into the next.
+
+Splitters never see more than one location's allocation at a time, so they cannot overlap with routing's location decision. Routing answers "which locations?"; splitters answer "how do we slice each location's packages?"
+
+### Built-in Splitters
+
+| Splitter | Default? | What it does |
+|---|---|---|
+| `Spree::Stock::Splitter::ShippingCategory` | Yes | Groups items in each package by their product's [Shipping Category](#shipping-categories), so each package has only one category. Ensures shipping methods scoped to specific categories receive the right items. |
+| `Spree::Stock::Splitter::Backordered` | Yes | Splits each package into an on-hand part and a backordered part. The two halves can ship at different times with different ETAs. |
+| `Spree::Stock::Splitter::Digital` | Yes | Separates digital items from physical items so digital deliveries don't get bundled with a physical package. |
+| `Spree::Stock::Splitter::Weight` | Opt-in | Caps each package at a weight threshold (default `150`). Splits heavy packages until each is under the limit. Used by carriers with per-package weight limits. |
+
+The default chain is set in `Spree::Core::Engine` and can be overridden:
+
+```ruby
+# config/initializers/spree.rb
+Rails.application.config.spree.stock_splitters = [
+ Spree::Stock::Splitter::ShippingCategory,
+ Spree::Stock::Splitter::Backordered,
+ Spree::Stock::Splitter::Digital,
+ Spree::Stock::Splitter::Weight # add the opt-in weight cap
+]
+```
-### Weight Splitting
+The order matters — each splitter's output is the next one's input.
-By default, Spree also splits shipments when a package exceeds a weight threshold (default: 150 units). This prevents individual packages from being too heavy.
+### Extending Splitters
-<Info>
-Split shipment behavior is customizable. See the [Customization Quickstart](/developer/customization/quickstart) for details on creating custom splitting rules.
-</Info>
+To add custom splitting logic — refrigerated SKUs, gift wrap separation, bulky-vs-small bin separation, anything that needs to fan one location's allocation into multiple shipments — write a new subclass of `Spree::Stock::Splitter::Base`. See the [Build Custom Stock Splitter](/developer/how-to/custom-stock-splitter) guide.
## Examples
@@ -211,4 +295,5 @@ A store shipping from 2 locations (New York, Los Angeles) with 3 carriers and 3
- [Inventory](/developer/core-concepts/inventory) — Stock locations and inventory management
- [Calculators](/developer/core-concepts/calculators) — Shipping rate calculators
- [Addresses](/developer/core-concepts/addresses) — Shipping address and zones
+- [Build Custom Order Routing](/developer/how-to/custom-order-routing) — Custom rules and strategies for choosing the fulfillment location
- [Events](/developer/core-concepts/events) — Subscribe to shipment events (e.g., `shipment.shipped`)
diff --git a/docs/developer/how-to/custom-order-routing.mdx b/docs/developer/how-to/custom-order-routing.mdx
new file mode 100644
index 0000000000..80074da6de
--- /dev/null
+++ b/docs/developer/how-to/custom-order-routing.mdx
@@ -0,0 +1,309 @@
+---
+title: Build Custom Order Routing
+description: Step-by-step guide to extending Spree's order routing — write custom rules to add new signals, or a custom strategy to replace the algorithm entirely.
+---
+
+import { Since } from '/snippets/since.mdx';
+
+<Since version="5.5" />
+
+## Overview
+
+Order routing decides which [Stock Location](/developer/core-concepts/inventory#stock-locations) fulfills an order at checkout. Spree gives you two extension points:
+
+- **Rules** — add a new signal to the existing rules-walking algorithm (proximity, customer tier, refrigerated SKUs, day-of-week dispatch).
+- **Strategies** — replace the algorithm entirely (delegate to a warehouse management system, run an ML model, call an optimization solver).
+
+This guide covers both. Most extensions are rules — they compose with the built-ins and don't require rewriting the pipeline.
+
+Before starting, make sure you understand [how order routing works in Spree](/developer/core-concepts/shipments#order-routing).
+
+| If the answer is "yes" | Pick |
+|---|---|
+| Could this work just by reordering or adding signals to the existing algorithm? | A **rule** |
+| Does the data live in another system you have to call? | A **strategy** |
+| Will the algorithm need access to multiple orders simultaneously (batching, capacity-aware)? | A **strategy** |
+| Are you replacing the entire decision (no rules at all)? | A **strategy** |
+
+## Custom Routing Rules
+
+A rule is one input to the rules-walking algorithm. Each rule subclasses `Spree::OrderRoutingRule` and implements `#rank`, returning an array of `LocationRanking` — one per candidate location.
+
+### Step 1: Create the Rule Class
+
+```ruby app/models/spree/order_routing/rules/closest_location.rb
+module Spree
+ module OrderRouting
+ module Rules
+ class ClosestLocation < Spree::OrderRoutingRule
+ preference :max_distance_km, :integer, default: 1000
+
+ def rank(order, locations)
+ target = order.ship_address&.coordinates
+ return locations.map { |l| LocationRanking.new(location: l, rank: nil) } if target.nil?
+
+ locations.map do |loc|
+ distance = loc.distance_from(target)
+ ranked = distance && distance <= preferred_max_distance_km ? distance.to_i : nil
+ LocationRanking.new(location: loc, rank: ranked)
+ end
+ end
+ end
+ end
+ end
+end
+```
+
+#### Key Method to Implement
+
+| Method | Required | Description |
+|--------|----------|-------------|
+| `rank(order, locations)` | Yes | Returns one `LocationRanking` per input location. Lower rank wins (`0` is best); `nil` means abstain (the rule has no opinion about that location and is skipped for that pass). |
+
+#### Using Preferences
+
+Rules use Spree's preference system for configuration, the same way [Promotion Rules](/developer/how-to/custom-promotion#using-preferences) do. Each preference creates getter/setter methods automatically:
+
+```ruby
+preference :max_distance_km, :integer, default: 1000
+
+# Creates:
+# preferred_max_distance_km / preferred_max_distance_km=
+```
+
+Available types: `:string`, `:integer`, `:decimal`, `:boolean`, `:array`.
+
+### Step 2: Activate the Rule on a Channel
+
+Every routing rule belongs to a Channel. Pick the channel(s) you want it active on and insert a row:
+
+```ruby
+store = Spree::Store.default
+channel = store.default_channel
+
+Spree::OrderRouting::Rules::ClosestLocation.create!(
+ store: store,
+ channel: channel,
+ position: 0, # before the seeded preferred_location rule
+ preferred_max_distance_km: 500
+)
+```
+
+Spree's autoloader picks up models under `app/models/` automatically — no separate registration step.
+
+To activate the rule across multiple channels, create one row per channel. That keeps each channel's rule list explicit and lets you tune per-channel preferences independently.
+
+### Rank Semantics
+
+The reducer composes rules using "first non-tie wins":
+
+| Situation | What the reducer does |
+|---|---|
+| All rules abstain (`nil`) for a location | Falls back to `StockLocation.default`, then by `id` |
+| One rule returns a unique minimum rank | That location wins; remaining rules skipped |
+| One rule returns a tied minimum | The tied locations carry forward; the next rule weighs in *only on those* |
+| All rules tie through the whole chain | Final tiebreak: default location, then by `id` |
+
+Practical implications:
+
+- **Returning `0` for everything is a reset.** If every location ties at `0`, all locations carry forward — the reducer treats it as "no signal" and moves on.
+- **Coverage-style metrics negate.** When higher-is-better, return `-coverage` so lower wins. See `Spree::OrderRouting::Rules::MinimizeSplits` for the canonical example.
+- **Abstaining yields to other rules.** `nil` is the right answer when your rule has no opinion — it lets later rules decide.
+
+### Step 3: Test the Rule
+
+```ruby spec/models/spree/order_routing/rules/closest_location_spec.rb
+require 'rails_helper'
+
+RSpec.describe Spree::OrderRouting::Rules::ClosestLocation, type: :model do
+ let(:store) { @default_store }
+ let(:channel) { store.default_channel }
+ let(:near) { create(:stock_location, latitude: 40.71, longitude: -74.00) } # NYC
+ let(:far) { create(:stock_location, latitude: 34.05, longitude: -118.24) } # LA
+ let(:order) { build(:order, store: store, ship_address: build(:address, latitude: 40.75, longitude: -73.99)) }
+
+ subject(:rule) do
+ described_class.new(store: store, channel: channel, position: 99, preferred_max_distance_km: 5000)
+ end
+
+ it 'ranks the closer location lower' do
+ rankings = rule.rank(order, [near, far])
+ expect(rankings.find { |r| r.location == near }.rank).to be < rankings.find { |r| r.location == far }.rank
+ end
+
+ it 'abstains for every location when the order has no shippable address' do
+ addressless_order = build(:order, store: store, ship_address: nil)
+ rankings = rule.rank(addressless_order, [near, far])
+ expect(rankings.map(&:rank)).to all(be_nil)
+ end
+end
+```
+
+### Common Pitfalls
+
+- **Forgetting `position`.** `position` is required and `acts_as_list`-scoped per channel. Use a number that doesn't collide with the seeded `1` / `2` / `3` (low for "before the defaults", `100+` for "after the defaults").
+- **Returning fewer rankings than locations.** Always return one entry per input location, including abstains (`nil` rank). The reducer needs to see every location.
+- **Trying to "block" a location.** Rules rank, they don't filter. To exclude a location, lower its rank to a value worse than every other rule produces, or abstain everywhere except the locations you want and rely on a later rule to cover the rest.
+
+## Custom Routing Strategies
+
+A strategy is a complete algorithm — when rules-walking doesn't fit your problem, you write a strategy that owns the entire allocation pipeline.
+
+### Step 1: Create the Strategy Class
+
+The contract is `Spree::OrderRouting::Strategy::Base`. There are no defaults — you implement all four methods:
+
+| Method | When it fires | Returns |
+|---|---|---|
+| `#for_allocation` | Cart → checkout transition (`Order#create_proposed_shipments`) | `Array<Spree::Stock::Package>` |
+| `#for_sale(fulfillment:)` | A shipment ships | (side effect) |
+| `#for_release` | An in-flight order is canceled before shipping | (side effect) |
+| `#for_cancellation` | A shipped order is canceled (return) | (side effect) |
+
+The four methods bracket the lifecycle: allocation → sale, allocation → release, or allocation → cancellation. Whatever your algorithm does at allocation time, the other three are where you reverse or settle it.
+
+```ruby app/models/acme/oms/strategy.rb
+module Acme
+ module Oms
+ class Strategy < Spree::OrderRouting::Strategy::Base
+ def for_allocation
+ decision = client.allocate(order_payload)
+ return [] if decision.assignments.empty?
+
+ decision.assignments.map { |assignment| build_package(assignment) }
+ end
+
+ def for_sale(fulfillment:)
+ client.notify_shipped(fulfillment_payload(fulfillment))
+ end
+
+ def for_release
+ client.release(order.number)
+ end
+
+ def for_cancellation
+ client.cancel_and_restock(order.number)
+ end
+
+ private
+
+ def client
+ @client ||= Acme::Oms::Client.new(api_key: ENV.fetch('ACME_OMS_API_KEY'))
+ end
+
+ def order_payload
+ {
+ order_number: order.number,
+ line_items: order.line_items.map { |li| { sku: li.variant.sku, qty: li.quantity } },
+ ship_to: order.ship_address&.country&.iso
+ }
+ end
+
+ def build_package(assignment)
+ location = Spree::StockLocation.find_by!(code: assignment.location_code)
+ units = order.inventory_units.where(variant_id: assignment.variant_ids).to_a
+
+ package = Spree::Stock::Packer.new(location, units, Spree.stock_splitters).packages.first
+ package.shipping_rates = Spree::Stock::Estimator.new(order).shipping_rates(package)
+ package
+ end
+
+ def fulfillment_payload(fulfillment)
+ # ...
+ end
+ end
+ end
+end
+```
+
+Notes:
+
+- **Strategies are plain Ruby classes**, not ActiveRecord models. Live under `app/models/` so the autoloader picks them up; or anywhere on the load path if you'd rather organize them as services.
+- **`for_allocation` returns `Spree::Stock::Package` objects.** The order's `create_proposed_shipments` turns those into `Shipment`s by calling `package.to_shipment`. Returning shipments directly will break the call site.
+- **Reuse the existing primitives.** `Spree::Stock::Packer`, `Spree::Stock::Estimator`, and `Spree::Stock::InventoryUnitBuilder` handle packing, rate estimation, and inventory unit construction. Custom strategies are about the location decision, not re-implementing the packing pipeline.
+
+### Step 2: Register the Strategy
+
+Strategies are selected by class name string — set on `Spree::Store` (default) or `Spree::Channel` (override).
+
+Activate on the whole store:
+
+```ruby
+Spree::Store.default.update!(
+ preferred_order_routing_strategy: 'Acme::Oms::Strategy'
+)
+```
+
+Override on one channel only:
+
+```ruby
+store = Spree::Store.default
+store.channels.find_by(code: 'pos').update!(
+ preferred_order_routing_strategy: 'Acme::Oms::Strategy'
+)
+```
+
+Resolution order: `channel.preferred_order_routing_strategy` → `store.preferred_order_routing_strategy`. The class is `safe_constantize`-d and rejected if it doesn't subclass `Strategy::Base`.
+
+### Step 3: Test the Strategy
+
+Strategy tests are integration tests — build an order, instantiate the strategy, exercise the four methods, assert on the resulting shipments and mocked side effects.
+
+```ruby spec/models/acme/oms/strategy_spec.rb
+require 'rails_helper'
+
+RSpec.describe Acme::Oms::Strategy, type: :model do
+ let(:store) { @default_store }
+ let(:variant) { create(:variant) }
+ let(:location) { create(:stock_location, code: 'NYC') }
+ let(:order) { create(:order_with_line_items, store: store, line_items_attributes: [{ variant: variant, quantity: 1 }]) }
+
+ before { location.stock_item_or_create(variant).update!(count_on_hand: 10) }
+
+ subject(:strategy) { described_class.new(order: order) }
+
+ describe '#for_allocation' do
+ it 'returns packages from the OMS-chosen locations' do
+ stub_oms_decision(assignments: [{ location_code: 'NYC', variant_ids: [variant.id] }])
+
+ packages = strategy.for_allocation
+ expect(packages.map(&:stock_location)).to all(eq(location))
+ end
+
+ it 'returns no packages when the OMS has nothing to assign' do
+ stub_oms_decision(assignments: [])
+ expect(strategy.for_allocation).to eq([])
+ end
+ end
+end
+```
+
+### Common Pitfalls
+
+- **Forgetting the lifecycle hooks.** `for_release` and `for_cancellation` raise `NotImplementedError` by default. If your algorithm doesn't need post-allocation hooks, override them as no-ops explicitly.
+- **Ignoring inventory.** Even custom strategies should query `Spree::StockLocation.active` and respect the order's reserved units. Hardcoding `Spree::StockLocation.first` will work in tests and break in production.
+- **Side effects in `for_sale` / `for_release`.** These fire from state-machine callbacks where the order may already be partially mutated. Treat the methods as side-effect endpoints; pull what you need from the `order` and `fulfillment` arguments — don't reload state mid-call.
+
+## Coexistence with Stock Reservations
+
+Stock reservations and order routing are independent systems in 5.5 — they make decisions at different times and protect different invariants.
+
+| Concern | Reservation system | Order routing |
+|---|---|---|
+| **When it fires** | Cart mutation (add item, change qty, enter checkout) | Cart → checkout transition |
+| **What it decides** | How many units of a variant are held for this cart | Which `StockLocation` fulfills the order |
+| **Granularity** | Per-variant | Per-order |
+
+`Spree::Stock::Quantifier` already subtracts active reservations from `count_on_hand` per-variant across all locations, so global "can we sell this variant?" math is correct even when the reservation and the routing decision land on different locations.
+
+What this means for you when writing custom rules and strategies:
+
+- **Don't read `StockReservation` from inside a routing rule's `#rank`.** The reservations were created against arbitrary stock_items at cart time and don't reflect the routing decision.
+- **Don't relocate reservations from a custom strategy's `for_allocation`.** That's the path 6.0 codifies; doing it ad-hoc in 5.5 races against the cart services that own reservation lifecycle.
+- **`AvailabilityValidator` is the safety net.** If a routing decision picks a location that's actually short on stock, the validator catches it before the order completes.
+
+## Next Steps
+
+- [How orders work](/developer/core-concepts/orders) — Order lifecycle and the routing context
+- [Inventory & Stock Locations](/developer/core-concepts/inventory) — Where the locations live
+- [Build Custom Promotion Rules & Actions](/developer/how-to/custom-promotion) — A similar STI-based extension pattern
diff --git a/docs/developer/how-to/custom-stock-splitter.mdx b/docs/developer/how-to/custom-stock-splitter.mdx
new file mode 100644
index 0000000000..0052251c0c
--- /dev/null
+++ b/docs/developer/how-to/custom-stock-splitter.mdx
@@ -0,0 +1,213 @@
+---
+title: Build a Custom Stock Splitter
+description: Step-by-step guide to extending Spree's stock splitter chain — break a location's allocation into multiple shipments along your own axis (refrigeration, gift wrap, bin size, hazmat, anything you need to physically separate).
+---
+
+## Overview
+
+When [Order Routing](/developer/core-concepts/shipments#order-routing) picks one or more stock locations to fulfill an order, each location's allocation is then run through a chain of **splitters**. Each splitter looks at the packages produced so far and decides whether to break them further along its own axis.
+
+Spree ships with four splitters out of the box (`ShippingCategory`, `Backordered`, `Digital`, `Weight`). You add your own when you need a *physical* separation that isn't expressed by any of the existing ones — refrigerated SKUs that can't share a box with ambient ones, hazmat goods that need their own carrier label, gift-wrap items that ship from a separate processing room, and so on.
+
+Before starting, make sure you understand [how splitting works in Spree](/developer/core-concepts/shipments#stock-splitters) and the [order routing](/developer/core-concepts/shipments#order-routing) layer that runs before splitters.
+
+| If the answer is "yes" | Pick |
+|---|---|
+| Should this affect _which_ locations fulfill the order? | A [routing rule](/developer/how-to/custom-order-routing#custom-routing-rules), not a splitter |
+| Does it just need to break one location's allocation into multiple physical packages? | A **splitter** |
+| Should it apply to every location, every order? | A **splitter** registered globally |
+| Should it apply only on certain channels or stores? | A **splitter** plus a guard inside `#split` |
+
+### Splitters vs Order Routing — quick recap
+
+Routing picks _which_ locations ship; splitters decide _how_ each location's packages are broken up. They live at different layers and never overlap:
+
+| Layer | Decides | Sees | Output |
+|---|---|---|---|
+| Routing | Location order | All eligible locations + the whole order | Ranked location list |
+| Splitter | Intra-location packaging | One location's packages so far | More (or fewer) packages |
+
+A plugin can absolutely ship both — for example, a refrigerated-goods plugin might add a `RefrigeratedRouting::Rule` (prefer locations with cold storage) **and** a `RefrigeratedSplitter` (separate cold items from ambient items within each location). The two extension points are independent.
+
+## Custom Stock Splitters
+
+A splitter subclasses `Spree::Stock::Splitter::Base` and implements `#split(packages)`. The method receives an array of packages produced by the previous splitter (or the initial single-package output of `Packer#default_package`), returns an array of packages, and *must* call `return_next` so the chain continues.
+
+### Step 1: Create the Splitter Class
+
+```ruby app/models/spree/stock/splitter/refrigerated.rb
+module Spree
+ module Stock
+ module Splitter
+ class Refrigerated < Spree::Stock::Splitter::Base
+ def split(packages)
+ split_packages = packages.flat_map { |pkg| split_by_temperature(pkg) }
+ return_next(split_packages)
+ end
+
+ private
+
+ def split_by_temperature(package)
+ grouped = package.contents.group_by { |item| item.variant.refrigerated? }
+ grouped.values.map { |contents| build_package(contents) }
+ end
+ end
+ end
+ end
+end
+```
+
+#### Key Method to Implement
+
+| Method | Required | Description |
+|--------|----------|-------------|
+| `#split(packages)` | Yes | Receives the packages produced by the previous splitter, returns the new (possibly larger or smaller) array of packages. **Must call `return_next(packages)`** so the next splitter in the chain runs. |
+
+#### Helpers Inherited from `Splitter::Base`
+
+| Helper | Returns | When to use |
+|---|---|---|
+| `build_package(contents = [])` | A new `Spree::Stock::Package` for the splitter's `stock_location` | When you create a new package out of contents you've separated from an input package |
+| `return_next(packages)` | The result of the next splitter, or `packages` if this is the last splitter | Always — at the end of `#split` |
+| `stock_location` | The location the parent `Packer` is packing for | When you need to inspect or compare against the location |
+| `packer` | The `Packer` instance | Rarely needed; available for advanced cases |
+
+#### What `package.contents` Looks Like
+
+Each `package.contents` is an array of `Spree::Stock::ContentItem` — wrappers around `InventoryUnit`. The two attributes you'll use most:
+
+```ruby
+content.variant # The Spree::Variant being shipped
+content.inventory_unit # The Spree::InventoryUnit (gives access to line_item, order, etc.)
+content.weight # Convenience: variant.weight × inventory_unit.quantity
+content.state # :on_hand or :backordered
+```
+
+So the splitter's job is "look at each package's contents, decide which contents stay together, build new packages, return the chained result."
+
+### Step 2: Register the Splitter
+
+Splitters are registered globally on `Rails.application.config.spree.stock_splitters` — every order runs through the full chain. Add yours via an initializer:
+
+```ruby config/initializers/spree.rb
+Rails.application.config.to_prepare do
+ Rails.application.config.spree.stock_splitters << Spree::Stock::Splitter::Refrigerated
+end
+```
+
+The `to_prepare` block re-runs on Zeitwerk code reloads in development, so the splitter survives reloads correctly. Putting the line at the top of the initializer (outside `to_prepare`) works too in production but can leave a stale registry in development.
+
+#### Replacing the Whole Chain
+
+If you'd rather control the full chain (uncommon — the defaults are well-chosen), assign instead of append:
+
+```ruby
+Rails.application.config.spree.stock_splitters = [
+ Spree::Stock::Splitter::ShippingCategory,
+ Spree::Stock::Splitter::Refrigerated, # custom one slotted in
+ Spree::Stock::Splitter::Backordered,
+ Spree::Stock::Splitter::Digital
+]
+```
+
+#### Ordering Matters
+
+Splitters run in array order, each feeding the next. Two practical rules:
+
+1. **Coarse before fine.** `ShippingCategory` runs first by default because it groups packages by carrier-relevant category before any other axis cuts in. Your custom splitter usually wants to run after it, unless you're separating items that should *never* share a package even within a category (e.g. hazmat).
+2. **`Backordered` should usually be last among the "type" splitters.** It splits on-hand from backordered items, which is a state-axis split rather than a packaging-axis split. Splitting before `Backordered` gives you finer category buckets; splitting after does too — pick based on whether your axis applies to backorders. Refrigerated items have the same handling whether on-hand or backordered, so running before `Backordered` is fine. Hazmat shipping rules might differ between on-hand (real package) and backorder (paperwork only), so running after might be cleaner.
+
+### Step 3: Test the Splitter
+
+Splitter tests are unit tests — instantiate a fake `Packer`, hand the splitter a hand-built package, assert on the output. There's no factory required.
+
+```ruby spec/models/spree/stock/splitter/refrigerated_spec.rb
+require 'rails_helper'
+
+RSpec.describe Spree::Stock::Splitter::Refrigerated, type: :model do
+ let(:stock_location) { build_stubbed(:stock_location) }
+ let(:packer) { instance_double(Spree::Stock::Packer, stock_location: stock_location) }
+ let(:cold_variant) { build_stubbed(:variant).tap { |v| allow(v).to receive(:refrigerated?).and_return(true) } }
+ let(:warm_variant) { build_stubbed(:variant).tap { |v| allow(v).to receive(:refrigerated?).and_return(false) } }
+
+ let(:cold_item) { content_item_for(cold_variant) }
+ let(:warm_item) { content_item_for(warm_variant) }
+
+ subject(:splitter) { described_class.new(packer) }
+
+ it 'splits a mixed package into a refrigerated package and an ambient package' do
+ package = Spree::Stock::Package.new(stock_location, [cold_item, warm_item])
+
+ result = splitter.split([package])
+
+ expect(result.size).to eq(2)
+ expect(result.flat_map { |p| p.contents.map(&:variant) }).to contain_exactly(cold_variant, warm_variant)
+ end
+
+ it 'leaves an all-cold package as a single package' do
+ package = Spree::Stock::Package.new(stock_location, [cold_item])
+
+ result = splitter.split([package])
+
+ expect(result.size).to eq(1)
+ expect(result.first.contents.map(&:variant)).to eq([cold_variant])
+ end
+
+ it 'returns chained packages unchanged when there is a next_splitter' do
+ next_splitter = instance_double(Spree::Stock::Splitter::Base, split: [:done])
+ splitter = described_class.new(packer, next_splitter)
+ package = Spree::Stock::Package.new(stock_location, [cold_item, warm_item])
+
+ expect(splitter.split([package])).to eq([:done])
+ end
+
+ def content_item_for(variant)
+ inventory_unit = build_stubbed(:inventory_unit, variant: variant)
+ Spree::Stock::ContentItem.new(inventory_unit, :on_hand)
+ end
+end
+```
+
+### Step 4 (optional): Add a Variant-side Predicate
+
+The example above relies on `variant.refrigerated?`. In a real plugin you'd back that with a [Custom Field](/developer/core-concepts/custom-fields) on `Spree::Variant` — say a boolean metafield with key `refrigerated` — and define the predicate as a thin reader:
+
+```ruby app/models/spree/variant_decorator.rb
+Spree::Variant.class_eval do
+ def refrigerated?
+ metafields.find_by(namespace: 'logistics', key: 'refrigerated')&.value == 'true'
+ end
+end
+```
+
+This keeps the splitter pure and lets merchants flag SKUs from the admin UI without touching code.
+
+### Common Pitfalls
+
+- **Forgetting to call `return_next`.** If you return raw packages instead of `return_next(packages)`, every splitter after yours in the chain is silently skipped. The integration test will catch it; the unit test usually won't.
+- **Building empty packages.** If you `group_by` and the group has no contents, `build_package([])` produces a package with no contents that downstream code may treat as a real package. Skip empty groups: `grouped.values.reject(&:empty?).map { |c| build_package(c) }`.
+- **Mutating input packages in place.** A splitter should return new packages built from the contents of the inputs, not edit the originals — `Packer` and other splitters keep references. Use `build_package(contents)`, not `package.contents = ...`.
+- **Doing routing-style work.** A splitter only sees one location's contents. If your logic needs to compare across locations ("ship the cheapest one first"), that's a routing rule or strategy, not a splitter.
+
+## Coexistence with Order Routing
+
+Splitters and routing run in series, not in parallel — every package a splitter sees comes from a single location that routing already chose. The interaction is purely top-down:
+
+| Step | Layer | What runs |
+|---|---|---|
+| 1 | Routing | `Strategy::Rules#for_allocation` ranks all eligible locations |
+| 2 | Per-location packing | One `Packer` per location runs the full splitter chain |
+| 3 | Cross-location dedup | `Prioritizer.Adjuster` walks packages in rank order, assigns each inventory unit to the first package with on-hand stock |
+| 4 | Rate estimation | `Estimator` attaches shipping rates |
+
+Practical implications:
+
+- **Splitter output feeds the Prioritizer.** A splitter that produces 3 packages from one location adds 3 candidates to the Prioritizer's pool. The Prioritizer keeps each unit in the highest-ranked package that still has it on hand and prunes empties.
+- **Splitters can produce backordered-only packages.** That's fine — the `Backordered` splitter is the canonical example. The Prioritizer treats backordered packages as a fallback after exhausting on-hand options across all higher-ranked locations.
+- **A splitter can't see which location ranked higher.** It runs per-location with no awareness of the rank. If you need rank-aware splitting (rare), do it in a custom strategy's `build_packages`, not a splitter.
+
+## Next Steps
+
+- [Shipments — Stock Splitters](/developer/core-concepts/shipments#stock-splitters) — Concept overview and built-in splitter list
+- [Build Custom Order Routing](/developer/how-to/custom-order-routing) — The other layer of split-shipment customization
+- [Custom Fields](/developer/core-concepts/custom-fields) — Tag variants with the data your splitter reads
diff --git a/docs/developer/upgrades/5.4-to-5.5.mdx b/docs/developer/upgrades/5.4-to-5.5.mdx
index 7c4047ffdb..2733e2927f 100644
--- a/docs/developer/upgrades/5.4-to-5.5.mdx
+++ b/docs/developer/upgrades/5.4-to-5.5.mdx
@@ -21,6 +21,31 @@ description: This guide covers upgrading a Spree 5.4 application to Spree 5.5.
bin/rake spree:install:migrations && bin/rails db:migrate
```
+### Run the channels upgrade
+
+Spree 5.5 promotes `Order#channel` from a free-text string column to a real `Spree::Channel` FK. **Run this rake task immediately after `db:migrate`** — it seeds the channel rows your existing stores need and backfills `spree_orders.channel_id` from the legacy string column:
+
+```bash
+bin/rake spree:channels:upgrade
+```
+
+The task is idempotent — safe to re-run if it fails partway, and a no-op on stores/orders that have already been upgraded. It runs two sub-tasks in order:
+
+1. **`spree:channels:create_defaults`** — creates a default `online` channel for every store that doesn't already have one. New 5.5+ stores get this automatically via the `Store` after_create callback; this sub-task only matters for stores that already exist when you upgrade. The channel's after_create hook seeds the three default routing rules (Preferred Location → Minimize Splits → Default Location).
+
+2. **`spree:channels:backfill_order_channel_ids`** — scans each store's orders, creates one `Spree::Channel` per distinct legacy `channel` value (claiming `NULL`/blank rows under the `online` default channel), and writes `channel_id`.
+
+You can also run the two steps individually if you'd rather pace the upgrade:
+
+```bash
+bin/rake spree:channels:create_defaults
+bin/rake spree:channels:backfill_order_channel_ids
+```
+
+Orders modified after the upgrade auto-set `channel_id` via the model's `before_validation` callback, so the backfill is only strictly required for orders that aren't touched again post-upgrade — but running it once at upgrade time avoids surprises later.
+
+The legacy `channel` string column is **kept** on `spree_orders` and ignored by ActiveRecord (`Spree::Order` declares it in `ignored_columns`). It will be dropped in a later Spree release once enough time has passed for everyone to have run the backfill — until then it's harmless DB ballast that lets the rake task be re-run if you need to.
+
### 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).
@@ -88,6 +113,22 @@ 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.
+### (Optional) Opt out of rules-based Order Routing
+
+Spree 5.5 introduces [Order Routing](/developer/core-concepts/shipments#order-routing) — a configurable, per-channel pipeline that decides which stock locations fulfill an order. Every store and every channel ships with three default rules (Preferred Location → Minimize Splits → Default Location) that produce sensible behavior out of the box, with no migration work required.
+
+If you've heavily customized fulfillment in Spree 5.4 and aren't ready to adopt the new rules engine, you can keep the legacy pre-5.5 routing by switching the store's strategy to `Spree::OrderRouting::Strategy::Legacy`:
+
+```ruby
+store.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy')
+```
+
+The Legacy strategy delegates to `Spree::Stock::Coordinator`, which is the exact pre-5.5 packing pipeline — every active stock location is packed, the Prioritizer distributes inventory units across the resulting packages, and no merchant routing rules are consulted. Your existing customizations on `Coordinator`, `Packer`, `Prioritizer`, and the splitters keep working unchanged.
+
+<Warning>
+`Spree::OrderRouting::Strategy::Legacy` and `Spree::Stock::Coordinator` are slated for removal in Spree 6.0. Use this only as a temporary escape hatch while you evaluate the new Rules strategy. New 5.5+ installations should stay on the default Rules strategy.
+</Warning>
+
## Behavior changes worth knowing
### Cart changes during checkout can now fail with insufficient stock
@@ -99,3 +140,11 @@ Storefronts and custom integrations that act on the cart should expect this new
### 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.
+
+### Order Routing chooses location order via merchant rules instead of database order
+
+The default routing strategy (`Spree::OrderRouting::Strategy::Rules`) packs the same set of stock locations as before, but the **order** in which locations are tried is now determined by the routing rules — Preferred Location → Minimize Splits → Default Location — rather than by raw database row order. The unit distribution (Prioritizer + Adjuster) is unchanged: top-ranked location's packages get first pick of on-hand inventory, the rest spills over.
+
+For most stores this is invisible: when one location can fulfill the entire cart, that location now wins consistently (instead of depending on database iteration order). When the cart needs to split across locations, the same multi-location split happens — just with the location order driven by rules.
+
+If you rely on the legacy "every location packed in iteration order, no rule consulted" behavior, see [Opt out of rules-based Order Routing](#optional-opt-out-of-rules-based-order-routing) above.
diff --git a/docs/docs.json b/docs/docs.json
index beba20fa1d..5f991cf233 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -308,6 +308,16 @@
"icon": "book-open",
"description": "Step-by-step guides for common tasks",
"groups": [
+ {
+ "group": "Order Routing",
+ "icon": "route",
+ "pages": ["developer/how-to/custom-order-routing"]
+ },
+ {
+ "group": "Stock Splitters",
+ "icon": "boxes-stacked",
+ "pages": ["developer/how-to/custom-stock-splitter"]
+ },
{
"group": "Payments",
"icon": "credit-card",
diff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.md
index b71357395b..441f1ecd45 100644
--- a/docs/plans/6.0-admin-api.md
+++ b/docs/plans/6.0-admin-api.md
@@ -591,11 +591,11 @@ Customer assignment is handled via the standard `PATCH /api/v3/admin/orders/:id`
- [ ] `GET /api/v3/admin/promotions/:promotion_id/coupon_codes`
### Stock Locations
-- [ ] `GET /api/v3/admin/stock_locations`
-- [ ] `GET /api/v3/admin/stock_locations/:id`
-- [ ] `POST /api/v3/admin/stock_locations`
-- [ ] `PATCH /api/v3/admin/stock_locations/:id`
-- [ ] `DELETE /api/v3/admin/stock_locations/:id`
+- [x] `GET /api/v3/admin/stock_locations`
+- [x] `GET /api/v3/admin/stock_locations/:id`
+- [x] `POST /api/v3/admin/stock_locations`
+- [x] `PATCH /api/v3/admin/stock_locations/:id`
+- [x] `DELETE /api/v3/admin/stock_locations/:id`
### Stock Items
- [ ] `GET /api/v3/admin/stock_items` — filterable by stock_location, variant
diff --git a/docs/plans/6.0-channels-catalogs-b2b.md b/docs/plans/6.0-channels-catalogs-b2b.md
index a638b6265b..982ddbfb08 100644
--- a/docs/plans/6.0-channels-catalogs-b2b.md
+++ b/docs/plans/6.0-channels-catalogs-b2b.md
@@ -560,13 +560,13 @@ GET /api/v3/store/products # automatically filtered by channel + catalog con
### Phase 5: Cleanup (6.1)
- Drop `spree_store_products_legacy` table
-- Remove `Order.channel` string column (replaced by FK)
- Remove `StoreProduct` model
+- Drop `spree_orders.channel` string column (5.5+ already ignores it via `ignored_columns`; 5.5 ships a backfill rake that copies values into `channel_id`)
## Constraints on Current Work
-- **`Spree::Channel` itself ships in 5.5** as part of `6.0-order-routing.md`. The model in 5.5 is the minimal shape (store, name, code, active, preferences, metafields) — exactly what's specified in the Channel section below, minus `default_catalog_id` (no `Catalog` yet). 6.0 layers on `default_catalog_id`, `default_stock_location_id`, and the `has_many :product_listings` association without needing migrations against the table — only `add_reference` migrations to add new FKs.
-- **`Order.channel_id` FK ships in 5.5** (the deprecated string column is dropped in the same migration). 6.0 doesn't need to migrate Orders — just adds `company_location_id`.
+- **`Spree::Channel` itself ships in 5.5** as part of `6.0-order-routing.md`. The model in 5.5 is the minimal shape (store, name, code, active, preferences, metafields) — exactly what's specified in the Channel section below, minus `default_catalog_id` (no `Catalog` yet) and minus `default_stock_location_id` (defined in `6.0-order-routing.md`'s Phase 2). 6.0 layers these on with `add_reference` migrations against `spree_channels` (`default_catalog_id`, `default_stock_location_id`) plus the `has_many :product_listings` association and the new `spree_product_listings` table. No table-level alterations to existing columns.
+- **`Order.channel_id` FK ships in 5.5** alongside the legacy string column. The 5.5 upgrade rake `spree:channels:upgrade` (which composes `create_defaults` + `backfill_order_channel_ids`) populates the FK; `Spree::Order` ignores the string column via `ignored_columns`. The string column is dropped in 6.1 cleanup. 6.0 doesn't need to migrate Orders — just adds `company_location_id`.
- **Don't add new features to StoreProduct.** It's being replaced by ProductListing.
- **New store-scoped product queries should use `store.products`** (which will be rerouted through channels).
- **PriceList stays as-is.** Catalog optionally references a PriceList — don't duplicate pricing logic.
diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.md
index d45e9b3b58..1317b8e665 100644
--- a/docs/plans/6.0-fulfillment-and-delivery.md
+++ b/docs/plans/6.0-fulfillment-and-delivery.md
@@ -174,6 +174,11 @@ Industry consensus (Shopify, Medusa, Saleor): merchant pickup locations are stoc
#### StockLocation changes (merchant pickup)
+> **Status: shipped.** The pickup-related columns and the `country_iso=` /
+> `state_abbr=` setters landed alongside the Admin API for stock locations
+> (PR shipped 2026-05-08). The rename work and the `pickup_point` /
+> `PickupPointProvider` machinery in this plan are still pending.
+
```ruby
class Spree::StockLocation < Spree.base_class
KINDS = %w[warehouse store fulfillment_center].freeze
diff --git a/docs/plans/6.0-order-routing.md b/docs/plans/6.0-order-routing.md
new file mode 100644
index 0000000000..c6e6c556a0
--- /dev/null
+++ b/docs/plans/6.0-order-routing.md
@@ -0,0 +1,703 @@
+# Order Routing
+
+**Status:** Design Finalized
+**Target:** Spree 5.5 (Phase 1) → 6.0 (Phase 2+)
+**Depends on:** none for Phase 1; 6.0 phases extend `6.0-channels-catalogs-b2b.md`, `6.0-stock-reservations.md`, `6.0-typed-stock-movements.md`, `6.0-cart-order-split.md`
+**Author:** Damian + Claude
+**Last updated:** 2026-05-10
+
+## Summary
+
+Replace the implicit, hard-to-extend stock-location selection that lives inside `Spree::Stock::Coordinator` + `Prioritizer` with a layered, two-tier extension model:
+
+1. **`Spree::OrderRouting::Strategy::Base`** — a four-method strategy interface (`for_allocation`, `for_sale`, `for_release`, `for_cancellation`). Strategies are *whole algorithms* — rules-walking, OMS delegation, ML, optimization. Swappable per-Store today, per-Channel once `6.0-channels-catalogs-b2b.md` lands.
+2. **`Spree::OrderRouting::Strategy::Rules`** — the only concrete strategy in core. Walks `Spree::OrderRoutingRule` rows in priority order, applies a Shopify-style reducer, returns `Spree::Stock::Package[]`.
+3. **`Spree::OrderRoutingRule` STI base** + **subclass per rule kind** — rules are *signals* the rules engine considers. Plugins extend by defining a new STI subclass (`class AcmeFresh::Routing::RefrigeratedRule < Spree::OrderRoutingRule`). The persisted `type` column drives polymorphism; no separate registry needed. Mirrors `Spree::PromotionRule`, `Spree::PromotionAction`, `Spree::Calculator`, `Spree::PaymentMethod`.
+
+The two extension points address fundamentally different needs:
+
+| Need | Mechanism | How often used |
+|---|---|---|
+| New algorithm (OMS, ML, solver, batch routing) | Custom `OrderRouting::Strategy::Base` subclass | Rare — handful of plugins ever |
+| New signal (metafield, customer attribute, day-of-week) | Custom STI subclass of `Spree::OrderRoutingRule` | Common — most extensions |
+
+Industry parity: Vendure has the strategy contract but no admin UI. Shopify has the admin UI but gates customization behind Plus + Wasm Functions. Saleor has a two-value enum. Medusa picks ~at random. Spree gets both — a clean Ruby strategy contract *and* a built-in admin-configurable rules engine extended via Spree's standard STI pattern.
+
+## Problem
+
+### 1. Routing is implicit and unswappable
+
+Today `Spree::Stock::Coordinator` (`spree/core/app/models/spree/stock/coordinator.rb`) loops through every active `StockLocation` that stocks the cart's variants, packs each one, and runs them through `Spree::Stock::Prioritizer` — whose `Adjuster` distributes units across packages in raw database iteration order, with `sort_packages` left as an empty TODO. There's no place to plug in "prefer the Brooklyn store" or "minimize split shipments" — customizers monkey-patch the coordinator. The packing pipeline itself is solid; what's missing is the merchant-controllable ordering layer in front of it.
+
+### 2. No merchant configuration
+
+Stores with multiple `StockLocation`s have no admin lever. The system picks via insertion order + the `default` flag. Shopify has had configurable rules for years; Spree has nothing.
+
+### 3. Inputs the customer cares about aren't used
+
+Real merchants want routing to consider: shipping address proximity, market scoping, customer-group preference, whether splitting hurts margin, B2B Company default location, admin-set "fulfill from this store" hint, custom metafield values. None of these are inputs to today's selection.
+
+### 4. Reservation/allocation lifecycle has no owner
+
+5.5 `Spree::StockReservation` (already shipped) holds units against a `stock_item` per cart, but `Spree::StockReservations::Reserve#select_stock_item` picks the location via a `detect` over `variant.stock_items` — first active match. That's effectively random; it has no awareness of merchant routing preferences and is independent of whatever location ends up fulfilling the order. `6.0-typed-stock-movements.md` will introduce typed `allocated`/`shipped`/`released` movements that need the same per-location decision. Both want a single canonical owner of the location decision: that's routing's job — but routing doesn't exist as a concept yet.
+
+## Current State
+
+| Concern | How it works today (pre-5.5) | Gap |
+|---|---|---|
+| Location selection | `Coordinator` packs every active location stocking the cart; `Prioritizer.Adjuster` distributes units across packages in iteration order | No merchant control over location order |
+| Splits | `Splitter` chains run per-location; multi-location splits emerge naturally from Prioritizer's first-package-wins-on-hand walk | Cannot influence whether to split across locations |
+| Address proximity | Not considered | Storefront UX worse than competitors |
+| Market scoping | Not considered | Multi-market merchants can't keep orders in-market |
+| Admin override | None — must monkey-patch | No "fulfill from this store" affordance |
+| Per-channel routing | None — `Order.channel` is a free-text string | POS vs online vs wholesale all use same logic |
+
+## Key Decisions (do not deviate without discussion)
+
+### Strategy contract is total replacement, not a hook framework
+
+`Base` declares four `NotImplementedError` methods: `for_allocation(order:)`, `for_sale(fulfillment:)`, `for_release(order:)`, `for_cancellation(order:)`. No defaults. No hooks. Subclasses implement all four.
+
+This is Vendure's choice and it's the right one — partial overriding leads to "did I override `for_release`? Let me grep the parent" confusion. A custom strategy is a complete, self-contained algorithm.
+
+The base class lives in `Spree::OrderRouting::Strategy::Base` and **`Rules` does not extend `Base` with rule-specific helpers** — it's a peer that happens to be the default. Strategies do not share infrastructure.
+
+### `Rules` is the only concrete strategy in core
+
+Core ships exactly one strategy: `Spree::OrderRouting::Strategy::Rules`. It walks `Spree::OrderRoutingRule` rows. Everything else is a downstream plugin.
+
+There is no `Default` strategy class. The default *strategy* IS `Rules`; `Rules` is configured to behave like today by seeding three default rules (preferred_location → minimize_splits → default_location). Stores upgrading from earlier Spree versions get those rules automatically via a data migration.
+
+### Rules are STI subclasses of `Spree::OrderRoutingRule`
+
+`Spree::OrderRoutingRule` is the STI base. It declares `#rank(order, locations) → Array<LocationRanking>`. Each rule kind is an STI subclass:
+
+```ruby
+class Spree::OrderRouting::Rules::PreferredLocation < Spree::OrderRoutingRule; end
+class Spree::OrderRouting::Rules::MinimizeSplits < Spree::OrderRoutingRule; end
+class Spree::OrderRouting::Rules::DefaultLocation < Spree::OrderRoutingRule; end
+```
+
+Persistence uses Rails STI: the `type` column (e.g. `'Spree::OrderRouting::Rules::PreferredLocation'`) drives instance class on read; instantiating the subclass writes the right `type`.
+
+Plugins extend by defining a new subclass — no registry, no boot-time wiring:
+
+```ruby
+# In a plugin
+module AcmeFresh
+ module Routing
+ class RefrigeratedRule < Spree::OrderRoutingRule
+ def rank(order, locations)
+ # ... return Array<Spree::OrderRoutingRule::LocationRanking>
+ end
+ end
+ end
+end
+```
+
+Once defined and autoloaded, the subclass behaves like any other rule kind: persists via STI, appears in the admin UI, feeds the reducer.
+
+**Custom rules are the dominant extension path.** Custom strategies are for unusual algorithms (OMS, ML, optimization solvers); custom rules are for new signals within rules-walking.
+
+This pattern mirrors `Spree::PromotionRule`, `Spree::PromotionAction`, `Spree::Calculator`, and `Spree::PaymentMethod` — established Spree STI patterns. Avoids the boot-order foot guns of a class registry (autoload timing, plugin ordering).
+
+### Rule reducer: first non-tie wins
+
+Each rule produces a `LocationRanking[]` — one entry per eligible location, with `rank` integer where lower is better, or `nil` if the rule abstains for that location.
+
+The reducer walks rules in `position` order:
+1. Drop rankings where `rank` is `nil` (rule abstains).
+2. Find the location(s) with the lowest rank for this rule.
+3. If unique → that's the winner. Stop.
+4. If tied → carry the tied set to the next rule.
+5. Ran out of rules with ties → pick `StockLocation.default`, then by `id`.
+
+This matches Shopify's mental model. Weighted-sum scoring was considered and rejected — it makes individual rules' effects unpredictable for merchants tweaking config.
+
+### Strategy class chosen via Store preference (Channel later)
+
+```ruby
+# Spree::Store
+preference :order_routing_strategy, :string, default: 'Spree::OrderRouting::Strategy::Rules'
+```
+
+Resolved on `Order` via:
+
+```ruby
+class Spree::Order < Spree.base_class
+ def order_routing_strategy
+ klass_name = channel&.preferred_order_routing_strategy.presence ||
+ store.preferred_order_routing_strategy
+ klass_name.constantize.new(order: self)
+ end
+end
+```
+
+`channel&.preferred_order_routing_strategy.presence ||` is dead code in 5.5 (Order has no channel yet) but the resolver is shaped correctly so 6.0 channels integration is purely additive.
+
+### Rules belong to a Channel
+
+`Spree::OrderRoutingRule` Phase 1 schema: `store_id` (NOT NULL), `channel_id` (NOT NULL), `type` (STI), `position`, `active`, `preferences` (Spree::Preferences serialized text — same pattern as `Spree::PromotionRule`/`Spree::Calculator`).
+
+Every rule is tied to a Channel. The `Order#ensure_channel_presence` before_validation guarantees every Order has a Channel set (defaulting to `store.default_channel`), so the strategy resolver is a single-axis lookup: `order.channel.order_routing_rules.active.ordered`. There is no "store-wide rules with channel fallback" model — Channels are first-class and seed their own defaults.
+
+`store_id` is denormalized for fast filtering and `acts_as_list scope: :channel_id`; the validator enforces `channel.store_id == store_id`.
+
+Per-rule config (e.g. `RefrigeratedRule`'s temperature threshold) lives on the subclass via `preference :max_temp_c, :integer, default: 4`. No separate `config` JSON column — Spree::Preferences provides typed defaults, validation, and admin UI integration out of the box.
+
+### `Order.preferred_stock_location_id` is one rule's input
+
+`Order.preferred_stock_location_id` is a real FK column. The `preferred_location` rule reads it. No bias logic in `Base`, no special handling outside that one rule.
+
+The cascade method on Order:
+
+```ruby
+def inferred_preferred_stock_location_id
+ preferred_stock_location_id.presence ||
+ company_location&.preferred_stock_location_id ||
+ created_by&.try(:preferred_stock_location_id) ||
+ channel&.default_stock_location_id
+end
+```
+
+Phase 1 only `Order.preferred_stock_location_id` and the cascade reading from `created_by&.preferred_stock_location_id` (if AdminUser ships with the column). Phase 2 adds `Channel.default_stock_location_id` and `CompanyLocation.preferred_stock_location_id` at the same time as those plans land.
+
+### Reservation-first allocation (Phase 3)
+
+Phase 1 `for_allocation` returns `Package[]` exactly as `Coordinator#packages` does today. The packages become `Shipment`s. **5.5 reservations operate independently of routing** — `Spree::StockReservations::Reserve#select_stock_item` picks the first active `stock_item` for a variant, which can disagree with what the routing strategy chooses for the same order. The `Quantifier` is per-variant-across-locations so global availability arithmetic is correct, but stock is conceptually double-locked at the chosen-but-not-reserved location for the TTL window. See the [Stock reservations and routing](../developer/order/order-routing.mdx#stock-reservations-and-routing) section in the dev guide for the user-facing version.
+
+Phase 3 makes routing the canonical owner of the location decision. The handoff:
+
+1. **`Reserve` stops picking a location.** Cart-time reservations are held against the variant total, not a specific `stock_item`. Schema change: `spree_stock_reservations.stock_item_id` becomes nullable; a non-null `stock_item_id` means "pinned by routing." `Quantifier#reserved_quantity` shifts from `SUM(quantity) WHERE stock_item_id IN (...)` to `SUM(quantity) WHERE variant_id = ?` (with `stock_item_id IS NULL` rows counting against any of the variant's locations).
+2. **`Strategy#for_allocation` pins reservations.** When the strategy chooses location L for variant V's units, it `UPDATE`s the unpinned reservation rows for that `(order, variant)` pair to set `stock_item_id` to L's stock_item. This becomes the moment "we reserve units at this specific location."
+3. **`for_sale(fulfillment:)` writes typed `shipped` movements.** Pinned reservation row stays alive until shipment ships; on `after_ship`, the strategy writes a typed `shipped` movement that decrements `count_on_hand` at the pinned location, then deletes the reservation.
+4. **`for_release` writes typed `released` movements.** When a checkout reverts to cart or the reservation expires, pinned rows are released — typed `released` movement is conceptually a no-op on stock today, but lets us audit the lifecycle.
+5. **`for_cancellation` writes typed `received` movements.** Restock at the location the order shipped from.
+
+Strategy contract doesn't change between Phase 1 and Phase 3 — implementations grow. Plugin-authored strategies that worked in 5.5 keep working in 6.0, with the addition that custom strategies are now expected to coordinate with the reservation system per the contract above.
+
+Open questions for Phase 3 (parked until `6.0-stock-reservations.md` and `6.0-typed-stock-movements.md` are scheduled):
+
+- **Atomicity of pinning + packing.** The `for_allocation` call already runs inside the cart-state transition's transaction; pinning reservations needs to happen in the same transaction (or a nested savepoint) so a packer failure rolls back the pin.
+- **Multi-location splits.** When routing splits an order across two locations, each location gets its own pinned reservation rows. The unpinned-reservation row for the variant is split into two pinned rows.
+- **Backwards compatibility with the `Reserve` invariant `validates :line_item_id, uniqueness: { scope: :stock_item_id }`.** Splitting a single line item across two stock_items requires either a different uniqueness key (e.g. `[line_item_id, stock_item_id]` already permits multiple stock_items per line_item — verify) or splitting the reservation by per-location quantity.
+
+### Splits are first-class but auto-merge by default
+
+A strategy returning two `Package`s for a four-line cart produces two `Shipment`s. Phase 1's seeded rules include `minimize_splits` near the top — without merchant action, single-shipment is preferred. Merchants who want aggressive splitting (faster delivery) demote it.
+
+### Failure mode: no eligible location → empty packages → today's behavior
+
+If `for_allocation` returns an empty `Package[]` (no location stocks the cart), today's behavior happens — `Order#create_proposed_shipments` results in no shipments, downstream validation fails. Phase 4 (with `6.0-fulfillment-and-delivery.md`) adds `fulfillment_status: 'on_hold'` for graceful handling.
+
+## Design Details
+
+### `Spree::OrderRouting::Strategy::Base`
+
+```ruby
+module Spree
+ module OrderRouting
+ module Strategy
+ class Base
+ attr_reader :order
+
+ def initialize(order:)
+ @order = order
+ end
+
+ # Decide which locations fulfill which items at order placement.
+ # Returns Spree::Stock::Package[] — one per chosen location.
+ # Each package owns a subset of the order's inventory units.
+ def for_allocation
+ raise NotImplementedError
+ end
+
+ # Convert allocation -> shipped at the location bound to this fulfillment.
+ # Default implementations should delegate to StockLocation.unstock.
+ def for_sale(fulfillment:)
+ raise NotImplementedError
+ end
+
+ # Release allocations when an order/draft is canceled before shipment.
+ def for_release
+ raise NotImplementedError
+ end
+
+ # Restock when a fulfilled order is canceled (return / RA).
+ def for_cancellation
+ raise NotImplementedError
+ end
+ end
+ end
+ end
+end
+```
+
+### `Spree::OrderRouting::Strategy::Rules`
+
+```ruby
+module Spree
+ module OrderRouting
+ module Strategy
+ class Rules < Base
+ # Sketch — the actual implementation lives in
+ # spree/core/app/models/spree/order_routing/strategy/rules.rb.
+ def for_allocation
+ locations = eligible_locations
+ return [] if locations.empty?
+
+ # Rank ALL eligible locations best-first via the reducer, then
+ # let Prioritizer's Adjuster distribute units across packages —
+ # units the top-ranked location can't cover spill into the
+ # next-ranked location's packages. Preserves pre-5.5 Coordinator
+ # multi-location split behavior with rule-driven location order.
+ ordered = Reducer.new(applicable_rules.to_a, order: order).rank_all(locations)
+ return [] if ordered.empty?
+
+ packages = build_packages(ordered) # one Packer per location
+ packages = Spree::Stock::Prioritizer.new(packages).prioritized_packages
+ estimate_rates(packages)
+ end
+
+ # Stock decrement / restock today happens via Spree::Shipment's
+ # state machine. The hooks below are part of the contract for the
+ # Phase 3 reservation + typed-movement work; in 5.5 they are no-ops.
+ def for_sale(fulfillment:); end
+ def for_release; end
+ def for_cancellation; end
+
+ private
+
+ def applicable_rules
+ order.channel.order_routing_rules.active.ordered
+ end
+ end
+ end
+ end
+end
+```
+
+### `Spree::OrderRoutingRule` (STI base)
+
+```ruby
+class Spree::OrderRoutingRule < Spree.base_class
+ # Lower rank wins; nil rank = abstain.
+ LocationRanking = Struct.new(:location, :rank, keyword_init: true)
+
+ has_prefix_id :rrule
+
+ belongs_to :store, class_name: 'Spree::Store'
+
+ attribute :active, :boolean, default: true
+ # Subclasses declare typed preferences via `preference :foo, :string`
+ # (Spree::Preferences serialized into the `preferences` text column).
+
+ validates :type, presence: true
+ validates :position, presence: true, numericality: { only_integer: true }
+
+ scope :active, -> { where(active: true) }
+ scope :ordered, -> { order(:position) }
+ scope :for_channel, ->(channel) { where(channel_id: channel.id) }
+
+ acts_as_list scope: :channel_id
+
+ # Subclasses override.
+ # @param order [Spree::Order]
+ # @param locations [Array<Spree::StockLocation>]
+ # @return [Array<LocationRanking>]
+ def rank(_order, _locations)
+ raise NotImplementedError, "#{self.class} must implement #rank(order, locations)"
+ end
+end
+```
+
+### Built-in STI subclasses
+
+```ruby
+module Spree
+ module OrderRouting
+ module Rules
+ # Reads order.inferred_preferred_stock_location_id.
+ # Rank 0 if found, nil otherwise (abstain).
+ class PreferredLocation < Spree::OrderRoutingRule
+ def rank(order, locations)
+ preferred = order.inferred_preferred_stock_location_id
+ locations.map do |loc|
+ LocationRanking.new(location: loc, rank: loc.id == preferred ? 0 : nil)
+ end
+ end
+ end
+
+ # Higher coverage = lower rank.
+ # Coverage = number of line items this location can fulfill alone.
+ class MinimizeSplits < Spree::OrderRoutingRule
+ def rank(order, locations)
+ # ... (batched stock_item lookup omitted for brevity)
+ end
+ end
+
+ # Mirrors today's behavior: StockLocation.default first.
+ # Provides a baseline so the reducer always has a winner.
+ class DefaultLocation < Spree::OrderRoutingRule
+ def rank(_order, locations)
+ locations.map do |loc|
+ LocationRanking.new(location: loc, rank: loc.default? ? 0 : 1)
+ end
+ end
+ end
+ end
+ end
+end
+```
+
+### Reducer
+
+```ruby
+module Spree
+ module OrderRouting
+ module Strategy
+ class Reducer
+ def initialize(rules, order:)
+ @rules, @order = rules, order
+ end
+
+ # Pick the single best location.
+ # @param locations [Array<Spree::StockLocation>]
+ # @return [Spree::StockLocation, nil]
+ def pick(locations)
+ remaining = locations
+ @rules.each do |rule|
+ rankings = rule.rank(@order, remaining).reject { |r| r.rank.nil? }
+ next if rankings.empty?
+
+ min_rank = rankings.map(&:rank).min
+ top = rankings.select { |r| r.rank == min_rank }.map(&:location)
+
+ return top.first if top.size == 1
+ remaining = top # carry tied set forward
+ end
+
+ # Out of rules with ties: prefer default location, else first by id.
+ remaining.sort_by { |l| [l.default? ? 0 : 1, l.id] }.first
+ end
+
+ # Rank ALL locations best-first. Used by Strategy::Rules for
+ # multi-location split fallback: when the top location can't cover
+ # the cart, the next-ranked one picks up the slack.
+ # @param locations [Array<Spree::StockLocation>]
+ # @return [Array<Spree::StockLocation>]
+ def rank_all(locations)
+ remaining = locations.dup
+ ordered = []
+ until remaining.empty?
+ chosen = pick(remaining) or break
+ ordered << chosen
+ remaining = remaining.reject { |l| l.id == chosen.id }
+ end
+ ordered
+ end
+ end
+ end
+ end
+end
+```
+
+### Per-location packing (inside `Strategy::Rules`)
+
+The `Rules` strategy embeds the packing pipeline directly — there is no separate `PackageBuilder` class. The flow is:
+
+```ruby
+# Inside Strategy::Rules
+def build_packages(locations)
+ locations.flat_map do |location|
+ Spree::Stock::Packer.new(location, inventory_units, Spree.stock_splitters).packages
+ end
+end
+
+def inventory_units
+ @inventory_units ||= Spree::Stock::InventoryUnitBuilder.new(order).units
+end
+
+def estimate_rates(packages)
+ estimator = Spree::Stock::Estimator.new(order)
+ packages.each { |pkg| pkg.shipping_rates = estimator.shipping_rates(pkg) }
+ packages
+end
+```
+
+The full sequence in `for_allocation`:
+
+1. `eligible_locations` — fetch active locations stocking any cart variant.
+2. `Reducer#rank_all` — full ranking, best-first.
+3. `build_packages` — one `Packer` per location; each emits one or more packages depending on the configured splitters.
+4. `Spree::Stock::Prioritizer#prioritized_packages` — Adjuster walks packages in rank order, assigns each unit to the first package with on-hand stock, prunes empty packages.
+5. `estimate_rates` — `Estimator` attaches shipping rates to each surviving package.
+
+This reuses the legacy Coordinator's packing machinery wholesale; the only thing routing changes is the *order* in which locations are presented to the Prioritizer.
+
+### `Spree::OrderRouting::Strategy::Legacy` (5.x escape hatch)
+
+Thin wrapper around `Spree::Stock::Coordinator` for merchants who heavily customized `Coordinator`/`Packer`/`Prioritizer` in 5.4 and aren't ready to adopt rules-based routing. Drops in 6.0 along with `Coordinator`.
+
+```ruby
+module Spree
+ module OrderRouting
+ module Strategy
+ class Legacy < Base
+ def for_allocation
+ Spree::Stock::Coordinator.new(order).packages
+ end
+
+ def for_sale(fulfillment:); end
+ def for_release; end
+ def for_cancellation; end
+ end
+ end
+ end
+end
+```
+
+Opt-in via `store.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy')`. Documented in `docs/developer/upgrades/5.4-to-5.5.mdx`.
+
+### `Order.preferred_stock_location_id`
+
+```ruby
+class Spree::Order < Spree.base_class
+ belongs_to :preferred_stock_location, class_name: 'Spree::StockLocation', optional: true
+
+ def inferred_preferred_stock_location_id
+ preferred_stock_location_id.presence ||
+ company_location&.preferred_stock_location_id ||
+ created_by&.try(:preferred_stock_location_id) ||
+ channel&.try(:default_stock_location_id)
+ end
+
+ def order_routing_strategy
+ klass_name = channel&.try(:preferred_order_routing_strategy).presence ||
+ store.preferred_order_routing_strategy
+ klass_name.constantize.new(order: self)
+ end
+end
+```
+
+### Three call sites
+
+| File | Before | After |
+|---|---|---|
+| `Order#create_proposed_shipments` (`order.rb:752`) | `Spree::Stock::Coordinator.new(self).shipments` | `order_routing_strategy.for_allocation.map { |pkg| pkg.to_shipment.tap { ... } }` |
+| `Exchange#shipments` (`exchange.rb:22`) | `Spree::Stock::Coordinator.new(@order, units).shipments` | unchanged for now — Exchange takes custom inventory units, defer integration to Phase 2 |
+| `Cart::EstimateShippingRates` (deprecated) | unchanged | unchanged — deprecated path, do not touch |
+
+### Migration: `spree_order_routing_rules`
+
+```ruby
+class CreateSpreeOrderRoutingRules < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_order_routing_rules do |t|
+ t.references :store, null: false
+ t.references :channel, null: false
+ t.string :type, null: false # STI discriminator
+ t.integer :position, null: false
+ t.boolean :active, null: false
+ t.text :preferences # Spree::Preferences serialized hash (same as PromotionRule)
+ t.timestamps
+ end
+ add_index :spree_order_routing_rules, [:channel_id, :position]
+ add_index :spree_order_routing_rules, [:channel_id, :active, :position],
+ name: 'idx_order_routing_rules_lookup'
+ add_index :spree_order_routing_rules, :type
+ end
+end
+```
+
+### Migration: `Order.preferred_stock_location_id`
+
+```ruby
+class AddPreferredStockLocationToSpreeOrders < ActiveRecord::Migration[7.2]
+ def change
+ add_reference :spree_orders, :preferred_stock_location
+ end
+end
+```
+
+### Data migration: seed a default Channel and rules per Store
+
+```ruby
+class SeedDefaultChannelAndRulesForStores < ActiveRecord::Migration[7.2]
+ def up
+ Spree::Store.find_each do |store|
+ channel = store.channels.find_by(code: 'online') ||
+ store.channels.create!(name: 'Online Store', code: 'online')
+
+ next if channel.order_routing_rules.any?
+
+ Spree::OrderRouting::Rules::PreferredLocation.create!(store: store, channel: channel, position: 1)
+ Spree::OrderRouting::Rules::MinimizeSplits.create!(store: store, channel: channel, position: 2)
+ Spree::OrderRouting::Rules::DefaultLocation.create!(store: store, channel: channel, position: 3)
+ end
+ end
+
+ def down
+ # No-op; rules + channels tables drop in their own down migrations.
+ end
+end
+```
+
+### Hook into Store / Channel creation
+
+Store seeds a default Channel; Channel seeds its own rules. Both are
+idempotent and after_create-based.
+
+```ruby
+class Spree::Store < Spree.base_class
+ after_create :seed_default_channel
+
+ private
+
+ def seed_default_channel
+ return if channels.any?
+
+ channels.create!(name: 'Online Store', code: Spree::Channel::DEFAULT_CODE)
+ end
+end
+
+class Spree::Channel < Spree.base_class
+ after_create :seed_default_order_routing_rules
+
+ private
+
+ def seed_default_order_routing_rules
+ return if order_routing_rules.any?
+
+ Spree::OrderRouting::Rules::PreferredLocation.create!(store: store, channel: self, position: 1)
+ Spree::OrderRouting::Rules::MinimizeSplits.create!(store: store, channel: self, position: 2)
+ Spree::OrderRouting::Rules::DefaultLocation.create!(store: store, channel: self, position: 3)
+ end
+end
+```
+
+### Admin API (Phase 2 — defer to channels)
+
+Phase 1 ships no admin UI for routing rules. The 5.5 default seed (3 rules per store) covers the customer's wedge case. Admin API + SPA settings page land in Phase 2 when channels are present and merchants have a real reason to tune per-channel routing.
+
+Phase 1 admin API change is small:
+
+```
+PATCH /api/v3/admin/orders/:id { preferred_stock_location_id: "sloc_..." }
+```
+
+— exposing the new column on the existing `Order` admin endpoint.
+
+## Migration Path
+
+### Phase 1 — 5.5 (this work)
+
+1. Migration: `spree_channels` table.
+2. Migration: `Order.channel` (deprecated string) → `Order.channel_id` FK.
+3. Migration: `spree_order_routing_rules` table (`type` STI discriminator, `channel_id` NOT NULL).
+4. Migration: `Order.preferred_stock_location_id` FK.
+5. Model: `Spree::Channel` — minimal (`store`, `name`, `code`, `active`, preferences, metafields). No catalogs, no listings — those land in 6.0.
+6. Model: `Spree::OrderRoutingRule` STI base + `LocationRanking` struct + `for_channel` scope + `channel_belongs_to_store` validator.
+7. Strategy classes: `OrderRouting::Strategy::Base`, `OrderRouting::Strategy::Rules`, `OrderRouting::Strategy::Legacy` (escape hatch), `Reducer` (with both `pick` and `rank_all`).
+8. STI subclasses: `Spree::OrderRouting::Rules::PreferredLocation`, `MinimizeSplits`, `DefaultLocation`.
+9. Preferences: `Store#preferred_order_routing_strategy` (default), `Channel#preferred_order_routing_strategy` (override).
+10. Order: `preferred_stock_location` association, `channel` association (auto-defaults to `store.default_channel`), `inferred_preferred_stock_location_id`, `order_routing_strategy` (channel pref → store pref fallback).
+11. `Strategy::Rules#applicable_rules` walks `order.channel.order_routing_rules.active.ordered` — single-axis lookup, every rule belongs to a channel.
+12. Replace `Order#create_proposed_shipments` Coordinator call.
+13. Store after_create: `seed_default_channel` creates one `'online'` channel.
+14. Channel after_create: `seed_default_order_routing_rules` creates the 3 default rules tied to the channel.
+15. Data migration: seed default channel + 3 rules per existing store.
+16. Admin API: expose `preferred_stock_location_id` on Order.
+17. Tests: strategy + each rule subclass + reducer + integration test for `Order#create_proposed_shipments` honoring `preferred_stock_location_id` + channel-scoped rules and strategy override.
+18. **Parity tests**: `spec/models/spree/order_routing/strategy/parity_spec.rb` runs shared examples against both `Strategy::Legacy` and `Strategy::Rules` to lock in no-regression invariants vs. the pre-5.5 Coordinator (single-location coverage, multi-location splits at variant or quantity granularity, backorder behavior, `track_inventory: false`, stock reservation interactions).
+
+### Phase 2 — 6.0, with `6.0-channels-catalogs-b2b.md`
+
+`Channel` already exists from Phase 1; Phase 2 layers on top:
+
+- `Channel.default_stock_location_id` FK.
+- `Channel.preferred_stock_location_id` (or similar) for B2B / staff-default cascade input.
+- `Channel.default_catalog_id` FK (added when `Catalog` ships).
+- `CompanyLocation.preferred_stock_location_id` FK.
+- `Spree::Admin::User.preferred_stock_location_id` FK (staff sign-in default).
+- Admin API + SPA settings page for channels and per-channel routing rules.
+- New rule kinds: `closest_location`, `stay_in_market`, `ranked_locations`, `metafield`.
+
+### Phase 3 — 6.0, with `6.0-stock-reservations.md` + `6.0-typed-stock-movements.md`
+
+The reservation/routing handoff. See "Reservation-first allocation (Phase 3)" above for the design; the work breakdown:
+
+1. **Schema**: `spree_stock_reservations.stock_item_id` becomes nullable. `variant_id` added (NOT NULL, FK), allowing reservations to be held against a variant total before location pinning.
+2. **`Spree::StockReservations::Reserve` no longer picks a location.** `select_stock_item` is removed; the service writes reservations with `stock_item_id: nil` and `variant_id: variant.id`.
+3. **`Spree::Stock::Quantifier#reserved_quantity`** sums all reservations for the variant — pinned ones (subtract from the pinned `stock_item.count_on_hand`) and unpinned (subtract from the variant's pool, no specific location).
+4. **`Strategy#for_allocation` pins reservations.** When the chosen location is decided, the strategy `UPDATE`s the order's unpinned reservations for the variant to set `stock_item_id`. This happens in the same transaction as `create_proposed_shipments`.
+5. **`Strategy#for_sale(fulfillment:)`** writes a typed `kind: 'shipped'` `Spree::StockMovement` and deletes the now-redundant pinned reservation. Replaces the implicit `Shipment#after_ship → StockLocation#unstock` path.
+6. **`Strategy#for_release`** writes a typed `kind: 'released'` movement (audit trail) and deletes the unpinned reservation. Wired from cart-revert and TTL expiry paths.
+7. **`Strategy#for_cancellation`** writes a typed `kind: 'received'` movement at the location the order shipped from and creates a restocking entry.
+8. **Custom strategies opt in** by implementing the four hooks; the contract is unchanged from 5.5, but the implementations now do real bookkeeping. Plugin-authored strategies that just override `for_allocation` (e.g. an OMS delegator) keep working — their `for_sale`/etc. can keep their 5.5 no-op behavior or implement the typed-movement hooks too.
+
+### Phase 4 — 6.0, with `6.0-fulfillment-and-delivery.md` + `6.0-cart-order-split.md`
+
+- Strategy fires in `Spree::Carts::Complete` (the cart→order conversion site post-split).
+- `Package`s become `Fulfillment`s (renamed from Shipment).
+- `for_allocation` returning empty → `fulfillment_status: 'on_hold'`.
+- `Exchange#shipments` migrates to use the strategy via custom inventory units.
+
+### Phase 5 — 6.1, cleanup
+
+- Remove direct Coordinator references from non-strategy code.
+- Document migration path for legacy Coordinator subclasses → custom `OrderRouting::Strategy`.
+- Coordinator stays public but documented as "internal use by Rules strategy."
+
+## Constraints on Current Work
+
+- **Don't add features to `Stock::Coordinator` or `Prioritizer`.** They're being absorbed into `OrderRouting::Strategy::Rules` as implementation detail.
+- **Don't hardcode `StockLocation.default` selection** in new code. Take the location as an argument or call `order.order_routing_strategy.for_allocation`.
+- **Don't add per-channel routing logic to `Channel`** — it lives on `OrderRoutingRule`. Channel just provides scoping and a strategy override.
+- **Storefront/checkout calls that need a location** should accept a strategy result, not query `StockLocation.active.first`.
+- **New code that reads `Order.channel` (string)** should not — wait for the FK in `6.0-channels-catalogs-b2b.md`.
+- **New rule kinds** should subclass `Spree::OrderRoutingRule` directly (STI). No registration, no kind strings — Rails STI does the dispatch via the `type` column. Don't add `if rule.is_a?(Foo)` branches to `Rules` strategy or the reducer; rule classes own their own `#rank` logic.
+
+## Resolved Questions
+
+1. **Strategy vs rules.** Both. Strategies are different *algorithms* (rules-walking, OMS, ML). Rules are different *signals* within the rules-walking algorithm. Custom rules are the dominant extension path; custom strategies are rare.
+
+2. **Rule reducer model.** First non-tie wins (Shopify-style). Weighted-sum scoring rejected — too unpredictable for merchants tuning config.
+
+3. **Strategy registration.** Per-Store preference (Phase 1) → per-Channel preference falling back to Store (Phase 2). NOT `Spree::Dependencies` — that bakes "one strategy per app" into the API and would have to be undone for channels.
+
+4. **Where the strategy fires.** Today: `Order#create_proposed_shipments`. Phase 4: `Spree::Carts::Complete` per `6.0-cart-order-split.md`.
+
+5. **Per-line-item override?** Not in any phase. Strategy decides per-package, which is the same granularity as Shopify and Vendure. Per-line-item override is a future consideration if real demand emerges.
+
+6. **Plus-tier features.** None. All rules ship in core OSS. The strategy class + rule registry are the extension points — paid integrations ship their own strategies / rule kinds as plugins.
+
+7. **`Default` strategy class?** None. The default *strategy* is `Rules`. The default *behavior* comes from seeded rules. Avoids "Default vs Rules" confusion when both would coexist.
+
+8. **Multi-location splits in Phase 1.** Required, no regressions vs. pre-5.5 Coordinator. Approach: the reducer ranks *all* eligible locations (not just picks one), each is packed independently, then `Spree::Stock::Prioritizer` walks the packages in rank order and assigns each unit to the first package with on-hand stock — units the top-ranked location can't cover spill into the next-ranked location's packages. This is the same Adjuster behavior the legacy Coordinator relied on; routing now provides the location ordering instead of the database iteration order.
+
+9. **Legacy strategy escape hatch in 5.x.** Ship `Spree::OrderRouting::Strategy::Legacy` (a thin wrapper around `Spree::Stock::Coordinator`) so merchants who heavily customized `Coordinator`/`Packer`/`Prioritizer` in 5.4 can opt out of rules-based routing during the upgrade window via `store.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy')`. Documented in the 5.4-to-5.5 upgrade guide. Drops in 6.0 along with `Coordinator`.
+
+## Open Questions
+
+1. **Geocoder gem in core OSS.** `closest_location` rule (Phase 2) needs distance calculation. Lean toward bundling `geocoder` gem with lazy lat/lng on `StockLocation`. Defer decision to Phase 2.
+
+2. **Rule conflict UX.** When rules disagree (preferred vs in-market), the merchant might be surprised by the priority order's effect. Defer to Phase 2 admin UI design — likely a "rule preview" with sample addresses.
+
+3. **Custom rules in admin UI.** Plugin-registered kinds need to render in the admin SPA. Likely a `config_schema` method on rule classes that returns a JSON schema for the rule's `config` field. Defer to Phase 2.
+
+4. **Reservation-aware eligibility.** Phase 1 routing reads raw `count_on_hand` from `Spree::StockItem` — neither `OrderRouting::Strategy::Rules#eligible_locations` (existence check) nor `Rules::MinimizeSplits` (coverage check) subtract active `Spree::StockReservation` quantities. Reservations still protect at the `Quantifier` layer (`can_supply?` gates entry) and at order completion (`AvailabilityValidator`), so a routing decision against reservation-held stock fails closed rather than oversells. Going through `Quantifier` per location × variant adds a SUM query per cell, which is too costly for the eligibility hot path. Revisit when `6.0-typed-stock-movements.md` lands the `allocated_count` column on `Spree::StockItem` — that lets `available_count` become a single SQL expression and routing can join it directly without per-pair queries.
+
+## References
+
+- Current coordinator: `spree/core/app/models/spree/stock/coordinator.rb`
+- Current prioritizer (with empty `sort_packages`): `spree/core/app/models/spree/stock/prioritizer.rb`
+- Strategy contract pattern in Spree: `docs/plans/6.0-tax-provider.md`, `docs/plans/6.0-delivery-rate-provider.md`
+- Reservation + movement plans: `docs/plans/6.0-stock-reservations.md`, `docs/plans/6.0-typed-stock-movements.md`
+- Channel scoping: `docs/plans/6.0-channels-catalogs-b2b.md`
+- Cart→Order conversion site for `for_allocation`: `docs/plans/6.0-cart-order-split.md`
+- Shopify Order Routing rules: https://help.shopify.com/en/manual/fulfillment/setup/order-routing
+- Shopify Order Routing Function API: https://shopify.dev/docs/api/functions/latest/order-routing-location-rule
+- Saleor allocation strategies: https://docs.saleor.io/developer/stock/stock-allocation
+- Vendure StockLocationStrategy: https://docs.vendure.io/reference/typescript-api/products-stock/stock-location-strategy
+- Medusa workflow customization: https://docs.medusajs.com/resources/commerce-modules/inventory/inventory-in-flows
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
index 3fd16de5bd..8ffa9c315e 100644
--- a/spree/core/app/models/spree/channel.rb
+++ b/spree/core/app/models/spree/channel.rb
@@ -2,33 +2,44 @@ module Spree
# Lightweight distribution surface within a Store: online storefront, POS,
# marketplace integration, wholesale portal. Channels carry order
# attribution and the routing-strategy override.
- #
- # 5.5 ships only the Channel model + per-channel order routing. The
- # 6.0-channels-catalogs-b2b plan layers ProductListing, Catalog, B2B
- # Companies, and per-channel API keys on top of this same model.
class Channel < Spree.base_class
+ DEFAULT_CODE = 'online'.freeze
+
has_prefix_id :ch
include Spree::SingleStoreResource
include Spree::Metafields
include Spree::Metadata
- # Class name of the Spree::OrderRouting::Strategy::Base subclass for this
- # channel. Empty -> falls back to the Store-level preference.
+ # Empty -> falls back to the Store-level preference.
preference :order_routing_strategy, :string, default: nil
belongs_to :store, class_name: 'Spree::Store'
- has_many :orders, class_name: 'Spree::Order', inverse_of: :channel
+ has_many :orders, class_name: 'Spree::Order', inverse_of: :channel, dependent: :nullify
has_many :order_routing_rules, class_name: 'Spree::OrderRoutingRule', dependent: :destroy
attribute :active, :boolean, default: true
validates :name, presence: true
- validates :code, presence: true, uniqueness: { scope: :store_id }
+ validates :code, presence: true, uniqueness: { scope: spree_base_uniqueness_scope + [:store_id] }
+
+ after_create :seed_default_order_routing_rules
scope :active, -> { where(active: true) }
self.whitelisted_ransackable_attributes = %w[name code active store_id]
+
+ private
+
+ # Default ordering: preferred location wins, then minimize splits, then
+ # fall back to StockLocation.default. See docs/plans/6.0-order-routing.md.
+ def seed_default_order_routing_rules
+ return if order_routing_rules.any?
+
+ Spree::OrderRouting::Rules::PreferredLocation.create!(store: store, channel: self, position: 1)
+ Spree::OrderRouting::Rules::MinimizeSplits.create!(store: store, channel: self, position: 2)
+ Spree::OrderRouting::Rules::DefaultLocation.create!(store: store, channel: self, position: 3)
+ end
end
end
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 1ba329bf50..40e0e26ffc 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -9,6 +9,11 @@ module Spree
class Order < Spree.base_class
has_prefix_id :or # Stripe: or_
+ # Legacy free-text `channel` column was replaced by the `channel_id` FK
+ # (see 6.0-order-routing.md). The string column stays in the DB so the
+ # 5.4-to-5.5 backfill rake can read it; AR ignores it everywhere else.
+ self.ignored_columns += ['channel']
+
PAYMENT_STATES = %w(balance_due credit_owed failed paid void)
SHIPMENT_STATES = %w(backorder canceled partial pending ready shipped)
LINE_ITEM_REMOVABLE_STATES = %w(cart address delivery payment confirm resumed)
@@ -160,6 +165,7 @@ module Spree
belongs_to :store, class_name: 'Spree::Store'
belongs_to :market, class_name: 'Spree::Market', optional: true
belongs_to :channel, class_name: 'Spree::Channel', optional: true
+ belongs_to :preferred_stock_location, class_name: 'Spree::StockLocation', optional: true
with_options dependent: :destroy do
has_many :state_changes, as: :stateful, class_name: 'Spree::StateChange'
@@ -499,7 +505,9 @@ module Spree
end
def ensure_channel_presence
- self.channel ||= store&.default_channel
+ return if channel_id.present?
+
+ self.channel = store&.default_channel
end
def allow_cancel?
@@ -763,7 +771,31 @@ module Spree
# and are not returned or shipped should be deleted
inventory_units.on_hand_or_backordered.delete_all
- self.shipments = Spree::Stock::Coordinator.new(self).shipments
+ self.shipments = order_routing_strategy.for_allocation.map do |package|
+ package.to_shipment.tap { |s| s.address_id = ship_address_id }
+ end
+ end
+
+ # @return [Spree::OrderRouting::Strategy::Base]
+ def order_routing_strategy
+ klass_name = channel&.preferred_order_routing_strategy.presence ||
+ store.preferred_order_routing_strategy
+ klass = klass_name&.safe_constantize
+
+ unless klass && klass <= Spree::OrderRouting::Strategy::Base
+ raise ArgumentError, "Invalid order routing strategy: #{klass_name.inspect}"
+ end
+
+ klass.new(order: self)
+ end
+
+ # Cascade for the `preferred_location` rule kind. Channel and B2B sources
+ # are layered in by their respective plans.
+ #
+ # @return [Integer, nil]
+ def inferred_preferred_stock_location_id
+ preferred_stock_location_id.presence ||
+ created_by&.try(:preferred_stock_location_id)
end
# Returns the total weight of the inventory units in the order
diff --git a/spree/core/app/models/spree/order_routing/rules/default_location.rb b/spree/core/app/models/spree/order_routing/rules/default_location.rb
new file mode 100644
index 0000000000..b66b743d23
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/rules/default_location.rb
@@ -0,0 +1,16 @@
+module Spree
+ module OrderRouting
+ module Rules
+ # Ranks the StockLocation marked `default: true` at 0 and others at 1.
+ # Provides a deterministic baseline so the reducer always has a winner
+ # once higher-priority rules abstain or tie.
+ class DefaultLocation < Spree::OrderRoutingRule
+ def rank(_order, locations)
+ locations.map do |loc|
+ LocationRanking.new(location: loc, rank: loc.default? ? 0 : 1)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing/rules/minimize_splits.rb b/spree/core/app/models/spree/order_routing/rules/minimize_splits.rb
new file mode 100644
index 0000000000..e6045096d6
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/rules/minimize_splits.rb
@@ -0,0 +1,45 @@
+module Spree
+ module OrderRouting
+ module Rules
+ # Prefers locations that can fulfill more demand on their own.
+ # Higher coverage → lower (better) rank, so the location that single-handedly
+ # covers the most variants wins. Coverage is counted per distinct variant
+ # so a variant repeated across multiple line items isn't double-counted.
+ class MinimizeSplits < Spree::OrderRoutingRule
+ def rank(order, locations)
+ demand = required_quantity_by_variant(order)
+ counts = stock_item_counts(demand.keys, locations)
+
+ locations.map do |loc|
+ coverage = demand.count do |variant_id, qty|
+ (counts[[loc.id, variant_id]] || 0) >= qty
+ end
+
+ LocationRanking.new(location: loc, rank: -coverage)
+ end
+ end
+
+ private
+
+ def required_quantity_by_variant(order)
+ order.line_items.each_with_object(Hash.new(0)) do |li, h|
+ next if li.variant_id.nil?
+
+ h[li.variant_id] += li.quantity
+ end
+ end
+
+ # One query for the entire location × variant matrix instead of
+ # N variants × M locations stock_item lookups.
+ def stock_item_counts(variant_ids, locations)
+ return {} if variant_ids.empty? || locations.empty?
+
+ Spree::StockItem
+ .where(stock_location_id: locations.map(&:id), variant_id: variant_ids)
+ .pluck(:stock_location_id, :variant_id, :count_on_hand)
+ .each_with_object({}) { |(loc_id, var_id, count), h| h[[loc_id, var_id]] = count }
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing/rules/preferred_location.rb b/spree/core/app/models/spree/order_routing/rules/preferred_location.rb
new file mode 100644
index 0000000000..94e1f821cf
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/rules/preferred_location.rb
@@ -0,0 +1,22 @@
+module Spree
+ module OrderRouting
+ module Rules
+ # Ranks the order's inferred preferred location at 0 and abstains for
+ # everything else. Lets admins / staff / B2B contexts pin "fulfill from
+ # this location" without preventing fallback when the preferred location
+ # doesn't actually stock the items — subsequent rules tie-break.
+ class PreferredLocation < Spree::OrderRoutingRule
+ def rank(order, locations)
+ preferred_id = order.inferred_preferred_stock_location_id
+
+ locations.map do |loc|
+ LocationRanking.new(
+ location: loc,
+ rank: (preferred_id.present? && loc.id.to_s == preferred_id.to_s) ? 0 : nil
+ )
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing/strategy/base.rb b/spree/core/app/models/spree/order_routing/strategy/base.rb
new file mode 100644
index 0000000000..de809dacad
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/strategy/base.rb
@@ -0,0 +1,39 @@
+module Spree
+ module OrderRouting
+ module Strategy
+ # Contract for order routing strategies. Subclasses implement all four
+ # methods — there are no defaults. New routing *signals* (proximity,
+ # day-of-week, etc.) ship as STI subclasses of Spree::OrderRoutingRule;
+ # a custom strategy is appropriate only when the algorithm itself is a
+ # different shape (OMS delegation, ML model, optimization solver).
+ #
+ # Selected per Order via Spree::Order#order_routing_strategy.
+ # See docs/plans/6.0-order-routing.md.
+ class Base
+ attr_reader :order
+
+ def initialize(order:)
+ @order = order
+ end
+
+ # @return [Array<Spree::Stock::Package>]
+ def for_allocation
+ raise NotImplementedError, "#{self.class} must implement #for_allocation"
+ end
+
+ # @param fulfillment [Spree::Shipment]
+ def for_sale(fulfillment:)
+ raise NotImplementedError, "#{self.class} must implement #for_sale"
+ end
+
+ def for_release
+ raise NotImplementedError, "#{self.class} must implement #for_release"
+ end
+
+ def for_cancellation
+ raise NotImplementedError, "#{self.class} must implement #for_cancellation"
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing/strategy/legacy.rb b/spree/core/app/models/spree/order_routing/strategy/legacy.rb
new file mode 100644
index 0000000000..d672b2d8ef
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/strategy/legacy.rb
@@ -0,0 +1,33 @@
+module Spree
+ module OrderRouting
+ module Strategy
+ # Pre-5.5 routing behavior. Delegates to Spree::Stock::Coordinator,
+ # which packs every active stock location and lets Prioritizer's
+ # Adjuster distribute units across the resulting packages — no rules
+ # consulted, no merchant-driven preferences, location order is
+ # whatever the database returns.
+ #
+ # Provided as an opt-in escape hatch for merchants upgrading from 5.4
+ # who are not ready to adopt rules-based routing. Configure via:
+ #
+ # store.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy')
+ #
+ # Spree 6.0 drops this strategy along with the underlying Coordinator.
+ # See docs/plans/6.0-order-routing.md.
+ class Legacy < Base
+ def for_allocation
+ Spree::Stock::Coordinator.new(order).packages
+ end
+
+ # Stock decrement / restock today happens via Spree::Shipment's state
+ # machine (after_ship / after_cancel). The strategy hooks below are
+ # part of the contract for the future reservation + typed-movement
+ # phase. In 5.5 they are no-ops; existing model callbacks already do
+ # the right thing.
+ def for_sale(fulfillment:); end
+ def for_release; end
+ def for_cancellation; end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing/strategy/reducer.rb b/spree/core/app/models/spree/order_routing/strategy/reducer.rb
new file mode 100644
index 0000000000..b253a564b1
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/strategy/reducer.rb
@@ -0,0 +1,68 @@
+require 'set'
+
+module Spree
+ module OrderRouting
+ module Strategy
+ # Walks rules in priority order and applies a "first non-tie wins" reducer.
+ #
+ # For each rule:
+ # 1. Drop rankings where rank is nil (rule abstains for that location).
+ # 2. Find the location(s) with the lowest rank (best).
+ # 3. Unique winner -> return it.
+ # 4. Tie -> carry the tied set forward to the next rule.
+ #
+ # Out of rules with ties: prefer the StockLocation marked default,
+ # then by id. Guarantees a winner whenever locations is non-empty.
+ class Reducer
+ def initialize(rules, order:)
+ @rules = rules
+ @order = order
+ end
+
+ # @param locations [Array<Spree::StockLocation>]
+ # @return [Spree::StockLocation, nil]
+ def pick(locations)
+ return nil if locations.empty?
+
+ remaining = locations
+ remaining_ids = remaining.map(&:id).to_set
+
+ @rules.each do |rule|
+ rankings = rule.rank(@order, remaining).select do |r|
+ r.rank && remaining_ids.include?(r.location.id)
+ end
+ next if rankings.empty?
+
+ min_rank = rankings.map(&:rank).min
+ top = rankings.select { |r| r.rank == min_rank }.map(&:location)
+
+ return top.first if top.size == 1
+
+ remaining = top
+ remaining_ids = top.map(&:id).to_set
+ end
+
+ remaining.min_by { |l| [l.default? ? 0 : 1, l.id] }
+ end
+
+ # Returns every input location, ordered best-first by the same rule
+ # chain that drives #pick. Each successive location is the best of
+ # what remains — used by Strategy::Rules to fan out an allocation
+ # across multiple locations when no single location covers the cart.
+ #
+ # @param locations [Array<Spree::StockLocation>]
+ # @return [Array<Spree::StockLocation>]
+ def rank_all(locations)
+ remaining = locations.dup
+ ordered = []
+ until remaining.empty?
+ chosen = pick(remaining) or break
+ ordered << chosen
+ remaining = remaining.reject { |l| l.id == chosen.id }
+ end
+ ordered
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing/strategy/rules.rb b/spree/core/app/models/spree/order_routing/strategy/rules.rb
new file mode 100644
index 0000000000..f9c40db2b7
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/strategy/rules.rb
@@ -0,0 +1,81 @@
+module Spree
+ module OrderRouting
+ module Strategy
+ # Default order routing strategy: walks Spree::OrderRoutingRule rows in
+ # priority order, runs the Reducer to fully rank eligible locations,
+ # packs each location, and lets Spree::Stock::Prioritizer distribute
+ # inventory units across packages so units that the top-ranked
+ # location can't cover spill over to subsequent locations.
+ #
+ # See docs/plans/6.0-order-routing.md.
+ class Rules < Base
+ def for_allocation
+ locations = eligible_locations
+ return [] if locations.empty?
+
+ ordered = Reducer.new(applicable_rules.to_a, order: order).rank_all(locations)
+ return [] if ordered.empty?
+
+ packages = build_packages(ordered)
+ packages = prioritize_packages(packages)
+ estimate_rates(packages)
+ end
+
+ # Stock decrement / restock today happens via Spree::Shipment's state
+ # machine (after_ship / after_cancel). The strategy methods below are
+ # part of the contract for the future reservation + typed-movement
+ # phase — see 6.0-stock-reservations.md and 6.0-typed-stock-movements.md.
+ # In 5.5 they are no-ops; the existing model callbacks already do the
+ # right thing.
+ def for_sale(fulfillment:); end
+ def for_release; end
+ def for_cancellation; end
+
+ private
+
+ def applicable_rules
+ order.channel.order_routing_rules.active.ordered
+ end
+
+ def eligible_locations
+ Spree::StockLocation.active
+ .joins(:stock_items)
+ .where(spree_stock_items: { variant_id: requested_variant_ids })
+ .distinct
+ .to_a
+ end
+
+ def requested_variant_ids
+ inventory_units.map(&:variant_id).uniq
+ end
+
+ def inventory_units
+ @inventory_units ||= Spree::Stock::InventoryUnitBuilder.new(order).units
+ end
+
+ # Pack each ranked location independently. Packages are emitted in
+ # rank order so the Prioritizer's first-package-wins-on-hand logic
+ # honors the routing decision.
+ def build_packages(locations)
+ locations.flat_map do |location|
+ Spree::Stock::Packer.new(location, inventory_units, Spree.stock_splitters).packages
+ end
+ end
+
+ # Prioritizer's Adjuster distributes each inventory_unit across
+ # packages: the first package with on-hand stock fulfills the unit,
+ # and downstream packages have that unit removed. Packages whose
+ # items all get stripped are pruned.
+ def prioritize_packages(packages)
+ Spree::Stock::Prioritizer.new(packages).prioritized_packages
+ end
+
+ def estimate_rates(packages)
+ estimator = Spree::Stock::Estimator.new(order)
+ packages.each { |pkg| pkg.shipping_rates = estimator.shipping_rates(pkg) }
+ packages
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing_rule.rb b/spree/core/app/models/spree/order_routing_rule.rb
new file mode 100644
index 0000000000..fd766ea642
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing_rule.rb
@@ -0,0 +1,63 @@
+module Spree
+ # STI base for order routing rules. Subclasses live in
+ # app/models/spree/order_routing/rules/ and implement #rank(order, locations).
+ #
+ # Plugins extend the engine by defining a new subclass:
+ #
+ # class AcmeFresh::OrderRouting::RefrigeratedRule < Spree::OrderRoutingRule
+ # preference :max_temp_c, :integer, default: 4
+ #
+ # def rank(order, locations)
+ # # ... return Array<LocationRanking>
+ # end
+ # end
+ #
+ # See docs/plans/6.0-order-routing.md.
+ class OrderRoutingRule < Spree.base_class
+ self.table_name = 'spree_order_routing_rules'
+
+ # `rank` is integer (lower = better) when the rule has an opinion,
+ # nil to abstain (the reducer skips abstaining rankings).
+ LocationRanking = Struct.new(:location, :rank, keyword_init: true)
+
+ has_prefix_id :orule
+
+ include Spree::SingleStoreResource
+
+ belongs_to :store, class_name: 'Spree::Store'
+ belongs_to :channel, class_name: 'Spree::Channel'
+
+ attribute :active, :boolean, default: true
+
+ validates :type, :channel, presence: true
+ validates :position, presence: true, numericality: { only_integer: true }
+ validate :channel_belongs_to_store
+
+ scope :active, -> { where(active: true) }
+ scope :ordered, -> { order(:position) }
+ scope :for_channel, ->(channel) { where(channel_id: channel.id) }
+
+ acts_as_list scope: :channel_id
+
+ self.whitelisted_ransackable_attributes = %w[type position active store_id channel_id]
+
+ # Subclasses override. Returns an Array<LocationRanking> — one per location,
+ # with rank=nil to abstain.
+ #
+ # @param order [Spree::Order]
+ # @param locations [Array<Spree::StockLocation>]
+ # @return [Array<LocationRanking>]
+ def rank(_order, _locations)
+ raise NotImplementedError, "#{self.class} must implement #rank(order, locations)"
+ end
+
+ private
+
+ def channel_belongs_to_store
+ return if channel.nil? || store_id.nil?
+ return if channel.store_id == store_id
+
+ errors.add(:channel, Spree.t('errors.messages.channel_store_mismatch'))
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index c5cb57718e..206769653b 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -55,6 +55,9 @@ module Spree
preference :digital_asset_authorized_clicks, :integer, default: 5
preference :digital_asset_authorized_days, :integer, default: 7
preference :digital_asset_link_expire_time, :integer, default: 300
+ # Class name of the Spree::OrderRouting::Strategy::Base subclass that
+ # decides which StockLocation fulfills which items.
+ preference :order_routing_strategy, :string, default: 'Spree::OrderRouting::Strategy::Rules'
#
# Associations
@@ -110,6 +113,7 @@ module Spree
has_many :webhook_deliveries, through: :webhook_endpoints, class_name: 'Spree::WebhookDelivery'
has_many :channels, class_name: 'Spree::Channel', dependent: :destroy
+ has_many :order_routing_rules, through: :channels, class_name: 'Spree::OrderRoutingRule'
has_many :customer_groups, class_name: 'Spree::CustomerGroup', dependent: :destroy, inverse_of: :store
@@ -180,11 +184,8 @@ module Spree
Spree::Store.default&.supported_locales_list || []
end
- # The Channel new orders default to when no other context is provided.
- # 5.5 always seeds an 'online' channel; merchants can rename or add
- # alongside it in 6.0.
def default_channel
- channels.find_by(code: 'online') || channels.active.first
+ channels.find_by(code: Spree::Channel::DEFAULT_CODE) || channels.active.first
end
# @deprecated Use Markets instead. Will be removed in Spree 5.5.
@@ -413,12 +414,10 @@ module Spree
end
end
- # 5.5 ships one Channel per Store ('online'). 6.0 channels admin lets
- # merchants add POS / wholesale / etc. See docs/plans/6.0-channels-catalogs-b2b.md.
def seed_default_channel
return if channels.any?
- channels.create!(name: 'Online Store', code: 'online')
+ channels.create!(name: 'Online Store', code: Spree::Channel::DEFAULT_CODE)
end
def ensure_default_taxonomies_are_created
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 6243f91381..59716a8821 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1130,6 +1130,7 @@ en:
messages:
blank: can't be blank
cannot_remove_icon: Cannot remove image
+ channel_store_mismatch: must belong to the same store
could_not_create_taxon: Could not create taxon
must_be_origin_only: must be an origin (scheme and host) without path, query, or fragment
no_shipping_methods_available: No shipping methods available for selected location, please change your address and try again.
diff --git a/spree/core/db/migrate/20260508204041_create_spree_order_routing_rules.rb b/spree/core/db/migrate/20260508204041_create_spree_order_routing_rules.rb
new file mode 100644
index 0000000000..8c3fb51c2b
--- /dev/null
+++ b/spree/core/db/migrate/20260508204041_create_spree_order_routing_rules.rb
@@ -0,0 +1,18 @@
+class CreateSpreeOrderRoutingRules < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_order_routing_rules do |t|
+ t.references :store, null: false
+ t.references :channel, null: false
+ t.string :type, null: false
+ t.integer :position, null: false
+ t.boolean :active, null: false
+ t.text :preferences
+ t.timestamps
+ end
+
+ add_index :spree_order_routing_rules, [:channel_id, :position]
+ add_index :spree_order_routing_rules, [:channel_id, :active, :position],
+ name: 'idx_order_routing_rules_lookup'
+ add_index :spree_order_routing_rules, :type
+ end
+end
diff --git a/spree/core/db/migrate/20260508204042_add_preferred_stock_location_to_spree_orders.rb b/spree/core/db/migrate/20260508204042_add_preferred_stock_location_to_spree_orders.rb
new file mode 100644
index 0000000000..d34a7e410d
--- /dev/null
+++ b/spree/core/db/migrate/20260508204042_add_preferred_stock_location_to_spree_orders.rb
@@ -0,0 +1,5 @@
+class AddPreferredStockLocationToSpreeOrders < ActiveRecord::Migration[7.2]
+ def change
+ add_reference :spree_orders, :preferred_stock_location
+ end
+end
diff --git a/spree/core/db/migrate/20260508204043_add_channel_id_to_spree_orders.rb b/spree/core/db/migrate/20260508204043_add_channel_id_to_spree_orders.rb
index 4adc1a6cb1..8d0ab0bbcf 100644
--- a/spree/core/db/migrate/20260508204043_add_channel_id_to_spree_orders.rb
+++ b/spree/core/db/migrate/20260508204043_add_channel_id_to_spree_orders.rb
@@ -1,6 +1,10 @@
class AddChannelIdToSpreeOrders < ActiveRecord::Migration[7.2]
+ # Non-destructive: adds the FK column alongside the existing `channel`
+ # string column. Old reads keep working until the upgrade rake task
+ # `spree:order_routing:backfill_channel_ids` populates `channel_id`.
+ # The string column is dropped in a follow-up migration once the
+ # backfill has run.
def change
- remove_column :spree_orders, :channel, :string, default: 'spree'
add_reference :spree_orders, :channel
end
end
diff --git a/spree/core/lib/tasks/channels.rake b/spree/core/lib/tasks/channels.rake
new file mode 100644
index 0000000000..8211636c20
--- /dev/null
+++ b/spree/core/lib/tasks/channels.rake
@@ -0,0 +1,68 @@
+namespace :spree do
+ namespace :channels do
+ desc 'Create a default channel for every store that does not already have one'
+ task create_defaults: :environment do
+ created = 0
+ Spree::Store.find_each do |store|
+ next if store.channels.exists?
+
+ # The Channel after_create hook seeds the three default routing
+ # rules (PreferredLocation, MinimizeSplits, DefaultLocation) so
+ # this single create! covers both the channel and its rules.
+ store.channels.create!(name: 'Online Store', code: Spree::Channel::DEFAULT_CODE)
+ created += 1
+ puts " Store '#{store.name}': created default channel '#{Spree::Channel::DEFAULT_CODE}'"
+ end
+
+ puts created.zero? ? ' All stores already have at least one channel.' : " Created #{created} default channel(s)."
+ end
+
+ desc 'Backfill spree_orders.channel_id from the legacy spree_orders.channel string column'
+ task backfill_order_channel_ids: :environment do
+ # Idempotent: only touches orders where channel_id is nil. Safe to
+ # re-run after partial completion. Returns gracefully if the legacy
+ # string column has already been dropped.
+ unless legacy_channel_column?
+ puts 'Legacy channel column not present — backfill is unnecessary.'
+ next
+ end
+
+ Spree::Store.find_each do |store|
+ legacy_codes = Spree::Order.where(store_id: store.id, channel_id: nil)
+ .distinct
+ .pluck(Arel.sql('channel'))
+ .compact_blank
+
+ codes_to_process = legacy_codes.uniq
+ codes_to_process << Spree::Channel::DEFAULT_CODE unless codes_to_process.include?(Spree::Channel::DEFAULT_CODE)
+
+ codes_to_process.each do |code|
+ channel = store.channels.find_or_create_by!(code: code) do |c|
+ c.name = code.titleize
+ end
+
+ scope = Spree::Order.where(store_id: store.id, channel_id: nil)
+ scope = if code == Spree::Channel::DEFAULT_CODE
+ # Only the default channel claims NULL/blank rows.
+ scope.where(Arel.sql("channel = ? OR channel IS NULL OR channel = ''"), code)
+ else
+ scope.where(Arel.sql('channel = ?'), code)
+ end
+
+ updated = scope.update_all(channel_id: channel.id)
+
+ next if updated.zero?
+
+ puts " Store '#{store.name}': mapped #{updated} orders with channel='#{code}' → #{channel.name} (#{channel.code})"
+ end
+ end
+ end
+
+ desc 'Run the full 5.4 → 5.5 channel upgrade: create defaults, then backfill order channels'
+ task upgrade: %i[create_defaults backfill_order_channel_ids]
+
+ def legacy_channel_column?
+ ActiveRecord::Base.connection.column_exists?(:spree_orders, :channel)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/channel_spec.rb b/spree/core/spec/models/spree/channel_spec.rb
index ace8cdd0ff..d97ad7db25 100644
--- a/spree/core/spec/models/spree/channel_spec.rb
+++ b/spree/core/spec/models/spree/channel_spec.rb
@@ -71,4 +71,25 @@ RSpec.describe Spree::Channel, type: :model do
expect(channel.prefixed_id).to start_with('ch_')
end
end
+
+ describe '#seed_default_order_routing_rules' do
+ it 'creates the three built-in rules in priority order on create' do
+ expect { described_class.create!(store: store, name: 'POS', code: 'pos') }
+ .to change(Spree::OrderRoutingRule, :count).by(3)
+
+ rules = described_class.find_by(code: 'pos').order_routing_rules.ordered
+ expect(rules.map(&:class)).to eq([
+ Spree::OrderRouting::Rules::PreferredLocation,
+ Spree::OrderRouting::Rules::MinimizeSplits,
+ Spree::OrderRouting::Rules::DefaultLocation
+ ])
+ expect(rules.map(&:position)).to eq([1, 2, 3])
+ end
+
+ it 'is idempotent — re-invoking does not create duplicates' do
+ channel = described_class.create!(store: store, name: 'POS', code: 'pos')
+ expect { channel.send(:seed_default_order_routing_rules) }
+ .not_to change(Spree::OrderRoutingRule, :count)
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/order_routing/rules/default_location_spec.rb b/spree/core/spec/models/spree/order_routing/rules/default_location_spec.rb
new file mode 100644
index 0000000000..607feed899
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/rules/default_location_spec.rb
@@ -0,0 +1,18 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OrderRouting::Rules::DefaultLocation, type: :model do
+ let(:store) { @default_store }
+ let(:order) { build(:order, store: store) }
+
+ subject(:rule) { described_class.new(store: store, position: 1) }
+
+ it 'ranks the default location 0 and others 1' do
+ default_loc = create(:stock_location, default: true)
+ secondary = create(:stock_location, default: false)
+
+ rankings = rule.rank(order, [default_loc, secondary])
+
+ expect(rankings.find { |r| r.location == default_loc }.rank).to eq(0)
+ expect(rankings.find { |r| r.location == secondary }.rank).to eq(1)
+ end
+end
diff --git a/spree/core/spec/models/spree/order_routing/rules/minimize_splits_spec.rb b/spree/core/spec/models/spree/order_routing/rules/minimize_splits_spec.rb
new file mode 100644
index 0000000000..5cadeac420
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/rules/minimize_splits_spec.rb
@@ -0,0 +1,37 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OrderRouting::Rules::MinimizeSplits, type: :model do
+ let(:store) { @default_store }
+
+ let(:variant_a) { create(:variant) }
+ let(:variant_b) { create(:variant) }
+ let(:order) do
+ build(:order, store: store).tap do |o|
+ o.line_items << build(:line_item, variant: variant_a, quantity: 1, order: o)
+ o.line_items << build(:line_item, variant: variant_b, quantity: 1, order: o)
+ end
+ end
+
+ let(:full_coverage) { create(:stock_location) }
+ let(:half_coverage) { create(:stock_location) }
+
+ before do
+ full_coverage.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ full_coverage.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+ half_coverage.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ # variant_b: no stock item / 0 count at half_coverage so coverage is 1.
+ end
+
+ subject(:rule) { described_class.new(store: store, position: 1) }
+
+ it 'ranks higher-coverage locations lower (better)' do
+ rankings = rule.rank(order, [full_coverage, half_coverage])
+
+ full_rank = rankings.find { |r| r.location == full_coverage }.rank
+ half_rank = rankings.find { |r| r.location == half_coverage }.rank
+
+ expect(full_rank).to be < half_rank
+ expect(full_rank).to eq(-2) # negative coverage
+ expect(half_rank).to eq(-1)
+ end
+end
diff --git a/spree/core/spec/models/spree/order_routing/rules/preferred_location_spec.rb b/spree/core/spec/models/spree/order_routing/rules/preferred_location_spec.rb
new file mode 100644
index 0000000000..b73f53203d
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/rules/preferred_location_spec.rb
@@ -0,0 +1,29 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OrderRouting::Rules::PreferredLocation, type: :model do
+ let(:store) { @default_store }
+ let(:preferred) { create(:stock_location, name: 'Preferred') }
+ let(:other) { create(:stock_location, name: 'Other') }
+ let(:locations) { [preferred, other] }
+
+ subject(:rule) { described_class.new(store: store, position: 1) }
+
+ context 'when the order has a preferred_stock_location_id' do
+ let(:order) { build(:order, store: store, preferred_stock_location: preferred) }
+
+ it 'ranks the preferred location 0 and abstains for others' do
+ rankings = rule.rank(order, locations)
+ expect(rankings.find { |r| r.location == preferred }.rank).to eq(0)
+ expect(rankings.find { |r| r.location == other }.rank).to be_nil
+ end
+ end
+
+ context 'when no preferred location is set' do
+ let(:order) { build(:order, store: store) }
+
+ it 'abstains for every location' do
+ rankings = rule.rank(order, locations)
+ expect(rankings.map(&:rank)).to all(be_nil)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/order_routing/strategy/legacy_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/legacy_spec.rb
new file mode 100644
index 0000000000..f3e2445cb6
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/strategy/legacy_spec.rb
@@ -0,0 +1,61 @@
+require 'spec_helper'
+
+# Strategy::Legacy delegates to Spree::Stock::Coordinator and therefore
+# inherits its pre-routing behavior wholesale: every active location packed,
+# Prioritizer's Adjuster distributes units across packages, no merchant
+# routing rules consulted.
+RSpec.describe Spree::OrderRouting::Strategy::Legacy, type: :model do
+ let(:store) { @default_store }
+ let(:variant_a) { create(:variant) }
+ let(:variant_b) { create(:variant) }
+ let!(:nyc) { create(:stock_location, name: 'NYC', default: true) }
+ let!(:la) { create(:stock_location, name: 'LA', default: false) }
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ create(:line_item, order: o, variant: variant_b, quantity: 1)
+ o.reload
+ end
+
+ subject { described_class.new(order: order) }
+
+ it 'splits the allocation across both locations when neither single one covers the cart' do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ la.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+
+ packages = subject.for_allocation
+ location_ids = packages.map { |p| p.stock_location.id }
+
+ expect(location_ids).to contain_exactly(nyc.id, la.id)
+ expect(packages.flat_map(&:on_hand).size).to eq(2)
+ expect(packages.flat_map(&:backordered)).to be_empty
+ end
+
+ it 'ignores OrderRoutingRule rows entirely' do
+ # PreferredLocation rule would normally make `la` the winner; Legacy
+ # should not consult it.
+ Spree::OrderRouting::Rules::PreferredLocation
+ .where(channel: order.channel).destroy_all
+ Spree::OrderRouting::Rules::PreferredLocation.create!(
+ store: store, channel: order.channel, position: 0
+ )
+ order.update!(preferred_stock_location: la)
+
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ nyc.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ la.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+
+ expect_any_instance_of(Spree::OrderRoutingRule).not_to receive(:rank)
+ subject.for_allocation
+ end
+
+ describe 'lifecycle hooks' do
+ it 'for_sale, for_release, for_cancellation are no-ops' do
+ expect { subject.for_sale(fulfillment: nil) }.not_to raise_error
+ expect { subject.for_release }.not_to raise_error
+ expect { subject.for_cancellation }.not_to raise_error
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb
new file mode 100644
index 0000000000..9ff55181db
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb
@@ -0,0 +1,661 @@
+require 'spec_helper'
+
+# Strategy::Rules must match Strategy::Legacy (= Spree::Stock::Coordinator)
+# on every routing-relevant scenario the legacy pipeline supported. This
+# file runs the same shared examples against both strategies; failures
+# under Rules are regressions vs. pre-5.5 behavior. Failures under Legacy
+# mean the expectation itself is wrong.
+RSpec.describe 'OrderRouting strategy parity', type: :model do
+ let(:store) { @default_store }
+
+ shared_examples 'a routing strategy preserving Coordinator behavior' do
+ let!(:nyc) { create(:stock_location, name: 'NYC', default: true) }
+ let!(:la) { create(:stock_location, name: 'LA', default: false) }
+
+ let(:variant_a) { create(:variant) }
+ let(:variant_b) { create(:variant) }
+
+ subject(:strategy) { strategy_class.new(order: order) }
+
+ def location_units(packages)
+ packages.each_with_object({}) do |pkg, h|
+ h[pkg.stock_location.id] ||= { on_hand: 0, backordered: 0 }
+ h[pkg.stock_location.id][:on_hand] += pkg.on_hand.sum(&:quantity)
+ h[pkg.stock_location.id][:backordered] += pkg.backordered.sum(&:quantity)
+ end
+ end
+
+ def total_on_hand(packages)
+ packages.flat_map(&:on_hand).sum(&:quantity)
+ end
+
+ def total_backordered(packages)
+ packages.flat_map(&:backordered).sum(&:quantity)
+ end
+
+ # ---------------------------------------------------------------
+ # Single line_item, single location
+ # ---------------------------------------------------------------
+
+ context 'single line_item, single location, full coverage' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ before { nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10) }
+
+ it 'allocates from NYC, no backorder' do
+ units = location_units(strategy.for_allocation)
+ expect(units[nyc.id]).to eq(on_hand: 1, backordered: 0)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Multiple line_items, full coverage at one location
+ # ---------------------------------------------------------------
+
+ context 'two line_items both at NYC' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ create(:line_item, order: o, variant: variant_b, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ nyc.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+ end
+
+ it 'NYC covers everything, LA never engaged' do
+ units = location_units(strategy.for_allocation)
+ expect(units[nyc.id]).to eq(on_hand: 2, backordered: 0)
+ expect(units[la.id]).to be_nil
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Multi-location splits across distinct variants
+ # ---------------------------------------------------------------
+
+ context 'two line_items, one per location' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ create(:line_item, order: o, variant: variant_b, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ la.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+ end
+
+ it 'splits variant_a → NYC, variant_b → LA' do
+ units = location_units(strategy.for_allocation)
+ expect(units[nyc.id]).to eq(on_hand: 1, backordered: 0)
+ expect(units[la.id]).to eq(on_hand: 1, backordered: 0)
+ end
+ end
+
+ context 'three line_items, one per location' do
+ let(:variant_c) { create(:variant) }
+ let!(:berlin) { create(:stock_location, name: 'Berlin', default: false) }
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ create(:line_item, order: o, variant: variant_b, quantity: 1)
+ create(:line_item, order: o, variant: variant_c, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ la.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+ berlin.stock_item_or_create(variant_c).update!(count_on_hand: 10)
+ end
+
+ it 'splits across all three' do
+ units = location_units(strategy.for_allocation)
+ expect(units[nyc.id]).to eq(on_hand: 1, backordered: 0)
+ expect(units[la.id]).to eq(on_hand: 1, backordered: 0)
+ expect(units[berlin.id]).to eq(on_hand: 1, backordered: 0)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Single-variant quantity splits (the divergence we hit)
+ # ---------------------------------------------------------------
+
+ context 'one variant, quantity > top location, second location covers the rest' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 5)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 2)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ end
+
+ # Coordinator (Legacy) packs every location and splits NYC: 2 / LA: 3.
+ # Rules with MinimizeSplits prefers a single location when one
+ # covers the cart alone, so it routes everything to LA. Both
+ # outcomes are valid — the invariant the parity check enforces is
+ # that all 5 units are on_hand and none backordered.
+ it 'allocates 5 on_hand, 0 backordered (location distribution may differ)' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(5)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+
+ context 'one variant, quantity > all individual locations but ≤ combined' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 8)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 5)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 5)
+ end
+
+ it 'must split across both locations to avoid backorder' do
+ packages = strategy.for_allocation
+ units = location_units(packages)
+
+ # Neither location can cover qty 8 alone — both must be used.
+ expect(total_on_hand(packages)).to eq(8)
+ expect(total_backordered(packages)).to eq(0)
+ expect(units.keys).to contain_exactly(nyc.id, la.id)
+ end
+ end
+
+ context 'one variant, quantity > all locations combined' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 10)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 2, backorderable: true)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 3, backorderable: true)
+ end
+
+ it 'allocates available stock plus backorders the rest' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(5)
+ expect(total_backordered(packages)).to eq(5)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Mixed scenarios
+ # ---------------------------------------------------------------
+
+ context 'mixed: variant_a fully at NYC, variant_b qty 4 needs both' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 2)
+ create(:line_item, order: o, variant: variant_b, quantity: 4)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ nyc.stock_item_or_create(variant_b).update!(count_on_hand: 1)
+ la.stock_item_or_create(variant_b).update!(count_on_hand: 10)
+ end
+
+ it 'allocates 2 of variant_a and 1 of variant_b at NYC, 3 of variant_b at LA' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(6)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Backorder behavior
+ # ---------------------------------------------------------------
+
+ context 'no on-hand stock anywhere, variant is backorderable at NYC only' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 0, backorderable: true)
+ end
+
+ it 'returns a single backordered package' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(0)
+ expect(total_backordered(packages)).to eq(1)
+ end
+ end
+
+ context 'variant has stock_items but zero count, backorderable everywhere' do
+ let(:variant_unstocked) { create(:variant) }
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_unstocked, quantity: 1)
+ o.reload
+ end
+
+ before do
+ Spree::StockItem.where(variant_id: variant_unstocked.id).update_all(backorderable: true)
+ end
+
+ it 'returns a single backordered package' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(0)
+ expect(total_backordered(packages)).to eq(1)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Inventory tracking off (digital products, infinite supply)
+ # ---------------------------------------------------------------
+
+ context 'variant does not track inventory' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ li = create(:line_item, order: o, variant: variant_a, quantity: 5)
+ # Disable inventory tracking on the variant directly so the
+ # InventoryUnitBuilder + Packer treat it as infinite supply.
+ variant_a.update!(track_inventory: false)
+ o.reload
+ end
+
+ it 'allocates without consulting count_on_hand' do
+ packages = strategy.for_allocation
+ # All 5 units present, none backordered.
+ all_qty = packages.flat_map(&:contents).sum { |c| c.inventory_unit.quantity }
+ expect(all_qty).to eq(5)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Stock Reservations
+ # ---------------------------------------------------------------
+
+ context 'with stock reservations enabled' do
+ around do |ex|
+ original = Spree::Config[:stock_reservations_enabled]
+ Spree::Config[:stock_reservations_enabled] = true
+ ex.run
+ Spree::Config[:stock_reservations_enabled] = original
+ end
+
+ context 'another order holds a reservation at NYC' do
+ let(:other_order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 1)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+
+ # Other cart reserves the only NYC unit.
+ stock_item = nyc.stock_item(variant_a)
+ create(:stock_reservation,
+ stock_item: stock_item,
+ line_item: other_order.line_items.first,
+ order: other_order,
+ quantity: 1,
+ expires_at: 10.minutes.from_now)
+ end
+
+ it 'still produces packages — routing reads raw count_on_hand (documented caveat)' do
+ # Both Coordinator and Strategy::Rules read raw count_on_hand at
+ # the eligibility/packing layer; they don't subtract reservations.
+ # The AvailabilityValidator catches over-allocation at completion.
+ # Parity assertion: both strategies behave the same way here.
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages) + total_backordered(packages)).to eq(1)
+ end
+ end
+
+ context 'this order has its own reservation at NYC' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 5)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 5)
+
+ stock_item = nyc.stock_item(variant_a)
+ create(:stock_reservation,
+ stock_item: stock_item,
+ line_item: order.line_items.first,
+ order: order,
+ quantity: 1,
+ expires_at: 10.minutes.from_now)
+ end
+
+ it 'allocates the cart unaffected by its own reservation' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(1)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+
+ context 'expired reservations are ignored' do
+ let(:other_order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 1)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+
+ stock_item = nyc.stock_item(variant_a)
+ create(:stock_reservation,
+ stock_item: stock_item,
+ line_item: other_order.line_items.first,
+ order: other_order,
+ quantity: 1,
+ expires_at: 1.minute.ago)
+ end
+
+ it 'allocates as if the reservation did not exist' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(1)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+ end
+
+ context 'stock reservations globally disabled' do
+ around do |ex|
+ original = Spree::Config[:stock_reservations_enabled]
+ Spree::Config[:stock_reservations_enabled] = false
+ ex.run
+ Spree::Config[:stock_reservations_enabled] = original
+ end
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ before { nyc.stock_item_or_create(variant_a).update!(count_on_hand: 5) }
+
+ it 'allocates unaffected by reservation feature flag' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(1)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Splitter chain: shipping category split runs per-location
+ # ---------------------------------------------------------------
+
+ context 'two variants with different shipping categories at same location' do
+ let(:cat_light) { create(:shipping_category, name: 'Light') }
+ let(:cat_heavy) { create(:shipping_category, name: 'Heavy') }
+
+ let(:variant_light) { create(:variant, product: create(:product, shipping_category: cat_light, stores: [store])) }
+ let(:variant_heavy) { create(:variant, product: create(:product, shipping_category: cat_heavy, stores: [store])) }
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_light, quantity: 1)
+ create(:line_item, order: o, variant: variant_heavy, quantity: 1)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_light).update!(count_on_hand: 10)
+ nyc.stock_item_or_create(variant_heavy).update!(count_on_hand: 10)
+ end
+
+ # The ShippingCategory splitter is in the default Spree.stock_splitters
+ # chain — Coordinator and Rules both pass it to the Packer, so each
+ # location's allocation gets fanned out into one package per shipping
+ # category. Both pipelines should produce 2 NYC packages here.
+ it 'produces two NYC packages, one per shipping category' do
+ packages = strategy.for_allocation
+ nyc_packages = packages.select { |p| p.stock_location.id == nyc.id }
+ expect(nyc_packages.size).to eq(2)
+ categories = nyc_packages.flat_map { |p| p.contents.map { |c| c.variant.product.shipping_category_id } }.uniq
+ expect(categories).to contain_exactly(cat_light.id, cat_heavy.id)
+ expect(total_on_hand(packages)).to eq(2)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Inactive locations: excluded from candidates
+ # ---------------------------------------------------------------
+
+ context 'one location inactive, the other active' do
+ before do
+ # Mark NYC inactive after the variant's after(:create) hook has
+ # propagated stock_items to it.
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ nyc.update!(active: false)
+ end
+
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ o.reload
+ end
+
+ # Coordinator filters via `Spree::StockLocation.active`; Rules does
+ # the same. NYC must be invisible to both pipelines.
+ it 'routes to LA, NYC is not a candidate' do
+ units = location_units(strategy.for_allocation)
+ expect(units[la.id]).to eq(on_hand: 1, backordered: 0)
+ expect(units[nyc.id]).to be_nil
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Asymmetric stocking: variant present at only one location
+ # ---------------------------------------------------------------
+
+ context 'variant only stocked at LA, NYC has no stock_item for it' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 2)
+ o.reload
+ end
+
+ before do
+ # Drop the auto-propagated NYC stock_item entirely so NYC truly
+ # doesn't stock variant_a (Coordinator's eligible-locations join
+ # filters by stock_item presence; we want to exercise that path).
+ nyc.stock_items.where(variant_id: variant_a.id).destroy_all
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ end
+
+ it 'routes everything to LA' do
+ units = location_units(strategy.for_allocation)
+ expect(units[la.id]).to eq(on_hand: 2, backordered: 0)
+ expect(units[nyc.id]).to be_nil
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Zero on_hand + non-backorderable everywhere → packages drop
+ # ---------------------------------------------------------------
+
+ context 'every location has count_on_hand: 0 and is not backorderable' do
+ let(:order) do
+ # Stock available during line-item creation (so AvailabilityValidator
+ # passes), then dropped to 0 + non-backorderable to model the
+ # "no eligible inventory" routing scenario.
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10, backorderable: false)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 10, backorderable: false)
+
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ nyc.stock_item(variant_a).update!(count_on_hand: 0)
+ la.stock_item(variant_a).update!(count_on_hand: 0)
+ o.reload
+ end
+
+ it 'returns no packages with on_hand or backordered units' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(0)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Mixed track_inventory: tracked + untracked variants together
+ # ---------------------------------------------------------------
+
+ context 'order with one tracked variant and one untracked variant' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 1)
+ create(:line_item, order: o, variant: variant_b, quantity: 1)
+ # variant_b is untracked.
+ variant_b.update!(track_inventory: false)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 10)
+ # variant_b has no on_hand anywhere — but track_inventory: false
+ # means Packer adds it directly without consulting fill_status.
+ end
+
+ it 'allocates both variants on_hand at NYC' do
+ packages = strategy.for_allocation
+ nyc_qty = packages
+ .select { |p| p.stock_location.id == nyc.id }
+ .flat_map(&:contents).sum { |c| c.inventory_unit.quantity }
+ expect(nyc_qty).to eq(2)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Partial backorder distribution: top covers some, second backorders
+ # ---------------------------------------------------------------
+
+ context 'top location has 1 on_hand, second is 0 + backorderable, qty 3' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 3)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 1, backorderable: false)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 0, backorderable: true)
+ end
+
+ # The Adjuster's update_backorder only shrinks a captured backorder
+ # quantity when it sees ANOTHER on_hand item afterward — so when the
+ # only on_hand item is processed before the backorder is captured,
+ # the captured backorder quantity is the full fill_status backorder
+ # (3 here). Result: 1 on_hand at NYC + 3 backordered at LA = 4 units
+ # total in packages even though the order only needs 3. This is
+ # legacy Coordinator behavior; both pipelines must agree.
+ it 'matches legacy behavior: 1 on_hand at NYC, full backorder at LA' do
+ packages = strategy.for_allocation
+ # At least the on_hand is captured.
+ expect(total_on_hand(packages)).to eq(1)
+ # Backorder package preserves the requirement quantity from
+ # fill_status (3); Adjuster doesn't reconcile it against the
+ # 1 on_hand received earlier.
+ expect(total_backordered(packages)).to eq(3)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # All locations zero stock + all backorderable
+ # ---------------------------------------------------------------
+
+ context 'all locations have zero stock and are all backorderable' do
+ let(:order) do
+ o = create(:order, store: store, ship_address: create(:ship_address))
+ create(:line_item, order: o, variant: variant_a, quantity: 2)
+ o.reload
+ end
+
+ before do
+ nyc.stock_item_or_create(variant_a).update!(count_on_hand: 0, backorderable: true)
+ la.stock_item_or_create(variant_a).update!(count_on_hand: 0, backorderable: true)
+ end
+
+ it 'backorders all units at a single location' do
+ packages = strategy.for_allocation
+ expect(total_on_hand(packages)).to eq(0)
+ expect(total_backordered(packages)).to eq(2)
+ # Prioritizer collapses redundant backordered packages — the
+ # Adjuster strips backordered units from all but one package
+ # whenever the same variant appears in multiple. Both pipelines
+ # should converge on a single backordered package.
+ backordered_locs = packages.reject { |p| p.backordered.empty? }.map { |p| p.stock_location.id }
+ expect(backordered_locs.size).to eq(1)
+ end
+ end
+
+ # ---------------------------------------------------------------
+ # Empty cart
+ # ---------------------------------------------------------------
+
+ context 'order with no line items' do
+ let(:order) do
+ create(:order, store: store, ship_address: create(:ship_address))
+ end
+
+ it 'returns no packages' do
+ # No inventory units → no requested_variant_ids → no eligible
+ # locations → empty package list. Same for both pipelines.
+ packages = strategy.for_allocation
+ expect(packages).to eq([]).or be_empty
+ expect(total_on_hand(packages)).to eq(0)
+ expect(total_backordered(packages)).to eq(0)
+ end
+ end
+ end
+
+ describe Spree::OrderRouting::Strategy::Legacy do
+ let(:strategy_class) { described_class }
+ it_behaves_like 'a routing strategy preserving Coordinator behavior'
+ end
+
+ describe Spree::OrderRouting::Strategy::Rules do
+ let(:strategy_class) { described_class }
+ it_behaves_like 'a routing strategy preserving Coordinator behavior'
+ end
+end
diff --git a/spree/core/spec/models/spree/order_routing/strategy/reducer_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/reducer_spec.rb
new file mode 100644
index 0000000000..6f33ba4851
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/strategy/reducer_spec.rb
@@ -0,0 +1,63 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OrderRouting::Strategy::Reducer, type: :model do
+ let(:order) { build(:order, store: @default_store) }
+
+ let(:loc_a) { create(:stock_location, name: 'A', default: true) }
+ let(:loc_b) { create(:stock_location, name: 'B') }
+ let(:loc_c) { create(:stock_location, name: 'C') }
+ let(:locations) { [loc_a, loc_b, loc_c] }
+
+ # Test rule that returns canned rankings instead of running real logic.
+ def fake_rule(rankings)
+ instance_double(Spree::OrderRoutingRule).tap do |dbl|
+ allow(dbl).to receive(:rank) { |_o, _locs| rankings }
+ end
+ end
+
+ def ranking(loc, rank)
+ Spree::OrderRoutingRule::LocationRanking.new(location: loc, rank: rank)
+ end
+
+ it 'returns nil when no locations are eligible' do
+ expect(described_class.new([], order: order).pick([])).to be_nil
+ end
+
+ it 'returns the unique winner of the first rule that has one' do
+ rules = [
+ fake_rule([ranking(loc_a, nil), ranking(loc_b, nil), ranking(loc_c, nil)]), # all abstain
+ fake_rule([ranking(loc_a, 5), ranking(loc_b, 1), ranking(loc_c, 5)]) # B wins
+ ]
+
+ expect(described_class.new(rules, order: order).pick(locations)).to eq(loc_b)
+ end
+
+ it 'carries ties forward to the next rule' do
+ rules = [
+ fake_rule([ranking(loc_a, 0), ranking(loc_b, 0), ranking(loc_c, 1)]), # A & B tie
+ fake_rule([ranking(loc_a, 5), ranking(loc_b, 1), ranking(loc_c, 0)]) # B beats A in tied set
+ ]
+
+ expect(described_class.new(rules, order: order).pick(locations)).to eq(loc_b)
+ end
+
+ it 'falls back to the default location when rules tie all the way through' do
+ rules = [
+ fake_rule([ranking(loc_a, 0), ranking(loc_b, 0), ranking(loc_c, 0)]) # all tie
+ ]
+
+ expect(described_class.new(rules, order: order).pick(locations)).to eq(loc_a) # loc_a is default
+ end
+
+ it 'falls back to default when there are no rules at all' do
+ expect(described_class.new([], order: order).pick(locations)).to eq(loc_a)
+ end
+
+ it 'ignores abstaining (nil) rankings' do
+ rules = [
+ fake_rule([ranking(loc_a, nil), ranking(loc_b, nil), ranking(loc_c, 0)]) # only C ranked
+ ]
+
+ expect(described_class.new(rules, order: order).pick(locations)).to eq(loc_c)
+ end
+end
diff --git a/spree/core/spec/models/spree/order_routing/strategy/rules_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/rules_spec.rb
new file mode 100644
index 0000000000..f8be7204de
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/strategy/rules_spec.rb
@@ -0,0 +1,39 @@
+require 'spec_helper'
+
+# Integration scenarios for the default routing strategy. Per-rule semantics
+# live in spec/models/spree/order_routing/rules/*. Reducer mechanics live in
+# spec/models/spree/order_routing/strategy/reducer_spec.rb. This file just
+# verifies the strategy plumbs them together end-to-end.
+RSpec.describe Spree::OrderRouting::Strategy::Rules, type: :model do
+ let(:store) { @default_store }
+ let(:variant) { create(:variant) }
+
+ let!(:default_loc) { create(:stock_location, name: 'Default', default: true) }
+ let!(:preferred_loc) { create(:stock_location, name: 'Preferred', default: false) }
+
+ let(:order) do
+ create(:order_with_line_items, store: store, line_items_attributes: [{ variant: variant, quantity: 1 }])
+ end
+
+ before do
+ [default_loc, preferred_loc].each do |loc|
+ loc.stock_item_or_create(variant).update!(count_on_hand: 10)
+ end
+ end
+
+ subject { described_class.new(order: order) }
+
+ describe '#for_allocation (rules engaged)' do
+ it 'routes to the default location when no preference is set' do
+ packages = subject.for_allocation
+ expect(packages.map(&:stock_location)).to all(eq(default_loc))
+ end
+
+ it 'routes to the preferred location when set on the order' do
+ order.update!(preferred_stock_location: preferred_loc)
+
+ packages = subject.for_allocation
+ expect(packages.map(&:stock_location)).to all(eq(preferred_loc))
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/order_routing_rule_spec.rb b/spree/core/spec/models/spree/order_routing_rule_spec.rb
new file mode 100644
index 0000000000..5310dbfc0e
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing_rule_spec.rb
@@ -0,0 +1,85 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OrderRoutingRule, type: :model do
+ let(:store) { @default_store }
+ let(:channel) { store.default_channel }
+
+ describe 'validations' do
+ it 'requires a type' do
+ rule = described_class.new(store: store, channel: channel, position: 1)
+ expect(rule).not_to be_valid
+ expect(rule.errors[:type]).to be_present
+ end
+
+ it 'requires a channel' do
+ rule = Spree::OrderRouting::Rules::PreferredLocation.new(store: store, position: 1)
+ expect(rule).not_to be_valid
+ expect(rule.errors[:channel]).to be_present
+ end
+
+ it 'is valid when instantiated as an STI subclass with a channel' do
+ rule = Spree::OrderRouting::Rules::PreferredLocation.new(store: store, channel: channel, position: 1)
+ expect(rule).to be_valid
+ end
+
+ it 'rejects rules whose channel belongs to a different store' do
+ foreign_channel = create(:store).default_channel
+ rule = Spree::OrderRouting::Rules::PreferredLocation.new(
+ store: store, channel: foreign_channel, position: 1
+ )
+
+ expect(rule).not_to be_valid
+ expect(rule.errors[:channel]).to include(Spree.t('errors.messages.channel_store_mismatch'))
+ end
+ end
+
+ describe 'scopes' do
+ # Channels seed 3 default rules on create. We test scopes against fresh rules
+ # in a clean channel to avoid coupling to the seed list.
+ let(:fresh_channel) { create(:store).default_channel.tap { |c| c.order_routing_rules.destroy_all } }
+ let(:fresh_store) { fresh_channel.store }
+ let!(:active_rule) do
+ Spree::OrderRouting::Rules::PreferredLocation.create!(
+ store: fresh_store, channel: fresh_channel, position: 1, active: true
+ )
+ end
+ let!(:inactive_rule) do
+ Spree::OrderRouting::Rules::MinimizeSplits.create!(
+ store: fresh_store, channel: fresh_channel, position: 2, active: false
+ )
+ end
+
+ it 'filters by active' do
+ expect(described_class.for_channel(fresh_channel).active).to contain_exactly(active_rule)
+ end
+
+ it 'orders by position' do
+ expect(described_class.for_channel(fresh_channel).ordered.map(&:type))
+ .to eq(%w[Spree::OrderRouting::Rules::PreferredLocation Spree::OrderRouting::Rules::MinimizeSplits])
+ end
+
+ it 'for_channel returns rules belonging to that channel only' do
+ other_channel = fresh_store.channels.create!(name: 'POS', code: 'pos')
+ # Both channels seed 3 default rules each; we just verify the scope partitions them.
+ expect(described_class.for_channel(fresh_channel)).to contain_exactly(active_rule, inactive_rule)
+ expect(described_class.for_channel(other_channel).count).to eq(3)
+ expect(described_class.for_channel(other_channel).pluck(:channel_id)).to all(eq(other_channel.id))
+ end
+ end
+
+ describe '#rank' do
+ let(:order) { build(:order, store: store) }
+ let(:locations) { [create(:stock_location)] }
+
+ it 'is implemented by subclasses' do
+ rule = Spree::OrderRouting::Rules::DefaultLocation.create!(store: store, channel: channel, position: 99)
+ rankings = rule.rank(order, locations)
+ expect(rankings).to all(be_a(Spree::OrderRoutingRule::LocationRanking))
+ end
+
+ it 'raises NotImplementedError on the base class' do
+ rule = described_class.new(store: store, channel: channel, position: 99)
+ expect { rule.rank(order, locations) }.to raise_error(NotImplementedError)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 7279ead24b..04f4a26070 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -1554,6 +1554,57 @@ describe Spree::Order, type: :model do
end
end
+ it 'assigns the routing strategy returned packages, mapped to shipments' do
+ package = instance_double(Spree::Stock::Package)
+ shipment = build(:shipment)
+ allow(package).to receive(:to_shipment).and_return(shipment)
+
+ strategy = instance_double(Spree::OrderRouting::Strategy::Rules)
+ allow(strategy).to receive(:for_allocation).and_return([package])
+ allow(subject).to receive(:order_routing_strategy).and_return(strategy)
+
+ subject.create_proposed_shipments
+ expect(subject.shipments).to eq [shipment]
+ end
+ end
+
+ describe '#order_routing_strategy' do
+ it 'instantiates the strategy class configured on the store' do
+ strategy = order.order_routing_strategy
+ expect(strategy).to be_a(Spree::OrderRouting::Strategy::Rules)
+ expect(strategy.order).to eq(order)
+ end
+
+ it 'honors a custom store-level preference' do
+ stub_const('CustomStrategy', Class.new(Spree::OrderRouting::Strategy::Base))
+ # Use a transient store so the preference change rolls back with the
+ # transaction; mutating @default_store would leak across examples.
+ isolated_store = create(:store)
+ isolated_store.preferred_order_routing_strategy = 'CustomStrategy'
+ isolated_order = create(:order, store: isolated_store)
+
+ expect(isolated_order.order_routing_strategy).to be_a(CustomStrategy)
+ end
+
+ it 'lets a channel preference override the store preference' do
+ stub_const('ChannelStrategy', Class.new(Spree::OrderRouting::Strategy::Base))
+ isolated_store = create(:store)
+ channel = isolated_store.channels.first
+ channel.preferred_order_routing_strategy = 'ChannelStrategy'
+ channel.save!
+ isolated_order = create(:order, store: isolated_store, channel: channel)
+
+ expect(isolated_order.order_routing_strategy).to be_a(ChannelStrategy)
+ end
+
+ it 'falls back to the store preference when channel preference is blank' do
+ isolated_store = create(:store)
+ channel = isolated_store.channels.first
+ isolated_order = create(:order, store: isolated_store, channel: channel)
+
+ expect(channel.preferred_order_routing_strategy).to be_blank
+ expect(isolated_order.order_routing_strategy).to be_a(Spree::OrderRouting::Strategy::Rules)
+ end
end
describe '#ensure_channel_presence' do
@@ -1573,6 +1624,19 @@ describe Spree::Order, type: :model do
end
end
+ describe '#inferred_preferred_stock_location_id' do
+ let(:preferred) { create(:stock_location) }
+
+ it 'returns the explicit value when set' do
+ order.preferred_stock_location_id = preferred.id
+ expect(order.inferred_preferred_stock_location_id).to eq(preferred.id)
+ end
+
+ it 'returns nil when nothing in the cascade is set' do
+ expect(order.inferred_preferred_stock_location_id).to be_nil
+ end
+ end
+
describe '#all_inventory_units_returned?' do
subject { order.all_inventory_units_returned? }