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: bounded exchanges by returnable units and credited only what came back
Damian Legawiec49b08b1bf962
diff --git a/spree/core/app/workflows/spree/exchanges/create.rb b/spree/core/app/workflows/spree/exchanges/create.rbindex 965b8c2ab8..88c5ab74a0 100644--- a/spree/core/app/workflows/spree/exchanges/create.rb+++ b/spree/core/app/workflows/spree/exchanges/create.rb@@ -3,6 +3,8 @@ module Spree# Opens an exchange request: items coming back, and what should go out# in their place.class Create < Spree::Workflow+ include Spree::Returns::ReturnableQuantity+hooks :validate, :after_createattr_reader :exchange@@ -55,6 +57,10 @@ module Spree{ fulfillment_item: fulfillment_item, new_variant: new_variant, quantity: quantity }end++ # The credit an exchange pays out is priced on these quantities, so+ # they can never exceed what was shipped and not yet sent back.+ ensure_returnable_quantities(@normalized_items, action: 'exchanged')enddef build_exchangediff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rbindex bccdb441e6..bd67cc0fd8 100644--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb@@ -51,11 +51,23 @@ module Spree# Negative price difference means the replacements cost less than what# came back, so the customer is owed the difference.def credit_due?- exchange.price_difference.to_d.negative?+ settled_difference.negative?enddef credit_amount- exchange.price_difference.to_d.abs+ settled_difference.abs+ end++ # The difference on the units that actually came back — the same units+ # the replacements are shipped for. Priced on the requested quantity, an+ # exchange that asked for more than arrived would pay credit for goods+ # nobody returned.+ def settled_difference+ @settled_difference ||= exchange.exchange_line_items.sum(0.to_d) do |line|+ next 0.to_d if line.quantity.to_i.zero?++ line.price_difference.to_d / line.quantity.to_i * line.received_quantity.to_i+ endenddef ensure_fulfillablediff --git a/spree/core/app/workflows/spree/returns/create.rb b/spree/core/app/workflows/spree/returns/create.rbindex 8db0c852bd..dbefe3b0a3 100644--- a/spree/core/app/workflows/spree/returns/create.rb+++ b/spree/core/app/workflows/spree/returns/create.rb@@ -7,6 +7,8 @@ module Spree# regional consumer rights. That policy is the most-customized rule in# commerce and deliberately does not live in core.class Create < Spree::Workflow+ include Spree::Returns::ReturnableQuantity+hooks :validate, :after_create# The created return — hook handlers read it (nil while :validate runs).@@ -48,7 +50,7 @@ module Spreeend# Quantities are validated against what is actually still returnable —- # units already returned on an earlier request must not come back twice.+ # units already returned or exchanged must not come back twice.def normalize_items@normalized_items = items.map do |item|fulfillment_item = item[:fulfillment_item]@@ -57,23 +59,10 @@ module Spreefailure(order, :invalid_quantity) unless quantity.positive?failure(order, :item_not_on_order) unless fulfillment_item&.order_id == order.id- available = returnable_quantity_for(fulfillment_item)- if quantity > available- failure(order, "Only #{available} of #{fulfillment_item.variant.name} can be returned")- end-{ fulfillment_item: fulfillment_item, quantity: quantity }end- end-- def returnable_quantity_for(fulfillment_item)- already_requested = Spree::ReturnLineItem.- joins(:return).- where(fulfillment_item_id: fulfillment_item.id).- where.not(spree_returns: { status: 'canceled' }).- sum(:quantity)- fulfillment_item.quantity.to_i - already_requested+ ensure_returnable_quantities(@normalized_items, action: 'returned')enddef build_returndiff --git a/spree/core/app/workflows/spree/returns/returnable_quantity.rb b/spree/core/app/workflows/spree/returns/returnable_quantity.rbnew file mode 100644index 0000000000..85a774f21c--- /dev/null+++ b/spree/core/app/workflows/spree/returns/returnable_quantity.rb@@ -0,0 +1,53 @@+module Spree+ module Returns+ # How many units of a shipped item can still go back.+ #+ # A return and an exchange both take the same units off the customer, so+ # each counts the other: without that, the units a customer returned could+ # be exchanged again, and the credit for the exchange paid out a second+ # time. Units named twice in one request count twice too.+ module ReturnableQuantity+ extend ActiveSupport::Concern++ private++ # @param fulfillment_item [Spree::FulfillmentItem]+ # @param requested [Hash{Integer => Integer}] units already asked for in+ # this request, keyed by fulfillment item id+ # @return [Integer]+ def returnable_quantity_for(fulfillment_item, requested: {})+ returned = Spree::ReturnLineItem.+ joins(:return).+ where(fulfillment_item_id: fulfillment_item.id).+ where.not(Spree::Return.table_name => { status: 'canceled' }).+ sum(:quantity)+ exchanged = Spree::ExchangeLineItem.+ joins(:exchange).+ where(fulfillment_item_id: fulfillment_item.id).+ where.not(Spree::Exchange.table_name => { status: 'canceled' }).+ sum(:quantity)++ fulfillment_item.quantity.to_i - returned - exchanged - requested.fetch(fulfillment_item.id, 0)+ end++ # Checks each item's quantity against what is still returnable and+ # fails with the item's name when it is not.+ #+ # @param items [Array<Hash>] `[{ fulfillment_item:, quantity: }]`+ # @param action [String] 'returned' or 'exchanged', for the message+ def ensure_returnable_quantities(items, action:)+ requested = Hash.new(0)++ items.each do |item|+ fulfillment_item = item[:fulfillment_item]+ available = returnable_quantity_for(fulfillment_item, requested: requested)+ if item[:quantity] > available+ failure(order, "Only #{[available, 0].max} of #{fulfillment_item.variant.name} can be #{action}")+ end++ requested[fulfillment_item.id] += item[:quantity]+ end+ end+ end+ end+enddiff --git a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rbindex fe17f481ad..3097061a35 100644--- a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb@@ -26,6 +26,30 @@ RSpec.describe 'Spree::Exchanges workflows' doexpect(result.value.exchange_line_items.count).to eq(1)end+ # The credit an exchange pays is priced on its quantity, so a quantity+ # above what shipped would pay for goods nobody bought.+ it 'refuses more units than were shipped' do+ result = Spree::Exchanges::Create.call(+ order: order,+ items: [{ fulfillment_item: fulfillment_item, new_variant: replacement, quantity: fulfillment_item.quantity + 1 }]+ )++ expect(result).to be_failure+ expect(order.reload.exchanges).to be_empty+ end++ it 'refuses units that were already returned' do+ Spree::Returns::Create.call(order: order, items: [{ fulfillment_item: fulfillment_item, quantity: fulfillment_item.quantity }])++ expect(create_exchange).to be_failure+ end++ it 'refuses a single request naming the same units twice' do+ item = { fulfillment_item: fulfillment_item, new_variant: replacement, quantity: fulfillment_item.quantity }++ expect(Spree::Exchanges::Create.call(order: order, items: [item, item])).to be_failure+ end+it 'refuses a replacement that cannot be sold' doallow_any_instance_of(Spree::Variant).to receive(:purchasable?).and_return(false)@@ -139,6 +163,17 @@ RSpec.describe 'Spree::Exchanges workflows' doexpect(result.error.value[:base].join).to include('original_payment')end+ # Only the units that came back are replaced, so only they are credited.+ it 'credits only the units that were received' do+ line = cheap_exchange.exchange_line_items.first+ line.update_columns(quantity: 2, received_quantity: 1)+ per_unit = (line.line_item.amount / line.line_item.quantity) - line.new_variant.price_in(line.currency).amount++ Spree::Exchanges::Fulfill.call(exchange: cheap_exchange, refund_method: 'store_credit')++ expect(Spree::StoreCredit.find_by(originator: cheap_exchange).amount).to eq(per_unit)+ end+it 'accepts store credit' doresult = Spree::Exchanges::Fulfill.call(exchange: cheap_exchange, refund_method: 'store_credit')