Cache totals, man-hours and payments; add a business report

- Estimates now keep their total; estimates and invoices keep their man-hours: the quantities of the
  products/services set as "Replaced by imported time" (bundles included; the estimate item codes
  while that setting is blank). Filled in by the webhook and the sync.
- Payment model (QboBaseModel) caching each payment's customer, date, amount and unapplied amount,
  kept current by the webhook, the sync and the Receive payment page.
- Business report (View business reports permission, top menu): estimates written vs. invoices written
  vs. payments received, and estimated hours on estimates and issues vs. invoiced and spent hours, for
  a period, with a month-by-month breakdown.
- Fix two keyword arguments that defaulted to themselves (QboSyncDispatcher.enque_jobs, PdfService),
  which newer Ruby refuses to parse.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-31 07:54:28 -04:00
1 parent d07d99109b
commit 062ef9b8b3
20 files changed
+590 -5

No files matched your search

+15
View File
@@ -93,6 +93,10 @@ Invoices containing an Issue reference (e.g. `#123`) automatically attach to the
Customer records are automatically updated in the local database when changes occur in QuickBooks. Customer records are automatically updated in the local database when changes occur in QuickBooks.
### Estimates, Invoices and Payments
Estimates and invoices keep their number, date, customer, total and **man-hours** (the quantities of the products/services set as "Replaced by imported time", including lines inside bundles; the estimate item codes are used while that setting is blank). Payments keep their customer, date, amount and unapplied amount. These cached figures feed the business report.
--- ---
## Billing: Estimates, Invoices and Payments ## Billing: Estimates, Invoices and Payments
@@ -131,6 +135,16 @@ Customer records are automatically updated in the local database when changes oc
* The saved payment's page shows where it was applied and has **Print**, QuickBooks' payment PDF. * The saved payment's page shows where it was applied and has **Print**, QuickBooks' payment PDF.
* **Payments** on the customer page lists all of the customer's payments from QuickBooks, newest first: date, method, reference no., the invoices each was applied to (or Deposit), memo, amount and what's still unapplied, with totals. Each date opens the payment's page and **Print** opens its PDF. * **Payments** on the customer page lists all of the customer's payments from QuickBooks, newest first: date, method, reference no., the invoices each was applied to (or Deposit), memo, amount and what's still unapplied, with totals. Each date opens the payment's page and **Print** opens its PDF.
### Business report
**Business report** in the top menu compares, for a period (this or last month, quarter or year, or custom dates):
* **Sales**: estimates written, invoices written and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices.
* **Hours**: estimated hours on estimates, issues' estimated time, invoiced hours on invoices and time spent, with invoiced vs. spent and spent vs. estimated.
* **By month**: every figure month by month, with totals.
Estimates, invoices and payments count by their QuickBooks date. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. Estimates and invoices synced before these figures were added have no total or hours until a full sync (the report says how many); run one again after changing "Replaced by imported time".
### QuickBooks custom fields ### QuickBooks custom fields
Nothing is configured in Redmine. The plugin reads QuickBooks' sales form settings, and the custom fields on the 20 most recently changed estimates, and finds the fields by name: Nothing is configured in Redmine. The plugin reads QuickBooks' sales form settings, and the custom fields on the 20 most recently changed estimates, and finds the fields by name:
@@ -168,6 +182,7 @@ Administration → Items lists the QuickBooks product/service list (synced from
* **Create issues from estimates**: the Create issues page (was redmine_qbo_calendar's "Create issues from appointment estimates") * **Create issues from estimates**: the Create issues page (was redmine_qbo_calendar's "Create issues from appointment estimates")
* **View payments**: a customer's Payments list, the payment page and its PDF * **View payments**: a customer's Payments list, the payment page and its PDF
* **Receive payments**: the Receive payment page, plus everything View payments allows * **Receive payments**: the Receive payment page, plus everything View payments allows
* **View business reports**: the Business report
* **Write invoices**: create and edit invoices, and import time and estimates into them * **Write invoices**: create and edit invoices, and import time and estimates into them
* **Email invoices**: email invoices to customers * **Email invoices**: email invoices to customers
+22
View File
@@ -0,0 +1,22 @@
#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.
# Business report: estimates and invoices written and payments received, and estimated, invoiced and spent
# hours, for a period (RedmineQboBilling::BusinessReport)
class QboReportsController < ApplicationController
before_action :authorize_global
def index
@report = RedmineQboBilling::BusinessReport.new(period: params[:period].presence || 'this_year',
from: params[:from], to: params[:to], today: User.current.today)
end
end
+3 -2
View File
@@ -14,7 +14,8 @@ class QboSyncDispatcher
Customer, Customer,
Estimate, Estimate,
Invoice, Invoice,
Employee Employee,
Payment
].freeze ].freeze
# Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database. # Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database.
@@ -27,7 +28,7 @@ class QboSyncDispatcher
private private
# Dynamically enques all sync jobs # Dynamically enques all sync jobs
def self.enque_jobs(full_sync: full_sync) def self.enque_jobs(full_sync: false)
jobs = SYNC_JOBS.dup jobs = SYNC_JOBS.dup
# Allow other plugins to add addtional sync jobs via Hooks # Allow other plugins to add addtional sync jobs via Hooks
+1
View File
@@ -17,6 +17,7 @@ class WebhookProcessJob < ActiveJob::Base
Invoice Invoice
Estimate Estimate
Employee Employee
Payment
].freeze ].freeze
# Process incoming QBO webhook notifications and sync relevant data to Redmine # Process incoming QBO webhook notifications and sync relevant data to Redmine
+1
View File
@@ -16,6 +16,7 @@ class Customer < QboBaseModel
has_many :issues has_many :issues
has_many :invoices has_many :invoices
has_many :estimates has_many :estimates
has_many :payments
validates_presence_of :name validates_presence_of :name
before_validation :normalize_phone_numbers before_validation :normalize_phone_numbers
self.primary_key = :id self.primary_key = :id
+25
View File
@@ -0,0 +1,25 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# A customer payment, cached from QuickBooks for reporting: id, customer, date and amount. Kept current by the
# webhook and the sync; payments are received through the Receive payment page (RedmineQboBilling::PaymentWriter).
class Payment < QboBaseModel
belongs_to :customer, optional: true
validates :id, presence: true, uniqueness: true
self.primary_key = :id
qbo_sync push: false
def to_s
"#{txn_date} #{total_amount}"
end
end
+3
View File
@@ -26,6 +26,9 @@ class EstimateSyncService < SyncServiceBase
end end
map_attributes :doc_number, :txn_date map_attributes :doc_number, :txn_date
map_attribute :total_amount, :total
# Man-hours: quantities of the products/services set as "Replaced by imported time"
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
map_belongs_to :customer map_belongs_to :customer
end end
+2
View File
@@ -24,6 +24,8 @@ class InvoiceSyncService < SyncServiceBase
map_attributes :balance, :doc_number, :due_date, :txn_date map_attributes :balance, :doc_number, :due_date, :txn_date
map_attribute :total_amount, :total map_attribute :total_amount, :total
# Man-hours: quantities of the products/services set as "Replaced by imported time"
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
map_attribute :qbo_updated_at, "meta_data.last_updated_time" map_attribute :qbo_updated_at, "meta_data.last_updated_time"
map_belongs_to :customer map_belongs_to :customer
+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.
# Reads a payment's details from QuickBooks for the Payment model (payments are only cached here, never pushed)
class PaymentService < ServiceBase
private
def build_qbo_remote
Quickbooks::Model::Payment.new
end
end
+32
View File
@@ -0,0 +1,32 @@
#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.
# Caches QuickBooks payments: customer, date, amount and what's still unapplied
class PaymentSyncService < SyncServiceBase
private
# Specify the local model this service syncs
def self.model_class
Payment
end
map_attributes :txn_date
map_attribute :total_amount, :total
map_attribute :unapplied_amount
map_attribute :qbo_updated_at, "meta_data.last_updated_time"
# A payment whose customer hasn't synced yet keeps none until the next sync
map_attribute :customer do |remote|
id = remote.customer_ref&.value
id.present? ? Customer.find_by(id: id) : nil
end
end
+1 -1
View File
@@ -12,7 +12,7 @@ class PdfService
require 'combine_pdf' require 'combine_pdf'
# Subclasses should initialize with a QBO client instance # Subclasses should initialize with a QBO client instance
def initialize(entity: entity) def initialize(entity:)
raise "An entity to sync is required" unless entity raise "An entity to sync is required" unless entity
@entity = entity @entity = entity
end end
+148
View File
@@ -0,0 +1,148 @@
<% html_title l(:label_business_report) %>
<% money = @report.money %>
<% hours = @report.hours %>
<% ratios = @report.ratios %>
<% max_money = [money[:estimates][:total], money[:invoices][:total], money[:payments][:total]].max.to_f %>
<% max_hours = hours.values.max.to_f %>
<% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %>
<% fmt_hours = ->(h) { format('%.1f', h.to_f) } %>
<% pct = ->(v) { v.nil? ? '–' : "#{v}%" } %>
<h2><%= l(:label_business_report) %></h2>
<%= form_tag qbo_reports_path, method: :get, id: 'qbo-report-form' do %>
<fieldset class="box">
<legend><%= l(:label_report_period) %></legend>
<%= select_tag 'period',
options_for_select(RedmineQboBilling::BusinessReport::PERIODS.map { |p| [l("label_report_period_#{p}"), p] }, @report.period),
id: 'qbo-report-period' %>
<span id="qbo-report-dates">
<%= date_field_tag 'from', @report.from.iso8601, id: 'qbo-report-from' %>
&ndash;
<%= date_field_tag 'to', @report.to.iso8601, id: 'qbo-report-to' %>
</span>
<%= submit_tag l(:button_apply), name: nil %>
</fieldset>
<% end %>
<p class="qbo-report-range"><%= format_date(@report.from) %> &ndash; <%= format_date(@report.to) %></p>
<% if @report.unsynced_count > 0 %>
<p class="warning"><%= l(:text_report_needs_sync, count: @report.unsynced_count) %></p>
<% end %>
<div class="splitcontent">
<div class="splitcontentleft">
<h3><%= l(:label_report_money) %></h3>
<table class="list qbo-report">
<tbody>
<% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)],
[:payments, l(:label_report_payments_received)]].each do |key, label| %>
<tr>
<td class="name"><%= label %> <span class="count">(<%= money[key][:count] %>)</span></td>
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(money[key][:total], max_money) %>%"></div></td>
<td class="value"><%= number_to_currency(money[key][:total]) %></td>
</tr>
<% end %>
</tbody>
</table>
<p class="qbo-report-ratios">
<%= l(:label_report_invoiced_of_estimated) %>: <strong><%= pct.call(ratios[:invoiced_of_estimated]) %></strong><br />
<%= l(:label_report_collected_of_invoiced) %>: <strong><%= pct.call(ratios[:collected_of_invoiced]) %></strong><br />
<%= l(:label_report_open_balance) %>: <strong><%= number_to_currency(money[:invoices][:balance]) %></strong>
</p>
</div>
<div class="splitcontentright">
<h3><%= l(:label_report_hours) %></h3>
<table class="list qbo-report">
<tbody>
<% [[:estimate_hours, l(:label_report_estimate_hours)], [:issue_hours, l(:label_report_issue_hours)],
[:invoice_hours, l(:label_report_invoice_hours)], [:spent_hours, l(:label_report_spent_hours)]].each do |key, label| %>
<tr>
<td class="name"><%= label %></td>
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(hours[key], max_hours) %>%"></div></td>
<td class="value"><%= fmt_hours.call(hours[key]) %></td>
</tr>
<% end %>
</tbody>
</table>
<p class="qbo-report-ratios">
<%= l(:label_report_invoiced_of_spent) %>: <strong><%= pct.call(ratios[:invoiced_of_spent]) %></strong><br />
<%= l(:label_report_spent_of_estimated) %>: <strong><%= pct.call(ratios[:spent_of_estimated]) %></strong>
</p>
</div>
</div>
<h3><%= l(:label_report_by_month) %></h3>
<div class="autoscroll">
<table class="list qbo-report-months">
<thead>
<tr>
<th class="month"><%= l(:label_month) %></th>
<th><%= l(:label_report_estimates_written) %></th>
<th><%= l(:label_report_invoices_written) %></th>
<th><%= l(:label_report_payments_received) %></th>
<th class="hours-start"><%= l(:label_report_estimate_hours) %></th>
<th><%= l(:label_report_issue_hours) %></th>
<th><%= l(:label_report_invoice_hours) %></th>
<th><%= l(:label_report_spent_hours) %></th>
</tr>
</thead>
<tbody>
<% @report.months.each do |row| %>
<tr>
<td class="month"><%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %></td>
<td><%= number_to_currency(row[:estimates]) %></td>
<td><%= number_to_currency(row[:invoices]) %></td>
<td><%= number_to_currency(row[:payments]) %></td>
<td class="hours-start"><%= fmt_hours.call(row[:estimate_hours]) %></td>
<td><%= fmt_hours.call(row[:issue_hours]) %></td>
<td><%= fmt_hours.call(row[:invoice_hours]) %></td>
<td><%= fmt_hours.call(row[:spent_hours]) %></td>
</tr>
<% end %>
</tbody>
<tfoot>
<tr class="total">
<td class="month"><strong><%= l(:label_total) %></strong></td>
<td><strong><%= number_to_currency(money[:estimates][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:invoices][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:payments][:total]) %></strong></td>
<td class="hours-start"><strong><%= fmt_hours.call(hours[:estimate_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:issue_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:invoice_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:spent_hours]) %></strong></td>
</tr>
</tfoot>
</table>
</div>
<p class="info"><%= l(:text_report_notes) %></p>
<style>
table.qbo-report td { padding: 6px 4px; }
table.qbo-report td.name { text-align: left; white-space: nowrap; width: 1%; }
table.qbo-report td.name .count { color: #888; }
table.qbo-report td.bar { width: 100%; }
table.qbo-report td.value { text-align: right; white-space: nowrap; font-weight: bold; width: 1%; }
.qbo-bar { height: 14px; border-radius: 2px; min-width: 1px; background: #628db6; }
.qbo-bar-invoices, .qbo-bar-invoice_hours { background: #e8a33d; }
.qbo-bar-payments, .qbo-bar-spent_hours { background: #5aa05a; }
.qbo-bar-issue_hours { background: #9b7fc0; }
.qbo-report-ratios { margin: 8px 4px; line-height: 1.7; }
.qbo-report-range { color: #666; margin: 4px 0 10px; }
table.qbo-report-months td, table.qbo-report-months th { text-align: right; white-space: nowrap; }
table.qbo-report-months .month { text-align: left; }
table.qbo-report-months .hours-start { border-left: 2px solid #ddd; }
table.qbo-report-months tfoot td { border-top: 2px solid #ccc; }
#qbo-report-form select, #qbo-report-form input { vertical-align: middle; }
</style>
<%= javascript_tag do %>
$(function() {
var $period = $('#qbo-report-period'), $dates = $('#qbo-report-from, #qbo-report-to');
// Picking a preset fills its dates on Apply; changing a date switches to Custom
$dates.on('change', function() { $period.val('custom'); });
$period.on('change', function() { if ($period.val() !== 'custom') { $('#qbo-report-form').submit(); } });
});
<% end %>
+29 -1
View File
@@ -262,7 +262,7 @@ en:
text_invoice_from_estimate: "Made from estimate #%{number}. The estimate is closed when the invoice is saved." text_invoice_from_estimate: "Made from estimate #%{number}. The estimate is closed when the invoice is saved."
text_invoice_many_vehicles: "These work orders are for more than one vehicle:" text_invoice_many_vehicles: "These work orders are for more than one vehicle:"
text_line_bills_time: "Bills a QuickBooks time activity; saving marks the time as billed" text_line_bills_time: "Bills a QuickBooks time activity; saving marks the time as billed"
text_replaceable_items: "Products/services that billable time can replace on invoices, e.g. Labor. Only invoice lines with these are offered under Replace these lines when time is imported. Leave empty to offer every line. Ctrl/Cmd-click to pick several." text_replaceable_items: "Products/services that billable time can replace on invoices, e.g. Labor. Only invoice lines with these are offered under Replace these lines when time is imported. Leave empty to offer every line. They are also the man-hours counted on estimates and invoices for the business report (run a full sync after changing them). Ctrl/Cmd-click to pick several."
text_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). The time goes where the first ticked line is." text_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). The time goes where the first ticked line is."
# Issues from estimates (moved from redmine_qbo_calendar) # Issues from estimates (moved from redmine_qbo_calendar)
@@ -311,6 +311,34 @@ en:
label_no_payments: "No payments from this customer in QuickBooks" label_no_payments: "No payments from this customer in QuickBooks"
label_payment_totals: "Total" label_payment_totals: "Total"
permission_view_payments: "View payments" permission_view_payments: "View payments"
# ---- Business report ----
permission_view_business_reports: "View business reports"
label_business_report: "Business report"
label_report_period: "Period"
label_report_period_this_month: "This month"
label_report_period_last_month: "Last month"
label_report_period_this_quarter: "This quarter"
label_report_period_last_quarter: "Last quarter"
label_report_period_this_year: "This year"
label_report_period_last_year: "Last year"
label_report_period_custom: "Custom dates"
label_report_money: "Sales"
label_report_hours: "Hours"
label_report_by_month: "By month"
label_report_estimates_written: "Estimates written"
label_report_invoices_written: "Invoices written"
label_report_payments_received: "Payments received"
label_report_estimate_hours: "Estimated (estimates)"
label_report_issue_hours: "Estimated (issues)"
label_report_invoice_hours: "Invoiced (invoices)"
label_report_spent_hours: "Spent (issues)"
label_report_invoiced_of_estimated: "Invoiced vs. estimated"
label_report_collected_of_invoiced: "Collected vs. invoiced"
label_report_open_balance: "Still owed on these invoices"
label_report_invoiced_of_spent: "Invoiced vs. spent hours"
label_report_spent_of_estimated: "Spent vs. issues' estimated hours"
text_report_needs_sync: "%{count} estimates or invoices in this period don't have their total or hours yet. Run a full sync from QuickBooks to fill them in."
text_report_notes: "Estimates, invoices and payments count by their QuickBooks date; their hours are the quantities of the products/services set as \"Replaced by imported time\" (or the estimate item codes while that's blank). Issues' estimated time counts issues created in the period, without subtasks. Spent time counts time logged in the period."
notice_payment_not_found: "Payment not found in QuickBooks" notice_payment_not_found: "Payment not found in QuickBooks"
notice_payment_saved: "Payment of %{amount} saved in QuickBooks" notice_payment_saved: "Payment of %{amount} saved in QuickBooks"
text_no_payment_methods: "QuickBooks' payment methods couldn't be read. Check the QuickBooks connection." text_no_payment_methods: "QuickBooks' payment methods couldn't be read. Check the QuickBooks connection."
+3
View File
@@ -93,3 +93,6 @@ resources :accounts do
get :sync get :sync
end end
end end
# Business report (estimates, invoices, payments and hours for a period)
get 'qbo_reports', to: 'qbo_reports#index', as: :qbo_reports
@@ -0,0 +1,30 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Cached report figures: each estimate's total, and the man-hours on estimates and invoices (quantities of the
# products/services set as "Replaced by imported time"). Filled in by the sync and the webhook.
class AddEstimateTotalsAndHours < ActiveRecord::Migration[7.0]
def up
add_column :estimates, :total_amount, :decimal, precision: 15, scale: 2 unless column_exists?(:estimates, :total_amount)
add_column :estimates, :hours, :float unless column_exists?(:estimates, :hours)
add_column :invoices, :hours, :float unless column_exists?(:invoices, :hours)
add_index :estimates, :txn_date unless index_exists?(:estimates, :txn_date)
add_index :invoices, :txn_date unless index_exists?(:invoices, :txn_date)
end
def down
remove_index :invoices, :txn_date if index_exists?(:invoices, :txn_date)
remove_index :estimates, :txn_date if index_exists?(:estimates, :txn_date)
remove_column :invoices, :hours if column_exists?(:invoices, :hours)
remove_column :estimates, :hours if column_exists?(:estimates, :hours)
remove_column :estimates, :total_amount if column_exists?(:estimates, :total_amount)
end
end
+31
View File
@@ -0,0 +1,31 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Customer payments cached from QuickBooks (id, customer, date and amount) for reporting
class CreatePayments < ActiveRecord::Migration[7.0]
def up
return if table_exists?(:payments)
create_table :payments do |t|
t.references :customer, index: true
t.date :txn_date
t.decimal :total_amount, precision: 15, scale: 2
t.decimal :unapplied_amount, precision: 15, scale: 2
t.datetime :qbo_updated_at
t.timestamps null: true
end
add_index :payments, :txn_date
end
def down
drop_table :payments if table_exists?(:payments)
end
end
+3
View File
@@ -52,10 +52,13 @@ Redmine::Plugin.register :redmine_qbo do
permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :pdf, :open_invoices], permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :pdf, :open_invoices],
qbo_estimates: [:customer_info] }, global: true qbo_estimates: [:customer_info] }, global: true
permission :view_business_reports, { qbo_reports: [:index] }, global: true
# The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController) # The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController)
# Register top menu items # Register top menu items
menu :top_menu, :customers, { controller: :customers, action: :index }, caption: :label_customers, if: Proc.new {User.current.allowed_to?(:view_customers, nil, global: true)} menu :top_menu, :customers, { controller: :customers, action: :index }, caption: :label_customers, if: Proc.new {User.current.allowed_to?(:view_customers, nil, global: true)}
menu :top_menu, :qbo_reports, { controller: :qbo_reports, action: :index }, caption: :label_business_report,
after: :customers, if: Proc.new { User.current.allowed_to?(:view_business_reports, nil, global: true) }
Redmine::Search.map do |search| Redmine::Search.map do |search|
search.register :customers search.register :customers
+163
View File
@@ -0,0 +1,163 @@
#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 RedmineQboBilling
# Business figures for a date range, from the estimates, invoices and payments cached from QuickBooks and from
# Redmine's issues and spent time:
# money: estimates written, invoices written, payments received (totals and counts)
# hours: man-hours on estimates, issues' estimated time, man-hours invoiced, time spent
# with a month-by-month breakdown. Estimates, invoices and payments count by their QuickBooks date, issues by
# the day they were created (only issues without subtasks, so parents' totals aren't counted twice), and
# spent time by the day it was spent.
class BusinessReport
PERIODS = %w[this_month last_month this_quarter last_quarter this_year last_year custom].freeze
MONEY = %i[estimates invoices payments].freeze
HOURS = %i[estimate_hours issue_hours invoice_hours spent_hours].freeze
attr_reader :from, :to, :period
# The dates for a period, from today: [from, to]. "custom" uses the given dates (either can be blank).
def self.range_for(period, today: Date.current, from: nil, to: nil)
case period.to_s
when 'this_month' then [today.beginning_of_month, today.end_of_month]
when 'last_month' then m = today.prev_month; [m.beginning_of_month, m.end_of_month]
when 'this_quarter' then [today.beginning_of_quarter, today.end_of_quarter]
when 'last_quarter' then q = today.beginning_of_quarter.prev_month; [q.beginning_of_quarter, q.end_of_quarter]
when 'last_year' then y = today.prev_year; [y.beginning_of_year, y.end_of_year]
when 'custom'
f = parse_date(from) || today.beginning_of_year
t = parse_date(to) || today
f > t ? [t, f] : [f, t]
else [today.beginning_of_year, today.end_of_year]
end
end
def self.parse_date(value)
return value if value.is_a?(Date)
Date.iso8601(value.to_s) if value.present?
rescue ArgumentError
nil
end
# data (for tests): { estimates: [[date, total, hours]], invoices: [[date, total, hours, balance]],
# payments: [[date, total]], issues: [[date, estimated_hours]], time_entries: [[date, hours]] }
def initialize(period: 'this_year', from: nil, to: nil, today: Date.current, data: nil)
@period = PERIODS.include?(period.to_s) ? period.to_s : 'this_year'
@from, @to = self.class.range_for(@period, today: today, from: from, to: to)
@today = today
@data = data
end
def data
@data ||= load_data
end
# { estimates: { total:, count: }, invoices: { total:, count:, balance: }, payments: { total:, count: } }
def money
@money ||= {
estimates: { total: money_sum(data[:estimates], 1), count: data[:estimates].size },
invoices: { total: money_sum(data[:invoices], 1), count: data[:invoices].size, balance: money_sum(data[:invoices], 3) },
payments: { total: money_sum(data[:payments], 1), count: data[:payments].size }
}
end
# { estimate_hours:, issue_hours:, invoice_hours:, spent_hours: }
def hours
@hours ||= {
estimate_hours: hour_sum(data[:estimates], 2),
issue_hours: hour_sum(data[:issues], 1),
invoice_hours: hour_sum(data[:invoices], 2),
spent_hours: hour_sum(data[:time_entries], 1)
}
end
# Percentages comparing the figures (nil when there's nothing to compare against)
def ratios
{
invoiced_of_estimated: percent(money[:invoices][:total], money[:estimates][:total]),
collected_of_invoiced: percent(money[:payments][:total], money[:invoices][:total]),
invoiced_of_spent: percent(hours[:invoice_hours], hours[:spent_hours]),
spent_of_estimated: percent(hours[:spent_hours], hours[:issue_hours])
}
end
# One row per month in the range, up to the current month: { month: Date (1st), estimates:, invoices:,
# payments:, estimate_hours:, issue_hours:, invoice_hours:, spent_hours: }
def months
@months ||= begin
rows = []
month = from.beginning_of_month
last = [to, @today].min
last = from if last < from
while month <= last
rows << { month: month }.merge((MONEY + HOURS).index_with { |_| 0 })
month = month.next_month
end
index = rows.index_by { |r| [r[:month].year, r[:month].month] }
add = lambda do |list, key, col, kind|
list.each do |row|
r = index[[row[0].year, row[0].month]] or next
r[key] += kind == :money ? to_d(row[col]) : row[col].to_f
end
end
add.call(data[:estimates], :estimates, 1, :money)
add.call(data[:invoices], :invoices, 1, :money)
add.call(data[:payments], :payments, 1, :money)
add.call(data[:estimates], :estimate_hours, 2, :hours)
add.call(data[:issues], :issue_hours, 1, :hours)
add.call(data[:invoices], :invoice_hours, 2, :hours)
add.call(data[:time_entries], :spent_hours, 1, :hours)
rows
end
end
# Estimates and invoices in the range that synced before totals and hours were cached (a full sync fills them)
def unsynced_count
data[:estimates].count { |r| r[1].nil? || r[2].nil? } + data[:invoices].count { |r| r[1].nil? || r[2].nil? }
end
private
def load_data
dates = from..to
times = from.in_time_zone.beginning_of_day..to.in_time_zone.end_of_day
leaf = "#{Issue.table_name}.rgt IS NULL OR #{Issue.table_name}.rgt - #{Issue.table_name}.lft = 1"
{
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours),
invoices: Invoice.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :balance),
payments: Payment.where(txn_date: dates).pluck(:txn_date, :total_amount),
issues: Issue.where(created_on: times).where(leaf).where.not(estimated_hours: nil)
.pluck(:created_on, :estimated_hours).map { |t, h| [t.in_time_zone.to_date, h] },
time_entries: TimeEntry.where(spent_on: dates).pluck(:spent_on, :hours)
}
end
def money_sum(rows, col)
rows.sum(BigDecimal('0')) { |r| to_d(r[col]) }
end
def hour_sum(rows, col)
rows.sum(0.0) { |r| r[col].to_f }.round(2)
end
def to_d(value)
BigDecimal(value.to_s.presence || '0')
rescue ArgumentError
BigDecimal('0')
end
def percent(part, whole)
whole = whole.to_f
return nil if whole <= 0
(part.to_f / whole * 100).round
end
end
end
+49
View File
@@ -0,0 +1,49 @@
#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 RedmineQboBilling
# The man-hours on a QuickBooks estimate or invoice: the quantities of its lines whose product/service is set
# as "Replaced by imported time" (e.g. Labor), including lines inside bundles. While that setting is blank,
# lines matching the estimate item codes are counted instead (counting every line would include parts).
module ManHours
module_function
def hours(document, item_ids: InvoiceWriter.replaceable_item_ids, codes: nil)
return 0.0 if document.nil?
ids = Array(item_ids).map(&:to_s).reject(&:blank?)
codes ||= EstimateIssueBuilder.item_codes if ids.empty?
sum_lines(document.line_items, ids, codes).round(2)
end
def sum_lines(lines, ids, codes)
Array(lines).sum do |line|
group = line.respond_to?(:group_line_detail) ? line.group_line_detail : nil
next sum_lines(group.line_items, ids, codes) if group
detail = sales_detail(line)
next 0.0 unless detail&.item_ref && man_hour_item?(detail.item_ref, ids, codes)
detail.quantity.to_f
end
end
def sales_detail(line)
if line.respond_to?(:sales_line_item_detail) then line.sales_line_item_detail
elsif line.respond_to?(:sales_item_line_detail) then line.sales_item_line_detail
end
end
def man_hour_item?(ref, ids, codes)
return ids.include?(ref.value.to_s) if ids.any?
EstimateIssueBuilder.item_matches?(ref.name, codes)
end
end
end
+8 -1
View File
@@ -100,8 +100,9 @@ module RedmineQboBilling
saved = with_service('Payment') { |service| service.create(payment) } saved = with_service('Payment') { |service| service.create(payment) }
raise Error, I18n.t(:error_payment_not_saved) unless saved raise Error, I18n.t(:error_payment_not_saved) unless saved
# Invoice balances changed: update the local invoices # Invoice balances changed: update the local invoices, and cache the payment for reports
applied.each { |invoice, _| sync_invoice(invoice[:id]) } applied.each { |invoice, _| sync_invoice(invoice[:id]) }
sync_payment(saved.id)
saved saved
end end
@@ -149,6 +150,12 @@ module RedmineQboBilling
QboConnectionService.with_qbo_service(entity: entity, &block) QboConnectionService.with_qbo_service(entity: entity, &block)
end end
def sync_payment(id)
PaymentSyncService.new.sync_by_id(id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not cache payment #{id}: #{e.message}"
end
def sync_invoice(id) def sync_invoice(id)
InvoiceSyncService.new.sync_by_id(id) InvoiceSyncService.new.sync_by_id(id)
rescue StandardError => e rescue StandardError => e