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.
Order Routing
Status: In Progress — Phase 1 implemented in 5.5 (Channel + OrderRoutingRule + strategy base/Rules/Reducer/Legacy); rules admin (Admin API v3 + React dashboard editor, no legacy Rails admin — see decisions.md 2026-07-21) shipped in 5.6; rest of Phase 2+ pending in 6.0
Target: Spree 5.5 (Phase 1 ✓) → 5.6 (rules admin ✓) → 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-07-21
Summary
Replace the implicit, hard-to-extend stock-location selection that lives inside Spree::Stock::Coordinator + Prioritizer with a layered, two-tier extension model:
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 once6.0-channels-catalogs-b2b.mdlands.Spree::OrderRouting::Strategy::Rules— the only concrete strategy in core. WalksSpree::OrderRoutingRulerows in priority order, applies a Shopify-style reducer, returnsSpree::Stock::Package[].Spree::OrderRoutingRuleSTI 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) and registering it viaSpree.order_routing.rules. The persistedtypecolumn drives runtime polymorphism; the registry is the allowlist for admin pickers +typevalidation. MirrorsSpree::PromotionRule/Spree::PromotionAction(STI and registered viaconfig.spree.promotions.rules).
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.
Since then (2026-09-02): sort_packages is no longer empty — it puts origins that can actually deliver to the destination ahead of the ones that cannot, because a profile with per-region origin groups was allocating to whichever warehouse came first and losing the item when that warehouse's group had no method for the address (see 6.0-delivery-profiles.md). That is a correctness floor, not the merchant-controllable ordering this plan is about: it has no configuration and expresses no preference beyond "can ship" over "cannot". Rank still decides between origins that can both deliver, so a strategy's ordering survives — but a strategy must not assume its rank is the last word.
Since then (2026-10-26): demotion alone did not keep units away from an origin that cannot deliver, since the Adjuster takes stock on hand anywhere over a backorder. Such an origin now gives up every unit the capable origins can supply between them. Rules#for_allocation also packs its ranked locations through Stock::Coordinator#allocated_packages(locations) instead of its own packers, then quotes them with Coordinator#estimate_packages, so an order allocates under the same delivery profile and channel coverage as its cart — before, an order could take stock from a location the item's profile excludes (decisions.md, 2026-10-26).
2. No merchant configuration
Stores with multiple StockLocations 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:
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 and registering it via Spree.order_routing.rules:
# 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, autoloaded, and registered, 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 patterns that pair STI with a config.spree.* registry. Register rule kinds in config.after_initialize (or a plugin initializer) so they're available after autoload, the same way core registers the three built-ins.
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:
- Drop rankings where
rankisnil(rule abstains). - Find the location(s) with the lowest rank for this rule.
- If unique → that's the winner. Stop.
- If tied → carry the tied set to the next rule.
- Ran out of rules with ties → pick
StockLocation.default, then byid.
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)
# Spree::Store
preference :order_routing_strategy, :string, default: 'Spree::OrderRouting::Strategy::Rules'
Resolved on Order via:
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:
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 Shipments. 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 section in the dev guide for the user-facing version.
Phase 3 makes routing the canonical owner of the location decision. The handoff:
Reservestops picking a location. Cart-time reservations are held against the variant total, not a specificstock_item. Schema change:spree_stock_reservations.stock_item_idbecomes nullable; a non-nullstock_item_idmeans "pinned by routing."Quantifier#reserved_quantityshifts fromSUM(quantity) WHERE stock_item_id IN (...)toSUM(quantity) WHERE variant_id = ?(withstock_item_id IS NULLrows counting against any of the variant's locations).Strategy#for_allocationpins reservations. When the strategy chooses location L for variant V's units, itUPDATEs the unpinned reservation rows for that(order, variant)pair to setstock_item_idto L's stock_item. This becomes the moment "we reserve units at this specific location."for_sale(fulfillment:)writes typedshippedmovements. Pinned reservation row stays alive until shipment ships; onafter_ship, the strategy writes a typedshippedmovement that decrementscount_on_handat the pinned location, then deletes the reservation.for_releasewrites typedreleasedmovements. When a checkout reverts to cart or the reservation expires, pinned rows are released — typedreleasedmovement is conceptually a no-op on stock today, but lets us audit the lifecycle.for_cancellationwrites typedreceivedmovements. 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_allocationcall 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
Reserveinvariantvalidates :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 Packages for a four-line cart produces two Shipments. 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
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
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)
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
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
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:
# 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:
Stock::Coordinator#candidate_stock_locations— fetch active locations stocking any cart variant.Reducer#rank_all— full ranking, best-first.Stock::Coordinator#allocated_packages(ranked)— onePackerper location, given only the units the item's delivery profile and the order's channel allow it; each emits one or more packages depending on the configured splitters.Spree::Stock::Prioritizer#prioritized_packages(inside the Coordinator) — origins that can deliver go first and take every unit they can supply; then the Adjuster walks packages in rank order, assigns each unit to the first package with on-hand stock, and prunes empty packages.Stock::Coordinator#estimate_packages— the Coordinator'sEstimatorattaches 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.
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
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
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
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
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.
class Spree::Store < Spree.base_class
after_create :ensure_default_channel
private
def ensure_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 :ensure_default_order_routing_rules
private
def ensure_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 + dashboard editor (shipped in 5.6)
Phase 1 shipped no admin UI for routing rules — the 5.5 default seed (3 rules per store) covered the wedge case, plus a small admin API change:
PATCH /api/v3/admin/orders/:id { preferred_stock_location_id: "sloc_..." }
The rules-management slice of Phase 2 shipped in 5.6, React dashboard only — no legacy Rails admin UI (decisions.md 2026-07-21):
- Admin API v3: nested CRUD
/api/v3/admin/channels/:channel_id/order_routing_rules(mirrors promotion rules:SubclassedResource,scoped_resource :settings, flat paramstype/active/position/preferences) + top-levelGET /order_routing_rules/typesdiscovery driven bysubclasses_with_preference_schemaoverSpree.order_routing.rules. Create withoutpositionappends at the end of the channel's list; updatingpositionreorders around it (acts_as_list). The STItypeis immutable after create — delete and re-create to change kind. - One rule per kind per channel — a duplicate signal would either be a no-op or fight itself in the reducer walk. Enforced by a unique DB index on
(channel_id, type)+ model uniqueness validation, and the dashboard picker only offers kinds not yet on the channel (mirrorsPromotionRule's per-promotion type uniqueness). @spree/admin-sdk:client.channels.orderRoutingRules.{list,get,create,update,delete}+client.orderRoutingRules.types().- Dashboard: routing-rules editor embedded in the channel edit sheet (
OrderRoutingRulesSection) — dnd-kit drag-to-reorder, per-rule active switches, "Add rule" picker fed by the types endpoint, per-rule preference editing via the schema-drivenPreferencesForm. Plugin-registered rule kinds appear automatically with their preference schemas (answers old Open Question 3 — no separateconfig_schemaneeded). The section renders only when the channel's effective strategy isRules— the channel override, falling back to the store preference (now exposed aspreferred_order_routing_strategyon the admin Store serializer).
Remaining Phase 2 scope (new rule kinds, Channel FK additions) is unchanged below.
Migration Path
Phase 1 — 5.5 (this work)
- Migration:
spree_channelstable. - Migration:
Order.channel(deprecated string) →Order.channel_idFK. - Migration:
spree_order_routing_rulestable (typeSTI discriminator,channel_idNOT NULL). - Migration:
Order.preferred_stock_location_idFK. - Model:
Spree::Channel— minimal (store,name,code,active, preferences, metafields). No catalogs, no listings — those land in 6.0. - Model:
Spree::OrderRoutingRuleSTI base +LocationRankingstruct +for_channelscope +channel_belongs_to_storevalidator. - Strategy classes:
OrderRouting::Strategy::Base,OrderRouting::Strategy::Rules,OrderRouting::Strategy::Legacy(escape hatch),Reducer(with bothpickandrank_all). - STI subclasses:
Spree::OrderRouting::Rules::PreferredLocation,MinimizeSplits,DefaultLocation. - Preferences:
Store#preferred_order_routing_strategy(default),Channel#preferred_order_routing_strategy(override). - Order:
preferred_stock_locationassociation,channelassociation (auto-defaults tostore.default_channel),inferred_preferred_stock_location_id,order_routing_strategy(channel pref → store pref fallback). Strategy::Rules#applicable_ruleswalksorder.channel.order_routing_rules.active.ordered— single-axis lookup, every rule belongs to a channel.- Replace
Order#create_proposed_shipmentsCoordinator call. - Store after_create:
ensure_default_channelcreates one'online'channel. - Channel after_create:
ensure_default_order_routing_rulescreates the 3 default rules tied to the channel. - Data migration: seed default channel + 3 rules per existing store.
- Admin API: expose
preferred_stock_location_idon Order. - Tests: strategy + each rule subclass + reducer + integration test for
Order#create_proposed_shipmentshonoringpreferred_stock_location_id+ channel-scoped rules and strategy override. - Parity tests:
spec/models/spree/order_routing/strategy/parity_spec.rbruns shared examples against bothStrategy::LegacyandStrategy::Rulesto 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_idFK.Channel.preferred_stock_location_id(or similar) for B2B / staff-default cascade input.Channel.default_catalog_idFK (added whenCatalogships).CompanyLocation.preferred_stock_location_idFK.Spree::Admin::User.preferred_stock_location_idFK (staff sign-in default).Admin API + SPA settings page for channels and per-channel routing rules.Shipped in 5.6 (see "Admin API + dashboard editor" above).- 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:
- Schema:
spree_stock_reservations.stock_item_idbecomes nullable.variant_idadded (NOT NULL, FK), allowing reservations to be held against a variant total before location pinning. Spree::StockReservations::Reserveno longer picks a location.select_stock_itemis removed; the service writes reservations withstock_item_id: nilandvariant_id: variant.id.Spree::Stock::Quantifier#reserved_quantitysums all reservations for the variant — pinned ones (subtract from the pinnedstock_item.count_on_hand) and unpinned (subtract from the variant's pool, no specific location).Strategy#for_allocationpins reservations. When the chosen location is decided, the strategyUPDATEs the order's unpinned reservations for the variant to setstock_item_id. This happens in the same transaction ascreate_proposed_shipments.Strategy#for_sale(fulfillment:)writes a typedkind: 'shipped'Spree::StockMovementand deletes the now-redundant pinned reservation. Replaces the implicitShipment#after_ship → StockLocation#unstockpath.Strategy#for_releasewrites a typedkind: 'released'movement (audit trail) and deletes the unpinned reservation. Wired from cart-revert and TTL expiry paths.Strategy#for_cancellationwrites a typedkind: 'received'movement at the location the order shipped from and creates a restocking entry.- 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 — theirfor_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). Packages becomeFulfillments (renamed from Shipment).for_allocationreturning empty →fulfillment_status: 'on_hold'.Exchange#shipmentsmigrates 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::CoordinatororPrioritizer. They're being absorbed intoOrderRouting::Strategy::Rulesas implementation detail. - Don't hardcode
StockLocation.defaultselection in new code. Take the location as an argument or callorder.order_routing_strategy.for_allocation. - Don't add per-channel routing logic to
Channel— it lives onOrderRoutingRule. 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 in6.0-channels-catalogs-b2b.md. - New rule kinds subclass
Spree::OrderRoutingRuledirectly (STI) and register the class viaSpree.order_routing.rules << MyRule. STI still does the runtime dispatch via thetypecolumn — the registry is the curated allowlist of available/valid kinds (it backs admin pickers and thetypeinclusion validation), not a dispatch table. Don't addif rule.is_a?(Foo)branches toRulesstrategy or the reducer; rule classes own their own#ranklogic.
Resolved Questions
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.
Rule reducer model. First non-tie wins (Shopify-style). Weighted-sum scoring rejected — too unpredictable for merchants tuning config.
Strategy registration. Two layers. Selection is a Per-Store preference (Phase 1) → per-Channel preference falling back to Store (Phase 2) — NOT
Spree::Dependencies, which would bake "one strategy per app" into the API. Availability is an allowlist registry:Spree.order_routing.strategies(Spree's standardconfig.spree.*extension-point convention, alongsidecalculators,stock_splitters,payment_methods). Core registersStrategy::RulesandStrategy::Legacy; plugins register their own and may unregister (e.g. dropLegacy). Models readSpree.order_routing.strategiesdirectly (no wrapper API), like every otherconfig.spree.*extension point. A strategy must be both aStrategy::Basesubclass and registered to be selectable —Store#preferred_order_routing_strategy/Channel#preferred_order_routing_strategyvalidate inclusion in the registry, andOrder#order_routing_strategyonly instantiates registered classes (unregistering or a stale persisted value falls back to the defaultRulesrather than raising). This replaces the original "validate byStrategy::Basesubclass only" check and is what closes the class of bug where a non-strategy (e.g. the internalReducercollaborator) could be selected.Where the strategy fires. Today:
Order#create_proposed_shipments. Phase 4:Spree::Carts::Completeper6.0-cart-order-split.md.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.
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.
Defaultstrategy class? None. The default strategy isRules. The default behavior comes from seeded rules. Avoids "Default vs Rules" confusion when both would coexist.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::Prioritizerwalks 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.Legacy strategy escape hatch in 5.x. Ship
Spree::OrderRouting::Strategy::Legacy(a thin wrapper aroundSpree::Stock::Coordinator) so merchants who heavily customizedCoordinator/Packer/Prioritizerin 5.4 can opt out of rules-based routing during the upgrade window viastore.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Legacy'). Documented in the 5.4-to-5.5 upgrade guide. Drops in 6.0 along withCoordinator.
Open Questions
Geocoder gem in core OSS.
closest_locationrule (Phase 2) needs distance calculation. Lean toward bundlinggeocodergem with lazy lat/lng onStockLocation. Defer decision to Phase 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.
Custom rules in admin UI.Resolved in 5.6: no separateconfig_schema— the existingSpree::PreferenceSchema(preference :name, :typedeclarations →preference_schemaon the/typespayload) drives the dashboard's schema-drivenPreferencesForm, same as promotion rules/actions. Plugin rule kinds render automatically once registered.Reservation-aware eligibility. Phase 1 routing reads raw
count_on_handfromSpree::StockItem— neitherOrderRouting::Strategy::Rules#eligible_locations(existence check) norRules::MinimizeSplits(coverage check) subtract activeSpree::StockReservationquantities. Reservations still protect at theQuantifierlayer (can_supply?gates entry) and at order completion (AvailabilityValidator), so a routing decision against reservation-held stock fails closed rather than oversells. Going throughQuantifierper location × variant adds a SUM query per cell, which is too costly for the eligibility hot path. Revisit when6.0-typed-stock-movements.mdlands theallocated_countcolumn onSpree::StockItem— that letsavailable_countbecome 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 (
sort_packagesdemotes origins that cannot reach the destination,withdraw_covered_itemstakes from them every unit the others can supply):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