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.

Move a seller's earnings from the ledger to their bank

Damian Legawiecfa75e79190c6
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
new file mode 100644
index 0000000000..2e218fe992
--- /dev/null
+++ b/spree/core/app/jobs/spree/seller_payouts/sweep_due_job.rb
@@ -0,0 +1,56 @@
+module Spree
+ module SellerPayouts
+ # Settles every seller whose schedule has come round.
+ #
+ # 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.
+ #
+ # 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 SweepDueJob < ::Spree::BaseJob
+ queue_as Spree.queues.payouts
+
+ def perform
+ Spree::Seller.where(status: 'approved').find_each do |seller|
+ next if seller.resolved_payouts_schedule_interval == 'manual'
+ next unless due?(seller)
+
+ currencies_owed(seller).each do |currency|
+ Spree.seller_payout_sweep_workflow.call(seller: seller, currency: currency)
+ end
+ end
+ end
+
+ private
+
+ # Whether enough time has passed since this seller was last settled.
+ # 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.
+ def due?(seller)
+ last = seller.seller_payouts.order(:created_at).last
+ return true if last.nil?
+
+ last.created_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/subscribers/spree/seller_transfer_reversal_subscriber.rb b/spree/core/app/subscribers/spree/seller_transfer_reversal_subscriber.rb
new file mode 100644
index 0000000000..73e42302fa
--- /dev/null
+++ b/spree/core/app/subscribers/spree/seller_transfer_reversal_subscriber.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module Spree
+ # Takes back part of a seller's earning when their order is refunded.
+ #
+ # Hangs off `refund.created` rather than off returns, exchanges or claims
+ # individually: every one of those funnels its money movement through a
+ # refund, so one listener covers all three.
+ #
+ # A refund on an order that never shipped reverses nothing, because nothing
+ # was credited — the workflow answers that case by doing nothing rather than
+ # by failing.
+ class SellerTransferReversalSubscriber < Spree::Subscriber
+ subscribes_to 'refund.created'
+
+ def handle(event)
+ refund = Spree::Refund.find_by_prefix_id(event.payload['id'])
+ return unless refund
+
+ order = refund.order
+ return if order.nil? || order.seller_id.blank?
+
+ Spree.seller_transfer_reverse_workflow.call(order: order, amount: refund.amount)
+ end
+ end
+end
diff --git a/spree/core/app/subscribers/spree/seller_transfer_subscriber.rb b/spree/core/app/subscribers/spree/seller_transfer_subscriber.rb
new file mode 100644
index 0000000000..1466ddf73e
--- /dev/null
+++ b/spree/core/app/subscribers/spree/seller_transfer_subscriber.rb
@@ -0,0 +1,26 @@
+# frozen_string_literal: true
+
+module Spree
+ # Credits a seller once their order's goods have all gone out.
+ #
+ # Subscribes to `order.fulfilled` only, never the legacy `order.shipped` it
+ # is dual-emitted alongside — both would fire this. The workflow is
+ # idempotent regardless, but crediting twice and relying on a unique index to
+ # refuse it is not a design, it is a rescue.
+ #
+ # Asynchronous, unlike the commission subscriber: a provider that moves money
+ # makes a network call, and a fulfillment must not wait on a bank. What the
+ # seller earned is already determined by the time this runs — the order is
+ # fulfilled and its commission is written — so nothing is lost by deferring.
+ class SellerTransferSubscriber < Spree::Subscriber
+ subscribes_to 'order.fulfilled'
+
+ def handle(event)
+ order = Spree::Order.find_by_prefix_id(event.payload['id'])
+ return unless order
+ return if order.seller_id.blank?
+
+ Spree.seller_transfer_create_workflow.call(order: order)
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/seller_payouts/complete.rb b/spree/core/app/workflows/spree/seller_payouts/complete.rb
new file mode 100644
index 0000000000..395748d396
--- /dev/null
+++ b/spree/core/app/workflows/spree/seller_payouts/complete.rb
@@ -0,0 +1,47 @@
+module Spree
+ module SellerPayouts
+ # Records that a settlement actually reached the seller.
+ #
+ # Two callers, one meaning. An operator running the built-in provider marks
+ # a payout paid once they have sent the bank transfer; a connected provider
+ # marks it paid when its webhook says the money landed. Either way this is
+ # a claim about the outside world, which is why nothing asserts it
+ # automatically at the moment a payout is created.
+ #
+ # Completing is what debits the seller's balance, since the balance is
+ # earnings less *completed* settlements.
+ class Complete < Spree::Workflow
+ hooks :validate, :after_complete
+
+ # @param seller_payout [Spree::SellerPayout]
+ # @param reference [String, nil] the provider's own id for the
+ # settlement, when one made it
+ # @return [Spree::ServiceModule::Result]
+ def perform(seller_payout:, reference: nil)
+ super
+
+ step :replay_completed
+ run_hooks :validate
+ step :mark_completed
+ run_hooks :after_complete
+
+ seller_payout.publish_event('seller_payout.completed')
+ success(seller_payout)
+ end
+
+ private
+
+ # A webhook can arrive twice, and an operator can double-click.
+ def replay_completed
+ halt!(seller_payout) if seller_payout.completed?
+ end
+
+ def mark_completed
+ attributes = { status: 'completed' }
+ attributes[:reference] = reference if reference.present?
+
+ seller_payout.update!(attributes)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/seller_payouts/sweep.rb b/spree/core/app/workflows/spree/seller_payouts/sweep.rb
new file mode 100644
index 0000000000..e0e3c85bab
--- /dev/null
+++ b/spree/core/app/workflows/spree/seller_payouts/sweep.rb
@@ -0,0 +1,116 @@
+module Spree
+ module SellerPayouts
+ # Settles what a seller has accrued in one currency.
+ #
+ # The second level of the ledger. It gathers every earning that has been
+ # confirmed and not yet settled, batches them into one payout, and asks the
+ # provider to send it. A settlement therefore names exactly which orders it
+ # covered, which is what a seller needs to reconcile a deposit.
+ #
+ # **The stamp is the claim.** Creating the payout and marking its transfers
+ # with its id happen in one transaction, and a sweep only ever looks at
+ # transfers with no payout — so a batch can never be swept twice, and a
+ # re-run after a crash finds nothing left to take.
+ #
+ # A failed send leaves the transfers stamped: the retry re-sends *this*
+ # payout rather than sweeping the same earnings into a second one.
+ class Sweep < Spree::Workflow
+ hooks :validate, :after_sweep
+
+ attr_reader :payout
+
+ # @param seller [Spree::Seller]
+ # @param currency [String] settled per currency, since nothing is ever
+ # converted
+ # @return [Spree::ServiceModule::Result] value is the payout, or the
+ # seller when there was nothing to settle
+ def perform(seller:, currency:)
+ super
+
+ step :ensure_payable
+ step :collect_transfers
+ step :ensure_worth_sending
+ run_hooks :validate
+
+ step :claim_transfers
+ external_step :execute_payout
+ run_hooks :after_sweep
+
+ success(payout)
+ end
+
+ private
+
+ # A provider that moves money cannot pay a seller it has no account for.
+ # The earnings simply stay unsettled until one exists — they are not
+ # lost, and the next sweep will find them.
+ def ensure_payable
+ return unless provider.class.requires_payout_account?
+
+ halt!(seller) unless seller.payouts_enabled?
+ end
+
+ def collect_transfers
+ @transfers = seller.seller_transfers.unsettled.where(currency: currency).to_a
+ halt!(seller) if @transfers.empty?
+
+ @amount = @transfers.sum(&:amount)
+ 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.
+ # A balance that has gone negative (reversals outrunning earnings) is
+ # likewise left to be absorbed by what comes next.
+ def ensure_worth_sending
+ halt!(seller) if @amount <= 0
+ halt!(seller) if @amount < seller.resolved_minimum_payout_amount
+ end
+
+ def claim_transfers
+ ApplicationRecord.transaction do
+ @payout = Spree::SellerPayout.create!(
+ seller: seller,
+ amount: @amount,
+ currency: currency,
+ provider: provider_name,
+ status: 'pending',
+ period_start: @transfers.map(&:created_at).min,
+ period_end: Time.current
+ )
+
+ # The claim. A concurrent sweep can only take rows this one has not,
+ # so the same earning is never in two payouts.
+ claimed = Spree::SellerTransfer.where(id: @transfers.map(&:id), payout_id: nil).
+ update_all(payout_id: @payout.id, updated_at: Time.current)
+
+ # Another sweep beat this one to some of them; the amount would be a
+ # lie, so this payout takes only what it actually claimed.
+ restate_amount if claimed != @transfers.size
+ end
+ end
+
+ def restate_amount
+ @payout.update!(amount: @payout.transfers.sum(:amount))
+ end
+
+ def execute_payout
+ provider.pay!(payout)
+ rescue StandardError => e
+ # The transfers stay stamped deliberately: retrying means re-sending
+ # this payout, never sweeping the same earnings into a second one.
+ payout.update!(status: 'failed')
+ Rails.error.report(e, handled: true, context: { seller_payout_id: payout.id }, source: 'spree.core')
+ failure(payout, e.message)
+ end
+
+ def provider
+ @provider ||= seller.store.payout_provider_instance
+ end
+
+ def provider_name
+ provider.class.name.demodulize.underscore
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/seller_transfers/create.rb b/spree/core/app/workflows/spree/seller_transfers/create.rb
new file mode 100644
index 0000000000..ae7bc32d42
--- /dev/null
+++ b/spree/core/app/workflows/spree/seller_transfers/create.rb
@@ -0,0 +1,113 @@
+module Spree
+ module SellerTransfers
+ # Credits a seller for one order whose goods have gone out.
+ #
+ # The first level of the ledger. What the seller earned is their sale less
+ # what the marketplace charged them, and it is **payment-source-agnostic**:
+ # store credit and gift cards are how the customer paid, which is the
+ # platform's funding concern. The seller is owed their cut either way.
+ #
+ # Idempotent by the unique index on `(order_id) WHERE kind = 'earning'` —
+ # the fulfillment event can fire more than once (it is dual-emitted under a
+ # legacy name for one release), and a re-fired event must find the earning
+ # that exists rather than credit the seller twice.
+ class Create < Spree::Workflow
+ hooks :validate, :after_create
+
+ attr_reader :seller_transfer
+
+ # @param order [Spree::Order] the seller's order, fully fulfilled
+ # @return [Spree::ServiceModule::Result] value is the Spree::SellerTransfer,
+ # or the order when there is nothing to credit
+ def perform(order:)
+ super
+
+ step :ensure_creditable
+ step :replay_existing
+ run_hooks :validate
+
+ step :build_transfer
+ external_step :execute_transfer
+ run_hooks :after_create
+
+ success(seller_transfer)
+ end
+
+ private
+
+ # A first-party order earns nobody anything — the money is already the
+ # operator's. Nor does an order whose goods have not all gone out, or one
+ # with no goods at all: `fully_fulfilled?` answers true for an order with
+ # no fulfillments, since none of nothing is outstanding.
+ def ensure_creditable
+ halt!(order) if order.seller_id.blank?
+ halt!(order) if order.fulfillments.empty?
+ halt!(order) unless order.fully_fulfilled?
+ halt!(order) unless payable_seller?
+ end
+
+ def replay_existing
+ existing = Spree::SellerTransfer.earnings.find_by(order_id: order.id)
+ halt!(existing) if existing
+ end
+
+ def build_transfer
+ @seller_transfer = Spree::SellerTransfer.create!(
+ seller: order.seller,
+ order: order,
+ amount: earned_amount,
+ currency: order.currency,
+ kind: 'earning',
+ provider: provider_name,
+ status: 'pending'
+ )
+ rescue ActiveRecord::RecordNotUnique
+ # Another delivery of the same event got there first; the unique index
+ # is what makes that safe, and its winner is the answer.
+ halt!(Spree::SellerTransfer.earnings.find_by!(order_id: order.id))
+ end
+
+ # Outside any transaction: a provider that moves money makes a network
+ # call here, and a row lock must not be held across it.
+ def execute_transfer
+ provider.transfer!(seller_transfer)
+ rescue StandardError => e
+ # The money may or may not have moved — that is precisely what an
+ # operator has to resolve, so the row parks rather than pretending.
+ seller_transfer.update!(status: 'processing')
+ Rails.error.report(e, handled: true, context: { seller_transfer_id: seller_transfer.id },
+ source: 'spree.core')
+ failure(seller_transfer, e.message)
+ end
+
+ # What the seller earned: their sale, less the marketplace's commission
+ # including the VAT charged on it — the platform invoices the seller for
+ # both, and the seller reclaims that VAT as input tax.
+ #
+ # A platform-remitted seller does not receive the consumer tax either,
+ # since the marketplace files it (Decision 9).
+ def earned_amount
+ base = order.total.to_d
+ base -= order.additional_tax_total.to_d if order.seller.tax_remittance == 'platform'
+
+ [base - order.commission_lines.sum(:total).to_d, 0].max
+ end
+
+ # A provider that executes transfers cannot pay a seller it has no
+ # account for — crediting them would promise money nothing can send.
+ def payable_seller?
+ return true unless provider.class.requires_payout_account?
+
+ order.seller.payouts_enabled?
+ end
+
+ def provider
+ @provider ||= order.store.payout_provider_instance
+ end
+
+ def provider_name
+ provider.class.name.demodulize.underscore
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/seller_transfers/reverse.rb b/spree/core/app/workflows/spree/seller_transfers/reverse.rb
new file mode 100644
index 0000000000..6dc909ee96
--- /dev/null
+++ b/spree/core/app/workflows/spree/seller_transfers/reverse.rb
@@ -0,0 +1,80 @@
+module Spree
+ module SellerTransfers
+ # Takes back part of what a seller earned, after a refund.
+ #
+ # Written as its own negative row rather than by editing the earning, so
+ # what a seller has earned is always the sum of their transfers and the
+ # history stays readable. If the earning was already settled in a closed
+ # payout, the reversal simply lands in the next period — a settlement that
+ # happened is never rewritten.
+ #
+ # The ledger row is written in every tier. Whether money is actually pulled
+ # back is the provider's business, and the built-in one pulls back nothing.
+ class Reverse < Spree::Workflow
+ hooks :validate, :after_reverse
+
+ attr_reader :reversal
+
+ # @param order [Spree::Order] the seller order being refunded
+ # @param amount [BigDecimal, Numeric] how much of the earning to take
+ # back; capped at what is left of it
+ # @return [Spree::ServiceModule::Result] value is the reversal, or the
+ # order when there was nothing to reverse
+ def perform(order:, amount:)
+ super
+
+ step :find_earning
+ step :bound_amount
+ run_hooks :validate
+
+ step :build_reversal
+ external_step :execute_reversal
+ run_hooks :after_reverse
+
+ success(reversal)
+ end
+
+ private
+
+ def find_earning
+ @earning = Spree::SellerTransfer.earnings.find_by(order_id: order.id)
+ # Nothing was ever credited — the order was refunded before it shipped,
+ # which is the ordinary case and not an error.
+ halt!(order) if @earning.nil?
+ end
+
+ # Never more than is left of the earning, however many times an order is
+ # refunded: a marketplace cannot claw back more than it credited.
+ def bound_amount
+ @bounded = [amount.to_d.abs, @earning.reversible_amount].min
+ halt!(order) if @bounded <= 0
+ end
+
+ def build_reversal
+ @reversal = Spree::SellerTransfer.create!(
+ seller: @earning.seller,
+ order: order,
+ reversed_from: @earning,
+ # Negative, so what a seller has earned is the plain sum of the rows.
+ amount: -@bounded,
+ currency: @earning.currency,
+ kind: 'refund_reversal',
+ provider: @earning.provider,
+ status: 'pending'
+ )
+ end
+
+ def execute_reversal
+ provider.reverse!(reversal)
+ rescue StandardError => e
+ reversal.update!(status: 'processing')
+ Rails.error.report(e, handled: true, context: { seller_transfer_id: reversal.id }, source: 'spree.core')
+ failure(reversal, e.message)
+ end
+
+ def provider
+ @provider ||= order.store.payout_provider_instance
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index d015e23ce8..6708c29fe9 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -123,7 +123,8 @@ module Spree
api_keys: :default,
search: :default,
stock_reservations: :default,
- tax_identifiers: :default
+ tax_identifiers: :default,
+ payouts: :default
).tap do |queues|
# @deprecated The taxons queue was renamed to categories in 6.0; removed in 6.1.
queues.define_singleton_method(:taxons) do
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index cec9424967..68baa419ac 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -197,6 +197,10 @@ module Spree
payment_capture_workflow: 'Spree::Payments::Capture',
payment_void_workflow: 'Spree::Payments::Void',
refund_create_workflow: 'Spree::Refunds::Create',
+ seller_transfer_create_workflow: 'Spree::SellerTransfers::Create',
+ seller_transfer_reverse_workflow: 'Spree::SellerTransfers::Reverse',
+ seller_payout_sweep_workflow: 'Spree::SellerPayouts::Sweep',
+ seller_payout_complete_workflow: 'Spree::SellerPayouts::Complete',
payments_handle_webhook_workflow: 'Spree::Payments::HandleWebhook',
payment_session_complete_workflow: 'Spree::PaymentSessions::Complete',
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 7815ef7bcb..5969e0fb91 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -580,6 +580,8 @@ module Spree
Spree::OrderCommissionSubscriber,
Spree::OrderStatusSubscriber,
Spree::PaymentSplitSubscriber,
+ Spree::SellerTransferSubscriber,
+ Spree::SellerTransferReversalSubscriber,
Spree::ExportSubscriber,
Spree::ReportSubscriber,
Spree::InvitationEmailSubscriber,
diff --git a/spree/core/spec/subscribers/spree/seller_transfer_subscriber_spec.rb b/spree/core/spec/subscribers/spree/seller_transfer_subscriber_spec.rb
new file mode 100644
index 0000000000..2bbb905c6d
--- /dev/null
+++ b/spree/core/spec/subscribers/spree/seller_transfer_subscriber_spec.rb
@@ -0,0 +1,65 @@
+require 'spec_helper'
+
+# The ledger's trigger, exercised through the events it actually listens to
+# rather than by calling the workflow — the wiring is the thing most likely to
+# be wrong, and it fails silently when it is.
+RSpec.describe Spree::SellerTransferSubscriber, :events do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+
+ def seller_order
+ order = create(:order, store: store, seller: seller)
+ create(:line_item, order: order)
+ order.update_columns(total: 100, status: 'placed', completed_at: Time.current)
+ order.reload
+ end
+
+ it 'credits the seller when the order’s goods go out' do
+ order = seller_order
+ create(:fulfillment, order: order, cart: nil, status: 'fulfilled')
+
+ perform_enqueued_jobs(only: Spree::Events::SubscriberJob) { order.publish_event('order.fulfilled') }
+
+ expect(seller.balance('USD')).to eq(100)
+ end
+
+ # order.fulfilled is dual-emitted under the legacy name order.shipped for one
+ # release. Listening to both would credit twice; the unique index would
+ # refuse the second, but relying on that is a rescue rather than a design.
+ it 'does not credit again on the legacy event name' do
+ order = seller_order
+ create(:fulfillment, order: order, cart: nil, status: 'fulfilled')
+
+ perform_enqueued_jobs(only: Spree::Events::SubscriberJob) do
+ order.publish_event('order.fulfilled')
+ order.publish_event('order.shipped')
+ end
+
+ expect(Spree::SellerTransfer.count).to eq(1)
+ end
+
+ it 'leaves the operator’s own order alone' do
+ order = create(:order, store: store)
+ order.update_columns(status: 'placed', completed_at: Time.current)
+ create(:fulfillment, order: order, cart: nil, status: 'fulfilled')
+
+ perform_enqueued_jobs(only: Spree::Events::SubscriberJob) { order.publish_event('order.fulfilled') }
+
+ expect(Spree::SellerTransfer.count).to eq(0)
+ end
+
+ describe 'a refund afterwards' do
+ it 'takes back what it gave' do
+ order = seller_order
+ create(:fulfillment, order: order, cart: nil, status: 'fulfilled')
+ payment = create(:payment, order: order, amount: 100, status: 'completed')
+
+ perform_enqueued_jobs(only: Spree::Events::SubscriberJob) do
+ order.publish_event('order.fulfilled')
+ create(:refund, payment: payment, order: order, amount: 40)
+ end
+
+ expect(seller.balance('USD')).to eq(60)
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb b/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb
new file mode 100644
index 0000000000..634e6c034b
--- /dev/null
+++ b/spree/core/spec/workflows/spree/seller_payouts/sweep_spec.rb
@@ -0,0 +1,112 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SellerPayouts::Sweep do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+
+ def earn(amount, currency: 'USD', status: 'completed', payout: nil)
+ create(:seller_transfer, seller: seller, currency: currency, amount: amount, status: status, payout: payout,
+ order: create(:order, store: store, seller: seller, currency: currency))
+ end
+
+ describe 'what it settles' do
+ it 'batches every unsettled earning into one payout' do
+ earn(40)
+ earn(30)
+
+ result = described_class.call(seller: seller, currency: 'USD')
+
+ expect(result).to be_success
+ expect(result.value.amount).to eq(70)
+ expect(result.value.transfers.count).to eq(2)
+ end
+
+ it 'names the earnings it covered, so a deposit can be reconciled' do
+ first = earn(40)
+ second = earn(30)
+
+ payout = described_class.call(seller: seller, currency: 'USD').value
+
+ expect(payout.transfers).to contain_exactly(first, second)
+ end
+
+ it 'leaves earnings in another currency for their own settlement' do
+ earn(40)
+ earn(30, currency: 'EUR')
+
+ payout = described_class.call(seller: seller, currency: 'USD').value
+
+ expect(payout.amount).to eq(40)
+ expect(Spree::SellerTransfer.unsettled.where(currency: 'EUR').count).to eq(1)
+ end
+
+ it 'ignores earnings a previous settlement already took' do
+ earn(40, payout: create(:seller_payout, seller: seller))
+ earn(30)
+
+ expect(described_class.call(seller: seller, currency: 'USD').value.amount).to eq(30)
+ end
+
+ it 'ignores an earning that is not yet confirmed' do
+ earn(40)
+ earn(30, status: 'pending')
+
+ expect(described_class.call(seller: seller, currency: 'USD').value.amount).to eq(40)
+ end
+ end
+
+ describe 'when there is nothing worth sending' do
+ it 'does nothing for a seller who has earned nothing' do
+ expect { described_class.call(seller: seller, currency: 'USD') }.
+ not_to change { Spree::SellerPayout.count }
+ end
+
+ # The balance carries rather than being sent: a payout costs a fee either
+ # way, and one meaningful deposit beats five trivial ones.
+ it 'holds a balance below the seller’s threshold' do
+ seller.update!(minimum_payout_amount: 50)
+ earn(20)
+
+ expect { described_class.call(seller: seller, currency: 'USD') }.
+ not_to change { Spree::SellerPayout.count }
+ expect(Spree::SellerTransfer.unsettled.count).to eq(1)
+ end
+
+ it 'holds a balance that reversals have taken negative' do
+ earn(40)
+ earn(-60)
+
+ expect { described_class.call(seller: seller, currency: 'USD') }.
+ not_to change { Spree::SellerPayout.count }
+ end
+ end
+
+ # The stamp is the claim: a sweep only ever looks at unstamped earnings, so
+ # a re-run finds nothing left to take.
+ describe 'sweeping twice' do
+ it 'takes nothing the first sweep already claimed' do
+ earn(40)
+ described_class.call(seller: seller, currency: 'USD')
+
+ expect { described_class.call(seller: seller.reload, currency: 'USD') }.
+ not_to change { Spree::SellerPayout.count }
+ end
+ end
+
+ describe 'the balance' do
+ it 'is unchanged until the settlement is confirmed' do
+ earn(40)
+ described_class.call(seller: seller, currency: 'USD')
+
+ expect(seller.balance('USD')).to eq(40)
+ end
+
+ it 'falls once the settlement completes' do
+ earn(40)
+ payout = described_class.call(seller: seller, currency: 'USD').value
+ Spree.seller_payout_complete_workflow.call(seller_payout: payout)
+
+ expect(seller.balance('USD')).to eq(0)
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/seller_transfers/create_spec.rb b/spree/core/spec/workflows/spree/seller_transfers/create_spec.rb
new file mode 100644
index 0000000000..de7d9e7503
--- /dev/null
+++ b/spree/core/spec/workflows/spree/seller_transfers/create_spec.rb
@@ -0,0 +1,108 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SellerTransfers::Create do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+
+ # A shipped seller order worth 100, on which the marketplace charged 12
+ # including the VAT it charges the seller on its fee.
+ def shipped_order(total: 100, commission: 12, tax_remittance: 'seller', tax: 0)
+ order = create(:order, store: store, seller: seller)
+ line_item = create(:line_item, order: order)
+ create(:fulfillment, order: order, cart: nil, status: 'fulfilled')
+ seller.update!(tax_remittance: tax_remittance)
+
+ if commission.positive?
+ create(:commission_line, order: order, seller: seller, line_item: line_item,
+ amount: commission, tax_amount: 0, total: commission, currency: order.currency)
+ end
+
+ # Written last and directly: the workflow reads the order's own totals, and
+ # letting recalculation derive them from the factory's line items would be
+ # testing the totals workflow rather than the ledger.
+ order.update_columns(total: total, additional_tax_total: tax, status: 'placed',
+ completed_at: Time.current)
+
+ order.reload
+ end
+
+ describe 'what the seller earned' do
+ it 'is the sale less what the marketplace charged them' do
+ result = described_class.call(order: shipped_order)
+
+ expect(result).to be_success
+ expect(result.value.amount).to eq(88)
+ end
+
+ it 'credits nothing below zero when commission outruns the sale' do
+ result = described_class.call(order: shipped_order(total: 10, commission: 40))
+
+ expect(result.value.amount).to eq(0)
+ end
+
+ # The marketplace files the consumer tax under facilitator rules, so it is
+ # never the seller's to receive.
+ it 'withholds consumer tax from a platform-remitted seller' do
+ result = described_class.call(order: shipped_order(total: 100, commission: 12, tax_remittance: 'platform', tax: 20))
+
+ expect(result.value.amount).to eq(68)
+ end
+
+ it 'leaves consumer tax with a seller who remits it themselves' do
+ result = described_class.call(order: shipped_order(total: 100, commission: 12, tax: 20))
+
+ expect(result.value.amount).to eq(88)
+ end
+ end
+
+ describe 'what it refuses to credit' do
+ it 'ignores the operator’s own order' do
+ order = create(:order, store: store, status: 'placed', completed_at: Time.current)
+ create(:fulfillment, order: order, cart: nil, status: 'fulfilled')
+
+ expect { described_class.call(order: order.reload) }.not_to change { Spree::SellerTransfer.count }
+ end
+
+ it 'ignores an order whose goods have not gone out' do
+ order = create(:order, store: store, seller: seller, total: 50)
+ create(:fulfillment, order: order, cart: nil, status: 'unfulfilled')
+
+ expect { described_class.call(order: order.reload) }.not_to change { Spree::SellerTransfer.count }
+ end
+
+ # fully_fulfilled? answers true for an order with no fulfillments, since
+ # none of nothing is outstanding — which must not read as shipped.
+ it 'ignores an order with nothing to fulfil' do
+ order = create(:order, store: store, seller: seller, total: 50)
+
+ expect { described_class.call(order: order) }.not_to change { Spree::SellerTransfer.count }
+ end
+ end
+
+ describe 'replay' do
+ it 'returns the earning that exists rather than crediting twice' do
+ order = shipped_order
+ first = described_class.call(order: order).value
+
+ second = described_class.call(order: order.reload)
+
+ expect(second.value.id).to eq(first.id)
+ expect(Spree::SellerTransfer.count).to eq(1)
+ end
+ end
+
+ describe 'with the record-only provider' do
+ it 'confirms the earning immediately, since nothing has to be sent' do
+ result = described_class.call(order: shipped_order)
+
+ expect(result.value).to be_completed
+ expect(result.value.provider).to eq('system')
+ end
+
+ it 'counts toward the seller’s balance' do
+ described_class.call(order: shipped_order)
+
+ expect(seller.balance('USD')).to eq(88)
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/seller_transfers/reverse_spec.rb b/spree/core/spec/workflows/spree/seller_transfers/reverse_spec.rb
new file mode 100644
index 0000000000..e5fee89344
--- /dev/null
+++ b/spree/core/spec/workflows/spree/seller_transfers/reverse_spec.rb
@@ -0,0 +1,72 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SellerTransfers::Reverse do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, :approved, store: store) }
+ let(:order) { create(:order, store: store, seller: seller, total: 100) }
+
+ def earn(amount = 80)
+ create(:seller_transfer, :completed, seller: seller, order: order, amount: amount)
+ end
+
+ describe 'taking money back' do
+ it 'writes a negative row rather than editing the earning' do
+ earning = earn
+
+ result = described_class.call(order: order, amount: 30)
+
+ expect(result).to be_success
+ expect(result.value.amount).to eq(-30)
+ expect(earning.reload.amount).to eq(80)
+ end
+
+ it 'leaves the seller with what is left' do
+ earn
+ described_class.call(order: order, amount: 30)
+
+ expect(seller.balance('USD')).to eq(50)
+ end
+
+ it 'links the reversal to what it reverses' do
+ earning = earn
+
+ expect(described_class.call(order: order, amount: 30).value.reversed_from).to eq(earning)
+ end
+ end
+
+ describe 'what it will not take back' do
+ it 'refuses to claw back more than was credited' do
+ earn(80)
+
+ expect(described_class.call(order: order, amount: 200).value.amount).to eq(-80)
+ end
+
+ it 'takes nothing once the earning is fully reversed' do
+ earn(80)
+ described_class.call(order: order, amount: 80)
+
+ expect { described_class.call(order: order, amount: 20) }.
+ not_to change { Spree::SellerTransfer.count }
+ end
+
+ # An order refunded before it shipped never credited anybody.
+ it 'does nothing when there was no earning' do
+ expect { described_class.call(order: order, amount: 30) }.
+ not_to change { Spree::SellerTransfer.count }
+ end
+ end
+
+ # A settlement that has happened is never rewritten: the reversal is simply
+ # unsettled, so the next sweep nets it off what comes after.
+ describe 'when the earning was already settled' do
+ it 'leaves the closed payout alone and waits for the next one' do
+ payout = create(:seller_payout, :completed, seller: seller, amount: 80)
+ create(:seller_transfer, :completed, seller: seller, order: order, amount: 80, payout: payout)
+
+ reversal = described_class.call(order: order, amount: 30).value
+
+ expect(payout.reload.amount).to eq(80)
+ expect(reversal.payout).to be_nil
+ end
+ end
+end