Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: Allocated stock from a warehouse that can deliver over one that cannot (#14986)
Łukasz Adamczyk75e29731b039
diff --git a/docs/developer/core-concepts/carts.mdx b/docs/developer/core-concepts/carts.mdxindex 34ed9cfd4a..240c495d41 100644--- a/docs/developer/core-concepts/carts.mdx+++ b/docs/developer/core-concepts/carts.mdx@@ -142,7 +142,7 @@ meant for a person, and `step` is only a grouping hint.This is what lets you design your own checkout. Spree tells you what's missing; you decide how and when to ask for it — one long page, a few steps, or whatever suits your storefront.-Seven checks run on every cart read:+Eight checks run on every cart read:| `code` | `step` | Raised when ||---|---|---|@@ -150,6 +150,7 @@ Seven checks run on every cart read:| `email_required` | `address` | No email address || `ship_address_required` | `address` | Something needs shipping and there is no address || `delivery_method_required` | `delivery` | A delivery method hasn't been chosen |+| `delivery_unavailable` | `delivery` | Part of an item cannot be delivered to the shipping address || `payment_required` | `payment` | The total isn't covered by payments || `po_number_required` | `address` | A company requires a purchase-order number || `order_minimum_not_met` | `cart` | Below the order minimum, with the shortfall in the message |diff --git a/docs/developer/core-concepts/inventory.mdx b/docs/developer/core-concepts/inventory.mdxindex 45b15550ad..fa909f1fe4 100644--- a/docs/developer/core-concepts/inventory.mdx+++ b/docs/developer/core-concepts/inventory.mdx@@ -217,6 +217,8 @@ A reservation is a short, time-limited hold placed when a customer enters checkoReservations never touch `count_on_hand` — they're a separate layer consulted when availability is read, and their total per stock level is what `reserved_count` shows. A backorderable item is skipped entirely, since unlimited supply needs no holding.+Stock is held at the location the order will ship from — the same choice that builds the cart's delivery options — so a cart drawing on two warehouses holds at both. Once the customer gives an address, a warehouse that cannot deliver there holds nothing; units no other warehouse can supply are reported as undeliverable instead. When an edit to the cart or a new address moves an item to another warehouse, its hold moves with it.+How long the hold lasts is a **store setting**, because it's a decision about the checkout experience rather than a property of a warehouse. Reservations can also be switched off entirely.<Info>diff --git a/docs/plans/6.0-channel-delivery.md b/docs/plans/6.0-channel-delivery.mdindex b121eb9511..cbe4a830a6 100644--- a/docs/plans/6.0-channel-delivery.md+++ b/docs/plans/6.0-channel-delivery.md@@ -34,7 +34,7 @@ Channel#served_stock_locations # empty → store.stock_locations### Enforcement points (all one predicate)-1. **Allocation** — `Stock::Coordinator` already asks `profile.covers_location?`; it additionally asks `channel.serves_location?` when the cart has a channel. Items allocate only from origins both the profile's groups and the channel serve.+1. **Allocation** — `Stock::Coordinator` already asks `profile.covers_location?`; it additionally asks `channel.serves_location?` when the cart has a channel. Items allocate only from origins both the profile's groups and the channel serve. Orders go through the same check, since `OrderRouting::Strategy::Rules` packs through the Coordinator (2026-10-26; before, an order's allocation skipped both).2. **Quoting** — `Stock::Estimator`'s method filter already consults `serves_location?(package.stock_location)`; a package sourced from a non-served location never exists (filtered at allocation), so quoting needs no extra check — documented as invariant, covered by spec.3. **Pickup discovery** — the store `pickup_locations` endpoint and `Carts::Update`'s `preferred_stock_location_id` resolution intersect with the cart's channel.4. **Pickup selection** — `Carts::Update` resolves the customer's `preferred_stock_location_id` through `pickup_enabled` AND the cart channel's served set, so a non-served counter 404s exactly like a non-pickup one.diff --git a/docs/plans/6.0-delivery-profiles.md b/docs/plans/6.0-delivery-profiles.mdindex e3606abbd8..446a36e764 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 flow1. **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), 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.+2. **Allocate** — the Coordinator allocates a profile's items only from stock locations the profile covers (its join; empty = all), for carts and for orders alike (`OrderRouting::Strategy::Rules` packs its ranked locations through the Coordinator). 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, and an origin that cannot deliver gives up every unit the capable origins can supply between them, backorders included — ordering alone is not enough, because the Adjuster takes stock on hand anywhere over a backorder (decisions.md, 2026-10-26). Coverage stays the hard filter and deliverability the preference — a unit no capable origin can supply stays where it was allocated, so the cart can report it rather than silently losing the item, and checkout refuses to complete while any unit is in no fulfillment.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).diff --git a/docs/plans/6.0-order-routing.md b/docs/plans/6.0-order-routing.mdindex 75fc77e1e2..b1977d8bb2 100644--- a/docs/plans/6.0-order-routing.md+++ b/docs/plans/6.0-order-routing.md@@ -31,6 +31,8 @@ Today `Spree::Stock::Coordinator` (`spree/core/app/models/spree/stock/coordinato**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 configurationStores 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.@@ -429,11 +431,11 @@ endThe full sequence in `for_allocation`:-1. `eligible_locations` — fetch active locations stocking any cart variant.+1. `Stock::Coordinator#candidate_stock_locations` — fetch active locations stocking any cart variant.2. `Reducer#rank_all` — full ranking, best-first.-3. `build_packages` — one `Packer` per location; each emits one or more packages depending on the configured splitters.-4. `Spree::Stock::Prioritizer#prioritized_packages` — Adjuster walks packages in rank order, assigns each unit to the first package with on-hand stock, prunes empty packages.-5. `estimate_rates` — `Estimator` attaches shipping rates to each surviving package.+3. `Stock::Coordinator#allocated_packages(ranked)` — one `Packer` per 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.+4. `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.+5. `Stock::Coordinator#estimate_packages` — the Coordinator's `Estimator` attaches shipping rates to each surviving package.This reuses the legacy Coordinator's packing machinery wholesale; the only thing routing changes is the *order* in which locations are presented to the Prioritizer.@@ -698,7 +700,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 (`sort_packages` demotes origins that cannot reach the destination): `spree/core/app/models/spree/stock/prioritizer.rb`+- Current prioritizer (`sort_packages` demotes origins that cannot reach the destination, `withdraw_covered_items` takes 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`diff --git a/docs/plans/6.0-stock-reservations.md b/docs/plans/6.0-stock-reservations.mdindex 16232b95c9..46fd68241d 100644--- a/docs/plans/6.0-stock-reservations.md+++ b/docs/plans/6.0-stock-reservations.md@@ -400,7 +400,7 @@ This is purely additive — no existing tables or models are modified (beyond Qu## Open Questions-1. **Multi-location reservation.** When a store has multiple stock locations, should the reservation lock stock at a specific location (determined at reservation time) or float until fulfillment? Locking early is simpler but may lead to suboptimal warehouse selection. Floating requires re-checking at completion.+1. ~~**Multi-location reservation.** When a store has multiple stock locations, should the reservation lock stock at a specific location (determined at reservation time) or float until fulfillment? Locking early is simpler but may lead to suboptimal warehouse selection. Floating requires re-checking at completion.~~ **Resolved (2026-10-26):** a hold locks the location the allocation takes each unit from. `Reserve` runs `Stock::Coordinator#allocated_packages` (packing only, no rate quotes) and holds each line's on-hand units at that package's location, so one line can hold at several locations. Each call re-allocates and withdraws the cart's holds the allocation no longer takes, and a change of destination calls it again rather than only extending the holds, so a hold follows the cart and its address as they change. Once the cart has an address, a unit only a location unable to deliver there would pack is not held. A line placed only in part is refused as before; one placed nowhere (no covered location stocks it), or only where nothing can deliver, is left to the delivery check, which reports it as undeliverable. Holding the first location with stock, as the service sketch above does, held stock at a warehouse that could not ship the order and refused a cart another warehouse could have backordered (decisions.md, 2026-10-26).2. **Reservation failure UX.** When stock runs out during reservation (another customer completed first), should the checkout: (a) block the transition with an error, (b) auto-adjust the quantity down and notify, or (c) allow proceeding with a backorder warning? Probably (a) by default with (b) as an option.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 9cc823443e..2fa86c1d65 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,13 @@+## 2026-10-26: A warehouse that cannot deliver gives up the units another can supply, and holds follow the allocation++**Context:** A profile with per-region origin groups still allocated a cart to a warehouse with no method for the address whenever the warehouse that could deliver held the item only as backorderable (V-3596). Putting the capable warehouse first had no effect, because the Adjuster takes stock on hand anywhere over a backorder; the cart then reported the item as undeliverable. Reproducing it showed four more gaps on the same path. Orders allocated through `OrderRouting::Strategy::Rules`, which skipped the delivery profile and channel coverage that carts apply. A cart whose rebuild dropped an undeliverable proposal could still complete, placing an order with part of a line in no fulfillment. The checkout hold locked the first warehouse with stock, which could be one that cannot ship the order, and refused a cart another warehouse could have backordered. And allocation packed one line per variant, so a second line of the same variant (possible with a custom line finder) was allocated nowhere.++**Decision:** A backorder from a warehouse that can deliver beats stock on hand in one that cannot. `Stock::Prioritizer` takes from the warehouses that cannot deliver every unit the capable ones can supply between them, on hand or backordered; a unit they cannot cover stays where it was, so the split and the `delivery_unavailable` warning remain for it rather than a partial shipment being offered. `Rules#for_allocation` ranks `Stock::Coordinator#candidate_stock_locations` and packs them through `Coordinator#allocated_packages(locations)`, so carts and orders allocate under one coverage check; the routing plan already saw the Coordinator becoming the strategy's internal machinery. A cart reports `delivery_unavailable` among its advisory requirements while any unit of a line needing delivery is in no fulfillment, so a storefront can say so before taking payment, and completion refuses it. `StockReservations::Reserve` runs the allocation without quoting rates (`Coordinator#allocated_packages`) and holds each line's on-hand units at the location it is packed from, withdrawing the cart's holds the allocation no longer takes; a line placed only in part is refused, as before, while one placed nowhere is left to the completion check. Once the cart has an address, a unit packed only at a location unable to deliver there is not held either, since the cart cannot complete with it and the hold would block buyers that location does serve. A change of destination reserves again instead of only extending the holds, so holds placed before the address was known move to where the order will ship from. The packer splits one shelf between the lines of a variant in order, and the Prioritizer tells proposed units apart by line item.++**Consequences:** A shopper may now wait for a backorder where before they were told the item could not be delivered. One line can hold stock at several warehouses, and each hold re-runs allocation, which costs the packing and deliverability queries but never a carrier request. An address change can now be refused when the warehouse serving the new address cannot cover the cart, as entering checkout already could. Holds and allocation still read stock on hand without other checkouts' holds, so a contended shelf is refused at the hold rather than spilling to the next warehouse — the routing plan's reservation-aware eligibility question stays open. The profile page's "Ships from" card still shows only the first origin group's warehouses; it is left for a separate change.++**Plans amended:** `6.0-delivery-profiles.md` (Runtime flow, step 2), `6.0-order-routing.md` (Since then, the `for_allocation` sequence, References), `6.0-channel-delivery.md` (Enforcement points, step 1), `6.0-stock-reservations.md` (Open Question 1, resolved).+## 2026-10-26: Every release is published from a tag, in one workflow**Context:** The npm packages published from `packages.yml` whenever a merge to `main` touched certain paths, while the gems published from `release.yml` on a tag pushed by hand. The two halves of one Spree release went out at different times, a later merge cancelled a release part-way, and gems published without any check of the commit.diff --git a/spree/core/app/models/spree/order_routing/strategy/rules.rb b/spree/core/app/models/spree/order_routing/strategy/rules.rbindex 739b09ec53..ea34cc1ba5 100644--- a/spree/core/app/models/spree/order_routing/strategy/rules.rb+++ b/spree/core/app/models/spree/order_routing/strategy/rules.rb@@ -10,7 +10,7 @@ module Spree# See docs/plans/6.0-order-routing.md.class Rules < Basedef for_allocation- locations = eligible_locations+ locations = coordinator.candidate_stock_locationsreturn [] if locations.empty?ordered = Spree::OrderRouting::Strategy::Reducer@@ -18,9 +18,11 @@ module Spree.rank_all(locations)return [] if ordered.empty?- packages = build_packages(ordered)- packages = prioritize_packages(packages)- estimate_rates(packages)+ # Packed in rank order through the Coordinator, so an order allocates+ # under the same delivery profile and channel coverage as its cart,+ # and the Prioritizer's first-package-wins-on-hand logic honors the+ # routing decision between origins that can reach the destination.+ coordinator.estimate_packages(coordinator.allocated_packages(ordered))end# Stock decrement / restock today happens via Spree::Fulfillment's state@@ -39,50 +41,8 @@ module Spreeorder.channel.order_routing_rules.active.orderedend- def eligible_locations- order.store.stock_locations.active- .joins(:stock_levels)- .where(Spree::StockLevel.table_name => { variant_id: requested_variant_ids })- .distinct- .to_a- end-- def requested_variant_ids- inventory_units.map(&:variant_id).uniq- end-- def inventory_units- @inventory_units ||= Spree::Stock::InventoryUnitBuilder.new(order).units- end-- # Pack each ranked location independently. Packages are emitted in- # rank order so the Prioritizer's first-package-wins-on-hand logic- # honors the routing decision.- def build_packages(locations)- stock_levels = Spree::Stock::Packer.stock_levels_by_location(locations, requested_variant_ids)-- locations.flat_map do |location|- Spree::Stock::Packer.new(location, inventory_units, Spree.stock_splitters, owner: order,- stock_levels: stock_levels.fetch(location.id, {})).packages- end- end-- # Prioritizer's Adjuster distributes each inventory_unit across- # packages: the first package with on-hand stock fulfills the unit,- # and downstream packages have that unit removed. Packages whose- # items all get stripped are pruned. Rank only decides between origins- # that can reach the destination — the Prioritizer demotes the rest.- def prioritize_packages(packages)- Spree::Stock::Prioritizer.new(packages, estimator: estimator).prioritized_packages- end-- def estimate_rates(packages)- packages.each { |pkg| pkg.delivery_rates = estimator.delivery_rates(pkg) }- packages- end-- def estimator- @estimator ||= Spree::Stock::Estimator.new(order)+ def coordinator+ @coordinator ||= Spree::Stock::Coordinator.new(order)endendenddiff --git a/spree/core/app/models/spree/stock/coordinator.rb b/spree/core/app/models/spree/stock/coordinator.rbindex 1b7e6aea18..b03db50bcc 100644--- a/spree/core/app/models/spree/stock/coordinator.rb+++ b/spree/core/app/models/spree/stock/coordinator.rb@@ -22,13 +22,45 @@ module Spreeenddef packages- packages = build_packages- packages = prioritize_packages(packages)- packages = estimate_packages(packages)+ estimate_packages(allocated_packages)end- def build_packages(packages = [])- stock_locations = stock_locations_with_requested_variants.to_a+ # Where each unit comes from, without quoting a rate, so a caller that+ # only needs the origins — a checkout hold — never costs a carrier request.+ #+ # @param stock_locations [Array<Spree::StockLocation>] candidate origins, preferred first+ # @return [Array<Spree::Stock::Package>]+ def allocated_packages(stock_locations = candidate_stock_locations)+ prioritize_packages(build_packages(stock_locations: stock_locations))+ end++ # Whether any delivery method can carry the package to the order's+ # address, by the rule allocation ranked origins with, so no rate is requested.+ #+ # @param package [Spree::Stock::Package]+ # @return [Boolean]+ def deliverable?(package)+ estimator.deliverable?(package)+ end++ # @param packages [Array<Spree::Stock::Package>]+ # @return [Array<Spree::Stock::Package>] the same packages, with their delivery rates+ def estimate_packages(packages)+ packages.each do |package|+ package.delivery_rates = estimator.delivery_rates(package)+ end+ packages+ end++ # Active locations stocking any requested variant, in database order.+ #+ # @return [Array<Spree::StockLocation>]+ def candidate_stock_locations+ order.store.stock_locations.active.joins(:stock_levels)+ .where(Spree::StockLevel.table_name => { variant_id: requested_variant_ids }).distinct.to_a+ end++ def build_packages(packages = [], stock_locations: candidate_stock_locations)stock_levels = Packer.stock_levels_by_location(stock_locations, requested_variant_ids)stock_locations.each do |stock_location|@@ -44,11 +76,6 @@ module Spreeprivate- def stock_locations_with_requested_variants- order.store.stock_locations.active.joins(:stock_levels).- where(Spree::StockLevel.table_name => { variant_id: requested_variant_ids }).distinct- end-# An item may only be allocated from locations its delivery profile# covers — a profile narrowed to the cold-storage warehouse never packs# from anywhere else — intersected with the channel's served set when@@ -104,13 +131,6 @@ module Spreeprioritizer.prioritized_packagesend- def estimate_packages(packages)- 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 estimatordiff --git a/spree/core/app/models/spree/stock/packer.rb b/spree/core/app/models/spree/stock/packer.rbindex 0bd60c091b..862438b267 100644--- a/spree/core/app/models/spree/stock/packer.rb+++ b/spree/core/app/models/spree/stock/packer.rb@@ -44,25 +44,35 @@ module Spreepackage = build_package# Group by variant_id as grouping by variant fires cached query.- units_by_variant_id = inventory_units.index_by(&:variant_id)+ units_by_variant_id = inventory_units.group_by(&:variant_id)# The package's variants and their levels here, each in one query# rather than one per variant. Lowest id first, as StockLocation#stock_level reads.variants = variants_for(units_by_variant_id)stock_levels = @stock_levels || stock_location.stock_levels.where(variant_id: units_by_variant_id.keys).order(:id).group_by(&:variant_id).transform_values(&:first)- units_by_variant_id.each do |variant_id, inventory_unit|+ units_by_variant_id.each do |variant_id, units|variant = variants[variant_id] || Spree::Variant.find(variant_id)- unit = inventory_unit.dup # Can be used by others, do not use directly+ # Can be used by others, do not use directly+ units = units.map(&:dup)if variant.should_track_inventory?stock_level = stock_levels[variant_id]next if stock_level.nil?- on_hand, backordered = stock_location.fill_status(variant, unit.quantity, stock_level: stock_level)- package.add(FulfillmentItem.split(unit, backordered), :backordered) if backordered.positive?- package.add(FulfillmentItem.split(unit, on_hand), :on_hand) if on_hand.positive?+ on_hand, backordered = stock_location.fill_status(variant, units.sum(&:quantity), stock_level: stock_level)+ # Two lines of one variant draw on one shelf, so it is split+ # between them in order rather than offered to each in full.+ units.each do |unit|+ unit_on_hand = [on_hand, unit.quantity].min+ unit_backordered = [backordered, unit.quantity - unit_on_hand].min+ on_hand -= unit_on_hand+ backordered -= unit_backordered++ package.add(FulfillmentItem.split(unit, unit_backordered), :backordered) if unit_backordered.positive?+ package.add(FulfillmentItem.split(unit, unit_on_hand), :on_hand) if unit_on_hand.positive?+ endelse- package.add unit+ units.each { |unit| package.add unit }endend@@ -84,8 +94,8 @@ module Spree# The units' own variants when they carry them, so a cart's variants are# read once however many locations are packed.def variants_for(units_by_variant_id)- variants = units_by_variant_id.each_with_object({}) do |(variant_id, unit), loaded|- loaded[variant_id] = unit.variant if unit.association(:variant).loaded?+ variants = units_by_variant_id.each_with_object({}) do |(variant_id, units), loaded|+ loaded[variant_id] = units.first.variant if units.first.association(:variant).loaded?endmissing_ids = units_by_variant_id.keys - variants.keysmissing_ids.empty? ? variants : variants.merge(Spree::Variant.where(id: missing_ids).index_by(&:id))diff --git a/spree/core/app/models/spree/stock/prioritizer.rb b/spree/core/app/models/spree/stock/prioritizer.rbindex 6290cfbae4..0c14750b36 100644--- a/spree/core/app/models/spree/stock/prioritizer.rb+++ b/spree/core/app/models/spree/stock/prioritizer.rb@@ -18,6 +18,7 @@ module Spreedef prioritized_packagessort_packages+ withdraw_covered_itemsadjust_packagesprune_packagespackages@@ -44,11 +45,10 @@ module Spreeend# 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.+ # one of them. 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@@ -56,25 +56,40 @@ module Spreedef sort_packagesreturn if estimator.nil?- ranked = packages.each_with_index.sort_by do |package, index|- [estimator.deliverable?(package) ? 0 : 1, index]+ deliverable, @undeliverable_packages = packages.partition { |package| estimator.deliverable?(package) }+ packages.replace(deliverable + @undeliverable_packages)+ end++ # Ordering alone loses to the Adjuster, which takes stock on hand anywhere+ # over a backorder; a unit the capable origins cannot cover stays, so it is+ # still reported as undeliverable rather than lost.+ def withdraw_covered_items+ return if @undeliverable_packages.blank? || @undeliverable_packages.size == packages.size++ supplied = supplied_quantities(packages - @undeliverable_packages)++ @undeliverable_packages.each do |package|+ package.contents.each do |item|+ package.remove_item(item) if supplied[hash_item(item)] >= item.inventory_unit.required_quantity+ endend+ end- packages.replace(ranked.map(&:first))+ def supplied_quantities(packages)+ packages.flat_map(&:contents).each_with_object(Hash.new(0)) do |item, supplied|+ supplied[hash_item(item)] += item.quantity+ endenddef prune_packagespackages.reject!(&:empty?)end+ # A proposed unit has no fulfillment, so its line item keeps two lines of+ # one variant apart; a pair, as XORed ids collide whenever they match.def hash_item(item)- shipment = item.inventory_unit.fulfillment- variant = item.inventory_unit.variant- if shipment.present?- variant.hash ^ shipment.hash- else- variant.hash- end+ unit = item.inventory_unit+ [unit.variant, unit.fulfillment || unit.line_item_id]endendenddiff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rbindex a2594a198a..c702d822a3 100644--- a/spree/core/app/services/spree/carts/update.rb+++ b/spree/core/app/services/spree/carts/update.rb@@ -252,12 +252,13 @@ module Spree# Three-way dispatch on the cart→checkout transition:# entering checkout → Reserve, mid-checkout mutation → Extend, reverting to cart → Release.+ # A new destination reserves again, because it can move the units to another origin.# A failed Reserve raises so the enclosing transaction rolls back and the# outer rescue surfaces the error to the API caller.def sync_stock_reservations(was_in_checkout:)if !cart.in_checkout?Spree::StockReservations::Release.call(cart: cart) if was_in_checkout- elsif was_in_checkout+ elsif was_in_checkout && !@destination_changed && !@new_delivery_destinationSpree::StockReservations::Extend.call(cart: cart)elseresult = Spree::StockReservations::Reserve.call(cart: cart)diff --git a/spree/core/app/services/spree/stock_reservations/reserve.rb b/spree/core/app/services/spree/stock_reservations/reserve.rbindex 4c328e6fd6..91a6996f61 100644--- a/spree/core/app/services/spree/stock_reservations/reserve.rb+++ b/spree/core/app/services/spree/stock_reservations/reserve.rb@@ -14,13 +14,17 @@ module SpreeApplicationRecord.transaction dotargets = build_targets(cart)- break if targets.empty?# Pessimistic lock + fresh read of count_on_hand. The lock serializes# concurrent checkouts and we use the locked rows below so we never- # check stock against a stale association cache.+ # check stock against a stale association cache. The shelves held+ # now are locked with the new ones, in id order, so two checkouts+ # moving holds past each other cannot deadlock.+ stock_level_ids = targets.map { |_, si, _| si.id } |+ Spree::StockReservation.for_order(cart).pluck(:stock_level_id)locked_stock_levels = Spree::StockLevel- .where(id: targets.map { |_, si| si.id })+ .where(id: stock_level_ids)+ .order(:id).lock.index_by(&:id)@@ -29,22 +33,13 @@ module Spreethis_order_used = Hash.new(0)- targets.each do |line_item, stock_level|+ reservations = targets.map do |line_item, stock_level, quantity|stock_level = locked_stock_levels.fetch(stock_level.id)available = stock_level.available_count - held.fetch(stock_level.id, 0) - this_order_used[stock_level.id]- if available < line_item.quantity- raise InsufficientStockError.new(- line_item,- I18n.t(- 'spree.insufficient_stock_for_reservation',- item: line_item.variant.name,- available: [available, 0].max- )- )- end+ raise_insufficient_stock(line_item, available) if available < quantity- this_order_used[stock_level.id] += line_item.quantity+ this_order_used[stock_level.id] += quantityreservation = existing[[stock_level.id, line_item.id]] ||Spree::StockReservation.new(stock_level: stock_level, line_item: line_item)@@ -55,10 +50,15 @@ module Spreereservation.order = cartreservation.cart = nilend- reservation.quantity = line_item.quantity+ reservation.quantity = quantityreservation.expires_at = expires_atreservation.save!+ reservationend++ # Left in place, a hold the allocation moved away from blocks other buyers until it expires.+ moved = Spree::StockReservation.for_order(cart).where.not(id: reservations.map(&:id))+ Spree::StockReservation.withdraw(moved)endsuccess(cart)@@ -68,23 +68,71 @@ module Spreeprivate+ # Held where the allocation packs each unit, so the hold protects the stock the order will ship.def build_targets(cart)- cart.line_items.includes(variant: [:product, { stock_levels: :stock_location }]).filter_map do |line_item|+ cart.line_items.reset+ coordinator = Spree::Stock::Coordinator.new(cart)+ packages = coordinator.allocated_packages+ check_allocated_in_full(cart, packages_items(packages))++ # Once the address is known, a unit only an origin unable to reach it+ # would pack cannot ship, so it is left to the delivery check rather+ # than held where it blocks buyers that origin does serve.+ packages = packages.select { |package| coordinator.deliverable?(package) } if cart.ship_address.present?+ items = packages_items(packages)+ stock_levels = Spree::Stock::Packer.stock_levels_by_location(packages.map(&:stock_location).uniq,+ cart.line_items.map(&:variant_id).uniq)++ # Summed because a splitter can pack one line into several packages from one location.+ quantities = Hash.new(0)+ items.each do |stock_location, item|+ next unless item.on_hand?++ line_item = item.inventory_unit.line_itemvariant = line_item.variant- next unless variant&.should_track_inventory?-- stock_level = select_stock_level(variant)+ stock_level = stock_levels.dig(stock_location.id, variant.id)# Backorderable and pre-cart variants oversell past count_on_hand,# so a reservation capped at on-hand stock would wrongly reject them;# their cap is enforced by Stock::Quantifier#can_supply? instead.+ next unless variant.should_track_inventory?next if stock_level.nil? || stock_level.backorderable? || variant.preorder?- [line_item, stock_level]+ quantities[[line_item, stock_level]] += item.quantity+ end++ quantities.map { |(line_item, stock_level), quantity| [line_item, stock_level, quantity] }+ end++ def packages_items(packages)+ packages.flat_map { |package| package.contents.map { |item| [package.stock_location, item] } }+ end++ # A line placed nowhere is left to the delivery check, which can say why;+ # one placed in part has shelves that fall short, and is refused.+ def check_allocated_in_full(cart, items)+ allocated = items.each_with_object(Hash.new(0)) do |(_, item), quantities|+ quantities[item.inventory_unit.line_item_id] += item.quantity+ end++ cart.line_items.each do |line_item|+ variant = line_item.variant+ next unless variant&.should_track_inventory?+ next if variant.preorder?++ placed = allocated[line_item.id]+ raise_insufficient_stock(line_item, placed) if placed.positive? && placed < line_item.quantityendend- def select_stock_level(variant)- variant.stock_levels.detect { |si| si.stock_location&.active? && si.available? }+ def raise_insufficient_stock(line_item, available)+ raise InsufficientStockError.new(+ line_item,+ I18n.t(+ 'spree.insufficient_stock_for_reservation',+ item: line_item.variant.name,+ available: [available, 0].max+ )+ )enddef held_by_others(stock_level_ids, owner)@@ -104,8 +152,8 @@ module Spreedef existing_reservations_for(targets)return {} if targets.empty?- stock_level_ids = targets.map { |_, si| si.id }- line_item_ids = targets.map { |li, _| li.id }+ stock_level_ids = targets.map { |_, si, _| si.id }+ line_item_ids = targets.map { |li, _, _| li.id }Spree::StockReservation.where(stock_level_id: stock_level_ids, line_item_id: line_item_ids)diff --git a/spree/core/lib/spree/checkout/default_requirements.rb b/spree/core/lib/spree/checkout/default_requirements.rbindex e389ed0ea7..dee7536411 100644--- a/spree/core/lib/spree/checkout/default_requirements.rb+++ b/spree/core/lib/spree/checkout/default_requirements.rb@@ -10,6 +10,12 @@ module Spree## @see Requirementsclass DefaultRequirements+ # Everything the discontinuation and stock checks read, so a set of+ # lines is checked at once.+ STOCK_CHECK_ASSOCIATIONS = {+ variant: [{ product: %i[store product_publications] }, { stock_levels: %i[stock_location active_stock_reservations] }]+ }.freeze+# @param cart [Spree::Cart]def initialize(cart)@cart = cart@@ -33,6 +39,7 @@ module Spreer << req('address', 'email', I18n.t('spree.checkout_requirements.email_required')) unless @cart.email.present?r << req('address', 'ship_address', I18n.t('spree.checkout_requirements.ship_address_required')) if @cart.shipping_address_required? && @cart.ship_address.blank?r << req('delivery', 'delivery_method', I18n.t('spree.checkout_requirements.delivery_method_required')) if delivery_step_required? && !delivery_method_selected?+ r.concat(undeliverable_errors)r << req('payment', 'payment', I18n.t('spree.checkout_requirements.payment_required')) if payment_required? && !payment_satisfied?r << req('address', 'po_number', I18n.t('spree.checkout_requirements.po_number_required')) if po_number_missing?r << order_minimum_requirement if below_order_minimum?@@ -102,16 +109,37 @@ module Spreeendend+ # A rebuild drops a proposal no method can quote with only a transient+ # warning, so part of a line can be in no fulfillment. Advisory, so the+ # buyer reads it while they can still change the address or the cart.+ def undeliverable_errors+ return [] unless delivery_step_required? && @cart.fulfillments.any?++ undelivered_line_items.map do |line_item|+ req('delivery', 'line_items', I18n.t('spree.cart_line_item.delivery_unavailable', li_name: line_item.name),+ code: 'delivery_unavailable')+ end+ end++ # A line short of stock is packed short too; the stock check already+ # names it. Only lines short of a fulfillment pay for that check, so a+ # cart read stays at one query.+ def undelivered_line_items+ allocated = Spree::FulfillmentItem.where(fulfillment_id: @cart.fulfillments.select(:id))+ .group(:line_item_id).sum(:quantity)+ short = @cart.line_items.select { |line_item| allocated.fetch(line_item.id, 0) < line_item.quantity }+ return [] if short.empty?++ ActiveRecord::Associations::Preloader.new(records: short, associations: STOCK_CHECK_ASSOCIATIONS).call+ short.reject { |line_item| discontinued?(line_item) || !line_item.sufficient_stock? }+ end+def discontinued?(line_item)line_item.variant.nil? || line_item.variant.discontinued? || line_item.variant.product.discontinued?enddef completion_line_items- # Everything the discontinuation and stock checks read, for every line- # at once.- @completion_line_items ||= @cart.line_items.includes(- variant: [{ product: %i[store product_publications] }, { stock_levels: %i[stock_location active_stock_reservations] }]- ).to_a+ @completion_line_items ||= @cart.line_items.includes(STOCK_CHECK_ASSOCIATIONS).to_aenddef delivery_step_required?diff --git a/spree/core/spec/lib/spree/checkout/requirements_spec.rb b/spree/core/spec/lib/spree/checkout/requirements_spec.rbindex a9ea45d7ff..5942707d5a 100644--- a/spree/core/spec/lib/spree/checkout/requirements_spec.rb+++ b/spree/core/spec/lib/spree/checkout/requirements_spec.rb@@ -78,6 +78,58 @@ RSpec.describe Spree::Checkout::Requirements do)end+ it 'reports part of a line in no fulfillment before completion, so the buyer can change it' do+ line_item = order.line_items.first+ line_item.update_column(:quantity, line_item.quantity + 1)++ expect(described_class.new(order.reload).call).to include(+ a_hash_including(step: 'delivery', code: 'delivery_unavailable')+ )+ end++ it 'checks the lines short of a fulfillment together, so more of them cost no more queries' do+ cart_with_short_lines = lambda do |count|+ create(:order_with_line_items, store: store, line_items_count: count).tap do |cart|+ cart.line_items.each { |line_item| line_item.update_column(:quantity, line_item.quantity + 1) }+ end.reload+ end+ # Inside the store a request runs in, as without one every stock check looks the default store up.+ query_count = lambda do |cart|+ count = 0+ counter = ->(*, payload) { count += 1 unless payload[:name].to_s.match?(/SCHEMA|TRANSACTION/) || payload[:cached] }+ Spree::Current.set(store: store) do+ ActiveSupport::Notifications.subscribed(counter, 'sql.active_record') { described_class.new(cart).call }+ end+ count+ end++ two, three = cart_with_short_lines.call(2), cart_with_short_lines.call(3)++ expect(query_count.call(three)).to eq(query_count.call(two))+ end++ it 'completes once every unit of every line is in a fulfillment' do+ expect(described_class.new(order).call(completion: true))+ .not_to include(a_hash_including(code: 'delivery_unavailable'))+ end++ it 'leaves a line short of stock to the stock check' do+ line_item = order.line_items.first+ line_item.update_column(:quantity, line_item.quantity + 1)+ line_item.variant.stock_levels.update_all(count_on_hand: 0, backorderable: false)++ codes = described_class.new(order.reload).call(completion: true).map { |requirement| requirement[:code] }+ expect(codes).to include('out_of_stock')+ expect(codes).not_to include('delivery_unavailable')+ end++ it 'says nothing of delivery before any can be proposed' do+ order.fulfillments.destroy_all++ expect(described_class.new(order.reload).call(completion: true))+ .not_to include(a_hash_including(code: 'delivery_unavailable'))+ end+it 'does not require shipping_method when no delivery step' doallow(order).to receive(:has_checkout_step?).with('delivery').and_return(false)allow(order).to receive(:has_checkout_step?).with('payment').and_return(true)diff --git a/spree/core/spec/models/spree/order_routing/strategy/rules_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/rules_spec.rbindex f3bf5fa352..8b31a7c8a2 100644--- a/spree/core/spec/models/spree/order_routing/strategy/rules_spec.rb+++ b/spree/core/spec/models/spree/order_routing/strategy/rules_spec.rb@@ -36,6 +36,14 @@ RSpec.describe Spree::OrderRouting::Strategy::Rules, type: :model doexpect(packages.map(&:stock_location)).to all(eq(preferred_loc))end+ it "never allocates from a location the item's delivery profile does not cover" do+ variant.product.delivery_profile.default_origin_group.stock_locations = [default_loc]+ default_loc.stock_level_or_create(variant).update!(count_on_hand: 0, backorderable: false)++ packages = subject.for_allocation+ expect(packages.map(&:stock_location)).not_to include(preferred_loc)+ end+it 'resolves the reducer from the strategy namespace' dostub_const("#{described_class}::Reducer",diff --git a/spree/core/spec/models/spree/stock/coordinator_spec.rb b/spree/core/spec/models/spree/stock/coordinator_spec.rbindex 8223796317..4b76ec082a 100644--- a/spree/core/spec/models/spree/stock/coordinator_spec.rb+++ b/spree/core/spec/models/spree/stock/coordinator_spec.rb@@ -129,6 +129,18 @@ module Spreeexpect(packages.map { |package| package.stock_location.name }).to eq [eu_warehouse.name]expect(packages.first.delivery_rates.map(&:name)).to include('EU Standard')end++ it 'backorders from the origin that serves the destination rather than ship nothing from stock on hand' do+ order.variants.each do |variant|+ eu_warehouse.stock_level_or_create(variant).update!(count_on_hand: 0, backorderable: true)+ end++ packages = subject.packages++ expect(packages.map { |package| package.stock_location.name }).to eq [eu_warehouse.name]+ expect(packages.first.quantity(:backordered)).to eq order.line_items.sum(&:quantity)+ expect(packages.first.delivery_rates.map(&:name)).to include('EU Standard')+ endenddescribe 'channel-scoped allocation' do@@ -187,6 +199,18 @@ module Spreeexpect(subject.build_packages.count).to eq(StockLocation.count)end+ it 'allocates every line when two lines share a variant' do+ product.stock_levels.each { |stock_level| stock_level.update!(count_on_hand: 10) }+ second = create(:line_item, order: order, variant: product.default_variant, quantity: 3)++ allocated = Hash.new(0)+ described_class.new(order.reload).packages.flat_map(&:contents).each do |item|+ allocated[item.inventory_unit.line_item_id] += item.quantity+ end++ expect(allocated).to eq(order.line_items.first.id => 2, second.id => 3)+ end+context 'missing stock items in stock location' dolet!(:another_location) { create(:stock_location, propagate_all_variants: false) }diff --git a/spree/core/spec/models/spree/stock/packer_spec.rb b/spree/core/spec/models/spree/stock/packer_spec.rbindex fb804baf3d..525ed35599 100644--- a/spree/core/spec/models/spree/stock/packer_spec.rb+++ b/spree/core/spec/models/spree/stock/packer_spec.rb@@ -46,6 +46,20 @@ module Spreeexpect(package.backordered.size).to eq 1end+ context 'two lines of one variant' do+ let(:variant) { create(:variant) }+ let(:inventory_units) { Array.new(2) { FulfillmentItem.new(variant: variant, quantity: 3) } }++ it 'splits the shelf between them rather than offering it to each in full' do+ stock_location.stock_level_or_create(variant).update!(count_on_hand: 4, backorderable: false)++ package = subject.default_package++ expect(package.on_hand.map(&:quantity)).to eq [3, 1]+ expect(package.backordered).to be_empty+ end+ end+context "location doesn't have order items in stock" dolet(:stock_location) { create(:stock_location, propagate_all_variants: false) }let(:inventory_units) { [FulfillmentItem.new(variant: create(:variant))] }diff --git a/spree/core/spec/models/spree/stock/prioritizer_spec.rb b/spree/core/spec/models/spree/stock/prioritizer_spec.rbindex cf7c3e4a21..beeeb5bea8 100644--- a/spree/core/spec/models/spree/stock/prioritizer_spec.rb+++ b/spree/core/spec/models/spree/stock/prioritizer_spec.rb@@ -47,6 +47,36 @@ module Spreeexpect(packages.first.quantity).to eq 2end+ it 'backorders from an origin that can deliver rather than take stock on hand from one that cannot' 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, :backordered }+ end++ packages = Prioritizer.new([undeliverable, deliverable],+ estimator: deliverable_only(deliverable)).prioritized_packages++ expect(packages).to eq [deliverable]+ expect(packages.first.quantity(:backordered)).to eq 2+ end++ it 'leaves a unit the origins that can deliver cannot supply with the origin that holds it' do+ 2.times { build_inventory_unit }+ covered, uncovered = inventory_units++ undeliverable = pack { |package| inventory_units.each { |unit| package.add unit } }+ deliverable = Package.new(other_location).tap { |package| package.add covered, :backordered }++ packages = Prioritizer.new([undeliverable, deliverable],+ estimator: deliverable_only(deliverable)).prioritized_packages++ expect(packages).to eq [deliverable, undeliverable]+ expect(deliverable.contents.map(&:inventory_unit)).to eq [covered]+ expect(undeliverable.contents.map(&:inventory_unit)).to eq [uncovered]+ end+it 'keeps the order it was given between origins that can both deliver' do2.times { build_inventory_unit }diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rbindex 11fbdb57c0..28a675f9a5 100644--- a/spree/core/spec/services/spree/carts/update_spec.rb+++ b/spree/core/spec/services/spree/carts/update_spec.rb@@ -961,6 +961,14 @@ module Spreeexpect(Spree::StockReservation.where(cart_id: cart.id).maximum(:expires_at)).to be > original_expiryend++ it 'reserves again when the destination changes, since the units may ship from elsewhere' do+ cart.line_items.first.variant.stock_levels.first.update!(backorderable: true)++ described_class.call(cart: cart, params: { shipping_address: address_params.merge(city: 'Brooklyn', postal_code: '11201') })++ expect(Spree::StockReservation.where(cart_id: cart.id)).to be_empty+ endend# Reverting to the `cart` state from inside Update isn't reachable viadiff --git a/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb b/spree/core/spec/services/spree/stock_reservations/reserve_spec.rbindex cb27a5cdb9..931f42d406 100644--- a/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb+++ b/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb@@ -2,9 +2,14 @@ require 'spec_helper'describe Spree::StockReservations::Reserve dolet(:store) { create(:store) }- let(:variant) { create(:variant) }- let!(:stock_location) { variant.stock_levels.first.stock_location.tap { |sl| sl.update!(active: true) } }- let!(:stock_level) { variant.stock_levels.first.tap { |si| si.update!(backorderable: false); si.set_count_on_hand(10) } }+ let!(:stock_location) { create(:stock_location, store: store) }+ let(:variant) { create(:variant, product: create(:product, store: store)) }+ let!(:stock_level) do+ variant.stock_levels.find_by!(stock_location: stock_location).tap do |si|+ si.update!(backorderable: false)+ si.set_count_on_hand(10)+ end+ endlet(:order) { create(:order, store: store) }let!(:line_item) { create(:line_item, order: order, variant: variant, quantity: 3) }@@ -91,6 +96,81 @@ describe Spree::StockReservations::Reserve doexpect(result.error.to_s).to include('available')end+ it 'holds two lines of one variant on the shelf they share' do+ second = create(:line_item, order: order, variant: variant, quantity: 3)++ expect(result).to be_success+ expect(Spree::StockReservation.where(line_item: [line_item, second]).pluck(:quantity)).to contain_exactly(3, 3)+ expect(stock_level.reload.reserved_count).to eq(6)+ end++ it 'holds each unit at the location the allocation takes it from' do+ stock_level.set_count_on_hand(2)+ other_level = create(:stock_location, store: store).stock_level_or_create(variant)+ other_level.update!(backorderable: false)+ other_level.set_count_on_hand(10)++ expect(result).to be_success+ expect(stock_level.reload.reserved_count).to eq(2)+ expect(other_level.reload.reserved_count).to eq(1)+ end++ it 'withdraws a hold the allocation no longer takes from that shelf' do+ result+ stock_level.update!(backorderable: true)++ described_class.call(cart: order)++ expect(Spree::StockReservation.for_order(order)).to be_empty+ expect(stock_level.reload.reserved_count).to eq(0)+ end++ it 'leaves a line no covered location stocks to the delivery check rather than refuse it' do+ variant.product.delivery_profile.default_origin_group.stock_locations =+ [create(:stock_location, store: store, propagate_all_variants: false)]++ expect(result).to be_success+ expect(Spree::StockReservation.for_order(order)).to be_empty+ end++ context 'when only one origin can deliver to the address' do+ let(:profile) { variant.product.delivery_profile }+ let(:netherlands) { Spree::Country.by_iso('NL') }+ let(:eu_location) { create(:stock_location, store: store, propagate_all_variants: false) }+ let!(:eu_level) do+ eu_location.stock_level_or_create(variant).tap do |level|+ level.update!(backorderable: false)+ level.set_count_on_hand(2)+ end+ end++ before do+ Spree::DeliveryMethod.delete_all+ eu_group = profile.delivery_origin_groups.create!(name: 'EU')+ profile.default_origin_group.stock_locations = [stock_location]+ eu_group.stock_locations = [eu_location]++ eu_zone = create(:delivery_zone_with_country, store: store, delivery_profile: profile,+ delivery_origin_group: eu_group, country: netherlands)+ create(:delivery_method, store: store, delivery_profile: profile, delivery_origin_group: eu_group, delivery_zone: eu_zone)+ end++ it 'does not hold units that only an origin unable to reach the address would ship' do+ order.update!(ship_address: create(:address, country: netherlands, state: nil))++ expect(result).to be_success+ expect(eu_level.reload.reserved_count).to eq(2)+ expect(stock_level.reload.reserved_count).to eq(0)+ end++ it 'holds where the allocation packs while no address says what can ship' do+ order.update_columns(ship_address_id: nil)++ expect(result).to be_success+ expect(stock_level.reload.reserved_count + eu_level.reload.reserved_count).to eq(3)+ end+ end+it 'skips backorderable stock items' dostock_level.update!(backorderable: true)expect { result }.not_to change(Spree::StockReservation, :count)diff --git a/spree/core/spec/workflows/spree/orders/upsert_items_spec.rb b/spree/core/spec/workflows/spree/orders/upsert_items_spec.rbindex 5b1b5fba05..bc2fc30abf 100644--- a/spree/core/spec/workflows/spree/orders/upsert_items_spec.rb+++ b/spree/core/spec/workflows/spree/orders/upsert_items_spec.rb@@ -8,9 +8,11 @@ module Spreelet(:variant) { create(:variant) }let(:variant2) { create(:variant) }+ let(:stock_location) { create(:stock_location, store: store) }+before do[variant, variant2].each do |v|- v.stock_levels.first.update!(count_on_hand: 10)+ stock_location.stock_level_or_create(v).update!(count_on_hand: 10)store.products << v.product unless store.products.include?(v.product)endend