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: Returns clawed back more than the returned units earned

Łukasz Adamczyk24835f347e4a
diff --git a/spree/core/app/models/spree/claim.rb b/spree/core/app/models/spree/claim.rb
index 46499d108b..716f2d36b7 100644
--- a/spree/core/app/models/spree/claim.rb
+++ b/spree/core/app/models/spree/claim.rb
@@ -47,6 +47,16 @@ module Spree
claim_line_items.sum(&:refund_amount)
end
+ # What a refund from this claim paid for, line by line — each line already
+ # carries the amount agreed for it.
+ #
+ # @return [Hash{Integer => BigDecimal}] line item id => amount
+ def refunded_line_amounts
+ claim_line_items.each_with_object(Hash.new(0)) do |line, amounts|
+ amounts[line.line_item_id] += line.refund_amount.to_d
+ end
+ end
+
def display_refund_total
Spree::Money.new(refund_total, currency: currency)
end
diff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rb
index d78bd99f65..39150688c8 100644
--- a/spree/core/app/models/spree/refund.rb
+++ b/spree/core/app/models/spree/refund.rb
@@ -63,6 +63,18 @@ module Spree
originator.return_line_items.to_a
end
+ # What this refund paid for, line by line, when whatever caused it can say.
+ # Empty for a manual refund or a cancellation, which name no originator, and
+ # for an exchange, whose credit is a net price difference across the swap
+ # rather than the value of the units that came back.
+ #
+ # @return [Hash{Integer => BigDecimal}] line item id => amount
+ def refunded_line_amounts
+ return {} unless originator.respond_to?(:refunded_line_amounts)
+
+ originator.refunded_line_amounts
+ end
+
# Returns true if the refund is editable.
#
# Read through the refund's own order: a payment shared by a split checkout
diff --git a/spree/core/app/models/spree/return.rb b/spree/core/app/models/spree/return.rb
index 1649b33f52..179e7c97e5 100644
--- a/spree/core/app/models/spree/return.rb
+++ b/spree/core/app/models/spree/return.rb
@@ -115,6 +115,19 @@ module Spree
return_line_items.sum(&:pre_tax_amount)
end
+ # What a refund from this return paid for, line by line. Counts what the
+ # warehouse received rather than what the customer announced, so it agrees
+ # with the amount {Spree::Returns::Refund} works out for itself.
+ #
+ # @return [Hash{Integer => BigDecimal}] line item id => amount
+ def refunded_line_amounts
+ return_line_items.each_with_object(Hash.new(0)) do |line, amounts|
+ next if line.quantity.to_i.zero? || line.received_quantity.to_i.zero?
+
+ amounts[line.line_item_id] += (line.pre_tax_amount / line.quantity) * line.received_quantity.to_i
+ end
+ end
+
# What has actually been refunded so far — a return can be refunded in
# more than one step (part to store credit, part to the card), and store
# credit is its own ledger rather than a Spree::Refund row.
diff --git a/spree/core/app/workflows/spree/seller_transfers/reverse.rb b/spree/core/app/workflows/spree/seller_transfers/reverse.rb
index e1814dcb99..9805e740c0 100644
--- a/spree/core/app/workflows/spree/seller_transfers/reverse.rb
+++ b/spree/core/app/workflows/spree/seller_transfers/reverse.rb
@@ -75,16 +75,76 @@ module Spree
# A refund is the customer's gross figure — it carries the tax and the
# marketplace's commission, while the seller only ever received their net
# cut. Taking the gross back would charge them the commission on goods
- # that came back, so it is scaled by what the order earned them against
- # what the customer paid. A full refund still nets to the whole earning.
+ # that came back, so what comes back is always the seller's share of it.
+ #
+ # Which share depends on what the refund can say about itself. A return or
+ # a claim names the lines it paid for, and those lines earned a knowable
+ # amount. Anything else — a manual refund, a cancellation — is only an
+ # amount against an order, and the order's own ratio is the best available
+ # answer.
def seller_share_of(refunded)
+ attributed_share(refunded) || blended_share(refunded)
+ end
+
+ # What the named lines actually earned, scaled to what this refund paid.
+ #
+ # The scaling is not a refinement: one return is refunded once per payment
+ # it draws on, and every one of those refunds names the same lines. Taking
+ # them at face value would claw the same units back once per payment.
+ # Scaling also absorbs an operator who refunded a different amount than the
+ # lines are worth — a restocking fee, or goodwill on top.
+ #
+ # Nil when the refund names nothing, which sends the caller to the blend.
+ def attributed_share(refunded)
+ amounts = refund&.refunded_line_amounts
+ return if amounts.blank?
+
+ gross = amounts.values.sum.to_d
+ return if gross <= 0
+
+ earned = amounts.sum { |line_item_id, amount| line_earning(line_item_id, amount.to_d) }
+ quantize(earned * (refunded.to_d.abs / gross))
+ end
+
+ def blended_share(refunded)
paid = order.total.to_d
return refunded.to_d.abs if paid.zero?
- Spree::Money::Rounding.quantize(
- refunded.to_d.abs * (@earning.amount / paid),
- Spree::Money::Rounding.precision(@earning.currency)
- )
+ quantize(refunded.to_d.abs * (@earning.amount / paid))
+ end
+
+ # What one line's refunded value earned the seller: their money less the
+ # commission charged on it, and less the consumer tax when the marketplace
+ # remits it — mirroring how the earning itself was worked out.
+ #
+ # The commission comes from the row written against that line at
+ # placement, not from today's rate: rates change, a clamped fee is not the
+ # rate times the base, and a fixed rate is charged per unit.
+ def line_earning(line_item_id, amount)
+ line_item = order_line_items[line_item_id]
+ paid = line_item&.amount.to_d
+ return amount if paid.zero?
+
+ # Only ever a fraction of the line, so a clamped commission is divided
+ # rather than reasoned about — the best available attribution.
+ share = amount / paid
+ earned = amount - (commission_totals[line_item_id].to_d * share)
+ earned -= line_item.tax_total.to_d * share if order.seller&.tax_remittance == 'platform'
+ earned
+ end
+
+ def order_line_items
+ @order_line_items ||= order.line_items.index_by(&:id)
+ end
+
+ def commission_totals
+ @commission_totals ||= Spree::CommissionLine.for_line_items.
+ where(line_item_id: order_line_items.keys).
+ pluck(:line_item_id, :total).to_h
+ end
+
+ def quantize(amount)
+ Spree::Money::Rounding.quantize(amount, Spree::Money::Rounding.precision(@earning.currency))
end
# Nil when there is nothing left to take back, which the caller turns
diff --git a/spree/core/spec/models/spree/return_spec.rb b/spree/core/spec/models/spree/return_spec.rb
index f4047e06bd..f598617264 100644
--- a/spree/core/spec/models/spree/return_spec.rb
+++ b/spree/core/spec/models/spree/return_spec.rb
@@ -43,6 +43,23 @@ RSpec.describe Spree::Return do
end
end
+ # The seller's clawback is built from these, so a line the warehouse never
+ # counted must not appear: nothing came back, so nothing was earned back.
+ describe '#refunded_line_amounts' do
+ let(:return_record) { create(:received_return, store: store) }
+ let(:line) { return_record.return_line_items.first }
+
+ it 'names each line and what it is worth' do
+ expect(return_record.refunded_line_amounts).to eq(line.line_item_id => line.pre_tax_amount)
+ end
+
+ it 'counts what was received rather than what was announced' do
+ line.update!(received_quantity: 0)
+
+ expect(return_record.refunded_line_amounts).to be_empty
+ end
+ end
+
describe Spree::ReturnLineItem do
let(:return_record) { create(:return, store: store) }
let(:line) { return_record.return_line_items.first }
diff --git a/spree/core/spec/workflows/spree/seller_transfers/reverse_spec.rb b/spree/core/spec/workflows/spree/seller_transfers/reverse_spec.rb
index 54e41d0faa..91a5323ab9 100644
--- a/spree/core/spec/workflows/spree/seller_transfers/reverse_spec.rb
+++ b/spree/core/spec/workflows/spree/seller_transfers/reverse_spec.rb
@@ -43,6 +43,106 @@ RSpec.describe Spree::SellerTransfers::Reverse do
end
end
+ # The blend above is only right when every part of the order earned the seller
+ # the same proportion. It never does: commission excludes shipping, so goods
+ # earn 90% and delivery 100%. A refund that names the units it paid for can be
+ # answered exactly instead.
+ describe 'when the refund names the lines it paid for' do
+ let(:order) { create(:shipped_order, store: store, seller: seller, line_items_count: 1, line_items_price: 18) }
+ let(:line_item) { order.line_items.first }
+ let(:return_record) { create(:received_return, order: order, store: store) }
+ let(:refund) { create(:refund, amount: 18, originator: return_record) }
+
+ before { create(:commission_line, order: order, seller: seller, line_item: line_item, amount: 1.8, total: 1.8) }
+
+ # 18.00 of goods less the 1.80 charged on them. The blend would have taken
+ # 18.00 x (earning / order total), dipping into the delivery as well.
+ it 'takes back what the returned units earned, not a slice of the whole order' do
+ earn(order.total - 1.8)
+
+ expect(described_class.call(order: order, amount: 18, refund: refund).value.amount).to eq(-16.2)
+ end
+
+ it 'leaves the seller the delivery the customer was never refunded' do
+ earn(order.total - 1.8)
+ described_class.call(order: order, amount: 18, refund: refund)
+
+ expect(seller.balance('USD')).to eq(order.delivery_total)
+ end
+
+ it 'ignores a line the customer announced but never sent back' do
+ return_record.return_line_items.each { |line| line.update!(received_quantity: 0) }
+ earn(order.total - 1.8)
+
+ # Nothing came back, so nothing is attributable and the order's own ratio
+ # answers instead — which is the figure that dips into the delivery.
+ blended = (18 * ((order.total - 1.8) / order.total)).round(2)
+
+ expect(described_class.call(order: order, amount: 18, refund: refund).value.amount).to eq(-blended)
+ end
+
+ context 'when only part of a line comes back' do
+ before do
+ line_item.update!(price: 24, quantity: 3)
+ Spree::CommissionLine.for_line_items.update_all(amount: 7.2, total: 7.2)
+ end
+
+ # One of three units: 24.00 of goods less its third of the 7.20 charged
+ # on the line.
+ it 'takes back that unit’s share of the line' do
+ earn(order.total - 7.2)
+
+ expect(described_class.call(order: order, amount: 24, refund: refund).value.amount).to eq(-21.6)
+ end
+ end
+
+ # One return is refunded once per payment it draws on, and every one of
+ # those refunds names the same lines. Taken at face value they would each
+ # claw back the whole thing.
+ it 'splits one clawback across the refunds a single return produced' do
+ earn(order.total - 1.8)
+ first = create(:refund, amount: 10, originator: return_record)
+ second = create(:refund, amount: 8, originator: return_record)
+
+ described_class.call(order: order, amount: 10, refund: first)
+ described_class.call(order: order, amount: 8, refund: second)
+
+ expect(Spree::SellerTransfer.reversals_only.sum(:amount)).to eq(-16.2)
+ end
+
+ it 'scales when the operator refunded something other than what the units are worth' do
+ earn(order.total - 1.8)
+
+ # Half of what came back is worth, so half of what it earned.
+ expect(described_class.call(order: order, amount: 9, refund: refund).value.amount).to eq(-8.1)
+ end
+
+ context 'when the marketplace remits the consumer tax' do
+ before do
+ seller.update!(tax_remittance: 'platform')
+ line_item.update!(additional_tax_total: 2)
+ end
+
+ # The seller never received the tax, so it is not theirs to give back.
+ it 'takes the tax off the attributed lines too' do
+ earn(order.total - 1.8)
+
+ expect(described_class.call(order: order, amount: 18, refund: refund).value.amount).to eq(-14.2)
+ end
+ end
+ end
+
+ describe 'when the refund names nothing' do
+ # A cancellation and a manual refund carry no originator, so there is
+ # nothing to attribute and the order's own ratio is the best answer.
+ it 'falls back to the order’s ratio' do
+ earn(80)
+
+ expect(described_class.call(order: order, amount: 30, refund: create(:refund, amount: 30)).value.amount).
+ to eq(-24)
+ end
+ end
+
describe 'what it will not take back' do
it 'refuses to claw back more than was credited' do
earn(80)