From a64016eb9503ba29620411fc632f7bdd799a90bd Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Thu, 26 Feb 2026 19:48:29 -0500 Subject: [PATCH] Refactor QBO billing to use ActiveJob; remove threaded billing and add manual job enqueue support --- app/controllers/qbo_controller.rb | 31 ++++-- app/jobs/bill_issue_time_job.rb | 108 +++++++++++++++++++++ app/models/customer.rb | 2 - config/locales/en.yml | 3 + lib/redmine_qbo/patches/issue_patch.rb | 125 ++++++------------------- 5 files changed, 159 insertions(+), 110 deletions(-) create mode 100644 app/jobs/bill_issue_time_job.rb diff --git a/app/controllers/qbo_controller.rb b/app/controllers/qbo_controller.rb index 8216693..a65ce09 100644 --- a/app/controllers/qbo_controller.rb +++ b/app/controllers/qbo_controller.rb @@ -62,18 +62,29 @@ class QboController < ApplicationController # Manual Billing def bill - i = Issue.find_by_id params[:id] - if i.customer - billed = i.bill_time + issue = Issue.find_by(id: params[:id]) + return render_404 unless issue - if i.bill_time - redirect_to i, flash: { notice: I18n.t( :label_billed_success ) + i.customer.name } - else - redirect_to i, flash: { error: I18n.t(:label_billing_error) } - end - else - redirect_to i, flash: { error: I18n.t(:label_billing_error_no_customer) } + unless issue.customer + redirect_to issue, flash: { error: I18n.t(:label_billing_error_no_customer) } + return end + + unless issue.assigned_to&.employee_id.present? + redirect_to issue, flash: { error: I18n.t(:label_billing_error_no_employee) } + return + end + + unless Qbo.first + redirect_to issue, flash: { error: I18n.t(:label_billing_error_no_qbo) } + return + end + + BillIssueTimeJob.perform_later(issue.id) + + redirect_to issue, flash: { + notice: I18n.t(:label_billing_enqueued) + " #{issue.customer.name}" + } end # Quickbooks Webhook Callback diff --git a/app/jobs/bill_issue_time_job.rb b/app/jobs/bill_issue_time_job.rb new file mode 100644 index 0000000..76b2f09 --- /dev/null +++ b/app/jobs/bill_issue_time_job.rb @@ -0,0 +1,108 @@ +#The MIT License (MIT) +# +#Copyright (c) 2016 - 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 BillIssueTimeJob < ActiveJob::Base + queue_as :default + + def perform(issue_id) + issue = Issue.find(issue_id) + + Rails.logger.debug "QBO: Starting billing for issue ##{issue.id}" + + issue.with_lock do + unbilled_entries = issue.time_entries.where(billed: [false, nil]).lock + + return if unbilled_entries.blank? + + totals = aggregate_hours(unbilled_entries) + return if totals.blank? + + qbo = Qbo.first + raise "No QBO configuration found" unless qbo + + qbo.perform_authenticated_request do |access_token| + create_time_activities(issue, totals, access_token, qbo) + end + + # Only mark billed AFTER successful QBO creation + unbilled_entries.update_all(billed: true) + end + + Rails.logger.debug "QBO: Completed billing for issue ##{issue.id}" + rescue => e + Rails.logger.error "QBO: Billing failed for issue ##{issue_id} - #{e.message}" + raise e + end + + private + + def aggregate_hours(entries) + entries.includes(:activity) + .group_by { |e| e.activity&.name } + .transform_values { |rows| rows.sum(&:hours) } + .compact + end + + def create_time_activities(issue, totals, access_token, qbo) + time_service = Quickbooks::Service::TimeActivity.new( + company_id: qbo.realm_id, + access_token: access_token + ) + + item_service = Quickbooks::Service::Item.new( + company_id: qbo.realm_id, + access_token: access_token + ) + + totals.each do |activity_name, hours_float| + next if activity_name.blank? + next if hours_float.to_f <= 0 + + item = find_item(item_service, activity_name) + next unless item + + hours, minutes = convert_hours(hours_float) + + time_entry = Quickbooks::Model::TimeActivity.new + time_entry.description = build_description(issue) + time_entry.employee_id = issue.assigned_to.employee_id + time_entry.customer_id = issue.customer_id + time_entry.billable_status = "Billable" + time_entry.hours = hours + time_entry.minutes = minutes + time_entry.name_of = "Employee" + time_entry.txn_date = Date.today + time_entry.hourly_rate = item.unit_price + time_entry.item_id = item.id + + Rails.logger.debug "QBO: Creating TimeActivity for #{activity_name} (#{hours}h #{minutes}m)" + + time_service.create(time_entry) + end + end + + def convert_hours(hours_float) + total_minutes = (hours_float.to_f * 60).round + hours = total_minutes / 60 + minutes = total_minutes % 60 + [hours, minutes] + end + + def build_description(issue) + base = "#{issue.tracker} ##{issue.id}: #{issue.subject}" + return base if issue.closed? + "#{base} (Partial @ #{issue.done_ratio}%)" + end + + def find_item(item_service, name) + safe = name.gsub("'", "\\\\'") + item_service.query("SELECT * FROM Item WHERE Name = '#{safe}'").first + end +end \ No newline at end of file diff --git a/app/models/customer.rb b/app/models/customer.rb index 2e88461..93bd409 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -30,8 +30,6 @@ class Customer < ActiveRecord::Base :type => :to_s, :description => Proc.new {|o| "#{I18n.t :label_primary_phone}: #{o.phone_number} #{I18n.t:label_mobile_phone}: #{o.mobile_phone_number}"}, :datetime => Proc.new {|o| o.updated_at || o.created_at} - - #default_scope { order(name: :asc) } # Convenience Method # returns the customer's email diff --git a/config/locales/en.yml b/config/locales/en.yml index 0673ef5..8786e07 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -29,6 +29,9 @@ en: label_billing_address: "Billing Address" label_billing_error: "Customer could not be billed. Check for Customer or Assignee and try again." label_billing_error_no_customer: "Cannot bill without an assigned customer." + label_billing_error_no_employee: "Cannot bill without an assigned employee." + label_billing_error_no_qbo: "Cannot bill without a QuickBooks connection. Please connect to QuickBooks and try again." + label_billing_enqueued: "Billing has been enqueued for issue" label_billed_success: "Successfully billed " label_client_id: "Intuit QBO OAuth2 Client ID" label_client_secret: "Intuit QBO OAuth2 Client Secret" diff --git a/lib/redmine_qbo/patches/issue_patch.rb b/lib/redmine_qbo/patches/issue_patch.rb index ff7b3ea..1f23d48 100644 --- a/lib/redmine_qbo/patches/issue_patch.rb +++ b/lib/redmine_qbo/patches/issue_patch.rb @@ -12,130 +12,59 @@ require_dependency 'issue' module RedmineQbo module Patches - - # Patches Redmine's Issues dynamically. - # Adds relationships for customers, estimates, invoices, customer_tokens - # Adds before and after save hooks module IssuePatch - def self.included(base) # :nodoc: + def self.included(base) base.extend(ClassMethods) - base.send(:include, InstanceMethods) - # Same as typing in the class base.class_eval do belongs_to :customer, class_name: 'Customer', foreign_key: :customer_id, optional: true belongs_to :customer_token, primary_key: :id belongs_to :estimate, primary_key: :id has_and_belongs_to_many :invoices + before_save :titlize_subject - after_save :bill_time + after_commit :enqueue_billing, on: :update end - end - + module ClassMethods - + end - + module InstanceMethods - - # Create billable time entries - def bill_time - logger.debug "QBO: Billing time for issue ##{self.id}" - logger.debug "Issue is closed? #{self.closed?}" - - return false if self.assigned_to.nil? - return false unless Qbo.first - return false unless self.customer - Thread.new do - spent_time = self.time_entries.where(billed: [false, nil]) - spent_hours ||= spent_time.sum(:hours) || 0 + def enqueue_billing + Rails.logger.debug "QBO: Checking if issue needs to be billed for issue ##{id}" + #return unless saved_change_to_status_id? + return unless closed? + return unless customer.present? + return unless assigned_to&.employee_id.present? + return unless Qbo.first - logger.debug "Issue has spent hours: #{spent_hours}" - - if spent_hours > 0 then - - # Prepare to create a new Time Activity - qbo = Qbo.first - qbo.perform_authenticated_request do |access_token| - time_service = Quickbooks::Service::TimeActivity.new(company_id: qbo.realm_id, access_token: access_token) - item_service = Quickbooks::Service::Item.new(company_id: qbo.realm_id, access_token: access_token) - time_entry = Quickbooks::Model::TimeActivity.new - - # Lets total up each activity before billing. - # This will simpify the invoicing with a single billable time entry per time activity - h = Hash.new(0) - spent_time.each do |entry| - h[entry.activity.name] += entry.hours - # update time entries billed status - entry.billed = true - entry.save - end - - # Now letes upload our totals for each activity as their own billable time entry - h.each do |key, val| - logger.debug "Processing activity '#{key}' with #{val.to_i} hours for issue ##{self.id}" + Rails.logger.debug "QBO: Enqueuing billing for issue ##{id}" + BillIssueTimeJob.perform_later(id) + end - # Convert float spent time to hours and minutes - hours = val.to_i - minutesDecimal = (( val - hours) * 60) - minutes = minutesDecimal.to_i + def titlize_subject + Rails.logger.debug "QBO: Titlizing subject for issue ##{id}" - logger.debug "Converted #{val.to_i} hours to #{hours} hours and #{minutes} minutes" - - # Lets match the activity to an qbo item - item = item_service.query("SELECT * FROM Item WHERE Name = '#{key}' ").first - next if item.nil? - - # Create the new billable time entry and upload it - time_entry.description = "#{self.tracker} ##{self.id}: #{self.subject} #{"(Partial @ #{self.done_ratio}%)" unless self.closed?}" - time_entry.employee_id = self.assigned_to.employee_id - time_entry.customer_id = self.customer_id - time_entry.billable_status = "Billable" - time_entry.hours = hours - time_entry.minutes = minutes - time_entry.name_of = "Employee" - time_entry.txn_date = Date.today - time_entry.hourly_rate = item.unit_price - time_entry.item_id = item.id - time_entry.start_time = start_date - time_entry.end_time = Time.now - time_service.create(time_entry) - end - end + self.subject = subject.split(/\s+/).map do |word| + if word =~ /[A-Z]/ && word =~ /[0-9]/ + word + else + word.capitalize end - end - return true + end.join(' ') end end - - # Create a shareable link for a customer + def share_token - CustomerToken.get_token self + CustomerToken.get_token(self) end - - # Titleize the subject before save , but keep words containing numbers mixed with letters capitalized - def titlize_subject - logger.debug "QBO: Titlizing subject for issue ##{self.id}" - self.subject = self.subject.split(/\s+/).map do |word| - # If word is NOT purely alphanumeric (contains special chars), - # or is all upper/lower, we can handle it. - # excluding alphanumeric strings with mixed case and numbers (e.g., "ID555ABC") from being altered. - if word =~ /[A-Z]/ && word =~ /[0-9]/ - word - else - word.downcase - word.capitalize - end - end.join(' ') - end - end + end - # Add module to Issue Issue.send(:include, IssuePatch) - end end \ No newline at end of file