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
Hold a settlement whose outcome nobody knows instead of retrying it
Damian Legawiec3e3016eb6eaf
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rbindex fcfe055f7a..ff2a3c9099 100644--- a/spree/core/app/models/spree/seller.rb+++ b/spree/core/app/models/spree/seller.rb@@ -234,6 +234,11 @@ module Spree# the rows. Per currency because nothing is ever converted — a seller# trading in two currencies accrues two balances and is paid twice.#+ # Only settlements known to have completed count against it, so one whose+ # outcome was never established still reads as owed. That is the honest+ # answer while nobody knows, and it cannot be paid twice by mistake: those+ # earnings stay claimed by the settlement holding them until it resolves.+ ## @param currency [String]# @return [BigDecimal]def balance(currency)diff --git a/spree/core/app/models/spree/seller_payout.rb b/spree/core/app/models/spree/seller_payout.rbindex 4d89d3b159..17642f3094 100644--- a/spree/core/app/models/spree/seller_payout.rb+++ b/spree/core/app/models/spree/seller_payout.rb@@ -49,7 +49,7 @@ module Spree# transition graph.#include Spree::HasStatus- has_status :pending, :processing, :completed, :failed, default: :pending+ has_status :pending, :processing, :completed, :failed, :unresolved, default: :pending## Scopes@@ -91,6 +91,20 @@ module Spreeendend+ # Records that nobody knows whether this settlement happened, and+ # deliberately keeps its earnings claimed.+ #+ # The opposite of {#fail!} in the one way that matters. Releasing here+ # would let the next sweep assemble the same earnings into a second+ # payout, and a provider's idempotency key only protects a retry for as+ # long as the provider keeps the record — Stripe prunes after a day, so a+ # monthly sweep is well past it. Held instead, the earnings stay out of+ # every later sweep until a person or a webhook settles what actually+ # happened.+ def unresolve!+ update!(status: 'unresolved')+ end+# Hands the earnings back to the next sweep without recording a failure —# for a settlement that never had anything to send.def release_transfersdiff --git a/spree/core/app/workflows/spree/seller_payouts/complete.rb b/spree/core/app/workflows/spree/seller_payouts/complete.rbindex 458b254484..48c08128fa 100644--- a/spree/core/app/workflows/spree/seller_payouts/complete.rb+++ b/spree/core/app/workflows/spree/seller_payouts/complete.rb@@ -46,7 +46,9 @@ module Spreeattributes = { status: 'completed', updated_at: Time.current }attributes[:reference] = reference if reference.present?- claimed = Spree::SellerPayout.where(id: seller_payout.id, status: %w[pending processing]).+ # `unresolved` is claimable too: it is the settlement whose outcome was+ # never known, and this is the answer it was waiting for.+ claimed = Spree::SellerPayout.where(id: seller_payout.id, status: %w[pending processing unresolved]).update_all(attributes)halt!(seller_payout.reload) if claimed.zero?diff --git a/spree/core/app/workflows/spree/seller_payouts/sweep.rb b/spree/core/app/workflows/spree/seller_payouts/sweep.rbindex fcc346b883..d5e02d3fb5 100644--- a/spree/core/app/workflows/spree/seller_payouts/sweep.rb+++ b/spree/core/app/workflows/spree/seller_payouts/sweep.rb@@ -124,6 +124,13 @@ module Spreedef execute_payoutprovider.pay!(payout)+ rescue Spree::Core::AmbiguousGatewayError => e+ # The provider could not say whether the money moved. Its earnings stay+ # claimed so no later sweep can send them again, and the row waits for+ # a person or a webhook to say which way it went.+ payout.unresolve!+ Rails.error.report(e, handled: true, context: { seller_payout_id: payout.id }, source: 'spree.core')+ failure(payout, e.message)rescue StandardError => epayout.fail!Rails.error.report(e, handled: true, context: { seller_payout_id: payout.id }, source: 'spree.core')diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 2d8145af56..ee69f996ee 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -795,6 +795,14 @@ module Spreemodule Coreclass GatewayError < RuntimeError; end++ # The call may or may not have taken effect — a timeout, a dropped+ # connection, anything that leaves the answer at the provider rather than+ # in the response. Distinct from its parent because the safe reaction is+ # the opposite one: a definite failure can be retried, while an unknown+ # outcome must not be, since retrying is how the same money moves twice.+ class AmbiguousGatewayError < GatewayError; end+class DestroyWithOrdersError < StandardError; endendenddiff --git a/spree/core/spec/models/spree/seller_payout_spec.rb b/spree/core/spec/models/spree/seller_payout_spec.rbindex e1fa670192..325cb8ffa4 100644--- a/spree/core/spec/models/spree/seller_payout_spec.rb+++ b/spree/core/spec/models/spree/seller_payout_spec.rb@@ -39,5 +39,34 @@ RSpec.describe Spree::SellerPayout, type: :model doexpect(described_class.owed).to contain_exactly(pending_payout, processing)end++ # It may already have been sent. Counting it as still to send is how the+ # same money goes out twice.+ it 'leaves out one whose outcome nobody knows' do+ create(:seller_payout, seller: seller, status: 'unresolved')++ expect(described_class.owed).to be_empty+ end+ end++ # The opposite of #fail! in the one way that matters: the earnings stay+ # claimed, so no later sweep can assemble them into a second settlement.+ describe '#unresolve!' do+ let(:payout) { create(:seller_payout, seller: seller) }++ it 'keeps the earnings it claimed' do+ transfer = create(:seller_transfer, :completed, seller: seller, payout: payout,+ order: create(:order, store: store, seller: seller))++ payout.unresolve!++ expect(transfer.reload.payout_id).to eq(payout.id)+ end++ it 'records that the outcome is unknown' do+ payout.unresolve!++ expect(payout.reload).to be_unresolved+ endendenddiff --git a/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb b/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rbindex ba79df5b22..4e1b1718b2 100644--- a/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb+++ b/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb@@ -150,6 +150,50 @@ RSpec.describe Spree::SellerPayouts::Sweep doendend+ # A timeout is not a refusal: the provider may have moved the money before+ # the answer was lost. Releasing the earnings here is what would let a later+ # sweep pay them a second time, since an idempotency key only holds for as+ # long as the provider keeps its record.+ describe 'when nobody knows whether the money moved' do+ before do+ earn(40)+ allow_any_instance_of(Spree::PayoutProvider::System).to receive(:pay!).+ and_raise(Spree::Core::AmbiguousGatewayError, 'connection timed out')+ end++ it 'reports the failure' do+ expect(described_class.call(seller: seller, currency: 'USD')).to be_failure+ end++ it 'holds the earnings rather than letting them fall into another payout' do+ described_class.call(seller: seller, currency: 'USD')++ expect(seller.seller_transfers.unsettled).to be_empty+ end++ it 'sends nothing on the next sweep' do+ described_class.call(seller: seller, currency: 'USD')+ allow_any_instance_of(Spree::PayoutProvider::System).to receive(:pay!).and_call_original++ expect { described_class.call(seller: seller.reload, currency: 'USD') }.+ not_to change { Spree::SellerPayout.count }+ end++ it 'leaves the settlement waiting to be resolved' do+ described_class.call(seller: seller, currency: 'USD')++ expect(Spree::SellerPayout.last).to be_unresolved+ end++ # It is not owed — it may already have been sent — and it is not settled+ # either, so it belongs in neither queue until somebody says which.+ it 'stops counting it as money still to send' do+ described_class.call(seller: seller, currency: 'USD')++ expect(Spree::SellerPayout.owed).to be_empty+ end+ end+# A concurrent sweep can claim rows this one counted, leaving it holding# nothing. Asking a provider to move zero is not a settlement.describe 'when another sweep claimed everything first' dodiff --git a/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rbindex aefa0595d6..a8ba6c9067 100644--- a/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb+++ b/spree/providers/stripe/app/models/spree_stripe/gateway/connect.rb@@ -242,8 +242,25 @@ module SpreeStripe# id when it did — an event naming an id we hold no settlement for is# about a payout somebody made outside Spree, and guessing which of our# settlements it meant would complete the wrong one.+ # By Stripe's id first, then by the one we sent with the request.+ #+ # The reference is normally stored the moment the payout is created, but+ # not when the answer to that call was lost — which is exactly the case+ # that most needs the webhook, since nothing else will tell the operator+ # whether the money moved. Stripe echoes our metadata back, so the id we+ # sent identifies the row when the id it assigned is not on file.def find_payout(seller, object)- seller.seller_payouts.find_by(reference: object.id)+ by_reference = seller.seller_payouts.find_by(reference: object.id)+ return by_reference if by_reference++ # A Stripe object raises for a key it does not carry rather than+ # answering nil, and an older payout has no metadata at all.+ return nil unless object.respond_to?(:metadata)++ payout_id = object.metadata['spree_seller_payout_id']+ return nil if payout_id.blank?++ seller.seller_payouts.find_by(id: payout_id, reference: nil)enddef verify_connect_webhook_signature(raw_body, headers)diff --git a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rbindex 12a78c3cbc..7197f79356 100644--- a/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb+++ b/spree/providers/stripe/app/models/spree_stripe/payout_provider.rb@@ -192,6 +192,13 @@ module SpreeStripe# matches on Stripe's own id instead of guessing by amount.seller_payout.update!(reference: payout.id)seller_payout+ rescue Stripe::APIConnectionError, Stripe::IdempotencyError => e+ # Nobody knows whether the money moved. The request may have reached+ # Stripe and created the payout before the answer was lost, so core must+ # not put these earnings back on the pile — the idempotency key stops a+ # retry only while Stripe keeps the record, which is a day, and sweeps+ # run on a merchant's schedule rather than inside one.+ raise Spree::Core::AmbiguousGatewayError, e.messageend# Pulls a seller's money back after a refund.diff --git a/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rbindex 0bd1dcaaa1..80a0ae4538 100644--- a/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb+++ b/spree/providers/stripe/spec/models/spree_stripe/gateway/connect_spec.rb@@ -88,6 +88,50 @@ RSpec.describe SpreeStripe::Gateway::Connect doexpect(payout.reload).to be_pendingend++ # When the answer to the create call was lost, Stripe's id was never+ # stored — and that is the settlement most in need of this event, since+ # nothing else can say whether the money moved. Stripe echoes back the id+ # we sent, so the row is still identifiable.+ context 'when the settlement never recorded Stripe’s id' do+ let!(:unresolved) do+ create(:seller_payout, seller: seller, currency: 'USD', reference: nil, status: 'unresolved')+ end++ before do+ allow(Stripe::Webhook).to receive(:construct_event).and_return(+ stripe_event(+ 'payout.paid',+ { id: 'po_lost', currency: 'usd', amount: 2_000,+ metadata: { 'spree_seller_payout_id' => unresolved.id.to_s } },+ account: 'acct_seller'+ )+ )+ end++ it 'finds it by the id we sent and completes it' do+ gateway.handle_payout_webhook(raw_body, headers)++ expect(unresolved.reload).to be_completed+ end++ it 'writes down the id Stripe assigned it' do+ gateway.handle_payout_webhook(raw_body, headers)++ expect(unresolved.reload.reference).to eq('po_lost')+ end++ # The fallback exists for rows that never got an id. One that has a+ # different id is a different settlement, and matching it by metadata+ # would complete the wrong one.+ it 'leaves a settlement that already holds another id alone' do+ unresolved.update!(reference: 'po_other')++ gateway.handle_payout_webhook(raw_body, headers)++ expect(unresolved.reload).not_to be_completed+ end+ endendcontext 'payout.failed' do@@ -116,6 +160,24 @@ RSpec.describe SpreeStripe::Gateway::Connect doexpect(seller.seller_transfers.unsettled.sum(:amount)).to eq(40)end++ # The settlement whose outcome was never known has been holding its+ # earnings precisely so nothing could send them twice. Stripe saying the+ # money did not move is the definite answer that frees them.+ context 'for a settlement nobody knew the outcome of' do+ let!(:payout) do+ create(:seller_payout, seller: seller, currency: 'USD', reference: 'po_1', status: 'unresolved')+ end++ it 'releases the earnings it was holding' do+ create(:seller_transfer, :completed, seller: seller, payout: payout, amount: 40,+ order: create(:order, store: store, seller: seller))++ gateway.handle_payout_webhook(raw_body, headers)++ expect(seller.seller_transfers.unsettled.sum(:amount)).to eq(40)+ end+ endend# Stripe redelivers on any non-2xx or timeout. Without matching on its owndiff --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 e04ee01f2d..516a5417bc 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@@ -144,6 +144,35 @@ RSpec.describe SpreeStripe::PayoutProvider doexpect { described_class.new.pay!(other) }.to raise_error(Spree::Core::GatewayError)end++ # Stripe may have created the payout before the answer was lost. Core has+ # to hear that the outcome is unknown, because its reaction is the opposite+ # of the one a refusal deserves.+ context 'when the answer is lost on the way back' do+ it 'says so, rather than reporting a refusal' do+ allow(Stripe::Payout).to receive(:create).and_raise(Stripe::APIConnectionError, 'timed out')++ expect { described_class.new.pay!(payout) }.+ to raise_error(Spree::Core::AmbiguousGatewayError)+ end++ # Reusing a key with different parameters means Stripe already holds a+ # payout under it — so something moved, whatever this call thought.+ it 'says the same when Stripe rejects a reused key' do+ allow(Stripe::Payout).to receive(:create).and_raise(Stripe::IdempotencyError, 'key reused')++ expect { described_class.new.pay!(payout) }.+ to raise_error(Spree::Core::AmbiguousGatewayError)+ end+ end++ # A refusal is definite, and core is right to release the earnings for it.+ it 'reports an outright refusal as an ordinary failure' do+ allow(Stripe::Payout).to receive(:create).+ and_raise(Stripe::InvalidRequestError.new('insufficient funds', 'amount'))++ expect { described_class.new.pay!(payout) }.to raise_error(Stripe::InvalidRequestError)+ endend# The column is a cache of what a webhook last said, and a webhook can fail