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.

Fix building shipping rates on multi origin delivery (#14562)

Kacper Mękarskia41d1c01fbf1
diff --git a/docs/plans/6.0-delivery-profiles.md b/docs/plans/6.0-delivery-profiles.md
index 5cd80b074f..e3606abbd8 100644
--- a/docs/plans/6.0-delivery-profiles.md
+++ b/docs/plans/6.0-delivery-profiles.md
@@ -62,7 +62,7 @@ Spree::DeliveryProfile spree_delivery_profiles (STI, prefix
## Runtime flow
1. **Split** — `Stock::Splitter::DeliveryProfile` (replaces `Splitter::FulfillmentType`) partitions cart contents by each item's resolved profile.
-2. **Allocate** — the Coordinator allocates a profile's items only from stock locations the profile covers (its join; empty = all).
+2. **Allocate** — the Coordinator allocates a profile's items only from stock locations the profile covers (its join; empty = all), and among those it prefers an origin that can actually deliver to the destination: `Stock::Prioritizer` puts packages the Estimator finds a method for ahead of the rest, so the units are filled from one of them. Coverage stays the hard filter and deliverability the preference — a destination no origin serves must still yield a package, so the cart can report it rather than silently losing the item.
3. **Quote** — for a package (profile, origin): candidates are the profile's methods whose ships-from set covers the origin, whose zone is nil or includes the ship address, passing the existing rule/calculator/audience filters; rate providers then fan out (multi-rate carriers untouched).
4. **Derive, never declare twice** — `Product#digital?` ⇐ its profile kind (`DeliveryProfiles::Digital`); pickupable ⇐ the profile contains a pickup-provider method; the order requires an address ⇐ any item's profile answers `requires_shipping_address?` (kind-declared for Digital, derived from the methods' providers for physical kinds).
@@ -89,6 +89,8 @@ Spree::DeliveryProfile spree_delivery_profiles (STI, prefix
- New delivery features must resolve eligibility through the profile chain — never reintroduce parallel product-side capability arrays.
- Behavior questions route through classes (`provider_class.digital?`, `profile.requires_shipping_address?`) — never reintroduce a stored type/modality string on methods, products, or profiles. Fulfillment.fulfillment_type (the historical column on fulfillments) remains as recorded data only.
- The Store API surface for profiles is read-only derivation (product serializers may expose digital/pickupable); profile management is Admin API only.
+- Deliverability is asked once, through `Stock::Estimator#deliverable?` — allocation and the rate refresh share the method filter so they can never disagree about which origins can serve a destination. Never re-implement that question against zones or origin groups directly, and never answer it by calling a rate provider: allocation would then cost a carrier request per candidate warehouse.
+- Anything building packages sets `Package#owner` to the cart or order it is allocating. Left unset, `#owner` falls back to walking a unit's `order_id`, and cart-phase units carry none — the package would take its currency, store and destination from whatever order shares that id (which is what broke multi-currency freight quoting).
## Open Questions
diff --git a/docs/plans/6.0-order-routing.md b/docs/plans/6.0-order-routing.md
index ea232e1360..75fc77e1e2 100644
--- a/docs/plans/6.0-order-routing.md
+++ b/docs/plans/6.0-order-routing.md
@@ -29,6 +29,8 @@ Industry parity: Vendure has the strategy contract but no admin UI. Shopify has
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.
+
### 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.
@@ -696,7 +698,7 @@ The reservation/routing handoff. See "Reservation-first allocation (Phase 3)" ab
## 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`
+- Current prioritizer (`sort_packages` demotes origins that cannot reach the destination): `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`
diff --git a/spree/core/app/models/spree/order_routing/strategy/rules.rb b/spree/core/app/models/spree/order_routing/strategy/rules.rb
index aaf8dd3e83..2bd01c30a3 100644
--- a/spree/core/app/models/spree/order_routing/strategy/rules.rb
+++ b/spree/core/app/models/spree/order_routing/strategy/rules.rb
@@ -59,24 +59,29 @@ module Spree
# 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|
+ packages = locations.flat_map do |location|
Spree::Stock::Packer.new(location, inventory_units, Spree.stock_splitters).packages
end
+ packages.each { |package| package.owner = order }
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.
+ # items all get stripped are pruned. Rank only decides between origins
+ # that can reach the destination — the Prioritizer demotes the rest.
def prioritize_packages(packages)
- Spree::Stock::Prioritizer.new(packages).prioritized_packages
+ Spree::Stock::Prioritizer.new(packages, estimator: estimator).prioritized_packages
end
def estimate_rates(packages)
- estimator = Spree::Stock::Estimator.new(order)
packages.each { |pkg| pkg.delivery_rates = estimator.delivery_rates(pkg) }
packages
end
+
+ def estimator
+ @estimator ||= Spree::Stock::Estimator.new(order)
+ end
end
end
end
diff --git a/spree/core/app/models/spree/stock/coordinator.rb b/spree/core/app/models/spree/stock/coordinator.rb
index 713bbd2d35..f8786c70ba 100644
--- a/spree/core/app/models/spree/stock/coordinator.rb
+++ b/spree/core/app/models/spree/stock/coordinator.rb
@@ -36,6 +36,11 @@ module Spree
packages += packer.packages
end
+ # A proposal's packages belong to the cart or order being allocated.
+ # Saying so is what gives them its currency, store and destination —
+ # Package#owner would otherwise fall back to guessing from a unit's
+ # order_id, which cart-phase units deliberately don't carry.
+ packages.each { |package| package.owner = order }
packages
end
@@ -97,18 +102,23 @@ module Spree
end
def prioritize_packages(packages)
- prioritizer = Prioritizer.new(packages)
+ prioritizer = Prioritizer.new(packages, estimator: estimator)
prioritizer.prioritized_packages
end
def estimate_packages(packages)
- estimator = Estimator.new(order)
packages.each do |package|
package.delivery_rates = estimator.delivery_rates(package)
end
packages
end
+ # Shared between prioritization (which origins can deliver at all) and
+ # the rate refresh, so both answer with the same eligibility rules.
+ def estimator
+ @estimator ||= Estimator.new(order)
+ end
+
def build_packer(stock_location, inventory_units)
Packer.new(stock_location, inventory_units, splitters(stock_location))
end
diff --git a/spree/core/app/models/spree/stock/estimator.rb b/spree/core/app/models/spree/stock/estimator.rb
index 4d812e6983..842ca81bb2 100644
--- a/spree/core/app/models/spree/stock/estimator.rb
+++ b/spree/core/app/models/spree/stock/estimator.rb
@@ -20,6 +20,20 @@ module Spree
sort_delivery_rates(rates)
end
+ # Whether any delivery method is eligible to carry this package — the
+ # same eligibility a rate refresh applies, stopping short of asking any
+ # rate provider for a price. Allocation reads it to prefer an origin
+ # whose methods can actually reach the destination, so it must never
+ # cost a carrier API call.
+ #
+ # @param package [Spree::Stock::Package]
+ # @param audience [Symbol] {Spree::DeliveryMethod::STOREFRONT} (default)
+ # or {Spree::DeliveryMethod::BACKOFFICE}
+ # @return [Boolean]
+ def deliverable?(package, audience = DeliveryMethod::STOREFRONT)
+ delivery_methods(package, audience).any?
+ end
+
# @deprecated Use {#delivery_rates}; removed in 6.1.
def shipping_rates(package, audience = DeliveryMethod::STOREFRONT)
Spree::Deprecation.warn('Spree::Stock::Estimator#shipping_rates is deprecated and will be removed in Spree 6.1. Use #delivery_rates instead.')
diff --git a/spree/core/app/models/spree/stock/inventory_unit_builder.rb b/spree/core/app/models/spree/stock/inventory_unit_builder.rb
index cad0255db7..d81d034f75 100644
--- a/spree/core/app/models/spree/stock/inventory_unit_builder.rb
+++ b/spree/core/app/models/spree/stock/inventory_unit_builder.rb
@@ -6,6 +6,11 @@ module Spree
end
def units
+ # Same rule as Spree::Fulfillment#set_up_inventory: the item's order_id
+ # is a completion-time denormalization, so during checkout it stays nil
+ # rather than pointing at whatever order happens to share the cart's
+ # id — a stranger's order whose currency and ship address would then
+ # stand in for the customer's.
@order.line_items.map do |line_item|
# They go through multiple splits, avoid loading the
# association to order until needed.
@@ -14,7 +19,7 @@ module Spree
line_item_id: line_item.id,
variant_id: line_item.variant_id,
quantity: line_item.quantity,
- order_id: @order.id
+ order_id: @order.is_a?(Spree::Order) ? @order.id : nil
)
end
end
diff --git a/spree/core/app/models/spree/stock/package.rb b/spree/core/app/models/spree/stock/package.rb
index e9e3f94d0e..6781f44be3 100644
--- a/spree/core/app/models/spree/stock/package.rb
+++ b/spree/core/app/models/spree/stock/package.rb
@@ -3,9 +3,10 @@ module Spree
class Package
attr_reader :stock_location, :contents
attr_accessor :delivery_rates
- # The cart or order this package is being quoted for. Set when a
- # fulfillment builds the package; nil for proposed packages the
- # coordinator builds before anything is persisted.
+ # The cart or order this package is being quoted for. Every builder sets
+ # it — a fulfillment, the allocator for a proposal — so the package takes
+ # its currency, store and destination from the real record instead of
+ # {#owner}'s fallback.
attr_writer :owner
def initialize(stock_location, contents = [])
@@ -16,11 +17,13 @@ module Spree
# Who this package is for.
#
- # Prefers the owner the fulfillment supplied over walking to
- # `inventory_unit.order`: during checkout a fulfillment belongs to a
- # Cart, while its units can still carry an order_id from elsewhere, and
- # following that returns a stranger's order — whose ship address would
- # then stand in for the customer's.
+ # Prefers the owner it was built with. The walk to `inventory_unit.order`
+ # is only a safety net for packages built by code that sets none, and it
+ # answers badly in both directions: a cart's units carry no order_id, so
+ # it returns nil and the package has no store or currency of its own,
+ # while a unit carrying an order_id from elsewhere returns a stranger's
+ # order — whose currency and ship address would stand in for the
+ # customer's.
#
# @return [Spree::Cart, Spree::Order, nil]
def owner
diff --git a/spree/core/app/models/spree/stock/prioritizer.rb b/spree/core/app/models/spree/stock/prioritizer.rb
index 0011d96cb2..6290cfbae4 100644
--- a/spree/core/app/models/spree/stock/prioritizer.rb
+++ b/spree/core/app/models/spree/stock/prioritizer.rb
@@ -1,11 +1,18 @@
module Spree
module Stock
class Prioritizer
- attr_reader :packages
+ attr_reader :packages, :estimator
- def initialize(packages, adjuster_class = Adjuster)
+ # @param packages [Array<Spree::Stock::Package>] candidate packages, in
+ # the order the caller prefers them (routing rank, location order)
+ # @param adjuster_class [Class]
+ # @param estimator [Spree::Stock::Estimator, nil] consulted for
+ # deliverability, so an origin that cannot serve the destination loses
+ # to one that can. Omitted, the caller's order stands as given.
+ def initialize(packages, adjuster_class = Adjuster, estimator: nil)
@packages = packages
@adjuster_class = adjuster_class
+ @estimator = estimator
@adjusters = {}
end
@@ -36,8 +43,24 @@ module Spree
@adjusters[hash_item item]
end
+ # Origins that can deliver go first, so the Adjuster fills each unit from
+ # one of them and the origins that cannot are left empty and pruned. A
+ # profile with per-region origin groups would otherwise allocate to
+ # whichever warehouse came first, and when that warehouse's group has no
+ # method for the destination the item is dropped as undeliverable even
+ # though another warehouse could have shipped it.
+ #
+ # The caller's order survives within each group, so routing rank and the
+ # store's location order still decide between origins that can both
+ # deliver.
def sort_packages
- # order packages by preferred stock_locations
+ return if estimator.nil?
+
+ ranked = packages.each_with_index.sort_by do |package, index|
+ [estimator.deliverable?(package) ? 0 : 1, index]
+ end
+
+ packages.replace(ranked.map(&:first))
end
def prune_packages
diff --git a/spree/core/spec/models/spree/stock/coordinator_spec.rb b/spree/core/spec/models/spree/stock/coordinator_spec.rb
index 198b8ed971..6d5eb26807 100644
--- a/spree/core/spec/models/spree/stock/coordinator_spec.rb
+++ b/spree/core/spec/models/spree/stock/coordinator_spec.rb
@@ -43,6 +43,75 @@ module Spree
end
end
+ # Origin groups exist so different warehouses can serve different zones.
+ # The destination has to decide which warehouse packs the goods, or the
+ # cart allocates to one whose group has no method for the address and
+ # drops the item as undeliverable while the other could have shipped it.
+ describe 'multi-origin allocation' do
+ let(:profile) { store.default_delivery_profile }
+ let!(:us_warehouse) do
+ create(:stock_location, store: store, name: "US #{SecureRandom.hex(3)}",
+ propagate_all_variants: true, default: true)
+ end
+ let!(:eu_warehouse) do
+ create(:stock_location, store: store, name: "EU #{SecureRandom.hex(3)}",
+ propagate_all_variants: true, country: Spree::Country.by_iso('NL'))
+ end
+
+ let(:us_group) { profile.default_origin_group }
+ let(:eu_group) { profile.delivery_origin_groups.create!(name: 'EU Fulfillment') }
+
+ let(:netherlands) { Spree::Country.by_iso('NL') }
+ let(:dutch_address) { create(:address, country: netherlands, state: nil) }
+ let(:order) { create(:order_with_line_items, store: store, ship_address: dutch_address) }
+
+ before do
+ # Every method in this setup is zone-bound, as it is for a merchant
+ # who split their origins by region — the factory's worldwide method
+ # would make the US warehouse look able to deliver anywhere.
+ order
+ Spree::DeliveryMethod.delete_all
+
+ us_group.stock_locations = [us_warehouse]
+ eu_group.stock_locations = [eu_warehouse]
+
+ us_zone = create(
+ :delivery_zone_with_country,
+ store: store, delivery_profile: profile,
+ delivery_origin_group: us_group, country: Spree::Country.by_iso('US')
+ )
+ eu_zone = create(
+ :delivery_zone_with_country,
+ store: store, delivery_profile: profile,
+ delivery_origin_group: eu_group, country: netherlands
+ )
+
+ create(
+ :delivery_method,
+ name: 'US Standard', store: store, delivery_profile: profile,
+ delivery_origin_group: us_group, delivery_zone: us_zone
+ )
+ create(
+ :delivery_method,
+ name: 'EU Standard', store: store, delivery_profile: profile,
+ delivery_origin_group: eu_group, delivery_zone: eu_zone
+ )
+
+ order.variants.each do |variant|
+ [us_warehouse, eu_warehouse].each do |location|
+ location.stock_level_or_create(variant).adjust_count_on_hand(10)
+ end
+ end
+ end
+
+ it 'allocates from the origin whose group serves the destination' do
+ packages = subject.packages
+
+ expect(packages.map { |package| package.stock_location.name }).to eq [eu_warehouse.name]
+ expect(packages.first.delivery_rates.map(&:name)).to include('EU Standard')
+ end
+ end
+
describe 'channel-scoped allocation' do
let!(:warehouse) { create(:stock_location, store: store, name: "Warehouse #{SecureRandom.hex(3)}", backorderable_default: true, propagate_all_variants: true) }
let(:channel) { create(:channel, store: store) }
diff --git a/spree/core/spec/models/spree/stock/inventory_unit_builder_spec.rb b/spree/core/spec/models/spree/stock/inventory_unit_builder_spec.rb
index 9f23d30961..b8b92571f2 100644
--- a/spree/core/spec/models/spree/stock/inventory_unit_builder_spec.rb
+++ b/spree/core/spec/models/spree/stock/inventory_unit_builder_spec.rb
@@ -29,6 +29,17 @@ module Spree
it 'sets the order_id on inventory units' do
expect(subject.units.map(&:order_id).uniq).to eq [order.id]
end
+
+ context 'when building for a cart' do
+ let(:cart) { create(:cart_with_line_items) }
+
+ subject { InventoryUnitBuilder.new(cart) }
+
+ it 'leaves the order_id blank rather than writing the cart id into it' do
+ expect(subject.units).to be_present
+ expect(subject.units.map(&:order_id).uniq).to eq [nil]
+ end
+ end
end
end
end
diff --git a/spree/core/spec/models/spree/stock/prioritizer_spec.rb b/spree/core/spec/models/spree/stock/prioritizer_spec.rb
index a481ac498a..5662680ab3 100644
--- a/spree/core/spec/models/spree/stock/prioritizer_spec.rb
+++ b/spree/core/spec/models/spree/stock/prioritizer_spec.rb
@@ -23,6 +23,51 @@ module Spree
package
end
+ describe 'deliverability' do
+ let(:other_location) { build(:stock_location) }
+
+ def deliverable_only(*deliverable_packages)
+ estimator = instance_double(Estimator)
+ allow(estimator).to receive(:deliverable?) { |package| deliverable_packages.include?(package) }
+ estimator
+ end
+
+ it 'fills the units from an origin that can deliver rather than the first one offered' do
+ 2.times { build_inventory_unit }
+
+ undeliverable = pack { |package| inventory_units.each { |unit| package.add unit } }
+ deliverable = Package.new(other_location).tap do |package|
+ inventory_units.each { |unit| package.add unit }
+ end
+
+ packages = Prioritizer.new([undeliverable, deliverable],
+ estimator: deliverable_only(deliverable)).prioritized_packages
+
+ expect(packages).to eq [deliverable]
+ expect(packages.first.quantity).to eq 2
+ end
+
+ it 'keeps the order it was given between origins that can both deliver' do
+ 2.times { build_inventory_unit }
+
+ first = pack { |package| package.add inventory_units.first }
+ second = Package.new(other_location).tap { |package| package.add inventory_units.last }
+
+ packages = Prioritizer.new([first, second],
+ estimator: deliverable_only(first, second)).prioritized_packages
+
+ expect(packages).to eq [first, second]
+ end
+
+ it 'leaves the order alone without an estimator to ask' do
+ build_inventory_unit
+ first = pack { |package| package.add inventory_units.first }
+ second = Package.new(other_location).tap { |package| package.add inventory_units.first }
+
+ expect(Prioritizer.new([first, second]).prioritized_packages).to eq [first]
+ end
+ end
+
it 'keeps a single package' do
package1 = pack do |package|
package.add build_inventory_unit