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
Record what each seller has earned and what has been settled to them
Damian Legawiecb39f197af272
diff --git a/spree/core/app/models/spree/payout_provider/base.rb b/spree/core/app/models/spree/payout_provider/base.rbnew file mode 100644index 0000000000..010673b80e--- /dev/null+++ b/spree/core/app/models/spree/payout_provider/base.rb@@ -0,0 +1,89 @@+module Spree+ module PayoutProvider+ # Contract for whatever actually moves money to a seller.+ #+ # Core records both levels of the ledger for every marketplace — what each+ # seller earned as their orders shipped, and what has been settled to them.+ # A provider decides whether that money moves on its own: the built-in one+ # records and leaves the operator to pay by bank, while a connected+ # provider performs the transfer and reports back.+ #+ # Three verbs, one per thing that can happen to money:+ #+ # transfer! — a seller earned on a fulfilled order (level one)+ # pay! — their accrued earnings are settled (level two)+ # reverse! — a refund takes some of an earning back+ #+ # Every verb must be **idempotent**, keyed on the record's prefixed id: a+ # crash between the remote call and the local commit is retried, and a+ # retry must find the movement it already made rather than make a second.+ #+ # Providers are stateless and constructed without arguments, as tax and+ # delivery-rate providers are; anything request-specific arrives as an+ # argument.+ class Base+ # The name a merchant sees when choosing how sellers are paid.+ #+ # @return [String]+ def self.display_name+ name.demodulize.titleize+ end++ # Whether this provider can be selected for a store — an external one+ # overrides it to require connected credentials.+ #+ # @param store [Spree::Store]+ # @return [Boolean]+ def self.available_for_store?(_store)+ true+ end++ # Whether this provider needs sellers to hold an account with it before+ # they can be paid. A marketplace settling by bank transfer does not; a+ # connected provider does, and core will not credit a seller it cannot+ # pay through one.+ #+ # @return [Boolean]+ def self.requires_payout_account?+ false+ end++ # Credits a seller for one fulfilled order.+ #+ # @param seller_transfer [Spree::SellerTransfer]+ # @return [Spree::SellerTransfer]+ def transfer!(_seller_transfer)+ raise NotImplementedError+ end++ # Settles a seller's accrued earnings.+ #+ # @param seller_payout [Spree::SellerPayout]+ # @return [Spree::SellerPayout]+ def pay!(_seller_payout)+ raise NotImplementedError+ end++ # Takes back part of an earning after a refund.+ #+ # The ledger row is written by core either way — the books stay correct+ # in every tier — so a provider that cannot pull money back implements+ # this as a no-op rather than refusing.+ #+ # @param seller_transfer [Spree::SellerTransfer] the reversal row+ # @return [Spree::SellerTransfer]+ def reverse!(_seller_transfer)+ raise NotImplementedError+ end++ # The key a provider passes to its own API so a retried call cannot move+ # money twice.+ #+ # @param record [Spree::SellerTransfer, Spree::SellerPayout]+ # @return [String]+ def idempotency_key(record)+ "spree-#{record.prefixed_id}"+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/payout_provider/system.rb b/spree/core/app/models/spree/payout_provider/system.rbnew file mode 100644index 0000000000..22b3381e07--- /dev/null+++ b/spree/core/app/models/spree/payout_provider/system.rb@@ -0,0 +1,36 @@+module Spree+ module PayoutProvider+ # The built-in provider: it keeps the books and moves no money.+ #+ # This is what a marketplace runs before it connects anything. Sellers+ # accrue earnings as their orders ship, those earnings batch into+ # settlements on schedule, and the operator sees exactly what is owed to+ # whom — then pays it by bank transfer and marks the settlement complete.+ #+ # An earning is confirmed immediately, because with no remote party there+ # is nothing to confirm: the seller has shipped and the marketplace holds+ # their money. A settlement, by contrast, stays pending until somebody says+ # it was actually sent — that is a claim about the outside world, and only+ # a person can make it here.+ class System < Base+ def transfer!(seller_transfer)+ seller_transfer.update!(status: 'completed')+ seller_transfer+ end++ # Deliberately does nothing. The payout waits in the operator's queue+ # until it is marked paid — recording it as settled here would assert a+ # bank transfer nobody has made.+ def pay!(seller_payout)+ seller_payout+ end++ # The ledger row is the whole reversal. Nothing was ever sent, so+ # nothing has to come back.+ def reverse!(seller_transfer)+ seller_transfer.update!(status: 'completed')+ seller_transfer+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rbindex e4dc91a72c..e842327d00 100644--- a/spree/core/app/models/spree/seller.rb+++ b/spree/core/app/models/spree/seller.rb@@ -134,6 +134,13 @@ module Spreehas_many :orders, class_name: 'Spree::Order', dependent: nilhas_many :payment_splits, through: :orders, class_name: 'Spree::PaymentSplit', source: :payment_splits+ # The two levels of the fund ledger: what this seller has earned, and what+ # has been settled to them. Left alone when the seller goes, for the same+ # reason as their orders and commission — money that moved is a fact about+ # the past.+ has_many :seller_transfers, class_name: 'Spree::SellerTransfer', dependent: nil+ has_many :seller_payouts, class_name: 'Spree::SellerPayout', dependent: nil+# What this seller has done about the marketplace's requirements — their# attestations, the documents they uploaded, what the operator made of# them. Goes with the seller, since it means nothing without them.@@ -207,6 +214,48 @@ module Spreeterms_accepted_at.present?end+ # What the marketplace still owes this seller in one currency.+ #+ # Derived rather than stored: it is the whole point of keeping both ledger+ # levels, and a column would be a second answer that could disagree with+ # the rows. Per currency because nothing is ever converted — a seller+ # trading in two currencies accrues two balances and is paid twice.+ #+ # @param currency [String]+ # @return [BigDecimal]+ def balance(currency)+ earned = seller_transfers.completed.where(currency: currency).sum(:amount)+ settled = seller_payouts.completed.where(currency: currency).sum(:amount)++ earned - settled+ end++ # Whether a provider says this seller may be sent money yet.+ #+ # A marketplace settling offline never asks, so a seller with no account+ # reference is payable by definition — it is only a provider that executes+ # transfers which can refuse one.+ #+ # @return [Boolean]+ def payouts_enabled?+ payouts_enabled_at.present?+ end++ # What this seller's settlement schedule is, falling back to the store's.+ #+ # @return [String]+ def resolved_payouts_schedule_interval+ payouts_schedule_interval.presence || store.preferred_default_payouts_schedule_interval+ end++ # The balance a settlement must reach before it is worth sending, falling+ # back to the store's. Below it, the balance simply carries to next time.+ #+ # @return [BigDecimal]+ def resolved_minimum_payout_amount+ (minimum_payout_amount || store.preferred_default_minimum_payout_amount).to_d+ end+# Where customers send returns — this seller's default stock location.## A location rather than a loose address because a received return has todiff --git a/spree/core/app/models/spree/seller_payout.rb b/spree/core/app/models/spree/seller_payout.rbnew file mode 100644index 0000000000..5b9b2ecb52--- /dev/null+++ b/spree/core/app/models/spree/seller_payout.rb@@ -0,0 +1,66 @@+# frozen_string_literal: true++module Spree+ # One settlement to one seller: the earnings they had accrued, batched and+ # sent on their own schedule.+ #+ # The second of the ledger's two levels. Transfers credit a seller as each+ # order ships; a payout is the money actually leaving — daily, weekly,+ # monthly, or whenever an operator says so. It names exactly which transfers+ # it settled, so a seller asking "what is this deposit for" has an answer,+ # and so a reversal arriving after a payout closed lands in the next period+ # rather than rewriting a settlement that already happened.+ #+ # Core records both levels for every marketplace. Whether money actually+ # moves is the {Spree::PayoutProvider}'s business: the built-in one records+ # and leaves the operator to pay by bank, while a provider like Stripe+ # Connect performs the transfer itself.+ class SellerPayout < Spree.base_class+ has_prefix_id :vpo++ include Spree::Metadata++ #+ # Associations+ #+ belongs_to :seller, class_name: 'Spree::Seller'+ # What this payout settles. Deliberately nullify rather than destroy: a+ # transfer is the record of an earning and outlives the settlement that+ # paid it, so a deleted payout releases its transfers back to the next+ # sweep instead of erasing what the seller earned.+ has_many :transfers, class_name: 'Spree::SellerTransfer', foreign_key: :payout_id,+ inverse_of: :payout, dependent: :nullify++ #+ # Validations+ #+ validates :amount, numericality: true+ validates :currency, presence: true+ validates :provider, presence: true++ #+ # Statuses. As with transfers, movement is through workflows rather than a+ # transition graph.+ #+ include Spree::HasStatus+ has_status :pending, :processing, :completed, :failed, default: :pending++ #+ # Scopes+ #+ # Money promised but not yet gone — what an operator's queue is for.+ scope :owed, -> { where(status: %w[pending processing]) }++ self.whitelisted_ransackable_attributes = %w[amount currency status provider reference period_start period_end created_at]+ self.whitelisted_ransackable_associations = %w[seller transfers]++ extend Spree::DisplayMoney+ money_methods :amount++ # @return [BigDecimal] what the transfers this payout holds actually come+ # to, for checking a stored amount against its parts+ def transfers_total+ transfers.sum(:amount)+ end+ end+enddiff --git a/spree/core/app/models/spree/seller_transfer.rb b/spree/core/app/models/spree/seller_transfer.rbnew file mode 100644index 0000000000..9bfc626c30--- /dev/null+++ b/spree/core/app/models/spree/seller_transfer.rb@@ -0,0 +1,88 @@+# frozen_string_literal: true++module Spree+ # What one seller earned on one order, credited when the goods went out.+ #+ # The first of the ledger's two levels. A seller earns on **fulfillment**,+ # not on payment: the marketplace holds the money until the goods actually+ # ship, and a digital order fulfils immediately so it earns immediately. The+ # second level — {Spree::SellerPayout} — sweeps these into a bank settlement+ # on the seller's own schedule.+ #+ # The amount is the seller's sale less what the marketplace charged them, and+ # is deliberately **payment-source-agnostic**: store credit and gift cards are+ # how the customer paid, which is the platform's funding concern, not the+ # seller's. They are owed their cut either way.+ #+ # A refund writes a second row against the same order rather than editing+ # this one, so what a seller has earned is always the sum of their transfers+ # and the history stays readable.+ class SellerTransfer < Spree.base_class+ has_prefix_id :vtr++ include Spree::Metadata++ KINDS = %w[earning refund_reversal].freeze++ #+ # Associations+ #+ belongs_to :seller, class_name: 'Spree::Seller'+ belongs_to :order, class_name: 'Spree::Order'+ # Nil until a sweep settles this transfer; the stamp is what claims it, so+ # a re-run sweep can never batch the same earning twice.+ belongs_to :payout, class_name: 'Spree::SellerPayout', optional: true, inverse_of: :transfers+ belongs_to :reversed_from, class_name: 'Spree::SellerTransfer', optional: true, inverse_of: :reversals+ has_many :reversals, class_name: 'Spree::SellerTransfer', foreign_key: :reversed_from_id,+ inverse_of: :reversed_from, dependent: :nullify++ #+ # Validations+ #+ validates :amount, numericality: true+ validates :currency, presence: true+ validates :kind, presence: true, inclusion: { in: KINDS }+ validates :provider, presence: true++ #+ # Statuses. No state machine: a transfer moves through the payout+ # workflows, which can explain a refusal, rather than through a transition+ # graph (docs/plans/6.0-service-workflows.md).+ #+ include Spree::HasStatus+ has_status :pending, :processing, :completed, :failed, default: :pending++ #+ # Scopes+ #+ scope :earnings, -> { where(kind: 'earning') }+ scope :reversals_only, -> { where(kind: 'refund_reversal') }+ # Earned and confirmed, but not yet swept into a settlement — what the next+ # payout will pick up.+ scope :unsettled, -> { completed.where(payout_id: nil) }++ self.whitelisted_ransackable_attributes = %w[amount currency kind status provider reference created_at]+ self.whitelisted_ransackable_associations = %w[seller order payout]++ extend Spree::DisplayMoney+ money_methods :amount++ # What is left of this earning to give back.+ #+ # Original less what reversals have already taken, floored at zero — a+ # refund can never claw back more than the seller was credited, however+ # many times the order is refunded.+ #+ # @return [BigDecimal]+ def reversible_amount+ return 0.to_d unless earning?++ [amount - reversals.sum(:amount).abs, 0].max+ end++ # @return [Boolean]+ def earning?+ kind == 'earning'+ end+ end+enddiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex bed5b0d9dc..29390e3d87 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -76,6 +76,18 @@ module Spree# same reason as auto_approve_sellers: what the marketplace lists is what# it vouches for.preference :auto_approve_seller_products, :boolean, default: false+ # Who pays this store's sellers. Blank means core's record-only provider,+ # so a marketplace that has connected nothing still keeps a correct ledger+ # and settles by hand.+ preference :payout_provider, :string, default: nil+ # How often sellers are settled, unless one carries its own schedule.+ # Monthly by default because it is the interval that needs least of an+ # operator paying by hand, which is what the built-in provider expects.+ preference :default_payouts_schedule_interval, :string, default: 'monthly'+ # What a seller's balance must reach before a settlement is worth sending;+ # below it the balance carries to the next period. Zero pays whatever is+ # owed, which is right for a provider that moves money for free.+ preference :default_minimum_payout_amount, :decimal, default: 0# Checkout preferences# Store-level fallback for the channel-owned `guest_checkout` preference# (see Spree::Channel::Gating). Retained so existing accessors keep working.@@ -378,6 +390,17 @@ module Spree@unique_name ||= "#{name} (#{code})"end+ # Who pays this store's sellers, ready to be asked.+ #+ # Resolved per call rather than memoized, so a marketplace that connects a+ # provider mid-process starts using it without a restart — the same shape+ # markets use for tax.+ #+ # @return [Spree::PayoutProvider::Base]+ def payout_provider_instance+ (preferred_payout_provider.presence || Spree.default_payout_provider.to_s).constantize.new+ end+def formatted_url@formatted_url ||= beginclean_url = url.to_s.sub(%r{^https?://}, '').split(':').firstdiff --git a/spree/core/db/migrate/20260822000001_create_spree_seller_transfers.rb b/spree/core/db/migrate/20260822000001_create_spree_seller_transfers.rbnew file mode 100644index 0000000000..314da562fe--- /dev/null+++ b/spree/core/db/migrate/20260822000001_create_spree_seller_transfers.rb@@ -0,0 +1,66 @@+class CreateSpreeSellerTransfers < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_seller_transfers do |t|+ t.references :seller, null: false+ # The child order this earning came from. One earning per order — see the+ # partial index below.+ t.references :order, null: false+ # Nil until a payout sweeps this transfer up and settles it.+ t.references :payout, index: true+ # The earning this row reverses, when a refund gave money back.+ t.references :reversed_from, index: true++ t.decimal :amount, precision: 10, scale: 2, null: false, default: 0+ t.string :currency, null: false+ # earning | refund_reversal+ t.string :kind, null: false+ t.string :status, null: false # no DB default: set by the creating workflow++ # Which provider moved (or recorded) the money, and what it called the+ # movement. A `system` transfer has no reference — the operator settles+ # offline.+ t.string :provider, null: false+ t.string :reference++ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end++ t.timestamps+ end++ add_index :spree_seller_transfers, [:seller_id, :currency, :status]+ add_index :spree_seller_transfers, [:seller_id, :created_at]++ # A re-fired fulfillment event must find the existing row rather than+ # credit the seller twice. Reversals are deliberately outside the+ # constraint: an order can be refunded more than once.+ if connection.supports_partial_index?+ add_index :spree_seller_transfers, :order_id, unique: true,+ where: "kind = 'earning'",+ name: 'index_seller_transfers_on_order_earning'+ else+ # MySQL has no partial index. Indexing the id together with the row's own+ # primary key for every other kind gives the same guarantee: earnings+ # collide on the order, reversals never collide at all.+ execute <<~SQL.squish+ CREATE UNIQUE INDEX index_seller_transfers_on_order_earning+ ON spree_seller_transfers(order_id, (CASE WHEN kind = 'earning' THEN 0 ELSE id END))+ SQL+ end++ # A provider's own id for the movement, unique where one exists: a retry+ # whose idempotency key returned the same external transfer must re-sync+ # this row rather than create a second.+ if connection.supports_partial_index?+ add_index :spree_seller_transfers, [:provider, :reference], unique: true,+ where: 'reference IS NOT NULL',+ name: 'index_seller_transfers_on_provider_reference'+ else+ add_index :spree_seller_transfers, [:provider, :reference],+ name: 'index_seller_transfers_on_provider_reference'+ end+ end+enddiff --git a/spree/core/db/migrate/20260822000002_create_spree_seller_payouts.rb b/spree/core/db/migrate/20260822000002_create_spree_seller_payouts.rbnew file mode 100644index 0000000000..f5274a03b5--- /dev/null+++ b/spree/core/db/migrate/20260822000002_create_spree_seller_payouts.rb@@ -0,0 +1,42 @@+class CreateSpreeSellerPayouts < ActiveRecord::Migration[8.1]+ def change+ create_table :spree_seller_payouts do |t|+ t.references :seller, null: false++ # The sum of the transfers this payout settles, fixed when it is+ # assembled. Not derived on read: a settled payout is a record of what+ # was sent, and later reversals belong to the next period rather than+ # rewriting a closed one.+ t.decimal :amount, precision: 10, scale: 2, null: false, default: 0+ t.string :currency, null: false+ t.string :status, null: false # no DB default: set by the creating workflow++ # What this payout covers, so a statement can name its period.+ t.datetime :period_start+ t.datetime :period_end++ t.string :provider, null: false+ t.string :reference++ if t.respond_to?(:jsonb)+ t.jsonb :metadata+ else+ t.json :metadata+ end++ t.timestamps+ end++ add_index :spree_seller_payouts, [:seller_id, :currency, :status]+ add_index :spree_seller_payouts, [:seller_id, :created_at]++ if connection.supports_partial_index?+ add_index :spree_seller_payouts, [:provider, :reference], unique: true,+ where: 'reference IS NOT NULL',+ name: 'index_seller_payouts_on_provider_reference'+ else+ add_index :spree_seller_payouts, [:provider, :reference],+ name: 'index_seller_payouts_on_provider_reference'+ end+ end+enddiff --git a/spree/core/db/migrate/20260822000003_add_payout_account_to_spree_sellers.rb b/spree/core/db/migrate/20260822000003_add_payout_account_to_spree_sellers.rbnew file mode 100644index 0000000000..c5b1c3b521--- /dev/null+++ b/spree/core/db/migrate/20260822000003_add_payout_account_to_spree_sellers.rb@@ -0,0 +1,17 @@+class AddPayoutAccountToSpreeSellers < ActiveRecord::Migration[8.1]+ def change+ # The seller's account with whichever provider pays them, and whether that+ # provider says it may yet send money.+ #+ # Deliberately provider-agnostic columns rather than `stripe_account_id`:+ # the payout provider is pluggable, and a marketplace paying by SEPA batch+ # or PayPal has an account reference too. Which provider the reference+ # belongs to is the store's payout provider, so it is not repeated here.+ add_column :spree_sellers, :payout_account_reference, :string+ # Set from the provider's own account status — a Stripe Express account+ # says when it is payouts_enabled. Nil until a provider has been asked.+ add_column :spree_sellers, :payouts_enabled_at, :datetime++ add_index :spree_sellers, :payout_account_reference+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex 1ec73914b7..d015e23ce8 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -375,6 +375,30 @@ module SpreeRails.application.config.spree.inventory_providers = valueend+ # How sellers get paid. Core ships {Spree::PayoutProvider::System}, which+ # keeps the books and leaves the operator to settle; a provider gem appends+ # one that moves the money itself.+ #+ # @return [Array<Class>]+ def self.payout_providers+ Rails.application.config.spree.payout_providers+ end++ def self.payout_providers=(value)+ Rails.application.config.spree.payout_providers = value+ end++ # The provider a store pays through when it has named none.+ #+ # @return [Class]+ def self.default_payout_provider+ Rails.application.config.spree.default_payout_provider+ end++ def self.default_payout_provider=(value)+ Rails.application.config.spree.default_payout_provider = value+ end+# Validator enforcing the password policy on the default auth models# ({Spree::Customer}, {Spree::AdminUser}). Defaults to# {Spree::PasswordLengthValidator}, which reads the configurable length bounds.diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex cce3dc43f7..7815ef7bcb 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -15,6 +15,8 @@ module Spree:tax_providers,:pricing_providers,:inventory_providers,+ :default_payout_provider,+ :payout_providers,:password_validator,:fulfillment_providers,:tracking_carriers,@@ -168,6 +170,13 @@ module Spreeapp.config.spree.inventory_providers = []end+ # How sellers get paid. A provider gem — the Stripe Connect one, or a+ # marketplace's own — registers from an initializer file; core's+ # record-only System concatenates below.+ initializer 'spree.register.payout_providers', before: :load_config_initializers do |app|+ app.config.spree.payout_providers = []+ end+initializer 'spree.register.delivery_profile_types', before: :load_config_initializers do |app|app.config.spree.delivery_profile_types = []end@@ -264,6 +273,12 @@ module SpreeRails.application.config.spree.pricing_providers.concat [Spree::PricingProvider::Internal]Rails.application.config.spree.inventory_providers.concat [Spree::InventoryProvider::Internal]+ # How sellers are paid when a store names nothing: the books are kept+ # and the operator settles offline. Assigned only if an initializer has+ # not already chosen one.+ Rails.application.config.spree.default_payout_provider ||= Spree::PayoutProvider::System+ Rails.application.config.spree.payout_providers.concat [Spree::PayoutProvider::System]+# Password policy for the default auth models. Swap for corporate rules,# breach-list lookups or entropy scoring.Rails.application.config.spree.password_validator = Spree::PasswordLengthValidatordiff --git a/spree/core/lib/spree/testing_support/factories/seller_payout_factory.rb b/spree/core/lib/spree/testing_support/factories/seller_payout_factory.rbnew file mode 100644index 0000000000..7f3247dc44--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/seller_payout_factory.rb@@ -0,0 +1,13 @@+FactoryBot.define do+ factory :seller_payout, class: Spree::SellerPayout do+ seller+ amount { BigDecimal(20) }+ currency { 'USD' }+ provider { 'system' }+ status { 'pending' }++ trait :completed do+ status { 'completed' }+ end+ end+enddiff --git a/spree/core/lib/spree/testing_support/factories/seller_transfer_factory.rb b/spree/core/lib/spree/testing_support/factories/seller_transfer_factory.rbnew file mode 100644index 0000000000..21f1cfffdf--- /dev/null+++ b/spree/core/lib/spree/testing_support/factories/seller_transfer_factory.rb@@ -0,0 +1,20 @@+FactoryBot.define do+ factory :seller_transfer, class: Spree::SellerTransfer do+ seller+ order+ amount { BigDecimal(20) }+ currency { 'USD' }+ kind { 'earning' }+ provider { 'system' }+ status { 'pending' }++ trait :completed do+ status { 'completed' }+ end++ trait :reversal do+ kind { 'refund_reversal' }+ amount { BigDecimal(-5) }+ end+ end+enddiff --git a/spree/core/spec/models/spree/seller_payout_spec.rb b/spree/core/spec/models/spree/seller_payout_spec.rbnew file mode 100644index 0000000000..e1fa670192--- /dev/null+++ b/spree/core/spec/models/spree/seller_payout_spec.rb@@ -0,0 +1,43 @@+require 'spec_helper'++RSpec.describe Spree::SellerPayout, type: :model do+ let(:store) { @default_store }+ let(:seller) { create(:seller, :approved, store: store) }++ it_behaves_like 'metadata'++ describe 'the transfers it settles' do+ let(:payout) { create(:seller_payout, seller: seller, amount: 60) }++ before do+ 2.times do+ create(:seller_transfer, :completed, seller: seller, amount: 30, payout: payout,+ order: create(:order, store: store, seller: seller))+ end+ end++ it 'names exactly what it paid for' do+ expect(payout.transfers.count).to eq(2)+ expect(payout.transfers_total).to eq(60)+ end++ # A deleted settlement must not erase what the seller earned — the+ # transfers go back to being unsettled and the next sweep picks them up.+ it 'releases its transfers rather than destroying them when it goes' do+ payout.destroy!++ expect(Spree::SellerTransfer.count).to eq(2)+ expect(Spree::SellerTransfer.unsettled.count).to eq(2)+ end+ end++ describe '.owed' do+ it 'is money promised but not yet gone' do+ pending_payout = create(:seller_payout, seller: seller)+ processing = create(:seller_payout, seller: seller, status: 'processing')+ create(:seller_payout, :completed, seller: seller)++ expect(described_class.owed).to contain_exactly(pending_payout, processing)+ end+ end+enddiff --git a/spree/core/spec/models/spree/seller_spec.rb b/spree/core/spec/models/spree/seller_spec.rbindex 0112d3b8af..704cbb4641 100644--- a/spree/core/spec/models/spree/seller_spec.rb+++ b/spree/core/spec/models/spree/seller_spec.rb@@ -360,4 +360,60 @@ describe Spree::Seller doexpect(ability).not_to be_can(:manage, seller)endend++ describe '#balance' do+ let(:store) { @default_store }+ let(:seller) { create(:seller, :approved, store: store) }++ def earn(amount, currency: 'USD', status: 'completed')+ create(:seller_transfer, seller: seller, currency: currency, amount: amount, status: status,+ order: create(:order, store: store, seller: seller, currency: currency))+ end++ it 'is what has been earned less what has been settled' do+ earn(40)+ earn(30)+ create(:seller_payout, :completed, seller: seller, amount: 50)++ expect(seller.balance('USD')).to eq(20)+ end++ it 'counts only confirmed earnings' do+ earn(40)+ earn(25, status: 'pending')++ expect(seller.balance('USD')).to eq(40)+ end++ # Nothing is ever converted, so a seller trading in two currencies accrues+ # two balances and is settled in each.+ it 'keeps each currency separate' do+ earn(40)+ earn(30, currency: 'EUR')++ expect(seller.balance('USD')).to eq(40)+ expect(seller.balance('EUR')).to eq(30)+ end++ it 'is nothing for a seller who has earned nothing' do+ expect(seller.balance('USD')).to eq(0)+ end+ end++ describe 'settlement configuration' do+ let(:store) { @default_store }+ let(:seller) { create(:seller, :approved, store: store) }++ it 'falls back to the store’s schedule and threshold' do+ expect(seller.resolved_payouts_schedule_interval).to eq('monthly')+ expect(seller.resolved_minimum_payout_amount).to eq(0)+ end++ it 'prefers its own once it deviates' do+ seller.update!(payouts_schedule_interval: 'weekly', minimum_payout_amount: 25)++ expect(seller.resolved_payouts_schedule_interval).to eq('weekly')+ expect(seller.resolved_minimum_payout_amount).to eq(25)+ end+ endenddiff --git a/spree/core/spec/models/spree/seller_transfer_spec.rb b/spree/core/spec/models/spree/seller_transfer_spec.rbnew file mode 100644index 0000000000..b97334b490--- /dev/null+++ b/spree/core/spec/models/spree/seller_transfer_spec.rb@@ -0,0 +1,68 @@+require 'spec_helper'++RSpec.describe Spree::SellerTransfer, type: :model do+ let(:store) { @default_store }+ let(:seller) { create(:seller, :approved, store: store) }+ let(:order) { create(:order, store: store, seller: seller) }++ it_behaves_like 'metadata'++ describe 'one earning per order' do+ it 'refuses a second earning for the same order' do+ create(:seller_transfer, seller: seller, order: order)++ expect { create(:seller_transfer, seller: seller, order: order) }.+ to raise_error(ActiveRecord::RecordNotUnique)+ end++ # A refund can happen more than once, so reversals are deliberately+ # outside the constraint.+ it 'allows several reversals against the same order' do+ earning = create(:seller_transfer, seller: seller, order: order)++ expect {+ 2.times { create(:seller_transfer, :reversal, seller: seller, order: order, reversed_from: earning) }+ }.not_to raise_error+ end+ end++ describe '#reversible_amount' do+ let(:earning) { create(:seller_transfer, :completed, seller: seller, order: order, amount: 40) }++ it 'is the whole earning while nothing has been given back' do+ expect(earning.reversible_amount).to eq(40)+ end++ it 'is what is left after a partial reversal' do+ create(:seller_transfer, :reversal, seller: seller, order: order, reversed_from: earning, amount: -15)++ expect(earning.reload.reversible_amount).to eq(25)+ end++ # However many times an order is refunded, a marketplace can never claw+ # back more than it credited.+ it 'floors at zero rather than going negative' do+ create(:seller_transfer, :reversal, seller: seller, order: order, reversed_from: earning, amount: -40)+ create(:seller_transfer, :reversal, seller: seller, order: order, reversed_from: earning, amount: -10)++ expect(earning.reload.reversible_amount).to eq(0)+ end++ it 'is nothing for a row that is itself a reversal' do+ reversal = create(:seller_transfer, :reversal, seller: seller, order: order, reversed_from: earning)++ expect(reversal.reversible_amount).to eq(0)+ end+ end++ describe '.unsettled' do+ it 'is what a payout sweep will pick up' do+ awaiting = create(:seller_transfer, :completed, seller: seller, order: order)+ create(:seller_transfer, :completed, seller: seller, order: create(:order, store: store, seller: seller),+ payout: create(:seller_payout, seller: seller))+ create(:seller_transfer, seller: seller, order: create(:order, store: store, seller: seller))++ expect(described_class.unsettled).to contain_exactly(awaiting)+ end+ end+end