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.

Stop the retry job resending an earning nobody can account for

Damian Legawiece947ef244d41
diff --git a/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb
index f3fc96dc90..d372170fba 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/sellers_controller.rb
@@ -109,6 +109,15 @@ module Spree
[:users]
end
+ # A checklist kind may ask a payment provider whether a seller can be
+ # paid, which is one network call — fine for one seller, but a page
+ # of them would make the list as slow as the operator's connection.
+ # Marked here rather than inferred from the eager-loaded checklist,
+ # which a single-seller read shares.
+ def collection
+ @marked_collection ||= super.each { |seller| seller.onboarding_requirements_cached = true }
+ end
+
# What the serializer's onboarding progress reads for every seller,
# on the list and on the profile alike: the checklist's kinds look
# at addresses, branding and the seller's own submissions, and the
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb
index 13d5b7099b..a4678a59fb 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/sellers_controller_spec.rb
@@ -61,6 +61,35 @@ RSpec.describe Spree::Api::V3::Admin::SellersController, type: :controller do
end
end
+ # A requirement kind may ask a payment provider whether a seller can be
+ # paid. One call is fine for one seller; a page of them would make the list
+ # as slow as the operator's connection.
+ describe 'asking the payout provider' do
+ before do
+ Spree::SellerRequirements::PayoutAccount.create!(store: store, name: 'Payout account', required: true)
+ end
+
+ it 'is not done per row on the list' do
+ create(:seller, store: store)
+ expect_any_instance_of(Spree::PayoutProvider::System).not_to receive(:onboarded?)
+
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+
+ # Here the operator is looking at exactly this seller, so the answer has
+ # to be the current one — the checklist is eager-loaded either way, which
+ # is why that cannot be the signal.
+ it 'is done for the seller being looked at' do
+ expect_any_instance_of(Spree::PayoutProvider::System).to receive(:onboarded?).at_least(:once).and_return(true)
+
+ get :show, params: { id: seller.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ end
+ end
+
describe 'GET #show' do
it 'returns the seller profile' do
get :show, params: { id: seller.prefixed_id }, as: :json
diff --git a/spree/core/app/jobs/spree/seller_payouts/sweep_due_job.rb b/spree/core/app/jobs/spree/seller_payouts/sweep_due_job.rb
index 11f94393c5..48d60179fc 100644
--- a/spree/core/app/jobs/spree/seller_payouts/sweep_due_job.rb
+++ b/spree/core/app/jobs/spree/seller_payouts/sweep_due_job.rb
@@ -1,78 +1,33 @@
module Spree
module SellerPayouts
- # Settles every seller whose schedule has come round.
+ # Hands every approved seller to a job of their own.
#
- # Scheduled by the host app — daily is right, since the job itself decides
- # who is actually due. A scheduler cannot express "weekly, but per seller,
- # from whenever that seller was last paid", so the interval logic lives
- # here rather than in a cron expression.
+ # Scheduled by the host app — daily is right, since {SweepSellerJob}
+ # decides who is actually due. A scheduler cannot express "weekly, but per
+ # seller, from whenever that seller was last paid", so the interval logic
+ # lives there rather than in a cron expression.
#
- # Deliberately no retry beyond the base job's infrastructure errors: a
- # sweep that half-ran has already claimed its transfers, and re-running is
- # safe only because of that claim, not because the work is repeatable.
+ # This job only fans out. Settling talks to a payment provider, so doing it
+ # inline would hold one worker for the whole marketplace and let a single
+ # slow provider call delay every seller behind it. Enqueued in batches with
+ # plain `ActiveJob.perform_all_later`, which every queue adapter supports —
+ # core must not require a particular one.
class SweepDueJob < ::Spree::BaseJob
queue_as Spree.queues.payouts
+ # How many jobs are handed to the adapter at a time. Enough to make the
+ # round trip worth it, small enough that a marketplace with a hundred
+ # thousand sellers never builds one enormous array.
+ BATCH_SIZE = 1_000
+
def perform
# Store by store, so each seller is reached through the store that owns
- # them — which is what makes the (store, status) index usable, and what
- # the schedule falls back to anyway.
+ # them — which is what makes the (store, status) index usable.
Spree::Store.find_each do |store|
- store.sellers.approved.find_each { |seller| sweep_seller(seller) }
- end
- end
-
- private
-
- # One seller's failure must not end the run for everyone behind them.
- def sweep_seller(seller)
- return if seller.resolved_payouts_schedule_interval == 'manual'
-
- currencies_owed(seller).each do |currency|
- next unless due?(seller, currency)
-
- Spree.seller_payout_sweep_workflow.call(seller: seller, currency: currency)
+ store.sellers.approved.in_batches(of: BATCH_SIZE) do |sellers|
+ ActiveJob.perform_all_later(sellers.ids.map { |id| SweepSellerJob.new(id) })
+ end
end
- rescue StandardError => e
- Rails.error.report(e, handled: true, context: { seller_id: seller.id }, source: 'spree.core')
- end
-
- # Whether enough time has passed since this seller was last settled in
- # this currency. A seller who has never been paid is due as soon as they
- # have earned anything — their first settlement should not wait a whole
- # period.
- #
- # Asked per currency, because settlements are made per currency. Reading
- # the seller's most recent payout across all of them would let an
- # out-of-band settlement in one currency reset the clock for every other
- # — a monthly seller paid early in dollars would have their euro balance
- # skipped for another month.
- def due?(seller, currency)
- # Failed payouts are excluded: one releases its earnings back to the
- # next sweep, so counting it as a settlement would block the very
- # retry it exists to allow — for a whole interval, with the money
- # sitting owed and unsent.
- settled_at = seller.seller_payouts.where(currency: currency).
- where.not(status: 'failed').maximum(:created_at)
- return true if settled_at.nil?
-
- settled_at <= interval_ago(seller.resolved_payouts_schedule_interval)
- end
-
- def interval_ago(interval)
- case interval
- when 'daily' then 1.day.ago
- when 'weekly' then 1.week.ago
- when 'biweekly' then 2.weeks.ago
- else 1.month.ago
- end
- end
-
- # Only the currencies this seller actually has earnings waiting in — a
- # marketplace trading in three currencies should not run three sweeps for
- # a seller who sold in one.
- def currencies_owed(seller)
- seller.seller_transfers.unsettled.distinct.pluck(:currency)
end
end
end
diff --git a/spree/core/app/jobs/spree/seller_payouts/sweep_seller_job.rb b/spree/core/app/jobs/spree/seller_payouts/sweep_seller_job.rb
new file mode 100644
index 0000000000..536ddf8771
--- /dev/null
+++ b/spree/core/app/jobs/spree/seller_payouts/sweep_seller_job.rb
@@ -0,0 +1,70 @@
+module Spree
+ module SellerPayouts
+ # Settles one seller, in every currency they are owed in.
+ #
+ # Its own job rather than a loop inside {SweepDueJob}, because settling a
+ # seller talks to a payment provider: a marketplace with a few thousand of
+ # them would otherwise hold one worker for the whole run, and one slow
+ # provider call would delay every seller queued behind it.
+ #
+ # Deliberately no retry beyond the base job's infrastructure errors: a
+ # sweep that half-ran has already claimed its transfers, and re-running is
+ # safe only because of that claim, not because the work is repeatable.
+ class SweepSellerJob < ::Spree::BaseJob
+ queue_as Spree.queues.payouts
+
+ # @param seller_id [Integer]
+ def perform(seller_id)
+ seller = Spree::Seller.find_by(id: seller_id)
+ return if seller.nil?
+ return if seller.resolved_payouts_schedule_interval == 'manual'
+
+ currencies_owed(seller).each do |currency|
+ next unless due?(seller, currency)
+
+ Spree.seller_payout_sweep_workflow.call(seller: seller, currency: currency)
+ end
+ end
+
+ private
+
+ # Whether enough time has passed since this seller was last settled in
+ # this currency. A seller who has never been paid is due as soon as they
+ # have earned anything — their first settlement should not wait a whole
+ # period.
+ #
+ # Asked per currency, because settlements are made per currency. Reading
+ # the seller's most recent payout across all of them would let an
+ # out-of-band settlement in one currency reset the clock for every other
+ # — a monthly seller paid early in dollars would have their euro balance
+ # skipped for another month.
+ def due?(seller, currency)
+ # Failed payouts are excluded: one releases its earnings back to the
+ # next sweep, so counting it as a settlement would block the very
+ # retry it exists to allow — for a whole interval, with the money
+ # sitting owed and unsent.
+ settled_at = seller.seller_payouts.where(currency: currency).
+ where.not(status: 'failed').maximum(:created_at)
+ return true if settled_at.nil?
+
+ settled_at <= interval_ago(seller.resolved_payouts_schedule_interval)
+ end
+
+ def interval_ago(interval)
+ case interval
+ when 'daily' then 1.day.ago
+ when 'weekly' then 1.week.ago
+ when 'biweekly' then 2.weeks.ago
+ else 1.month.ago
+ end
+ end
+
+ # Only the currencies this seller actually has earnings waiting in — a
+ # marketplace trading in three currencies should not run three sweeps for
+ # a seller who sold in one.
+ def currencies_owed(seller)
+ seller.seller_transfers.unsettled.distinct.pluck(:currency)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rb b/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rb
index 43a0874337..ddb08cdd67 100644
--- a/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rb
+++ b/spree/core/app/jobs/spree/seller_transfers/execute_pending_job.rb
@@ -10,6 +10,11 @@ module Spree
# That distinction matters: a sweep would never reach these rows, because
# it looks for confirmed earnings and a seller whose only rows are pending
# has none, so nothing would prompt it in the one case this exists for.
+ #
+ # It takes the retryable rows — never sent, or refused outright. A transfer
+ # whose outcome the provider could not report is left alone: asking again
+ # is precisely how the same money moves twice, and only a person can say
+ # what actually happened.
class ExecutePendingJob < ::Spree::BaseJob
queue_as Spree.queues.payouts
@@ -20,19 +25,22 @@ module Spree
provider = seller.store.payout_provider_instance
- # `processing` as well as `pending`: a transfer whose provider call
- # raised parks there, and without picking it up again a single network
- # blip would strand that earning for good — it is counted in no
- # balance and collected by no sweep.
- # Earnings only. A reversal parks in `processing` the same way when its
- # own provider call raises, but sending one through `transfer!` would
+ # Earnings only. A reversal is retryable the same way when its own
+ # provider call is refused, but sending one through `transfer!` would
# pay the seller the amount it exists to take back — the row is
# negative and the amount sent is its absolute value.
- seller.seller_transfers.earnings.where(status: %w[pending processing], payout_id: nil).find_each do |transfer|
+ seller.seller_transfers.earnings.retryable.where(payout_id: nil).find_each do |transfer|
provider.transfer!(transfer)
+ rescue Spree::Core::AmbiguousGatewayError => e
+ # The money may already have moved, so this row must not be offered
+ # again: left retryable, the next run would send it a second time,
+ # and an idempotency key stops that only while the provider still
+ # holds its record.
+ transfer.update!(status: 'unresolved')
+ Rails.error.report(e, handled: true, context: { seller_transfer_id: transfer.id }, source: 'spree.core')
rescue StandardError => e
- # One seller's stuck earning must not stop the rest — the row stays
- # pending and the next attempt finds it.
+ # A refusal — the money did not move. One seller's stuck earning must
+ # not stop the rest, and the row stays retryable for the next run.
Rails.error.report(e, handled: true, context: { seller_transfer_id: transfer.id }, source: 'spree.core')
end
end
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index ff2a3c9099..509c0cdd7a 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -357,10 +357,26 @@ module Spree
# @return [Array<Spree::SellerRequirementStatus>]
def onboarding_requirements
@onboarding_requirements ||= Spree::Sellers::Requirements.new(
- self, preloaded: store&.association(:seller_requirements)&.loaded? || false
+ self,
+ preloaded: store&.association(:seller_requirements)&.loaded? || false,
+ cached: onboarding_requirements_cached
).statuses
end
+ # Whether this seller's checklist may answer from what Spree already knows
+ # rather than asking a payment provider. Set by a caller rendering many
+ # sellers at once, where one network call per row is the difference
+ # between a list that loads and one that does not.
+ #
+ # Deliberately not inferred from the checklist being eager-loaded: a
+ # single-seller read shares that preload, and there the operator is
+ # looking at exactly this seller and wants the current answer.
+ attr_writer :onboarding_requirements_cached
+
+ def onboarding_requirements_cached
+ @onboarding_requirements_cached || false
+ end
+
# @return [Hash{Symbol => Integer}] done and total over the whole
# checklist, optional requirements included
def onboarding_progress
diff --git a/spree/core/app/models/spree/seller_requirement.rb b/spree/core/app/models/spree/seller_requirement.rb
index 9c7a507fdd..8c82d7d7f1 100644
--- a/spree/core/app/models/spree/seller_requirement.rb
+++ b/spree/core/app/models/spree/seller_requirement.rb
@@ -168,6 +168,17 @@ module Spree
# never see that. Not overridable for exactly that reason; kinds
# override {#met_by_seller?} instead.
#
+ # Whether this evaluation may answer from what Spree already knows rather
+ # than asking the outside world. Set by `Spree::Sellers::Requirements` for
+ # a listing, where one network call per row is the difference between a
+ # page that loads and one that does not. A kind that never leaves the
+ # database can ignore it; one that calls a provider should read the value
+ # it last recorded instead.
+ #
+ # False everywhere it matters — the two approval gates and a seller's own
+ # page ask for the current answer.
+ attr_accessor :prefer_cached
+
# @param seller [Spree::Seller]
# @return [Boolean]
def satisfied?(seller)
diff --git a/spree/core/app/models/spree/seller_requirements/payout_account.rb b/spree/core/app/models/spree/seller_requirements/payout_account.rb
index 202848fb88..e778aba6ad 100644
--- a/spree/core/app/models/spree/seller_requirements/payout_account.rb
+++ b/spree/core/app/models/spree/seller_requirements/payout_account.rb
@@ -21,13 +21,23 @@ module Spree
# may be dead before the seller clicks it — the panel asks for a fresh one
# at the moment of clicking, through the seller API.
class PayoutAccount < Spree::SellerRequirement
+ # Asked of the provider, since only it knows for certain — except on a
+ # listing, which reads the stamp a webhook last wrote. Otherwise a page
+ # of sellers makes one call to the payment provider per row, and the
+ # operator's list is as slow as their network.
def met_by_seller?(seller)
+ return seller.payouts_enabled? if prefer_cached
+
provider_for(seller).onboarded?(seller)
end
- # Asked of the provider, since only it knows — and its three answers
- # want different words: go and finish, wait, or you have been refused.
+ # Which of the three is true: go and finish, wait, or you have been
+ # refused. Each wants different words, and only the provider knows — so
+ # a listing, which is not asking, says nothing rather than guessing from
+ # the stamp.
def blocker(seller)
+ return nil if prefer_cached
+
provider = provider_for(seller)
state = provider.onboarding_state(seller)
return nil if state.nil?
diff --git a/spree/core/app/models/spree/seller_transfer.rb b/spree/core/app/models/spree/seller_transfer.rb
index c3d21d72e1..0f593068cf 100644
--- a/spree/core/app/models/spree/seller_transfer.rb
+++ b/spree/core/app/models/spree/seller_transfer.rb
@@ -69,6 +69,10 @@ module Spree
#
scope :earnings, -> { where(kind: 'earning') }
scope :reversals_only, -> { where(kind: 'refund_reversal') }
+ # Safe to ask the provider about again: never sent, or refused outright.
+ # Deliberately excludes `unresolved`, where the provider could not say
+ # whether the money moved — asking again is how it moves twice.
+ scope :retryable, -> { with_status('pending', 'processing') }
# Earned and confirmed, but not yet swept into a settlement — what the next
# payout will pick up.
scope :unsettled, -> { completed.where(payout_id: nil) }
diff --git a/spree/core/app/services/spree/sellers/requirements.rb b/spree/core/app/services/spree/sellers/requirements.rb
index 2c0221e143..9088e1af3a 100644
--- a/spree/core/app/services/spree/sellers/requirements.rb
+++ b/spree/core/app/services/spree/sellers/requirements.rb
@@ -21,9 +21,15 @@ module Spree
# should say so — a page of sellers shares one store, so its rows load
# once for all of them — because trusting whatever happens to be
# cached would let a gate measure against a stale checklist.
- def initialize(seller, preloaded: false)
+ # @param cached [Boolean] let a requirement answer from what Spree
+ # already knows instead of asking the outside world. A listing says so:
+ # a kind that checks a payment provider would otherwise make one
+ # network call per row. Never for a gate or a single seller's own
+ # page, where the answer has to be current.
+ def initialize(seller, preloaded: false, cached: false)
@seller = seller
@preloaded = preloaded
+ @cached = cached
end
# The checklist, in the operator's order. Requirements a kind says do
@@ -101,6 +107,8 @@ module Spree
end
def build_status(requirement)
+ requirement.prefer_cached = @cached
+
Spree::SellerRequirementStatus.new(
id: requirement.prefixed_id,
kind: requirement.class.api_type,
diff --git a/spree/core/spec/jobs/spree/seller_payouts/sweep_due_job_spec.rb b/spree/core/spec/jobs/spree/seller_payouts/sweep_due_job_spec.rb
index b8f9527287..1dafcb4547 100644
--- a/spree/core/spec/jobs/spree/seller_payouts/sweep_due_job_spec.rb
+++ b/spree/core/spec/jobs/spree/seller_payouts/sweep_due_job_spec.rb
@@ -4,98 +4,47 @@ RSpec.describe Spree::SellerPayouts::SweepDueJob do
let(:store) { @default_store }
let(:seller) { create(:seller, :approved, store: store) }
- def earn(amount, seller: nil, currency: 'USD')
- owner = seller || self.seller
- create(:seller_transfer, :completed, seller: owner, currency: currency, amount: amount,
- order: create(:order, store: owner.store, seller: owner, currency: currency))
+ def enqueued_seller_ids
+ enqueued_jobs.
+ select { |job| job[:job] == Spree::SellerPayouts::SweepSellerJob }.
+ map { |job| job[:args].first }
end
- it 'settles a seller who is owed money' do
- earn(40)
-
- expect { described_class.perform_now }.to change { Spree::SellerPayout.count }.by(1)
- end
-
- it 'leaves a seller who has earned nothing' do
+ it 'hands an approved seller to a job of their own' do
seller
- expect { described_class.perform_now }.not_to change { Spree::SellerPayout.count }
- end
-
- # The operator settles these by hand, so nothing schedules them.
- it 'never settles a seller on a manual schedule' do
- seller.update!(payouts_schedule_interval: 'manual')
- earn(40)
+ described_class.perform_now
- expect { described_class.perform_now }.not_to change { Spree::SellerPayout.count }
+ expect(enqueued_seller_ids).to contain_exactly(seller.id)
end
it 'ignores a seller who is not approved' do
- pending_seller = create(:seller, store: store, status: 'pending')
- earn(40, seller: pending_seller)
-
- expect { described_class.perform_now }.not_to change { Spree::SellerPayout.count }
- end
-
- it 'settles each currency a seller is owed in separately' do
- earn(40)
- earn(30, currency: 'EUR')
+ create(:seller, store: store, status: 'pending')
described_class.perform_now
- expect(seller.seller_payouts.pluck(:currency, :amount)).to contain_exactly(['USD', 40], ['EUR', 30])
+ expect(enqueued_seller_ids).to be_empty
end
# Every marketplace on the installation is swept, each seller reached
# through the store that owns them.
- it 'settles sellers across every store' do
- other_store = create(:store)
- other_seller = create(:seller, :approved, store: other_store)
- earn(40)
- earn(30, seller: other_seller)
+ it 'reaches sellers across every store' do
+ seller
+ other_seller = create(:seller, :approved, store: create(:store))
described_class.perform_now
- expect(seller.seller_payouts.count).to eq(1)
- expect(other_seller.seller_payouts.count).to eq(1)
- end
-
- # A failed payout released its earnings back to the next sweep, so counting
- # it as a settlement would block the retry it exists to allow.
- it 'retries a seller whose last settlement failed' do
- earn(40)
- create(:seller_payout, seller: seller, currency: 'USD', status: 'failed', amount: 0)
-
- expect { described_class.perform_now }.to change { Spree::SellerPayout.where(status: 'pending').count }.by(1)
+ expect(enqueued_seller_ids).to contain_exactly(seller.id, other_seller.id)
end
- it 'still waits when the last settlement went out' do
- earn(40)
+ # Whether a seller is actually due is the per-seller job's question — this
+ # one only fans out, so a settled seller still gets a job that decides to do
+ # nothing. Asking here would mean running the interval logic twice.
+ it 'leaves the due date to the job it enqueues' do
create(:seller_payout, seller: seller, currency: 'USD', status: 'completed', amount: 40)
- expect { described_class.perform_now }.not_to change { Spree::SellerPayout.count }
- end
-
- # One stuck seller must not end the run for everyone behind them.
- it 'carries on past a seller whose settlement fails' do
- other_seller = create(:seller, :approved, store: store)
- earn(40)
- earn(30, seller: other_seller)
- allow(Spree).to receive(:seller_payout_sweep_workflow).and_wrap_original do |original|
- workflow = original.call
- failing = seller
- Class.new do
- define_singleton_method(:call) do |seller:, currency:|
- raise StandardError, 'provider down' if seller.id == failing.id
-
- workflow.call(seller: seller, currency: currency)
- end
- end
- end
-
described_class.perform_now
- expect(seller.seller_payouts.count).to eq(0)
- expect(other_seller.seller_payouts.count).to eq(1)
+ expect(enqueued_seller_ids).to contain_exactly(seller.id)
end
end
diff --git a/spree/core/spec/jobs/spree/seller_payouts/sweep_seller_job_spec.rb b/spree/core/spec/jobs/spree/seller_payouts/sweep_seller_job_spec.rb
new file mode 100644
index 0000000000..e9a17ce774
--- /dev/null
+++ b/spree/core/spec/jobs/spree/seller_payouts/sweep_seller_job_spec.rb
@@ -0,0 +1,61 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SellerPayouts::SweepSellerJob do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+
+ def earn(amount, seller: nil, currency: 'USD')
+ owner = seller || self.seller
+ create(:seller_transfer, :completed, seller: owner, currency: currency, amount: amount,
+ order: create(:order, store: owner.store, seller: owner, currency: currency))
+ end
+
+ it 'settles a seller who is owed money' do
+ earn(40)
+
+ expect { described_class.perform_now(seller.id) }.to change { Spree::SellerPayout.count }.by(1)
+ end
+
+ it 'leaves a seller who has earned nothing' do
+ expect { described_class.perform_now(seller.id) }.not_to change { Spree::SellerPayout.count }
+ end
+
+ # The operator settles these by hand, so nothing schedules them.
+ it 'never settles a seller on a manual schedule' do
+ seller.update!(payouts_schedule_interval: 'manual')
+ earn(40)
+
+ expect { described_class.perform_now(seller.id) }.not_to change { Spree::SellerPayout.count }
+ end
+
+ it 'settles each currency a seller is owed in separately' do
+ earn(40)
+ earn(30, currency: 'EUR')
+
+ described_class.perform_now(seller.id)
+
+ expect(seller.seller_payouts.pluck(:currency, :amount)).to contain_exactly(['USD', 40], ['EUR', 30])
+ end
+
+ # A failed payout released its earnings back to the next sweep, so counting
+ # it as a settlement would block the retry it exists to allow.
+ it 'retries a seller whose last settlement failed' do
+ earn(40)
+ create(:seller_payout, seller: seller, currency: 'USD', status: 'failed', amount: 0)
+
+ expect { described_class.perform_now(seller.id) }.
+ to change { Spree::SellerPayout.where(status: 'pending').count }.by(1)
+ end
+
+ it 'still waits when the last settlement went out' do
+ earn(40)
+ create(:seller_payout, seller: seller, currency: 'USD', status: 'completed', amount: 40)
+
+ expect { described_class.perform_now(seller.id) }.not_to change { Spree::SellerPayout.count }
+ end
+
+ # A seller can be deleted between the fan-out and the job running.
+ it 'does nothing for a seller that has gone' do
+ expect { described_class.perform_now(-1) }.not_to raise_error
+ end
+end
diff --git a/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rb b/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rb
index 106d10fe61..7b312957a2 100644
--- a/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rb
+++ b/spree/core/spec/jobs/spree/seller_transfers/execute_pending_job_spec.rb
@@ -74,4 +74,39 @@ RSpec.describe Spree::SellerTransfers::ExecutePendingJob do
expect(transfer.reload).to be_pending
end
+
+ # This job is the retry, so leaving an earning it could not account for in a
+ # retryable state means the next run sends the same money again.
+ context 'when the provider cannot say whether the money moved' do
+ before do
+ allow_any_instance_of(Spree::PayoutProvider::System).to receive(:transfer!).
+ and_raise(Spree::Core::AmbiguousGatewayError, 'connection timed out')
+ end
+
+ it 'parks the earning where no later run will send it' do
+ transfer = pending_earning
+
+ described_class.perform_now(seller.id)
+
+ expect(transfer.reload).to be_unresolved
+ end
+
+ it 'does not offer it again on the next run' do
+ pending_earning
+ described_class.perform_now(seller.id)
+
+ expect(seller.seller_transfers.earnings.retryable).to be_empty
+ end
+ end
+
+ # A refusal means the money did not move, so the earning is still owed.
+ it 'leaves a refused earning for the next run' do
+ allow_any_instance_of(Spree::PayoutProvider::System).to receive(:transfer!).
+ and_raise(StandardError, 'gateway down')
+ transfer = pending_earning
+
+ described_class.perform_now(seller.id)
+
+ expect(transfer.reload).to be_pending
+ end
end
diff --git a/spree/core/spec/models/spree/seller_requirements/payout_account_spec.rb b/spree/core/spec/models/spree/seller_requirements/payout_account_spec.rb
index 1a1a6c43d1..06f43e5708 100644
--- a/spree/core/spec/models/spree/seller_requirements/payout_account_spec.rb
+++ b/spree/core/spec/models/spree/seller_requirements/payout_account_spec.rb
@@ -85,6 +85,44 @@ RSpec.describe Spree::SellerRequirements::PayoutAccount do
end
end
+ # A page of sellers would otherwise make one call to the payment provider
+ # per row, which is the difference between a list that loads and one that
+ # does not.
+ describe 'on a listing' do
+ before { requirement.prefer_cached = true }
+
+ it 'answers from the stamp rather than asking the provider' do
+ expect_any_instance_of(Spree::PayoutProvider::System).not_to receive(:onboarded?)
+ seller.update!(payouts_enabled_at: Time.current)
+
+ expect(requirement).to be_met_by_seller(seller)
+ end
+
+ it 'reads a seller with no stamp as unmet' do
+ # Only a provider that actually moves money can refuse a seller; the
+ # record-only one counts everybody payable.
+ allow(Spree::PayoutProvider::System).to receive(:requires_payout_account?).and_return(true)
+ seller.update!(payouts_enabled_at: nil)
+
+ expect(requirement).not_to be_met_by_seller(seller)
+ end
+
+ # Which of the three states applies is the provider's to say, and a
+ # listing is not asking — so it says nothing rather than guessing.
+ it 'offers no explanation it would have to invent' do
+ expect_any_instance_of(Spree::PayoutProvider::System).not_to receive(:onboarding_state)
+
+ expect(requirement.blocker(seller)).to be_nil
+ end
+ end
+
+ # The gates and a seller's own page ask the provider, whatever a list does.
+ it 'asks the provider when nobody said a cached answer would do' do
+ expect_any_instance_of(Spree::PayoutProvider::System).to receive(:onboarded?).and_return(true)
+
+ expect(requirement).to be_met_by_seller(seller)
+ end
+
# A marketplace settling by hand should not have this forced on it.
it 'is registered as a kind an operator may add' do
expect(Spree.seller_requirements).to include(described_class)