New plugin: monthly sales commission (SOP-OPS-013)

Reads the month's paid sales from QuickBooks Online (invoices paid in
full that month, sales receipts), deducts refund receipts, credit memos
and adjustments, works out the commission pool with the threshold and
marginal brackets, and records each sales rep's payout once the month
is approved for payroll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-16 18:53:25 -05:00
commit 6fcd5f9b64
44 files changed
+2661

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class CommissionRepsTest < Redmine::IntegrationTest
include QboCommissionTestHelper
def test_admin_only
log_user('jsmith', 'jsmith')
get '/commission_reps'
assert_response :forbidden
end
def test_add_edit_and_remove
log_user('admin', 'admin')
get '/commission_reps/new'
assert_response :success
post '/commission_reps', params: { commission_rep: { user_id: '2', probation_until: '2026-12-31', active: '1' } }
assert_redirected_to '/commission_reps'
rep = CommissionRep.find_by(user_id: 2)
assert_equal Date.new(2026, 12, 31), rep.probation_until
post '/commission_reps', params: { commission_rep: { user_id: '2' } }
assert_response :unprocessable_entity
get '/commission_reps'
assert_select 'td.name', text: 'John Smith'
patch "/commission_reps/#{rep.id}", params: { commission_rep: { user_id: '3', probation_until: '', active: '0' } }
assert_redirected_to '/commission_reps'
rep.reload
assert_equal 2, rep.user_id
assert_nil rep.probation_until
assert_not rep.active?
delete "/commission_reps/#{rep.id}"
assert_equal 0, CommissionRep.count
end
end
+180
View File
@@ -0,0 +1,180 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class SalesCommissionsTest < Redmine::IntegrationTest
include QboCommissionTestHelper
def setup
stub_qbo
create_rep(2)
create_rep(3)
end
def test_needs_a_permission
log_user('jsmith', 'jsmith')
get '/sales_commission/2026-10'
assert_response :forbidden
Role.find(1).add_permission!(:approve_sales_commission)
get '/sales_commission'
assert_response :success
assert_select '#top-menu a.sales-commissions[href=?]', '/sales_commission/current'
end
def test_menu_opens_this_month
log_user('admin', 'admin')
travel_to Date.new(2026, 11, 18) do
get '/sales_commission/current'
assert_redirected_to '/sales_commission/2026-11'
end
end
def test_month_picker
log_user('admin', 'admin')
get '/sales_commission', params: { month: '2026-10' }
assert_redirected_to '/sales_commission/2026-10'
end
def test_open_month
log_user('admin', 'admin')
get '/sales_commission/2026-10'
assert_response :success
assert_select 'h2', text: /October 2026/
assert_select '.sales-commission-summary .value', text: '$120,000.00'
assert_select '.sales-commission-summary .value', text: '$119,000.00'
assert_select '.sales-commission-summary .value', text: '$595.00'
assert_select '#sales-commission-payouts td', text: '$595.00', count: 2
assert_select '#sales-commission-sales tbody tr', 2
assert_select 'input[name=?][value=?][checked]', 'included[]', 'refund_receipt:3'
assert_select 'input[name=?][value="2"][checked]', 'eligible[]'
assert_select 'input[name=approve]'
end
def test_view_only
Role.find(1).add_permission!(:view_sales_commission)
log_user('jsmith', 'jsmith')
get '/sales_commission'
assert_response :forbidden
get '/sales_commission/2026-10'
assert_response :success
assert_select '.sales-commission-summary .value', text: '$595.00'
assert_select 'h2 a[href=?]', '/sales_commission', count: 0
assert_select 'input[name=?]', 'included[]', count: 0
assert_select 'input[name=approve]', count: 0
assert_select 'a[href*="qbo.intuit.com"]', count: 0
post '/sales_commission/2026-10', params: { approve: '1' }
assert_response :forbidden
assert_nil CommissionMonth.for(commission_month)
get '/sales_commission/2026-10.csv'
assert_response :forbidden
end
def test_untick_and_approve
log_user('admin', 'admin')
post '/sales_commission/2026-10', params: { shown: '1', shown_deductions: ['refund_receipt:3'], included: [],
shown_reps: %w[2 3], eligible: ['2'], notes: 'Checked with bookkeeping' }
assert_redirected_to '/sales_commission/2026-10'
record = CommissionMonth.for(commission_month)
assert_equal ['refund_receipt:3'], record.excluded_keys
assert_equal [3], record.unpaid_user_ids
assert_not record.approved?
get '/sales_commission/2026-10'
assert_select '.sales-commission-summary .value', text: '$600.00'
assert_select 'input[name=?][value=?]:not([checked])', 'included[]', 'refund_receipt:3'
assert_select 'input[name=?][value="3"]:not([checked])', 'eligible[]'
post '/sales_commission/2026-10', params: { shown: '1', shown_deductions: ['refund_receipt:3'], included: [],
shown_reps: %w[2 3], eligible: ['2'], approve: '1' }
assert_redirected_to '/sales_commission/2026-10'
record.reload
assert record.approved?
assert_equal BigDecimal('600'), record.pool
assert_equal({ 2 => BigDecimal('600'), 3 => BigDecimal('0') }, record.payouts.to_h { |p| [p.user_id, p.amount] })
get '/sales_commission/2026-10'
assert_select '.sales-commission-approved', text: /Approved for payroll by/
assert_select 'input[name=approve]', count: 0
assert_select 'a[href=?]', '/sales_commission/2026-10.csv'
get '/sales_commission/2026-10.csv'
assert_response :success
assert_match %r{\Atext/csv}, response.content_type
rows = CSV.parse(response.body)
assert_equal 3, rows.size
assert_includes rows, ['2026-10', 'jsmith', 'John Smith', '600.00', 'Yes', nil]
get '/sales_commission'
assert_select 'td', text: '$600.00'
end
def test_approved_month_is_locked_until_reopened
log_user('admin', 'admin')
post '/sales_commission/2026-10', params: { approve: '1' }
record = CommissionMonth.for(commission_month)
assert record.approved?
post '/sales_commission/2026-10/adjustments', params: { description: 'Late refund', amount: '50' }
assert_equal 0, record.adjustments.count
assert_equal 'This month is approved. Reopen it to change it.', flash[:error]
post '/sales_commission/2026-10/reopen'
assert_redirected_to '/sales_commission/2026-10'
assert_not record.reload.approved?
end
def test_current_month_cannot_be_approved
log_user('admin', 'admin')
month = RedmineQboCommission::Month.containing(Date.current)
get "/sales_commission/#{month.label}"
assert_select 'input[name=approve]', count: 0
assert_select 'p.warning'
post "/sales_commission/#{month.label}", params: { approve: '1' }
assert_equal "The month isn't over yet.", flash[:error]
end
def test_adjustments
log_user('admin', 'admin')
post '/sales_commission/2026-10/adjustments', params: { description: 'Returned lift kit, refunded by check', amount: '$19,000' }
assert_redirected_to '/sales_commission/2026-10'
adjustment = CommissionAdjustment.last
assert_equal BigDecimal('19000'), adjustment.amount
assert_equal User.find(1), adjustment.author
get '/sales_commission/2026-10'
assert_select '.sales-commission-summary .value', text: '$100,000.00'
assert_select '.sales-commission-summary .value', text: '$500.00'
post '/sales_commission/2026-10/adjustments', params: { description: '', amount: 'abc' }
assert flash[:error].present?
assert_equal 1, CommissionAdjustment.count
delete "/sales_commission/2026-10/adjustments/#{adjustment.id}"
assert_equal 0, CommissionAdjustment.count
end
def test_quickbooks_error
RedmineQboCommission::QboSource.stubs(:transactions).raises(StandardError, 'QBO not connected')
log_user('admin', 'admin')
get '/sales_commission/2026-10'
assert_response :success
assert_select 'p.conflict', text: /QBO not connected/
end
def test_refresh
RedmineQboCommission::QboSource.expects(:transactions).with(commission_month, refresh: true).returns([])
log_user('admin', 'admin')
post '/sales_commission/2026-10/refresh'
assert_redirected_to '/sales_commission/2026-10'
end
end
+63
View File
@@ -0,0 +1,63 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../../../test/test_helper', __dir__)
module QboCommissionTestHelper
# October 2026: over, so it can be approved
MONTH_START = Date.new(2026, 10, 1)
def self.included(base)
base.fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations
base.setup do
CommissionLine.delete_all
CommissionAdjustment.delete_all
CommissionPayout.delete_all
CommissionMonth.delete_all
CommissionRep.delete_all
Rails.cache.clear
end
end
def commission_month
RedmineQboCommission::Month.new(MONTH_START)
end
def sale(id, total, tax: 0, kind: 'invoice', date: MONTH_START + 10, customer: 'Jane Customer')
RedmineQboCommission::Txn.new(kind: kind, txn_id: id.to_s, doc_number: "10#{id}", customer_name: customer,
txn_date: date, total: BigDecimal(total.to_s), tax: BigDecimal(tax.to_s))
end
def refund(id, total, tax: 0, kind: 'refund_receipt')
sale(id, total, tax: tax, kind: kind)
end
# $120,000 of sales without tax, and a $1,000 refund: $119,000, a $595.00 commission
def october_txns
[sale(1, 64_200, tax: 4_200), sale(2, 60_000), refund(3, 1_000)]
end
def stub_qbo(txns = october_txns)
RedmineQboCommission::QboSource.stubs(:transactions).returns(txns)
end
def create_rep(user_id, **attributes)
CommissionRep.create!({ user_id: user_id }.merge(attributes))
end
def with_commission_settings(values)
saved = Setting.plugin_redmine_qbo_commission
Setting.plugin_redmine_qbo_commission = RedmineQboCommission::Settings::DEFAULTS.merge(values)
yield
ensure
Setting.plugin_redmine_qbo_commission = saved
end
end
+90
View File
@@ -0,0 +1,90 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class ApproverTest < ActiveSupport::TestCase
include QboCommissionTestHelper
def setup
User.current = User.find(1)
create_rep(2)
create_rep(3, probation_until: MONTH_START + 10)
end
def approve(month = commission_month)
RedmineQboCommission::Approver.new(month, user: User.find(1)).approve
end
def test_records_the_month
RedmineQboCommission::QboSource.expects(:transactions).with(commission_month, refresh: true).returns(october_txns)
record = approve
assert record.approved?
assert_equal User.find(1), record.approved_by
assert_equal BigDecimal('120000'), record.gross_sales
assert_equal BigDecimal('1000'), record.deductions
assert_equal BigDecimal('119000'), record.net_sales
assert_equal BigDecimal('595'), record.pool
assert_equal BigDecimal('100000'), record.threshold
assert_equal 3, record.lines.count
payouts = record.payouts.index_by(&:user_id)
assert_equal BigDecimal('595'), payouts[2].amount
assert payouts[2].eligible?
assert_equal BigDecimal('0'), payouts[3].amount
assert_not payouts[3].eligible?
end
def test_approved_month_no_longer_follows_quickbooks_or_settings
stub_qbo
approve
stub_qbo([sale(9, 200_000)])
with_commission_settings('base_rate' => '5') do
report = CommissionMonth.for(commission_month).report
assert_equal BigDecimal('119000'), report.net_sales
assert_equal BigDecimal('595'), report.pool.amount
assert_equal [BigDecimal('595'), BigDecimal('0')], report.payouts.sort_by { |p| p.user.id }.map(&:amount)
end
end
def test_keeps_unticked_deductions
stub_qbo
record = CommissionMonth.create!(month_start: MONTH_START)
record.update!(excluded_keys: ['refund_receipt:3'])
record = approve
assert_equal BigDecimal('120000'), record.net_sales
assert_equal [false], record.lines.where(kind: 'refund_receipt').pluck(:included)
assert_not record.report.included?(october_txns.last)
end
def test_month_must_be_over
stub_qbo
month = RedmineQboCommission::Month.containing(Date.current)
assert_raises(RedmineQboCommission::Approver::Error) { approve(month) }
end
def test_cannot_approve_twice
stub_qbo
approve
assert_raises(RedmineQboCommission::Approver::Error) { approve }
end
def test_reopen
stub_qbo
record = approve
record.adjustments.create!(description: 'Check refund', amount: 100)
RedmineQboCommission::Approver.reopen(record)
record.reload
assert_not record.approved?
assert_nil record.approved_by
assert_equal 0, record.lines.count
assert_equal 0, record.payouts.count
assert_equal 1, record.adjustments.count
end
end
+78
View File
@@ -0,0 +1,78 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class MonthReportTest < ActiveSupport::TestCase
include QboCommissionTestHelper
def report(txns = october_txns, record: nil)
RedmineQboCommission::MonthReport.new(commission_month, txns: txns, commission_month: record)
end
def test_totals
report = report()
assert_equal BigDecimal('120000'), report.gross_sales
assert_equal BigDecimal('1000'), report.deductions_total
assert_equal BigDecimal('119000'), report.net_sales
assert_equal BigDecimal('595'), report.pool.amount
assert_equal %w[1 2], report.sales.map(&:txn_id)
assert_equal %w[3], report.deductions.map(&:txn_id)
end
def test_unticked_deductions_and_adjustments
record = CommissionMonth.create!(month_start: MONTH_START)
record.excluded_keys = ['refund_receipt:3']
record.save!
record.adjustments.create!(description: 'Returned lift kit, refunded by check', amount: 2_500)
record.adjustments.create!(description: 'Missed sale', amount: -500)
report = report(record: record.reload)
assert_not report.included?(october_txns.last)
assert_equal BigDecimal('2000'), report.deductions_total
assert_equal BigDecimal('118000'), report.net_sales
end
def test_every_eligible_rep_gets_the_whole_pool
create_rep(2)
create_rep(3)
create_rep(4, probation_until: MONTH_START + 5)
create_rep(5, active: false)
payouts = report.payouts.index_by { |payout| payout.user.id }
assert_equal [2, 3, 4], payouts.keys.sort
assert_equal BigDecimal('595'), payouts[2].amount
assert_equal BigDecimal('595'), payouts[3].amount
assert_equal BigDecimal('0'), payouts[4].amount
assert_match(/probation/i, payouts[4].ineligible_reason)
assert_equal BigDecimal('1190'), report.payouts_total
end
def test_probation_ending_before_the_month
create_rep(2, probation_until: MONTH_START - 1)
assert report.payouts.first.eligible?
end
def test_unticked_rep
create_rep(2)
create_rep(3)
record = CommissionMonth.create!(month_start: MONTH_START)
record.update!(unpaid_user_ids: [3])
payouts = report(record: record).payouts.index_by { |payout| payout.user.id }
assert_equal BigDecimal('595'), payouts[2].amount
assert_equal BigDecimal('0'), payouts[3].amount
assert_not payouts[3].eligible?
end
def test_below_the_threshold_pays_nothing
create_rep(2)
report = report([sale(1, 99_000)])
assert_equal BigDecimal('0'), report.payouts.first.amount
assert report.payouts.first.eligible?
end
end
+42
View File
@@ -0,0 +1,42 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class MonthTest < ActiveSupport::TestCase
Month = RedmineQboCommission::Month
def test_parse
assert_equal Date.new(2026, 11, 1), Month.parse('2026-11').start_date
assert_equal Date.new(2026, 11, 1), Month.parse('2026-11-18').start_date
assert_nil Month.parse('2026-13')
assert_nil Month.parse('nope')
end
def test_dates_and_names
month = Month.parse('2026-02')
assert_equal Date.new(2026, 2, 28), month.end_date
assert_equal '2026-02', month.to_param
assert_equal 'February 2026', month.name
assert_equal '2026-01', (month - 1).label
assert_equal '2027-01', (Month.parse('2026-12') + 1).label
end
def test_completed
month = Month.parse('2026-10')
assert month.completed?(Date.new(2026, 11, 1))
assert_not month.completed?(Date.new(2026, 10, 31))
assert_equal '2026-10', Month.last_completed(Date.new(2026, 11, 16)).label
end
def test_starts_on_the_first
assert_raises(ArgumentError) { Month.new(Date.new(2026, 11, 2)) }
end
end
+54
View File
@@ -0,0 +1,54 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class PoolTest < ActiveSupport::TestCase
def pool(sales)
RedmineQboCommission::Pool.new(BigDecimal(sales.to_s))
end
# SOP-OPS-013 §3.3
def test_sop_examples
assert_equal BigDecimal('500'), pool(100_000).amount
assert_equal BigDecimal('600'), pool(120_000).amount
assert_equal BigDecimal('812.5'), pool(150_000).amount
assert_equal BigDecimal('1062.5'), pool(175_000).amount
end
def test_nothing_below_the_threshold
assert_equal BigDecimal('0'), pool('99999.99').amount
assert_not pool('99999.99').threshold_met?
assert_equal BigDecimal('0.01'), pool('99999.99').short_of_threshold
assert_equal [], pool(50_000).parts
assert_equal BigDecimal('100000'), pool(-500).short_of_threshold
end
def test_brackets
parts = pool(175_000).parts
assert_equal [[0, 125_000, BigDecimal('0.5')], [125_000, 150_000, BigDecimal('0.75')], [150_000, 175_000, BigDecimal('1')]],
parts.map { |part| [part.from, part.to, part.rate] }
assert_equal [BigDecimal('625'), BigDecimal('187.5'), BigDecimal('250')], parts.map(&:amount)
assert_equal 1, pool(125_000).parts.size
assert_equal BigDecimal('625'), pool(125_000).amount
end
def test_rounds_to_the_cent
assert_equal BigDecimal('500.01'), pool('100001.23').amount
end
def test_settings
saved = Setting.plugin_redmine_qbo_commission
Setting.plugin_redmine_qbo_commission = RedmineQboCommission::Settings::DEFAULTS.merge('threshold' => '50000', 'base_rate' => '1')
assert_equal BigDecimal('600'), pool(60_000).amount
ensure
Setting.plugin_redmine_qbo_commission = saved
end
end
+158
View File
@@ -0,0 +1,158 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class QboSourceTest < ActiveSupport::TestCase
include QboCommissionTestHelper
# Answers the source's QuickBooks queries from lists of records, by the entity queried
class FakeSource < RedmineQboCommission::QboSource
attr_reader :queries
def initialize(month, records)
super(month)
@records = records
@queries = []
end
private
def query(_service_class, sql)
@queries << sql
entity = sql[/FROM (\w+)/, 1]
list = @records.fetch(entity, [])
ids = sql[/Id IN \(([^)]*)\)/, 1]
ids ? list.select { |record| ids.include?("'#{record.id}'") } : list
end
end
def ref(name)
Quickbooks::Model::BaseReference.new(name)
end
def link(type, id)
linked = Quickbooks::Model::LinkedTransaction.new
linked.txn_type = type
linked.txn_id = id.to_s
linked
end
def record(klass, id, total, date, tax: nil, links: [], items: [])
record = klass.new
record.id = id.to_s
record.doc_number = "D#{id}" if record.respond_to?(:doc_number=)
record.txn_date = date
record.total = BigDecimal(total.to_s)
record.customer_ref = Quickbooks::Model::BaseReference.new(id.to_s).tap { |r| r.name = "Customer #{id}" }
if tax
record.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
record.txn_tax_detail.total_tax = BigDecimal(tax.to_s)
end
record.linked_transactions = links if record.respond_to?(:linked_transactions=)
if items.any?
record.line_items = items.map do |item_id|
line = Quickbooks::Model::Line.new
line.sales_item_line_detail = Quickbooks::Model::SalesItemLineDetail.new
line.sales_item_line_detail.item_ref = Quickbooks::Model::BaseReference.new(item_id.to_s)
line
end
end
record
end
def payment(id, date)
record(Quickbooks::Model::Payment, id, 1, date)
end
def invoice(id, total, date, **options)
record(Quickbooks::Model::Invoice, id, total, date, **options)
end
def test_paid_on
assert_equal Date.new(2026, 10, 9), RedmineQboCommission::QboSource.paid_on(Date.new(2026, 10, 2), [Date.new(2026, 10, 9), nil])
# A deposit taken before the invoice: paid in full on the invoice's date
assert_equal Date.new(2026, 10, 2), RedmineQboCommission::QboSource.paid_on(Date.new(2026, 10, 2), [Date.new(2026, 8, 1)])
end
def test_invoices_count_in_the_month_paid_in_full
records = {
'Invoice' => [
invoice(1, 1070, MONTH_START + 4, tax: 70, links: [link('Payment', 50)]), # paid in October
invoice(2, 500, Date.new(2026, 9, 20), links: [link('Payment', 51)]), # September, paid in October
invoice(3, 800, MONTH_START + 2, links: [link('Payment', 52)]), # paid in November
invoice(4, 300, MONTH_START + 6, links: [link('Payment', 53), link('Estimate', 9)]), # deposit from August
invoice(5, 0, MONTH_START + 6), # voided
invoice(6, 200, Date.new(2026, 11, 3), links: [link('Payment', 50)]), # dated November
invoice(7, 100, Date.new(2026, 9, 3), links: [link('CreditMemo', 70)]) # settled by a September credit memo
],
'Payment' => [payment(50, MONTH_START + 9), payment(51, MONTH_START + 1), payment(52, Date.new(2026, 11, 2)),
payment(53, Date.new(2026, 8, 1))],
'CreditMemo' => [record(Quickbooks::Model::CreditMemo, 70, 100, Date.new(2026, 9, 30))]
}
with_commission_settings('include_sales_receipts' => '0', 'deduct_refund_receipts' => '0', 'deduct_credit_memos' => '0') do
source = FakeSource.new(commission_month, records)
txns = source.fetch
assert_equal %w[2 4 1], txns.map(&:txn_id)
first = txns.find { |txn| txn.txn_id == '1' }
assert_equal MONTH_START + 9, first.txn_date
assert_equal BigDecimal('1000'), first.net
assert_equal 'Customer 1', first.customer_name
assert_equal MONTH_START + 6, txns.find { |txn| txn.txn_id == '4' }.txn_date
assert_match(/Balance = '0' AND MetaData.LastUpdatedTime >= '2026-10-01T00:00:00/, source.queries.first)
end
end
def test_receipts_and_credit_memos
records = {
'SalesReceipt' => [record(Quickbooks::Model::SalesReceipt, 1, 107, MONTH_START + 3, tax: 7)],
'RefundReceipt' => [record(Quickbooks::Model::RefundReceipt, 2, 50, MONTH_START + 4)],
'CreditMemo' => [record(Quickbooks::Model::CreditMemo, 3, 40, MONTH_START + 5, items: [12]),
record(Quickbooks::Model::CreditMemo, 4, 100, MONTH_START + 5, items: [31]), # tech bonus
record(Quickbooks::Model::CreditMemo, 5, 60, MONTH_START + 5, items: [31, 12])]
}
with_commission_settings('excluded_item_ids' => ['31']) do
source = FakeSource.new(commission_month, records)
txns = source.fetch
assert_equal [%w[sales_receipt 1], %w[refund_receipt 2], %w[credit_memo 3], %w[credit_memo 5]],
txns.map { |txn| [txn.kind, txn.txn_id] }
assert_equal BigDecimal('100'), txns.first.net
assert(source.queries.any? { |sql| sql.include?("TxnDate >= '2026-10-01' AND TxnDate <= '2026-10-31'") })
end
end
def test_settings_leave_out_receipts_and_credit_memos
records = { 'SalesReceipt' => [record(Quickbooks::Model::SalesReceipt, 1, 100, MONTH_START)],
'RefundReceipt' => [record(Quickbooks::Model::RefundReceipt, 2, 50, MONTH_START)],
'CreditMemo' => [record(Quickbooks::Model::CreditMemo, 3, 40, MONTH_START)] }
with_commission_settings('include_sales_receipts' => '0', 'deduct_refund_receipts' => '0', 'deduct_credit_memos' => '0') do
assert_equal [], FakeSource.new(commission_month, records).fetch
end
end
def test_transactions_are_cached
source = FakeSource.new(commission_month, { 'SalesReceipt' => [record(Quickbooks::Model::SalesReceipt, 1, 100, MONTH_START)] })
RedmineQboCommission::QboSource.expects(:new).once.returns(source)
with_memory_cache do
2.times { assert_equal [BigDecimal('100')], RedmineQboCommission::QboSource.transactions(commission_month).map(&:net) }
assert RedmineQboCommission::QboSource.read_at(commission_month)
end
end
private
def with_memory_cache
saved = Rails.cache
Rails.cache = ActiveSupport::Cache::MemoryStore.new
yield
ensure
Rails.cache = saved
end
end