diff --git a/README.md b/README.md index 18e336a..2b95fe1 100644 --- a/README.md +++ b/README.md @@ -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. +### 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 @@ -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. * **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 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") * **View payments**: a customer's Payments list, the payment page and its PDF * **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 * **Email invoices**: email invoices to customers diff --git a/app/controllers/qbo_reports_controller.rb b/app/controllers/qbo_reports_controller.rb new file mode 100644 index 0000000..15641f7 --- /dev/null +++ b/app/controllers/qbo_reports_controller.rb @@ -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 diff --git a/app/jobs/qbo_sync_dispatcher.rb b/app/jobs/qbo_sync_dispatcher.rb index d488ab6..4152c57 100644 --- a/app/jobs/qbo_sync_dispatcher.rb +++ b/app/jobs/qbo_sync_dispatcher.rb @@ -14,7 +14,8 @@ class QboSyncDispatcher Customer, Estimate, Invoice, - Employee + Employee, + Payment ].freeze # Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database. @@ -27,7 +28,7 @@ class QboSyncDispatcher private # Dynamically enques all sync jobs - def self.enque_jobs(full_sync: full_sync) + def self.enque_jobs(full_sync: false) jobs = SYNC_JOBS.dup # Allow other plugins to add addtional sync jobs via Hooks diff --git a/app/jobs/webhook_process_job.rb b/app/jobs/webhook_process_job.rb index 283090b..d99aeef 100644 --- a/app/jobs/webhook_process_job.rb +++ b/app/jobs/webhook_process_job.rb @@ -17,6 +17,7 @@ class WebhookProcessJob < ActiveJob::Base Invoice Estimate Employee + Payment ].freeze # Process incoming QBO webhook notifications and sync relevant data to Redmine diff --git a/app/models/customer.rb b/app/models/customer.rb index 5fa260f..a9c0cb4 100644 --- a/app/models/customer.rb +++ b/app/models/customer.rb @@ -16,6 +16,7 @@ class Customer < QboBaseModel has_many :issues has_many :invoices has_many :estimates + has_many :payments validates_presence_of :name before_validation :normalize_phone_numbers self.primary_key = :id diff --git a/app/models/payment.rb b/app/models/payment.rb new file mode 100644 index 0000000..bbee059 --- /dev/null +++ b/app/models/payment.rb @@ -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 diff --git a/app/services/estimate_sync_service.rb b/app/services/estimate_sync_service.rb index be8448c..8c06c79 100644 --- a/app/services/estimate_sync_service.rb +++ b/app/services/estimate_sync_service.rb @@ -26,6 +26,9 @@ class EstimateSyncService < SyncServiceBase end 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 end \ No newline at end of file diff --git a/app/services/invoice_sync_service.rb b/app/services/invoice_sync_service.rb index 5b86c5a..0f31ee6 100644 --- a/app/services/invoice_sync_service.rb +++ b/app/services/invoice_sync_service.rb @@ -24,6 +24,8 @@ class InvoiceSyncService < SyncServiceBase map_attributes :balance, :doc_number, :due_date, :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_attribute :qbo_updated_at, "meta_data.last_updated_time" map_belongs_to :customer diff --git a/app/services/payment_service.rb b/app/services/payment_service.rb new file mode 100644 index 0000000..e68a7ce --- /dev/null +++ b/app/services/payment_service.rb @@ -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 diff --git a/app/services/payment_sync_service.rb b/app/services/payment_sync_service.rb new file mode 100644 index 0000000..47ee6af --- /dev/null +++ b/app/services/payment_sync_service.rb @@ -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 diff --git a/app/services/pdf_service.rb b/app/services/pdf_service.rb index 33b98c7..249ac83 100644 --- a/app/services/pdf_service.rb +++ b/app/services/pdf_service.rb @@ -12,7 +12,7 @@ class PdfService require 'combine_pdf' # Subclasses should initialize with a QBO client instance - def initialize(entity: entity) + def initialize(entity:) raise "An entity to sync is required" unless entity @entity = entity end diff --git a/app/views/qbo_reports/index.html.erb b/app/views/qbo_reports/index.html.erb new file mode 100644 index 0000000..2f2dcda --- /dev/null +++ b/app/views/qbo_reports/index.html.erb @@ -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}%" } %> + +

<%= l(:label_business_report) %>

+ +<%= form_tag qbo_reports_path, method: :get, id: 'qbo-report-form' do %> +
+ <%= l(:label_report_period) %> + <%= select_tag 'period', + options_for_select(RedmineQboBilling::BusinessReport::PERIODS.map { |p| [l("label_report_period_#{p}"), p] }, @report.period), + id: 'qbo-report-period' %> + + <%= date_field_tag 'from', @report.from.iso8601, id: 'qbo-report-from' %> + – + <%= date_field_tag 'to', @report.to.iso8601, id: 'qbo-report-to' %> + + <%= submit_tag l(:button_apply), name: nil %> +
+<% end %> + +

<%= format_date(@report.from) %> – <%= format_date(@report.to) %>

+ +<% if @report.unsynced_count > 0 %> +

<%= l(:text_report_needs_sync, count: @report.unsynced_count) %>

+<% end %> + +
+
+

<%= l(:label_report_money) %>

