Files
redmine_qbo_commission/app/controllers/sales_commissions_controller.rb
T
rickyandClaude Opus 5.5 6fcd5f9b64 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>
2026-11-16 18:53:25 -05:00

158 lines
6.4 KiB
Ruby

#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