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: an order refunded to store credit still showed as paid (#14687)
Łukasz Adamczyke0be0c27088b
diff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.mdindex fd84330c09..1f800065b8 100644--- a/docs/plans/6.0-cart-order-split.md+++ b/docs/plans/6.0-cart-order-split.md@@ -64,7 +64,7 @@ Every competitor treats this as load-bearing. `Spree::Carts::Complete`:**(b) Transition-triggered recalculation → recalculation-on-write.** Today tax/prices/shipment rebuilds fire *only* on state transitions (4 call sites) — an address changed in place at `payment` never re-runs tax. The Cart model recalculates explicitly on the writes that matter: address/market change → re-price, re-tax, rebuild delivery proposals (the destructive `create_proposed_shipments` behavior becomes an idempotent cart-side rebuild; the order's fulfillments are a frozen copy, never rebuilt); item changes → totals + reservations (the existing Release/Reserve/Extend dispatch in `Carts::Update` carries over). The stale memoized `tax_zone` hazard dies with the memoized order context.-**(c) Statuses → derive-then-persist (OSS platform B's hybrid, explicitly not OSS platform A's pure derivation).** OSS platform A derives payment/fulfillment status at read time and has open bugs to show for it (can't filter/sort admin order lists — #14095; status stuck after full return — #13882); the hosted market leader has the analogous `financial_status:expired` filter-index bug. Spree's admin is Ransack-heavy — pure derivation breaks order-list filtering on day one. So: `payment_status` and `fulfillment_status` are **stored, indexed string columns** (names per the normalize plan), recomputed by a single `Spree::Orders::UpdateStatuses` service triggered from payment/fulfillment/refund/return event subscribers. One writer, many triggers. Rules that competitors learned the hard way: quantize money to currency precision **before** comparing; subtract granted/pending refunds from the total before comparing; include `overcharged` (OSS platform B) and `voided` (the hosted market leader) in the payment domain; define the returns interplay explicitly (where OSS platform A's derivation broke). The `fulfillment_status` domain (incl. `backorder`) is owned by `6.0-fulfillment-and-delivery.md`.+**(c) Statuses → derive-then-persist (OSS platform B's hybrid, explicitly not OSS platform A's pure derivation).** OSS platform A derives payment/fulfillment status at read time and has open bugs to show for it (can't filter/sort admin order lists — #14095; status stuck after full return — #13882); the hosted market leader has the analogous `financial_status:expired` filter-index bug. Spree's admin is Ransack-heavy — pure derivation breaks order-list filtering on day one. So: `payment_status` and `fulfillment_status` are **stored, indexed string columns** (names per the normalize plan), recomputed by a single `Spree::Orders::UpdateStatuses` service triggered from payment/fulfillment/refund/store-credit/return event subscribers. One writer, many triggers. Rules that competitors learned the hard way: quantize money to currency precision **before** comparing; subtract granted/pending refunds from the total before comparing, counting refunds paid as store credit alongside the gateway rows (2026-09-22 — credit writes no `Spree::Refund`, so counting those alone left a fully credited order reading `paid`); include `overcharged` (OSS platform B) and `voided` (the hosted market leader) in the payment domain; define the returns interplay explicitly (where OSS platform A's derivation broke). The `fulfillment_status` domain (incl. `backorder`) is owned by `6.0-fulfillment-and-delivery.md`.### 6. Order lifecycle stays on Order, without a machinediff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.mdindex e0a3577c20..5dd27f5a80 100644--- a/docs/plans/6.0-returns-exchanges-claims.md+++ b/docs/plans/6.0-returns-exchanges-claims.md@@ -82,7 +82,12 @@ Replacements built where the drop would otherwise have removed capability:through `originator`.- **`Return#refunded_total`** now sums refunds **and** store credits — storecredit is its own ledger and never creates a `Spree::Refund` row, so the- old sum reported zero for a store-credit refund.+ old sum reported zero for a store-credit refund. Extended 2026-09-22 to the+ order: a refund paid as credit names the order it settles+ (`spree_store_credits.refunded_order_id`), all three workflows issue it through+ `Refunds::OrderPayments#issue_refund_store_credit`, and+ `Orders::UpdateStatuses` counts both ledgers — without which an order+ refunded this way went on reading `paid`.- **`StoreCreditCategory.default_reimbursement_category`** →`.default_refund_category` (deprecated alias kept). Superseded 2026-08-18:store credits no longer carry a category at all — the workflows set onlydiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 6881cb8693..7bc3821544 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,15 @@+## 2026-09-22: Store credit names the order it puts right, so payment status counts both ledgers++**Context:** An order refunded to store credit went on reading `paid`. Reproduced on `main`: order R1016, total $99.99, one $89.99 line returned and refunded as credit — the return reported `refunded_total` $89.99 and `refundable_total` $0.00 while the order reported `payment_status: paid` and nothing given back. A claim behaves the same, and lands there by default, since the claim resolve dialog and `ClaimActions#resolve` both default to `store_credit` where the return side defaults to `original_payment` (V-3660). The cause was a decision applied in one place and not the other: the 2026-08-11 ruling that store credit is its own ledger and never writes a `Spree::Refund` row taught `Return#refunded_total` to sum both, but `Orders::UpdateStatuses#money_for` still counted refund rows alone. V-3561 was closed on the strength of the original-payment half working.++**Decision:** A store credit issued as a refund names the order it settles, in a nullable `spree_store_credits.refunded_order_id` — the same argument as `spree_refunds.order_id` (2026-08-20), which exists because a refund reached its order through its payment and a split checkout has no such payment to ask. Named `refunded_order` rather than `order` because this table already answers `orders` with the orders a credit went on to pay for, and a credit that settles one order and is spent on another is ordinary. `Orders::UpdateStatuses` adds that sum to the refunded figure in both branches, ordinary and grouped, so `refunded` in the derivation means what the customer got back rather than what left a gateway. The three `issue_store_credit` copies in `Returns::Refund`, `Claims::Resolve` and `Exchanges::Fulfill` become one `issue_refund_store_credit` in `Refunds::OrderPayments`, beside the gateway half — three copies drifting apart is what let one rule be applied to the ledger and not to the order. `OrderStatusSubscriber` gains the `store_credit.*` events, which are the only announcement a credit-settled claim makes — including `deleted`, so it resolves paranoid records with deleted ones included rather than losing the row that just went.++Rejected: walking `order.returns/claims/exchanges` to their credits, which needs three indexed queries on a path that runs on every payment, fulfillment and refund event, and counts no originator an extension adds. Also rejected: netting credit out of `payment_total`. That column is what came in through payments, the money is still with the store, and moving it would take `paid?` and `outstanding_balance` with it.++**Consequences:** `payment_status` moves on orders that were reading `paid`, which is the point. No backfill ships with it, in the migration or as an upgrade step. There is nothing to backfill: Spree 5 never set `originator` on a reimbursement's credit — that chain linked through `spree_reimbursement_credits`, and `migrate_returns` re-points refunds only — so no credit on an upgraded install carries a return, claim or exchange originator. The only rows a backfill could reach are a 6.0 beta tester's, and one console line fixes those. The `refunded` and `partially_refunded` Ransack scopes now read the derived column instead of re-summing refund rows through a join, which is what stored statuses are for; they had no callers and would otherwise have contradicted the column beside them. A credit for part of an order reads `partially_refunded`; one covering everything captured reads `refunded`. `payment_total` deliberately does not move, so a fully credit-refunded order shows `payment_status: refunded` beside a `payment_total` equal to its total — two columns answering two questions, and the second is the honest one for money that never left. The two roles a store credit plays stay in separate tables — credit as payment is `spree_payments.source`, credit as refund is this column — so nothing counts one as the other. Left alone, all pre-existing and none of them made worse here: `Order#order_refunded?` and `#partially_refunded?` count refund rows only and have the same blind spot, but nothing reads them; a claim's gateway refund is still stamped with the "Return processing" reason rather than the claim's own; `SellerTransferReversalSubscriber` hangs off `refund.created`, so a marketplace seller is never clawed back for a refund paid as credit, against its own comment that "every one of those funnels its money movement through a refund"; and `Payment#credit_allowed` counts refund rows alone, so credit does not reduce gateway headroom and the same money can be handed back twice through two post-sale records. The last two are money defects worth their own issues.++**Plans amended:** `6.0-returns-exchanges-claims.md` (the `Return#refunded_total` replacement bullet), `6.0-cart-order-split.md` (the derive-then-persist rules).+## 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.diff --git a/spree/core/app/models/spree/claim.rb b/spree/core/app/models/spree/claim.rbindex 677175adbd..0784841155 100644--- a/spree/core/app/models/spree/claim.rb+++ b/spree/core/app/models/spree/claim.rb@@ -33,6 +33,7 @@ module Spreehas_many :claim_line_items, class_name: 'Spree::ClaimLineItem',dependent: :destroy, inverse_of: :claimhas_many :refunds, class_name: 'Spree::Refund', as: :originator, dependent: :nullify+ has_many :store_credits, class_name: 'Spree::StoreCredit', as: :originator, dependent: :nullifyvalidates :claim_line_items, presence: true, on: :createvalidates :resolution, inclusion: { in: RESOLUTIONS }, allow_nil: truediff --git a/spree/core/app/models/spree/exchange.rb b/spree/core/app/models/spree/exchange.rbindex dcfd63e1d1..24fe6bd464 100644--- a/spree/core/app/models/spree/exchange.rb+++ b/spree/core/app/models/spree/exchange.rb@@ -32,6 +32,7 @@ module Spreehas_many :exchange_line_items, class_name: 'Spree::ExchangeLineItem',dependent: :destroy, inverse_of: :exchangehas_many :refunds, class_name: 'Spree::Refund', as: :originator, dependent: :nullify+ has_many :store_credits, class_name: 'Spree::StoreCredit', as: :originator, dependent: :nullifyvalidates :exchange_line_items, presence: true, on: :creatediff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 4c6980a2a4..7fa8c5edbe 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -242,6 +242,11 @@ module Spree# checkout names the one child being refunded. Keyed on that column rather# than walked through payments, which a grouped order does not own.has_many :refunds, class_name: 'Spree::Refund', inverse_of: :order, dependent: :nullify+ # The other half of what this order gave back. A refund paid as store+ # credit writes no Spree::Refund row, so anything measuring what the+ # customer got back has to add the two ledgers.+ has_many :store_credit_refunds, class_name: 'Spree::StoreCredit', inverse_of: :refunded_order,+ foreign_key: :refunded_order_id, dependent: :nullify# Typed adjustment rows owned by this order (line-, fulfillment- and# order-level). See docs/plans/6.0-6.1-split-adjustments.md.@@ -333,12 +338,8 @@ module Spreescope :partially_shipped, -> { where(fulfillment_status: %w[partial]) }scope :not_shipped, -> { where(fulfillment_status: %w[unfulfilled partial]) }scope :shipped, -> { where(fulfillment_status: %w[fulfilled delivered shipped]) }- scope :refunded, lambda {- joins(:refunds).group(:id).having("sum(#{Spree::Refund.table_name}.amount) = #{Spree::Order.table_name}.total")- }- scope :partially_refunded, lambda {- joins(:refunds).group(:id).having("sum(#{Spree::Refund.table_name}.amount) < #{Spree::Order.table_name}.total")- }+ scope :refunded, -> { where(payment_status: 'refunded') }+ scope :partially_refunded, -> { where(payment_status: 'partially_refunded') }scope :with_deleted_bill_address, -> { joins(:bill_address).where.not(Address.table_name => { deleted_at: nil }) }scope :with_deleted_ship_address, -> { joins(:ship_address).where.not(Address.table_name => { deleted_at: nil }) }diff --git a/spree/core/app/models/spree/store_credit.rb b/spree/core/app/models/spree/store_credit.rbindex 3101204636..754604e807 100644--- a/spree/core/app/models/spree/store_credit.rb+++ b/spree/core/app/models/spree/store_credit.rb@@ -25,6 +25,8 @@ module Spreeinclude Spree::DeprecatedCustomerAliasbelongs_to :created_by, class_name: Spree.admin_user_class.to_s, foreign_key: 'created_by_id', optional: truebelongs_to :originator, polymorphic: true, optional: true+ belongs_to :refunded_order, class_name: 'Spree::Order', optional: true,+ inverse_of: :store_credit_refundshas_many :store_credit_events, class_name: 'Spree::StoreCreditEvent'has_many :payments, as: :source, class_name: 'Spree::Payment'diff --git a/spree/core/app/services/spree/orders/update_statuses.rb b/spree/core/app/services/spree/orders/update_statuses.rbindex 618145383c..5e162a7cc0 100644--- a/spree/core/app/services/spree/orders/update_statuses.rb+++ b/spree/core/app/services/spree/orders/update_statuses.rb@@ -60,14 +60,20 @@ module Spree# shipped and been captured while another has not, no proportion of the# group's totals can describe either.#+ # Refunded spans both ledgers. A refund paid as store credit writes no+ # {Spree::Refund} row, and counting only those rows left an order that+ # had given every penny back still reading `paid`.+ ## @return [Array(BigDecimal, BigDecimal, BigDecimal)] captured,# authorized and refunded, in that orderdef money_for(order)+ credited = order.store_credit_refunds.sum(:amount)+unless order.order_group_id.present?return [order.payments.valid.completed.sum(:amount),order.payments.valid.pending.sum(:amount),- order.refunds.sum(:amount)+ order.refunds.sum(:amount) + credited]end@@ -76,7 +82,7 @@ module Spree# Authorized means still to draw: what the shares allow, less what has# already been taken against them.- [captured, splits.sum(&:authorized_amount) - captured, splits.sum(&:refunded_amount)]+ [captured, splits.sum(&:authorized_amount) - captured, splits.sum(&:refunded_amount) + credited]end# Rolls the fulfillments up into one word for filtering and display.diff --git a/spree/core/app/subscribers/spree/order_status_subscriber.rb b/spree/core/app/subscribers/spree/order_status_subscriber.rbindex d995a399ce..e8d3521f3a 100644--- a/spree/core/app/subscribers/spree/order_status_subscriber.rb+++ b/spree/core/app/subscribers/spree/order_status_subscriber.rb@@ -1,6 +1,6 @@module Spree# The trigger side of derive-then-persist statuses: any payment, refund,- # fulfillment or return change recomputes the owning order's+ # store credit, fulfillment or return change recomputes the owning order's# payment_status / fulfillment_status through the single writer# (Spree::Orders::UpdateStatuses). Synchronous so API responses right# after a capture/void/fulfill already carry the fresh status. Cart-owned@@ -15,12 +15,15 @@ module Spreesubscribes_to 'payment.created', 'payment.updated', 'payment.deleted','payment.completed', 'payment.captured', 'payment.voided','refund.created', 'refund.updated',+ 'store_credit.created', 'store_credit.updated', 'store_credit.deleted','fulfillment.created', 'fulfillment.updated', 'fulfillment.deleted','return.received', 'return.refunded', 'return.canceled',async: false# Events whose payload changes what the customer has actually paid, so# payment_total has to be re-summed before statuses derive from it.+ # Store credit is not one of them: the money stayed with the store, and+ # payment_total is what came in through payments.MONEY_EVENTS = %w[payment.created payment.updated payment.deleted payment.completedpayment.voided refund.created refund.updated@@ -63,19 +66,24 @@ module Spreeresource_class = {'payment' => Spree::Payment,'refund' => Spree::Refund,+ 'store_credit' => Spree::StoreCredit,'fulfillment' => Spree::Fulfillment,'return' => Spree::Return}[event.resource_type]return if resource_class.nil?- record = resource_class.find_by_prefix_id(event.payload['id'])- # None of these models are paranoid, so a .deleted event arrives with- # its row already gone and a payload carrying no owner — nothing can- # lead back to the order. The models whose deletion changes order- # money recalculate from their own after_destroy instead.+ # A paranoid model's .deleted event leaves the row in place but out of+ # default scope, and a credit that has been withdrawn is exactly the+ # kind of change the order has to learn about.+ record = (resource_class.try(:with_deleted) || resource_class).+ find_by_prefix_id(event.payload['id'])+ # Neither Payment nor Fulfillment is paranoid, so their .deleted events+ # arrive with the row already gone and a payload carrying no owner —+ # nothing can lead back to the order. The models whose deletion changes+ # order money recalculate from their own after_destroy instead.return if record.nil?- record.try(:owner) || record.try(:order) ||+ record.try(:owner) || record.try(:order) || record.try(:refunded_order) ||record.try(:payment)&.try(:owner)endenddiff --git a/spree/core/app/workflows/spree/claims/resolve.rb b/spree/core/app/workflows/spree/claims/resolve.rbindex 7a44978299..78627f62b0 100644--- a/spree/core/app/workflows/spree/claims/resolve.rb+++ b/spree/core/app/workflows/spree/claims/resolve.rb@@ -130,17 +130,13 @@ module Spreeenddef issue_store_credit- @refunds = [- Spree::StoreCredit.create!(- store: claim.store,- customer: claim.order.customer,- amount: @amount_to_refund,- currency: claim.currency,- created_by: resolver,- originator: claim,- memo: "Claim #{claim.number}"- )- ]+ @refunds = issue_refund_store_credit(+ order: claim.order,+ amount: @amount_to_refund,+ record: claim,+ memo: "Claim #{claim.number}",+ refunder: resolver+ )enddef refund_at_gatewaydiff --git a/spree/core/app/workflows/spree/exchanges/fulfill.rb b/spree/core/app/workflows/spree/exchanges/fulfill.rbindex ab17c948cb..bccdb441e6 100644--- a/spree/core/app/workflows/spree/exchanges/fulfill.rb+++ b/spree/core/app/workflows/spree/exchanges/fulfill.rb@@ -112,17 +112,13 @@ module Spreeenddef issue_store_credit- @refunds = [- Spree::StoreCredit.create!(- store: exchange.store,- customer: exchange.order.customer,- amount: credit_amount,- currency: exchange.currency,- created_by: refunder,- originator: exchange,- memo: "Exchange #{exchange.number}"- )- ]+ @refunds = issue_refund_store_credit(+ order: exchange.order,+ amount: credit_amount,+ record: exchange,+ memo: "Exchange #{exchange.number}",+ refunder: refunder+ )enddef refund_at_gatewaydiff --git a/spree/core/app/workflows/spree/refunds/order_payments.rb b/spree/core/app/workflows/spree/refunds/order_payments.rbindex 4a9f182c9e..2da7831306 100644--- a/spree/core/app/workflows/spree/refunds/order_payments.rb+++ b/spree/core/app/workflows/spree/refunds/order_payments.rb@@ -2,7 +2,8 @@module Spreemodule Refunds- # Gives a post-sale workflow one way to put money back on an order.+ # Gives a post-sale workflow its two ways to put money back on an order:+ # back to what paid for it, or as store credit.## Returns, claims and exchanges all owe the customer money for the same# reason — goods that are going back, or were never right — and all three@@ -22,6 +23,36 @@ module Spreeprivate+ # Puts `amount` back as store credit.+ #+ # Credit is its own ledger and writes no {Spree::Refund} row, so the+ # credit names the order it settles — without that the order could not+ # tell it had given anything back, and its payment status stayed `paid`+ # on money the customer had already been made whole for.+ #+ # @param order [Spree::Order] the order being put right+ # @param amount [BigDecimal] how much to give back+ # @param record [Spree::Return, Spree::Claim, Spree::Exchange] what asked+ # for it; it originates the credit+ # @param memo [String] what the customer reads on the credit+ # @param refunder [Object, nil] whoever is issuing it+ # @return [Array<Spree::StoreCredit>] the one credit written, shaped like+ # {#refund_order_payments} so both branches answer the same way+ def issue_refund_store_credit(order:, amount:, record:, memo:, refunder: nil)+ [+ Spree::StoreCredit.create!(+ store: record.store,+ customer: order.customer,+ refunded_order: order,+ amount: amount,+ currency: record.currency,+ created_by: refunder,+ originator: record,+ memo: memo+ )+ ]+ end+# Puts `amount` back on `order`, oldest payment first, until it is# covered.#diff --git a/spree/core/app/workflows/spree/returns/refund.rb b/spree/core/app/workflows/spree/returns/refund.rbindex 2c431a1457..5d1c62624e 100644--- a/spree/core/app/workflows/spree/returns/refund.rb+++ b/spree/core/app/workflows/spree/returns/refund.rb@@ -95,16 +95,13 @@ module Spreeenddef issue_store_credit- credit = Spree::StoreCredit.create!(- store: return_record.store,- customer: return_record.order.customer,+ @refunds = issue_refund_store_credit(+ order: return_record.order,amount: @amount_to_refund,- currency: return_record.currency,- created_by: refunder,- originator: return_record,- memo: "Return #{return_record.number}"+ record: return_record,+ memo: "Return #{return_record.number}",+ refunder: refunder)- @refunds = [credit]end# Each refund row commits, then Refund#perform! credits it at thediff --git a/spree/core/db/migrate/20260922000001_add_refunded_order_to_spree_store_credits.rb b/spree/core/db/migrate/20260922000001_add_refunded_order_to_spree_store_credits.rbnew file mode 100644index 0000000000..52b063f33b--- /dev/null+++ b/spree/core/db/migrate/20260922000001_add_refunded_order_to_spree_store_credits.rb@@ -0,0 +1,5 @@+class AddRefundedOrderToSpreeStoreCredits < ActiveRecord::Migration[8.1]+ def change+ add_reference :spree_store_credits, :refunded_order, index: true+ end+enddiff --git a/spree/core/spec/models/spree/order_updater_spec.rb b/spree/core/spec/models/spree/order_updater_spec.rbindex 76080eef82..e883cc6aa9 100644--- a/spree/core/spec/models/spree/order_updater_spec.rb+++ b/spree/core/spec/models/spree/order_updater_spec.rb@@ -218,6 +218,36 @@ module Spreeendend+ # A refund paid as store credit writes no Spree::Refund row, so an order+ # settled that way used to read `paid` on money already given back.+ context 'refunded to store credit' do+ before { create(:payment, order: order, amount: order_total, status: 'completed') }++ it 'is partially_refunded when part of it came back as credit' do+ create(:store_credit, refunded_order: order, store: order.store, customer: order.customer, amount: order_total - 1)++ updater.update_payment_state++ expect(order.payment_state).to eq('partially_refunded')+ end++ it 'is refunded when all of it came back as credit' do+ create(:store_credit, refunded_order: order, store: order.store, customer: order.customer, amount: order_total)++ updater.update_payment_state++ expect(order.payment_state).to eq('refunded')+ end++ it 'ignores credit that settles no order' do+ create(:store_credit, store: order.store, customer: order.customer, amount: order_total)++ updater.update_payment_state++ expect(order.payment_state).to eq('paid')+ end+ end+context 'order is canceled' dobefore { order.update_columns(status: 'canceled') }diff --git a/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb b/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rbindex f8676884f4..4b61876d76 100644--- a/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb+++ b/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb@@ -6,10 +6,60 @@ RSpec.describe Spree::OrderStatusSubscriber doit 'subscribes to every status-bearing record family' doexpect(described_class.subscription_patterns).to include('payment.completed', 'payment.voided', 'refund.created',+ 'store_credit.created', 'store_credit.updated', 'store_credit.deleted','fulfillment.updated', 'return.received')end+ # Credit issued as a refund is the other half of what an order gave back,+ # and nothing else announces it — a claim settled this way writes no refund.+ it 'recomputes the owning order statuses when a refund is issued as store credit' do+ create(:payment, order: order, cart: nil, amount: order.total, status: 'completed')+ credit = create(:store_credit, refunded_order: order, store: order.store, customer: order.customer, amount: order.total)+ order.update_columns(payment_status: 'paid')++ event = Spree::Event.new(name: 'store_credit.created', payload: { 'id' => credit.prefixed_id }, store_id: order.store_id)+ described_class.new.handle(event)++ expect(order.reload.payment_status).to eq('refunded')+ end++ it 'ignores store credit that settles no order' do+ create(:payment, order: order, cart: nil, amount: order.total, status: 'completed')+ order.update_statuses!+ credit = create(:store_credit, store: @default_store, customer: order.customer, amount: order.total)++ event = Spree::Event.new(name: 'store_credit.created', payload: { 'id' => credit.prefixed_id }, store_id: credit.store_id)++ expect { described_class.new.handle(event) }.not_to change { order.reload.payment_status }.from('paid')+ end++ # Amending or withdrawing a credit changes what the order gave back just as+ # issuing it did, and neither writes a refund row to announce it.+ it 'recomputes when a refund credit is amended' do+ create(:payment, order: order, cart: nil, amount: order.total, status: 'completed')+ credit = create(:store_credit, refunded_order: order, store: order.store, customer: order.customer, amount: order.total)+ credit.update!(amount: 1)+ order.update_columns(payment_status: 'refunded')++ event = Spree::Event.new(name: 'store_credit.updated', payload: { 'id' => credit.prefixed_id }, store_id: order.store_id)+ described_class.new.handle(event)++ expect(order.reload.payment_status).to eq('partially_refunded')+ end++ it 'recomputes when a refund credit is withdrawn' do+ create(:payment, order: order, cart: nil, amount: order.total, status: 'completed')+ credit = create(:store_credit, refunded_order: order, store: order.store, customer: order.customer, amount: order.total)+ credit.destroy+ order.update_columns(payment_status: 'refunded')++ event = Spree::Event.new(name: 'store_credit.deleted', payload: { 'id' => credit.prefixed_id }, store_id: order.store_id)+ described_class.new.handle(event)++ expect(order.reload.payment_status).to eq('paid')+ end+it 'recomputes the owning order statuses when a return is received' doreturn_record = create(:approved_return, order: order, store: order.store)Spree::Returns::Receive.call(return_record: return_record)diff --git a/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rbindex d750faa968..a2b98da0f3 100644--- a/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb+++ b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb@@ -51,6 +51,26 @@ RSpec.describe Spree::PaymentSplitSubscriber, :events, type: :model doexpect(seller_order.reload.payment_status).to eq('partially_refunded')end+ # A child order owns no payments, so its share is the only thing that can+ # say what it gave back — and credit never touches the share.+ it 'reports a credit refund against one child and leaves the sibling alone' do+ Spree::Orders::UpdateStatuses.call(order: first_party_order)++ create(:store_credit, refunded_order: seller_order, store: store,+ customer: seller_order.customer, amount: 40)++ expect(seller_order.reload.payment_status).to eq('refunded')+ expect(first_party_order.reload.payment_status).to eq('paid')+ end++ it 'counts a credit refund alongside a gateway refund on the same child' do+ refund!(seller_order, 10)+ create(:store_credit, refunded_order: seller_order, store: store,+ customer: seller_order.customer, amount: 30)++ expect(seller_order.reload.payment_status).to eq('refunded')+ end+it 'totals several refunds on one order rather than counting the last' dorefund!(seller_order, 10)refund!(seller_order, 5)diff --git a/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rbindex 984a82556e..63712bd748 100644--- a/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/claims/lifecycle_spec.rb@@ -110,6 +110,16 @@ RSpec.describe 'Spree::Claims workflows' doexpect(Spree::StoreCredit.find_by(originator: claim)).to be_presentend+ # Credit writes no refund row, so unless it names the order it settles the+ # order goes on reading `paid` on money the customer already has back.+ it 'leaves the order showing what the credit gave back' do+ Spree::Claims::Resolve.call(claim: claim, resolution: 'refund')++ expect(Spree::StoreCredit.find_by(originator: claim).refunded_order).to eq(order)+ expect { order.update_statuses! }.to change { order.reload.payment_status }.+ from('paid').to('partially_refunded')+ end+it 'refuses to refund more than the customer paid' doresult = Spree::Claims::Resolve.call(claim: claim, resolution: 'refund', amount: 10_000)diff --git a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rbindex b96903d920..fe17f481ad 100644--- a/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/exchanges/lifecycle_spec.rb@@ -143,6 +143,9 @@ RSpec.describe 'Spree::Exchanges workflows' doresult = Spree::Exchanges::Fulfill.call(exchange: cheap_exchange, refund_method: 'store_credit')expect(result).to be_success+ # Credit writes no refund row, so naming the order is the only way the+ # order can tell it gave anything back.+ expect(Spree::StoreCredit.find_by(originator: cheap_exchange).refunded_order).to eq(cheap_exchange.order)endendenddiff --git a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rbindex 1748d8fdb8..93dfcc3f37 100644--- a/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb+++ b/spree/core/spec/workflows/spree/returns/lifecycle_spec.rb@@ -206,6 +206,9 @@ RSpec.describe 'Spree::Returns workflows' docredit = Spree::StoreCredit.find_by(originator: return_record)expect(credit).to be_presentexpect(credit.amount).to eq(return_record.refund_total)+ # Credit writes no refund row, so naming the order is the only way the+ # order can tell it gave anything back.+ expect(credit.refunded_order).to eq(return_record.order)endit 'credits only the lines that actually arrived' do