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:
rickyandClaude Opus 5.5 committed 2026-11-16 12:13:30 -05:00
commit a2ecb74c1d
37 files changed
+2274

No files matched your search

+21
View File
@@ -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.
+64
View File
@@ -0,0 +1,64 @@
# Redmine QBO Bonus
The weekly billable hours bonus for shop technicians (SOP-OPS-012, *Weekly Billable Hours Bonus Program*), paid as QuickBooks Online credit memos on each technician's customer account.
The bonus is a team goal. Everyone's billable hours count toward the shop's weekly total. That includes the technicians, the Foreman, and anyone else picked in the settings, such as front desk staff who help in the shop. Only the bonus technicians get the bonus.
* **Week**: Sunday through Saturday. It's named like Redmine's time report weeks (`2026-47`), by the year and ISO week number of its Monday.
* **Billable hours**: the time logged that week on the picked projects (with their subprojects), on every tracker except the picked ones (or only the picked ones).
* **Target**: 110 shop hours. A shop that reaches it earns each technician $100 and the Foreman $150.
* **Tiers**: every full 15 hours above the target (125, 140, ...) earns each technician another $100 and the Foreman another $150.
* **Eligibility**: a technician in their 90-day probation that week gets no bonus. Neither does one who missed any part of a scheduled shift; that one is unchecked when the week is run.
All the numbers can be changed in the settings.
## The credit memo
Each qualifying technician gets one credit memo per week on their QuickBooks customer account. It's emailed to the email on that account.
```
Tech Bonus 2026-47 127.5/110 hours (total/goal) 1 x $100.00 $100.00
Tier Bonus 2026-47 1 x 15 hours over goal 1 x $100.00 $100.00
```
The tier line is only there when a tier was reached. Both lines use the product/service picked in the settings, which sets the account the bonuses are booked to. They're non-taxable.
## Running a week
**Tech bonuses** (top menu) lists the weeks run so far. Pick a week to see:
* the shop's hours, the goal, the tiers reached and the hours to the next tier;
* each technician's hours and bonus, with an **Attended** box. Uncheck a technician who missed part of a scheduled shift;
* the hours of everyone whose time counted, with a link to Redmine's time report using the same filters, to check them.
Once the week is over, **Create & email credit memos** makes and emails the credit memos. The page then links each one in QuickBooks and shows whether it was emailed. A week can be run again, for example after fixing a technician's customer account or attendance. Running it again only makes the credit memos still missing, so nobody is credited twice. **Email again** resends a credit memo.
## 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_bonus.git
cd ..
bundle exec rake redmine:plugins:migrate
```
Restart Redmine, then:
1. **In QuickBooks**, make a service (e.g. *Tech Bonus*) booked to the account the bonuses should go to, then sync products/services in Redmine (**Administration » Items**).
2. **Administration » Plugins » Redmine QBO Bonus plugin » Configure**:
* Pick the projects, the trackers to leave out, and anyone besides the technicians whose time counts. With no users picked, everyone's time counts.
* Check the target and amounts.
* Pick the product/service.
3. **Administration » Bonus technicians**: add each technician and the Foreman. Give each one their role, the QuickBooks customer account their bonus is credited to, and the last day of their probation if they're in it.
4. **Administration » Roles and permissions**: give **Run tech bonuses** to the roles that run the bonus. It's a global permission, so it applies to any role the user has in any project.
## Tests
```
RAILS_ENV=test bundle exec rake redmine:plugins:test NAME=redmine_qbo_bonus
```
@@ -0,0 +1,68 @@
#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 » Bonus technicians: who earns the weekly bonus, their role and their QuickBooks customer account
class BonusTechniciansController < ApplicationController
layout 'admin'
self.main_menu = false
menu_item :bonus_technicians
before_action :require_admin
before_action :find_technician, only: [:edit, :update, :destroy]
def index
@technicians = BonusTechnician.sorted.includes(:customer).to_a
end
def new
@technician = BonusTechnician.new
end
def create
@technician = BonusTechnician.new(technician_params)
if @technician.save
flash[:notice] = l(:notice_successful_create)
redirect_to bonus_technicians_path
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @technician.update(technician_params)
flash[:notice] = l(:notice_successful_update)
redirect_to bonus_technicians_path
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@technician.destroy
flash[:notice] = l(:notice_successful_delete)
redirect_to bonus_technicians_path
end
private
def find_technician
@technician = BonusTechnician.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
def technician_params
permitted = params.require(:bonus_technician).permit(:user_id, :customer_id, :role, :probation_until, :active)
permitted[:customer_id] = permitted[:customer_id].presence if permitted.key?(:customer_id)
permitted
end
end
@@ -0,0 +1,97 @@
#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.
# Weekly billable hours bonus (SOP-OPS-012): the weeks run so far, a week's hours and bonuses, and running it
class TechBonusesController < ApplicationController
self.main_menu = false
menu_item :tech_bonuses
before_action :authorize_global
before_action :find_week, only: [:show, :create]
helper :tech_bonuses
WEEKS_TO_PICK = 12
def index
# The week picker
week = RedmineQboBonus::Week.parse(params[:week]) if params[:week].present?
return redirect_to(tech_bonus_week_path(week.to_param)) if week
@bonus_weeks = TechBonusWeek.recent.includes(:credits, :run_by).limit(52).to_a
@weeks = (0...WEEKS_TO_PICK).map { |n| RedmineQboBonus::Week.last_completed - n }
@week = RedmineQboBonus::Week.last_completed
end
def show
@report = RedmineQboBonus::WeekReport.new(@week)
@bonus_week = TechBonusWeek.for(@week)
@credits = @bonus_week ? @bonus_week.credits.index_by(&:user_id) : {}
end
def create
runner = RedmineQboBonus::Runner.new(@week, attended_user_ids: Array(params[:attended]))
bonus_week = runner.run
credits = bonus_week.credits.to_a
if !bonus_week.goal_met?
flash[:warning] = l(:notice_tech_bonus_goal_not_met, week: @week.label)
elsif credits.any? { |credit| credit.status == 'failed' }
flash[:error] = l(:notice_tech_bonus_some_failed)
else
flash[:notice] = l(:notice_tech_bonus_run, count: credits.count(&:credited?), week: @week.label)
end
redirect_to tech_bonus_week_path(@week.to_param)
rescue RedmineQboBonus::Runner::Error => e
flash[:error] = e.message
redirect_to tech_bonus_week_path(@week.to_param)
end
# Emails a credit memo again (e.g. after fixing the technician's email in QuickBooks)
def resend
credit = TechBonusCredit.find(params[:id])
week = credit.tech_bonus_week.week
unless credit.credited?
render_404
return
end
Rails.cache.delete(credit.customer.details_cache_key) if credit.customer
email = RedmineQboBonus::Runner.customer_email(credit.customer)
if RedmineQboBonus::Runner.email(credit, email)
flash[:notice] = l(:notice_tech_bonus_emailed, email: email)
else
flash[:error] = credit.message
end
redirect_to tech_bonus_week_path(week.to_param)
rescue ActiveRecord::RecordNotFound
render_404
end
# The credit memo as QuickBooks prints it
def pdf
credit = TechBonusCredit.find(params[:id])
return render_404 unless credit.credited?
pdf = RedmineQboBonus::CreditMemoWriter.pdf(credit.credit_memo_id)
send_data pdf, filename: "credit-memo-#{credit.doc_number.presence || credit.credit_memo_id}.pdf",
type: 'application/pdf', disposition: 'inline'
rescue ActiveRecord::RecordNotFound
render_404
rescue StandardError => e
flash[:error] = e.message
redirect_to tech_bonuses_path
end
private
def find_week
@week = RedmineQboBonus::Week.parse(params[:week])
render_404 unless @week
end
end
+44
View File
@@ -0,0 +1,44 @@
#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 TechBonusesHelper
def bonus_hours(hours)
RedmineQboBonus.format_hours(hours)
end
def bonus_money(amount)
RedmineQboBonus.format_money(amount)
end
# "2026-47 (11/15/2026 – 11/21/2026)"
def bonus_week_title(week)
"#{week.label} (#{format_date(week.start_date)} – #{format_date(week.end_date)})"
end
def credit_memo_url(credit)
host = RedmineQbo.respond_to?(:sandbox_mode?) && RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'
"https://#{host}.qbo.intuit.com/app/creditmemo?txnId=#{credit.credit_memo_id}"
end
def credit_memo_link(credit)
return '' unless credit&.credited?
label = credit.doc_number.present? ? "##{credit.doc_number}" : l(:label_tech_bonus_credit_memo)
safe_join([link_to(label, credit_memo_url(credit), target: '_blank', rel: 'noopener'),
link_to('PDF', tech_bonus_credit_pdf_path(credit), target: '_blank', rel: 'noopener')], ' · ')
end
def bonus_status_tag(credit)
return '' unless credit
css = { 'emailed' => 'tech-bonus-ok', 'created' => 'tech-bonus-ok', 'failed' => 'tech-bonus-error' }
content_tag(:span, credit.status_name, class: "tech-bonus-status #{css[credit.status]}")
end
end
+67
View File
@@ -0,0 +1,67 @@
#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 BonusTechnician < ApplicationRecord
# The SOP's roles, by their bonus amounts (RedmineQboBonus::Settings.amount)
ROLES = %w[technician foreman].freeze
belongs_to :user
belongs_to :customer, optional: true
has_many :credits, class_name: 'TechBonusCredit', foreign_key: :user_id, primary_key: :user_id
validates :user_id, presence: true, uniqueness: true
validates :role, inclusion: { in: ROLES }
validate :customer_exists
scope :active, -> { where(active: true) }
scope :sorted, -> { includes(:user).order(Arel.sql('users.firstname, users.lastname')).references(:users) }
def self.role_options
ROLES.map { |role| [I18n.t("label_bonus_role_#{role}"), role] }
end
def role_name
I18n.t("label_bonus_role_#{role}")
end
def name
user&.name.to_s
end
# In the 90-day probation during the week (no bonus that week)
def on_probation?(week)
probation_until.present? && probation_until >= week.start_date
end
# Why the technician can't get a bonus for the week (attendance aside), or nil
def ineligible_reason(week)
return I18n.t(:text_tech_bonus_inactive) unless active?
return I18n.t(:text_tech_bonus_probation, date: I18n.l(probation_until)) if on_probation?(week)
return I18n.t(:text_tech_bonus_no_customer) if customer.nil?
nil
end
def base_amount
RedmineQboBonus::Settings.amount(role)
end
def tier_amount
RedmineQboBonus::Settings.tier_amount(role)
end
private
def customer_exists
return if customer_id.blank?
errors.add(:customer_id, :invalid) unless Customer.exists?(id: customer_id)
end
end
+33
View File
@@ -0,0 +1,33 @@
#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 TechBonusCredit < ApplicationRecord
STATUSES = %w[created emailed skipped failed].freeze
belongs_to :tech_bonus_week
belongs_to :user
belongs_to :customer, optional: true
validates :user_id, uniqueness: { scope: :tech_bonus_week_id }
validates :status, inclusion: { in: STATUSES }
# A credit memo was made in QuickBooks (whether or not it was emailed)
def credited?
credit_memo_id.present?
end
def amount
base_amount.to_d + tier_amount.to_d
end
def status_name
I18n.t("label_tech_bonus_status_#{status}")
end
end
+45
View File
@@ -0,0 +1,45 @@
#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 TechBonusWeek < ApplicationRecord
belongs_to :run_by, class_name: 'User', optional: true
has_many :credits, class_name: 'TechBonusCredit', dependent: :destroy
validates :week_start, presence: true, uniqueness: true
scope :recent, -> { order(week_start: :desc) }
def self.for(week)
find_by(week_start: week.start_date)
end
def week
RedmineQboBonus::Week.new(week_start)
end
def goal_met?
total_hours >= goal_hours
end
# Each user's hours, as { user_id => BigDecimal }
def hours_by_user
JSON.parse(self[:hours_by_user].presence || '{}').to_h { |id, hours| [id.to_i, BigDecimal(hours.to_s)] }
rescue JSON::ParserError
{}
end
def hours_by_user=(hours)
self[:hours_by_user] = hours.to_h { |id, value| [id.to_s, value.to_d.round(2).to_s('F')] }.to_json
end
def credited_total
credits.select(&:credited?).sum(&:amount)
end
end
@@ -0,0 +1,32 @@
<%= error_messages_for @technician %>
<% taken = BonusTechnician.where.not(id: @technician.id).pluck(:user_id) %>
<% users = User.active.sorted.where.not(id: taken).to_a %>
<% users << @technician.user if @technician.user && !users.include?(@technician.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: @technician.persisted? } %>
</p>
<p>
<label for="bonus_technician_customer_name"><%= l(:label_bonus_technician_customer) %></label>
<%= text_field_tag 'customer_name', @technician.customer&.name, id: 'bonus_technician_customer_name',
class: 'customer-name', autocomplete: 'off', size: 40, placeholder: l(:label_choose_a_customer),
data: { autocomplete_url: '/customers/autocomplete' } %>
<%= f.hidden_field :customer_id, id: 'customer_id' %>
<em class="info"><%= l(:text_bonus_technician_customer) %></em>
</p>
<p><%= f.select :role, BonusTechnician.role_options, required: true %></p>
<p>
<%= f.date_field :probation_until, label: :field_bonus_technician_probation_until %>
<em class="info"><%= l(:text_bonus_technician_probation) %></em>
</p>
<p><%= f.check_box :active %></p>
</div>
<%= javascript_tag do %>
$(function() {
if (window.initCustomerAutocomplete) { window.initCustomerAutocomplete(document); }
$('#bonus_technician_customer_name').on('input', function() {
if (!$(this).val()) { $('#customer_id').val(''); }
});
});
<% end %>
@@ -0,0 +1,8 @@
<h2><%= link_to l(:label_bonus_technician_plural), bonus_technicians_path %> » <%= @technician.name %></h2>
<%= labelled_form_for @technician, url: bonus_technician_path(@technician), method: :patch do |f| %>
<%= render partial: 'bonus_technicians/form', locals: { f: f } %>
<%= submit_tag l(:button_save) %>
<% end %>
<% html_title @technician.name %>
@@ -0,0 +1,45 @@
<div class="contextual">
<%= link_to sprite_icon('add', l(:label_bonus_technician_new)), new_bonus_technician_path, class: 'icon icon-add' %>
<%= link_to sprite_icon('settings', l(:label_settings)), plugin_settings_path('redmine_qbo_bonus'), class: 'icon icon-settings' %>
</div>
<h2><%= l(:label_bonus_technician_plural) %></h2>
<p><em class="info"><%= l(:text_bonus_technicians) %></em></p>
<% if @technicians.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_role) %></th>
<th><%= l(:label_bonus_technician_customer) %></th>
<th><%= l(:field_bonus_technician_probation_until) %></th>
<th><%= l(:field_active) %></th>
<th></th>
</tr>
</thead>
<tbody>
<% @technicians.each do |tech| %>
<tr>
<td class="name"><%= link_to_user tech.user %></td>
<td><%= tech.role_name %></td>
<td><%= tech.customer ? link_to(tech.customer.name, customer_path(tech.customer)) : content_tag(:span, l(:text_tech_bonus_no_customer), class: 'tech-bonus-error') %></td>
<td><%= format_date(tech.probation_until) %></td>
<td><%= checked_image tech.active? %></td>
<td class="buttons">
<%= link_to sprite_icon('edit', l(:button_edit)), edit_bonus_technician_path(tech), class: 'icon icon-edit' %>
<%= link_to sprite_icon('del', l(:button_delete)), bonus_technician_path(tech), method: :delete,
data: { confirm: l(:text_are_you_sure) }, class: 'icon icon-del' %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% end %>
<% html_title l(:label_bonus_technician_plural) %>
+8
View File
@@ -0,0 +1,8 @@
<h2><%= link_to l(:label_bonus_technician_plural), bonus_technicians_path %> » <%= l(:label_bonus_technician_new) %></h2>
<%= labelled_form_for @technician, url: bonus_technicians_path do |f| %>
<%= render partial: 'bonus_technicians/form', locals: { f: f } %>
<%= submit_tag l(:button_create) %>
<% end %>
<% html_title l(:label_bonus_technician_new) %>
+84
View File
@@ -0,0 +1,84 @@
<%# Settings for redmine_qbo_bonus (Administration » Plugins » Configure) %>
<% s = RedmineQboBonus::Settings %>
<% field = ->(key) { "settings[#{key}]" } %>
<p>
<%= link_to sprite_icon('user', l(:label_bonus_technician_plural)), bonus_technicians_path, class: 'icon icon-user' %>
<%= link_to sprite_icon('time', l(:label_tech_bonus_plural)), tech_bonuses_path, class: 'icon icon-time' %>
</p>
<fieldset class="box tabular">
<legend><%= l(:label_tech_bonus_hours_counted) %></legend>
<p>
<label for="qbo_bonus_projects"><%= l(:label_project_plural) %></label>
<%= hidden_field_tag "#{field.call('project_ids')}[]", '', id: nil %>
<%= select_tag "#{field.call('project_ids')}[]",
project_tree_options_for_select(Project.active.sorted.to_a, selected: Project.where(id: s.project_ids).to_a),
multiple: true, size: 8, id: 'qbo_bonus_projects' %>
<em class="info"><%= l(:text_tech_bonus_projects) %></em>
</p>
<p>
<label for="qbo_bonus_subprojects"><%= l(:label_tech_bonus_include_subprojects) %></label>
<%= hidden_field_tag field.call('include_subprojects'), '0', id: nil %>
<%= check_box_tag field.call('include_subprojects'), '1', s.include_subprojects?, id: 'qbo_bonus_subprojects' %>
</p>
<p>
<label for="qbo_bonus_trackers"><%= l(:label_tracker_plural) %></label>
<%= select_tag field.call('tracker_mode'),
options_for_select([[l(:label_tech_bonus_trackers_exclude), 'exclude'], [l(:label_tech_bonus_trackers_include), 'include']], s.tracker_mode),
id: 'qbo_bonus_tracker_mode' %><br>
<%= hidden_field_tag "#{field.call('tracker_ids')}[]", '', id: nil %>
<%= select_tag "#{field.call('tracker_ids')}[]", options_from_collection_for_select(Tracker.sorted, :id, :name, s.tracker_ids),
multiple: true, size: 8, id: 'qbo_bonus_trackers' %>
<em class="info"><%= l(:text_tech_bonus_trackers) %></em>
</p>
<p>
<label for="qbo_bonus_users"><%= l(:label_tech_bonus_users) %></label>
<%= hidden_field_tag "#{field.call('user_ids')}[]", '', id: nil %>
<%= select_tag "#{field.call('user_ids')}[]", options_from_collection_for_select(User.active.sorted, :id, :name, s.user_ids),
multiple: true, size: 8, id: 'qbo_bonus_users' %>
<em class="info"><%= l(:text_tech_bonus_users) %></em>
</p>
</fieldset>
<fieldset class="box tabular">
<legend><%= l(:label_tech_bonus_target) %></legend>
<p>
<label for="qbo_bonus_goal"><%= l(:label_tech_bonus_goal_hours) %></label>
<%= number_field_tag field.call('goal_hours'), RedmineQboBonus.format_hours(s.goal_hours), id: 'qbo_bonus_goal', min: 0, step: 0.25, style: 'width: 6em' %>
<em class="info"><%= l(:text_tech_bonus_goal) %></em>
</p>
<p>
<label for="qbo_bonus_tier"><%= l(:label_tech_bonus_tier_hours) %></label>
<%= number_field_tag field.call('tier_hours'), RedmineQboBonus.format_hours(s.tier_hours), id: 'qbo_bonus_tier', min: 0.25, step: 0.25, style: 'width: 6em' %>
<em class="info"><%= l(:text_tech_bonus_tier) %></em>
</p>
<% BonusTechnician::ROLES.each do |role| %>
<p>
<label for="qbo_bonus_<%= role %>_amount"><%= l("label_bonus_role_#{role}") %></label>
<%= number_field_tag field.call("#{role}_amount"), RedmineQboBonus.format_hours(s.amount(role)), id: "qbo_bonus_#{role}_amount", min: 0, step: 0.01, style: 'width: 6em' %>
<%= l(:label_tech_bonus_per_tier) %>
<%= number_field_tag field.call("#{role}_tier_amount"), RedmineQboBonus.format_hours(s.tier_amount(role)), id: "qbo_bonus_#{role}_tier_amount", min: 0, step: 0.01, style: 'width: 6em' %>
</p>
<% end %>
</fieldset>
<fieldset class="box tabular">
<legend><%= l(:label_tech_bonus_credit_memo) %></legend>
<p>
<label for="qbo_bonus_item"><%= l(:label_tech_bonus_item) %><span class="required"> *</span></label>
<%= select_tag field.call('item_id'), options_from_collection_for_select(Item.sellable.order(:name), :id, :name, s.item_id),
include_blank: true, id: 'qbo_bonus_item' %>
<em class="info"><%= l(:text_tech_bonus_item) %></em>
</p>
<p>
<label for="qbo_bonus_memo"><%= l(:label_tech_bonus_customer_memo) %></label>
<%= text_area_tag field.call('customer_memo'), s.customer_memo, id: 'qbo_bonus_memo', rows: 2, cols: 60 %>
</p>
<p>
<label for="qbo_bonus_email"><%= l(:label_tech_bonus_email_credits) %></label>
<%= hidden_field_tag field.call('email_credits'), '0', id: nil %>
<%= check_box_tag field.call('email_credits'), '1', s.email_credits?, id: 'qbo_bonus_email' %>
<em class="info"><%= l(:text_tech_bonus_email_credits) %></em>
</p>
</fieldset>
+3
View File
@@ -0,0 +1,3 @@
<% content_for :header_tags do %>
<%= stylesheet_link_tag 'qbo_bonus', plugin: 'redmine_qbo_bonus' %>
<% end %>
+57
View File
@@ -0,0 +1,57 @@
<%= render partial: 'tech_bonuses/styles' %>
<div class="contextual">
<% if User.current.admin? %>
<%= link_to sprite_icon('user', l(:label_bonus_technician_plural)), bonus_technicians_path, class: 'icon icon-user' %>
<%= link_to sprite_icon('settings', l(:label_settings)), plugin_settings_path('redmine_qbo_bonus'), class: 'icon icon-settings' %>
<% end %>
</div>
<h2><%= l(:label_tech_bonus_plural) %></h2>
<%= form_tag(tech_bonuses_path, method: :get, id: 'tech-bonus-week-picker', class: 'tech-bonus-picker') do %>
<label for="tech_bonus_week"><%= l(:label_tech_bonus_week) %></label>
<%= select_tag 'week', options_for_select(@weeks.map { |week| [bonus_week_title(week), week.to_param] }, @week.to_param),
id: 'tech_bonus_week' %>
<%= submit_tag l(:button_tech_bonus_preview), name: nil %>
<% end %>
<h3><%= l(:label_tech_bonus_history) %></h3>
<% if @bonus_weeks.empty? %>
<p class="nodata"><%= l(:label_no_data) %></p>
<% else %>
<div class="autoscroll">
<table class="list tech-bonus-weeks">
<thead>
<tr>
<th><%= l(:label_tech_bonus_week) %></th>
<th><%= l(:label_tech_bonus_hours_total_goal) %></th>
<th><%= l(:label_tech_bonus_tiers) %></th>
<th><%= l(:label_tech_bonus_credits) %></th>
<th><%= l(:label_tech_bonus_amount) %></th>
<th><%= l(:label_tech_bonus_run_by) %></th>
</tr>
</thead>
<tbody>
<% @bonus_weeks.each do |bonus_week| %>
<tr>
<td><%= link_to bonus_week_title(bonus_week.week), tech_bonus_week_path(bonus_week.week.to_param) %></td>
<td class="<%= bonus_week.goal_met? ? 'tech-bonus-ok' : 'tech-bonus-miss' %>">
<%= bonus_hours(bonus_week.total_hours) %>/<%= bonus_hours(bonus_week.goal_hours) %>
</td>
<td><%= bonus_week.tiers %></td>
<td>
<%= bonus_week.credits.count(&:credited?) %>
<% failed = bonus_week.credits.count { |credit| credit.status == 'failed' } %>
<% if failed.positive? %><span class="tech-bonus-error">(<%= l(:label_tech_bonus_failed_count, count: failed) %>)</span><% end %>
</td>
<td><%= bonus_money(bonus_week.credited_total) %></td>
<td><%= bonus_week.run_by ? link_to_user(bonus_week.run_by) : '' %> <%= format_time(bonus_week.updated_at) %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% end %>
<% html_title l(:label_tech_bonus_plural) %>
+153
View File
@@ -0,0 +1,153 @@
<%= render partial: 'tech_bonuses/styles' %>
<% report = @report %>
<% previous_week = @week - 1 %>
<% next_week = @week + 1 %>
<div class="contextual">
<%= link_to "« #{previous_week.label}", tech_bonus_week_path(previous_week.to_param) %>
<% if next_week.start_date <= Date.current %>
| <%= link_to "#{next_week.label} »", tech_bonus_week_path(next_week.to_param) %>
<% end %>
| <%= link_to sprite_icon('time', l(:label_tech_bonus_time_report)), report_time_entries_path(report.redmine_report_params), class: 'icon icon-time' %>
</div>
<h2><%= link_to l(:label_tech_bonus_plural), tech_bonuses_path %> » <%= bonus_week_title(@week) %></h2>
<div class="tech-bonus-summary">
<div class="box">
<%= l(:label_tech_bonus_total_hours) %>
<span class="value <%= report.goal_met? ? 'tech-bonus-ok' : 'tech-bonus-miss' %>"><%= bonus_hours(report.total_hours) %></span>
</div>
<div class="box">
<%= l(:label_tech_bonus_goal_hours) %>
<span class="value"><%= bonus_hours(report.goal_hours) %></span>
</div>
<div class="box">
<%= l(:label_tech_bonus_tiers) %>
<span class="value"><%= report.tiers %></span>
<%= l(:text_tech_bonus_tier_every, hours: bonus_hours(report.tier_hours)) %>
</div>
<div class="box">
<% if report.goal_met? %>
<%= l(:label_tech_bonus_next_tier) %>
<% else %>
<%= l(:label_tech_bonus_short_of_goal) %>
<% end %>
<span class="value"><%= bonus_hours(report.hours_to_next_tier) %></span>
</div>
</div>
<% unless @week.completed? %>
<p class="warning"><%= l(:text_tech_bonus_week_in_progress, date: format_date(@week.end_date)) %></p>
<% end %>
<h3><%= l(:label_tech_bonus_technicians) %></h3>
<% if report.lines.empty? %>
<p class="nodata"><%= l(:text_tech_bonus_no_technicians) %>
<% if User.current.admin? %><%= link_to l(:label_bonus_technician_new), new_bonus_technician_path %><% end %></p>
<% else %>
<%= form_tag tech_bonus_week_path(@week.to_param), method: :post, id: 'tech-bonus-run' do %>
<div class="autoscroll">
<table class="list tech-bonus-table">
<thead>
<tr>
<th><%= l(:label_user) %></th>
<th><%= l(:field_role) %></th>
<th><%= l(:label_tech_bonus_hours) %></th>
<th title="<%= l(:text_tech_bonus_attendance) %>"><%= l(:label_tech_bonus_attended) %></th>
<th><%= l(:label_tech_bonus_base) %></th>
<th><%= l(:label_tech_bonus_tier_bonus) %></th>
<th><%= l(:label_tech_bonus_amount) %></th>
<th><%= l(:label_tech_bonus_credit_memo) %></th>
<th><%= l(:field_status) %></th>
<th></th>
</tr>
</thead>
<tbody>
<% report.lines.each do |line| %>
<% tech = line.technician %>
<% credit = @credits[tech.user_id] %>
<% credited = credit&.credited? %>
<tr class="<%= 'ineligible' unless line.eligible? %>">
<td class="name"><%= link_to_user tech.user %><br><small><%= tech.customer&.name || l(:text_tech_bonus_no_customer) %></small></td>
<td><%= tech.role_name %></td>
<td><%= bonus_hours(line.hours) %></td>
<td>
<% if credited %>
<%= sprite_icon('checked', l(:general_text_Yes)) %>
<% elsif line.eligible? %>
<%= check_box_tag 'attended[]', tech.user_id, credit.nil? || credit.message != l(:text_tech_bonus_missed_shift),
id: "attended_#{tech.user_id}", disabled: !report.goal_met? %>
<% end %>
</td>
<% if credited %>
<td><%= bonus_money(credit.base_amount) %></td>
<td><%= bonus_money(credit.tier_amount) %></td>
<td><%= bonus_money(credit.amount) %></td>
<% else %>
<td><%= bonus_money(line.base_amount) %></td>
<td><%= bonus_money(line.tier_amount) %></td>
<td><%= bonus_money(line.amount) %></td>
<% end %>
<td><%= credit_memo_link(credit) %></td>
<td class="message">
<%= bonus_status_tag(credit) %>
<% message = credit&.message.presence || line.ineligible_reason %>
<% if credit&.emailed_to.present? %><br><small><%= credit.emailed_to %></small><% end %>
<% if message %><br><small><%= message %></small><% end %>
</td>
<td>
<% if credited %>
<%= link_to sprite_icon('email', l(:button_tech_bonus_resend)), resend_tech_bonus_credit_path(credit),
method: :post, class: 'icon icon-email',
data: { confirm: l(:text_tech_bonus_resend_confirm) } %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<p><em class="info"><%= l(:text_tech_bonus_attendance) %></em></p>
<% if @week.completed? %>
<p>
<% label = report.goal_met? ? l(:button_tech_bonus_run) : l(:button_tech_bonus_record) %>
<%= submit_tag label, data: { confirm: report.goal_met? ? l(:text_tech_bonus_run_confirm) : nil } %>
<% if @bonus_week %>
<em class="info"><%= l(:text_tech_bonus_already_run, user: @bonus_week.run_by&.name, time: format_time(@bonus_week.updated_at)) %></em>
<% end %>
</p>
<% end %>
<% end %>
<% end %>
<h3><%= l(:label_tech_bonus_shop_hours) %></h3>
<% if report.hours_by_user.empty? %>
<p class="nodata"><%= l(:label_no_data) %></p>
<% else %>
<% tech_ids = report.technicians.map(&:user_id) %>
<div class="autoscroll">
<table class="list tech-bonus-table">
<thead>
<tr><th><%= l(:label_user) %></th><th><%= l(:label_tech_bonus_hours) %></th></tr>
</thead>
<tbody>
<% report.hours_by_user.each do |user_id, hours| %>
<tr>
<td class="name">
<%= report.users[user_id] ? link_to_user(report.users[user_id]) : "##{user_id}" %>
<% unless tech_ids.include?(user_id) %><small>(<%= l(:text_tech_bonus_helping) %>)</small><% end %>
</td>
<td><%= bonus_hours(hours) %></td>
</tr>
<% end %>
</tbody>
<tfoot>
<tr><td class="name"><%= l(:label_total_time) %></td><td><%= bonus_hours(report.total_hours) %></td></tr>
</tfoot>
</table>
</div>
<% end %>
<% html_title "#{l(:label_tech_bonus_plural)} #{@week.label}" %>
+14
View File
@@ -0,0 +1,14 @@
/* redmine_qbo_bonus: weekly bonus pages */
.tech-bonus-picker { margin-bottom: 1em; }
.tech-bonus-summary { display: flex; flex-wrap: wrap; gap: 1em; margin: 1em 0; }
.tech-bonus-summary .box { flex: 1 1 10em; margin: 0; text-align: center; }
.tech-bonus-summary .value { font-size: 1.8em; font-weight: bold; display: block; }
.tech-bonus-ok { color: #2e7d32; }
.tech-bonus-miss { color: #b26a00; }
.tech-bonus-error { color: #c62828; }
.tech-bonus-status { font-weight: bold; }
table.list.tech-bonus-table td { text-align: center; }
table.list.tech-bonus-table td.name, table.list.tech-bonus-table td.message { text-align: left; }
table.list.tech-bonus-table tr.ineligible td { opacity: .6; }
table.list.tech-bonus-table tfoot td { font-weight: bold; }
+90
View File
@@ -0,0 +1,90 @@
en:
permission_run_tech_bonuses: "Run tech bonuses"
label_tech_bonus_plural: "Tech bonuses"
label_bonus_technician_plural: "Bonus technicians"
label_bonus_technician_new: "New bonus technician"
label_bonus_technician_customer: "Customer account"
label_bonus_role_technician: "Technician"
label_bonus_role_foreman: "Foreman"
field_bonus_technician_probation_until: "Probation until"
field_probation_until: "Probation until"
label_tech_bonus_week: "Week"
label_tech_bonus_history: "Weeks run"
label_tech_bonus_hours_total_goal: "Hours (total/goal)"
label_tech_bonus_tiers: "Tiers"
label_tech_bonus_credits: "Credit memos"
label_tech_bonus_failed_count: "%{count} failed"
label_tech_bonus_amount: "Amount"
label_tech_bonus_run_by: "Run by"
label_tech_bonus_time_report: "Time report"
label_tech_bonus_total_hours: "Shop hours"
label_tech_bonus_goal_hours: "Goal hours"
label_tech_bonus_tier_hours: "Tier hours"
label_tech_bonus_next_tier: "Hours to next tier"
label_tech_bonus_short_of_goal: "Hours short of goal"
label_tech_bonus_technicians: "Technicians"
label_tech_bonus_hours: "Hours"
label_tech_bonus_attended: "Attended"
label_tech_bonus_base: "Bonus"
label_tech_bonus_tier_bonus: "Tier bonus"
label_tech_bonus_credit_memo: "Credit memo"
label_tech_bonus_shop_hours: "Hours by user"
label_tech_bonus_hours_counted: "Billable hours"
label_tech_bonus_include_subprojects: "Include subprojects"
label_tech_bonus_trackers_exclude: "All trackers except"
label_tech_bonus_trackers_include: "Only these trackers"
label_tech_bonus_users: "Users"
label_tech_bonus_target: "Target and amounts"
label_tech_bonus_per_tier: "+ per tier"
label_tech_bonus_item: "Product/service"
label_tech_bonus_customer_memo: "Message on credit memo"
label_tech_bonus_email_credits: "Email credit memos"
label_tech_bonus_status_created: "Created"
label_tech_bonus_status_emailed: "Emailed"
label_tech_bonus_status_skipped: "Skipped"
label_tech_bonus_status_failed: "Failed"
button_tech_bonus_preview: "Show"
button_tech_bonus_run: "Create & email credit memos"
button_tech_bonus_record: "Record week"
button_tech_bonus_resend: "Email again"
notice_tech_bonus_run: "%{count} credit memo(s) for week %{week}."
notice_tech_bonus_goal_not_met: "Week %{week} didn't reach the goal, so there are no bonuses."
notice_tech_bonus_some_failed: "Some credit memos couldn't be made. See why below, then run the week again to retry them."
notice_tech_bonus_emailed: "Credit memo emailed to %{email}."
error_tech_bonus_week_not_over: "The week isn't over yet."
error_tech_bonus_no_item: "Pick the product/service for bonus credit memos in the plugin's settings."
error_tech_bonus_not_created: "QuickBooks didn't create the credit memo."
error_tech_bonus_not_emailed: "QuickBooks didn't email the credit memo."
text_tech_bonus_line: "Tech Bonus %{week} %{total}/%{goal} hours (total/goal)"
text_tech_bonus_tier_line: "Tier Bonus %{week} %{tiers} x %{hours} hours over goal"
text_tech_bonus_private_note: "Weekly billable hours bonus (SOP-OPS-012), week %{week} (%{from} to %{to}). Made by Redmine."
text_tech_bonus_tier_every: "every %{hours} hours over goal"
text_tech_bonus_week_in_progress: "This week isn't over until %{date}, so its hours can still change. Its bonus can be run once it's over."
text_tech_bonus_no_technicians: "No bonus technicians yet."
text_tech_bonus_attendance: "Uncheck a technician who missed any part of a scheduled shift this week: they don't get the bonus (SOP-OPS-012 §4)."
text_tech_bonus_run_confirm: "Create a credit memo in QuickBooks for each checked technician, and email it to them?"
text_tech_bonus_resend_confirm: "Email this credit memo again?"
text_tech_bonus_already_run: "Last run by %{user} on %{time}. Running it again only makes the credit memos still missing."
text_tech_bonus_helping: "not a technician"
text_tech_bonus_inactive: "Not active"
text_tech_bonus_probation: "On probation until %{date}"
text_tech_bonus_no_customer: "No customer account"
text_tech_bonus_missed_shift: "Missed a scheduled shift"
text_tech_bonus_no_email: "Not emailed: the customer account has no email in QuickBooks."
text_tech_bonus_email_failed: "Not emailed: %{error}"
text_bonus_technicians: "The technicians and Foreman who earn the weekly billable hours bonus (SOP-OPS-012). Their bonus is credited to their customer account in QuickBooks."
text_bonus_technician_customer: "Their customer account in QuickBooks. Credit memos are emailed to its email."
text_bonus_technician_probation: "The last day of their 90-day probation. Weeks that start on or before this day get no bonus."
text_tech_bonus_projects: "Time logged on these projects counts. None: every project."
text_tech_bonus_trackers: "Time logged without an issue counts with \"All trackers except\"."
text_tech_bonus_users: "Whose time counts toward the shop's hours besides the bonus technicians' (e.g. front desk staff who help in the shop). None: everyone's."
text_tech_bonus_goal: "The shop's weekly target (SOP-OPS-012: 110)."
text_tech_bonus_tier: "A tier bonus for every full this many hours over the goal (SOP-OPS-012: 15)."
text_tech_bonus_item: "The QuickBooks product/service on the credit memo lines (e.g. \"Tech Bonus\"). It sets the account the bonuses are booked to."
text_tech_bonus_email_credits: "Email each credit memo to the technician when it's made."
+23
View File
@@ -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.
RedmineApp::Application.routes.draw do
# Weekly bonus: the weeks run, a week's hours and bonuses (by its Sunday, e.g. /tech_bonuses/2026-11-15)
get 'tech_bonuses', to: 'tech_bonuses#index', as: :tech_bonuses
get 'tech_bonuses/:week', to: 'tech_bonuses#show', as: :tech_bonus_week, constraints: { week: /\d{4}-\d{2}-\d{2}/ }
post 'tech_bonuses/:week', to: 'tech_bonuses#create', constraints: { week: /\d{4}-\d{2}-\d{2}/ }
get 'tech_bonuses/credits/:id/pdf', to: 'tech_bonuses#pdf', as: :tech_bonus_credit_pdf
post 'tech_bonuses/credits/:id/resend', to: 'tech_bonuses#resend', as: :resend_tech_bonus_credit
# Administration » Bonus technicians
resources :bonus_technicians, except: [:show]
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.
class CreateBonusTechnicians < ActiveRecord::Migration[7.0]
def change
# A technician who earns the weekly bonus, and the QuickBooks customer account their credits go to
create_table :bonus_technicians do |t|
t.integer :user_id, null: false
# redmine_qbo's customers.id (the QuickBooks customer id)
t.string :customer_id
# technician or foreman (their amounts)
t.string :role, null: false, default: 'technician'
# No bonus for a week 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 :bonus_technicians, :user_id, unique: true
end
end
+28
View File
@@ -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.
class CreateTechBonusWeeks < ActiveRecord::Migration[7.0]
def change
# A week a bonus was run for, with the hours and target it was run with
create_table :tech_bonus_weeks do |t|
# The week's Sunday
t.date :week_start, null: false
t.decimal :total_hours, precision: 10, scale: 2, null: false, default: 0
t.decimal :goal_hours, precision: 10, scale: 2, null: false, default: 0
t.decimal :tier_hours, precision: 10, scale: 2, null: false, default: 0
t.integer :tiers, null: false, default: 0
# Each user's hours that week, as JSON ({"user_id": hours})
t.text :hours_by_user
t.integer :run_by_id
t.timestamps
end
add_index :tech_bonus_weeks, :week_start, unique: true
end
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.
class CreateTechBonusCredits < ActiveRecord::Migration[7.0]
def change
# A technician's bonus for a week: the credit memo made for it, or why there wasn't one
create_table :tech_bonus_credits do |t|
t.integer :tech_bonus_week_id, null: false
t.integer :user_id, null: false
t.string :customer_id
t.string :role
t.decimal :base_amount, precision: 10, scale: 2, null: false, default: 0
t.decimal :tier_amount, precision: 10, scale: 2, null: false, default: 0
# The QuickBooks credit memo
t.string :credit_memo_id
t.string :doc_number
# created, emailed, skipped or failed
t.string :status, null: false
# Why it was skipped or failed
t.text :message
t.string :emailed_to
t.datetime :emailed_at
t.timestamps
end
add_index :tech_bonus_credits, [:tech_bonus_week_id, :user_id], unique: true
add_index :tech_bonus_credits, :user_id
end
end
+44
View File
@@ -0,0 +1,44 @@
#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_bonus do
# About
name 'Redmine QBO Bonus plugin'
author 'Rick Barrette'
description 'Weekly billable hours bonus for technicians (SOP-OPS-012): totals the shop\'s billable hours for a week, ' \
'and credits each qualifying technician\'s QuickBooks customer account with an emailed credit memo'
version '2026.11.0'
url 'https://gitea.rickbarrette.org/ricky/redmine_qbo_bonus'
author_url 'https://barrettefabrication.com'
requires_redmine version_or_higher: '7.0.0'
# Customers, products/services and the QuickBooks connection live 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: RedmineQboBonus::Settings::DEFAULTS.dup, partial: 'settings/qbo_bonus'
# Previewing a week's bonus, creating and emailing its credit memos
permission :run_tech_bonuses, { tech_bonuses: [:index, :show, :create, :resend, :pdf] }, global: true
menu :top_menu, :tech_bonuses, { controller: 'tech_bonuses', action: 'index' },
caption: :label_tech_bonus_plural, after: :my_page,
if: proc { User.current.allowed_to?(:run_tech_bonuses, nil, global: true) }
# The technicians who earn the bonus and their QuickBooks customer accounts
menu :admin_menu, :bonus_technicians, { controller: 'bonus_technicians', action: 'index' },
caption: :label_bonus_technician_plural, icon: 'user', html: { class: 'icon icon-user' }
end
RedmineQboBonus.setup
+28
View File
@@ -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
+109
View File
@@ -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
+111
View File
@@ -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
+81
View File
@@ -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
+149
View File
@@ -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
@@ -0,0 +1,50 @@
#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 BonusTechniciansTest < Redmine::IntegrationTest
include QboBonusTestHelper
def test_admins_link_a_user_to_a_customer
customer = create_customer(id: 9100, name: 'Jane Tech')
log_user('admin', 'admin')
get '/bonus_technicians/new'
assert_response :success
assert_select 'input.customer-name'
assert_difference 'BonusTechnician.count', 1 do
post '/bonus_technicians', params: { bonus_technician: { user_id: '2', customer_id: customer.id.to_s,
role: 'foreman', active: '1' } }
end
assert_redirected_to '/bonus_technicians'
tech = BonusTechnician.last
assert_equal customer, tech.customer
assert_equal 'foreman', tech.role
get '/bonus_technicians'
assert_select 'td', text: 'Jane Tech'
patch "/bonus_technicians/#{tech.id}", params: { bonus_technician: { probation_until: '2026-12-01' } }
assert_equal Date.new(2026, 12, 1), tech.reload.probation_until
end
def test_unknown_customer
log_user('admin', 'admin')
post '/bonus_technicians', params: { bonus_technician: { user_id: '2', customer_id: '424242', role: 'technician' } }
assert_response :unprocessable_entity
end
def test_admins_only
log_user('jsmith', 'jsmith')
get '/bonus_technicians'
assert_response :forbidden
end
end
+88
View File
@@ -0,0 +1,88 @@
#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 TechBonusesTest < Redmine::IntegrationTest
include QboBonusTestHelper
def setup
Customer.any_instance.stubs(:email).returns('tech@example.com')
RedmineQboBonus::Settings.stubs(:item).returns(Struct.new(:id, :name).new('31', 'Tech Bonus'))
RedmineQboBonus::CreditMemoWriter.stubs(:send_email).returns(true)
RedmineQboBonus::CreditMemoWriter.any_instance.stubs(:create).returns(saved_credit_memo)
create_technician(2)
log_time(2, 100)
log_time(3, 15.5)
end
def test_needs_the_permission
log_user('jsmith', 'jsmith')
get '/tech_bonuses'
assert_response :forbidden
Role.find(1).add_permission!(:run_tech_bonuses)
get '/tech_bonuses'
assert_response :success
assert_select '#top-menu a.tech-bonuses'
end
def test_week_preview
log_user('admin', 'admin')
get '/tech_bonuses', params: { week: '2026-11-10' }
assert_redirected_to '/tech_bonuses/2026-11-08'
get '/tech_bonuses/2026-11-08'
assert_response :success
assert_select 'h2', text: /2026-46/
assert_select '.tech-bonus-summary .value', text: '115.5'
assert_select 'input[name=?][value="2"]', 'attended[]'
assert_select 'td', text: '$100.00'
assert_select 'a[href^="/time_entries/report"]'
end
def test_run_week
log_user('admin', 'admin')
post '/tech_bonuses/2026-11-08', params: { attended: ['2'] }
assert_redirected_to '/tech_bonuses/2026-11-08'
credit = TechBonusCredit.find_by(user_id: 2)
assert_equal 'emailed', credit.status
assert_equal '1042', credit.doc_number
follow_redirect!
assert_select 'a[href*="creditmemo?txnId=777"]', text: '#1042'
get '/tech_bonuses'
assert_select 'table.tech-bonus-weeks td', text: /115.5\/110/
end
def test_pdf
log_user('admin', 'admin')
post '/tech_bonuses/2026-11-08', params: { attended: ['2'] }
credit = TechBonusCredit.find_by(user_id: 2)
RedmineQboBonus::CreditMemoWriter.expects(:pdf).with('777').returns('%PDF-1.4')
get "/tech_bonuses/credits/#{credit.id}/pdf"
assert_response :success
assert_equal 'application/pdf', response.media_type
end
def test_resend
log_user('admin', 'admin')
post '/tech_bonuses/2026-11-08', params: { attended: ['2'] }
credit = TechBonusCredit.find_by(user_id: 2)
RedmineQboBonus::CreditMemoWriter.expects(:send_email).with('777', 'tech@example.com').returns(true)
post "/tech_bonuses/credits/#{credit.id}/resend"
assert_redirected_to '/tech_bonuses/2026-11-08'
end
def test_not_a_week
log_user('admin', 'admin')
get '/tech_bonuses/2026-02-31'
assert_response :not_found
end
end
+70
View File
@@ -0,0 +1,70 @@
#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 QboBonusTestHelper
# Sunday 2026-11-08 to Saturday 2026-11-14 (2026-46)
WEEK_START = Date.new(2026, 11, 8)
def self.included(base)
base.fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :enabled_modules
base.setup do
TechBonusCredit.delete_all
TechBonusWeek.delete_all
BonusTechnician.delete_all
TimeEntry.delete_all
Customer.where(id: 9000..9999).delete_all
end
end
def bonus_week
RedmineQboBonus::Week.new(WEEK_START)
end
# Time logged without Redmine's checks (membership, permissions)
def log_time(user_id, hours, spent_on: WEEK_START + 1, issue_id: 1, project_id: nil)
issue = issue_id && Issue.find(issue_id)
entry = TimeEntry.new(user_id: user_id, author_id: user_id, hours: hours, spent_on: spent_on, issue: issue,
project_id: project_id || issue&.project_id, activity_id: 9)
entry.save!(validate: false)
entry
end
# A customer, without sending it to QuickBooks
def create_customer(id: 9001, name: 'Jane Tech')
customer = Customer.new(id: id, name: name)
customer.skip_qbo_push = true
customer.save!
customer
end
def create_technician(user_id, role: 'technician', customer: nil, **attributes)
customer ||= create_customer(id: 9000 + user_id, name: "Tech #{user_id}")
BonusTechnician.create!({ user_id: user_id, role: role, customer_id: customer.id }.merge(attributes))
end
def with_bonus_settings(values)
saved = Setting.plugin_redmine_qbo_bonus
Setting.plugin_redmine_qbo_bonus = RedmineQboBonus::Settings::DEFAULTS.merge(values)
yield
ensure
Setting.plugin_redmine_qbo_bonus = saved
end
# A credit memo as QuickBooks returns it
def saved_credit_memo(id: '777', doc_number: '1042')
memo = Quickbooks::Model::CreditMemo.new
memo.id = id
memo.doc_number = doc_number
memo
end
end
+57
View File
@@ -0,0 +1,57 @@
#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 CreditMemoWriterTest < ActiveSupport::TestCase
include QboBonusTestHelper
FakeItem = Struct.new(:id, :name)
def setup
RedmineQboBonus::Settings.stubs(:item).returns(FakeItem.new('31', 'Tech Bonus'))
end
def build(hours)
tech = create_technician(2)
log_time(2, hours)
report = RedmineQboBonus::WeekReport.new(bonus_week)
RedmineQboBonus::CreditMemoWriter.new(report).build(report.lines.first, customer: tech.customer,
email: 'tech@example.com')
end
def test_one_line_at_the_goal
memo = build(115.5)
assert_equal 1, memo.line_items.size
line = memo.line_items.first
assert_equal 'Tech Bonus 2026-46 115.5/110 hours (total/goal)', line.description
assert_equal BigDecimal('100'), line.amount
assert_equal '31', line.sales_item_line_detail.item_ref.value
assert_equal 'NON', line.sales_item_line_detail.tax_code_ref.value
assert_equal '9002', memo.customer_ref.value
assert_equal 'tech@example.com', memo.bill_email.address
end
def test_tiers_on_their_own_line
memo = build(141)
assert_equal 2, memo.line_items.size
tier = memo.line_items.last
assert_equal 'Tier Bonus 2026-46 2 x 15 hours over goal', tier.description
assert_equal BigDecimal('2'), tier.sales_item_line_detail.quantity
assert_equal BigDecimal('100'), tier.sales_item_line_detail.unit_price
assert_equal BigDecimal('200'), tier.amount
assert_includes memo.to_xml.to_s, 'Tier Bonus'
end
def test_needs_a_product_or_service
RedmineQboBonus::Settings.stubs(:item).returns(nil)
assert_raises(RedmineQboBonus::CreditMemoWriter::Error) { build(120) }
end
end
+128
View File
@@ -0,0 +1,128 @@
#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 RunnerTest < ActiveSupport::TestCase
include QboBonusTestHelper
# Stands in for QuickBooks
class FakeWriter
attr_reader :created
def initialize(fail_for: [])
@created = []
@fail_for = fail_for
end
def create(line, customer:, email: nil)
raise 'QuickBooks is down' if @fail_for.include?(line.technician.user_id)
@created << [line.technician.user_id, line.amount, email]
memo = Quickbooks::Model::CreditMemo.new
memo.id = (700 + @created.size).to_s
memo.doc_number = (1000 + @created.size).to_s
memo
end
end
def setup
User.current = User.find(1)
RedmineQboBonus::Settings.stubs(:item).returns(Struct.new(:id, :name).new('31', 'Tech Bonus'))
Customer.any_instance.stubs(:email).returns('tech@example.com')
RedmineQboBonus::CreditMemoWriter.stubs(:send_email).returns(true)
@tech = create_technician(2)
@foreman = create_technician(3, role: 'foreman')
log_time(2, 60)
log_time(3, 50)
log_time(1, 16) # 126 hours: 1 tier
end
def run_bonus(attended: [2, 3], writer: FakeWriter.new)
runner = RedmineQboBonus::Runner.new(bonus_week, attended_user_ids: attended, writer: writer)
[runner.run, writer]
end
def test_credits_and_emails_each_technician
week, writer = run_bonus
assert_equal [[2, BigDecimal('200'), 'tech@example.com'], [3, BigDecimal('300'), 'tech@example.com']],
writer.created.sort_by(&:first)
assert_equal BigDecimal('126'), week.total_hours
assert_equal 1, week.tiers
assert_equal BigDecimal('16'), week.hours_by_user[1]
credit = week.credits.find_by(user_id: 3)
assert_equal 'emailed', credit.status
assert_equal 'tech@example.com', credit.emailed_to
assert credit.credited?
assert_equal BigDecimal('500'), week.credited_total
end
def test_missed_shift_is_skipped
week, writer = run_bonus(attended: [2])
assert_equal [2], writer.created.map(&:first)
credit = week.credits.find_by(user_id: 3)
assert_equal 'skipped', credit.status
assert_equal BigDecimal('0'), credit.amount
end
def test_running_again_never_credits_twice
run_bonus(attended: [2])
week, writer = run_bonus(attended: [2, 3])
assert_equal [3], writer.created.map(&:first)
assert_equal 2, week.credits.count(&:credited?)
end
def test_a_failure_is_recorded_and_retried
week, = run_bonus(writer: FakeWriter.new(fail_for: [3]))
credit = week.credits.find_by(user_id: 3)
assert_equal 'failed', credit.status
assert_equal 'QuickBooks is down', credit.message
week, writer = run_bonus
assert_equal [3], writer.created.map(&:first)
assert_equal 'emailed', week.credits.find_by(user_id: 3).status
end
def test_no_email_keeps_it_created
Customer.any_instance.stubs(:email).returns(nil)
week, = run_bonus
credit = week.credits.find_by(user_id: 2)
assert_equal 'created', credit.status
assert_match(/no email/, credit.message)
end
def test_not_emailed_when_turned_off
RedmineQboBonus::CreditMemoWriter.expects(:send_email).never
with_bonus_settings('email_credits' => '0') do
week, = run_bonus
assert_equal %w[created created], week.credits.map(&:status)
end
end
def test_goal_not_met_records_the_week_only
TimeEntry.where(user_id: 3).delete_all # 76 hours
week, writer = run_bonus
assert_empty writer.created
assert_not week.goal_met?
assert_empty week.credits
end
def test_needs_a_product_or_service
RedmineQboBonus::Settings.stubs(:item).returns(nil)
assert_raises(RedmineQboBonus::Runner::Error) { run_bonus }
assert_equal 0, TechBonusWeek.count
end
def test_only_finished_weeks
runner = RedmineQboBonus::Runner.new(RedmineQboBonus::Week.containing(Date.current), attended_user_ids: [2],
writer: FakeWriter.new)
assert_raises(RedmineQboBonus::Runner::Error) { runner.run }
end
end
+127
View File
@@ -0,0 +1,127 @@
#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 WeekReportTest < ActiveSupport::TestCase
include QboBonusTestHelper
def report
RedmineQboBonus::WeekReport.new(bonus_week)
end
def test_everyones_hours_count_toward_the_shop_total
create_technician(2)
log_time(2, 60)
log_time(3, 40.5) # not a technician (e.g. front desk)
log_time(2, 8, spent_on: WEEK_START - 1) # Saturday before
log_time(2, 8, spent_on: WEEK_START + 7) # Sunday after
assert_equal({ 2 => BigDecimal('60'), 3 => BigDecimal('40.5') }, report.hours_by_user)
assert_equal BigDecimal('100.5'), report.total_hours
assert_not report.goal_met?
assert_equal 0, report.tiers
end
def test_sunday_and_saturday_count
log_time(2, 5, spent_on: WEEK_START)
log_time(2, 5, spent_on: WEEK_START + 6)
assert_equal BigDecimal('10'), report.total_hours
end
def test_a_tier_for_every_full_15_hours_over_the_goal
{ '110' => 0, '124.99' => 0, '125' => 1, '139.75' => 1, '140' => 2 }.each do |hours, tiers|
TimeEntry.delete_all
log_time(2, BigDecimal(hours))
assert_equal tiers, report.tiers, "#{hours} hours"
assert report.goal_met?
end
end
def test_projects_and_subprojects
log_time(2, 10, issue_id: 1) # eCookbook
log_time(2, 20, issue_id: 5) # eCookbook's subproject
log_time(2, 40, issue_id: 4) # OnlineStore
with_bonus_settings('project_ids' => ['1'], 'include_subprojects' => '1') do
assert_equal BigDecimal('30'), report.total_hours
end
with_bonus_settings('project_ids' => ['1'], 'include_subprojects' => '0') do
assert_equal BigDecimal('10'), report.total_hours
end
end
def test_excluded_trackers
Issue.find(2).update_columns(tracker_id: 3)
log_time(2, 10, issue_id: 1)
log_time(2, 20, issue_id: 2)
log_time(2, 5, issue_id: nil, project_id: 1)
with_bonus_settings('tracker_mode' => 'exclude', 'tracker_ids' => ['3']) do
assert_equal BigDecimal('15'), report.total_hours
end
with_bonus_settings('tracker_mode' => 'include', 'tracker_ids' => ['3']) do
assert_equal BigDecimal('20'), report.total_hours
end
end
def test_picked_users_and_the_technicians
create_technician(2)
log_time(2, 10)
log_time(3, 20)
log_time(1, 40)
with_bonus_settings('user_ids' => ['3']) do
assert_equal [2, 3], report.hours_by_user.keys.sort
end
end
def test_what_each_technician_earns
create_technician(2)
create_technician(3, role: 'foreman')
log_time(2, 70)
log_time(3, 72) # 142 hours: 2 tiers
lines = report.lines.index_by { |line| line.technician.user_id }
assert_equal BigDecimal('100'), lines[2].base_amount
assert_equal BigDecimal('200'), lines[2].tier_amount
assert_equal BigDecimal('150'), lines[3].base_amount
assert_equal BigDecimal('300'), lines[3].tier_amount
assert_equal BigDecimal('450'), lines[3].amount
end
def test_nothing_below_the_goal
create_technician(2)
log_time(2, 109.75)
assert_equal BigDecimal('0'), report.lines.first.amount
assert_equal BigDecimal('0.25'), report.hours_to_next_tier
end
def test_probation_and_missing_customer_are_ineligible
create_technician(2, probation_until: WEEK_START)
tech = create_technician(3)
tech.update_columns(customer_id: nil)
log_time(2, 130)
lines = report.lines.index_by { |line| line.technician.user_id }
assert_match(/probation/i, lines[2].ineligible_reason)
assert_equal BigDecimal('0'), lines[2].amount
assert_match(/customer/i, lines[3].ineligible_reason)
BonusTechnician.find_by(user_id: 2).update!(probation_until: WEEK_START - 1)
assert RedmineQboBonus::WeekReport.new(bonus_week).lines.find { |l| l.technician.user_id == 2 }.eligible?
end
def test_redmine_report_params
with_bonus_settings('project_ids' => ['2'], 'tracker_ids' => %w[3 18]) do
params = report.redmine_report_params
assert_equal %w[spent_on project_id issue.tracker_id], params[:f]
assert_equal '!', params[:op]['issue.tracker_id']
assert_equal %w[2026-11-08 2026-11-14], params[:v]['spent_on']
end
end
end
+54
View File
@@ -0,0 +1,54 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
class WeekTest < ActiveSupport::TestCase
Week = RedmineQboBonus::Week
def test_weeks_run_sunday_to_saturday
week = Week.containing(Date.new(2026, 11, 18))
assert_equal Date.new(2026, 11, 15), week.start_date
assert_equal Date.new(2026, 11, 21), week.end_date
assert_equal week, Week.containing(Date.new(2026, 11, 15))
assert_equal week, Week.containing(Date.new(2026, 11, 21))
assert_equal week + 1, Week.containing(Date.new(2026, 11, 22))
end
def test_named_by_the_iso_week_of_their_monday
assert_equal '2026-47', Week.containing(Date.new(2026, 11, 18)).label
assert_equal '2026-46', Week.containing(Date.new(2026, 11, 8)).label
assert_equal '2026-53', Week.containing(Date.new(2026, 12, 31)).label
assert_equal '2027-01', Week.containing(Date.new(2027, 1, 3)).label
end
def test_last_completed_week
assert_equal Date.new(2026, 11, 8), Week.last_completed(Date.new(2026, 11, 16)).start_date
assert_equal Date.new(2026, 11, 8), Week.last_completed(Date.new(2026, 11, 15)).start_date
assert_equal Date.new(2026, 11, 15), Week.last_completed(Date.new(2026, 11, 22)).start_date
end
def test_completed_once_saturday_is_over
week = Week.containing(Date.new(2026, 11, 18))
assert_not week.completed?(Date.new(2026, 11, 21))
assert week.completed?(Date.new(2026, 11, 22))
end
def test_parse
assert_equal Date.new(2026, 11, 15), Week.parse('2026-11-18').start_date
assert_equal '2026-11-15', Week.parse('2026-11-15').to_param
assert_nil Week.parse('nope')
assert_nil Week.parse('2026-13-45')
end
def test_only_starts_on_sunday
assert_raises(ArgumentError) { Week.new(Date.new(2026, 11, 16)) }
end
end