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,21 @@
|
||||
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.
|
||||
@@ -0,0 +1,59 @@
|
||||
# Redmine QBO Commission
|
||||
|
||||
The monthly sales commission for sales reps, service advisors and counter sales staff (SOP-OPS-013, *Monthly Sales Commission & Revenue Bonus*). The month's paid sales are read from QuickBooks Online and the commission pool is worked out. Management then approves the month, and each rep's payout is recorded for payroll.
|
||||
|
||||
* **Threshold**: no commission for a month below $100,000 of sales. At or above it, the whole month counts, from the first dollar.
|
||||
* **Rates** (marginal): 0.5% of sales up to $125,000, 0.75% from $125,000 to $150,000, and 1% above $150,000. A $150,000 month pays $625.00 + $187.50 = $812.50.
|
||||
* **Payouts**: every eligible rep is paid the whole commission. A rep isn't paid for a month if they're inactive, or if any day of the month falls in their 90-day probation. The approver can also untick a rep for the month.
|
||||
|
||||
All the numbers can be changed in the settings.
|
||||
|
||||
## What counts as a sale
|
||||
|
||||
* **Invoices paid in full in the 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. A deposit taken months before the work counts in the month the job was invoiced and the last of it paid.
|
||||
* **Sales receipts dated in the month** (counter sales paid on the spot). These can be turned off in the settings.
|
||||
|
||||
Amounts are without sales tax. Voided transactions ($0) don't count.
|
||||
|
||||
## Deductions
|
||||
|
||||
Returns, canceled orders and refunded deposits are deducted from the month's sales (SOP-OPS-013 §4):
|
||||
|
||||
* **Refund receipts and credit memos dated in the month** are listed and ticked. Untick one that isn't a return. Credit memos made only of the products/services picked in the settings aren't listed. The tech bonus credit memos from [redmine_qbo_bonus](https://gitea.rickbarrette.org/ricky/redmine_qbo_bonus) are always left out.
|
||||
* **Adjustments** cover anything QuickBooks doesn't show as a refund, such as a return refunded by company check. A negative adjustment adds sales back.
|
||||
|
||||
## Approving a month
|
||||
|
||||
**Sales commission** in the top menu opens this month, so far. It shows the month's sales, how far they are from the threshold, the pool, and each rep's payout. QuickBooks is read at most every 15 minutes; **Read from QuickBooks** reads it again now.
|
||||
|
||||
Once the month is over, **Approve for payroll** reads QuickBooks one last time. It records the sales, deductions, threshold, rates and payouts, so the month no longer changes with QuickBooks or the settings. **Payroll CSV** downloads each rep's payout. **Reopen** puts an approved month back to being worked out from QuickBooks; the unticked items, adjustments and notes are kept.
|
||||
|
||||
Approvers see each transaction linked to QuickBooks, and the list of months with the month picker.
|
||||
|
||||
## Requirements
|
||||
|
||||
* Redmine 7
|
||||
* redmine_qbo 2026.11.0 or later, connected to QuickBooks Online
|
||||
|
||||
## Installation
|
||||
|
||||
```
|
||||
cd /path/to/redmine/plugins
|
||||
git clone https://gitea.rickbarrette.org/ricky/redmine_qbo_commission.git
|
||||
cd ..
|
||||
bundle exec rake redmine:plugins:migrate
|
||||
```
|
||||
|
||||
Restart Redmine, then:
|
||||
|
||||
1. **Administration » Commission reps**: add each sales rep, with the last day of their probation if they're in it.
|
||||
2. **Administration » Plugins » Redmine QBO Commission plugin » Configure**: check the threshold, rates and what counts.
|
||||
3. **Administration » Roles and permissions**: give **Approve sales commission** to Management and Bookkeeping. Give **View sales commission** to the sales reps, so they can follow the month toward the threshold. Both are global permissions, so they apply to any role the user has in any project.
|
||||
|
||||
**View sales commission** shows a month's sales, pool and payouts, read-only. It doesn't link to QuickBooks, list the months, change or approve a month, or download the payroll CSV.
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
RAILS_ENV=test bundle exec rake redmine:plugins:test NAME=redmine_qbo_commission
|
||||
```
|
||||
@@ -0,0 +1,66 @@
|
||||
#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.
|
||||
|
||||
# Administration » Commission reps: who earns the monthly sales commission
|
||||
class CommissionRepsController < ApplicationController
|
||||
layout 'admin'
|
||||
self.main_menu = false
|
||||
menu_item :commission_reps
|
||||
|
||||
before_action :require_admin
|
||||
before_action :find_rep, only: [:edit, :update, :destroy]
|
||||
|
||||
def index
|
||||
@reps = CommissionRep.sorted.to_a
|
||||
end
|
||||
|
||||
def new
|
||||
@rep = CommissionRep.new
|
||||
end
|
||||
|
||||
def create
|
||||
@rep = CommissionRep.new(rep_params)
|
||||
if @rep.save
|
||||
flash[:notice] = l(:notice_successful_create)
|
||||
redirect_to commission_reps_path
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def edit; end
|
||||
|
||||
def update
|
||||
if @rep.update(rep_params.except(:user_id))
|
||||
flash[:notice] = l(:notice_successful_update)
|
||||
redirect_to commission_reps_path
|
||||
else
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
@rep.destroy
|
||||
flash[:notice] = l(:notice_successful_delete)
|
||||
redirect_to commission_reps_path
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_rep
|
||||
@rep = CommissionRep.find(params[:id])
|
||||
rescue ActiveRecord::RecordNotFound
|
||||
render_404
|
||||
end
|
||||
|
||||
def rep_params
|
||||
params.require(:commission_rep).permit(:user_id, :probation_until, :active)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,157 @@
|
||||
#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 'csv'
|
||||
|
||||
# Monthly sales commission (SOP-OPS-013): the months, a month's sales, pool and payouts, and approving it for payroll
|
||||
class SalesCommissionsController < ApplicationController
|
||||
self.main_menu = false
|
||||
menu_item :sales_commissions
|
||||
|
||||
before_action :authorize_global
|
||||
before_action :find_month, except: [:index, :current]
|
||||
before_action :find_open_record, only: [:update, :add_adjustment, :remove_adjustment]
|
||||
|
||||
helper :sales_commissions
|
||||
|
||||
MONTHS_TO_PICK = 12
|
||||
|
||||
def index
|
||||
# The month picker
|
||||
month = RedmineQboCommission::Month.parse(params[:month]) if params[:month].present?
|
||||
return redirect_to(sales_commission_month_path(month.to_param)) if month
|
||||
|
||||
@commission_months = CommissionMonth.recent.includes(:approved_by, :payouts).limit(36).to_a
|
||||
@months = (0...MONTHS_TO_PICK).map { |n| RedmineQboCommission::Month.containing(Date.current) - n }
|
||||
end
|
||||
|
||||
# The top menu opens this month, so far
|
||||
def current
|
||||
redirect_to sales_commission_month_path(RedmineQboCommission::Month.containing(Date.current).to_param)
|
||||
end
|
||||
|
||||
def show
|
||||
@record = CommissionMonth.for(@month)
|
||||
@can_approve = RedmineQboCommission.allowed?
|
||||
if @record&.approved?
|
||||
@report = @record.report
|
||||
else
|
||||
@report = RedmineQboCommission::MonthReport.new(@month, txns: read_transactions, commission_month: @record)
|
||||
@read_at = RedmineQboCommission::QboSource.read_at(@month)
|
||||
end
|
||||
|
||||
respond_to do |format|
|
||||
format.html
|
||||
format.csv do
|
||||
return render_403 unless @can_approve && @record&.approved?
|
||||
|
||||
send_data payroll_csv, type: 'text/csv; header=present',
|
||||
filename: "sales-commission-#{@month.label}.csv"
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Saves the approver's choices (ticked deductions and reps, notes), and approves the month when asked
|
||||
def update
|
||||
if params[:shown].present?
|
||||
@record.excluded_keys = Array(params[:shown_deductions]) - Array(params[:included])
|
||||
@record.unpaid_user_ids = Array(params[:shown_reps]).map(&:to_i) - Array(params[:eligible]).map(&:to_i)
|
||||
end
|
||||
@record.notes = params[:notes] if params.key?(:notes)
|
||||
@record.save!
|
||||
|
||||
if params[:approve].present?
|
||||
RedmineQboCommission::Approver.new(@month).approve
|
||||
flash[:notice] = l(:notice_sales_commission_approved, month: @month.name)
|
||||
else
|
||||
flash[:notice] = l(:notice_successful_update)
|
||||
end
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
rescue RedmineQboCommission::Approver::Error => e
|
||||
flash[:error] = e.message
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "[redmine_qbo_commission] Approving #{@month.label}: #{e.message}"
|
||||
flash[:error] = l(:error_sales_commission_qbo, error: e.message)
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
end
|
||||
|
||||
# Reads the month from QuickBooks again now
|
||||
def refresh
|
||||
RedmineQboCommission::QboSource.transactions(@month, refresh: true)
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
rescue StandardError => e
|
||||
flash[:error] = l(:error_sales_commission_qbo, error: e.message)
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
end
|
||||
|
||||
def reopen
|
||||
record = CommissionMonth.for(@month)
|
||||
return render_404 unless record&.approved?
|
||||
|
||||
RedmineQboCommission::Approver.reopen(record)
|
||||
flash[:notice] = l(:notice_sales_commission_reopened, month: @month.name)
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
end
|
||||
|
||||
def add_adjustment
|
||||
adjustment = @record.adjustments.build(description: params[:description].to_s.strip, author: User.current,
|
||||
amount: BigDecimal(params[:amount].to_s.delete(',$ '), exception: false))
|
||||
if adjustment.save
|
||||
flash[:notice] = l(:notice_successful_create)
|
||||
else
|
||||
flash[:error] = adjustment.errors.full_messages.join(', ')
|
||||
end
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
end
|
||||
|
||||
def remove_adjustment
|
||||
@record.adjustments.find(params[:id]).destroy
|
||||
flash[:notice] = l(:notice_successful_delete)
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
rescue ActiveRecord::RecordNotFound
|
||||
render_404
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def find_month
|
||||
@month = RedmineQboCommission::Month.parse(params[:month])
|
||||
render_404 unless @month
|
||||
end
|
||||
|
||||
# Only an open month can be changed
|
||||
def find_open_record
|
||||
@record = CommissionMonth.find_or_create_by!(month_start: @month.start_date)
|
||||
return unless @record.approved?
|
||||
|
||||
flash[:error] = l(:error_sales_commission_already_approved)
|
||||
redirect_to sales_commission_month_path(@month.to_param)
|
||||
end
|
||||
|
||||
def read_transactions
|
||||
RedmineQboCommission::QboSource.transactions(@month)
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "[redmine_qbo_commission] Reading #{@month.label} from QuickBooks: #{e.message}"
|
||||
@error = l(:error_sales_commission_qbo, error: e.message)
|
||||
[]
|
||||
end
|
||||
|
||||
def payroll_csv
|
||||
CSV.generate do |csv|
|
||||
csv << [l(:label_sales_commission_month), l(:field_login), l(:label_user), l(:label_sales_commission_amount),
|
||||
l(:label_sales_commission_paid), l(:label_sales_commission_reason)]
|
||||
@report.payouts.each do |payout|
|
||||
csv << [@month.label, payout.user&.login, payout.user&.name, format('%.2f', payout.amount),
|
||||
payout.eligible? ? l(:general_text_Yes) : l(:general_text_No), payout.ineligible_reason]
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,30 @@
|
||||
#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 SalesCommissionsHelper
|
||||
def commission_money(amount)
|
||||
RedmineQboCommission.format_money(amount)
|
||||
end
|
||||
|
||||
def commission_rate(rate)
|
||||
RedmineQboCommission.format_rate(rate)
|
||||
end
|
||||
|
||||
# The transaction's number, linked to it in QuickBooks for those who approve
|
||||
def commission_txn_link(txn, can_approve)
|
||||
label = txn.doc_number.present? ? "##{txn.doc_number}" : txn.kind_name
|
||||
can_approve ? link_to(label, txn.qbo_url, target: '_blank', rel: 'noopener') : label
|
||||
end
|
||||
|
||||
# "Approved by Jane Smith on 12/03/2026 09:15 AM"
|
||||
def commission_approved_text(record)
|
||||
l(:text_sales_commission_approved_by, user: record.approved_by&.name.to_s, time: format_time(record.approved_at))
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,19 @@
|
||||
#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.
|
||||
|
||||
# A deduction the approver adds by hand (e.g. a return refunded by company check), or with a negative amount,
|
||||
# sales added back
|
||||
class CommissionAdjustment < ApplicationRecord
|
||||
belongs_to :commission_month
|
||||
belongs_to :author, class_name: 'User', optional: true
|
||||
|
||||
validates :description, presence: true, length: { maximum: 255 }
|
||||
validates :amount, presence: true, numericality: { other_than: 0 }
|
||||
end
|
||||
@@ -0,0 +1,21 @@
|
||||
#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.
|
||||
|
||||
# A QuickBooks transaction as it counted toward an approved month
|
||||
class CommissionLine < ApplicationRecord
|
||||
belongs_to :commission_month
|
||||
|
||||
validates :kind, inclusion: { in: RedmineQboCommission::Txn::KINDS }
|
||||
|
||||
def to_txn
|
||||
RedmineQboCommission::Txn.new(kind: kind, txn_id: txn_id, doc_number: doc_number, customer_name: customer_name,
|
||||
txn_date: txn_date, total: total.to_d, tax: tax.to_d)
|
||||
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.
|
||||
|
||||
# A commission month: the approver's choices while it's open, and once it's approved, what was approved for payroll
|
||||
class CommissionMonth < ApplicationRecord
|
||||
STATUSES = %w[open approved].freeze
|
||||
|
||||
belongs_to :approved_by, class_name: 'User', optional: true
|
||||
has_many :lines, -> { order(:txn_date, :id) }, class_name: 'CommissionLine', dependent: :delete_all
|
||||
has_many :adjustments, -> { order(:id) }, class_name: 'CommissionAdjustment', dependent: :delete_all
|
||||
has_many :payouts, class_name: 'CommissionPayout', dependent: :delete_all
|
||||
|
||||
validates :month_start, presence: true, uniqueness: true
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
|
||||
scope :recent, -> { order(month_start: :desc) }
|
||||
|
||||
def self.for(month)
|
||||
find_by(month_start: month.start_date)
|
||||
end
|
||||
|
||||
def month
|
||||
RedmineQboCommission::Month.new(month_start)
|
||||
end
|
||||
|
||||
def approved?
|
||||
status == 'approved'
|
||||
end
|
||||
|
||||
# The deductions the approver unticked (Txn#key)
|
||||
def excluded_keys
|
||||
json_list(:excluded_keys)
|
||||
end
|
||||
|
||||
def excluded_keys=(keys)
|
||||
self[:excluded_keys] = Array(keys).map(&:to_s).uniq.sort.to_json
|
||||
end
|
||||
|
||||
# The reps the approver unticked
|
||||
def unpaid_user_ids
|
||||
json_list(:unpaid_user_ids).map(&:to_i)
|
||||
end
|
||||
|
||||
def unpaid_user_ids=(ids)
|
||||
self[:unpaid_user_ids] = Array(ids).map(&:to_i).uniq.sort.to_json
|
||||
end
|
||||
|
||||
# The brackets the month was approved with, as [[limit or nil, rate]]
|
||||
def brackets
|
||||
JSON.parse(self[:brackets].presence || '[]').map { |limit, rate| [limit && BigDecimal(limit.to_s), BigDecimal(rate.to_s)] }
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
|
||||
def brackets=(brackets)
|
||||
self[:brackets] = brackets.map { |limit, rate| [limit&.to_d&.to_s('F'), rate.to_d.to_s('F')] }.to_json
|
||||
end
|
||||
|
||||
# An approved month's report, from what was recorded
|
||||
def report
|
||||
txns = lines.map(&:to_txn)
|
||||
RedmineQboCommission::ApprovedReport.new(month, txns: txns, commission_month: self,
|
||||
pool_options: { threshold: threshold, brackets: brackets })
|
||||
end
|
||||
|
||||
def payouts_total
|
||||
payouts.sum(&:amount)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def json_list(attribute)
|
||||
Array(JSON.parse(self[attribute].presence || '[]'))
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,17 @@
|
||||
#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.
|
||||
|
||||
# A sales rep's commission for an approved month, or why they weren't paid
|
||||
class CommissionPayout < ApplicationRecord
|
||||
belongs_to :commission_month
|
||||
belongs_to :user
|
||||
|
||||
validates :user_id, uniqueness: { scope: :commission_month_id }
|
||||
end
|
||||
@@ -0,0 +1,36 @@
|
||||
#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.
|
||||
|
||||
# A sales rep who earns the monthly commission (SOP-OPS-013 §2)
|
||||
class CommissionRep < ApplicationRecord
|
||||
belongs_to :user
|
||||
|
||||
validates :user_id, presence: true, uniqueness: true
|
||||
|
||||
scope :active, -> { where(active: true) }
|
||||
scope :sorted, -> { includes(:user).order(Arel.sql('users.firstname, users.lastname')).references(:users) }
|
||||
|
||||
def name
|
||||
user&.name.to_s
|
||||
end
|
||||
|
||||
# In the 90-day probation on any day of the month (no commission that month)
|
||||
def on_probation?(month)
|
||||
probation_until.present? && probation_until >= month.start_date
|
||||
end
|
||||
|
||||
# Why the rep isn't paid for the month, or nil
|
||||
def ineligible_reason(month)
|
||||
return I18n.t(:text_sales_commission_inactive) unless active?
|
||||
return I18n.t(:text_sales_commission_probation, date: I18n.l(probation_until)) if on_probation?(month)
|
||||
|
||||
nil
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,15 @@
|
||||
<%= error_messages_for @rep %>
|
||||
<% taken = CommissionRep.where.not(id: @rep.id).pluck(:user_id) %>
|
||||
<% users = User.active.sorted.where.not(id: taken).to_a %>
|
||||
<% users << @rep.user if @rep.user && !users.include?(@rep.user) %>
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<%= f.select :user_id, users.map { |user| [user.name, user.id] }, { include_blank: true, required: true, label: :field_user },
|
||||
{ disabled: @rep.persisted? } %>
|
||||
</p>
|
||||
<p>
|
||||
<%= f.date_field :probation_until, label: :field_commission_rep_probation_until %>
|
||||
<em class="info"><%= l(:text_commission_rep_probation) %></em>
|
||||
</p>
|
||||
<p><%= f.check_box :active %></p>
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
<h2><%= link_to l(:label_commission_rep_plural), commission_reps_path %> » <%= @rep.name %></h2>
|
||||
|
||||
<%= labelled_form_for @rep, url: commission_rep_path(@rep), method: :patch do |f| %>
|
||||
<%= render partial: 'commission_reps/form', locals: { f: f } %>
|
||||
<%= submit_tag l(:button_save) %>
|
||||
<% end %>
|
||||
|
||||
<% html_title @rep.name %>
|
||||
@@ -0,0 +1,41 @@
|
||||
<div class="contextual">
|
||||
<%= link_to sprite_icon('add', l(:label_commission_rep_new)), new_commission_rep_path, class: 'icon icon-add' %>
|
||||
<%= link_to sprite_icon('settings', l(:label_settings)), plugin_settings_path('redmine_qbo_commission'), class: 'icon icon-settings' %>
|
||||
</div>
|
||||
|
||||
<h2><%= l(:label_commission_rep_plural) %></h2>
|
||||
|
||||
<p><em class="info"><%= l(:text_commission_reps) %></em></p>
|
||||
|
||||
<% if @reps.empty? %>
|
||||
<p class="nodata"><%= l(:label_no_data) %></p>
|
||||
<% else %>
|
||||
<div class="autoscroll">
|
||||
<table class="list">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:label_user) %></th>
|
||||
<th><%= l(:field_commission_rep_probation_until) %></th>
|
||||
<th><%= l(:field_active) %></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @reps.each do |rep| %>
|
||||
<tr>
|
||||
<td class="name"><%= link_to_user rep.user %></td>
|
||||
<td><%= format_date(rep.probation_until) %></td>
|
||||
<td><%= checked_image rep.active? %></td>
|
||||
<td class="buttons">
|
||||
<%= link_to sprite_icon('edit', l(:button_edit)), edit_commission_rep_path(rep), class: 'icon icon-edit' %>
|
||||
<%= link_to sprite_icon('del', l(:button_delete)), commission_rep_path(rep), method: :delete,
|
||||
data: { confirm: l(:text_are_you_sure) }, class: 'icon icon-del' %>
|
||||
</td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<% html_title l(:label_commission_rep_plural) %>
|
||||
@@ -0,0 +1,8 @@
|
||||
<h2><%= link_to l(:label_commission_rep_plural), commission_reps_path %> » <%= l(:label_commission_rep_new) %></h2>
|
||||
|
||||
<%= labelled_form_for @rep, url: commission_reps_path do |f| %>
|
||||
<%= render partial: 'commission_reps/form', locals: { f: f } %>
|
||||
<%= submit_tag l(:button_create) %>
|
||||
<% end %>
|
||||
|
||||
<% html_title l(:label_commission_rep_new) %>
|
||||
@@ -0,0 +1,3 @@
|
||||
<% content_for :header_tags do %>
|
||||
<%= stylesheet_link_tag 'qbo_commission', plugin: 'redmine_qbo_commission' %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,57 @@
|
||||
<%= render partial: 'sales_commissions/styles' %>
|
||||
|
||||
<div class="contextual">
|
||||
<% if User.current.admin? %>
|
||||
<%= link_to sprite_icon('user', l(:label_commission_rep_plural)), commission_reps_path, class: 'icon icon-user' %>
|
||||
<%= link_to sprite_icon('settings', l(:label_settings)), plugin_settings_path('redmine_qbo_commission'), class: 'icon icon-settings' %>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<h2><%= l(:label_sales_commission) %></h2>
|
||||
|
||||
<%= form_tag(sales_commissions_path, method: :get, id: 'sales-commission-month-picker', class: 'sales-commission-picker') do %>
|
||||
<label for="sales_commission_month"><%= l(:label_sales_commission_month) %></label>
|
||||
<%= select_tag 'month', options_for_select(@months.map { |month| [month.name, month.to_param] }, (@months.second || @months.first).to_param),
|
||||
id: 'sales_commission_month' %>
|
||||
<%= submit_tag l(:button_sales_commission_show), name: nil %>
|
||||
<% end %>
|
||||
|
||||
<h3><%= l(:label_sales_commission_history) %></h3>
|
||||
<% if @commission_months.empty? %>
|
||||
<p class="nodata"><%= l(:label_no_data) %></p>
|
||||
<% else %>
|
||||
<div class="autoscroll">
|
||||
<table class="list sales-commission-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:label_sales_commission_month) %></th>
|
||||
<th><%= l(:field_status) %></th>
|
||||
<th><%= l(:label_sales_commission_net_sales) %></th>
|
||||
<th><%= l(:label_sales_commission_pool) %></th>
|
||||
<th><%= l(:label_sales_commission_payouts_total) %></th>
|
||||
<th><%= l(:label_sales_commission_approved_by) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @commission_months.each do |record| %>
|
||||
<tr>
|
||||
<td class="name"><%= link_to record.month.name, sales_commission_month_path(record.month.to_param) %></td>
|
||||
<td class="text">
|
||||
<% if record.approved? %>
|
||||
<span class="sales-commission-ok"><%= l(:label_sales_commission_status_approved) %></span>
|
||||
<% else %>
|
||||
<span class="sales-commission-miss"><%= l(:label_sales_commission_status_open) %></span>
|
||||
<% end %>
|
||||
</td>
|
||||
<td><%= record.approved? ? commission_money(record.net_sales) : '' %></td>
|
||||
<td><%= record.approved? ? commission_money(record.pool) : '' %></td>
|
||||
<td><%= record.approved? ? commission_money(record.payouts_total) : '' %></td>
|
||||
<td class="text"><%= record.approved_by ? link_to_user(record.approved_by) : '' %> <%= format_time(record.approved_at) if record.approved_at %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<% html_title l(:label_sales_commission) %>
|
||||
@@ -0,0 +1,296 @@
|
||||
<%= render partial: 'sales_commissions/styles' %>
|
||||
<% report = @report %>
|
||||
<% pool = report.pool %>
|
||||
<% approved = @record&.approved? %>
|
||||
<% editable = @can_approve && !approved %>
|
||||
<% previous_month = @month - 1 %>
|
||||
<% next_month = @month + 1 %>
|
||||
|
||||
<div class="contextual">
|
||||
<%= link_to "« #{previous_month.label}", sales_commission_month_path(previous_month.to_param) %>
|
||||
<% if next_month.start_date <= Date.current %>
|
||||
| <%= link_to "#{next_month.label} »", sales_commission_month_path(next_month.to_param) %>
|
||||
<% end %>
|
||||
<% if approved && @can_approve %>
|
||||
| <%= link_to sprite_icon('download', l(:label_sales_commission_payroll_csv)),
|
||||
sales_commission_month_path(@month.to_param, format: 'csv'), class: 'icon icon-download' %>
|
||||
<% end %>
|
||||
<% if editable %>
|
||||
| <%= link_to sprite_icon('reload', l(:button_sales_commission_refresh)), refresh_sales_commission_month_path(@month.to_param),
|
||||
method: :post, class: 'icon icon-reload' %>
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<h2><%= @can_approve ? link_to(l(:label_sales_commission), sales_commissions_path) : l(:label_sales_commission) %> » <%= @month.name %></h2>
|
||||
|
||||
<% if @error %>
|
||||
<p class="conflict"><%= @error %></p>
|
||||
<% end %>
|
||||
|
||||
<% if approved %>
|
||||
<p class="sales-commission-approved">
|
||||
<%= sprite_icon('checked', commission_approved_text(@record)) %>
|
||||
<% if @can_approve %>
|
||||
<%= link_to l(:button_sales_commission_reopen), reopen_sales_commission_month_path(@month.to_param), method: :post,
|
||||
data: { confirm: l(:text_sales_commission_reopen_confirm) } %>
|
||||
<% end %>
|
||||
</p>
|
||||
<% elsif !@month.completed? %>
|
||||
<p class="warning"><%= l(:text_sales_commission_month_in_progress, date: format_date(@month.end_date)) %></p>
|
||||
<% end %>
|
||||
<% if !approved && @read_at %>
|
||||
<p><em class="info"><%= l(:text_sales_commission_read_at, time: format_time(@read_at)) %></em></p>
|
||||
<% end %>
|
||||
|
||||
<div class="sales-commission-summary">
|
||||
<div class="box">
|
||||
<%= l(:label_sales_commission_gross_sales) %>
|
||||
<span class="value"><%= commission_money(report.gross_sales) %></span>
|
||||
</div>
|
||||
<div class="box">
|
||||
<%= l(:label_sales_commission_deductions) %>
|
||||
<span class="value"><%= commission_money(report.deductions_total) %></span>
|
||||
</div>
|
||||
<div class="box">
|
||||
<%= l(:label_sales_commission_net_sales) %>
|
||||
<span class="value <%= pool.threshold_met? ? 'sales-commission-ok' : 'sales-commission-miss' %>"><%= commission_money(report.net_sales) %></span>
|
||||
<% percent = pool.threshold.positive? ? [[report.net_sales / pool.threshold * 100, 0].max, 100].min : 100 %>
|
||||
<div class="sales-commission-progress" title="<%= l(:label_sales_commission_threshold) %> <%= commission_money(pool.threshold) %>"><span style="width: <%= percent.to_f.round(1) %>%"></span></div>
|
||||
</div>
|
||||
<div class="box">
|
||||
<% if pool.threshold_met? %>
|
||||
<%= l(:label_sales_commission_threshold) %>
|
||||
<span class="value sales-commission-ok"><%= commission_money(pool.threshold) %></span>
|
||||
<%= l(:text_sales_commission_threshold_met) %>
|
||||
<% else %>
|
||||
<%= l(:label_sales_commission_short_of_threshold) %>
|
||||
<span class="value sales-commission-miss"><%= commission_money(pool.short_of_threshold) %></span>
|
||||
<%= l(:text_sales_commission_threshold_of, amount: commission_money(pool.threshold)) %>
|
||||
<% end %>
|
||||
</div>
|
||||
<div class="box">
|
||||
<%= l(:label_sales_commission_pool) %>
|
||||
<span class="value"><%= commission_money(pool.amount) %></span>
|
||||
<%= l(:text_sales_commission_each_rep) %>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<% if pool.parts.any? %>
|
||||
<div class="autoscroll">
|
||||
<table class="list sales-commission-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:label_sales_commission_bracket) %></th>
|
||||
<th><%= l(:label_sales_commission_rate) %></th>
|
||||
<th><%= l(:label_sales_commission_bracket_sales) %></th>
|
||||
<th><%= l(:label_sales_commission_amount) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% pool.parts.each do |part| %>
|
||||
<tr>
|
||||
<td class="name"><%= commission_money(part.from) %> – <%= commission_money(part.to) %></td>
|
||||
<td><%= commission_rate(part.rate) %></td>
|
||||
<td><%= commission_money(part.sales) %></td>
|
||||
<td><%= commission_money(part.amount) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr><td class="name" colspan="3"><%= l(:label_sales_commission_pool) %></td><td><%= commission_money(pool.amount) %></td></tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= form_tag(sales_commission_month_path(@month.to_param), method: :post, id: 'sales-commission-month') do %>
|
||||
<%= hidden_field_tag 'shown', '1', id: nil if editable %>
|
||||
|
||||
<h3><%= l(:label_sales_commission_payouts) %></h3>
|
||||
<% if report.payouts.empty? %>
|
||||
<p class="nodata"><%= l(:text_sales_commission_no_reps) %>
|
||||
<% if User.current.admin? %><%= link_to l(:label_commission_rep_new), new_commission_rep_path %><% end %></p>
|
||||
<% else %>
|
||||
<div class="autoscroll">
|
||||
<table class="list sales-commission-table" id="sales-commission-payouts">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:label_user) %></th>
|
||||
<% if editable %><th title="<%= l(:text_sales_commission_eligible) %>"><%= l(:label_sales_commission_paid) %></th><% end %>
|
||||
<th><%= l(:label_sales_commission_amount) %></th>
|
||||
<th><%= l(:label_sales_commission_reason) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% report.payouts.each do |payout| %>
|
||||
<% unticked = editable && @record&.unpaid_user_ids&.include?(payout.user&.id) %>
|
||||
<tr class="<%= 'ineligible' unless payout.eligible? %>">
|
||||
<td class="name"><%= payout.user ? link_to_user(payout.user) : '' %></td>
|
||||
<% if editable %>
|
||||
<td class="check">
|
||||
<% blocked = !payout.eligible? && !unticked %>
|
||||
<% unless blocked %>
|
||||
<%= hidden_field_tag 'shown_reps[]', payout.user.id, id: nil %>
|
||||
<%= check_box_tag 'eligible[]', payout.user.id, !unticked, id: "eligible_#{payout.user.id}" %>
|
||||
<% end %>
|
||||
</td>
|
||||
<% end %>
|
||||
<td><%= commission_money(payout.amount) %></td>
|
||||
<td class="text"><%= payout.ineligible_reason %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td class="name"><%= l(:label_total) %></td>
|
||||
<% if editable %><td></td><% end %>
|
||||
<td><%= commission_money(report.payouts_total) %></td>
|
||||
<td></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<h3><%= l(:label_sales_commission_deductions) %></h3>
|
||||
<% if report.deductions.empty? && report.adjustments.empty? %>
|
||||
<p class="nodata"><%= l(:label_no_data) %></p>
|
||||
<% else %>
|
||||
<div class="autoscroll">
|
||||
<table class="list sales-commission-table" id="sales-commission-deductions">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:label_sales_commission_deducted) %></th>
|
||||
<th><%= l(:label_date) %></th>
|
||||
<th><%= l(:field_type) %></th>
|
||||
<th><%= l(:label_sales_commission_number) %></th>
|
||||
<th><%= l(:label_sales_commission_customer) %></th>
|
||||
<th><%= l(:label_sales_commission_total) %></th>
|
||||
<th><%= l(:label_sales_commission_tax) %></th>
|
||||
<th><%= l(:label_sales_commission_amount) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% report.deductions.each do |txn| %>
|
||||
<% included = report.included?(txn) %>
|
||||
<tr class="<%= 'excluded' unless included %>">
|
||||
<td class="check">
|
||||
<% if editable %>
|
||||
<%= hidden_field_tag 'shown_deductions[]', txn.key, id: nil %>
|
||||
<%= check_box_tag 'included[]', txn.key, included, id: "included_#{txn.key.tr(':', '_')}" %>
|
||||
<% else %>
|
||||
<%= checked_image included %>
|
||||
<% end %>
|
||||
</td>
|
||||
<td class="text"><%= format_date(txn.txn_date) %></td>
|
||||
<td class="text"><%= txn.kind_name %></td>
|
||||
<td class="text"><%= commission_txn_link(txn, @can_approve) %></td>
|
||||
<td class="text"><%= txn.customer_name %></td>
|
||||
<td><%= commission_money(txn.total) %></td>
|
||||
<td><%= commission_money(txn.tax) %></td>
|
||||
<td><%= commission_money(txn.net) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
<% report.adjustments.each do |adjustment| %>
|
||||
<tr class="adjustment">
|
||||
<td class="check">
|
||||
<% if editable %>
|
||||
<%= link_to sprite_icon('del', l(:button_delete)), sales_commission_adjustment_path(@month.to_param, adjustment),
|
||||
method: :delete, data: { confirm: l(:text_are_you_sure) }, class: 'icon-only icon-del' %>
|
||||
<% else %>
|
||||
<%= checked_image true %>
|
||||
<% end %>
|
||||
</td>
|
||||
<td class="text"><%= format_date(adjustment.created_at) %></td>
|
||||
<td class="text"><%= l(:label_sales_commission_adjustment) %></td>
|
||||
<td class="text"></td>
|
||||
<td class="text"><%= adjustment.description %><% if adjustment.author %> <small>(<%= adjustment.author.name %>)</small><% end %></td>
|
||||
<td></td>
|
||||
<td></td>
|
||||
<td><%= commission_money(adjustment.amount) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr><td class="name" colspan="7"><%= l(:label_sales_commission_deductions) %></td><td><%= commission_money(report.deductions_total) %></td></tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<% if editable %>
|
||||
<p>
|
||||
<label for="sales_commission_notes"><%= l(:field_notes) %></label><br>
|
||||
<%= text_area_tag 'notes', @record&.notes, id: 'sales_commission_notes', rows: 3, cols: 80 %>
|
||||
</p>
|
||||
<p>
|
||||
<%= submit_tag l(:button_save), name: 'save' %>
|
||||
<% if @month.completed? %>
|
||||
<%= submit_tag l(:button_sales_commission_approve), name: 'approve',
|
||||
data: { confirm: l(:text_sales_commission_approve_confirm) } %>
|
||||
<% end %>
|
||||
</p>
|
||||
<% elsif @record&.notes.present? %>
|
||||
<h3><%= l(:field_notes) %></h3>
|
||||
<div class="wiki"><%= simple_format(h(@record.notes)) %></div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
<% if editable %>
|
||||
<%= form_tag(sales_commission_adjustments_path(@month.to_param), method: :post, class: 'sales-commission-adjustment',
|
||||
id: 'sales-commission-adjustment') do %>
|
||||
<fieldset class="box">
|
||||
<legend><%= l(:label_sales_commission_add_adjustment) %></legend>
|
||||
<%= text_field_tag 'description', '', placeholder: l(:field_description), required: true, maxlength: 255 %>
|
||||
<%= text_field_tag 'amount', '', placeholder: l(:label_sales_commission_amount), class: 'amount', required: true,
|
||||
inputmode: 'decimal' %>
|
||||
<%= submit_tag l(:button_add) %>
|
||||
<br><em class="info"><%= l(:text_sales_commission_adjustment) %></em>
|
||||
</fieldset>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
<h3><%= l(:label_sales_commission_sales) %> (<%= report.sales.size %>)</h3>
|
||||
<% if report.sales.empty? %>
|
||||
<p class="nodata"><%= l(:label_no_data) %></p>
|
||||
<% else %>
|
||||
<div class="autoscroll">
|
||||
<table class="list sales-commission-table" id="sales-commission-sales">
|
||||
<thead>
|
||||
<tr>
|
||||
<th><%= l(:label_sales_commission_paid_on) %></th>
|
||||
<th><%= l(:field_type) %></th>
|
||||
<th><%= l(:label_sales_commission_number) %></th>
|
||||
<th><%= l(:label_sales_commission_customer) %></th>
|
||||
<th><%= l(:label_sales_commission_total) %></th>
|
||||
<th><%= l(:label_sales_commission_tax) %></th>
|
||||
<th><%= l(:label_sales_commission_amount) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% report.sales.each do |txn| %>
|
||||
<tr>
|
||||
<td class="text"><%= format_date(txn.txn_date) %></td>
|
||||
<td class="text"><%= txn.kind_name %></td>
|
||||
<td class="text"><%= commission_txn_link(txn, @can_approve) %></td>
|
||||
<td class="text"><%= txn.customer_name %></td>
|
||||
<td><%= commission_money(txn.total) %></td>
|
||||
<td><%= commission_money(txn.tax) %></td>
|
||||
<td><%= commission_money(txn.net) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td class="name" colspan="4"><%= l(:label_total) %></td>
|
||||
<td><%= commission_money(report.sales.sum(BigDecimal('0'), &:total)) %></td>
|
||||
<td><%= commission_money(report.sales.sum(BigDecimal('0')) { |txn| txn.tax.to_d }) %></td>
|
||||
<td><%= commission_money(report.gross_sales) %></td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
<p><em class="info"><%= l(:text_sales_commission_sales) %></em></p>
|
||||
<% end %>
|
||||
|
||||
<% html_title "#{l(:label_sales_commission)} #{@month.label}" %>
|
||||
@@ -0,0 +1,65 @@
|
||||
<%# Settings for redmine_qbo_commission (Administration » Plugins » Configure) %>
|
||||
<% s = RedmineQboCommission::Settings %>
|
||||
<% field = ->(key) { "settings[#{key}]" } %>
|
||||
<% plain = ->(number) { number.to_d == number.to_d.to_i ? number.to_d.to_i.to_s : number.to_d.to_s('F') } %>
|
||||
<% brackets = s.brackets %>
|
||||
|
||||
<p>
|
||||
<%= link_to sprite_icon('user', l(:label_commission_rep_plural)), commission_reps_path, class: 'icon icon-user' %>
|
||||
<%= link_to sprite_icon('stats', l(:label_sales_commission)), sales_commissions_path, class: 'icon icon-stats' %>
|
||||
</p>
|
||||
|
||||
<fieldset class="box tabular">
|
||||
<legend><%= l(:label_sales_commission_rates) %></legend>
|
||||
<p>
|
||||
<label for="qbo_commission_threshold"><%= l(:label_sales_commission_threshold) %></label>
|
||||
$<%= number_field_tag field.call('threshold'), plain.call(s.threshold), id: 'qbo_commission_threshold', min: 0, step: 0.01, style: 'width: 9em' %>
|
||||
<em class="info"><%= l(:text_sales_commission_setting_threshold) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_commission_base_rate"><%= l(:label_sales_commission_base_rate) %></label>
|
||||
<%= number_field_tag field.call('base_rate'), plain.call(brackets[0][1]), id: 'qbo_commission_base_rate', min: 0, step: 0.01, style: 'width: 5em' %>%
|
||||
<%= l(:label_sales_commission_up_to) %>
|
||||
$<%= number_field_tag field.call('base_limit'), plain.call(brackets[0][0]), id: 'qbo_commission_base_limit', min: 0, step: 0.01, style: 'width: 9em' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_commission_step_rate"><%= l(:label_sales_commission_step_rate) %></label>
|
||||
<%= number_field_tag field.call('step_rate'), plain.call(brackets[1][1]), id: 'qbo_commission_step_rate', min: 0, step: 0.01, style: 'width: 5em' %>%
|
||||
<%= l(:label_sales_commission_up_to) %>
|
||||
$<%= number_field_tag field.call('step_limit'), plain.call(brackets[1][0]), id: 'qbo_commission_step_limit', min: 0, step: 0.01, style: 'width: 9em' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_commission_top_rate"><%= l(:label_sales_commission_top_rate) %></label>
|
||||
<%= number_field_tag field.call('top_rate'), plain.call(brackets[2][1]), id: 'qbo_commission_top_rate', min: 0, step: 0.01, style: 'width: 5em' %>%
|
||||
<%= l(:label_sales_commission_above) %>
|
||||
</p>
|
||||
<p><em class="info"><%= l(:text_sales_commission_setting_brackets) %></em></p>
|
||||
</fieldset>
|
||||
|
||||
<fieldset class="box tabular">
|
||||
<legend><%= l(:label_sales_commission_counted) %></legend>
|
||||
<p>
|
||||
<label for="qbo_commission_sales_receipts"><%= l(:label_sales_commission_include_sales_receipts) %></label>
|
||||
<%= hidden_field_tag field.call('include_sales_receipts'), '0', id: nil %>
|
||||
<%= check_box_tag field.call('include_sales_receipts'), '1', s.include_sales_receipts?, id: 'qbo_commission_sales_receipts' %>
|
||||
<em class="info"><%= l(:text_sales_commission_setting_sales_receipts) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_commission_refund_receipts"><%= l(:label_sales_commission_deduct_refund_receipts) %></label>
|
||||
<%= hidden_field_tag field.call('deduct_refund_receipts'), '0', id: nil %>
|
||||
<%= check_box_tag field.call('deduct_refund_receipts'), '1', s.deduct_refund_receipts?, id: 'qbo_commission_refund_receipts' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_commission_credit_memos"><%= l(:label_sales_commission_deduct_credit_memos) %></label>
|
||||
<%= hidden_field_tag field.call('deduct_credit_memos'), '0', id: nil %>
|
||||
<%= check_box_tag field.call('deduct_credit_memos'), '1', s.deduct_credit_memos?, id: 'qbo_commission_credit_memos' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_commission_items"><%= l(:label_sales_commission_excluded_items) %></label>
|
||||
<%= hidden_field_tag "#{field.call('excluded_item_ids')}[]", '', id: nil %>
|
||||
<%= select_tag "#{field.call('excluded_item_ids')}[]",
|
||||
options_from_collection_for_select(Item.order(:name), :id, :name, Array(s.values['excluded_item_ids']).map(&:to_s)),
|
||||
multiple: true, size: 8, id: 'qbo_commission_items' %>
|
||||
<em class="info"><%= l(:text_sales_commission_setting_excluded_items) %></em>
|
||||
</p>
|
||||
</fieldset>
|
||||
@@ -0,0 +1,19 @@
|
||||
/* redmine_qbo_commission: monthly commission pages */
|
||||
.sales-commission-picker { margin-bottom: 1em; }
|
||||
.sales-commission-summary { display: flex; flex-wrap: wrap; gap: 1em; margin: 1em 0; }
|
||||
.sales-commission-summary .box { flex: 1 1 10em; margin: 0; text-align: center; }
|
||||
.sales-commission-summary .value { font-size: 1.6em; font-weight: bold; display: block; }
|
||||
.sales-commission-progress { height: .6em; border-radius: .3em; background: rgba(128, 128, 128, .25); overflow: hidden; margin-top: .4em; }
|
||||
.sales-commission-progress span { display: block; height: 100%; background: #2e7d32; }
|
||||
.sales-commission-ok { color: #2e7d32; }
|
||||
.sales-commission-miss { color: #b26a00; }
|
||||
.sales-commission-error { color: #c62828; }
|
||||
table.list.sales-commission-table td { text-align: right; }
|
||||
table.list.sales-commission-table td.name, table.list.sales-commission-table td.text { text-align: left; }
|
||||
table.list.sales-commission-table td.check { text-align: center; }
|
||||
table.list.sales-commission-table tr.excluded td { opacity: .55; text-decoration: line-through; }
|
||||
table.list.sales-commission-table tr.excluded td.check { text-decoration: none; opacity: 1; }
|
||||
table.list.sales-commission-table tr.ineligible td { opacity: .6; }
|
||||
table.list.sales-commission-table tfoot td { font-weight: bold; }
|
||||
.sales-commission-adjustment input[type=text] { width: 20em; max-width: 100%; }
|
||||
.sales-commission-adjustment input.amount { width: 8em; }
|
||||
@@ -0,0 +1,88 @@
|
||||
en:
|
||||
permission_view_sales_commission: "View sales commission"
|
||||
permission_approve_sales_commission: "Approve sales commission"
|
||||
|
||||
label_sales_commission: "Sales commission"
|
||||
label_commission_rep_plural: "Commission reps"
|
||||
label_commission_rep_new: "New commission rep"
|
||||
field_commission_rep_probation_until: "Probation until"
|
||||
field_probation_until: "Probation until"
|
||||
|
||||
label_sales_commission_month: "Month"
|
||||
label_sales_commission_history: "Months"
|
||||
label_sales_commission_status_open: "Open"
|
||||
label_sales_commission_status_approved: "Approved"
|
||||
label_sales_commission_approved_by: "Approved by"
|
||||
label_sales_commission_gross_sales: "Paid sales"
|
||||
label_sales_commission_deductions: "Deductions"
|
||||
label_sales_commission_net_sales: "Commission sales"
|
||||
label_sales_commission_threshold: "Threshold"
|
||||
label_sales_commission_short_of_threshold: "Short of threshold"
|
||||
label_sales_commission_pool: "Commission"
|
||||
label_sales_commission_payouts: "Payouts"
|
||||
label_sales_commission_payouts_total: "Paid out"
|
||||
label_sales_commission_paid: "Paid"
|
||||
label_sales_commission_reason: "Why not"
|
||||
label_sales_commission_amount: "Amount"
|
||||
label_sales_commission_bracket: "Bracket"
|
||||
label_sales_commission_rate: "Rate"
|
||||
label_sales_commission_bracket_sales: "Sales in bracket"
|
||||
label_sales_commission_deducted: "Deduct"
|
||||
label_sales_commission_number: "No."
|
||||
label_sales_commission_customer: "Customer"
|
||||
label_sales_commission_total: "Total"
|
||||
label_sales_commission_tax: "Tax"
|
||||
label_sales_commission_paid_on: "Paid in full"
|
||||
label_sales_commission_sales: "Paid sales"
|
||||
label_sales_commission_adjustment: "Adjustment"
|
||||
label_sales_commission_add_adjustment: "Add an adjustment"
|
||||
label_sales_commission_payroll_csv: "Payroll CSV"
|
||||
label_sales_commission_kind_invoice: "Invoice"
|
||||
label_sales_commission_kind_sales_receipt: "Sales receipt"
|
||||
label_sales_commission_kind_refund_receipt: "Refund receipt"
|
||||
label_sales_commission_kind_credit_memo: "Credit memo"
|
||||
label_sales_commission_rates: "Threshold and rates"
|
||||
label_sales_commission_base_rate: "Base rate"
|
||||
label_sales_commission_step_rate: "Step-up rate"
|
||||
label_sales_commission_top_rate: "Top rate"
|
||||
label_sales_commission_up_to: "of sales up to"
|
||||
label_sales_commission_above: "of sales above that"
|
||||
label_sales_commission_counted: "What counts"
|
||||
label_sales_commission_include_sales_receipts: "Count sales receipts"
|
||||
label_sales_commission_deduct_refund_receipts: "Deduct refund receipts"
|
||||
label_sales_commission_deduct_credit_memos: "Deduct credit memos"
|
||||
label_sales_commission_excluded_items: "Not returns"
|
||||
|
||||
button_sales_commission_show: "Show"
|
||||
button_sales_commission_refresh: "Read from QuickBooks"
|
||||
button_sales_commission_approve: "Approve for payroll"
|
||||
button_sales_commission_reopen: "Reopen"
|
||||
|
||||
notice_sales_commission_approved: "%{month} is approved for payroll."
|
||||
notice_sales_commission_reopened: "%{month} is open again."
|
||||
|
||||
error_sales_commission_month_not_over: "The month isn't over yet."
|
||||
error_sales_commission_already_approved: "This month is approved. Reopen it to change it."
|
||||
error_sales_commission_qbo: "Couldn't read QuickBooks: %{error}"
|
||||
|
||||
text_sales_commission_month_in_progress: "This month isn't over until %{date}, so its sales can still change. It can be approved once it's over."
|
||||
text_sales_commission_read_at: "Read from QuickBooks at %{time}. It's read again every 15 minutes."
|
||||
text_sales_commission_approved_by: "Approved for payroll by %{user} on %{time}."
|
||||
text_sales_commission_threshold_met: "reached"
|
||||
text_sales_commission_threshold_of: "to reach %{amount}"
|
||||
text_sales_commission_each_rep: "for each rep"
|
||||
text_sales_commission_no_reps: "No commission reps yet."
|
||||
text_sales_commission_eligible: "Untick a rep who shouldn't be paid for this month."
|
||||
text_sales_commission_unticked: "Unticked when approving"
|
||||
text_sales_commission_inactive: "Not active"
|
||||
text_sales_commission_probation: "On probation until %{date}"
|
||||
text_sales_commission_adjustment: "Deducted from the month's sales, e.g. a return refunded by company check. A negative amount adds sales back."
|
||||
text_sales_commission_sales: "Invoices count in the month they're paid in full, and sales receipts on their date. Amounts are without sales tax."
|
||||
text_sales_commission_approve_confirm: "Read the month from QuickBooks one last time and approve it for payroll?"
|
||||
text_sales_commission_reopen_confirm: "Reopen this month? It goes back to being worked out from QuickBooks as it stands."
|
||||
text_commission_reps: "The sales reps, service advisors and counter sales staff who earn the monthly sales commission (SOP-OPS-013). Each eligible rep is paid the whole commission."
|
||||
text_commission_rep_probation: "The last day of their 90-day probation. Months that start on or before this day pay no commission."
|
||||
text_sales_commission_setting_threshold: "No commission for a month below this (SOP-OPS-013: $100,000). At or above it, the whole month counts from the first dollar."
|
||||
text_sales_commission_setting_brackets: "Each rate applies only to the sales inside its bracket (SOP-OPS-013: 0.5% up to $125,000, 0.75% up to $150,000, 1% above)."
|
||||
text_sales_commission_setting_sales_receipts: "Counter sales paid on the spot count on their date."
|
||||
text_sales_commission_setting_excluded_items: "Credit memos made only of these products/services aren't returns and aren't deducted. The tech bonus product/service (redmine_qbo_bonus) is always left out."
|
||||
@@ -0,0 +1,31 @@
|
||||
#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.
|
||||
|
||||
RedmineApp::Application.routes.draw do
|
||||
|
||||
# Monthly commission: the months, a month's sales, pool and payouts (by its year and month, e.g. /sales_commission/2026-11)
|
||||
month = { month: /\d{4}-\d{2}/ }
|
||||
get 'sales_commission', to: 'sales_commissions#index', as: :sales_commissions
|
||||
get 'sales_commission/current', to: 'sales_commissions#current', as: :current_sales_commission_month
|
||||
get 'sales_commission/:month', to: 'sales_commissions#show', as: :sales_commission_month, constraints: month
|
||||
post 'sales_commission/:month', to: 'sales_commissions#update', constraints: month
|
||||
post 'sales_commission/:month/refresh', to: 'sales_commissions#refresh', as: :refresh_sales_commission_month,
|
||||
constraints: month
|
||||
post 'sales_commission/:month/reopen', to: 'sales_commissions#reopen', as: :reopen_sales_commission_month,
|
||||
constraints: month
|
||||
post 'sales_commission/:month/adjustments', to: 'sales_commissions#add_adjustment',
|
||||
as: :sales_commission_adjustments, constraints: month
|
||||
delete 'sales_commission/:month/adjustments/:id', to: 'sales_commissions#remove_adjustment',
|
||||
as: :sales_commission_adjustment, constraints: month
|
||||
|
||||
# Administration » Commission reps
|
||||
resources :commission_reps, except: [:show]
|
||||
|
||||
end
|
||||
@@ -0,0 +1,23 @@
|
||||
#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.
|
||||
|
||||
class CreateCommissionReps < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
# A sales rep who earns the monthly commission
|
||||
create_table :commission_reps do |t|
|
||||
t.integer :user_id, null: false
|
||||
# No commission for a month that starts on or before this day (90-day probation)
|
||||
t.date :probation_until
|
||||
t.boolean :active, null: false, default: true
|
||||
t.timestamps
|
||||
end
|
||||
add_index :commission_reps, :user_id, unique: true
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,37 @@
|
||||
#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.
|
||||
|
||||
class CreateCommissionMonths < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
# A commission month: the approver's choices while it's open, and its totals once it's approved
|
||||
create_table :commission_months do |t|
|
||||
# The month's first day
|
||||
t.date :month_start, null: false
|
||||
# open or approved
|
||||
t.string :status, null: false, default: 'open'
|
||||
# The deductions (["credit_memo:123"]) and reps (user ids) the approver unticked, as JSON
|
||||
t.text :excluded_keys
|
||||
t.text :unpaid_user_ids
|
||||
t.text :notes
|
||||
# As approved: sales without tax, deductions, the sales the commission is on, each rep's commission
|
||||
t.decimal :gross_sales, precision: 15, scale: 2
|
||||
t.decimal :deductions, precision: 15, scale: 2
|
||||
t.decimal :net_sales, precision: 15, scale: 2
|
||||
t.decimal :pool, precision: 15, scale: 2
|
||||
# The threshold and brackets it was approved with ([[limit, rate]], as JSON)
|
||||
t.decimal :threshold, precision: 15, scale: 2
|
||||
t.text :brackets
|
||||
t.integer :approved_by_id
|
||||
t.datetime :approved_at
|
||||
t.timestamps
|
||||
end
|
||||
add_index :commission_months, :month_start, unique: true
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,30 @@
|
||||
#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.
|
||||
|
||||
class CreateCommissionLines < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
# A QuickBooks transaction as it counted toward an approved month
|
||||
create_table :commission_lines do |t|
|
||||
t.integer :commission_month_id, null: false
|
||||
# invoice, sales_receipt, refund_receipt or credit_memo
|
||||
t.string :kind, null: false
|
||||
t.string :txn_id, null: false
|
||||
t.string :doc_number
|
||||
t.string :customer_name
|
||||
# The day an invoice was paid in full, or the transaction's date
|
||||
t.date :txn_date
|
||||
t.decimal :total, precision: 15, scale: 2, null: false, default: 0
|
||||
t.decimal :tax, precision: 15, scale: 2, null: false, default: 0
|
||||
# Whether a deduction was ticked (sales always count)
|
||||
t.boolean :included, null: false, default: true
|
||||
end
|
||||
add_index :commission_lines, :commission_month_id
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,23 @@
|
||||
#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.
|
||||
|
||||
class CreateCommissionAdjustments < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
# A deduction added by hand (negative: sales added back)
|
||||
create_table :commission_adjustments do |t|
|
||||
t.integer :commission_month_id, null: false
|
||||
t.string :description, null: false
|
||||
t.decimal :amount, precision: 15, scale: 2, null: false
|
||||
t.integer :author_id
|
||||
t.timestamps
|
||||
end
|
||||
add_index :commission_adjustments, :commission_month_id
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,24 @@
|
||||
#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.
|
||||
|
||||
class CreateCommissionPayouts < ActiveRecord::Migration[7.0]
|
||||
def change
|
||||
# A rep's commission for an approved month, or why they weren't paid
|
||||
create_table :commission_payouts do |t|
|
||||
t.integer :commission_month_id, null: false
|
||||
t.integer :user_id, null: false
|
||||
t.decimal :amount, precision: 15, scale: 2, null: false, default: 0
|
||||
t.boolean :eligible, null: false, default: true
|
||||
t.string :reason
|
||||
t.timestamps
|
||||
end
|
||||
add_index :commission_payouts, [:commission_month_id, :user_id], unique: true
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,47 @@
|
||||
#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.
|
||||
|
||||
Redmine::Plugin.register :redmine_qbo_commission do
|
||||
|
||||
# About
|
||||
name 'Redmine QBO Commission plugin'
|
||||
author 'Rick Barrette'
|
||||
description 'Monthly sales commission (SOP-OPS-013): totals the month\'s paid sales from QuickBooks Online, ' \
|
||||
'works out the commission pool, and records each sales rep\'s payout for payroll'
|
||||
version '2026.11.0'
|
||||
url 'https://gitea.rickbarrette.org/ricky/redmine_qbo_commission'
|
||||
author_url 'https://barrettefabrication.com'
|
||||
requires_redmine version_or_higher: '7.0.0'
|
||||
|
||||
# The QuickBooks connection lives in redmine_qbo
|
||||
begin
|
||||
requires_redmine_plugin :redmine_qbo, version_or_higher: '2026.11.0'
|
||||
rescue Redmine::PluginNotFound
|
||||
raise 'Please install the redmine_qbo plugin (https://github.com/rickbarrette/redmine_qbo)'
|
||||
end
|
||||
|
||||
settings default: RedmineQboCommission::Settings::DEFAULTS.dup, partial: 'settings/qbo_commission'
|
||||
|
||||
# Seeing a month's sales, pool and payouts (e.g. the sales reps, to follow the month toward the threshold)
|
||||
permission :view_sales_commission, { sales_commissions: [:current, :show] }, global: true
|
||||
# The months, adjusting and approving a month for payroll, reopening it, the payroll CSV
|
||||
permission :approve_sales_commission,
|
||||
{ sales_commissions: [:index, :current, :show, :update, :refresh, :reopen,
|
||||
:add_adjustment, :remove_adjustment] },
|
||||
global: true
|
||||
|
||||
menu :top_menu, :sales_commissions, { controller: 'sales_commissions', action: 'current' },
|
||||
caption: :label_sales_commission, after: :my_page,
|
||||
if: proc { RedmineQboCommission.visible? }
|
||||
|
||||
# The sales reps who earn the commission
|
||||
menu :admin_menu, :commission_reps, { controller: 'commission_reps', action: 'index' },
|
||||
caption: :label_commission_rep_plural, icon: 'user', html: { class: 'icon icon-user' }
|
||||
end
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user