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: item changes dropped delivery to zero and reset the chosen rate (#14751)

Łukasz Adamczyke247703dba03
diff --git a/docs/plans/6.0-delivery-rate-provider.md b/docs/plans/6.0-delivery-rate-provider.md
index fa644d123c..6935cbeaa5 100644
--- a/docs/plans/6.0-delivery-rate-provider.md
+++ b/docs/plans/6.0-delivery-rate-provider.md
@@ -158,7 +158,7 @@ method sprawl; the `Internal` calculator path stays for manual rates.
### Selected-rate preservation is not the provider's business
-`Shipment#refresh_rates` remembers the previously selected method and re-selects it if still offered (`shipment.rb:348, 355-361`). This is checkout UX, not rate estimation. It stays exactly where it is. **No provider or checkout service may unconditionally `min_by(&:cost).update(selected: true)`** — that would silently reset a customer's or admin's chosen rate on every refresh.
+`Fulfillment#refresh_rates` remembers the previously selected rate and re-selects it if still offered: the same carrier service, then the same method, then the estimator's own pick. The proposal rebuilds follow the same rule (`Cart#rebuild_fulfillments!`, and `Order#rebuild_fulfillments!` on an open order): each new proposal takes the earlier choice from its stock location whose method it is quoted for, a rebuild after a destination change keeps nothing, and every proposal is priced at the rate it ends up with (2026-09-24, V-3696). This is checkout UX, not rate estimation, and it stays on the fulfillment. **No provider or checkout service may unconditionally `min_by(&:cost).update(selected: true)`** — that would silently reset a customer's or admin's chosen rate on every refresh.
### Provider is per delivery method, resolved through the method's store
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 7940dfe9f9..99b0f0e1a0 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -46,6 +46,18 @@ Rejected: deriving the statuses inside the totals workflow, which would cover ev
**Plans amended:** `6.0-cart-order-split.md` (the derive-then-persist triggers).
+## 2026-09-24: A rebuilt delivery proposal keeps the customer's choice and its price, silently, with no completion guard and no cleanup
+
+**Context:** Adding an item after the address was set dropped delivery to $0.00 and the order completed that way (V-3696). Reproduced on `main`: a cart read $20.00 + $5.00 Standard = $25.00 after the address; one more unit made it $40.00 + $0.00 = $40.00, and order R1001 was placed and paid at $40.00. Every cart recalculation rebuilds the delivery proposals through `Cart#ensure_updated_fulfillments` -> `rebuild_fulfillments!`, and nothing copied the selected rate's price onto the new rows, so their stored `cost` stayed 0 and `RecalculateTotals` summed that into `delivery_total`. Only the address-change path priced its rebuild; `Checkout::Advance`'s rebuild for quick checkout had the same gap. Completion's drift guard could not see it, because its in-lock recalculation re-sums the same stored zero. Review then found two more faces of the same rebuild. It re-ran the estimator's default pick, so a shopper who had chosen free Store Pickup was switched back to Standard on the next item change - hidden while the cost came out $0.00, a $5.00 charge once it did - against the rule in `6.0-delivery-rate-provider.md` that nothing may silently reset a chosen rate. And draft orders ride the same recalculation, where `Order#ensure_updated_fulfillments` deleted the fulfillments outright and rebuilt nothing: a $25.00 draft became $40.00 with no delivery at all when an admin added an item.
+
+**Decision:** A rebuild carries the choice over and prices what it builds. `Fulfillment#carry_over_selection` selects the rate standing for the one chosen before - the same carrier service when still quoted, then the same method, then the estimator's pick, the rule `refresh_rates` already applied, now shared through one private method - and sets the proposal's cost from it before it is saved. `Cart#rebuild_fulfillments!` and `Order#rebuild_fulfillments!` both call it, so every caller is covered: the recalculation after any item change, quick checkout, the draft-order build. The earlier choices are grouped by stock location, and each new proposal takes the first one whose method it is quoted for, because one location can ship several proposals - a digital item beside a physical one, stock on hand beside a backorder - each with its own choice. A rebuild for a changed destination keeps nothing (`keep_selection: false`, decided by `Carts::Update` and `Orders::Update` and passed down through `Cart#recalculate_for_address_change!` and `Orders::BuildFulfillments`): a choice made for one address is not a choice for another, and before an address is known only pickup is offered, so keeping that default once shipping is available would pin every cart to pickup. A destination change is a different address row, a pickup counter picked or cleared, or an edit to the fields a quote reads (`Spree::Address::DESTINATION_FIELDS`: street, city, state, postal code, country). The address id alone cannot say, because a guest's edit updates the row in place; and a corrected phone number or recipient name, or a market change, keeps the choice and quotes it again. `Orders::Update` now rebuilds on an in-place edit to those fields, where before it did not rebuild at all. `Order#ensure_updated_fulfillments` rebuilds instead of deleting. When the new contents re-quote the kept rate at a different price, the cart takes the new price without telling the shopper: it is the current quote for what they are buying, and the total already shows it.
+
+Rejected: a warning when delivery changes on rebuild - the new figure is correct, not a surprise to flag. Deferred: a completion guard refusing an order whose stored delivery cost disagrees with its selected rate. It would catch this whole class of defect, but fixing the one path that produces the disagreement is enough for now. Rejected: a cleanup task or upgrade note for orders already placed with $0.00 delivery - they exist only on 6.0 beta installs. Rejected: setting the cost in `Stock::Package#to_fulfillment`, which would reach every builder at once - including `OrderInventory`'s rebuild of a placed order, whose delivery was charged at placement and is re-priced only through the post-placement edit path. For the same reason `Order#rebuild_fulfillments!` does not carry a choice over or set a cost on a placed order; it still deletes and replaces that order's fulfillments, as it did before.
+
+**Consequences:** Adding, changing or removing items keeps the delivery the customer or admin chose, at its price for the new contents, on carts and draft orders alike; a new address still starts from the default. Beta orders already placed at $0.00 delivery stay as they are. Two proposals from one location offering the same methods (stock on hand beside a backorder) that had different choices are matched in order, so the pairing can swap; nothing identifies a proposal across a rebuild. Left alone, all pre-existing: `Order#ensure_updated_fulfillments` publishes `order.updated` before the recalculation has summed the new delivery costs, so the event carries the previous figures; a rebuild still drops the parcel locker frozen into `pickup_point_data`, so a kept pickup-point method needs its point chosen again; `recalculate_for_address_change!` quotes delivery before `item_total` is refreshed, so a rate that reads the order value quotes on the old figure; and the currency-change callback rebuilds before the line items are converted. Nothing yet stops a future path from storing a cost that disagrees with the selected rate; that is the deferred guard.
+
+**Plans amended:** `6.0-delivery-rate-provider.md` (Selected-rate preservation).
+
## 2026-09-23: The free-gift action prices its own gift, and covers the copy the shopper already has
**Context:** The `Create line items` action added its variant at full price and wrote no discount, so the promotion raised the bill: a cart of 2 x $89.99 became $269.97 when an automatic gift promotion applied, with no line saying why, and the shopper could not delete the gift because every recalculation put it back (V-3666). The action was the only one describing itself in the docs without saying how the money worked - "Free items", "free items in the cart", "Free gift with purchase" - while `discount_scope` answered nil, which is what excluded it from `Spree::Adjusters::Promotion`. The documented workaround, pairing it with an order discount set to the gift's price, was tested and fails three ways: the order-level amount prorates across every line, so the gift reads as an $8.57 purchase and the $20 item beside it as $11.43; the discount still pays out when the gift is out of stock, because `Promotion#activate` maps over actions independently ($20 cart, $15 off, no gift); and the compensation competes for the order group under 6.0 winner-only, so a larger promotion deletes it and the bill goes back up ($2.00 to $17.00 on entering a free-gift coupon).
diff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rb
index c908d03f14..8d83325a50 100644
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@ -27,6 +27,10 @@ module Spree
# those attributes depending of the logic of their applications
ADDRESS_FIELDS = %w(first_name last_name company address1 address2 city state postal_code country phone)
+ # The columns a delivery quote reads. A change to anything else (a phone
+ # number, the recipient's name) leaves the parcel going where it was.
+ DESTINATION_FIELDS = %w(address1 address2 city state_code postal_code country_code).freeze
+
# Beyond identity and ownership, three groups are excluded because they
# cannot tell two addresses apart. Latitude and longitude are derived from
# the address, so an entry whose geocoding has already run would otherwise
@@ -379,6 +383,12 @@ module Spree
attributes.except(*EXCLUDED_KEYS_FOR_COMPARISON)
end
+ # @return [Boolean] whether the last save moved this address somewhere
+ # else, as opposed to correcting who receives the parcel
+ def saved_change_to_destination?
+ saved_changes.keys.intersect?(DESTINATION_FIELDS)
+ end
+
# A country alone doesn't make an address — a new one is pre-filled with the
# store's default, so both the code and the association are ignored here.
def empty?
diff --git a/spree/core/app/models/spree/cart.rb b/spree/core/app/models/spree/cart.rb
index 252ae72007..437e804cd8 100644
--- a/spree/core/app/models/spree/cart.rb
+++ b/spree/core/app/models/spree/cart.rb
@@ -162,9 +162,15 @@ module Spree
# Idempotent delivery-proposal rebuild — replaces the destructive
# order-side create_proposed_fulfillments. Open fulfillments are rebuilt from
# the current items/address; nothing here touches a completed cart.
- def rebuild_fulfillments!
+ #
+ # @param keep_selection [Boolean] false when the destination changed: a
+ # choice made for one address is not a choice for another, and before an
+ # address is known the only rate on offer is a pickup default
+ def rebuild_fulfillments!(keep_selection: true)
return if completed?
+ previous_selections = keep_selection ? fulfillments.selected_rates_by_stock_location : {}
+
discounts.for_fulfillments.delete_all
tax_lines.for_fulfillments.delete_all
fees.for_fulfillments.delete_all
@@ -182,6 +188,7 @@ module Spree
Spree::Stock::Coordinator.new(self).fulfillments.each do |fulfillment|
fulfillment.address_id = ship_address_id
fulfillment.order = nil
+ fulfillment.carry_over_selection(previous_selections.fetch(fulfillment.stock_location_id, []))
fulfillments << fulfillment
end
prune_undeliverable_fulfillments!
@@ -231,7 +238,11 @@ module Spree
# Re-prices, re-taxes and rebuilds delivery proposals — the
# recalculation-on-write replacement for transition-triggered rebuilds.
# Called by Carts::Update after address/market changes.
- def recalculate_for_address_change!
+ #
+ # @param keep_selection [Boolean] true when the parcel still goes where it
+ # did (a market change, a corrected phone number), so the chosen
+ # delivery is kept and quoted again
+ def recalculate_for_address_change!(keep_selection: false)
# One provider round for the whole cart, and persisted: a per-item loop
# would ask an external pricing system once per line, and nothing here
# saves the line items — rebuild_fulfillments! and recalculate_totals!
@@ -244,8 +255,7 @@ module Spree
raise Spree::Pricing::PriceResolution::ProviderUnavailable, result.error.to_s if result.failure?
Spree::Carts::PriceItems.apply(result.value)
- rebuild_fulfillments!
- set_fulfillments_cost
+ rebuild_fulfillments!(keep_selection: keep_selection)
recalculate_totals!
end
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rb
index 14a43feab6..ea36d1a6fb 100644
--- a/spree/core/app/models/spree/fulfillment.rb
+++ b/spree/core/app/models/spree/fulfillment.rb
@@ -92,6 +92,18 @@ module Spree
delegate :store, :currency, to: :owner
+ # What a rebuild hands to {#carry_over_selection}, read before the old
+ # proposals and their rates are deleted. Grouped rather than keyed by
+ # location: one location can ship several proposals (a digital item beside
+ # a physical one, stock on hand beside a backorder), each with its own choice.
+ #
+ # @return [Hash{Integer => Array<Spree::DeliveryRate>}] the selected rates
+ # of each stock location's proposals
+ def self.selected_rates_by_stock_location
+ includes(:selected_delivery_rate).group_by(&:stock_location_id).
+ transform_values { |proposals| proposals.filter_map(&:selected_delivery_rate) }
+ end
+
# The exactly-one owner of this fulfillment — the cart during checkout,
# the order after completion. New code must read +owner+, never assume
# +order+.
@@ -543,34 +555,13 @@ module Spree
# StockEstimator.new assignment below will replace the current delivery_method
original_shipping_method_id = delivery_method.try(:id)
- # A carrier method quotes several rates (one per service), so the
- # method id alone no longer identifies the customer's choice — capture
- # the selected rate's carrier service too.
original_selection = selected_delivery_rate
- original_carrier = original_selection&.carrier
- original_service_level = original_selection&.service_level
self.delivery_rates = Stock::Estimator.new(owner).
delivery_rates(to_package, audience)
if delivery_method
- # Keep the previously chosen carrier service when it is still quoted,
- # then the previously chosen method, then the estimator's own pick
- # (the cheapest rate, already flagged selected) rather than leaving
- # the fulfillment unselected.
- selected_rate =
- if original_shipping_method_id && original_carrier
- delivery_rates.detect do |rate|
- rate.delivery_method_id == original_shipping_method_id &&
- rate.carrier == original_carrier &&
- rate.service_level == original_service_level
- end
- end
- selected_rate ||=
- if original_shipping_method_id
- delivery_rates.detect { |rate| rate.delivery_method_id == original_shipping_method_id }
- end
- selected_rate ||= delivery_rates.detect(&:selected)
+ selected_rate = successor_rate(original_shipping_method_id, original_selection)
save!
self.selected_shipping_rate_id = selected_rate.id if selected_rate
@@ -755,6 +746,25 @@ module Spree
end
end
+ # Carries the customer's choice onto a freshly built, unsaved proposal:
+ # takes the first of +candidates+ whose method this proposal is quoted for,
+ # selects the rate standing for it and prices the proposal at it, so a
+ # rebuild neither resets the choice nor drops its cost. The rate taken is
+ # removed from +candidates+, leaving the rest to this proposal's siblings.
+ #
+ # @param candidates [Array<Spree::DeliveryRate>] the rates selected on the
+ # proposals this stock location had before the rebuild
+ # @return [void]
+ def carry_over_selection(candidates)
+ quoted_method_ids = delivery_rates.map(&:delivery_method_id)
+ previous_rate = candidates.find { |rate| quoted_method_ids.include?(rate.delivery_method_id) }
+ candidates.delete(previous_rate)
+
+ choice = successor_rate(previous_rate&.delivery_method_id, previous_rate)
+ delivery_rates.each { |rate| rate.selected = rate == choice }
+ self.cost = choice&.cost || 0
+ end
+
# @deprecated No-op since 6.0; removed in 6.1.
#
# This re-derived the status from the order's payment state on every order
@@ -792,6 +802,21 @@ module Spree
private
+ # The previously chosen carrier service when it is still quoted, then the
+ # previously chosen method, then the estimator's own pick - a carrier
+ # method quotes one rate per service, so the method alone does not
+ # identify the choice.
+ def successor_rate(delivery_method_id, previous_rate)
+ same_method = delivery_method_id ? delivery_rates.select { |rate| rate.delivery_method_id == delivery_method_id } : []
+ same_service = if previous_rate&.carrier
+ same_method.detect do |rate|
+ rate.carrier == previous_rate.carrier && rate.service_level == previous_rate.service_level
+ end
+ end
+
+ same_service || same_method.first || delivery_rates.detect(&:selected)
+ end
+
# @return [Boolean] whether this parcel's order shares its payment with
# others placed in the same checkout
# Draws one parcel's worth from a payment and reports what it took.
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index eece1f7dc3..d11cd787f5 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -889,7 +889,15 @@ module Spree
fully_fulfilled?
end
- def rebuild_fulfillments!
+ # @param keep_selection [Boolean] false when the destination changed, so
+ # the new proposals start from the default rate
+ def rebuild_fulfillments!(keep_selection: true)
+ # A placed order's delivery was charged at placement; re-pricing it
+ # belongs to the post-placement edit path, not to a rebuild.
+ unless completed?
+ previous_selections = keep_selection ? fulfillments.selected_rates_by_stock_location : {}
+ end
+
discounts.for_fulfillments.delete_all
tax_lines.for_fulfillments.delete_all
fees.for_fulfillments.delete_all
@@ -904,7 +912,10 @@ module Spree
fulfillment_items.on_hand_or_backordered.delete_all
self.fulfillments = order_routing_strategy.for_allocation.map do |package|
- package.to_fulfillment.tap { |fulfillment| fulfillment.address_id = ship_address_id }
+ package.to_fulfillment.tap do |fulfillment|
+ fulfillment.address_id = ship_address_id
+ fulfillment.carry_over_selection(previous_selections.fetch(fulfillment.stock_location_id, [])) if previous_selections
+ end
end
end
@@ -977,13 +988,13 @@ module Spree
::Spree::PromotionHandler::Cart.new(self).activate
end
- # Drops stale fulfillments so they are rebuilt from current items.
+ # Rebuilds stale fulfillments from the current items, keeping the chosen
+ # rates. The first ones are Spree::Orders::BuildFulfillments' to build.
def ensure_updated_fulfillments
if fulfillments.any? && !completed?
- fulfillments.destroy_all
- update_column(:delivery_total, 0)
+ rebuild_fulfillments!
- # Manually publish update event since update_column bypasses callbacks
+ # Nothing here saves the order, so its update event is published by hand.
publish_event('order.updated')
end
end
diff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rb
index 17d02f0270..7afba40cf7 100644
--- a/spree/core/app/services/spree/carts/update.rb
+++ b/spree/core/app/services/spree/carts/update.rb
@@ -16,6 +16,9 @@ module Spree
assign_default_addresses
cart.save!
+ # Read before the items: processing them reloads the cart, which forgets what this save changed.
+ @destination_changed = destination_changed?
+ @new_delivery_destination = new_delivery_destination?
process_items
try_advance
@@ -65,6 +68,15 @@ module Spree
cart.saved_change_to_preferred_stock_location_id?
end
+ # Whether the chosen delivery belongs to a place the cart no longer
+ # ships to. A market change or a corrected phone number keeps the
+ # choice, quoted again.
+ def new_delivery_destination?
+ cart.saved_change_to_ship_address_id? ||
+ cart.saved_change_to_preferred_stock_location_id? ||
+ cart.ship_address&.saved_change_to_destination? || false
+ end
+
def assign_cart_attributes
cart.email = params[:email] if params[:email].present?
cart.customer_note = params[:customer_note] if params.key?(:customer_note)
@@ -237,8 +249,8 @@ module Spree
def try_advance
return if cart.complete?
- if @address_invalidated || destination_changed?
- cart.recalculate_for_address_change!
+ if @address_invalidated || @destination_changed
+ cart.recalculate_for_address_change!(keep_selection: !@new_delivery_destination)
else
cart.recalculate_totals!
end
diff --git a/spree/core/app/services/spree/orders/build_fulfillments.rb b/spree/core/app/services/spree/orders/build_fulfillments.rb
index 518e71eade..24fb5f98a5 100644
--- a/spree/core/app/services/spree/orders/build_fulfillments.rb
+++ b/spree/core/app/services/spree/orders/build_fulfillments.rb
@@ -17,13 +17,14 @@ module Spree
class BuildFulfillments
prepend Spree::ServiceModule::Base
- def call(order:)
+ # @param keep_selection [Boolean] false when the destination changed
+ def call(order:, keep_selection: true)
return success(order) if order.completed?
return success(order) unless order.ship_address_id.present?
return success(order) unless order.line_items.any?
return success(order) unless order.delivery_step_required?
- order.rebuild_fulfillments!
+ order.rebuild_fulfillments!(keep_selection: keep_selection)
order.create_shipment_tax_charge!
order.set_fulfillments_cost
order.apply_free_shipping_promotions
diff --git a/spree/core/app/services/spree/orders/update.rb b/spree/core/app/services/spree/orders/update.rb
index 21144e94bd..824e98caa5 100644
--- a/spree/core/app/services/spree/orders/update.rb
+++ b/spree/core/app/services/spree/orders/update.rb
@@ -28,9 +28,9 @@ module Spree
process_items(items_param) if items_param
- if items_param || @order.ship_address_id != ship_address_id_before
- build_fulfillments
- end
+ # An address row edited in place keeps its id, so an edit to the fields a quote reads counts too.
+ destination_changed = @order.ship_address_id != ship_address_id_before || @order.ship_address&.saved_change_to_destination?
+ build_fulfillments(keep_selection: !destination_changed) if items_param || destination_changed
@order.recalculate_totals!
@order.update_statuses!
@@ -74,8 +74,8 @@ module Spree
propagate_step_failure!(result, fallback: 'Failed to update items on order') if result.failure?
end
- def build_fulfillments
- result = Spree::Orders::BuildFulfillments.call(order: @order)
+ def build_fulfillments(keep_selection:)
+ result = Spree::Orders::BuildFulfillments.call(order: @order, keep_selection: keep_selection)
propagate_step_failure!(result, fallback: 'Failed to build shipments') if result.failure?
end
diff --git a/spree/core/spec/models/spree/address_spec.rb b/spree/core/spec/models/spree/address_spec.rb
index 752780e6d8..4592e5e043 100644
--- a/spree/core/spec/models/spree/address_spec.rb
+++ b/spree/core/spec/models/spree/address_spec.rb
@@ -763,6 +763,20 @@ describe Spree::Address, type: :model do
end
end
+ describe '#saved_change_to_destination?' do
+ let(:address) { create(:address) }
+
+ it 'ignores a change to who receives the parcel' do
+ address.update!(phone: '555-0000', first_name: 'Other')
+ expect(address.saved_change_to_destination?).to be(false)
+ end
+
+ it 'reports a change to where the parcel goes' do
+ address.update!(address1: '5 Edited Way')
+ expect(address.saved_change_to_destination?).to be(true)
+ end
+ end
+
describe '#to_s' do
let(:address) { create(:address) }
diff --git a/spree/core/spec/models/spree/cart_spec.rb b/spree/core/spec/models/spree/cart_spec.rb
index 0752d3a90d..8467b760c6 100644
--- a/spree/core/spec/models/spree/cart_spec.rb
+++ b/spree/core/spec/models/spree/cart_spec.rb
@@ -395,6 +395,17 @@ describe Spree::Cart, type: :model do
let!(:stock_location) { Spree::StockLocation.first || create(:stock_location, country: country, state: state) }
let(:ship_address) { create(:address, country: country, state: state) }
let(:cart) { create(:cart_with_line_items, store: store, ship_address: ship_address, email: '[email protected]') }
+ let(:express) do
+ create(:shipping_method, name: 'Express').tap do |method|
+ method.calculator.preferred_amount = 15
+ method.calculator.save
+ end
+ end
+
+ def choose(delivery_method)
+ fulfillment = cart.fulfillments.reload.first
+ fulfillment.selected_delivery_rate_id = fulfillment.delivery_rates.find_by!(delivery_method: delivery_method).id
+ end
describe '#rebuild_fulfillments!' do
it 'builds cart-owned proposals from the current items and address' do
@@ -406,6 +417,39 @@ describe Spree::Cart, type: :model do
expect(cart.fulfillments.first.delivery_rates).to be_present
end
+ it 'prices each proposal at its selected rate' do
+ cart.rebuild_fulfillments!
+
+ fulfillment = cart.fulfillments.first
+ expect(fulfillment.selected_delivery_rate.cost).to eq(5)
+ expect(fulfillment.reload.cost).to eq(5)
+ end
+
+ it 'keeps the delivery method the customer chose' do
+ express
+ cart.rebuild_fulfillments!
+ choose(express)
+
+ cart.rebuild_fulfillments!
+
+ fulfillment = cart.fulfillments.first
+ expect(fulfillment.selected_delivery_rate.delivery_method).to eq(express)
+ expect(fulfillment.cost).to eq(15)
+ end
+
+ it 'falls back to the default when the chosen method is no longer offered' do
+ express
+ cart.rebuild_fulfillments!
+ choose(express)
+ express.destroy
+
+ cart.rebuild_fulfillments!
+
+ fulfillment = cart.fulfillments.first
+ expect(fulfillment.selected_delivery_rate.delivery_method).to eq(shipping_method)
+ expect(fulfillment.cost).to eq(5)
+ end
+
it 'is idempotent and never touches a completed cart' do
cart.rebuild_fulfillments!
expect { cart.rebuild_fulfillments! }.not_to change { cart.fulfillments.count }
@@ -460,6 +504,46 @@ describe Spree::Cart, type: :model do
expect(completed).not_to receive(:rebuild_fulfillments!)
completed.ensure_updated_fulfillments
end
+
+ it 'keeps the chosen delivery and its price when an item is added after the address' do
+ express
+ cart.recalculate_for_address_change!
+ choose(express)
+
+ Spree.cart_add_item_workflow.call(cart: cart, variant: cart.line_items.first.variant, quantity: 1)
+
+ expect(cart.fulfillments.reload.first.selected_delivery_rate.delivery_method).to eq(express)
+ expect(cart.reload.delivery_total).to eq(15)
+ end
+
+ context 'with a discount code applied' do
+ def apply_code_and_add_item(promotion)
+ cart.recalculate_for_address_change!
+ cart.coupon_code = promotion.code
+ Spree::PromotionHandler::Coupon.new(cart).apply
+
+ Spree.cart_add_item_workflow.call(cart: cart, variant: cart.line_items.first.variant, quantity: 1)
+ cart.reload
+ end
+
+ it 'keeps both the order discount and the delivery charge' do
+ apply_code_and_add_item(create(:promotion_with_order_adjustment, weighted_order_adjustment_amount: 10))
+
+ expect(cart.delivery_total).to eq(5)
+ expect(cart.discount_total).to eq(-10)
+ expect(cart.total).to eq(cart.item_total + 5 - 10)
+ end
+
+ # The rebuild deletes the old proposal's discount, so free shipping has
+ # to be written again against the new proposal's cost.
+ it 'keeps a free-shipping code covering the whole delivery charge' do
+ apply_code_and_add_item(create(:free_shipping_promotion))
+
+ expect(cart.delivery_total).to eq(5)
+ expect(cart.discount_total).to eq(-5)
+ expect(cart.total).to eq(cart.item_total)
+ end
+ end
end
describe '#recalculate_for_address_change!' do
@@ -471,6 +555,20 @@ describe Spree::Cart, type: :model do
expect(cart.total).to eq(cart.item_total + cart.delivery_total + cart.adjustment_total)
end
+ # A guest's address edit updates the row in place, so its id alone cannot
+ # tell a new destination from the old one.
+ it 'starts from the default rate when the address is edited in place' do
+ express
+ cart.recalculate_for_address_change!
+ choose(express)
+ cart.ship_address.update!(address1: '5 Edited Way')
+
+ cart.recalculate_for_address_change!
+
+ expect(cart.fulfillments.reload.first.selected_delivery_rate.delivery_method).to eq(shipping_method)
+ expect(cart.reload.delivery_total).to eq(5)
+ end
+
# The re-price used to be computed into memory and dropped: nothing here
# saves the line items, and the recalculation that follows resets the
# association cache. A destination change has to leave the new figure in the
diff --git a/spree/core/spec/models/spree/order/shipments_spec.rb b/spree/core/spec/models/spree/order/shipments_spec.rb
index c421cc332f..64cd611a57 100644
--- a/spree/core/spec/models/spree/order/shipments_spec.rb
+++ b/spree/core/spec/models/spree/order/shipments_spec.rb
@@ -6,17 +6,6 @@ describe Spree::Order, type: :model do
context 'ensure shipments will be updated' do
before { Spree::Shipment.create!(order: order, stock_location: create(:stock_location)) }
- it 'destroys current shipments' do
- order.ensure_updated_fulfillments
- expect(order.shipments).to be_empty
- end
-
- it 'resets shipment_total' do
- order.update_column(:shipment_total, 5)
- order.ensure_updated_fulfillments
- expect(order.shipment_total).to eq(0)
- end
-
context "except when order is completed, that's OrderInventory job" do
it "doesn't touch anything" do
allow(order).to receive_messages completed?: true
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index 2fb6b280b9..8708e0b449 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -828,20 +828,36 @@ describe Spree::Order, type: :model do
let(:order) { create(:order_with_line_items) }
context 'when order has shipments and is not completed' do
+ let(:express) do
+ create(:shipping_method, name: 'Express').tap do |method|
+ method.calculator.preferred_amount = 15
+ method.calculator.save
+ end
+ end
+
before do
+ express
order.rebuild_fulfillments!
+ fulfillment = order.fulfillments.first
+ fulfillment.selected_delivery_rate_id = fulfillment.delivery_rates.find_by!(delivery_method: express).id
end
- it 'destroys all shipments' do
- expect(order.shipments).to be_present
+ it 'rebuilds them, keeping the chosen rate and its price' do
+ previous_ids = order.fulfillments.ids
+
order.ensure_updated_fulfillments
- expect(order.reload.shipments).to be_empty
+
+ fulfillment = order.fulfillments.reload.first
+ expect(previous_ids).not_to include(fulfillment.id)
+ expect(fulfillment.selected_delivery_rate.delivery_method).to eq(express)
+ expect(fulfillment.cost).to eq(15)
end
- it 'resets shipment_total to 0' do
- order.update_column(:shipment_total, 10.0)
- order.ensure_updated_fulfillments
- expect(order.reload.shipment_total).to eq(0)
+ it 'keeps delivery when an item is added to the draft' do
+ Spree.order_add_item_service.call(order: order, variant: order.line_items.first.variant, quantity: 1)
+
+ expect(order.fulfillments.reload.first.selected_delivery_rate.delivery_method).to eq(express)
+ expect(order.reload.delivery_total).to eq(15)
end
context 'events', :events do
diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rb
index b490f1d3fe..f07ab88b5b 100644
--- a/spree/core/spec/models/spree/shipment_spec.rb
+++ b/spree/core/spec/models/spree/shipment_spec.rb
@@ -535,6 +535,40 @@ describe Spree::Shipment, type: :model do
expect(shipment.shipping_method).to eq shipping_method1
end
+ context 'carry_over_selection' do
+ let(:digital_method) { create(:shipping_method) }
+
+ def proposal(*rates)
+ Spree::Fulfillment.new(delivery_rates: rates.map { |method, cost, selected| Spree::DeliveryRate.new(delivery_method: method, cost: cost, selected: selected) })
+ end
+
+ # One stock location can ship a digital item and a physical one as two
+ # proposals, each with its own choice to keep.
+ it 'gives each proposal the earlier choice it is quoted for' do
+ physical = proposal([shipping_method1, 10, true], [shipping_method2, 20, false])
+ digital = proposal([digital_method, 0, true])
+ candidates = [Spree::DeliveryRate.new(delivery_method: digital_method, cost: 0),
+ Spree::DeliveryRate.new(delivery_method: shipping_method2, cost: 20)]
+
+ physical.carry_over_selection(candidates)
+ digital.carry_over_selection(candidates)
+
+ expect(physical.delivery_rates.find(&:selected).delivery_method).to eq(shipping_method2)
+ expect(physical.cost).to eq(20)
+ expect(digital.delivery_rates.find(&:selected).delivery_method).to eq(digital_method)
+ expect(candidates).to be_empty
+ end
+
+ it 'prices the default rate when no earlier choice fits' do
+ physical = proposal([shipping_method1, 10, true], [shipping_method2, 20, false])
+
+ physical.carry_over_selection([])
+
+ expect(physical.delivery_rates.find(&:selected).delivery_method).to eq(shipping_method1)
+ expect(physical.cost).to eq(10)
+ end
+ end
+
context 'refresh_rates' do
let(:mock_estimator) { double('estimator', delivery_rates: shipping_rates) }
diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rb
index b2131a6cda..7f3cef009a 100644
--- a/spree/core/spec/services/spree/carts/update_spec.rb
+++ b/spree/core/spec/services/spree/carts/update_spec.rb
@@ -95,6 +95,16 @@ module Spree
described_class.call(cart: cart, params: { preferred_stock_location_id: pickup_location.prefixed_id })
end
+ # Processing items reloads the cart, which forgets what the save changed.
+ it 'rebuilds delivery proposals when the pickup intent arrives with items' do
+ expect(cart).to receive(:recalculate_for_address_change!).with(keep_selection: false)
+
+ described_class.call(cart: cart, params: {
+ preferred_stock_location_id: pickup_location.prefixed_id,
+ items: [{ variant_id: cart.line_items.first.variant.prefixed_id, quantity: 2 }]
+ })
+ end
+
it 'rebuilds delivery proposals when the pickup intent is cleared' do
cart.update!(preferred_stock_location_id: pickup_location.id)
@@ -355,6 +365,76 @@ module Spree
expect(cart.reload.fulfillments).to be_present
end
end
+
+ # A guest's edit updates the address row in place, so only the
+ # fields a quote reads can tell a new destination from a correction.
+ context 'when a guest who chose a rate edits the address' do
+ let!(:standard) { create(:shipping_method, name: 'Standard', store: store).tap { |method| method.calculator.update!(preferred_amount: 5) } }
+ let!(:express) { create(:shipping_method, name: 'Express', store: store).tap { |method| method.calculator.update!(preferred_amount: 15) } }
+ let(:cart) do
+ create(:cart_with_line_items, store: store, customer: nil, email: '[email protected]',
+ ship_address: create(:address, country: country, state: state),
+ bill_address: create(:address, country: country, state: state))
+ end
+ let(:edited_address) do
+ cart.ship_address.attributes.slice(*%w[first_name last_name address1 city postal_code country_code state_code phone]).symbolize_keys
+ end
+
+ before do
+ cart.recalculate_for_address_change!
+ fulfillment = cart.fulfillments.reload.first
+ fulfillment.selected_delivery_rate_id = fulfillment.delivery_rates.find_by!(delivery_method: express).id
+ cart.reload
+ end
+
+ context 'with only the phone number corrected' do
+ let(:params) { { shipping_address: edited_address.merge(phone: '555-0000') } }
+
+ it 'keeps the chosen rate' do
+ address_id = cart.ship_address_id
+
+ expect(subject).to be_success
+
+ cart.reload
+ expect(cart.ship_address_id).to eq(address_id)
+ expect(cart.fulfillments.first.selected_delivery_rate.delivery_method).to eq(express)
+ expect(cart.delivery_total).to eq(15)
+ end
+ end
+
+ context 'with the street changed' do
+ let(:params) { { shipping_address: edited_address.merge(address1: '5 Edited Way') } }
+
+ it 'starts from the default rate' do
+ address_id = cart.ship_address_id
+
+ expect(subject).to be_success
+
+ cart.reload
+ expect(cart.ship_address_id).to eq(address_id)
+ expect(cart.fulfillments.first.selected_delivery_rate.delivery_method).to eq(standard)
+ expect(cart.delivery_total).to eq(5)
+ end
+ end
+
+ context 'with the street changed and an item added in the same request' do
+ let(:params) do
+ {
+ shipping_address: edited_address.merge(address1: '5 Edited Way'),
+ items: [{ variant_id: cart.line_items.first.variant.prefixed_id, quantity: 2 }]
+ }
+ end
+
+ it 'starts from the default rate' do
+ expect(subject).to be_success
+
+ cart.reload
+ expect(cart.line_items.first.quantity).to eq(2)
+ expect(cart.fulfillments.first.selected_delivery_rate.delivery_method).to eq(standard)
+ expect(cart.delivery_total).to eq(5)
+ end
+ end
+ end
end
context 'with top-level shipping_address_id' do
diff --git a/spree/core/spec/services/spree/orders/update_spec.rb b/spree/core/spec/services/spree/orders/update_spec.rb
index 6cc802f7e5..8ea3e23732 100644
--- a/spree/core/spec/services/spree/orders/update_spec.rb
+++ b/spree/core/spec/services/spree/orders/update_spec.rb
@@ -207,6 +207,60 @@ module Spree
end
end
+ context 'when an admin chose a rate' do
+ let(:initial_address) { create(:address, customer: user, country: country, state: state) }
+ let!(:express) do
+ create(:shipping_method, name: 'Express').tap do |method|
+ method.calculator.preferred_amount = 15
+ method.calculator.save
+ end
+ end
+
+ before do
+ fulfillment = order.fulfillments.first
+ fulfillment.selected_delivery_rate_id = fulfillment.delivery_rates.find_by!(delivery_method: express).id
+ end
+
+ context 'and items change' do
+ let(:params) { { items: [{ variant_id: variant.prefixed_id, quantity: 3 }] } }
+
+ it 'keeps the chosen rate at its price' do
+ expect(subject).to be_success
+
+ expect(order.reload.fulfillments.first.selected_delivery_rate.delivery_method).to eq(express)
+ expect(order.delivery_total).to eq(15)
+ end
+ end
+
+ # An address edited in place keeps its id, yet it is a new destination.
+ context 'and the shipping address is edited in place' do
+ let(:params) { { shipping_address: { id: initial_address.id, address1: '5 Edited Way' } } }
+
+ it 'rebuilds from the default rate' do
+ expect(subject).to be_success
+
+ order.reload
+ expect(order.ship_address_id).to eq(initial_address.id)
+ expect(order.ship_address.address1).to eq('5 Edited Way')
+ expect(order.fulfillments.first.selected_delivery_rate.delivery_method).to eq(shipping_method)
+ expect(order.delivery_total).to eq(5)
+ end
+ end
+
+ context 'and only the recipient phone is edited' do
+ let(:params) { { shipping_address: { id: initial_address.id, phone: '555-0000' } } }
+
+ it 'keeps the chosen rate' do
+ expect(subject).to be_success
+
+ order.reload
+ expect(order.ship_address.phone).to eq('555-0000')
+ expect(order.fulfillments.first.selected_delivery_rate.delivery_method).to eq(express)
+ expect(order.delivery_total).to eq(15)
+ end
+ end
+ end
+
# The admin controller sends the public names; the column names and the
# Rails nested-attributes key stay accepted for existing callers.
%i[shipping_address ship_address ship_address_attributes].each do |key|