+ + + <% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)], + [:payments, l(:label_report_payments_received)]].each do |key, label| %> + + + + + + <% end %> + +
<%= label %> (<%= money[key][:count] %>)
<%= number_to_currency(money[key][:total]) %>
+

+ <%= l(:label_report_invoiced_of_estimated) %>: <%= pct.call(ratios[:invoiced_of_estimated]) %>
+ <%= l(:label_report_collected_of_invoiced) %>: <%= pct.call(ratios[:collected_of_invoiced]) %>
+ <%= l(:label_report_open_balance) %>: <%= number_to_currency(money[:invoices][:balance]) %> +

+
+ +
+

<%= l(:label_report_hours) %>

+ + + <% [[: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| %> + + + + + + <% end %> + +
<%= label %>
<%= fmt_hours.call(hours[key]) %>
+

+ <%= l(:label_report_invoiced_of_spent) %>: <%= pct.call(ratios[:invoiced_of_spent]) %>
+ <%= l(:label_report_spent_of_estimated) %>: <%= pct.call(ratios[:spent_of_estimated]) %> +

+
+
+ +

<%= l(:label_report_by_month) %>

+
+ + + + + + + + + + + + + + + <% @report.months.each do |row| %> + + + + + + + + + + + <% end %> + + + + + + + + + + + + + +
<%= l(:label_month) %><%= l(:label_report_estimates_written) %><%= l(:label_report_invoices_written) %><%= l(:label_report_payments_received) %><%= l(:label_report_estimate_hours) %><%= l(:label_report_issue_hours) %><%= l(:label_report_invoice_hours) %><%= l(:label_report_spent_hours) %>
<%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %><%= number_to_currency(row[:estimates]) %><%= number_to_currency(row[:invoices]) %><%= number_to_currency(row[:payments]) %><%= fmt_hours.call(row[:estimate_hours]) %><%= fmt_hours.call(row[:issue_hours]) %><%= fmt_hours.call(row[:invoice_hours]) %><%= fmt_hours.call(row[:spent_hours]) %>
<%= l(:label_total) %><%= number_to_currency(money[:estimates][:total]) %><%= number_to_currency(money[:invoices][:total]) %><%= number_to_currency(money[:payments][:total]) %><%= fmt_hours.call(hours[:estimate_hours]) %><%= fmt_hours.call(hours[:issue_hours]) %><%= fmt_hours.call(hours[:invoice_hours]) %><%= fmt_hours.call(hours[:spent_hours]) %>
+
+

<%= l(:text_report_notes) %>

+ + + +<%= 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 %> diff --git a/config/locales/en.yml b/config/locales/en.yml index b52180c..a771d93 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -262,7 +262,7 @@ en: 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_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." # Issues from estimates (moved from redmine_qbo_calendar) @@ -311,6 +311,34 @@ en: label_no_payments: "No payments from this customer in QuickBooks" label_payment_totals: "Total" 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_saved: "Payment of %{amount} saved in QuickBooks" text_no_payment_methods: "QuickBooks' payment methods couldn't be read. Check the QuickBooks connection." diff --git a/config/routes.rb b/config/routes.rb index 0ba7fbd..5546e1b 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -93,3 +93,6 @@ resources :accounts do get :sync end end + +# Business report (estimates, invoices, payments and hours for a period) +get 'qbo_reports', to: 'qbo_reports#index', as: :qbo_reports diff --git a/db/migrate/047_add_estimate_totals_and_hours.rb b/db/migrate/047_add_estimate_totals_and_hours.rb new file mode 100644 index 0000000..07628db --- /dev/null +++ b/db/migrate/047_add_estimate_totals_and_hours.rb @@ -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 diff --git a/db/migrate/048_create_payments.rb b/db/migrate/048_create_payments.rb new file mode 100644 index 0000000..028a86e --- /dev/null +++ b/db/migrate/048_create_payments.rb @@ -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 diff --git a/init.rb b/init.rb index 1be73e6..3d662c0 100644 --- a/init.rb +++ b/init.rb @@ -52,10 +52,13 @@ Redmine::Plugin.register :redmine_qbo do permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :pdf, :open_invoices], 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) # 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, :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| search.register :customers diff --git a/lib/redmine_qbo_billing/business_report.rb b/lib/redmine_qbo_billing/business_report.rb new file mode 100644 index 0000000..567aab9 --- /dev/null +++ b/lib/redmine_qbo_billing/business_report.rb @@ -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 diff --git a/lib/redmine_qbo_billing/man_hours.rb b/lib/redmine_qbo_billing/man_hours.rb new file mode 100644 index 0000000..a4f500f --- /dev/null +++ b/lib/redmine_qbo_billing/man_hours.rb @@ -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 diff --git a/lib/redmine_qbo_billing/payment_writer.rb b/lib/redmine_qbo_billing/payment_writer.rb index 0367613..18ffb80 100644 --- a/lib/redmine_qbo_billing/payment_writer.rb +++ b/lib/redmine_qbo_billing/payment_writer.rb @@ -100,8 +100,9 @@ module RedmineQboBilling saved = with_service('Payment') { |service| service.create(payment) } 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]) } + sync_payment(saved.id) saved end @@ -149,6 +150,12 @@ module RedmineQboBilling QboConnectionService.with_qbo_service(entity: entity, &block) 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) InvoiceSyncService.new.sync_by_id(id) rescue StandardError => e