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
Close the gaps a shared payment leaves in the paths that touch it
Damian Legawiec98c987c30f6e
diff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex 4f97fc0e50..fb73807daa 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -785,14 +785,27 @@ module Spreebegincapture_at_gateway(payment, bounded)rescue StandardError- # The money never moved, so the claim must not stand.- split.with_lock { split.update!(captured_amount: split.captured_amount - bounded) }+ # Released only when the money truly never moved. The capture workflow+ # keeps working after the charge commits — it authorizes the remainder+ # of a partially captured payment — so a failure at that point is not a+ # failure to capture, and giving the claim back would let this order+ # draw the same money again.+ release_share(split, bounded) unless payment.reload.completed?raiseendboundedend+ # Hands a claim back after a capture that never happened. Failures here are+ # reported rather than raised: the caller is already raising the reason the+ # capture failed, and losing that to a bookkeeping error would hide it.+ def release_share(split, amount)+ split.with_lock { split.update!(captured_amount: split.captured_amount - amount) }+ rescue StandardError => e+ Rails.error.report(e, handled: true, context: { payment_split_id: split.id }, source: 'spree.core')+ end+# @return [BigDecimal] how much of the share this parcel may take, marked# as taken; zero when nothing is leftdef claim_share(split, capturable_amount)diff --git a/spree/core/app/models/spree/order_group.rb b/spree/core/app/models/spree/order_group.rbindex 636ba33ed1..663875ad1d 100644--- a/spree/core/app/models/spree/order_group.rb+++ b/spree/core/app/models/spree/order_group.rb@@ -167,6 +167,14 @@ module Spreedef forget_derived_money@rolled_up_totals = nil@payment_total = nil+ # The figures are summed in Ruby off these associations, so dropping the+ # memo alone would recompute from the same stale rows — a payment that+ # settled after they were loaded would go unnoticed, which is the exact+ # case refresh_payment_total! exists to answer.+ return unless persisted?++ association(:payments).reset+ association(:orders).resetend# @return [BigDecimal] still to collect across the whole checkout@@ -179,6 +187,18 @@ module Spreetotal.positive? && payment_total >= totalend+ # The gift card this checkout was paid with, if any.+ #+ # A group holds no card of its own — the children carry it, each copied+ # from the one cart — so it answers with theirs. A payment method asks its+ # owner this when deciding whether it may be used, and the owner of a+ # grouped payment is this record.+ #+ # @return [Spree::GiftCard, nil]+ def gift_card+ orders.filter_map(&:gift_card).first+ end+# A group only ever exists because a checkout finished, so it is completed# by construction. Store-credit reporting asks, to tell what was applied# from what could still be.diff --git a/spree/core/app/models/spree/payment/custom_events.rb b/spree/core/app/models/spree/payment/custom_events.rbindex 3fe236d80e..2de0c7ad94 100644--- a/spree/core/app/models/spree/payment/custom_events.rb+++ b/spree/core/app/models/spree/payment/custom_events.rb@@ -60,8 +60,23 @@ module Spreechild = split.ordernext if child.nil? || child.total.to_d <= 0- settled = child.payment_splits.sum { |row| row.captured_amount - row.refunded_amount }- child.publish_event('order.paid') if settled >= child.total.to_d+ child.publish_event('order.paid') if settled_for(child) >= child.total.to_d+ end+ end++ # What a child has settled, counting this payment's share as taken.+ #+ # This runs before payment.completed reaches the subscriber that marks+ # the shares captured, so the column still reads zero for the payment+ # that just settled — asking it would decide no child had been paid.+ # Its share is therefore counted from what it authorised, and the other+ # payments from what they have actually drawn.+ #+ # @return [BigDecimal]+ def settled_for(child)+ child.payment_splits.sum do |row|+ taken = row.payment_id == id ? row.authorized_amount : row.captured_amount+ taken - row.refunded_amountendendenddiff --git a/spree/core/app/models/spree/refund.rb b/spree/core/app/models/spree/refund.rbindex 7906c2d7e8..23ba540754 100644--- a/spree/core/app/models/spree/refund.rb+++ b/spree/core/app/models/spree/refund.rb@@ -31,6 +31,7 @@ module Spreevalidates :amount, numericality: { greater_than: 0, allow_nil: true }endvalidate :amount_is_less_than_or_equal_to_allowed_amount, on: :create, if: :amount+ validate :order_is_covered_by_payment, on: :createattr_reader :response@@ -65,9 +66,12 @@ module Spree# Returns true if the refund is editable.#+ # Read through the refund's own order: a payment shared by a split checkout+ # belongs to no single order, so asking the payment would answer nil.+ ## @return [Boolean]def editable?- !payment.order.canceled?+ order.present? && !order.canceled?end# Credits the refund back at the gateway — the money movement, called@@ -99,6 +103,23 @@ module Spreeself.order_id ||= payment&.order_idend+ # A refund may only put right an order the payment actually paid for.+ # Without this a caller can name any order: the gateway credits this+ # payment while the totals of an unrelated one are recomputed, and on a+ # shared payment the share that should have recorded the refund is never+ # found.+ def order_is_covered_by_payment+ return if payment.blank? || order_id.blank?++ covered = if payment.grouped?+ payment.payment_splits.exists?(order_id: order_id)+ else+ payment.order_id == order_id+ end++ errors.add(:order, :invalid) unless covered+ end+# return a payment response object if successful or else raise an errordef process!(credit_cents)refund_total_in_cents = calculate_refund_amount(credit_cents)diff --git a/spree/core/app/services/spree/carts/split_by_seller.rb b/spree/core/app/services/spree/carts/split_by_seller.rbindex 6021c96043..a48fe99e44 100644--- a/spree/core/app/services/spree/carts/split_by_seller.rb+++ b/spree/core/app/services/spree/carts/split_by_seller.rb@@ -192,7 +192,13 @@ module Spree# nothing here has to divide anything.def divide_delivery_cost(original, replacement, weights)total_cost = original.cost.to_d- return if total_cost.zero? || weights.sum <= 0+ return if total_cost.zero?++ # Both halves worth nothing — a free sample boxed with paid goods —+ # still has to divide the charge, or the cost stays whole on each and+ # the customer is billed for delivery twice. Splitting it evenly is+ # the only honest answer when value cannot say.+ weights = [1, 1] if weights.sum <= 0shares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(to_minor_units(total_cost), weights)diff --git a/spree/core/app/services/spree/order_groups/allocate_payments.rb b/spree/core/app/services/spree/order_groups/allocate_payments.rbindex 70ed0ad678..9bf752e544 100644--- a/spree/core/app/services/spree/order_groups/allocate_payments.rb+++ b/spree/core/app/services/spree/order_groups/allocate_payments.rb@@ -24,10 +24,15 @@ module SpreeApplicationRecord.transaction doclaim_payments(group)- weights = orders.map { |order| Spree::Money::Rounding.to_minor_units(order.total, group.currency) }+ # What each child still needs covering. Payments draw this down as+ # they are allocated, so several payments cannot each round in the+ # same direction and leave one child a penny over and another under —+ # every child ends up with exactly its own total.+ outstanding = orders.map { |order| Spree::Money::Rounding.to_minor_units(order.total, group.currency) }group.payments.reload.each do |payment|- allocate(payment, orders, weights)+ taken = allocate(payment, orders, outstanding)+ outstanding = outstanding.each_with_index.map { |amount, index| amount - taken[index] }endend@@ -59,12 +64,17 @@ module Spree# every child of a fully paid checkout as merely authorised. So a# completed payment's shares are born captured, and one still pending is# captured later, as each seller dispatches.- def allocate(payment, orders, weights)+ #+ # @param outstanding [Array<Integer>] what each child still needs, in+ # minor units, so this payment covers what is left rather than+ # re-dividing the whole basket+ # @return [Array<Integer>] what each child took from this payment+ def allocate(payment, orders, outstanding)# A basket worth nothing — fully discounted, wholly gift-carded — has# nothing to divide by. Every child still gets a share saying so,# rather than none at all, so each reads as settled instead of waiting# on money that was never owed.- weights = Array.new(orders.size, 1) if weights.sum <= 0+ weights = outstanding.sum.positive? ? outstanding : Array.new(orders.size, 1)currency = payment.currencyshares = Spree::Adjusters::LargestRemainder.largest_remainder_shares(@@ -82,6 +92,8 @@ module Spreesplit.captured_amount = captured ? share : 0split.save!end++ sharesendenddiff --git a/spree/core/app/subscribers/spree/payment_split_subscriber.rb b/spree/core/app/subscribers/spree/payment_split_subscriber.rbindex 1f2940f0a6..07e1ad8941 100644--- a/spree/core/app/subscribers/spree/payment_split_subscriber.rb+++ b/spree/core/app/subscribers/spree/payment_split_subscriber.rb@@ -31,9 +31,13 @@ module Spreereturn if split.nil?# Recomputed from the refunds rather than incremented, so a replayed- # event cannot count the same money twice.- refunded = Spree::Refund.where(payment_id: refund.payment_id, order_id: order.id).sum(:amount)- split.update!(refunded_amount: refunded)+ # event cannot count the same money twice — and read and written under+ # the row's lock, so two refunds landing together cannot each total the+ # rows before the other's has committed.+ split.with_lock do+ refunded = Spree::Refund.where(payment_id: refund.payment_id, order_id: order.id).sum(:amount)+ split.update!(refunded_amount: refunded)+ end# Deliberately re-derived here even though OrderStatusSubscriber also# answers refund.created: subscriber order is not guaranteed, and a@@ -50,10 +54,17 @@ module Spreereturn if payment.nil? || !payment.grouped?payment.payment_splits.includes(:order).each do |split|- next if split.captured_amount >= split.authorized_amount+ # Read and written under the row's lock, so a dispatch capturing the+ # same share at the same moment cannot be overwritten by the figure+ # this one read before it.+ settled = split.with_lock do+ next false if split.captured_amount >= split.authorized_amount++ split.update!(captured_amount: split.authorized_amount)+ true+ end- split.update!(captured_amount: split.authorized_amount)- Spree::Orders::UpdateStatuses.call(order: split.order) if split.order+ Spree::Orders::UpdateStatuses.call(order: split.order) if settled && split.orderendendenddiff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rbindex bd3788a707..e8b0bac0b8 100644--- a/spree/core/app/workflows/spree/carts/complete.rb+++ b/spree/core/app/workflows/spree/carts/complete.rb@@ -392,13 +392,17 @@ module Spreefailure(cart, code: 'split_failed', message: result.error) if result.failure?@order_group = result.value- @order = order_group.orders.first+ # Ordered, because which child comes first decides which one carries+ # the confirmation email — that must not depend on how the rows come+ # back.+ @order = order_group.orders.order(:id).firstenddef allocate_payment_splitsreturn if order_group.nil?- Spree::OrderGroups::AllocatePayments.call(group: order_group)+ result = Spree::OrderGroups::AllocatePayments.call(group: order_group)+ failure(cart, code: 'split_failed', message: result.error) if result.failure?end# Places what the checkout produced — the children of a split, or the onediff --git a/spree/core/app/workflows/spree/carts/recalculate_totals.rb b/spree/core/app/workflows/spree/carts/recalculate_totals.rbindex 29d2f6f6c0..9bdeb298e5 100644--- a/spree/core/app/workflows/spree/carts/recalculate_totals.rb+++ b/spree/core/app/workflows/spree/carts/recalculate_totals.rb@@ -95,11 +95,29 @@ module Spree# thresholds, free shipping) reads these attributes, so they must# reflect the current line items — not the previous recalculation.def refresh_money_inputs- cart.payment_total = cart.payments.completed.includes(:refunds).inject(0) { |sum, payment| sum + payment.amount - payment.refunds.sum(:amount) }+ cart.payment_total = paid_so_farcart.item_total = cart.line_items.to_a.sum(&:amount)cart.delivery_total = cart.fulfillments.to_a.sum(&:cost)end+ # What has actually been paid towards this record.+ #+ # An order placed in a split checkout owns no payments — the customer+ # paid once, against the group — so its position is the sum of its+ # shares. Reading its own payments would persist nothing paid and report+ # the whole total as outstanding.+ #+ # @return [BigDecimal]+ def paid_so_far+ if cart.is_a?(Spree::Order) && cart.grouped?+ return cart.payment_splits.to_a.sum(&:net_captured_amount)+ end++ cart.payments.completed.includes(:refunds).inject(0) do |sum, payment|+ sum + payment.amount - payment.refunds.sum(:amount)+ end+ end+def refresh_grand_totalcart.total = cart.item_total + cart.delivery_total + cart.adjustment_totalenddiff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rbindex 7062e4e4c4..273a418e95 100644--- a/spree/core/app/workflows/spree/orders/cancel.rb+++ b/spree/core/app/workflows/spree/orders/cancel.rb@@ -138,6 +138,17 @@ module Spreeendend+ # What this order has actually been paid. An order placed in a split+ # checkout holds no payments of its own — the customer paid once, against+ # the group — so its position is the sum of its shares.+ #+ # @return [BigDecimal]+ def amount_paid+ return order.payment_total unless order.grouped?++ order.payment_splits.sum(&:net_captured_amount)+ end+# Canceling one order of a split checkout gives back that order's money# and nothing else: the payment is shared, so voiding it would release# the siblings' authorization too and un-pay sellers who are still@@ -150,24 +161,20 @@ module Spree# and being wrong about it releases an authorization a seller is still# relying on. Writing the share down leaves the payment voidable by# whoever cancels last, which reaches the same end without the risk.- # What this order has actually been paid. An order placed in a split- # checkout holds no payments of its own — the customer paid once, against- # the group — so its position is the sum of its shares.#- # @return [BigDecimal]- def amount_paid- return order.payment_total unless order.grouped?-- order.payment_splits.sum(&:net_captured_amount)- end-+ # Store credit and gift cards are refunded like any other share rather+ # than voided: a void releases a whole payment, which on a shared one is+ # the siblings' money too. The credit comes back to the customer either+ # way, and the refund path is the one that can return a part.def settle_grouped_paymentsremaining = @amount_to_refundorder.payment_splits.includes(:payment).each do |split|# Release what this order had reserved but never drew, always — the- # authorization is no longer for anything.- split.update!(authorized_amount: split.captured_amount)+ # authorization is no longer for anything. Under the row's lock, so+ # a dispatch claiming the same share concurrently either draws before+ # the release or finds nothing left.+ split.with_lock { split.update!(authorized_amount: split.captured_amount) }# Give money back only when the caller asked for it, and only up to# what they asked for, exactly as the ungrouped path does.diff --git a/spree/core/spec/services/spree/order_groups/allocate_payments_spec.rb b/spree/core/spec/services/spree/order_groups/allocate_payments_spec.rbnew file mode 100644index 0000000000..4326dd69d2--- /dev/null+++ b/spree/core/spec/services/spree/order_groups/allocate_payments_spec.rb@@ -0,0 +1,89 @@+require 'spec_helper'++RSpec.describe Spree::OrderGroups::AllocatePayments do+ let(:store) { @default_store }+ let(:seller) { create(:seller, :approved, store: store) }+ let(:group) { create(:order_group, store: store) }++ def payment_for(amount, status: 'completed')+ create(:payment, order: nil, cart: nil, order_group: group, amount: amount, status: status)+ end++ def shares_by_order+ group.orders.order(:id).map { |order| order.payment_splits.sum(:authorized_amount) }+ end++ # Totals that do not divide evenly, paid by two payments that likewise do+ # not. Each payment rounding on its own would hand one child a penny too+ # many and another a penny too few, so one reads overcharged and another+ # underpaid even though the group took exactly what it was owed.+ describe 'several payments against totals that do not divide evenly' do+ let!(:orders) do+ [BigDecimal('33.33'), BigDecimal('33.33'), BigDecimal('33.34')].map do |total|+ create(:order, store: store, order_group: group, seller: seller, total: total)+ end+ end++ before do+ payment_for(50)+ payment_for(50)+ described_class.call(group: group)+ end++ it 'gives each child exactly its own total' do+ expect(shares_by_order).to eq([BigDecimal('33.33'), BigDecimal('33.33'), BigDecimal('33.34')])+ end++ it 'shares out every penny the customer paid' do+ expect(Spree::PaymentSplit.sum(:authorized_amount)).to eq(100)+ end+ end++ describe 'one payment' do+ let!(:orders) do+ [BigDecimal('40'), BigDecimal('60')].map do |total|+ create(:order, store: store, order_group: group, total: total)+ end+ end++ before do+ payment_for(100)+ described_class.call(group: group)+ end++ it 'splits it by what each child is worth' do+ expect(shares_by_order).to eq([BigDecimal('40'), BigDecimal('60')])+ end++ it 'records a completed payment as captured' do+ expect(Spree::PaymentSplit.sum(:captured_amount)).to eq(100)+ end+ end++ describe 'a pending payment' do+ let!(:order) { create(:order, store: store, order_group: group, total: 25) }++ before do+ payment_for(25, status: 'pending')+ described_class.call(group: group)+ end++ it 'authorises the share without capturing it' do+ split = order.payment_splits.sole++ expect(split.authorized_amount).to eq(25)+ expect(split.captured_amount).to eq(0)+ end+ end++ describe 'replaying' do+ let!(:order) { create(:order, store: store, order_group: group, total: 25) }++ it 'writes each share once' do+ payment_for(25)+ described_class.call(group: group)++ expect { described_class.call(group: group.reload) }.not_to change { Spree::PaymentSplit.count }+ end+ end+enddiff --git a/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rbindex 3bfb90a604..3ec9a18fee 100644--- a/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb+++ b/spree/core/spec/subscribers/spree/payment_split_subscriber_spec.rb@@ -58,6 +58,28 @@ RSpec.describe Spree::PaymentSplitSubscriber, :events, type: :model doexpect(seller_split.reload.refunded_amount).to eq(15)end+ # order.paid is public webhook API, and it is published from the payment's+ # own after_commit — which runs before the subscriber marks the shares+ # captured, so the figure it reads has to count this payment's share itself.+ it 'declares each child paid when the shared payment settles' do+ pending_payment = create(:payment, order: nil, cart: nil, order_group: group,+ amount: 100, status: 'pending')+ create(:payment_split, payment: pending_payment, order: seller_order, authorized_amount: 40)+ create(:payment_split, payment: pending_payment, order: first_party_order, authorized_amount: 60)+ seller_split.destroy!+ first_party_split.destroy!++ published = []+ allow(Spree::Events).to receive(:publish).and_wrap_original do |original, name, *rest|+ published << name+ original.call(name, *rest)+ end++ pending_payment.complete!++ expect(published.count { |name| name == 'order.paid' }).to eq(2)+ end+it 'leaves an ungrouped order alone' doplain_order = create(:order, store: store, total: 20)plain_payment = create(:payment, order: plain_order, amount: 20, status: 'completed')