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: changing the quantity of an exchanged line deletes its original fulfillment (#14752)
Łukasz Adamczyk169d4941b0be
diff --git a/docs/developer/core-concepts/returns-exchanges-claims.mdx b/docs/developer/core-concepts/returns-exchanges-claims.mdxindex af5ebb1272..681f23283f 100644--- a/docs/developer/core-concepts/returns-exchanges-claims.mdx+++ b/docs/developer/core-concepts/returns-exchanges-claims.mdx@@ -199,6 +199,8 @@ curl -X PATCH 'https://api.mystore.com/api/v3/admin/orders/or_xxx/claims/claim_xA replacement creates a new [fulfillment](/developer/core-concepts/fulfillments) on the original order, so the customer doesn't have to place a second one.+The replacement is filed under the order line it replaces, but it doesn't count toward that line's quantity. Editing the line later, from a claim or an [exchange](#exchanges), adds or removes only the goods the customer paid for and leaves the replacement where it is.+## ExchangesAn exchange works like a return, but ends by sending different items instead of refunding:diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.mdindex 5dd27f5a80..aebfa11da2 100644--- a/docs/plans/6.0-returns-exchanges-claims.md+++ b/docs/plans/6.0-returns-exchanges-claims.md@@ -446,6 +446,13 @@ fulfillment items on the order and routes them throughfulfillments; they attach to the order like any other. Only the money records(`Refund`, `StoreCredit`) carry the `originator` back-reference.+Replacement units are flagged `spree_fulfillment_items.replacement`+(2026-09-25). They hang off the line they replace, and an edit of that line+counts only the unflagged units, so the replacement is neither counted toward+the quantity nor removed when it falls. `Exchanges::Fulfill` and+`Claims::Resolve` both build replacements through+`Spree::Fulfillments::Replacements`.+Restocking and replacement-fulfillment creation live in`Spree::Exchanges::Receive` and `Spree::Exchanges::Fulfill`. A credit due backis settled through the internal-vs-gateway branch (see "Refunding: internal vs@@ -858,7 +865,10 @@ rename (+ `ClaimReason`), `Spree::Metafields` on all three entities, and theremoval of the return-specific methods on `FulfillmentItem`(`current_or_new_return_item`, `current_return_item`, `exchanged_unit?`, andthe `original_return_item` association — `required_quantity` survives for-`Stock::Adjuster` with its exchange branch collapsed).+`Stock::Adjuster` with its exchange branch collapsed). The removal left+replacement units indistinguishable from bought ones; the `replacement` flag+(2026-09-25) restores that one distinction, and nothing else of the old+exchanged-unit API.### Phase 3b: Workflows — SHIPPEDdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex ffe5d01124..7940dfe9f9 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,15 @@+## 2026-09-25: Replacement units are flagged, so an order edit counts only what was bought++**Context:** Raising the quantity of an exchanged line on a placed order deleted the line's original fulfillment and its delivery charge (V-3707). Reproduced on `main`: order R1001, one Stainless kettle at $79.99 plus $5.00 Standard delivery, exchanged for Matte Black; raising the line to 2 answered 200, deleted the $5.00 fulfillment with its Stainless unit, took `delivery_total` from 5.0 to 0.0, and released the Stainless allocation instead of adding one. There were two causes. `Exchanges::Fulfill` and `Claims::Resolve` built their replacement units through `order.fulfillment_items.new`; the stock coordinator packs a copy of each, and the order's next save persisted the original as well, so every replacement left a second unit on the line with no fulfillment. `Spree::OrderInventory#verify` then counted every unit on the line against its quantity, found three units for a quantity of two, and removed the one it could reach, the original. With the stray unit gone the edit still added nothing, because the replacement counted as a unit the line already held. The 6.0 returns rebuild had removed `exchanged_unit?` and `original_return_item`, so nothing told a replacement apart from a unit the customer bought.++**Decision:** `spree_fulfillment_items` gains `replacement`, a boolean defaulting to false, set on every unit an exchange or claim sends. `OrderInventory#verify` leaves flagged units out of the count and out of the units it removes when the quantity falls, so an edit only ever adds or removes goods the customer paid for. A line being destroyed still counts and drains its replacements as it did before, so the stock promise on a same-variant replacement is released rather than left with nothing to cancel. Both workflows build their replacements through one `Spree::Fulfillments::Replacements` module, which builds the units by id rather than through the association writers: with `has_many_inversing`, each writer adds the unit to its owner's collection, and that owner's next save persists it. `Fulfillments::Create` and `FulfillmentChanger`, the two paths that rebuild units when a fulfillment is split or moved, carry the flag across. The changer takes it from the first unit it moves, the same way it already takes the line.++Rejected: counting only units of the line's own variant. It needs no migration and fixes exchanges, where a replacement is always a different variant, but a claim often sends the same variant again, and that replacement would still count. Rejected: fixing only the stray unit, which stops the deletion but leaves the raise adding nothing.++**Consequences:** Raising the line from 1 to 2 now keeps the original fulfillment and its $5.00, adds one Stainless unit and one Stainless allocation, and brings the total to $164.98. No data repair ships: replacement units already fulfilled on a beta install stay unflagged, and their stray duplicates stay behind, so an edit of those lines still misbehaves. The order still reads `paid` after the edit raises its total; that is V-3638. Left alone, all pre-existing: `OrderInventory#add_to_shipment` rebuilds every fulfillment on the order when no open fulfillment can take the unit, which on a placed order is what `Orders::BuildFulfillments` refuses to do. `#determine_target_fulfillment` can put a raised unit into a pending replacement fulfillment, which carries no delivery charge. Removing a line drains only units of the line's own variant, so an exchange replacement's stock promise outlives the line. `FulfillmentChanger` merges the units it moves by variant alone, so a fulfillment mixing bought and replacement units of one variant can come out with the wrong flag, as it can already come out with the wrong line. `Stock::Packer#default_package` keeps one unit per variant, so two replacements of the same variant for different lines fail as out of stock. An exchange accepts units that never shipped, then restocks them on receipt while the original fulfillment still holds them.++**Plans amended:** `6.0-returns-exchanges-claims.md` (the Exchange section's replacement-fulfillment note, the Phase 3 note on the removed exchanged-unit API).+## 2026-09-25: A free gift does not count toward what other promotions measure**Context:** The 2026-09-23 fix left the gift at its list price on its line and paid for it with a discount. Everything that measures the cart for promotions sums list prices, so the gift counted in full: 2 x $49.99 of paid goods plus a $49.99 gift passed a "spend over $100, 10% off" promotion, which took $15.00 and left the shopper paying $84.98 where $99.98 was owed, and with three paid units the 10% came to $20.00 instead of $15.00 (V-3710). A gift promotion with its own spend threshold was worse: its gift kept the cart over the threshold after the shopper dropped below it, so the same one-kettle cart cost $49.00 after starting at two and $60.00 when built fresh.diff --git a/spree/core/app/models/spree/fulfillment_changer.rb b/spree/core/app/models/spree/fulfillment_changer.rbindex 21b696dd7e..fd402341e1 100644--- a/spree/core/app/models/spree/fulfillment_changer.rb+++ b/spree/core/app/models/spree/fulfillment_changer.rb@@ -106,8 +106,8 @@ module Spreeenddef get_desired_shipment_inventory_unit(state)- desired_shipment.fulfillment_items.find_or_create_by(status: state, variant: variant) do |unit|- current_shipment_unit = current_shipment_units.first+ current_shipment_unit = current_shipment_units.first+ desired_shipment.fulfillment_items.find_or_create_by(status: state, variant: variant, replacement: current_shipment_unit&.replacement || false) do |unit|unit.variant_id = current_shipment_unit.variant_idunit.order_id = current_shipment_unit.order_idunit.line_item_id = current_shipment_unit.line_item_iddiff --git a/spree/core/app/models/spree/order_inventory.rb b/spree/core/app/models/spree/order_inventory.rbindex 4e7dd1c534..469352abfb 100644--- a/spree/core/app/models/spree/order_inventory.rb+++ b/spree/core/app/models/spree/order_inventory.rb@@ -26,7 +26,10 @@ module Spreedef verify(shipment = nil, is_updated: false, removing: false)return unless order.completed? || shipment.present?- units_count = fulfillment_items.reload.sum(&:quantity)+ # A replacement sent by an exchange or claim stands in for a unit the+ # quantity already paid for, so only a line being destroyed counts it.+ units = fulfillment_items.reload+ units_count = (removing ? units : units.reject(&:replacement?)).sum(&:quantity)line_item_changed = is_updated ? !line_item.saved_changes? : !line_item.changed?if removing@@ -67,12 +70,12 @@ module Spreedef remove_all_units(quantity, target_fulfillment = nil)if target_fulfillment.present?- remove_from_shipment(target_fulfillment, quantity)+ remove_from_shipment(target_fulfillment, quantity, include_replacements: true)elseorder.fulfillments.each do |shipment|break if quantity.zero?- quantity -= remove_from_shipment(shipment, quantity)+ quantity -= remove_from_shipment(shipment, quantity, include_replacements: true)endendend@@ -120,10 +123,12 @@ module Spreequantityend- def remove_from_shipment(shipment, quantity)+ def remove_from_shipment(shipment, quantity, include_replacements: false)return 0 if quantity.zero? || shipment.fulfilled?- shipment_units = shipment.inventory_units_for_item(line_item, variant).reject(&:shipped?).sort_by(&:status)+ shipment_units = shipment.inventory_units_for_item(line_item, variant).reject do |unit|+ unit.shipped? || (unit.replacement? && !include_replacements)+ end.sort_by(&:status)removed_quantity = 0removed_backordered = 0diff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rbindex 78627f62b0..ac151198ad 100644--- a/spree/core/app/workflows/spree/claims/resolve.rb+++ b/spree/core/app/workflows/spree/claims/resolve.rb@@ -7,6 +7,7 @@ module Spree# decide at resolution time rather than at claim creation.class Resolve < Spree::Workflowinclude Spree::Refunds::OrderPayments+ include Spree::Fulfillments::Replacementshooks :validate, :before_settle, :after_resolve@@ -96,37 +97,13 @@ module Spreeenddef build_replacement_fulfillments- units = claim.replacement_line_items.map do |line|- claim.order.fulfillment_items.new(- variant: line.variant_to_send,- quantity: line.quantity,- line_item: line.line_item,- order: claim.order,- status: 'on_hand'- )+ items = claim.replacement_line_items.map do |line|+ { variant: line.variant_to_send, quantity: line.quantity, line_item: line.line_item }end- failure(claim, :nothing_to_replace) if units.empty?+ failure(claim, :nothing_to_replace) if items.empty?- @fulfillments = Spree::Stock::Coordinator.new(claim.order, units).fulfillments- if @fulfillments.flat_map(&:fulfillment_items).sum(&:quantity) != units.sum(&:quantity)- failure(claim, :replacement_out_of_stock)- end-- claim.order.fulfillments += @fulfillments- claim.order.save!- @fulfillments.each { |fulfillment| allocate_replacement_stock(fulfillment) }- end-- # See Spree::Exchanges::Fulfill — a replacement that holds no promise- # ships without writing a movement, so the shelf never follows the goods.- def allocate_replacement_stock(fulfillment)- fulfillment.manifest.each do |item|- next unless item.variant.track_inventory?- next unless item.quantity.positive?-- fulfillment.stock_location.allocate(item.variant, item.quantity, fulfillment)- end+ @fulfillments = build_replacements(claim, items)enddef issue_store_creditdiff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rbindex bd67cc0fd8..f79949f9b4 100644--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb@@ -9,6 +9,7 @@ module Spree# authorization is not something core should do silently.class Fulfill < Spree::Workflowinclude Spree::Refunds::OrderPayments+ include Spree::Fulfillments::Replacementshooks :validate, :before_settle, :after_fulfill@@ -85,42 +86,15 @@ module Spree# Only lines that actually came back are replaced — a customer who# returned two of three items gets two replacements.def build_replacement_fulfillments- units = exchange.exchange_line_items.filter_map do |line|+ items = exchange.exchange_line_items.filter_map do |line|next if line.received_quantity.to_i.zero?- exchange.order.fulfillment_items.new(- variant: line.new_variant,- quantity: line.received_quantity,- line_item: line.line_item,- order: exchange.order,- status: 'on_hand'- )+ { variant: line.new_variant, quantity: line.received_quantity, line_item: line.line_item }end- failure(exchange, :nothing_to_fulfill) if units.empty?+ failure(exchange, :nothing_to_fulfill) if items.empty?- @fulfillments = Spree::Stock::Coordinator.new(exchange.order, units).fulfillments- if @fulfillments.flat_map(&:fulfillment_items).sum(&:quantity) != units.sum(&:quantity)- failure(exchange, :replacement_out_of_stock)- end-- exchange.order.fulfillments += @fulfillments- exchange.order.save!- @fulfillments.each { |fulfillment| allocate_replacement_stock(fulfillment) }- end-- # The replacement is promised the moment it exists, exactly as placement- # promises an order's own fulfillments. Without this the fulfillment holds- # nothing, and dispatch then writes no movement at all — an unallocated- # fulfillment is indistinguishable from one created before typed- # movements, so the goods would leave the shelf untouched and unrecorded.- def allocate_replacement_stock(fulfillment)- fulfillment.manifest.each do |item|- next unless item.variant.track_inventory?- next unless item.quantity.positive?-- fulfillment.stock_location.allocate(item.variant, item.quantity, fulfillment)- end+ @fulfillments = build_replacements(exchange, items)enddef issue_store_creditdiff --git a/spree/core/app/workflows/spree/fulfillments/create.rb b/spree/core/app/workflows/spree/fulfillments/create.rbindex dd3805f371..935e5f7f57 100644--- a/spree/core/app/workflows/spree/fulfillments/create.rb+++ b/spree/core/app/workflows/spree/fulfillments/create.rb@@ -231,7 +231,8 @@ module Spreestatus: unit.status,variant_id: unit.variant_id,line_item_id: unit.line_item_id,- order_id: order.id+ order_id: order.id,+ replacement: unit.replacement)target.pending = unit.pending# The quantity column has a database default of 1, so a freshdiff --git a/spree/core/app/workflows/spree/fulfillments/replacements.rb b/spree/core/app/workflows/spree/fulfillments/replacements.rbnew file mode 100644index 0000000000..6293e3b1ec--- /dev/null+++ b/spree/core/app/workflows/spree/fulfillments/replacements.rb@@ -0,0 +1,59 @@+# frozen_string_literal: true++module Spree+ module Fulfillments+ # Sends replacement goods for an exchange or a claim.+ #+ # Replacement units hang off the line they replace but are flagged, so an+ # edit of that line counts only what the customer bought — otherwise the+ # replacement reads as a unit the line already holds, and raising the+ # quantity adds nothing.+ module Replacements+ extend ActiveSupport::Concern++ private++ def build_replacements(record, items)+ order = record.order++ # By id, not through the association writers: with has_many inversing+ # each writer adds the template to its owner's collection, and the+ # owner's next save persists it beside the packed copy.+ units = items.map do |item|+ Spree::FulfillmentItem.new(+ order_id: order.id,+ line_item_id: item[:line_item].id,+ variant_id: item[:variant].id,+ quantity: item[:quantity],+ status: 'on_hand',+ replacement: true+ )+ end++ fulfillments = Spree::Stock::Coordinator.new(order, units).fulfillments+ if fulfillments.flat_map(&:fulfillment_items).sum(&:quantity) != units.sum(&:quantity)+ failure(record, :replacement_out_of_stock)+ end++ order.fulfillments += fulfillments+ order.save!+ fulfillments.each { |fulfillment| allocate_replacement_stock(fulfillment) }+ fulfillments+ end++ # The replacement is promised the moment it exists, exactly as placement+ # promises an order's own fulfillments. Without this the fulfillment holds+ # nothing, and dispatch then writes no movement at all — an unallocated+ # fulfillment is indistinguishable from one created before typed+ # movements, so the goods would leave the shelf untouched and unrecorded.+ def allocate_replacement_stock(fulfillment)+ fulfillment.manifest.each do |item|+ next unless item.variant.track_inventory?+ next unless item.quantity.positive?++ fulfillment.stock_location.allocate(item.variant, item.quantity, fulfillment)+ end+ end+ end+ end+enddiff --git a/spree/core/db/migrate/20260925000001_add_replacement_to_spree_fulfillment_items.rb b/spree/core/db/migrate/20260925000001_add_replacement_to_spree_fulfillment_items.rbnew file mode 100644index 0000000000..693b0828f6--- /dev/null+++ b/spree/core/db/migrate/20260925000001_add_replacement_to_spree_fulfillment_items.rb@@ -0,0 +1,5 @@+class AddReplacementToSpreeFulfillmentItems < ActiveRecord::Migration[8.1]+ def change+ add_column :spree_fulfillment_items, :replacement, :boolean, default: false, null: false+ end+enddiff --git a/spree/core/spec/models/spree/order_inventory_spec.rb b/spree/core/spec/models/spree/order_inventory_spec.rbindex 8c642b36b9..509050cc7f 100644--- a/spree/core/spec/models/spree/order_inventory_spec.rb+++ b/spree/core/spec/models/spree/order_inventory_spec.rb@@ -130,6 +130,31 @@ describe Spree::OrderInventory, type: :model doendend+ # What a claim sends is often the same variant as what was bought, so only+ # the flag tells the two apart.+ context 'when the line holds a replacement unit' do+ let(:shipment) { order.fulfillments.first }++ before do+ line_item.update!(quantity: 2)+ create(:fulfillment_item, fulfillment: shipment, variant: line_item.variant, line_item: line_item, order: order, replacement: true)+ end++ it 'does not count the replacement toward the quantity' do+ line_item.update!(quantity: 3)++ expect(line_item.fulfillment_items.reload.reject(&:replacement?).sum(&:quantity)).to eq(3)+ end++ it 'keeps the replacement when the quantity falls' do+ line_item.update!(quantity: 1)++ units = line_item.fulfillment_items.reload+ expect(units.reject(&:replacement?).sum(&:quantity)).to eq(1)+ expect(units.select(&:replacement?).sum(&:quantity)).to eq(1)+ end+ end+context 'when order has too many inventory units' dobefore doline_item.quantity = 3diff --git a/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rbindex 89833c069d..8c0d21ab8a 100644--- a/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb@@ -174,6 +174,9 @@ RSpec.describe 'Spree::Claims workflows' doexpect(result).to be_successexpect(result.value).to be_resolved+ # Flagged, and packed once — not also saved loose beside the packed copy.+ expect(order.fulfillment_items.reload.where(replacement: true).sum(:quantity)).to eq(claim.claim_line_items.sum(:quantity))+ expect(order.fulfillment_items.where(fulfillment_id: nil)).to be_emptyendenddiff --git a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rbindex 3097061a35..52434c44b7 100644--- a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb@@ -144,6 +144,37 @@ RSpec.describe 'Spree::Exchanges workflows' doexpect(replacement.stock_movements.allocated.sum(:quantity)).to eq(1)end+ # The coordinator packs a copy of each unit it is handed, so the unit+ # handed to it must not be saved as well.+ it 'flags the replacement and leaves no unit outside a fulfillment' do+ line = exchange.exchange_line_items.first+ line.new_variant.stock_levels.first&.set_count_on_hand(10)++ Spree::Exchanges::Fulfill.call(exchange: exchange)+ units = exchange.order.fulfillment_items.reload.where(variant: line.new_variant)++ expect(units.sum(:quantity)).to eq(1)+ expect(units).to all(have_attributes(replacement: true, fulfillment_id: be_present))+ end++ it 'adds a unit when the exchanged line is raised afterwards' do+ line = exchange.exchange_line_items.first+ line_item = line.line_item+ [line.new_variant, line_item.variant].each { |variant| variant.stock_levels.first&.set_count_on_hand(10) }+ Spree::Exchanges::Fulfill.call(exchange: exchange)+ original_fulfillments = exchange.order.fulfillments.reload.to_a+ quantity = line_item.reload.quantity + 1++ result = Spree::Orders::Update.call(+ order: exchange.order.reload,+ params: { items: [{ variant_id: line_item.variant_id, quantity: quantity }] }+ )++ expect(result).to be_success+ expect(line_item.fulfillment_items.reload.reject(&:replacement?).sum(&:quantity)).to eq(quantity)+ expect(exchange.order.fulfillments.reload).to include(*original_fulfillments)+ end+# The guard only matters when money moves: a cheaper replacement owes the# customer the difference, and an unrecognised method would otherwise fall# through to the gateway instead of store credit.