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: refund a return for the units the warehouse received (#14678)

Łukasz Adamczyk3353e0fc1984
diff --git a/docs/api-reference/seller.yaml b/docs/api-reference/seller.yaml
index 4d9fb69ea6..236f53b971 100644
--- a/docs/api-reference/seller.yaml
+++ b/docs/api-reference/seller.yaml
@@ -18242,7 +18242,7 @@ paths:
example:
error:
code: processing_error
- message: refund_exceeds_balance
+ message: That is more than the amount still refundable.
requestBody:
content:
application/json:
diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.md
index b1a4f74403..e0a3577c20 100644
--- a/docs/plans/6.0-returns-exchanges-claims.md
+++ b/docs/plans/6.0-returns-exchanges-claims.md
@@ -331,7 +331,7 @@ class Spree::Return < Spree.base_class
# What the customer is owed; #refunded_total sums actual refunds —
# a return can be refunded in more than one step.
def refund_total
- return_line_items.sum(&:pre_tax_amount)
+ return_line_items.sum(&:refund_amount)
end
end
```
@@ -366,9 +366,33 @@ class Spree::ReturnLineItem < Spree.base_class
before_validation :set_defaults_from_line_item, on: :create
delegate :order, :currency, to: :return
+
+ # What this line refunds. pre_tax_amount is what the announced units are
+ # worth and never moves; once the warehouse has counted, only the units
+ # that arrived are paid for. Rounded to the currency, because a third of
+ # $29.99 taken three times is not $29.99 until it is.
+ def refund_amount
+ return pre_tax_amount unless self.return.counted?
+ return 0.to_d if quantity.to_i.zero?
+
+ Spree::Money::Rounding.to_currency(
+ (pre_tax_amount / quantity) * received_quantity.to_i, currency
+ )
+ end
end
```
+`Return#counted?` is `received? || refunded?`, read from the status rather
+than `received_at`: the 5.x migration task writes the status and no
+timestamps, so keying off the timestamp would leave an upgraded store's
+received returns owed the quantities nobody counted.
+
+The line owns this sum, not the return — `Return#refund_total` and
+`#refunded_line_amounts` both just add up what each line says, the same shape
+as `Claim#refund_total` over `ClaimLineItem#refund_amount`. Keeping it in one
+place is what stops the offered amount and the amount actually owed drifting
+apart (2026-09-18).
+
### Exchange (as shipped)
A customer returns items and gets different items in return (different size, different product).
@@ -576,7 +600,7 @@ and costs nothing.
| `Returns::Create` | `order:`, `items:`, `reason:`, `stock_location:`, `created_by:` | `validate`, `after_create` | `validate` is where a store rejects out-of-window returns |
| `Returns::Approve` | `return_record:`, `approver:` | `validate`, `after_approve` | No label generation — see Resolved Question 2 |
| `Returns::Receive` | `return_record:`, `items:`, `received_by:` | `validate`, `before_restock`, `after_receive` | Partial receipt is the normal case: `items:` carries actual quantities and per-item resellable flags, written to `received_quantity` |
-| `Returns::Refund` | `return_record:`, `amount:`, `refund_method:` | `validate`, `before_refund`, `after_refund` | Branches on refund method (below); `on_flow_failure:` reverses the status |
+| `Returns::Refund` | `return_record:`, `amount:`, `refund_method:` | `validate`, `before_refund`, `after_refund` | Branches on refund method (below); `on_flow_failure:` reverses the status. `refundable_total` is both the default amount and the ceiling, so a caller naming an amount cannot get more than one who names none |
| `Returns::Cancel` | `return_record:`, `reason:` | `validate`, `after_cancel` | Restocks nothing; only valid from requested/approved |
```ruby
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index ec55d20408..bcd740dc26 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,15 @@
+## 2026-09-18: A return is owed what the warehouse counted, and the line works that out
+
+**Context:** A return requested for three units and received as two offered the merchant a refund of all three. The dashboard pre-fills the refund dialog from `refundable_total` and always submits what is in the box, so the workflow's own correct default (`amount || received_total`) was never reached, and the only ceiling was the same announced-quantity figure — nothing refused it. On a $269.97 order line the customer was paid $89.99 too much and the seller clawed back $242.97 where $161.98 was owed, because `SellerTransfers::Reverse` scales the seller's share by the refund amount. Reproduced from a clean install, then twice more here: identical orders refunded with and without an `amount` came out $269.97 and $179.98 (V-3654). The same received-based arithmetic existed in three places — `Returns::Refund#received_total`, `Return#refunded_line_amounts` and nowhere else that anyone reading `refund_total` would find — which is how the offered figure and the owed figure came to disagree.
+
+**Decision:** `Spree::ReturnLineItem#refund_amount` is the single answer to what a line refunds, and `Return#refund_total` / `#refunded_line_amounts` are plain sums over it — the shape `Claim#refund_total` already had over `ClaimLineItem#refund_amount`. Before the warehouse has counted, the line is worth the announced quantity, since nothing better exists to quote; once it has, only the units that arrived are paid for. "Counted" is `Return#counted?` — `received? || refunded?`, so the figure does not revert when the return moves on — read from the status and not from `received_at`, which `migrate_returns.rake` never writes: keying off the timestamp would have left every store upgraded from the 5.x return chain with the original bug intact. The derived share is rounded to the currency through `Spree::Money::Rounding.to_currency`, because this figure is now an enforced ceiling as well as a display: a third of $29.99 taken three times is $29.9900000000000000000000000000001 in BigDecimal, which would refuse a full refund of a fully received return, and a third of $10.00 taken three times is $9.9999999999999999999999999999999, which the dashboard would prefill into the amount box verbatim. `pre_tax_amount` keeps its meaning untouched as what the announced units are worth — it is stored history, and receiving must not rewrite it. `Returns::Refund` drops its private `received_total` and takes `refundable_total` as both its default and its ceiling, so the amount a caller may name is the amount a caller who names none would get.
+
+Rejected: correcting only the dialog's pre-fill, which leaves the Admin API, the seller panel and every integration able to over-refund; and having `Returns::Receive` overwrite `pre_tax_amount` at receipt, which fixes every reader for free but destroys the record of what the customer announced.
+
+**Consequences:** No API shape changes and no dashboard change at all — both panels already read `refundable_total`, and it is now right. The values move: after a partial receipt `refund_total`, `display_refund_total` and `refundable_total` all drop to what arrived, on the Admin, Seller and Store serializers alike, so the returns card and the customer's own return page stop quoting a figure nobody will be paid. An over-large amount is now a 422 `refund_exceeds_balance` where it used to succeed, which is a behaviour change for any integration that was passing the announced total deliberately. The seller clawback needed no change: it scales off the refund, so a correct refund makes it correct. The phantom outstanding balance on a refunded order (V-3562) is untouched and still open.
+
+**Plans amended:** `6.0-returns-exchanges-claims.md` (Return and ReturnLineItem snippets, the `Returns::Refund` workflow row).
+
## 2026-09-16: Two catalogs on one company charge the best of them, and every order line says which agreement priced it
**Context:** Nothing stopped an operator assigning a second catalog to a company — the audience picker offered the company again with no warning — and once both were active the buyer was charged from whichever catalog sorted first, not the cheaper one. Reported against a company holding a 5%-off catalog and a contract catalog with a quantity break: at 24 units the buyer paid $2,280.00 where the company's other agreement said $1,200.00, and reversing the two catalogs' order reversed the outcome (V-3635). The tie-break was the documented design — `Catalog#position`, which is the order of the store-wide catalogs screen — so a merchant dragging that list to tidy it changed what companies paid, with no screen anywhere listing a company's catalogs to show it had happened.
diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rb
index 9ab02eb5ab..5ff769ed23 100644
--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb
@@ -81,7 +81,10 @@ module Spree
if errors.is_a?(ActiveModel::Errors)
render_validation_error(errors)
else
- render_service_error(error)
+ # The unwrapped value, so a workflow's rejection symbol reaches
+ # the branch that translates it rather than the one that prints
+ # the wrapper.
+ render_service_error(errors)
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
index 777d9dd3a1..3bf2f5a370 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/returns_controller_spec.rb
@@ -187,6 +187,21 @@ RSpec.describe Spree::Api::V3::Admin::Orders::ReturnsController, type: :controll
expect(response).to have_http_status(:unprocessable_content)
end
+
+ # A workflow rejects with a symbol. The operator has to be told what went
+ # wrong, not handed `refund_exceeds_balance`.
+ it 'explains a refund larger than the return is owed' do
+ patch :refund, params: {
+ order_id: order.prefixed_id,
+ id: return_record.prefixed_id,
+ amount: '10000.00',
+ refund_method: 'store_credit'
+ }, as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['message']).to eq(Spree.t(:refund_exceeds_balance))
+ expect(json_response['error']['message']).not_to include('refund_exceeds_balance')
+ end
end
describe 'PATCH #cancel' do
diff --git a/spree/core/app/models/spree/return.rb b/spree/core/app/models/spree/return.rb
index 7d7a80e093..e09b5d4513 100644
--- a/spree/core/app/models/spree/return.rb
+++ b/spree/core/app/models/spree/return.rb
@@ -111,21 +111,31 @@ module Spree
end
end
+ # Whether the warehouse has reported on this return.
+ #
+ # @return [Boolean]
+ def counted?
+ received? || refunded?
+ end
+
# What the customer is owed for the items being returned.
def refund_total
- return_line_items.sum(&:pre_tax_amount)
+ return_line_items.sum(&:refund_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.
+ # What a refund from this return paid for, line by line. Only ever what
+ # the warehouse counted: the seller's clawback is built from this, and a
+ # line nobody counted earned nothing back.
#
# @return [Hash{Integer => BigDecimal}] line item id => amount
def refunded_line_amounts
+ return {} unless counted?
+
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?
+ amount = line.refund_amount
+ next if amount.zero?
- amounts[line.line_item_id] += (line.pre_tax_amount / line.quantity) * line.received_quantity.to_i
+ amounts[line.line_item_id] += amount
end
end
diff --git a/spree/core/app/models/spree/return_line_item.rb b/spree/core/app/models/spree/return_line_item.rb
index 0e40144131..2c87b05107 100644
--- a/spree/core/app/models/spree/return_line_item.rb
+++ b/spree/core/app/models/spree/return_line_item.rb
@@ -19,6 +19,25 @@ module Spree
delegate :order, :currency, to: :return
+ # What this line refunds. Once the warehouse has counted, only the units
+ # that arrived are paid for — a customer who announced three and sent two
+ # is owed two — and before the count there is nothing to go on but the
+ # announced quantity.
+ #
+ # Rounded to the currency, because this is the ceiling a refund is checked
+ # against as well as the figure the dialog offers: a third of $29.99 taken
+ # three times is not $29.99 until it is.
+ #
+ # @return [BigDecimal]
+ def refund_amount
+ return pre_tax_amount unless self.return.counted?
+ return 0.to_d if quantity.to_i.zero?
+
+ Spree::Money::Rounding.to_currency(
+ (pre_tax_amount / quantity) * received_quantity.to_i, currency
+ )
+ end
+
def display_pre_tax_amount
Spree::Money.new(pre_tax_amount, currency: currency)
end
diff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rb
index de42a06637..2c431a1457 100644
--- a/spree/core/app/workflows/spree/returns/refund.rb
+++ b/spree/core/app/workflows/spree/returns/refund.rb
@@ -52,15 +52,14 @@ module Spree
# original supply date rather than today's — the rate that applied then is
# the rate to credit back.
#
- # Only lines that actually arrived are credited, matching what
- # +received_total+ refunds: a customer who announced three items and sent
- # two must not have tax credited on the third.
+ # Only lines that actually arrived are credited: a customer who announced
+ # three items and sent two must not have tax credited on the third.
#
# The refunded amount goes with them, because it can be less than those
# lines are worth — a restocking fee, or an agreed part-refund. Without it
# a provider would credit the tax on goods whose value the merchant kept.
def refund_tax
- received = return_record.return_line_items.select { |line| line.received_quantity.to_i.positive? }
+ received = return_record.return_line_items.select { |line| line.refund_amount.positive? }
return if received.empty?
order = return_record.order
@@ -83,21 +82,16 @@ module Spree
failure(return_record, :not_received) unless return_record.received?
end
- # Only what actually came back is refundable — a customer who sent two
- # of three items gets two items' worth.
+ # Only what actually came back is refundable — a customer who sent two of
+ # three items gets two items' worth. One figure serves as both the
+ # default and the ceiling, so a caller naming an amount cannot ask for
+ # more than a caller who names none would get.
def resolve_amount
- @amount_to_refund = (amount || received_total).to_d
+ refundable = return_record.refundable_total.to_d
+ @amount_to_refund = amount ? amount.to_d : refundable
failure(return_record, :nothing_to_refund) unless @amount_to_refund.positive?
- failure(return_record, :refund_exceeds_balance) if @amount_to_refund > return_record.refundable_total.to_d
- end
-
- def received_total
- return_record.return_line_items.sum do |line|
- next 0 if line.quantity.to_i.zero?
-
- (line.pre_tax_amount / line.quantity) * line.received_quantity.to_i
- end
+ failure(return_record, :refund_exceeds_balance) if @amount_to_refund > refundable
end
def issue_store_credit
diff --git a/spree/core/spec/models/spree/return_spec.rb b/spree/core/spec/models/spree/return_spec.rb
index f598617264..ca57d5c453 100644
--- a/spree/core/spec/models/spree/return_spec.rb
+++ b/spree/core/spec/models/spree/return_spec.rb
@@ -41,6 +41,58 @@ RSpec.describe Spree::Return do
expect(return_record.refunded_total).to eq(0)
expect(return_record.refundable_total).to eq(return_record.refund_total)
end
+
+ # The refund dialog offers refundable_total, so a figure still counting
+ # units that never arrived is money out of the door (V-3654).
+ context 'when the warehouse counted fewer units than were announced' do
+ let(:return_record) { create(:received_return, store: store) }
+
+ before do
+ return_record.return_line_items.first.
+ update!(quantity: 3, received_quantity: 2, pre_tax_amount: 269.97)
+ end
+
+ it 'owes only what arrived' do
+ expect(return_record.refund_total).to eq(179.98)
+ expect(return_record.refundable_total).to eq(179.98)
+ end
+ end
+
+ # A third of a line does not divide, and this figure is the ceiling a
+ # refund is checked against as well as the one the dialog offers.
+ context 'when the share of the line does not divide evenly' do
+ let(:return_record) { create(:received_return, store: store) }
+ let(:line) { return_record.return_line_items.first }
+
+ it 'rounds what arrived to the currency' do
+ line.update!(quantity: 3, received_quantity: 2, pre_tax_amount: 10.00)
+
+ expect(return_record.refund_total).to eq(6.67)
+ end
+
+ it 'owes the whole line back when every unit arrived' do
+ line.update!(quantity: 3, received_quantity: 3, pre_tax_amount: 29.99)
+
+ expect(return_record.refund_total).to eq(29.99)
+ end
+ end
+
+ # The 5.x migration task writes the status but no received_at, so an
+ # upgraded store's received returns must not fall back to what the
+ # customer announced (V-3654).
+ context 'when a migrated return carries no received_at' do
+ let(:return_record) { create(:received_return, store: store) }
+
+ before do
+ return_record.return_line_items.first.
+ update!(quantity: 3, received_quantity: 2, pre_tax_amount: 269.97)
+ return_record.update_columns(received_at: nil)
+ end
+
+ it 'still owes only what arrived' do
+ expect(return_record.reload.refund_total).to eq(179.98)
+ end
+ end
end
# The seller's clawback is built from these, so a line the warehouse never
@@ -81,6 +133,12 @@ RSpec.describe Spree::Return do
it 'starts with nothing received' do
expect(line.received_quantity).to eq(0)
end
+
+ # Nothing has been counted yet, so what the customer announced is the only
+ # measure of what the return will cost.
+ it 'is owed the announced amount until the warehouse has counted' do
+ expect(line.refund_amount).to eq(line.pre_tax_amount)
+ end
end
describe '#to_package' do
let(:order) { create(:shipped_order, store: store) }
diff --git a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb
index a3c5b510e7..1748d8fdb8 100644
--- a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb
+++ b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb
@@ -248,6 +248,32 @@ RSpec.describe 'Spree::Returns workflows' do
)
end
+ # The money side pays nothing for a line the customer paid nothing for,
+ # so the tax side must not claim one either.
+ it 'leaves out a line that arrived but was worth nothing' do
+ line = return_record.return_line_items.first
+ free = create(:return_line_item,
+ return: return_record,
+ fulfillment_item: line.fulfillment_item,
+ line_item: line.line_item,
+ variant: line.variant,
+ quantity: 1)
+ free.update!(received_quantity: 1, pre_tax_amount: 0)
+ return_record.reload
+
+ order = return_record.order
+ provider = instance_double(Spree::TaxProvider::Internal, refund: nil, estimate: nil)
+ allow(order).to receive(:tax_provider).and_return(provider)
+ allow_any_instance_of(Spree::Return).to receive(:order).and_return(order)
+
+ Spree::Returns::Refund.call(return_record: return_record, refund_method: 'store_credit')
+
+ expect(provider).to have_received(:refund) do |_order, lines, **|
+ expect(lines).to include(line)
+ expect(lines).not_to include(free)
+ end
+ end
+
# A partial refund must not hand the provider the returned lines with no
# word of how little went back: crediting their full tax would reclaim tax
# the merchant kept, and a return is marked refunded only once.
@@ -267,6 +293,31 @@ RSpec.describe 'Spree::Returns workflows' do
)
end
+ # The refund dialog pre-fills the amount from the return and always
+ # submits it, so a ceiling that still counted the announced units paid
+ # for goods that never came back (V-3654).
+ context 'when the warehouse counted fewer units than were announced' do
+ before do
+ return_record.return_line_items.first.
+ update!(quantity: 3, received_quantity: 2, pre_tax_amount: 269.97)
+ end
+
+ it 'credits only what arrived when the caller names no amount' do
+ Spree::Returns::Refund.call(return_record: return_record, refund_method: 'store_credit')
+
+ expect(Spree::StoreCredit.find_by(originator: return_record).amount).to eq(179.98)
+ end
+
+ it 'refuses an amount that counts units that never came back' do
+ result = Spree::Returns::Refund.call(return_record: return_record, amount: 269.97,
+ refund_method: 'store_credit')
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq(:refund_exceeds_balance)
+ expect(Spree::StoreCredit.where(originator: return_record)).to be_empty
+ end
+ end
+
it 'lets a validate handler veto before any credit is issued' do
Spree.hooks.register('returns.refund.validate') { |flow| flow.reject!('refunds on hold') }