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: Seller payouts asked for more than the account could send
Łukasz Adamczykf998ee5be54c
diff --git a/spree/core/app/models/spree/payout_provider/base.rb b/spree/core/app/models/spree/payout_provider/base.rbindex 62cbe4702b..a817db491d 100644--- a/spree/core/app/models/spree/payout_provider/base.rb+++ b/spree/core/app/models/spree/payout_provider/base.rb@@ -174,6 +174,23 @@ module Spreeraise NotImplementedErrorend+ # How much of what a seller is owed this provider can move right now.+ #+ # What the ledger says a seller has earned and what their account can+ # actually send are different figures: money credited on fulfilment is+ # only payable once the customer's payment settles. A provider that knows+ # the difference answers it here, and the sweep settles what fits.+ #+ # Nil means the provider does not know or does not care — the built-in+ # one moves no money, so everything owed is payable.+ #+ # @param seller [Spree::Seller]+ # @param currency [String]+ # @return [BigDecimal, nil]+ def available_payout(_seller, _currency)+ nil+ end+# Takes back part of an earning after a refund.## The ledger row is written by core either way — the books stay correctdiff --git a/spree/core/app/workflows/spree/seller_payouts/sweep.rb b/spree/core/app/workflows/spree/seller_payouts/sweep.rbindex 32a1227024..511e6f3fb3 100644--- a/spree/core/app/workflows/spree/seller_payouts/sweep.rb+++ b/spree/core/app/workflows/spree/seller_payouts/sweep.rb@@ -34,6 +34,7 @@ module Spreesuperstep :ensure_payable+ external_step :resolve_available_payoutstep :collect_transfersstep :ensure_worth_sendingrun_hooks :validate@@ -54,13 +55,45 @@ module Spreehalt!(seller) unless seller.payouts_enabled?end+ # What a seller has earned and what their account can send are different+ # figures — money credited on fulfilment is only payable once the+ # customer's payment settles. Asked before anything is claimed, so a+ # provider that refuses to answer costs a period rather than a payout.+ def resolve_available_payout+ @available = provider.available_payout(seller, currency)+ rescue StandardError => e+ Rails.error.report(e, handled: true, context: { seller_id: seller.id, currency: currency }, source: 'spree.core')+ halt!(seller)+ end+def collect_transfers- @transfers = seller.seller_transfers.unsettled.where(currency: currency).to_a+ rows = seller.seller_transfers.unsettled.where(currency: currency).order(:created_at, :id).to_a+ halt!(seller) if rows.empty?++ @transfers = payable_within(rows)halt!(seller) if @transfers.empty?@amount = @transfers.sum(&:amount)end+ # Every reversal counts, whatever is available: it is money already taken+ # back, and leaving one out would settle earnings it cancels. Earnings+ # then join oldest first until the next one would not fit, so a payout+ # stays a contiguous period a seller can reconcile rather than a+ # selection made to hit a number.+ def payable_within(rows)+ return rows if @available.nil?++ reversals, earnings = rows.partition { |row| row.amount.negative? }+ running = reversals.sum(&:amount)++ reversals + earnings.take_while do |earning|+ fits = (running + earning.amount) <= @available+ running += earning.amount if fits+ fits+ end+ end+# Below the threshold the balance carries to the next period rather than# being sent — a payout costs the marketplace a fee either way, and a# seller would rather have one meaningful deposit than five trivial ones.diff --git a/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb b/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rbindex 4e1b1718b2..3ac925cd61 100644--- a/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb+++ b/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb@@ -116,6 +116,80 @@ RSpec.describe Spree::SellerPayouts::Sweep do# A payout is created by the sweep and by nothing else, so earnings left# stamped to a failed one would be unreachable — skipped by every later# sweep while the balance still says the seller is owed them.+ # What a seller has earned and what their account can send are different+ # figures: money credited on fulfilment is funded by the customer's payment+ # and only becomes payable once that settles. Asking for the whole balance+ # regardless is how every payout gets refused.+ describe 'when the provider can send less than is owed' do+ def available(amount)+ allow_any_instance_of(Spree::PayoutProvider::System).to receive(:available_payout).and_return(amount)+ end++ it 'settles the oldest earnings that fit' do+ old = earn(40)+ earn(30)+ available(50)++ payout = described_class.call(seller: seller, currency: 'USD').value++ expect(payout.amount).to eq(40)+ expect(payout.transfers).to contain_exactly(old)+ end++ it 'leaves the rest for the next period' do+ earn(40)+ recent = earn(30)+ available(50)+ described_class.call(seller: seller, currency: 'USD')++ expect(seller.seller_transfers.unsettled).to contain_exactly(recent)+ end++ # A reversal is money already taken back. Leaving one out of a batch would+ # settle earnings it cancels, paying the seller for a refunded sale.+ it 'always counts reversals, whatever is available' do+ earning = earn(40)+ reversal = create(:seller_transfer, :reversal, :completed, seller: seller, currency: 'USD', amount: -10,+ reversed_from: earning, order: earning.order)+ available(30)++ payout = described_class.call(seller: seller, currency: 'USD').value++ expect(payout.amount).to eq(30)+ expect(payout.transfers).to contain_exactly(earning, reversal)+ end++ # Nothing has settled yet. Better to wait than to write a payout row a+ # provider is certain to refuse.+ it 'settles nothing when no earning fits' do+ earn(40)+ available(0)++ expect { described_class.call(seller: seller, currency: 'USD') }.+ not_to change { Spree::SellerPayout.count }+ end++ it 'settles everything when the provider names no limit' do+ earn(40)+ earn(30)+ available(nil)++ expect(described_class.call(seller: seller, currency: 'USD').value.amount).to eq(70)+ end++ # A provider that cannot say costs a period, not a payout: settling a+ # smaller batch would under-pay, and asking for everything is the bug.+ it 'settles nothing when the provider cannot say' do+ earn(40)+ allow_any_instance_of(Spree::PayoutProvider::System).to receive(:available_payout).+ and_raise(Spree::Core::AmbiguousGatewayError, 'timed out')++ expect { described_class.call(seller: seller, currency: 'USD') }.+ not_to change { Spree::SellerPayout.count }+ expect(seller.seller_transfers.unsettled.sum(:amount)).to eq(40)+ end+ end+describe 'when the provider will not pay' dobefore doallow_any_instance_of(Spree::PayoutProvider::System).to receive(:pay!).and_raise(StandardError, 'gateway down')diff --git a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rbindex ecb0d6aec5..915a6738f2 100644--- a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb+++ b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb@@ -231,6 +231,35 @@ module SpreeStriperaise Spree::Core::AmbiguousGatewayError, e.messageend+ # What the seller's account can send today, in the currency asked for.+ #+ # A transfer is credited on fulfilment but funded by the customer's charge,+ # so the money reaches the seller's balance only when that charge settles.+ # Asking Stripe is the documented way to know the difference; a payout for+ # more than the available balance is refused outright.+ #+ # Zero when the account holds nothing in this currency — including a+ # cross-border seller whose account settles in its own currency and can+ # therefore never pay out what the ledger denominated the sale in.+ #+ # @return [BigDecimal]+ def available_payout(seller, currency)+ gateway = gateway_for(seller.store)+ account_id = seller.payout_account_reference(self.class)+ raise Spree::Core::GatewayError, 'Seller holds no Stripe account' if account_id.blank?++ balance = Stripe::Balance.retrieve({}, gateway.api_options.merge(stripe_account: account_id))+ wanted = currency.to_s.downcase+ minor = balance.available.select { |entry| entry.currency == wanted }.sum(&:amount)++ Spree::Money::Rounding.from_minor_units(minor, currency)+ rescue *AMBIGUOUS_ERRORS => e+ # The sweep must not read silence as "nothing to send" and settle a+ # smaller batch than the seller is owed, nor as "no limit" and ask for+ # everything again. Neither is knowable, so nothing is paid this period.+ raise Spree::Core::AmbiguousGatewayError, e.message+ end+# Pulls a seller's money back after a refund.## Ledger-only in open source: the row is written either way, so the booksdiff --git a/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rbindex 5cf77aadb2..4194d2a4b6 100644--- a/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb+++ b/spree/providers/stripe/spec/models/spree_stripe/payout_provider_spec.rb@@ -287,6 +287,59 @@ RSpec.describe SpreeStripe::PayoutProvider do# to arrive — an endpoint never registered, a delivery dropped. A seller who# has finished onboarding must not be left looking at a checklist that says# they have not while Stripe is ready to pay them.+ # A transfer is credited on fulfilment but funded by the customer's charge,+ # so the money reaches the seller only when that charge settles. Stripe+ # refuses a payout for more than the balance holds, so the sweep has to ask.+ describe '#available_payout' do+ def balance(entries)+ Stripe::StripeObject.construct_from(+ available: entries.map { |currency, amount| { currency: currency, amount: amount } }+ )+ end++ it 'reports what the account can send, in major units' do+ allow(Stripe::Balance).to receive(:retrieve).and_return(balance('usd' => 30_269))++ expect(described_class.new.available_payout(seller, 'USD')).to eq(302.69)+ end++ it 'asks as the connected account, since it is their balance' do+ expect(Stripe::Balance).to receive(:retrieve).+ with(anything, hash_including(stripe_account: 'acct_seller')).+ and_return(balance('usd' => 1_000))++ described_class.new.available_payout(seller, 'USD')+ end++ it 'sums the parts a balance is split into' do+ allow(Stripe::Balance).to receive(:retrieve).and_return(balance([['usd', 600], ['usd', 400]]))++ expect(described_class.new.available_payout(seller, 'USD')).to eq(10)+ end++ # The cross-border case: a GB account settles in GBP, so a ledger+ # denominated in USD has nothing that account can send.+ it 'reports nothing for a currency the account does not hold' do+ allow(Stripe::Balance).to receive(:retrieve).and_return(balance('gbp' => 12_254))++ expect(described_class.new.available_payout(seller, 'USD')).to eq(0)+ end++ it 'refuses to guess when Stripe cannot be reached' do+ allow(Stripe::Balance).to receive(:retrieve).and_raise(Stripe::APIConnectionError, 'timed out')++ expect { described_class.new.available_payout(seller, 'USD') }.+ to raise_error(Spree::Core::AmbiguousGatewayError)+ end++ it 'refuses a seller with no account rather than reporting zero' do+ seller.external_references.destroy_all++ expect { described_class.new.available_payout(seller.reload, 'USD') }.+ to raise_error(Spree::Core::GatewayError)+ end+ end+describe '#onboarded?' dodef stub_account(payouts_enabled:)allow(Stripe::Account).to receive(:retrieve).and_return(