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:
commit
6fcd5f9b64
44 files changed
+2661
No files matched your search
@@ -0,0 +1,35 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
|
||||
# May approve a month (adjust it, approve it for payroll, reopen it)
|
||||
def self.allowed?(user = User.current)
|
||||
user.allowed_to?(:approve_sales_commission, nil, global: true)
|
||||
end
|
||||
|
||||
# May see the commission pages (approve them, or only view them)
|
||||
def self.visible?(user = User.current)
|
||||
allowed?(user) || user.allowed_to?(:view_sales_commission, nil, global: true)
|
||||
end
|
||||
|
||||
# 1234.5 => "$1,234.50", -20 => "-$20.00"
|
||||
def self.format_money(amount)
|
||||
amount = amount.to_d.round(2)
|
||||
whole, cents = format('%.2f', amount.abs).split('.')
|
||||
"#{'-' if amount.negative?}$#{whole.reverse.scan(/\d{1,3}/).join(',').reverse}.#{cents}"
|
||||
end
|
||||
|
||||
# 0.5 => "0.5%", 1.0 => "1%"
|
||||
def self.format_rate(rate)
|
||||
rate = rate.to_d
|
||||
"#{rate == rate.to_i ? rate.to_i : rate.to_s('F').sub(/0+\z/, '')}%"
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,27 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# An approved month, from what was recorded when it was approved: its transactions, the deductions that were
|
||||
# ticked, the threshold and brackets it was approved with, and each rep's payout.
|
||||
class ApprovedReport < MonthReport
|
||||
def initialize(month, txns:, commission_month:, pool_options: {})
|
||||
super
|
||||
@excluded_keys = commission_month.lines.reject(&:included).map { |line| line.to_txn.key }
|
||||
end
|
||||
|
||||
def payouts
|
||||
@payouts ||= commission_month.payouts.includes(:user).to_a.sort_by { |payout| payout.user&.name.to_s }.map do |payout|
|
||||
Payout.new(user: payout.user, amount: payout.amount.to_d,
|
||||
ineligible_reason: payout.eligible? ? nil : payout.reason.presence || '-')
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,64 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# Approves a month for payroll (SOP-OPS-013 §4): reads its sales from QuickBooks once more, then records them,
|
||||
# the deductions, the pool and each rep's payout, so the month no longer changes with QuickBooks. A month can be
|
||||
# reopened (and approved again) until payroll is run.
|
||||
class Approver
|
||||
class Error < StandardError; end
|
||||
|
||||
def initialize(month, user: User.current, source: QboSource)
|
||||
@month = month
|
||||
@user = user
|
||||
@source = source
|
||||
end
|
||||
|
||||
def approve
|
||||
raise Error, I18n.t(:error_sales_commission_month_not_over) unless @month.completed?
|
||||
|
||||
txns = @source.transactions(@month, refresh: true)
|
||||
CommissionMonth.transaction do
|
||||
record = CommissionMonth.lock.find_or_create_by!(month_start: @month.start_date)
|
||||
raise Error, I18n.t(:error_sales_commission_already_approved) if record.approved?
|
||||
|
||||
report = MonthReport.new(@month, txns: txns, commission_month: record)
|
||||
record.lines.delete_all
|
||||
txns.each { |txn| record.lines.create!(line_attributes(txn, report)) }
|
||||
record.payouts.delete_all
|
||||
report.payouts.each do |payout|
|
||||
record.payouts.create!(user: payout.user, amount: payout.amount, eligible: payout.eligible?,
|
||||
reason: payout.ineligible_reason)
|
||||
end
|
||||
record.update!(status: 'approved', approved_by: @user, approved_at: Time.current,
|
||||
gross_sales: report.gross_sales, deductions: report.deductions_total,
|
||||
net_sales: report.net_sales, pool: report.pool.amount,
|
||||
threshold: report.pool.threshold, brackets: report.pool.brackets)
|
||||
record
|
||||
end
|
||||
end
|
||||
|
||||
# Back to open: the month is worked out from QuickBooks again. The approver's choices and adjustments stay.
|
||||
def self.reopen(record)
|
||||
CommissionMonth.transaction do
|
||||
record.lines.delete_all
|
||||
record.payouts.delete_all
|
||||
record.update!(status: 'open', approved_by: nil, approved_at: nil)
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def line_attributes(txn, report)
|
||||
{ kind: txn.kind, txn_id: txn.txn_id, doc_number: txn.doc_number, customer_name: txn.customer_name,
|
||||
txn_date: txn.txn_date, total: txn.total, tax: txn.tax, included: !txn.deduction? || report.included?(txn) }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,84 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# A commission month: a calendar month, named by its year and month ("2026-11")
|
||||
class Month
|
||||
include Comparable
|
||||
|
||||
attr_reader :start_date
|
||||
|
||||
def self.containing(date)
|
||||
new(date.to_date.beginning_of_month)
|
||||
end
|
||||
|
||||
# The last month that has ended
|
||||
def self.last_completed(today = Date.current)
|
||||
containing(today) - 1
|
||||
end
|
||||
|
||||
# From "2026-11" (or any date in the month); nil when it isn't one
|
||||
def self.parse(value)
|
||||
value = value.to_s
|
||||
value = "#{value}-01" if value.match?(/\A\d{4}-\d{2}\z/)
|
||||
containing(Date.iso8601(value))
|
||||
rescue Date::Error
|
||||
nil
|
||||
end
|
||||
|
||||
def initialize(start_date)
|
||||
@start_date = start_date.to_date
|
||||
raise ArgumentError, 'A commission month starts on its first day' unless @start_date.day == 1
|
||||
end
|
||||
|
||||
def end_date
|
||||
start_date.end_of_month
|
||||
end
|
||||
|
||||
def range
|
||||
start_date..end_date
|
||||
end
|
||||
|
||||
# "2026-11"
|
||||
def label
|
||||
start_date.strftime('%Y-%m')
|
||||
end
|
||||
|
||||
# "November 2026"
|
||||
def name
|
||||
"#{I18n.t('date.month_names')[start_date.month]} #{start_date.year}"
|
||||
end
|
||||
|
||||
# Whether the month is over, so its sales are final
|
||||
def completed?(today = Date.current)
|
||||
end_date < today
|
||||
end
|
||||
|
||||
def +(other)
|
||||
Month.new(start_date >> other)
|
||||
end
|
||||
|
||||
def -(other)
|
||||
self + -other
|
||||
end
|
||||
|
||||
def <=>(other)
|
||||
start_date <=> other.start_date
|
||||
end
|
||||
|
||||
def to_param
|
||||
label
|
||||
end
|
||||
|
||||
def to_s
|
||||
label
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,81 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# A month's commission (SOP-OPS-013): its paid sales, the deductions from them, the commission pool, and what
|
||||
# each sales rep is paid. Every eligible rep is paid the whole pool.
|
||||
#
|
||||
# An open month is worked out from QuickBooks as it stands (QboSource), with the approver's choices kept on its
|
||||
# CommissionMonth; an approved month from what was recorded when it was approved (CommissionMonth#report).
|
||||
class MonthReport
|
||||
Payout = Struct.new(:user, :amount, :ineligible_reason, keyword_init: true) do
|
||||
def eligible?
|
||||
ineligible_reason.nil?
|
||||
end
|
||||
end
|
||||
|
||||
attr_reader :month, :txns, :adjustments, :commission_month
|
||||
|
||||
# excluded_keys: the deductions the approver unticked (Txn#key); unpaid_user_ids: the reps they unticked
|
||||
def initialize(month, txns:, commission_month: nil, pool_options: {})
|
||||
@month = month
|
||||
@txns = txns
|
||||
@commission_month = commission_month
|
||||
@adjustments = commission_month ? commission_month.adjustments.to_a : []
|
||||
@excluded_keys = commission_month ? commission_month.excluded_keys : []
|
||||
@unpaid_user_ids = commission_month ? commission_month.unpaid_user_ids : []
|
||||
@pool_options = pool_options
|
||||
end
|
||||
|
||||
def sales
|
||||
@sales ||= txns.select(&:sale?)
|
||||
end
|
||||
|
||||
def deductions
|
||||
@deductions ||= txns.select(&:deduction?)
|
||||
end
|
||||
|
||||
def included?(txn)
|
||||
!@excluded_keys.include?(txn.key)
|
||||
end
|
||||
|
||||
def gross_sales
|
||||
sales.sum(BigDecimal('0'), &:net)
|
||||
end
|
||||
|
||||
# The ticked refunds and credit memos, and the adjustments
|
||||
def deductions_total
|
||||
deductions.select { |txn| included?(txn) }.sum(BigDecimal('0'), &:net) +
|
||||
adjustments.sum(BigDecimal('0')) { |adjustment| adjustment.amount.to_d }
|
||||
end
|
||||
|
||||
# The sales the commission is worked out on
|
||||
def net_sales
|
||||
gross_sales - deductions_total
|
||||
end
|
||||
|
||||
def pool
|
||||
@pool ||= Pool.new(net_sales, **@pool_options)
|
||||
end
|
||||
|
||||
def payouts
|
||||
@payouts ||= CommissionRep.sorted.select(&:active?).map do |rep|
|
||||
reason = rep.ineligible_reason(month)
|
||||
reason ||= I18n.t(:text_sales_commission_unticked) if @unpaid_user_ids.include?(rep.user_id)
|
||||
Payout.new(user: rep.user, amount: pool.threshold_met? && reason.nil? ? pool.amount : BigDecimal('0'),
|
||||
ineligible_reason: reason)
|
||||
end
|
||||
end
|
||||
|
||||
def payouts_total
|
||||
payouts.sum(BigDecimal('0'), &:amount)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# The commission pool for a month's sales (SOP-OPS-013 §3): nothing below the threshold; at or above it, every
|
||||
# dollar of the month from the first one, each bracket at its own rate (marginal rates).
|
||||
#
|
||||
# Pool.new(BigDecimal('150000')).amount # => 812.5 (125,000 x 0.5% + 25,000 x 0.75%)
|
||||
class Pool
|
||||
# One bracket's share: sales from..to at rate percent
|
||||
Part = Struct.new(:from, :to, :rate, :amount, keyword_init: true) do
|
||||
def sales
|
||||
to - from
|
||||
end
|
||||
end
|
||||
|
||||
attr_reader :sales, :threshold, :brackets
|
||||
|
||||
def initialize(sales, threshold: Settings.threshold, brackets: Settings.brackets)
|
||||
@sales = sales.to_d
|
||||
@threshold = threshold.to_d
|
||||
@brackets = brackets
|
||||
end
|
||||
|
||||
def threshold_met?
|
||||
sales.positive? && sales >= threshold
|
||||
end
|
||||
|
||||
# Sales still needed to reach the threshold
|
||||
def short_of_threshold
|
||||
threshold_met? ? BigDecimal('0') : threshold - [sales, BigDecimal('0')].max
|
||||
end
|
||||
|
||||
def parts
|
||||
return [] unless threshold_met?
|
||||
|
||||
@parts ||= begin
|
||||
lower = BigDecimal('0')
|
||||
brackets.each_with_object([]) do |(limit, rate), parts|
|
||||
upper = limit ? [sales, limit.to_d].min : sales
|
||||
break parts if upper <= lower
|
||||
|
||||
parts << Part.new(from: lower, to: upper, rate: rate.to_d, amount: (upper - lower) * rate.to_d / 100)
|
||||
break parts unless limit
|
||||
|
||||
lower = limit.to_d
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Each rep's commission, to the cent
|
||||
def amount
|
||||
parts.sum(BigDecimal('0'), &:amount).round(2, BigDecimal::ROUND_HALF_UP)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,136 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# Reads a month's paid sales and deductions from QuickBooks Online (SOP-OPS-013 §4):
|
||||
#
|
||||
# * Invoices paid in full that month. An invoice is paid in full on the later of its own date and the date of
|
||||
# the last payment or credit memo applied to it, so a deposit taken months before the work counts in the
|
||||
# month it was invoiced and the last of it paid. QuickBooks updates an invoice when a payment is applied to
|
||||
# it, so the invoices with a $0 balance changed since the month began are all that need reading.
|
||||
# * Sales receipts dated in the month (counter sales paid on the spot), if the settings say so.
|
||||
# * Refund receipts and credit memos dated in the month, as deductions, if the settings say so. Credit memos
|
||||
# made only of the excluded products/services (e.g. tech bonus credits) aren't returns and are left out.
|
||||
#
|
||||
# Voided transactions (a $0 total) don't count. Amounts are kept without sales tax.
|
||||
class QboSource
|
||||
CACHE_TTL = 15.minutes
|
||||
BATCH = 1000
|
||||
IDS_PER_QUERY = 100
|
||||
|
||||
# The month's transactions, read from QuickBooks at most every CACHE_TTL (refresh: true reads them now)
|
||||
def self.transactions(month, refresh: false)
|
||||
Rails.cache.delete(cache_key(month)) if refresh
|
||||
cached = Rails.cache.fetch(cache_key(month), expires_in: CACHE_TTL) do
|
||||
{ 'read_at' => Time.current.iso8601, 'txns' => new(month).fetch.map(&:to_cache) }
|
||||
end
|
||||
cached['txns'].map { |hash| Txn.from_h(hash) }
|
||||
end
|
||||
|
||||
# When the cached transactions were read from QuickBooks, or nil when they aren't cached
|
||||
def self.read_at(month)
|
||||
value = Rails.cache.read(cache_key(month))
|
||||
value && Time.zone.parse(value['read_at'].to_s)
|
||||
end
|
||||
|
||||
def self.cache_key(month)
|
||||
"redmine_qbo_commission/txns/#{month.to_param}"
|
||||
end
|
||||
|
||||
# The day an invoice was paid in full: the later of its date and the dates of what was applied to it
|
||||
def self.paid_on(txn_date, applied_dates)
|
||||
[txn_date, *applied_dates.compact].compact.max
|
||||
end
|
||||
|
||||
attr_reader :month
|
||||
|
||||
def initialize(month)
|
||||
@month = month
|
||||
end
|
||||
|
||||
def fetch
|
||||
txns = invoices
|
||||
txns += dated(Quickbooks::Service::SalesReceipt, 'SalesReceipt', 'sales_receipt') if Settings.include_sales_receipts?
|
||||
txns += dated(Quickbooks::Service::RefundReceipt, 'RefundReceipt', 'refund_receipt') if Settings.deduct_refund_receipts?
|
||||
txns += credit_memos if Settings.deduct_credit_memos?
|
||||
txns.sort_by { |txn| [txn.txn_date, txn.doc_number.to_s] }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def invoices
|
||||
since = month.start_date.in_time_zone.iso8601
|
||||
remote = query(Quickbooks::Service::Invoice,
|
||||
"SELECT * FROM Invoice WHERE Balance = '0' AND MetaData.LastUpdatedTime >= '#{since}'")
|
||||
remote = remote.select { |invoice| invoice.total.to_d.positive? && invoice.txn_date && invoice.txn_date <= month.end_date }
|
||||
dates = applied_dates(remote)
|
||||
remote.filter_map do |invoice|
|
||||
applied = linked(invoice).map { |link| dates[[link.txn_type, link.txn_id.to_s]] }
|
||||
paid_on = self.class.paid_on(invoice.txn_date, applied)
|
||||
txn('invoice', invoice, paid_on) if month.range.cover?(paid_on)
|
||||
end
|
||||
end
|
||||
|
||||
def credit_memos
|
||||
excluded = Settings.excluded_item_ids
|
||||
dated(Quickbooks::Service::CreditMemo, 'CreditMemo', 'credit_memo') do |memo|
|
||||
items = Array(memo.line_items).filter_map { |line| line.sales_item_line_detail&.item_ref&.value&.to_s }
|
||||
excluded.empty? || items.empty? || !items.all? { |item| excluded.include?(item) }
|
||||
end
|
||||
end
|
||||
|
||||
# The transactions of a type dated in the month (that the block keeps)
|
||||
def dated(service_class, entity, kind)
|
||||
remote = query(service_class, "SELECT * FROM #{entity} WHERE TxnDate >= '#{month.start_date.iso8601}' " \
|
||||
"AND TxnDate <= '#{month.end_date.iso8601}'")
|
||||
remote.filter_map do |record|
|
||||
next unless record.total.to_d.positive?
|
||||
next if block_given? && !yield(record)
|
||||
|
||||
txn(kind, record, record.txn_date)
|
||||
end
|
||||
end
|
||||
|
||||
# { ["Payment", "123"] => Date } for the payments and credit memos applied to the invoices
|
||||
def applied_dates(invoices)
|
||||
ids = Hash.new { |hash, type| hash[type] = [] }
|
||||
invoices.each { |invoice| linked(invoice).each { |link| ids[link.txn_type] << link.txn_id.to_s } }
|
||||
{ 'Payment' => Quickbooks::Service::Payment, 'CreditMemo' => Quickbooks::Service::CreditMemo }
|
||||
.each_with_object({}) do |(type, service_class), dates|
|
||||
ids[type].uniq.each_slice(IDS_PER_QUERY) do |slice|
|
||||
list = slice.map { |id| "'#{id.gsub(/\D/, '')}'" }.join(',')
|
||||
query(service_class, "SELECT * FROM #{type} WHERE Id IN (#{list})").each do |record|
|
||||
dates[[type, record.id.to_s]] = record.txn_date
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def linked(invoice)
|
||||
Array(invoice.linked_transactions).select { |link| %w[Payment CreditMemo].include?(link.txn_type) }
|
||||
end
|
||||
|
||||
def txn(kind, record, date)
|
||||
Txn.new(kind: kind, txn_id: record.id.to_s, doc_number: record.doc_number.to_s,
|
||||
customer_name: record.customer_ref&.name.to_s, txn_date: date,
|
||||
total: record.total.to_d, tax: record.txn_tax_detail&.total_tax.to_d)
|
||||
end
|
||||
|
||||
def query(service_class, sql)
|
||||
results = []
|
||||
qbo = QboConnectionService.current!
|
||||
qbo.perform_authenticated_request do |access_token|
|
||||
service = service_class.new(company_id: qbo.realm_id, access_token: access_token)
|
||||
service.query_in_batches(sql, per_page: BATCH) { |batch| results.concat(Array(batch)) }
|
||||
end
|
||||
results
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,72 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# The plugin's settings (Administration » Plugins » Redmine QBO Commission plugin » Configure). The defaults follow
|
||||
# SOP-OPS-013: nothing below $100,000 of monthly sales; at or above it, the whole month from the first dollar at
|
||||
# 0.5% up to $125,000, 0.75% from $125,000 to $150,000 and 1% above $150,000.
|
||||
module Settings
|
||||
DEFAULTS = {
|
||||
'threshold' => '100000',
|
||||
'base_limit' => '125000',
|
||||
'base_rate' => '0.5',
|
||||
'step_limit' => '150000',
|
||||
'step_rate' => '0.75',
|
||||
'top_rate' => '1',
|
||||
# Counter sales rung up as sales receipts are paid sales too, on their date
|
||||
'include_sales_receipts' => '1',
|
||||
# Returns: refund receipts and credit memos dated in the month are deducted
|
||||
'deduct_refund_receipts' => '1',
|
||||
'deduct_credit_memos' => '1',
|
||||
# Credit memos made only of these products/services aren't returns (e.g. the tech bonus credit memos)
|
||||
'excluded_item_ids' => []
|
||||
}.freeze
|
||||
|
||||
def self.values
|
||||
DEFAULTS.merge((Setting.plugin_redmine_qbo_commission.presence || {}).to_h.stringify_keys)
|
||||
end
|
||||
|
||||
def self.threshold
|
||||
number('threshold')
|
||||
end
|
||||
|
||||
# The marginal brackets, as [[upper limit or nil, rate in percent]]
|
||||
def self.brackets
|
||||
base_limit = number('base_limit')
|
||||
step_limit = [number('step_limit'), base_limit].max
|
||||
[[base_limit, number('base_rate')], [step_limit, number('step_rate')], [nil, number('top_rate')]]
|
||||
end
|
||||
|
||||
def self.include_sales_receipts?
|
||||
values['include_sales_receipts'].to_s == '1'
|
||||
end
|
||||
|
||||
def self.deduct_refund_receipts?
|
||||
values['deduct_refund_receipts'].to_s == '1'
|
||||
end
|
||||
|
||||
def self.deduct_credit_memos?
|
||||
values['deduct_credit_memos'].to_s == '1'
|
||||
end
|
||||
|
||||
# The products/services picked in the settings, and redmine_qbo_bonus' own when it's installed
|
||||
def self.excluded_item_ids
|
||||
ids = Array(values['excluded_item_ids']).map(&:to_s).reject(&:blank?)
|
||||
ids << RedmineQboBonus::Settings.item_id.to_s if defined?(RedmineQboBonus::Settings) && RedmineQboBonus::Settings.item_id
|
||||
ids.uniq
|
||||
end
|
||||
|
||||
def self.number(key)
|
||||
number = BigDecimal(values[key].to_s.strip, exception: false) || BigDecimal(DEFAULTS[key])
|
||||
number.negative? ? BigDecimal('0') : number
|
||||
end
|
||||
private_class_method :number
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,61 @@
|
||||
#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.
|
||||
|
||||
module RedmineQboCommission
|
||||
# A QuickBooks transaction that counts toward a month: a paid sale (an invoice paid in full that month, or a
|
||||
# sales receipt) or a deduction (a refund receipt or credit memo). Amounts are without sales tax.
|
||||
class Txn < Struct.new(:kind, :txn_id, :doc_number, :customer_name, :txn_date, :total, :tax, keyword_init: true)
|
||||
SALES = %w[invoice sales_receipt].freeze
|
||||
DEDUCTIONS = %w[refund_receipt credit_memo].freeze
|
||||
KINDS = (SALES + DEDUCTIONS).freeze
|
||||
|
||||
# From a cached hash (Rails.cache keeps plain values)
|
||||
def self.from_h(hash)
|
||||
hash = hash.to_h.symbolize_keys
|
||||
new(kind: hash[:kind].to_s, txn_id: hash[:txn_id].to_s, doc_number: hash[:doc_number].to_s,
|
||||
customer_name: hash[:customer_name].to_s, txn_date: hash[:txn_date] && Date.parse(hash[:txn_date].to_s),
|
||||
total: BigDecimal(hash[:total].to_s), tax: BigDecimal(hash[:tax].to_s))
|
||||
end
|
||||
|
||||
def to_cache
|
||||
to_h.merge(txn_date: txn_date&.iso8601, total: total.to_d.to_s('F'), tax: tax.to_d.to_s('F'))
|
||||
end
|
||||
|
||||
# "credit_memo:123": how a deduction is picked on the month page
|
||||
def key
|
||||
"#{kind}:#{txn_id}"
|
||||
end
|
||||
|
||||
def sale?
|
||||
SALES.include?(kind)
|
||||
end
|
||||
|
||||
def deduction?
|
||||
DEDUCTIONS.include?(kind)
|
||||
end
|
||||
|
||||
# The total without sales tax
|
||||
def net
|
||||
total.to_d - tax.to_d
|
||||
end
|
||||
|
||||
def kind_name
|
||||
I18n.t("label_sales_commission_kind_#{kind}")
|
||||
end
|
||||
|
||||
# The transaction's page in QuickBooks
|
||||
def qbo_url
|
||||
host = defined?(RedmineQbo) && RedmineQbo.respond_to?(:sandbox_mode?) && RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'
|
||||
page = { 'invoice' => 'invoice', 'sales_receipt' => 'salesreceipt', 'refund_receipt' => 'refundreceipt',
|
||||
'credit_memo' => 'creditmemo' }[kind]
|
||||
"https://#{host}.qbo.intuit.com/app/#{page}?txnId=#{txn_id}"
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user