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.

Added a seller balance and the ledger key that reads it

Damian Legawiecb9ed5a046485
diff --git a/spree/core/app/models/spree/payment_split.rb b/spree/core/app/models/spree/payment_split.rb
index 50f02d7a32..0e93a85672 100644
--- a/spree/core/app/models/spree/payment_split.rb
+++ b/spree/core/app/models/spree/payment_split.rb
@@ -40,7 +40,8 @@ module Spree
self.whitelisted_ransackable_associations = %w[payment order]
extend Spree::DisplayMoney
- money_methods :authorized_amount, :captured_amount, :refunded_amount
+ money_methods :authorized_amount, :captured_amount, :refunded_amount, :claimed_amount,
+ :net_captured_amount, :refundable_amount
# This child's reported position: what it has captured, less the refunds a
# subscriber has already written back to {#refunded_amount}.
diff --git a/spree/core/app/models/spree/seller.rb b/spree/core/app/models/spree/seller.rb
index 05fb396161..8e76d06eaf 100644
--- a/spree/core/app/models/spree/seller.rb
+++ b/spree/core/app/models/spree/seller.rb
@@ -277,6 +277,21 @@ module Spree
earned - settled
end
+ # The seller's position in every currency they have earned or been paid
+ # in, for the ledger screens. Empty before their first fulfilled sale.
+ #
+ # Only rows that contribute a figure decide the list: a currency whose
+ # every transfer failed would otherwise show a row of zeros on a money
+ # screen, which reads as a balance rather than as nothing having happened.
+ #
+ # @return [Array<Spree::SellerBalance>]
+ def balances
+ currencies = seller_transfers.where.not(status: 'failed').distinct.pluck(:currency) |
+ seller_payouts.completed.distinct.pluck(:currency)
+
+ currencies.sort.map { |currency| Spree::SellerBalance.for(self, currency) }
+ end
+
# The seller's account with whichever provider pays them — a Stripe Connect
# `acct_…`, or whatever a SEPA or PayPal provider issues.
#
diff --git a/spree/core/app/models/spree/seller_balance.rb b/spree/core/app/models/spree/seller_balance.rb
new file mode 100644
index 0000000000..77c4864e83
--- /dev/null
+++ b/spree/core/app/models/spree/seller_balance.rb
@@ -0,0 +1,50 @@
+module Spree
+ # One seller's position in one currency, read off the fund ledger.
+ #
+ # Never persisted: every figure is a sum over {Spree::SellerTransfer} and
+ # {Spree::SellerPayout} rows, so the ledger stays the only record and this
+ # only presents it. One per currency — a marketplace paying a seller in two
+ # currencies has two ledgers, and adding them would answer a question nobody
+ # asked.
+ class SellerBalance
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+
+ attribute :seller
+ attribute :currency, :string
+ # What the seller has earned: completed transfers, reversals included.
+ attribute :earned, :decimal, default: 0
+ # What has reached them: completed settlements.
+ attribute :paid, :decimal, default: 0
+ # Earnings still with the provider — a transfer not yet confirmed, or one
+ # whose outcome is unknown. Shown so a shipped order does not read as
+ # unpaid while the money is in flight.
+ attribute :pending, :decimal, default: 0
+
+ extend Spree::DisplayMoney
+ money_methods :earned, :paid, :pending, :balance
+
+ # @param seller [Spree::Seller]
+ # @param currency [String]
+ # @return [Spree::SellerBalance]
+ def self.for(seller, currency)
+ transfers = seller.seller_transfers.where(currency: currency)
+
+ new(
+ seller: seller,
+ currency: currency,
+ earned: transfers.completed.sum(:amount),
+ pending: transfers.with_status('pending', 'processing', 'unresolved').sum(:amount),
+ paid: seller.seller_payouts.completed.where(currency: currency).sum(:amount)
+ )
+ end
+
+ # What the marketplace still owes — the same figure {Spree::Seller#balance}
+ # answers, which is what the payout sweep settles.
+ #
+ # @return [BigDecimal]
+ def balance
+ earned - paid
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/seller_payout.rb b/spree/core/app/models/spree/seller_payout.rb
index 17642f3094..2ff1456c8a 100644
--- a/spree/core/app/models/spree/seller_payout.rb
+++ b/spree/core/app/models/spree/seller_payout.rb
@@ -57,7 +57,7 @@ module Spree
# 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_attributes = %w[amount currency status provider reference period_start period_end created_at seller_id]
self.whitelisted_ransackable_associations = %w[seller transfers]
extend Spree::DisplayMoney
diff --git a/spree/core/app/models/spree/seller_transfer.rb b/spree/core/app/models/spree/seller_transfer.rb
index dc3c53dc09..6d0f39f913 100644
--- a/spree/core/app/models/spree/seller_transfer.rb
+++ b/spree/core/app/models/spree/seller_transfer.rb
@@ -82,7 +82,7 @@ module Spree
# 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_attributes = %w[amount currency kind status provider reference created_at seller_id order_id payout_id]
self.whitelisted_ransackable_associations = %w[seller order payout refund]
extend Spree::DisplayMoney
diff --git a/spree/core/lib/spree/core/permission_configuration.rb b/spree/core/lib/spree/core/permission_configuration.rb
index a362172673..413fc00f69 100644
--- a/spree/core/lib/spree/core/permission_configuration.rb
+++ b/spree/core/lib/spree/core/permission_configuration.rb
@@ -463,6 +463,16 @@ module Spree
register_resource(:seller_profile, group: :access, subjects: -> { [:seller_profile] },
audiences: %i[seller])
+ # A seller reading their own books: balance, earnings, settlements.
+ #
+ # Its own key rather than part of `seller_profile`, so an owner can hand
+ # a packing teammate the orders without the money. Read-only, and a
+ # symbol for the reason `seller_profile` is one: the ledger classes
+ # belong to `payouts`, the operator's key. Which rows a seller reads is
+ # `current_seller` scope-fetching on their own branch.
+ register_resource(:seller_earnings, group: :access, subjects: -> { [:seller_earnings] },
+ write: false, audiences: %i[seller])
+
register_resource(:dashboard, group: :analytics, subjects: -> { [:dashboard] },
write: false, audiences: %i[seller])
end
diff --git a/spree/core/lib/tasks/seller_sample_data.rake b/spree/core/lib/tasks/seller_sample_data.rake
index 54d4d44300..a83bf659b4 100644
--- a/spree/core/lib/tasks/seller_sample_data.rake
+++ b/spree/core/lib/tasks/seller_sample_data.rake
@@ -1,6 +1,6 @@
namespace :spree do
namespace :sellers do
- desc 'Create a sample seller with a signed-in owner and a pending invitation, for trying the seller panel (development/test only)'
+ desc 'Create a sample seller with an owner, a pending invitation and a fund ledger, for trying the seller panel (development/test only)'
task sample_data: :environment do
# Refused outside development and test on purpose. This task writes a
# known password, and `find_or_initialize_by(email:)` can land on a real
@@ -70,12 +70,73 @@ namespace :spree do
)
end
+ # A fund ledger to read: a settled payout with the sales it covered, one
+ # still owed, and a sale not yet swept into either. Written directly
+ # rather than through fulfilment and the payout sweep — reaching those
+ # would mean placing and shipping real orders, which is a different
+ # task's job, and the screens under test read these rows either way.
+ provider = Spree::PayoutProvider::System.provider_key
+ currency = store.default_currency
+
+ if seller.seller_transfers.none?
+ # Each earning hangs off an order, because that is what a seller
+ # clicks through to from their ledger.
+ sample_orders = 5.times.map do |index|
+ Spree::Order.create!(
+ store: store, seller: seller, currency: currency,
+ email: "sample-buyer-#{index + 1}@example.com",
+ status: 'placed', completed_at: (index + 1).weeks.ago,
+ total: 100 + (index * 25), item_total: 100 + (index * 25)
+ )
+ end
+
+ settled = seller.seller_payouts.create!(
+ store: store, amount: 0, currency: currency, provider: provider, status: 'completed',
+ reference: 'BACS-SAMPLE-001',
+ period_start: 6.weeks.ago, period_end: 4.weeks.ago
+ )
+ owed = seller.seller_payouts.create!(
+ store: store, amount: 0, currency: currency, provider: provider, status: 'pending',
+ period_start: 3.weeks.ago, period_end: 1.week.ago
+ )
+
+ # Two settled, two owed, one still unswept — so the balance is a real
+ # subtraction rather than a single number, and the payouts queue has
+ # both a completed row and one to mark paid.
+ [[settled, 0], [settled, 1], [owed, 2], [owed, 3], [nil, 4]].each do |payout, index|
+ order = sample_orders[index]
+ seller.seller_transfers.create!(
+ store: store, order: order, payout: payout,
+ amount: order.total * 0.85, currency: currency,
+ kind: 'earning', provider: provider, status: 'completed',
+ created_at: order.completed_at
+ )
+ end
+
+ # A refund on the newest settled sale, so the reversal row and the
+ # negative amount both appear on the earnings screens.
+ original = seller.seller_transfers.earnings.order(:created_at).last
+ seller.seller_transfers.create!(
+ store: store, order: original.order, reversed_from: original,
+ amount: -(original.amount * 0.5), currency: currency,
+ kind: 'refund_reversal', provider: provider, status: 'completed'
+ )
+
+ # Each settlement is worth exactly what it claimed.
+ [settled, owed].each { |payout| payout.update!(amount: payout.transfers.sum(:amount)) }
+ end
+
progress = Spree::Sellers::Requirements.new(seller.reload).progress
+ balances = seller.balances
puts "Seller: #{seller.name} (#{seller.prefixed_id}, #{seller.status})"
puts "Checklist: #{progress[:done]}/#{progress[:total]} done"
puts "Sign in: #{email}"
puts "Pending: #{seller.invitations.pending.pluck(:email).join(', ')}"
+ puts "Ledger: #{seller.seller_transfers.count} earning(s), #{seller.seller_payouts.count} payout(s)"
+ balances.each do |balance|
+ puts "Balance: #{balance.display_balance} owed (#{balance.display_earned} earned, #{balance.display_paid} paid)"
+ end
end
end
end
diff --git a/spree/core/spec/lib/spree/core/permission_configuration_spec.rb b/spree/core/spec/lib/spree/core/permission_configuration_spec.rb
index 226a87a01a..0b3af58427 100644
--- a/spree/core/spec/lib/spree/core/permission_configuration_spec.rb
+++ b/spree/core/spec/lib/spree/core/permission_configuration_spec.rb
@@ -220,6 +220,38 @@ RSpec.describe Spree::PermissionConfiguration do
end
end
+ describe 'seller_earnings' do
+ let(:store) { @default_store }
+ let(:seller) { create(:seller, store: store) }
+ let(:user) { create(:admin_user) }
+
+ def ability_with(*permissions)
+ role = create(:role, name: 'seller', resource: seller, permissions: permissions)
+ create(:role_user, role: role, user: user)
+
+ Spree::Ability.new(user, resource: seller)
+ end
+
+ it 'is read-only and grantable to a seller' do
+ expect(Spree.permissions.grantable_keys(:seller)).to include('read_seller_earnings')
+ expect(Spree.permissions.grantable_keys(:seller)).not_to include('write_seller_earnings')
+ end
+
+ it 'grants a real ability rule' do
+ expect(ability_with('read_seller_earnings')).to be_can(:read, :seller_earnings)
+ end
+
+ # The ledger classes stay the operator's: holding the seller key must not
+ # open `Spree::SellerTransfer` generally.
+ it 'does not let a seller manage the ledger classes' do
+ expect(ability_with('read_seller_earnings')).not_to be_can(:read, Spree::SellerTransfer)
+ end
+
+ it 'is not implied by the profile key' do
+ expect(ability_with('write_seller_profile')).not_to be_can(:read, :seller_earnings)
+ end
+ end
+
describe 'seller_profile' do
let(:store) { @default_store }
let(:seller) { create(:seller, store: store) }
diff --git a/spree/core/spec/models/spree/seller_balance_spec.rb b/spree/core/spec/models/spree/seller_balance_spec.rb
new file mode 100644
index 0000000000..6a6de7ba0f
--- /dev/null
+++ b/spree/core/spec/models/spree/seller_balance_spec.rb
@@ -0,0 +1,46 @@
+require 'spec_helper'
+
+RSpec.describe Spree::SellerBalance, type: :model 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
+
+ describe '.for' do
+ it 'reads earned, paid, pending and the balance off the ledger' do
+ earn(40)
+ earn(30)
+ earn(-5)
+ earn(25, status: 'pending')
+ earn(10, status: 'unresolved')
+ earn(7, status: 'failed')
+ create(:seller_payout, :completed, seller: seller, amount: 50)
+ create(:seller_payout, seller: seller, amount: 15)
+
+ balance = described_class.for(seller, 'USD')
+
+ expect(balance.earned).to eq(65)
+ expect(balance.paid).to eq(50)
+ expect(balance.balance).to eq(15)
+ expect(balance.pending).to eq(35)
+ expect(balance.display_balance.to_s).to eq('$15.00')
+ end
+
+ it 'answers what Seller#balance answers' do
+ earn(40)
+ create(:seller_payout, :completed, seller: seller, amount: 10)
+
+ expect(described_class.for(seller, 'USD').balance).to eq(seller.balance('USD'))
+ end
+
+ it 'keeps another currency out' do
+ earn(40)
+ earn(30, currency: 'EUR')
+
+ expect(described_class.for(seller, 'EUR').earned).to eq(30)
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/seller_spec.rb b/spree/core/spec/models/spree/seller_spec.rb
index 141eddead0..b3e0ec99c6 100644
--- a/spree/core/spec/models/spree/seller_spec.rb
+++ b/spree/core/spec/models/spree/seller_spec.rb
@@ -398,6 +398,39 @@ describe Spree::Seller do
it 'is nothing for a seller who has earned nothing' do
expect(seller.balance('USD')).to eq(0)
end
+
+ describe '#balances' do
+ it 'is one position per currency the seller was ever paid or earned in, in order' do
+ earn(40)
+ earn(30, currency: 'EUR')
+ create(:seller_payout, :completed, seller: seller, amount: 5, currency: 'GBP')
+
+ expect(seller.balances.map(&:currency)).to eq(%w[EUR GBP USD])
+ expect(seller.balances.map(&:balance)).to eq([30, -5, 40])
+ end
+
+ it 'is empty before the first sale' do
+ expect(seller.balances).to be_empty
+ end
+
+ # A row of zeros on a money screen reads as a balance rather than as
+ # nothing having happened.
+ it 'leaves out a currency whose every transfer failed' do
+ earn(40)
+ earn(30, currency: 'EUR', status: 'failed')
+
+ expect(seller.balances.map(&:currency)).to eq(%w[USD])
+ end
+
+ # A settlement that never went out is not evidence the seller trades in
+ # that currency either.
+ it 'leaves out a currency holding only an unsettled payout' do
+ earn(40)
+ create(:seller_payout, seller: seller, amount: 5, currency: 'GBP')
+
+ expect(seller.balances.map(&:currency)).to eq(%w[USD])
+ end
+ end
end
describe 'settlement configuration' do