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.

Order routing strategy & rule registries with allowlist validation (#14142)

Damian Legawieca3bf791c9603
diff --git a/docs/developer/how-to/custom-order-routing.mdx b/docs/developer/how-to/custom-order-routing.mdx
index 04b4e36552..de37b42171 100644
--- a/docs/developer/how-to/custom-order-routing.mdx
+++ b/docs/developer/how-to/custom-order-routing.mdx
@@ -89,7 +89,12 @@ Spree::OrderRouting::Rules::ClosestLocation.create!(
)
```
-Spree's autoloader picks up models under `app/models/` automatically — no separate registration step.
+Register the rule kind so it's available to add and passes the `type` validation. Spree's autoloader picks up the model under `app/models/`; the registry is the curated allowlist (it also drives admin pickers):
+
+```ruby
+# config/initializers/spree.rb
+Spree.order_routing.rules << 'AcmeFresh::OrderRouting::RefrigeratedRule'.constantize
+```
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.
@@ -224,7 +229,17 @@ Notes:
### Step 2: Register the Strategy
-Strategies are selected by class name string — set on `Spree::Store` (default) or `Spree::Channel` (override).
+First register the class so it's selectable (this is the allowlist the model validation checks against, and the source for admin strategy pickers):
+
+```ruby
+# config/initializers/spree.rb
+Spree.order_routing.strategies << 'Acme::Oms::Strategy'.constantize
+
+# Optionally drop the legacy escape hatch:
+# Spree.order_routing.strategies.delete(Spree::OrderRouting::Strategy::Legacy)
+```
+
+Then select it by class name string — set on `Spree::Store` (default) or `Spree::Channel` (override). Setting an unregistered class fails validation.
Activate on the whole store:
@@ -243,7 +258,7 @@ store.channels.find_by(code: 'pos').update!(
)
```
-Resolution order: `channel.preferred_order_routing_strategy` → `store.preferred_order_routing_strategy` → the default `Strategy::Rules`. Only a value that points to a real `Strategy::Base` subclass is used; anything unset or invalid is skipped, so a misconfigured strategy falls back to the default instead of breaking checkout.
+Resolution order: `channel.preferred_order_routing_strategy` → `store.preferred_order_routing_strategy` → the default `Strategy::Rules`. Only a value pointing to a **registered** `Strategy::Base` subclass is used; anything unset, unregistered, or invalid is skipped, so a misconfiguration (or a strategy you've since unregistered) falls back to the default instead of breaking checkout.
### Step 3: Test the Strategy
diff --git a/docs/plans/6.0-order-routing.md b/docs/plans/6.0-order-routing.md
index 0e20fff479..2e9260df89 100644
--- a/docs/plans/6.0-order-routing.md
+++ b/docs/plans/6.0-order-routing.md
@@ -12,7 +12,7 @@ Replace the implicit, hard-to-extend stock-location selection that lives inside
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`.
+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`) and registering it via `Spree.order_routing.rules`. The persisted `type` column drives runtime polymorphism; the registry is the allowlist for admin pickers + `type` validation. Mirrors `Spree::PromotionRule`/`Spree::PromotionAction` (STI **and** registered via `config.spree.promotions.rules`).
The two extension points address fundamentally different needs:
@@ -80,7 +80,7 @@ class Spree::OrderRouting::Rules::DefaultLocation < Spree::OrderRoutingRule; e
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:
+Plugins extend by defining a new subclass and registering it via `Spree.order_routing.rules`:
```ruby
# In a plugin
@@ -95,11 +95,11 @@ module AcmeFresh
end
```
-Once defined and autoloaded, the subclass behaves like any other rule kind: persists via STI, appears in the admin UI, feeds the reducer.
+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 STI patterns. Avoids the boot-order foot guns of a class registry (autoload timing, plugin ordering).
+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
@@ -484,7 +484,7 @@ end
| 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 { ... } }` |
+| `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 |
@@ -656,7 +656,7 @@ The reservation/routing handoff. See "Reservation-first allocation (Phase 3)" ab
- **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.
+- **New rule kinds** subclass `Spree::OrderRoutingRule` directly (STI) **and register the class** via `Spree.order_routing.rules << MyRule`. STI still does the runtime *dispatch* via the `type` column — the registry is the curated allowlist of *available/valid* kinds (it backs admin pickers and the `type` inclusion validation), not a dispatch table. Don't add `if rule.is_a?(Foo)` branches to `Rules` strategy or the reducer; rule classes own their own `#rank` logic.
## Resolved Questions
@@ -664,7 +664,7 @@ The reservation/routing handoff. See "Reservation-first allocation (Phase 3)" ab
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.
+3. **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 standard `config.spree.*` extension-point convention, alongside `calculators`, `stock_splitters`, `payment_methods`). Core registers `Strategy::Rules` and `Strategy::Legacy`; plugins register their own and may unregister (e.g. drop `Legacy`). Models read `Spree.order_routing.strategies` directly (no wrapper API), like every other `config.spree.*` extension point. A strategy must be **both a `Strategy::Base` subclass and registered** to be selectable — `Store#preferred_order_routing_strategy` / `Channel#preferred_order_routing_strategy` validate inclusion in the registry, and `Order#order_routing_strategy` only instantiates registered classes (unregistering or a stale persisted value falls back to the default `Rules` rather than raising). This replaces the original "validate by `Strategy::Base` subclass only" check and is what closes the class of bug where a non-strategy (e.g. the internal `Reducer` collaborator) could be selected.
4. **Where the strategy fires.** Today: `Order#create_proposed_shipments`. Phase 4: `Spree::Carts::Complete` per `6.0-cart-order-split.md`.
diff --git a/spree/admin/app/helpers/spree/admin/channels_helper.rb b/spree/admin/app/helpers/spree/admin/channels_helper.rb
index 96ebc6db2e..5175c503c0 100644
--- a/spree/admin/app/helpers/spree/admin/channels_helper.rb
+++ b/spree/admin/app/helpers/spree/admin/channels_helper.rb
@@ -1,14 +1,13 @@
module Spree
module Admin
module ChannelsHelper
- # Concrete +Spree::OrderRouting::Strategy::Base+ subclasses presented in
- # the channel edit form. A blank value clears the channel-level override
- # and falls back to +Store#preferred_order_routing_strategy+.
+ # Registered +Spree::OrderRouting::Strategy::Base+ subclasses presented in
+ # the channel edit form, sourced from +Spree.order_routing.strategies+ so the
+ # picker can never drift from what the model accepts. A blank value clears the
+ # channel-level override and falls back to
+ # +Store#preferred_order_routing_strategy+.
def channel_order_routing_strategy_options
- [
- [Spree.t('admin.channels.order_routing_strategies.rules'), 'Spree::OrderRouting::Strategy::Rules'],
- [Spree.t('admin.channels.order_routing_strategies.legacy'), 'Spree::OrderRouting::Strategy::Legacy']
- ]
+ Spree.order_routing.strategies.map { |strategy| [strategy.display_name, strategy.to_s] }
end
end
end
diff --git a/spree/admin/config/locales/en.yml b/spree/admin/config/locales/en.yml
index 8e0df23529..e95197f970 100644
--- a/spree/admin/config/locales/en.yml
+++ b/spree/admin/config/locales/en.yml
@@ -79,9 +79,6 @@ en:
code_hint: A short, stable identifier (e.g. "online", "pos", "wholesale"). Used by API clients via the X-Spree-Channel header and for order attribution.
default: Default channel
default_hint: Exactly one channel per store is the default. Used as the fallback when no channel is selected and as the auto-publish target for new products.
- order_routing_strategies:
- legacy: Legacy
- rules: Rules (ordered)
order_routing_strategy: Order routing strategy
order_routing_strategy_hint: Overrides the store-level routing strategy for orders attributed to this channel.
order_routing_strategy_inherit: Inherit from store
diff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rb
index 82afd5a852..91cd697504 100644
--- a/spree/core/app/models/spree/channel.rb
+++ b/spree/core/app/models/spree/channel.rb
@@ -10,6 +10,7 @@ module Spree
include Spree::SingleStoreResource
include Spree::Metafields
include Spree::Metadata
+ include Spree::OrderRouting::HasStrategyPreference
# Empty -> falls back to the Store-level preference.
preference :order_routing_strategy, :string, default: nil
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index 72370f02f0..a7b682c108 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -777,11 +777,11 @@ module Spree
end
# Resolves the routing strategy from the channel override first, then the
- # store default. Any preference that doesn't resolve to a concrete
- # Spree::OrderRouting::Strategy::Base subclass (e.g. an internal collaborator
- # like Reducer that was never a strategy, or a typo'd custom class) is logged
- # and skipped rather than raised, falling back to the default Rules strategy
- # so a misconfiguration can't take down cart display or checkout.
+ # store default. Only a registered Spree::OrderRouting::Strategy::Base
+ # subclass is used; any other value (an unregistered/typo'd class, or a
+ # strategy that was unregistered after being persisted) is logged and
+ # skipped rather than raised, falling back to the default Rules strategy so
+ # a misconfiguration can't take down cart display or checkout.
#
# @return [Spree::OrderRouting::Strategy::Base]
def order_routing_strategy
@@ -1047,11 +1047,11 @@ module Spree
def valid_order_routing_strategy_class(klass_name)
return if klass_name.blank?
- klass = klass_name.safe_constantize
- return klass if klass && klass < Spree::OrderRouting::Strategy::Base
+ klass = Spree.order_routing.strategies.find { |strategy| strategy.to_s == klass_name.to_s }
+ return klass if klass
Rails.logger.warn(
- "[Spree] Ignoring invalid order routing strategy #{klass_name.inspect} " \
+ "[Spree] Ignoring unregistered order routing strategy #{klass_name.inspect} " \
"for order #{number.inspect}; falling back to the default strategy."
)
nil
diff --git a/spree/core/app/models/spree/order_routing/has_strategy_preference.rb b/spree/core/app/models/spree/order_routing/has_strategy_preference.rb
new file mode 100644
index 0000000000..0fbb82fc1e
--- /dev/null
+++ b/spree/core/app/models/spree/order_routing/has_strategy_preference.rb
@@ -0,0 +1,28 @@
+module Spree
+ module OrderRouting
+ # Shared validation for models carrying a +preferred_order_routing_strategy+
+ # preference (Spree::Store, Spree::Channel). A blank value is allowed (it
+ # falls back to the next level / the default Rules strategy); a present value
+ # must name a registered Spree::OrderRouting::Strategy::Base subclass.
+ module HasStrategyPreference
+ extend ActiveSupport::Concern
+
+ included do
+ validate :order_routing_strategy_must_be_registered
+ end
+
+ private
+
+ def order_routing_strategy_must_be_registered
+ value = preferred_order_routing_strategy
+ return if value.blank?
+ return if Spree.order_routing.strategies.any? { |strategy| strategy.to_s == value.to_s }
+
+ errors.add(
+ :preferred_order_routing_strategy,
+ Spree.t(:invalid_order_routing_strategy, scope: [:errors, :messages], default: 'is not a registered order routing strategy')
+ )
+ 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
index de809dacad..73589cecf9 100644
--- a/spree/core/app/models/spree/order_routing/strategy/base.rb
+++ b/spree/core/app/models/spree/order_routing/strategy/base.rb
@@ -12,6 +12,14 @@ module Spree
class Base
attr_reader :order
+ # Human label for admin strategy pickers. Override in a subclass or add
+ # an i18n key under +spree.order_routing.strategies+.
+ #
+ # @return [String]
+ def self.display_name
+ Spree.t(name.demodulize.underscore, scope: 'order_routing.strategies', default: name.demodulize.titleize)
+ end
+
def initialize(order:)
@order = order
end
diff --git a/spree/core/app/models/spree/order_routing_rule.rb b/spree/core/app/models/spree/order_routing_rule.rb
index fd766ea642..83499bd7d5 100644
--- a/spree/core/app/models/spree/order_routing_rule.rb
+++ b/spree/core/app/models/spree/order_routing_rule.rb
@@ -41,6 +41,8 @@ module Spree
self.whitelisted_ransackable_attributes = %w[type position active store_id channel_id]
+ validate :type_must_be_registered
+
# Subclasses override. Returns an Array<LocationRanking> — one per location,
# with rank=nil to abstain.
#
@@ -53,6 +55,16 @@ module Spree
private
+ # The +type+ presence validation already covers blank; here we only reject
+ # a present-but-unregistered STI type so arbitrary class names can't be
+ # persisted via the +type+ column.
+ def type_must_be_registered
+ return if type.blank?
+ return if Spree.order_routing.rules.any? { |rule| rule.to_s == type }
+
+ errors.add(:type, Spree.t(:invalid_order_routing_rule, scope: [:errors, :messages], default: 'is not a registered order routing rule'))
+ end
+
def channel_belongs_to_store
return if channel.nil? || store_id.nil?
return if channel.store_id == store_id
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 5a6388c1c8..3961135a8a 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -15,6 +15,7 @@ module Spree
include Spree::Stores::Channels
include Spree::Security::Stores if defined?(Spree::Security::Stores)
include Spree::UserManagement
+ include Spree::OrderRouting::HasStrategyPreference
#
# Magic methods
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 7befcbe9e3..59c924b221 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -1140,6 +1140,8 @@ en:
cannot_remove_icon: Cannot remove image
channel_store_mismatch: must belong to the same store
could_not_create_taxon: Could not create taxon
+ invalid_order_routing_rule: is not a registered order routing rule
+ invalid_order_routing_strategy: is not a registered order routing strategy
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.
store_association_can_not_be_changed: The store association can not be changed
@@ -1651,6 +1653,10 @@ en:
order_number: Order %{number}
order_processed_successfully: Your order has been processed successfully
order_resumed: Order resumed
+ order_routing:
+ strategies:
+ legacy: Legacy
+ rules: Rules (ordered)
order_state:
address: address
awaiting_return: awaiting return
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index f69d46155a..499cb27600 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -242,6 +242,14 @@ module Spree
Rails.application.config.spree.stock_splitters = value
end
+ def self.order_routing
+ Rails.application.config.spree.order_routing
+ end
+
+ def self.order_routing=(value)
+ Rails.application.config.spree.order_routing = value
+ end
+
def self.promotions
Rails.application.config.spree.promotions
end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index dc298a17a8..59ca601972 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -11,6 +11,7 @@ module Spree
:payment_methods,
:adjusters,
:stock_splitters,
+ :order_routing,
:promotions,
:pricing,
:line_item_comparison_hooks,
@@ -36,6 +37,7 @@ module Spree
SpreeCalculators = Struct.new(:shipping_methods, :tax_rates, :promotion_actions_create_adjustments, :promotion_actions_create_item_adjustments)
PromoEnvironment = Struct.new(:rules, :actions)
PricingEnvironment = Struct.new(:rules)
+ OrderRoutingEnvironment = Struct.new(:strategies, :rules)
SpreeValidators = Struct.new(:addresses)
MetafieldsEnvironment = Struct.new(:types, :enabled_resources)
isolate_namespace Spree
@@ -76,6 +78,15 @@ module Spree
initializer 'spree.register.adjustable_adjusters' do |app|
end
+ # Seed the order routing registries early so engines and apps can append
+ # their own strategies / rule kinds from initializer files. Core's defaults
+ # are concatenated in after_initialize below.
+ initializer 'spree.register.order_routing', before: :load_config_initializers do |app|
+ app.config.spree.order_routing = OrderRoutingEnvironment.new
+ app.config.spree.order_routing.strategies = []
+ app.config.spree.order_routing.rules = []
+ end
+
initializer 'spree.register.metafields' do |app|
app.config.spree.metafields = MetafieldsEnvironment.new
app.config.spree.metafields.types = []
@@ -134,6 +145,23 @@ module Spree
Spree::Adjustable::Adjuster::Tax
]
+ # Selectable order routing strategies. The internal Reducer collaborator
+ # is intentionally NOT listed — it is not a Strategy::Base. Plugins add
+ # their own (or remove Legacy) via this array.
+ Rails.application.config.spree.order_routing.strategies.concat [
+ Spree::OrderRouting::Strategy::Rules,
+ Spree::OrderRouting::Strategy::Legacy
+ ]
+
+ # Available order routing rule kinds. STI dispatches at runtime via the
+ # +type+ column; this array is the curated allowlist that drives admin
+ # pickers and the rule +type+ validation. Plugins append their own.
+ Rails.application.config.spree.order_routing.rules.concat [
+ Spree::OrderRouting::Rules::PreferredLocation,
+ Spree::OrderRouting::Rules::MinimizeSplits,
+ Spree::OrderRouting::Rules::DefaultLocation
+ ]
+
Rails.application.config.spree.calculators.promotion_actions_create_adjustments = [
Spree::Calculator::FlatPercentItemTotal,
Spree::Calculator::FlatRate,
diff --git a/spree/core/spec/models/spree/channel_spec.rb b/spree/core/spec/models/spree/channel_spec.rb
index 5f08517549..799b76ec19 100644
--- a/spree/core/spec/models/spree/channel_spec.rb
+++ b/spree/core/spec/models/spree/channel_spec.rb
@@ -68,18 +68,35 @@ RSpec.describe Spree::Channel, type: :model do
end
describe 'preferences' do
+ around do |example|
+ registered = Spree.order_routing.strategies.dup
+ example.run
+ Spree.order_routing.strategies.replace(registered)
+ end
+
it 'falls back to nil order_routing_strategy by default' do
channel = described_class.new(store: store, name: 'POS', code: 'pos')
expect(channel.preferred_order_routing_strategy).to be_nil
end
- it 'persists a custom routing strategy override' do
+ it 'persists a registered custom routing strategy override' do
+ stub_const('CustomStrategy', Class.new(Spree::OrderRouting::Strategy::Base))
+ Spree.order_routing.strategies << CustomStrategy
channel = described_class.create!(
store: store, name: 'POS', code: 'pos',
preferred_order_routing_strategy: 'CustomStrategy'
)
expect(channel.reload.preferred_order_routing_strategy).to eq('CustomStrategy')
end
+
+ it 'rejects an unregistered routing strategy override' do
+ channel = described_class.new(
+ store: store, name: 'POS', code: 'pos',
+ preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Reducer'
+ )
+ expect(channel).not_to be_valid
+ expect(channel.errors[:preferred_order_routing_strategy]).to be_present
+ end
end
describe 'prefixed_id' do
diff --git a/spree/core/spec/models/spree/order_routing/strategy/base_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/base_spec.rb
new file mode 100644
index 0000000000..6b5af29766
--- /dev/null
+++ b/spree/core/spec/models/spree/order_routing/strategy/base_spec.rb
@@ -0,0 +1,19 @@
+require 'spec_helper'
+
+RSpec.describe Spree::OrderRouting::Strategy::Base, type: :model do
+ describe 'Spree.order_routing.strategies' do
+ it 'includes the core strategies and excludes the internal Reducer collaborator' do
+ expect(Spree.order_routing.strategies).to include(
+ Spree::OrderRouting::Strategy::Rules,
+ Spree::OrderRouting::Strategy::Legacy
+ )
+ expect(Spree.order_routing.strategies).not_to include(Spree::OrderRouting::Strategy::Reducer)
+ end
+ end
+
+ describe '.display_name' do
+ it 'uses the i18n label when present' do
+ expect(Spree::OrderRouting::Strategy::Rules.display_name).to eq('Rules (ordered)')
+ 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
index 5310dbfc0e..69c1ee6a98 100644
--- a/spree/core/spec/models/spree/order_routing_rule_spec.rb
+++ b/spree/core/spec/models/spree/order_routing_rule_spec.rb
@@ -31,6 +31,23 @@ RSpec.describe Spree::OrderRoutingRule, type: :model do
expect(rule).not_to be_valid
expect(rule.errors[:channel]).to include(Spree.t('errors.messages.channel_store_mismatch'))
end
+
+ it 'rejects a present-but-unregistered STI type' do
+ rule = Spree::OrderRouting::Rules::PreferredLocation.new(store: store, channel: channel, position: 1)
+ rule.type = 'Spree::OrderRoutingRule'
+ expect(rule).not_to be_valid
+ expect(rule.errors[:type]).to be_present
+ end
+ end
+
+ describe 'Spree.order_routing.rules' do
+ it 'includes the core rule kinds' do
+ expect(Spree.order_routing.rules).to include(
+ Spree::OrderRouting::Rules::PreferredLocation,
+ Spree::OrderRouting::Rules::MinimizeSplits,
+ Spree::OrderRouting::Rules::DefaultLocation
+ )
+ end
end
describe 'scopes' do
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 4bfd754cb4..c4a2cdf13a 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -1576,18 +1576,27 @@ describe Spree::Order, type: :model do
end
describe '#order_routing_strategy' do
+ # Several examples register a stub strategy; snapshot and restore the global
+ # registry so the mutation doesn't leak across examples.
+ around do |example|
+ registered = Spree.order_routing.strategies.dup
+ example.run
+ Spree.order_routing.strategies.replace(registered)
+ end
+
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
+ it 'honors a custom registered store-level preference' do
stub_const('CustomStrategy', Class.new(Spree::OrderRouting::Strategy::Base))
+ Spree.order_routing.strategies << CustomStrategy
# 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_store.update!(preferred_order_routing_strategy: 'CustomStrategy')
isolated_order = create(:order, store: isolated_store)
expect(isolated_order.order_routing_strategy).to be_a(CustomStrategy)
@@ -1595,10 +1604,10 @@ describe Spree::Order, type: :model do
it 'lets a channel preference override the store preference' do
stub_const('ChannelStrategy', Class.new(Spree::OrderRouting::Strategy::Base))
+ Spree.order_routing.strategies << ChannelStrategy
isolated_store = create(:store)
channel = isolated_store.channels.first
- channel.preferred_order_routing_strategy = 'ChannelStrategy'
- channel.save!
+ channel.update!(preferred_order_routing_strategy: 'ChannelStrategy')
isolated_order = create(:order, store: isolated_store, channel: channel)
expect(isolated_order.order_routing_strategy).to be_a(ChannelStrategy)
@@ -1613,21 +1622,25 @@ describe Spree::Order, type: :model do
expect(isolated_order.order_routing_strategy).to be_a(Spree::OrderRouting::Strategy::Rules)
end
- it 'skips an invalid channel preference and uses the store preference' do
+ it 'skips an unregistered channel preference and uses the store preference' do
stub_const('StorePreferredStrategy', Class.new(Spree::OrderRouting::Strategy::Base))
+ Spree.order_routing.strategies << StorePreferredStrategy
isolated_store = create(:store)
isolated_store.update!(preferred_order_routing_strategy: 'StorePreferredStrategy')
channel = isolated_store.channels.first
- # Reducer is an internal collaborator of Rules, not a Strategy::Base.
- channel.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Reducer')
+ # Simulate a value persisted before it was unregistered (the model
+ # validation rejects it now) — e.g. the internal Reducer collaborator.
+ channel.preferred_order_routing_strategy = 'Spree::OrderRouting::Strategy::Reducer'
+ channel.save!(validate: false)
isolated_order = create(:order, store: isolated_store, channel: channel)
expect(isolated_order.order_routing_strategy).to be_a(StorePreferredStrategy)
end
- it 'falls back to the default Rules strategy when the persisted value is invalid' do
+ it 'falls back to the default Rules strategy when the persisted value is unregistered' do
isolated_store = create(:store)
- isolated_store.update!(preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Reducer')
+ isolated_store.preferred_order_routing_strategy = 'Spree::OrderRouting::Strategy::Reducer'
+ isolated_store.save!(validate: false)
isolated_order = create(:order, store: isolated_store)
expect(isolated_order.order_routing_strategy).to be_a(Spree::OrderRouting::Strategy::Rules)
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index 89ca13037e..ea27f83e69 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -279,6 +279,18 @@ describe Spree::Store, type: :model, without_global_store: true do
end
end
+ describe 'order routing strategy preference' do
+ it 'is valid with the default registered Rules strategy' do
+ expect(create(:store)).to be_valid
+ end
+
+ it 'rejects an unregistered strategy' do
+ store = build(:store, preferred_order_routing_strategy: 'Spree::OrderRouting::Strategy::Reducer')
+ expect(store).not_to be_valid
+ expect(store.errors[:preferred_order_routing_strategy]).to be_present
+ end
+ end
+
describe '.current' do
let!(:store_1) { Spree::Store.first || create(:store) }