New plugin: weekly technician bonus credit memos (SOP-OPS-012)
Totals the shop's billable hours for a Sunday-Saturday week (picked projects, trackers and users) against the SOP-OPS-012 target, and credits each qualifying technician's QuickBooks customer account with a credit memo: a "Tech Bonus <week> <total>/<goal> hours (total/goal)" line, plus a separate tier line for every full 15 hours over the goal. Credit memos are emailed through QuickBooks. - Bonus technicians (admin): user, QuickBooks customer, role (technician/foreman), probation end - Tech bonuses (global "Run tech bonuses" permission): week preview, attendance check, run, PDF and email again; re-running a week never credits anyone twice Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
a2ecb74c1d
37 files changed
+2274
No files matched your search
@@ -0,0 +1,28 @@
|
||||
#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 RedmineQboBonus
|
||||
|
||||
def self.setup; end
|
||||
|
||||
def self.allowed?(user = User.current)
|
||||
user.allowed_to?(:run_tech_bonuses, nil, global: true)
|
||||
end
|
||||
|
||||
# 95.5 => "95.5", 110.0 => "110", 87.583 => "87.58"
|
||||
def self.format_hours(hours)
|
||||
rounded = hours.to_d.round(2)
|
||||
rounded == rounded.to_i ? rounded.to_i.to_s : rounded.to_s('F').sub(/0+\z/, '')
|
||||
end
|
||||
|
||||
def self.format_money(amount)
|
||||
format('$%.2f', amount.to_d)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,98 @@
|
||||
#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 RedmineQboBonus
|
||||
# Makes a technician's bonus credit memo in QuickBooks and emails it to them.
|
||||
#
|
||||
# Tech Bonus 2026-47 125/110 hours (total/goal) 1 x $100.00
|
||||
# Tier Bonus 2026-47 1 x 15 hours over goal 1 x $100.00
|
||||
class CreditMemoWriter
|
||||
class Error < StandardError; end
|
||||
|
||||
def initialize(report)
|
||||
@report = report
|
||||
end
|
||||
|
||||
# The QuickBooks credit memo for a technician's line of the report
|
||||
def build(line, customer:, email: nil)
|
||||
item = Settings.item
|
||||
raise Error, I18n.t(:error_tech_bonus_no_item) unless item
|
||||
|
||||
memo = Quickbooks::Model::CreditMemo.new
|
||||
memo.customer_ref = Quickbooks::Model::BaseReference.new(customer.id.to_s)
|
||||
memo.txn_date = Date.current
|
||||
memo.bill_email = Quickbooks::Model::EmailAddress.new(email) if email.present?
|
||||
memo.customer_memo = Settings.customer_memo if Settings.customer_memo.present?
|
||||
memo.private_note = I18n.t(:text_tech_bonus_private_note, week: week.label,
|
||||
from: week.start_date.iso8601, to: week.end_date.iso8601)
|
||||
memo.line_items = [sales_line(item, base_subject, 1, line.base_amount)]
|
||||
if @report.tiers.positive? && line.tier_amount.positive?
|
||||
memo.line_items << sales_line(item, tier_subject, @report.tiers, line.tier_amount / @report.tiers)
|
||||
end
|
||||
memo
|
||||
end
|
||||
|
||||
# "Tech Bonus 2026-47 125/110 hours (total/goal)"
|
||||
def base_subject
|
||||
I18n.t(:text_tech_bonus_line, week: week.label, total: RedmineQboBonus.format_hours(@report.total_hours),
|
||||
goal: RedmineQboBonus.format_hours(@report.goal_hours))
|
||||
end
|
||||
|
||||
# "Tier Bonus 2026-47 2 x 15 hours over goal"
|
||||
def tier_subject
|
||||
I18n.t(:text_tech_bonus_tier_line, week: week.label, tiers: @report.tiers,
|
||||
hours: RedmineQboBonus.format_hours(@report.tier_hours))
|
||||
end
|
||||
|
||||
# Creates the credit memo in QuickBooks and returns it
|
||||
def create(line, customer:, email: nil)
|
||||
memo = build(line, customer: customer, email: email)
|
||||
saved = QboCreditMemoService.with_service { |service| service.create(memo) }
|
||||
raise Error, I18n.t(:error_tech_bonus_not_created) unless saved&.id.present?
|
||||
|
||||
saved
|
||||
end
|
||||
|
||||
# Emails the credit memo (to email, or its billing email). Returns the credit memo.
|
||||
def self.send_email(credit_memo_id, email = nil)
|
||||
sent = QboCreditMemoService.with_service { |service| service.send_credit_memo(credit_memo_id, email) }
|
||||
raise Error, I18n.t(:error_tech_bonus_not_emailed) unless sent
|
||||
|
||||
sent
|
||||
end
|
||||
|
||||
# The credit memo's PDF, as QuickBooks prints it
|
||||
def self.pdf(credit_memo_id)
|
||||
memo = Quickbooks::Model::CreditMemo.new
|
||||
memo.id = credit_memo_id.to_s
|
||||
QboCreditMemoService.with_service { |service| service.pdf(memo) }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def week
|
||||
@report.week
|
||||
end
|
||||
|
||||
def sales_line(item, description, quantity, unit_price)
|
||||
line = Quickbooks::Model::Line.new
|
||||
line.description = description
|
||||
line.amount = (unit_price * quantity).round(2)
|
||||
line.sales_item!
|
||||
detail = line.sales_item_line_detail
|
||||
detail.item_ref = Quickbooks::Model::BaseReference.new(item.id.to_s, name: item.name)
|
||||
detail.quantity = quantity
|
||||
detail.unit_price = unit_price.round(2)
|
||||
detail.service_date = week.end_date
|
||||
detail.tax_code_ref = Quickbooks::Model::BaseReference.new('NON')
|
||||
line
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
#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 RedmineQboBonus
|
||||
# quickbooks-ruby's credit memo service, with emailing. (QuickBooks' email call is named "send", which would
|
||||
# hide Ruby's Object#send, so it's send_credit_memo.)
|
||||
class QboCreditMemoService < Quickbooks::Service::CreditMemo
|
||||
# Runs the block with an authenticated service, refreshing the QuickBooks token when needed
|
||||
def self.with_service
|
||||
qbo = QboConnectionService.current!
|
||||
qbo.perform_authenticated_request do |access_token|
|
||||
yield new(company_id: qbo.realm_id, access_token: access_token)
|
||||
end
|
||||
end
|
||||
|
||||
# Emails the credit memo to the customer (to email_address, or its billing email when blank). QuickBooks uses
|
||||
# its own email template, marks the credit memo as sent and returns it; nil when it wasn't sent.
|
||||
def send_credit_memo(id, email_address = nil)
|
||||
query = email_address.present? ? "?sendTo=#{CGI.escape(email_address.to_s.strip)}" : ''
|
||||
url = "#{url_for_resource(model::REST_RESOURCE)}/#{id}/send#{query}"
|
||||
response = do_http_post(url, '', {}, { 'Content-Type' => 'application/octet-stream' })
|
||||
return nil unless response.code.to_i == 200
|
||||
|
||||
model.from_xml(parse_singular_entity_response(model, response.plain_body))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,109 @@
|
||||
#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 RedmineQboBonus
|
||||
# Runs a week's bonus: records the week's hours, then makes (and emails) a credit memo for each technician who
|
||||
# earned the bonus and attended all their scheduled shifts. Running a week again only redoes the technicians
|
||||
# without a credit memo, so nobody is credited twice.
|
||||
class Runner
|
||||
class Error < StandardError; end
|
||||
|
||||
# Emails a credit's memo and records the outcome on the credit (a failure keeps it as created, with why)
|
||||
def self.email(record, email)
|
||||
if email.blank?
|
||||
record.update!(message: I18n.t(:text_tech_bonus_no_email))
|
||||
return false
|
||||
end
|
||||
CreditMemoWriter.send_email(record.credit_memo_id, email)
|
||||
record.update!(status: 'emailed', emailed_to: email, emailed_at: Time.current, message: nil)
|
||||
true
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "[redmine_qbo_bonus] Emailing credit memo #{record.credit_memo_id}: #{e.message}"
|
||||
record.update!(message: I18n.t(:text_tech_bonus_email_failed, error: e.message))
|
||||
false
|
||||
end
|
||||
|
||||
# The email on the technician's QuickBooks customer account
|
||||
def self.customer_email(customer)
|
||||
customer&.email.presence
|
||||
rescue StandardError => e
|
||||
Rails.logger.warn "[redmine_qbo_bonus] Email for customer #{customer&.id}: #{e.message}"
|
||||
nil
|
||||
end
|
||||
|
||||
attr_reader :report, :bonus_week
|
||||
|
||||
# attended_user_ids: the technicians who worked all their scheduled shifts that week (SOP-OPS-012 §4)
|
||||
def initialize(week, attended_user_ids:, user: User.current, writer: nil)
|
||||
@week = week
|
||||
@report = WeekReport.new(week)
|
||||
@attended = attended_user_ids.map(&:to_i)
|
||||
@user = user
|
||||
@writer = writer || CreditMemoWriter.new(@report)
|
||||
end
|
||||
|
||||
def run
|
||||
raise Error, I18n.t(:error_tech_bonus_week_not_over) unless @week.completed?
|
||||
raise Error, I18n.t(:error_tech_bonus_no_item) if report.goal_met? && Settings.item.nil?
|
||||
|
||||
TechBonusWeek.transaction do
|
||||
@bonus_week = TechBonusWeek.lock.find_or_initialize_by(week_start: @week.start_date)
|
||||
@bonus_week.assign_attributes(total_hours: report.total_hours, goal_hours: report.goal_hours,
|
||||
tier_hours: report.tier_hours, tiers: report.tiers,
|
||||
hours_by_user: report.hours_by_user, run_by: @user)
|
||||
@bonus_week.save!
|
||||
end
|
||||
report.lines.each { |line| credit(line) } if report.goal_met?
|
||||
@bonus_week.credits.reload
|
||||
@bonus_week
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def credit(line)
|
||||
tech = line.technician
|
||||
record = @bonus_week.credits.find_or_initialize_by(user_id: tech.user_id)
|
||||
return if record.credited?
|
||||
|
||||
record.assign_attributes(customer_id: tech.customer_id, role: tech.role,
|
||||
base_amount: line.base_amount, tier_amount: line.tier_amount, message: nil)
|
||||
if !line.eligible?
|
||||
skip(record, line.ineligible_reason)
|
||||
elsif !@attended.include?(tech.user_id)
|
||||
skip(record, I18n.t(:text_tech_bonus_missed_shift))
|
||||
else
|
||||
create_credit_memo(record, line)
|
||||
end
|
||||
end
|
||||
|
||||
def skip(record, reason)
|
||||
record.update!(status: 'skipped', message: reason, base_amount: 0, tier_amount: 0)
|
||||
end
|
||||
|
||||
def create_credit_memo(record, line)
|
||||
customer = line.technician.customer
|
||||
email = customer_email(customer)
|
||||
memo = @writer.create(line, customer: customer, email: email)
|
||||
record.update!(status: 'created', credit_memo_id: memo.id.to_s, doc_number: memo.doc_number.to_s)
|
||||
email_credit(record, email) if Settings.email_credits?
|
||||
rescue StandardError => e
|
||||
Rails.logger.error "[redmine_qbo_bonus] Credit for user #{record.user_id}, week #{@week.label}: #{e.message}"
|
||||
record.update!(status: 'failed', message: e.message) unless record.credited?
|
||||
end
|
||||
|
||||
def email_credit(record, email)
|
||||
self.class.email(record, email)
|
||||
end
|
||||
|
||||
def customer_email(customer)
|
||||
self.class.customer_email(customer)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,111 @@
|
||||
#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 RedmineQboBonus
|
||||
# The plugin's settings (Administration » Plugins » Redmine QBO Bonus plugin » Configure). The defaults follow
|
||||
# SOP-OPS-012: a 110 billable hour shop target, a tier for every 15 hours above it, $100 a technician and
|
||||
# $150 for the Foreman, for the target and for each tier.
|
||||
module Settings
|
||||
DEFAULTS = {
|
||||
# Time logged on these projects counts (none: every project)
|
||||
'project_ids' => [],
|
||||
'include_subprojects' => '1',
|
||||
# Trackers: 'exclude' counts every tracker but these (and time logged without an issue),
|
||||
# 'include' only these
|
||||
'tracker_mode' => 'exclude',
|
||||
'tracker_ids' => [],
|
||||
# Whose time counts besides the technicians' (none: everyone's)
|
||||
'user_ids' => [],
|
||||
'goal_hours' => '110',
|
||||
'tier_hours' => '15',
|
||||
'technician_amount' => '100',
|
||||
'technician_tier_amount' => '100',
|
||||
'foreman_amount' => '150',
|
||||
'foreman_tier_amount' => '150',
|
||||
# The QuickBooks product/service on the credit memo lines
|
||||
'item_id' => '',
|
||||
'email_credits' => '1',
|
||||
'customer_memo' => 'Weekly Billable Hours Bonus (SOP-OPS-012). Thank you for your hard work!'
|
||||
}.freeze
|
||||
|
||||
TRACKER_MODES = %w[exclude include].freeze
|
||||
|
||||
def self.values
|
||||
DEFAULTS.merge((Setting.plugin_redmine_qbo_bonus.presence || {}).to_h.stringify_keys)
|
||||
end
|
||||
|
||||
def self.project_ids
|
||||
ids(values['project_ids'])
|
||||
end
|
||||
|
||||
def self.include_subprojects?
|
||||
values['include_subprojects'].to_s == '1'
|
||||
end
|
||||
|
||||
def self.tracker_mode
|
||||
TRACKER_MODES.include?(values['tracker_mode'].to_s) ? values['tracker_mode'].to_s : 'exclude'
|
||||
end
|
||||
|
||||
def self.tracker_ids
|
||||
ids(values['tracker_ids'])
|
||||
end
|
||||
|
||||
def self.user_ids
|
||||
ids(values['user_ids'])
|
||||
end
|
||||
|
||||
def self.goal_hours
|
||||
number(values['goal_hours'], DEFAULTS['goal_hours'])
|
||||
end
|
||||
|
||||
def self.tier_hours
|
||||
tier = number(values['tier_hours'], DEFAULTS['tier_hours'])
|
||||
tier.positive? ? tier : number(DEFAULTS['tier_hours'], 15)
|
||||
end
|
||||
|
||||
# The base and per-tier amounts of a role (BonusTechnician::ROLES)
|
||||
def self.amount(role)
|
||||
key = "#{role}_amount"
|
||||
number(values[key], DEFAULTS[key] || 0)
|
||||
end
|
||||
|
||||
def self.tier_amount(role)
|
||||
key = "#{role}_tier_amount"
|
||||
number(values[key], DEFAULTS[key] || 0)
|
||||
end
|
||||
|
||||
def self.item_id
|
||||
values['item_id'].to_s.presence
|
||||
end
|
||||
|
||||
def self.item
|
||||
item_id && Item.find_by(id: item_id)
|
||||
end
|
||||
|
||||
def self.email_credits?
|
||||
values['email_credits'].to_s == '1'
|
||||
end
|
||||
|
||||
def self.customer_memo
|
||||
values['customer_memo'].to_s.strip
|
||||
end
|
||||
|
||||
def self.ids(value)
|
||||
Array(value).map(&:to_s).reject(&:blank?).map(&:to_i).uniq
|
||||
end
|
||||
private_class_method :ids
|
||||
|
||||
def self.number(value, default)
|
||||
number = BigDecimal(value.to_s.strip, exception: false) || BigDecimal(default.to_s)
|
||||
number.negative? ? BigDecimal('0') : number
|
||||
end
|
||||
private_class_method :number
|
||||
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 RedmineQboBonus
|
||||
# A bonus week: Sunday through Saturday. It's named like Redmine's time report weeks ("2026-47"): the year and
|
||||
# ISO week number of its Monday.
|
||||
class Week
|
||||
include Comparable
|
||||
|
||||
attr_reader :start_date
|
||||
|
||||
# The week a date falls in
|
||||
def self.containing(date)
|
||||
date = date.to_date
|
||||
new(date - date.wday)
|
||||
end
|
||||
|
||||
# The last week that has ended
|
||||
def self.last_completed(today = Date.current)
|
||||
containing(today) - 1
|
||||
end
|
||||
|
||||
# From a week's Sunday ("2026-11-15") or any day in it; nil when it isn't a date
|
||||
def self.parse(value)
|
||||
date = Date.iso8601(value.to_s)
|
||||
containing(date)
|
||||
rescue Date::Error
|
||||
nil
|
||||
end
|
||||
|
||||
def initialize(start_date)
|
||||
@start_date = start_date.to_date
|
||||
raise ArgumentError, 'A bonus week starts on Sunday' unless @start_date.sunday?
|
||||
end
|
||||
|
||||
def end_date
|
||||
start_date + 6
|
||||
end
|
||||
|
||||
def range
|
||||
start_date..end_date
|
||||
end
|
||||
|
||||
def label
|
||||
monday = start_date + 1
|
||||
format('%<year>d-%<week>02d', year: monday.cwyear, week: monday.cweek)
|
||||
end
|
||||
|
||||
# Whether the week is over, so its hours are final
|
||||
def completed?(today = Date.current)
|
||||
end_date < today
|
||||
end
|
||||
|
||||
def +(other)
|
||||
Week.new(start_date + (7 * other))
|
||||
end
|
||||
|
||||
def -(other)
|
||||
self + -other
|
||||
end
|
||||
|
||||
def <=>(other)
|
||||
start_date <=> other.start_date
|
||||
end
|
||||
|
||||
def to_param
|
||||
start_date.iso8601
|
||||
end
|
||||
|
||||
def to_s
|
||||
label
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,149 @@
|
||||
#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 RedmineQboBonus
|
||||
# A week's shop hours against the SOP-OPS-012 target, and what each technician earns from them.
|
||||
#
|
||||
# The bonus is a team goal: everyone's billable hours count toward the shop total (the technicians', the
|
||||
# Foreman's and anyone else's picked in the settings, e.g. front desk staff who help in the shop), while only
|
||||
# the technicians get the bonus. Billable hours are the time logged on the picked projects and trackers.
|
||||
class WeekReport
|
||||
Line = Struct.new(:technician, :hours, :base_amount, :tier_amount, :ineligible_reason, keyword_init: true) do
|
||||
def eligible?
|
||||
ineligible_reason.nil?
|
||||
end
|
||||
|
||||
def amount
|
||||
base_amount + tier_amount
|
||||
end
|
||||
end
|
||||
|
||||
attr_reader :week
|
||||
|
||||
def initialize(week)
|
||||
@week = week
|
||||
end
|
||||
|
||||
def goal_hours
|
||||
Settings.goal_hours
|
||||
end
|
||||
|
||||
def tier_hours
|
||||
Settings.tier_hours
|
||||
end
|
||||
|
||||
# { user_id => hours } for everyone whose time counts, most hours first
|
||||
def hours_by_user
|
||||
@hours_by_user ||= time_entries.group(:user_id).sum(:hours)
|
||||
.transform_values { |hours| hours.to_d.round(2) }
|
||||
.reject { |_, hours| hours.zero? }
|
||||
.sort_by { |_, hours| -hours }.to_h
|
||||
end
|
||||
|
||||
def users
|
||||
@users ||= User.where(id: hours_by_user.keys).index_by(&:id)
|
||||
end
|
||||
|
||||
def total_hours
|
||||
hours_by_user.values.sum(BigDecimal('0'))
|
||||
end
|
||||
|
||||
def goal_met?
|
||||
total_hours >= goal_hours
|
||||
end
|
||||
|
||||
# One tier for every full tier_hours above the goal (110 => 0, 125 => 1, 139.9 => 1, 140 => 2)
|
||||
def tiers
|
||||
return 0 unless goal_met?
|
||||
|
||||
((total_hours - goal_hours) / tier_hours).floor
|
||||
end
|
||||
|
||||
# Hours above the goal still needed for the next tier
|
||||
def hours_to_next_tier
|
||||
return goal_hours - total_hours unless goal_met?
|
||||
|
||||
goal_hours + (tier_hours * (tiers + 1)) - total_hours
|
||||
end
|
||||
|
||||
def technicians
|
||||
@technicians ||= BonusTechnician.sorted.includes(:customer).to_a
|
||||
end
|
||||
|
||||
# What each technician earns (zero when the goal isn't met or they're not eligible)
|
||||
def lines
|
||||
@lines ||= technicians.select { |tech| tech.active? || hours_by_user.key?(tech.user_id) }.map do |tech|
|
||||
reason = tech.ineligible_reason(week)
|
||||
earns = goal_met? && reason.nil?
|
||||
Line.new(technician: tech,
|
||||
hours: hours_by_user.fetch(tech.user_id, BigDecimal('0')),
|
||||
base_amount: earns ? tech.base_amount : BigDecimal('0'),
|
||||
tier_amount: earns ? tech.tier_amount * tiers : BigDecimal('0'),
|
||||
ineligible_reason: reason)
|
||||
end
|
||||
end
|
||||
|
||||
def project_ids
|
||||
@project_ids ||= begin
|
||||
ids = Settings.project_ids
|
||||
if ids.any? && Settings.include_subprojects?
|
||||
Project.where(id: ids).flat_map { |project| project.self_and_descendants.pluck(:id) }.uniq
|
||||
else
|
||||
ids
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# The time entries that count toward the week's total
|
||||
def time_entries
|
||||
scope = TimeEntry.left_joins(:issue).where(spent_on: week.range)
|
||||
scope = scope.where(project_id: project_ids) if project_ids.any?
|
||||
scope = filter_trackers(scope)
|
||||
user_ids = Settings.user_ids
|
||||
if user_ids.any?
|
||||
scope = scope.where(user_id: (user_ids + BonusTechnician.pluck(:user_id)).uniq)
|
||||
end
|
||||
scope
|
||||
end
|
||||
|
||||
# Redmine's time report with the same filters, to check the hours against
|
||||
def redmine_report_params
|
||||
params = { set_filter: '1', columns: 'day', criteria: ['user'], t: ['hours'], f: ['spent_on'],
|
||||
op: { 'spent_on' => '><' }, v: { 'spent_on' => [week.start_date.iso8601, week.end_date.iso8601] } }
|
||||
add_filter(params, 'project_id', '=', project_ids) if project_ids.any?
|
||||
if Settings.tracker_ids.any?
|
||||
add_filter(params, 'issue.tracker_id', Settings.tracker_mode == 'include' ? '=' : '!', Settings.tracker_ids)
|
||||
end
|
||||
user_ids = Settings.user_ids
|
||||
add_filter(params, 'user_id', '=', (user_ids + BonusTechnician.pluck(:user_id)).uniq) if user_ids.any?
|
||||
params
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def filter_trackers(scope)
|
||||
ids = Settings.tracker_ids
|
||||
return scope if ids.empty?
|
||||
|
||||
if Settings.tracker_mode == 'include'
|
||||
scope.where(issues: { tracker_id: ids })
|
||||
else
|
||||
# Like Redmine's "is not" tracker filter: time logged without an issue still counts
|
||||
scope.where('issues.tracker_id IS NULL OR issues.tracker_id NOT IN (?)', ids)
|
||||
end
|
||||
end
|
||||
|
||||
def add_filter(params, field, operator, values)
|
||||
params[:f] << field
|
||||
params[:op][field] = operator
|
||||
params[:v][field] = values.map(&:to_s)
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user