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
Let the order learn about payments from events, not a save callback (#14469)
Damian Legawiec13b951b0b81e
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 671a862852..fe0d697df7 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,13 @@+## 2026-08-19: A payment settling refreshes the payment side only, through events++**Context:** `Payment#update_order` (an `after_save` callback) wrote `payment_total` with `update_column` and called `update_statuses!` inline, while `Carts::RecalculateTotals` carried the identical formula and `OrderStatusSubscriber` was already designated the sole status trigger. Measured with events enabled: one capture recomputed the order **four times** (callback + `payment.updated` + `payment.completed` + `payment.captured`). None of it was visible to the suite, because `Spree::Events.enabled?` is false in the test environment — the callback was doing all the work there, so nothing failed.++**Decision:** The callback is gone (deprecated shell until 7.0). Payment changes reach the order through events only. The subscriber re-sums **the payment side alone** via a new `Spree::Purchase::Totals#refresh_payment_total!` (shared by Cart and Order) — deliberately *not* the full totals workflow, which re-derives item and delivery money and would overwrite figures a caller set; the retired callback's own comment ("a payment settling moves only the payment side of the ledger") was right and an earlier attempt at this ignored it. `payment.captured` is skipped as the companion of `payment.completed`. Destruction keeps a dedicated `after_destroy`: `Spree::Payment` is not paranoid, so the row is gone when `payment.deleted` lands and its payload carries no owner — nothing can lead the subscriber back. Carts get the money refresh but no status update (they have no status columns).++**Rejected:** deduplicating per (order, request) — it silently swallowed the second settlement of a mixed-tender checkout, leaving `payment_total` at 0; skipping the settling save's own `payment.updated` — the payload cannot distinguish it from a genuine later edit, and skipping the wrong one leaves the order stale, so two cheap recomputations beat one missed; moving the callback's work into `Payments::Create` — three of the four payment-creating paths bypass that service.++**Consequences:** a capture recomputes twice (down from four). Callers must `reload` before reading `payment_total`: the subscriber writes through its own instance, so an in-memory copy goes stale — the batch loop's break guard re-reads that one column for this reason. Three latent bugs surfaced once specs ran with events on: the `order_ready_to_ship` factory produced `payment_state: 'paid'` with `payment_total: 0` (it had relied on the callback), `Payment::CustomEvents` called `order.paid?` on cart-owned payments where `order` is nil, and the break guard read a stale attribute. New specs assert the recomputation count with `events: true` so a re-added writer fails loudly.+## 2026-08-18: Payment flows leave the model — workflows implement, shells delegate**Context:** After the machine removal, `Payments::Capture` and `Payments::Void` were thin wrappers: guards and hooks in the workflow, the actual six-step choreography (`capture!` — gateway call, lock, recheck, capture event, split, remainder) opaque inside `Payment::Processing`. Mapping the callers showed the hook contract had holes: dispatch capture (`Fulfillment`) and order-cancel settlement called the model verbs directly, so a fraud hold on `payments.capture.validate` vetoed an admin capture but not a dispatch capture, and `payment.captured` fired for one and not the other. Checkout had no workflow at all. Review also confirmed two TOCTOU races (raised by coderabbit on #14460, verified real and **pre-dating the branch** — machine guards were in-memory checks over unconditional saves, and the machine allowed `completed → processing`): a stale instance could resurrect a settled payment and re-drive the gateway, and racing session writers could both pass a transition guard and double-publish.diff --git a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb b/spree/core/app/models/concerns/spree/purchase/payment_processing.rbindex ca68f9c51b..a883b44e11 100644--- a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb+++ b/spree/core/app/models/concerns/spree/purchase/payment_processing.rb@@ -61,15 +61,20 @@ module Spreeprivatedef process_payments_with(action)- # Don't run if there is nothing to pay.- return if payment_total >= total+ # Don't run if there is nothing to pay. Read from the database, not+ # the in-memory attribute: settlements land through the order status+ # subscriber, which holds its own instance of this record, so the+ # attribute here goes stale as soon as anything settles. Only that+ # column is read — reloading the whole record would discard in-memory+ # state the caller set.+ return if settled_payment_total >= total# Don't run if there are authorized paymentsreturn if pending_payments.any? && unprocessed_payments.empty?# Never complete without a successfully processed payment.raise Spree::Core::GatewayError, Spree.t(:no_payment_found) if unprocessed_payments.empty?unprocessed_payments.each do |payment|- break if payment_total >= total+ break if settled_payment_total >= totalresult = Spree.payment_process_workflow.call(payment: payment, action: action)raise Spree::Core::GatewayError, result.error.value.to_s if result.failure?@@ -78,6 +83,11 @@ module Spreeerrors.add(:base, e.message)falseend++ # @return [BigDecimal] payment_total as it stands in the database+ def settled_payment_total+ persisted? ? self.class.where(id: id).pick(:payment_total).to_d : payment_total.to_d+ endendendenddiff --git a/spree/core/app/models/concerns/spree/purchase/totals.rb b/spree/core/app/models/concerns/spree/purchase/totals.rbindex 3743a052f6..7049bc4905 100644--- a/spree/core/app/models/concerns/spree/purchase/totals.rb+++ b/spree/core/app/models/concerns/spree/purchase/totals.rb@@ -10,6 +10,31 @@ module Spreeline_items.sum(:quantity)end+ # Re-sums what the customer has actually paid, and nothing else. A+ # payment settling moves only the payment side of the ledger — item+ # and delivery money is the totals workflow's business, and+ # re-deriving it here would overwrite figures a caller set+ # deliberately.+ #+ # Shared by Cart and Order: both carry payment_total, and payments+ # settle on a cart during checkout.+ #+ # @return [BigDecimal] the persisted payment_total+ def refresh_payment_total!+ # One atomic statement: the sum and the write have to be a single+ # step, or two handlers settling different payments interleave and+ # the older one writes its smaller total last, leaving the record+ # short-paid with no further event coming to correct it.+ #+ # Deliberately not with_lock, which refuses a record carrying+ # unsaved changes — callers legitimately hold dirty attributes while+ # a payment is destroyed (cart teardown, order merging), and this+ # must never disturb their in-memory state.+ settled = settled_payments_arel+ self.class.where(id: id).update_all(payment_total: settled)+ self.payment_total = self.class.where(id: id).pick(:payment_total)+ end+# @return [Boolean]def outstanding_balance?outstanding_balance != 0@@ -33,6 +58,44 @@ module Spreedef fulfillment_discountdiscounts.for_fulfillments.sum(:amount) * -1end++ private++ # Completed payments less their refunds, as a scalar subquery so the+ # sum and the write are one statement.+ #+ # @return [Arel::Nodes::Grouping]+ def settled_payments_arel+ payments_table = Spree::Payment.arel_table+ refunds_table = Spree::Refund.arel_table++ settled = payments_table.project(payments_table[:id]).+ where(payments_table[owner_foreign_key].eq(id)).+ where(payments_table[:status].eq('completed'))++ captured = payments_table.project(payments_table[:amount].sum).+ where(payments_table[owner_foreign_key].eq(id)).+ where(payments_table[:status].eq('completed'))++ refunded = refunds_table.project(refunds_table[:amount].sum).+ where(refunds_table[:payment_id].in(settled))++ Arel::Nodes::NamedFunction.new(+ 'COALESCE',+ [+ Arel::Nodes::Subtraction.new(+ Arel::Nodes::NamedFunction.new('COALESCE', [Arel::Nodes::Grouping.new(captured), Arel.sql('0')]),+ Arel::Nodes::NamedFunction.new('COALESCE', [Arel::Nodes::Grouping.new(refunded), Arel.sql('0')])+ ),+ Arel.sql('0')+ ]+ )+ end++ # @return [Symbol] the column payments use to point at this record+ def owner_foreign_key+ is_a?(Spree::Cart) ? :cart_id : :order_id+ endendendenddiff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rbindex 93dea46e87..2a58be7916 100644--- a/spree/core/app/models/spree/payment.rb+++ b/spree/core/app/models/spree/payment.rb@@ -54,12 +54,15 @@ module Spree## Callbacksbefore_create :assign_risk_codes_from_source- # update the order totals, etc.- after_save :update_order, unless: -> { capture_on_dispatch }# invalidate previously entered paymentsafter_create :invalidate_old_paymentsafter_create :create_eligible_credit_event- after_destroy :update_order+ # Every other change reaches the order through payment events, which the+ # order status subscriber answers. Destruction cannot: Payment is not+ # paranoid, so the row is gone by the time payment.deleted lands and its+ # payload carries no owner — nothing can lead the subscriber back to the+ # order, which still has to stop counting that money.+ after_destroy :recalculate_owner_totalsattr_accessor :source_attributes, :request_env, :capture_on_dispatchattribute :skip_source_requirement, :boolean, default: false@@ -158,8 +161,30 @@ module Spreetrueend- def void!- update!(status: 'void')+ # The single void writer. A compare-and-swap rather than a plain save:+ # of two racing voids only the one whose update moves the row publishes+ # payment.voided, so the loser is an idempotent no-op. Callers that+ # already asked the gateway pass the authorization it returned.+ #+ # @param authorization [String, nil] written only when present — a+ # successful void without one must not null the stored reference+ # @return [Boolean] false when the payment was already void+ def void!(authorization: nil)+ if new_record?+ self.status = 'void'+ self.response_code = authorization if authorization.present?+ save!+ publish_event('payment.voided')+ return true+ end++ updates = { status: 'void', updated_at: Time.current }+ updates[:response_code] = authorization if authorization.present?++ return false unless self.class.where(id: id).where.not(status: 'void').update_all(updates) == 1++ assign_attributes(updates.except(:updated_at))+ clear_attribute_changes(updates.except(:updated_at).keys)publish_event('payment.voided')trueend@@ -463,16 +488,21 @@ module Spree- def update_order- return unless completed? || void? || (owner.is_a?(Spree::Order) && owner.completed?)+ def recalculate_owner_totals+ return if owner.blank?- # A payment settling moves only the payment side of the ledger — never- # re-sum item/adjustment money here.- completed_total = owner.payments.completed.includes(:refunds).sum { |payment| payment.amount - payment.refunds.sum(:amount) }- owner.update_column(:payment_total, completed_total)+ owner.refresh_payment_total!owner.update_statuses! if owner.is_a?(Spree::Order) && owner.completed?end+ # @deprecated The order recomputes itself from payment events —+ # Spree::Orders::UpdateStatuses writes statuses, the totals workflow+ # writes payment_total. Removed in 7.0.+ def update_order+ Spree::Deprecation.warn('Spree::Payment#update_order is deprecated and will be removed in Spree 7.0. The order recomputes from payment events; call owner.recalculate_totals! to force it.')+ owner&.recalculate_totals!+ end+def create_eligible_credit_event# When cancelling an order, a payment with the negative amount# of the payment total is created to refund the customer. Thatdiff --git a/spree/core/app/models/spree/payment/custom_events.rb b/spree/core/app/models/spree/payment/custom_events.rbindex 66e9f467b4..57b8fd87f5 100644--- a/spree/core/app/models/spree/payment/custom_events.rb+++ b/spree/core/app/models/spree/payment/custom_events.rb@@ -26,11 +26,25 @@ module Spreedef publish_payment_paid_eventpublish_event('payment.paid')- publish_order_paid_event if order.paid?++ # order is nil for a cart-owned payment — checkout is still in+ # flight, so there is no order to declare paid yet.+ return if order.nil?++ # Derived from the payment rows rather than order.paid?, which reads+ # payment_total — a column written by the order status subscriber on+ # the payment.completed event that has not been dispatched yet when+ # this after_commit runs. Reading it here (cached or reloaded) sees+ # the pre-settlement figure and the order is never declared paid.+ order.publish_event('order.paid') if order_settled_in_full?end- def publish_order_paid_event- order.publish_event('order.paid')+ # @return [Boolean]+ def order_settled_in_full?+ return false unless order.total.to_d.positive?++ settled = order.payments.completed.includes(:refunds).sum { |payment| payment.amount - payment.refunds.sum(:amount) }+ settled >= order.total.to_dendendenddiff --git a/spree/core/app/models/spree/payment/processing.rb b/spree/core/app/models/spree/payment/processing.rbindex 82502d9828..fdda78da6b 100644--- a/spree/core/app/models/spree/payment/processing.rb+++ b/spree/core/app/models/spree/payment/processing.rb@@ -113,6 +113,10 @@ module Spreeendend+ # The bookkeeping assigned above is in memory; void! writes status+ # through a conditional update, so persist the rest first.+ save! if changed?+case success_statewhen :complete then complete!when :pend then pend!diff --git a/spree/core/app/subscribers/spree/order_status_subscriber.rb b/spree/core/app/subscribers/spree/order_status_subscriber.rbindex d35d7838de..d995a399ce 100644--- a/spree/core/app/subscribers/spree/order_status_subscriber.rb+++ b/spree/core/app/subscribers/spree/order_status_subscriber.rb@@ -5,6 +5,12 @@ module Spree# (Spree::Orders::UpdateStatuses). Synchronous so API responses right# after a capture/void/fulfill already carry the fresh status. Cart-owned# records are skipped — carts have no status columns.+ #+ # Money-moving payment events additionally re-sum payment_total through+ # the totals workflow, which is the only writer of that column. A payment+ # save used to do both itself in an after_save callback; the callback and+ # these events overlapped, so one capture recomputed the order four+ # times.class OrderStatusSubscriber < Spree::Subscribersubscribes_to 'payment.created', 'payment.updated', 'payment.deleted','payment.completed', 'payment.captured', 'payment.voided',@@ -13,16 +19,47 @@ module Spree'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.+ MONEY_EVENTS = %w[+ payment.created payment.updated payment.deleted payment.completed+ payment.voided refund.created refund.updated+ return.refunded+ ].freeze++ # payment.captured always accompanies payment.completed for the same+ # settlement — the order changed once, so it is answered once. The+ # remaining overlap (payment.updated is the settling save's own+ # after_commit) is left alone deliberately: the payload cannot tell an+ # accompanying update from a genuine later edit of a completed payment,+ # and skipping the wrong one would leave the order stale. Two cheap+ # recomputations beat a missed one.+ #+ # Keyed on the event, never on the order: two payments settling in one+ # request (mixed tender) are two real settlements and must both count.+ SETTLEMENT_COMPANIONS = %w[payment.captured].freeze+def handle(event)- order = order_for(event)- return unless order+ return if event.name.in?(SETTLEMENT_COMPANIONS)++ owner = owner_for(event)+ return if owner.nil?++ # Only the payment side is re-summed, before statuses derive from it+ # (payment_status reads payment_total). Deliberately not the full+ # totals workflow: a payment settling must not re-derive item and+ # delivery money, which is the totals workflow's business and would+ # overwrite figures the caller set.+ owner.refresh_payment_total! if event.name.in?(MONEY_EVENTS) && owner.respond_to?(:refresh_payment_total!)- order.update_statuses!+ # Carts carry payment_total but no status columns — money still has to+ # be right while checkout is in flight, statuses only exist on orders.+ owner.update_statuses! if owner.is_a?(Spree::Order)endprivate- def order_for(event)+ def owner_for(event)resource_class = {'payment' => Spree::Payment,'refund' => Spree::Refund,@@ -32,14 +69,14 @@ module Spreereturn if resource_class.nil?record = resource_class.find_by_prefix_id(event.payload['id'])- # Deleted records are gone by the time the event lands — nothing to- # resolve; the deletion flows that matter (fulfillment rebuilds) run- # their own recalculation.+ # 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.return if record.nil?- owner = record.try(:owner) || record.try(:order) ||- record.try(:payment)&.try(:owner)- owner.is_a?(Spree::Order) ? owner : nil+ record.try(:owner) || record.try(:order) ||+ record.try(:payment)&.try(:owner)endendenddiff --git a/spree/core/app/workflows/spree/payments/void.rb b/spree/core/app/workflows/spree/payments/void.rbindex 9750f72fde..a4521abbc5 100644--- a/spree/core/app/workflows/spree/payments/void.rb+++ b/spree/core/app/workflows/spree/payments/void.rb@@ -38,7 +38,7 @@ module Spreedef void_at_gateway# Nothing ever reached the gateway, so there is nothing to release.if payment.response_code.blank?- mark_void+ payment.void!returnend@@ -55,41 +55,18 @@ module Spreeendif response.success?- mark_void(authorization: response.authorization)+ # Payment#void! is the compare-and-swap — of two racing voids only+ # one moves the row and publishes. There is no pre-gateway claim+ # here, unlike capture: the gateway is the authority on whether+ # the authorization can still be released, so only the terminal+ # write must never double.+ payment.void!(authorization: response.authorization)elsepayment.gateway_error(response)endrescue Spree::Core::GatewayError => errorfailure(payment, error.message)end-- # A compare-and-swap, like the session transitions: of two racing- # voids only the writer whose update moves the row publishes — the- # loser lands as idempotent success. There is no pre-gateway claim,- # because the gateway is the authority on whether the authorization- # can still be released; only the terminal write must never double.- # The authorization is written only when the gateway returned one —- # a successful void without it must not null the stored reference.- def mark_void(authorization: nil)- if payment.new_record?- payment.status = 'void'- payment.response_code = authorization if authorization.present?- payment.save!- payment.publish_event('payment.voided')- return- end-- updates = { status: 'void', updated_at: Time.current }- updates[:response_code] = authorization if authorization.present?-- claimed = Spree::Payment.where(id: payment.id).where.not(status: 'void')- .update_all(updates) == 1- return unless claimed-- payment.assign_attributes(updates.except(:updated_at))- payment.clear_attribute_changes(updates.except(:updated_at).keys)- payment.publish_event('payment.voided')- endendendenddiff --git a/spree/core/lib/spree/testing_support/factories/order_factory.rb b/spree/core/lib/spree/testing_support/factories/order_factory.rbindex f5af129a2b..090b4f53ac 100644--- a/spree/core/lib/spree/testing_support/factories/order_factory.rb+++ b/spree/core/lib/spree/testing_support/factories/order_factory.rb@@ -116,7 +116,16 @@ FactoryBot.define doendafter(:create) do |order, evaluator|- create(:payment, amount: order.total, order: order, state: 'completed') if evaluator.with_payment+ if evaluator.with_payment+ create(:payment, amount: order.total, order: order, status: 'completed')+ # payment_state above claims the order is paid; payment_total is+ # what the code actually reads (Fulfillments::Fulfill refuses an+ # unpaid order). The order learns this from payment events in+ # real life, and those are disabled in the test environment, so+ # the factory states it directly rather than leaving the two+ # halves disagreeing.+ order.update_column(:payment_total, order.payments.completed.sum(:amount))+ endorder.fulfillments.each do |shipment|shipment.fulfillment_items.update_all state: 'on_hand'diff --git a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rbindex b8075d5a73..37ed2f8bac 100644--- a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb@@ -78,13 +78,17 @@ RSpec.shared_examples 'a payment processing host' doendend- # Regression spec for https://github.com/spree/spree/issues/8148- it 'updates the record with correct payment total' do+ # Regression spec for https://github.com/spree/spree/issues/8148.+ # events: true — the record learns its payment_total from payment+ # events now, and they are disabled by default in the test environment.+ it 'updates the record with correct payment total', events: true dostub_store_preferences(capture_method: 'checkout')record.process_payments!expect(payment).to be_completed- expect(record.payment_total).to eq payment.amount+ # reload: the subscriber that writes payment_total holds its own+ # instance of this record, so the one here does not see the change.+ expect(record.reload.payment_total).to eq payment.amountendenddiff --git a/spree/core/spec/models/spree/order/payment_spec.rb b/spree/core/spec/models/spree/order/payment_spec.rbindex a0197c4fdc..99483e72e6 100644--- a/spree/core/spec/models/spree/order/payment_spec.rb+++ b/spree/core/spec/models/spree/order/payment_spec.rb@@ -24,7 +24,7 @@ module Spreeexpect(payment.reload).to be_completedend- context 'processes all checkout payments along with store credits' do+ context 'processes all checkout payments along with store credits', events: true docontext 'with store credits payment method auto capture turned on' doit 'order should be paid' dostore_credit = create(:store_credit_payment, amount: 50, order: order)@@ -82,7 +82,7 @@ module Spreeendend- it 'does not go over total for order' do+ it 'does not go over total for order', events: true dopayment_1 = create(:payment, amount: 50, order: order)payment_2 = create(:payment, amount: 50, order: order)payment_3 = create(:payment, amount: 50, order: order)diff --git a/spree/core/spec/models/spree/payment/custom_events_spec.rb b/spree/core/spec/models/spree/payment/custom_events_spec.rbindex 3d4e5c1684..42523a1216 100644--- a/spree/core/spec/models/spree/payment/custom_events_spec.rb+++ b/spree/core/spec/models/spree/payment/custom_events_spec.rb@@ -13,7 +13,7 @@ RSpec.describe Spree::Payment::CustomEvents dodescribe 'payment.paid event' doit 'publishes payment.paid when payment state changes to completed' do- allow(order).to receive(:paid?).and_return(false)+ payment.update!(amount: order.total - 1)payment.update!(state: 'completed')@@ -37,7 +37,7 @@ RSpec.describe Spree::Payment::CustomEvents dodescribe 'order.paid event' doit 'publishes order.paid when payment completes and order is fully paid' do- allow(order).to receive(:paid?).and_return(true)+ payment.update!(amount: order.total)payment.update!(state: 'completed')@@ -46,7 +46,7 @@ RSpec.describe Spree::Payment::CustomEvents doendit 'does not publish order.paid when order still has outstanding balance' do- allow(order).to receive(:paid?).and_return(false)+ payment.update!(amount: order.total - 1)payment.update!(state: 'completed')diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rbindex 148077c8a2..0bfa3ea3d7 100644--- a/spree/core/spec/models/spree/payment_spec.rb+++ b/spree/core/spec/models/spree/payment_spec.rb@@ -209,18 +209,21 @@ describe Spree::Payment, type: :model doenddescribe 'Callbacks' do- describe '#update_order' do+ # events: true — the order learns about payment changes through events+ # now, not an after_save callback, and they are disabled by default in+ # the test environment.+ describe 'keeping the order in step', events: true dolet(:payment) { create(:payment, order: order, status: 'completed') }context 'when destroying completed payment' doit 'updates the order' do- expect { payment.destroy }.to change { order.payment_total }.by(-payment.amount)+ expect { payment.destroy }.to change { order.reload.payment_total }.by(-payment.amount)endendcontext 'when voiding a payment' doit 'updates the order' do- expect { payment.void! }.to change { order.payment_total }.by(-payment.amount)+ expect { payment.void! }.to change { order.reload.payment_total }.by(-payment.amount)endendend@@ -854,10 +857,10 @@ describe Spree::Payment, type: :model doenddescribe '#save' do- context 'captured payments' do+ context 'captured payments', events: true doit 'update order payment total' dopayment = create(:payment, order: order, status: 'completed')- expect(order.payment_total).to eq payment.amount+ expect(order.reload.payment_total).to eq payment.amountendenddiff --git a/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb b/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rbindex 1474201e04..f8676884f4 100644--- a/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb+++ b/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb@@ -55,4 +55,48 @@ RSpec.describe Spree::OrderStatusSubscriber doexpect(order.reload.payment_status).to eq('paid')end++ # The order used to be updated from two places at once — an after_save+ # callback on Payment and these events — so one capture recomputed it four+ # times. The whole duplication was invisible because events are disabled in+ # the test environment by default; these run with them on.+ describe 'recomputation count', events: true do+ let(:order) { create(:order_ready_to_ship, store: @default_store) }++ def count_recomputes+ count = 0+ allow_any_instance_of(Spree::Order).to receive(:update_statuses!).and_wrap_original do |method, *args|+ count += 1+ method.call(*args)+ end+ yield+ count+ end++ # Two, not three: payment.captured is skipped as the companion of+ # payment.completed. The remaining pair (completed + the save's own+ # updated) is deliberate — see the subscriber's comment.+ it 'recomputes twice for a capture rather than once per published event' do+ payment = order.payments.first+ payment.update_columns(status: 'pending')++ count = count_recomputes { Spree.payment_capture_workflow.call(payment: payment) }++ expect(count).to eq(2)+ expect(order.reload.payment_status).to eq('paid')+ end++ it 'counts each settlement when two payments settle in one request' do+ cart_order = create(:order_with_line_items, store: @default_store, line_items_count: 1)+ cart_order.update_columns(total: 100, item_total: 100)+ method = create(:check_payment_method, store: @default_store)+ first = create(:payment, order: cart_order, payment_method: method, amount: 60, status: 'pending')+ second = create(:payment, order: cart_order, payment_method: method, amount: 40, status: 'pending')++ first.complete!+ second.complete!++ expect(cart_order.reload.payment_total).to eq(100)+ end+ endend