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.

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.md
index 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.rb
index 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 Spree
private
def 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 payments
return 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 >= total
result = 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 Spree
errors.add(:base, e.message)
false
end
+
+ # @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
+ end
end
end
end
diff --git a/spree/core/app/models/concerns/spree/purchase/totals.rb b/spree/core/app/models/concerns/spree/purchase/totals.rb
index 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 Spree
line_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 Spree
def fulfillment_discount
discounts.for_fulfillments.sum(:amount) * -1
end
+
+ 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
+ end
end
end
end
diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rb
index 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
#
# Callbacks
before_create :assign_risk_codes_from_source
- # update the order totals, etc.
- after_save :update_order, unless: -> { capture_on_dispatch }
# invalidate previously entered payments
after_create :invalidate_old_payments
after_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_totals
attr_accessor :source_attributes, :request_env, :capture_on_dispatch
attribute :skip_source_requirement, :boolean, default: false
@@ -158,8 +161,30 @@ module Spree
true
end
- 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')
true
end
@@ -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. That
diff --git a/spree/core/app/models/spree/payment/custom_events.rb b/spree/core/app/models/spree/payment/custom_events.rb
index 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 Spree
def publish_payment_paid_event
publish_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_d
end
end
end
diff --git a/spree/core/app/models/spree/payment/processing.rb b/spree/core/app/models/spree/payment/processing.rb
index 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 Spree
end
end
+ # The bookkeeping assigned above is in memory; void! writes status
+ # through a conditional update, so persist the rest first.
+ save! if changed?
+
case success_state
when :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.rb
index 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::Subscriber
subscribes_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)
end
private
- def order_for(event)
+ def owner_for(event)
resource_class = {
'payment' => Spree::Payment,
'refund' => Spree::Refund,
@@ -32,14 +69,14 @@ module Spree
return 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)
end
end
end
diff --git a/spree/core/app/workflows/spree/payments/void.rb b/spree/core/app/workflows/spree/payments/void.rb
index 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 Spree
def void_at_gateway
# Nothing ever reached the gateway, so there is nothing to release.
if payment.response_code.blank?
- mark_void
+ payment.void!
return
end
@@ -55,41 +55,18 @@ module Spree
end
if 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)
else
payment.gateway_error(response)
end
rescue Spree::Core::GatewayError => error
failure(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')
- end
end
end
end
diff --git a/spree/core/lib/spree/testing_support/factories/order_factory.rb b/spree/core/lib/spree/testing_support/factories/order_factory.rb
index 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 do
end
after(: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))
+ end
order.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.rb
index 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' do
end
end
- # 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 do
stub_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.amount
end
end
diff --git a/spree/core/spec/models/spree/order/payment_spec.rb b/spree/core/spec/models/spree/order/payment_spec.rb
index 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 Spree
expect(payment.reload).to be_completed
end
- context 'processes all checkout payments along with store credits' do
+ context 'processes all checkout payments along with store credits', events: true do
context 'with store credits payment method auto capture turned on' do
it 'order should be paid' do
store_credit = create(:store_credit_payment, amount: 50, order: order)
@@ -82,7 +82,7 @@ module Spree
end
end
- it 'does not go over total for order' do
+ it 'does not go over total for order', events: true do
payment_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.rb
index 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 do
describe 'payment.paid event' do
it '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 do
describe 'order.paid event' do
it '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 do
end
it '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.rb
index 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 do
end
describe '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 do
let(:payment) { create(:payment, order: order, status: 'completed') }
context 'when destroying completed payment' do
it '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)
end
end
context 'when voiding a payment' do
it '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)
end
end
end
@@ -854,10 +857,10 @@ describe Spree::Payment, type: :model do
end
describe '#save' do
- context 'captured payments' do
+ context 'captured payments', events: true do
it 'update order payment total' do
payment = create(:payment, order: order, status: 'completed')
- expect(order.payment_total).to eq payment.amount
+ expect(order.reload.payment_total).to eq payment.amount
end
end
diff --git a/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb b/spree/core/spec/subscribers/spree/order_status_subscriber_spec.rb
index 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 do
expect(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
+ end
end