Compare commits

..
4 Commits
Author SHA1 Message Date
Claude 3304fce92f Make billed estimates read-only
An estimate that's Converted or Closed in QuickBooks, or linked to an invoice, opens read-only and is
refused on save (this includes redmine_qbo_lineitems' estimates once invoiced). Its page lists the
invoices it's on. Estimates cache their status so lists show View instead of Edit for them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 08:34:41 -04:00
Claude 4732c32409 Combine the labor settings into Labor products/services
The estimate item codes and "Replaced by imported time" become one list of products/services
(RedmineQboBilling::LaborItems), used to create issues from an estimate's labor lines (and an
appointment's minimum hours), to offer an invoice's labor lines to be replaced by imported time, and
to total the hours on estimates and invoices for the business report. While none are chosen,
products/services named Labor are used. The old settings and redmine_qbo_calendar's fallbacks are no
longer read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 08:22:32 -04:00
Claude 616ee13725 Tidy the plugin settings page
- Three sections: QuickBooks connection, Synchronization and Billing.
- Synchronization is one table of every synced type (customers, employees, estimates, invoices,
  payments, items, accounts) with its count, last sync and a Sync link, plus Sync changes and Full sync.
  The separate billing stats and management boxes are folded into it.
- New payments sync (admin only).
- Sync links return to the page they were clicked on instead of the home page.
- Remove locale strings nothing uses any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 08:11:27 -04:00
Claude 062ef9b8b3 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
2026-10-31 07:54:28 -04:00
41 changed files with 824 additions and 201 deletions

No files matched your search

+27 -5
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 labor products/services, including lines inside bundles). 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
@@ -101,7 +105,8 @@ Customer records are automatically updated in the local database when changes oc
* **Edit** any estimate from the Edit link next to it on the customer page or the issue page. * **Edit** any estimate from the Edit link next to it on the customer page or the issue page.
* **Duplicate** an estimate to start a similar one: same customer, lines, subtotals, VIN and messages, dated today, with the current user as sales person. * **Duplicate** an estimate to start a similar one: same customer, lines, subtotals, VIN and messages, dated today, with the current user as sales person.
* **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit. * **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit.
* **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line whose item matches an **estimate item code** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Opened from an appointment, the issues get the appointment's dates, technician and vehicle. * **Read-only once billed**: an estimate that's Converted or Closed in QuickBooks, or linked to an invoice, can't be changed here either (including redmine_qbo_lineitems' estimates once they're invoiced). Its page lists the invoices it's on; it can still be viewed, emailed and duplicated, and it shows View instead of Edit in lists.
* **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line with one of the **labor products/services** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Opened from an appointment, the issues get the appointment's dates, technician and vehicle.
* **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link. * **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link.
* The page follows QuickBooks' estimate screen: customer, customer email, billing address, estimate date, expiration date, estimate number, then the product/service lines (#, product/service, description, qty, rate, amount, tax), the message displayed on the estimate, the memo, and the totals. * The page follows QuickBooks' estimate screen: customer, customer email, billing address, estimate date, expiration date, estimate number, then the product/service lines (#, product/service, description, qty, rate, amount, tax), the message displayed on the estimate, the memo, and the totals.
* Lines work like QuickBooks: the product list opens when the box is clicked, picking a product fills in its description, rate and tax, typing an amount works out the rate, a spare empty line is always at the bottom, and lines are reordered by dragging them by the handle. * Lines work like QuickBooks: the product list opens when the box is clicked, picking a product fills in its description, rate and tax, typing an amount works out the rate, a spare empty line is always at the bottom, and lines are reordered by dragging them by the handle.
@@ -113,7 +118,7 @@ Customer records are automatically updated in the local database when changes oc
* **Create invoice** on an estimate's page makes an invoice from it (customer, lines, subtotals, VIN), like QuickBooks' "Create invoice". **Create invoice** on the customer page starts a blank one, and the Edit link next to each invoice on the customer page opens it. * **Create invoice** on an estimate's page makes an invoice from it (customer, lines, subtotals, VIN), like QuickBooks' "Create invoice". **Create invoice** on the customer page starts a blank one, and the Edit link next to each invoice on the customer page opens it.
* **Import time & estimates** lists the customer's billable QuickBooks time (the time activities redmine_qbo makes from an issue's time entries) and their open estimates (e.g. the ones redmine_qbo_lineitems makes for parts that weren't quoted). * **Import time & estimates** lists the customer's billable QuickBooks time (the time activities redmine_qbo makes from an issue's time entries) and their open estimates (e.g. the ones redmine_qbo_lineitems makes for parts that weren't quoted).
* Tick the time to bill and, under **Replace these lines**, the lines it replaces (e.g. the estimate's labor lines). When products/services are set as **Replaced by imported time** in the plugin settings, only lines with one of them are offered there; with none set, every line is. The time goes where the first ticked line was and the ticked lines are removed, so the invoice reads in the same order. * Tick the time to bill and, under **Replace these lines**, the lines it replaces (e.g. the estimate's labor lines). Only lines with one of the **labor products/services** from the plugin settings are offered there. The time goes where the first ticked line was and the ticked lines are removed, so the invoice reads in the same order.
* Ticked estimates go right after the time for the same issue: a redmine_qbo_lineitems estimate starting "Added from: Install #116: …" lands after the time for #116, without that note line, since the time line already names the issue. Estimates with no matching time keep the note and go at the end. * Ticked estimates go right after the time for the same issue: a redmine_qbo_lineitems estimate starting "Added from: Install #116: …" lands after the time for #116, without that note line, since the time line already names the issue. Estimates with no matching time keep the note and go at the end.
* **Undo import** puts the lines back until the invoice is saved. * **Undo import** puts the lines back until the invoice is saved.
* **An estimate is billed once**: an estimate that's on an invoice (linked to one, or closed) or was rejected can't be made into an invoice or imported, and its page shows the invoice it's billed on. This is checked against QuickBooks again when the invoice is saved, so an estimate invoiced meanwhile (in another tab, by someone else, or in QuickBooks) stops the save. * **An estimate is billed once**: an estimate that's on an invoice (linked to one, or closed) or was rejected can't be made into an invoice or imported, and its page shows the invoice it's billed on. This is checked against QuickBooks again when the invoice is saved, so an estimate invoiced meanwhile (in another tab, by someone else, or in QuickBooks) stops the save.
@@ -131,6 +136,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 the labor products/services.
### 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,14 +183,15 @@ 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
2. Settings (Administration -> Plugins -> Configure) 2. Settings (Administration -> Plugins -> Configure)
* **Estimates expire after (days)**: new estimates get an expiration date this many days after the estimate date (e.g. 30). Leave blank for none. * **Estimates expire after (days)**: new estimates get an expiration date this many days after the estimate date (e.g. 30). Leave blank for none.
* **Issues from estimates**: the estimate item codes (also an estimate's labor hours, which an appointment's hours can't be less than), the default project and the default tracker. Until saved here, redmine_qbo_calendar's old values are used. * **Labor products/services** (e.g. Labor): one list used three ways. An estimate's lines with them can become issues (their quantities are also the estimate's labor hours, which an appointment's hours can't be less than); an invoice's lines with them are offered under Replace these lines when time is imported; and their quantities are the hours on estimates and invoices in the business report. While none are chosen, products/services named Labor are used.
* **Replaced by imported time**: the products/services (e.g. Labor) whose invoice lines time can replace. Only those lines are offered under Replace these lines; leave empty to offer every line. * **Issues from estimates**: the default project and the default tracker.
* Item and account counts, the default income account, and Sync Items / Sync Accounts. * Item and account counts, the default income account and their syncs are under Synchronization.
3. Writing an estimate 3. Writing an estimate
@@ -293,6 +309,12 @@ Administration → Plugins → Configure
Once authentication succeeds, the plugin performs an **initial synchronization**. Once authentication succeeds, the plugin performs an **initial synchronization**.
The settings page has three sections:
* **QuickBooks connection**: client ID and secret, webhook token, sandbox, when the access token expires, and Connect to QuickBooks.
* **Synchronization**: customers, employees, estimates, invoices, payments, products/services (items) and accounts, with how many of each are stored, when each last synced and a **Sync** link for each (it re-reads every record of that type). **Sync changes** reads only what changed since the last sync; **Full sync** re-reads everything. The default income account for new products/services is shown here too.
* **Billing**: estimate expiration, the labor products/services and the issues-from-estimates defaults.
--- ---
# User Mapping # User Mapping
+1 -1
View File
@@ -32,6 +32,6 @@ class AccountsController < ApplicationController
def sync def sync
Account.sync Account.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
end end
+1 -1
View File
@@ -213,7 +213,7 @@ class CustomersController < ApplicationController
def sync def sync
Customer.sync Customer.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
def update def update
+1 -1
View File
@@ -15,7 +15,7 @@ class EmployeesController < ApplicationController
def sync def sync
Employee.sync Employee.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
private private
+1 -1
View File
@@ -31,7 +31,7 @@ class EstimatesController < ApplicationController
def sync def sync
Estimate.sync Estimate.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
private private
+1 -1
View File
@@ -34,7 +34,7 @@ class InvoicesController < ApplicationController
def sync def sync
Invoice.sync Invoice.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
private private
+1 -1
View File
@@ -76,7 +76,7 @@ class ItemsController < ApplicationController
def sync def sync
Item.sync Item.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
def update def update
+1 -1
View File
@@ -70,7 +70,7 @@ class QboController < ApplicationController
full_sync = ActiveModel::Type::Boolean.new.cast(params[:full_sync]) full_sync = ActiveModel::Type::Boolean.new.cast(params[:full_sync])
QboSyncDispatcher.sync!(full_sync: full_sync) QboSyncDispatcher.sync!(full_sync: full_sync)
redirect_to :home, flash: { notice: I18n.t(:label_syncing) } redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end end
# Endpoint to receive QuickBooks webhook notifications. Validates the request and processes the payload to sync relevant data to Redmine. Responds with appropriate HTTP status codes based on success or failure of processing. # Endpoint to receive QuickBooks webhook notifications. Validates the request and processes the payload to sync relevant data to Redmine. Responds with appropriate HTTP status codes based on success or failure of processing.
+8 -1
View File
@@ -13,10 +13,17 @@
# listed on their payments page. # listed on their payments page.
class QboPaymentsController < ApplicationController class QboPaymentsController < ApplicationController
before_action :authorize_global before_action :authorize_global, except: :sync
before_action :require_admin, only: :sync
QBO_ERRORS = QboEstimatesController::QBO_ERRORS QBO_ERRORS = QboEstimatesController::QBO_ERRORS
# Re-reads every payment from QuickBooks into the local cache (admin, from the plugin settings)
def sync
Payment.sync
redirect_back fallback_location: home_path, flash: { notice: I18n.t(:label_syncing) }
end
# The customer's payments, newest first, read from QuickBooks # The customer's payments, newest first, read from QuickBooks
def index def index
@customer = Customer.find_by(id: params[:customer_id]) @customer = Customer.find_by(id: params[:customer_id])
+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
+6
View File
@@ -20,6 +20,12 @@ class Estimate < QboBaseModel
to_s to_s
end end
# True once QuickBooks has turned it into an invoice (status cached by the sync). The estimate page also
# checks for a linked invoice; either way a billed estimate can't be changed in Redmine.
def billed?
RedmineQboBilling::EstimateWriter::BILLED_STATUSES.include?(self[:txn_status].to_s)
end
# returns a human readable string # returns a human readable string
def to_s def to_s
return self[:doc_number] return self[:doc_number]
+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
+4
View File
@@ -26,6 +26,10 @@ class EstimateSyncService < SyncServiceBase
end end
map_attributes :doc_number, :txn_date map_attributes :doc_number, :txn_date
map_attribute :total_amount, :total
map_attribute :txn_status
# Man-hours: quantities of the labor products/services (plugin settings)
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 labor products/services (plugin settings)
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
+8 -53
View File
@@ -5,26 +5,22 @@
min: 0, step: 1, size: 6 %> min: 0, step: 1, size: 6 %>
<em class="info"><%= l(:text_estimate_expiration_days) %></em> <em class="info"><%= l(:text_estimate_expiration_days) %></em>
</p> </p>
<%# Labor: issues from estimates, lines imported time replaces on invoices, and hours for the business report.
While none are chosen, items named "Labor" are used and shown selected. %>
<p> <p>
<label for="settings_replaceable_item_ids"><%= l(:label_replaceable_items) %></label> <label for="settings_labor_item_ids"><%= l(:label_labor_items) %></label>
<%= hidden_field_tag 'settings[replaceable_item_ids][]', '', id: nil %> <%= hidden_field_tag 'settings[labor_item_ids][]', '', id: nil %>
<%= select_tag 'settings[replaceable_item_ids][]', <%= select_tag 'settings[labor_item_ids][]',
options_from_collection_for_select(Item.where(active: true).order(:name), :id, :name, options_from_collection_for_select(Item.where(active: true).order(:name), :id, :name,
Array(@settings['replaceable_item_ids']).map(&:to_s)), RedmineQboBilling::LaborItems.item_ids),
multiple: true, size: 8, id: 'settings_replaceable_item_ids' %> multiple: true, size: 8, id: 'settings_labor_item_ids' %>
<em class="info"><%= l(:text_replaceable_items) %></em> <em class="info"><%= l(:text_labor_items) %></em>
</p> </p>
</div> </div>
<%# Issues from estimates (moved from redmine_qbo_calendar; its old values are shown until these are saved) %>
<% issue_builder = RedmineQboBilling::EstimateIssueBuilder %> <% issue_builder = RedmineQboBilling::EstimateIssueBuilder %>
<fieldset class="box tabular"> <fieldset class="box tabular">
<legend><%= l(:label_estimate_issue_settings) %></legend> <legend><%= l(:label_estimate_issue_settings) %></legend>
<p>
<label for="settings_issue_item_codes"><%= l(:label_estimate_item_codes) %></label>
<%= text_area_tag 'settings[issue_item_codes]', issue_builder.item_codes.join("\n"), rows: 5, cols: 30, id: 'settings_issue_item_codes' %>
<em class="info"><%= l(:text_estimate_item_codes_info) %></em>
</p>
<p> <p>
<label for="settings_issue_default_project_id"><%= l(:label_default_project) %></label> <label for="settings_issue_default_project_id"><%= l(:label_default_project) %></label>
<%= select_tag 'settings[issue_default_project_id]', <%= select_tag 'settings[issue_default_project_id]',
@@ -40,44 +36,3 @@
<em class="info"><%= l(:text_default_tracker_info) %></em> <em class="info"><%= l(:text_default_tracker_info) %></em>
</p> </p>
</fieldset> </fieldset>
<%# QuickBooks product/service list and income accounts (moved from redmine_qbo_lineitems) %>
<div class="box tabular">
<p>
<label><strong><%= t(:label_item_count) %></strong></label>
<%= Item.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">
(@ <%= Item.last_sync %>)
</em>
</p>
<p>
<label><strong><%= t(:label_account_count) %></strong></label>
<%= Account.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">
(@ <%= Account.last_sync %>)
</em>
</p>
<p>
<label><strong><%= t(:label_last_sync) %> (QBO)</strong></label>
<%= Qbo.exists? ? Qbo.last_sync : l(:label_never_synced) %>
</p>
<p>
<label><strong><%= t(:label_default_account) %></strong></label>
<%= Account.get_default %>
</p>
</div>
<fieldset class="box">
<legend><%= l(:label_management_and_sync) %></legend>
<div style="margin-bottom: 15px;">
<%= link_to t(:label_sync_now_items), sync_items_path, class: 'button icon icon-reload' %>
<%= link_to t(:label_sync_now_accounts), sync_accounts_path, class: 'button icon icon-reload' %>
</div>
<div>
<%= link_to t(:label_items), items_path, class: 'icon icon-list' %>
<span style="margin: 0 10px; color: #ccc;">|</span>
<%= link_to t(:label_accounts), accounts_path, class: 'icon icon-list' %>
</div>
</fieldset>
+60 -48
View File
@@ -3,81 +3,93 @@
intuit.ipp.anywhere.setup({menuProxy: '/path/to/blue-dot', grantUrl: '<%= qbo_authenticate_path %>'}); intuit.ipp.anywhere.setup({menuProxy: '/path/to/blue-dot', grantUrl: '<%= qbo_authenticate_path %>'});
</script> </script>
<%# QuickBooks connection: app keys, webhook token, sandbox, and the OAuth connection %>
<h3><%= l(:label_qbo_connection) %></h3>
<div class="box tabular"> <div class="box tabular">
<p> <p>
<label><%= t(:label_client_id) %></label> <label><%= t(:label_client_id) %></label>
<%= text_field_tag 'settings[oauth_consumer_key]', settings[:oauth_consumer_key], size: 50 %> <%= text_field_tag 'settings[oauth_consumer_key]', settings[:oauth_consumer_key], size: 50 %>
</p> </p>
<p> <p>
<label><%= t(:label_client_secret) %></label> <label><%= t(:label_client_secret) %></label>
<%= password_field_tag 'settings[oauth_consumer_secret]', settings[:oauth_consumer_secret], size: 50 %> <%= password_field_tag 'settings[oauth_consumer_secret]', settings[:oauth_consumer_secret], size: 50 %>
</p> </p>
<p> <p>
<label><%= t(:label_webhook_token) %></label> <label><%= t(:label_webhook_token) %></label>
<%= text_field_tag 'settings[webhook_token]', settings[:webhook_token], size: 50 %> <%= text_field_tag 'settings[webhook_token]', settings[:webhook_token], size: 50 %>
</p> </p>
<p> <p>
<label><%= t(:label_sandbox) %></label> <label><%= t(:label_sandbox) %></label>
<%= check_box_tag 'settings[sandbox]', 1, settings[:sandbox] %> <%= check_box_tag 'settings[sandbox]', 1, settings[:sandbox] %>
</p> </p>
<hr />
<p> <p>
<label><%= t(:label_oauth_expires) %></label> <label><%= t(:label_oauth_expires) %></label>
<span class="icon <%= Qbo.oauth2_access_token_expires_at&.future? ? 'icon-ok' : 'icon-warning' %>"> <span class="icon <%= Qbo.oauth2_access_token_expires_at&.future? ? 'icon-ok' : 'icon-warning' %>">
<%= Qbo.oauth2_access_token_expires_at || 'N/A' %> <%= Qbo.oauth2_access_token_expires_at ? format_time(Qbo.oauth2_access_token_expires_at) : 'N/A' %>
</span> </span>
</p> </p>
<p> <p>
<label><%= t(:label_customer_count) %></label> <label></label>
<%= Customer.count %> <ipp:connectToIntuit></ipp:connectToIntuit>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Customer.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_employee_count) %></label>
<%= Employee.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Employee.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_invoice_count) %></label>
<%= Invoice.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Invoice.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_estimate_count) %></label>
<%= Estimate.count %>
<em style="color: #777; font-size: 0.9em; margin-left: 8px;">(@ <%= Estimate.last_sync %>)</em>
</p>
<p>
<label><%= t(:label_last_sync) %> (QBO)</label>
<%= Qbo.exists? ? Qbo.last_sync : 'Never synced' %>
</p> </p>
</div> </div>
<fieldset class="box"> <%# Everything kept in step with QuickBooks: how many records there are, when each last changed, and a sync
<legend>Management & Synchronization</legend> button for each. A type's sync re-reads all of its records from QuickBooks. %>
<% sync_rows = [
<div style="margin-bottom: 20px;"> [l(:label_customers), Customer, sync_customers_path, customers_path],
<ipp:connectToIntuit></ipp:connectToIntuit> [l(:label_employee_plural), Employee, employees_sync_path, nil],
</div> [l(:label_estimates), Estimate, estimates_sync_path, nil],
[l(:label_invoices), Invoice, invoices_sync_path, nil],
[l(:label_payments), Payment, sync_qbo_payments_path, nil],
[l(:label_items), Item, sync_items_path, items_path],
[l(:label_accounts), Account, sync_accounts_path, accounts_path]
] %>
<h3><%= l(:label_management_and_sync) %></h3>
<div class="box">
<table class="list qbo-sync-table">
<thead>
<tr>
<th class="name"></th>
<th class="count"><%= l(:label_qbo_records) %></th>
<th class="updated"><%= l(:label_last_sync) %></th>
<th class="buttons"></th>
</tr>
</thead>
<tbody>
<% sync_rows.each do |label, model, sync_path, list_path| %>
<tr>
<td class="name"><%= list_path ? link_to(label, list_path) : label %></td>
<td class="count"><%= model.count %></td>
<td class="updated"><%= model.last_sync %></td>
<td class="buttons"><%= link_to sprite_icon('reload', l(:label_sync)), sync_path, class: 'icon icon-reload' %></td>
</tr>
<% end %>
</tbody>
</table>
<div style="margin-bottom: 15px;"> <p class="qbo-sync-default-account">
<%= link_to t(:label_sync_now_customers), sync_customers_path, class: 'button icon icon-reload' %> <strong><%= t(:label_default_account) %>:</strong> <%= Account.get_default || '–' %>
<%= link_to t(:label_sync_now_employees), employees_sync_path, class: 'button icon icon-reload' %> <em class="info"><%= l(:text_default_account_info) %></em>
<%= link_to t(:label_sync_now_invoices), invoices_sync_path, class: 'button icon icon-reload' %> </p>
<%= link_to t(:label_sync_now_estimate), estimates_sync_path, class: 'button icon icon-reload' %>
</div>
</fieldset>
<%# Billing: estimates, issues from estimates, invoices, the product/service list and accounts %> <p class="qbo-sync-all">
<strong><%= t(:label_last_sync) %> (QBO):</strong> <%= Qbo.exists? ? Qbo.last_sync : l(:label_never_synced) %>
<%= link_to sprite_icon('reload', l(:label_sync_changes)), qbo_sync_path, class: 'button icon icon-reload' %>
<%= link_to sprite_icon('reload', l(:label_full_sync)), qbo_sync_path(full_sync: true), class: 'button icon icon-reload' %>
</p>
<em class="info"><%= l(:text_qbo_sync_info) %></em>
</div>
<style>
table.qbo-sync-table { margin-bottom: 10px; }
table.qbo-sync-table td.name, table.qbo-sync-table th.name { text-align: left; }
table.qbo-sync-table td.count { text-align: right; width: 8em; }
table.qbo-sync-table td.updated { width: 14em; }
table.qbo-sync-table td.buttons { width: 6em; }
.qbo-sync-all .button { margin-left: 8px; }
</style>
<%# Billing: estimates, issues from estimates and invoices %>
<h3><%= l(:label_billing_settings) %></h3> <h3><%= l(:label_billing_settings) %></h3>
<%= render partial: 'qbo/billing_settings', locals: { settings: settings } %> <%= render partial: 'qbo/billing_settings', locals: { settings: settings } %>
@@ -1,5 +1,5 @@
<%# Estimates linked to an issue are read-only here, so they get a View link instead of Edit %> <%# Billed estimates and estimates linked to an issue are read-only here, so they get a View link instead of Edit %>
<% if estimate.issues.exists? %> <% if estimate.billed? || estimate.issues.exists? %>
<%= link_to sprite_icon('zoom-in', l(:button_view_estimate)), edit_qbo_estimate_path(estimate.id), <%= link_to sprite_icon('zoom-in', l(:button_view_estimate)), edit_qbo_estimate_path(estimate.id),
class: 'icon-only icon-zoom-in qbo-estimate-edit-link', title: l(:button_view_estimate) %> class: 'icon-only icon-zoom-in qbo-estimate-edit-link', title: l(:button_view_estimate) %>
<% else %> <% else %>
+1 -1
View File
@@ -26,7 +26,7 @@
data: { data: {
document: form.document, document: form.document,
import_url: (import_options_qbo_invoices_path if invoice), import_url: (import_options_qbo_invoices_path if invoice),
replaceable_item_ids: (RedmineQboBilling::InvoiceWriter.replaceable_item_ids if invoice), labor_item_ids: (RedmineQboBilling::LaborItems.item_ids if invoice),
items_url: items_qbo_estimates_path, items_url: items_qbo_estimates_path,
customer_info_url: customer_info_qbo_estimates_path, customer_info_url: customer_info_qbo_estimates_path,
saved_subtotal: (form.persisted? ? form.subtotal.to_s('F') : ''), saved_subtotal: (form.persisted? ? form.subtotal.to_s('F') : ''),
+12 -13
View File
@@ -35,16 +35,6 @@
</p> </p>
<% end %> <% end %>
<% if !invoice && Array(form.invoiced_on).any? %>
<div class="warning qbo-estimate-notice">
<%= l(:text_estimate_billed_on) %>
<ul>
<% form.invoiced_on.each do |invoice_id, number| %>
<li><%= link_to "#{l(:label_invoice)} ##{number}", RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(invoice_id) : invoice_path(invoice_id) %></li>
<% end %>
</ul>
</div>
<% end %>
<% if form.duplicated_from.present? %> <% if form.duplicated_from.present? %>
<div class="flash notice"><%= l(:text_estimate_duplicated_from, number: form.duplicated_from) %></div> <div class="flash notice"><%= l(:text_estimate_duplicated_from, number: form.duplicated_from) %></div>
@@ -53,7 +43,18 @@
<div class="flash notice"><%= l(:text_invoice_from_estimate, number: form.converted_from) %></div> <div class="flash notice"><%= l(:text_invoice_from_estimate, number: form.converted_from) %></div>
<% end %> <% end %>
<% if form.locked == :linked %> <% if form.locked == :billed %>
<div class="warning qbo-estimate-notice">
<%= l(:error_estimate_billed) %>
<% if Array(form.invoiced_on).any? %>
<ul>
<% form.invoiced_on.each do |invoice_id, number| %>
<li><%= link_to "#{l(:label_invoice)} ##{number}", RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(invoice_id) : invoice_path(invoice_id) %></li>
<% end %>
</ul>
<% end %>
</div>
<% elsif form.locked == :linked %>
<div class="warning qbo-estimate-notice"> <div class="warning qbo-estimate-notice">
<%= l(:error_estimate_linked_to_issues) %> <%= l(:error_estimate_linked_to_issues) %>
<ul> <ul>
@@ -66,8 +67,6 @@
<p class="warning"><%= l(:error_invoice_paid) %></p> <p class="warning"><%= l(:error_invoice_paid) %></p>
<% elsif form.locked == :bundles %> <% elsif form.locked == :bundles %>
<p class="warning"><%= l(invoice ? :error_invoice_has_bundles : :error_estimate_has_bundles) %></p> <p class="warning"><%= l(invoice ? :error_invoice_has_bundles : :error_estimate_has_bundles) %></p>
<% elsif !invoice && %w[Converted Closed].include?(form.txn_status.to_s) && Array(form.invoiced_on).empty? %>
<p class="warning"><%= l(:text_estimate_closed) %></p>
<% end %> <% end %>
<% if RedmineQboBilling::Company.settings.empty? %> <% if RedmineQboBilling::Company.settings.empty? %>
+3 -3
View File
@@ -414,9 +414,9 @@ $(function () {
}; };
// The invoice's lines, for ticking the ones the time replaces (e.g. the estimate's labor lines). // The invoice's lines, for ticking the ones the time replaces (e.g. the estimate's labor lines).
// When products/services are set as replaceable by time in the plugin settings, only lines with one of // Only lines with one of the labor products/services (plugin settings) are offered; if none are known,
// them are offered; with none set, every line is. // every line is.
var replaceable = ($form.data('replaceableItemIds') || []).map(String); var replaceable = ($form.data('laborItemIds') || []).map(String);
var fillReplaceList = function () { var fillReplaceList = function () {
var $list = $('#qbo-import-replace').empty(); var $list = $('#qbo-import-replace').empty();
rows().each(function () { rows().each(function () {
+1 -1
View File
@@ -4,7 +4,7 @@
<%# Plugins add estimate actions here (e.g. redmine_qbo_calendar's Add appointment) %> <%# Plugins add estimate actions here (e.g. redmine_qbo_calendar's Add appointment) %>
<%= call_hook :view_qbo_estimate_contextual, { estimate_id: @form.id, customer_id: @form.customer_id, vin: @form.vin, doc_number: @form.doc_number } %> <%= call_hook :view_qbo_estimate_contextual, { estimate_id: @form.id, customer_id: @form.customer_id, vin: @form.vin, doc_number: @form.doc_number } %>
<%# An estimate is billed once: no Create invoice once it's on an invoice, closed or rejected %> <%# An estimate is billed once: no Create invoice once it's on an invoice, closed or rejected %>
<% if RedmineQboBilling.invoice_writer? && Array(@form.invoiced_on).empty? && !%w[Converted Closed Rejected].include?(@form.txn_status.to_s) %> <% if RedmineQboBilling.invoice_writer? && @form.locked != :billed && @form.txn_status.to_s != 'Rejected' %>
<%= link_to sprite_icon('document', l(:button_create_invoice)), new_qbo_invoice_path(estimate_id: @form.id), class: 'icon icon-document' %> <%= link_to sprite_icon('document', l(:button_create_invoice)), new_qbo_invoice_path(estimate_id: @form.id), class: 'icon icon-document' %>
<% end %> <% end %>
<% if User.current.allowed_to?(:create_estimate_issues, nil, global: true) %> <% if User.current.allowed_to?(:create_estimate_issues, nil, global: true) %>
@@ -45,7 +45,7 @@
<% if proposals.empty? %> <% if proposals.empty? %>
<p class="nodata"> <p class="nodata">
<%= l(:error_no_labor_lines_found) %> <%= l(:error_no_labor_lines_found) %>
(<%= l(:label_estimate_item_codes) %>: <%= RedmineQboBilling::EstimateIssueBuilder.item_codes.join(', ') %>) (<%= l(:label_labor_items) %>: <%= RedmineQboBilling::LaborItems.names.join(', ') %>)
<% if User.current.admin? %> <% if User.current.admin? %>
&middot; <%= link_to l(:label_settings), plugin_settings_path(id: 'redmine_qbo') %> &middot; <%= link_to l(:label_settings), plugin_settings_path(id: 'redmine_qbo') %>
<% 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 %>
+39 -20
View File
@@ -37,7 +37,6 @@ en:
label_closed_issues: "Closed Issues" label_closed_issues: "Closed Issues"
label_connected: "Successfully connected to QuickBooks" label_connected: "Successfully connected to QuickBooks"
label_create_estimate: "Create Estimate" label_create_estimate: "Create Estimate"
label_customer_count: "Customer Count"
label_customer_link_expires: "This customer link expires in" label_customer_link_expires: "This customer link expires in"
label_customer: "Customer" label_customer: "Customer"
label_customers: "Customers" label_customers: "Customers"
@@ -49,15 +48,12 @@ en:
label_edit: "Edit" label_edit: "Edit"
label_edit_customer: "Edit Customer" label_edit_customer: "Edit Customer"
label_email: "Email" label_email: "Email"
label_employee_count: "Employee Count"
label_error: "Error" label_error: "Error"
label_estimate_404: "Estimate not found" label_estimate_404: "Estimate not found"
label_estimate_count: "Estimate Count"
label_estimate: "Estimate" label_estimate: "Estimate"
label_estimates: "Estimates" label_estimates: "Estimates"
label_hours: "Hours" label_hours: "Hours"
label_invoice_404: "Invoice not found" label_invoice_404: "Invoice not found"
label_invoice_count: "Invoice Count"
label_invoices: "Invoices" label_invoices: "Invoices"
label_last_sync: "Last Sync" label_last_sync: "Last Sync"
label_load_customer: "Load Customer" label_load_customer: "Load Customer"
@@ -87,11 +83,6 @@ en:
label_share: "Share" label_share: "Share"
label_shipping_address: "Shipping Address" label_shipping_address: "Shipping Address"
label_sync: "Sync" label_sync: "Sync"
label_sync_now: "Sync Now"
label_sync_now_customers: "Sync Customers"
label_sync_now_employees: "Sync Employees"
label_sync_now_invoices: "Sync Invoices"
label_sync_now_estimate: "Sync Estimates"
label_syncing: "Syncing QuickBooks" label_syncing: "Syncing QuickBooks"
label_trim: "Trim" label_trim: "Trim"
label_webhook_token: "Intuit QBO Webhook Token" label_webhook_token: "Intuit QBO Webhook Token"
@@ -143,6 +134,7 @@ en:
error_estimate_changed_in_quickbooks: "This estimate was changed in QuickBooks after you opened it, so it wasn't saved." error_estimate_changed_in_quickbooks: "This estimate was changed in QuickBooks after you opened it, so it wasn't saved."
error_estimate_field_invalid: "%{field} is not valid" error_estimate_field_invalid: "%{field} is not valid"
error_estimate_linked_to_issues: "This estimate is linked to these issues, so it can't be changed here. Duplicate it to make a new estimate:" error_estimate_linked_to_issues: "This estimate is linked to these issues, so it can't be changed here. Duplicate it to make a new estimate:"
error_estimate_billed: "This estimate has been billed (turned into an invoice), so it can't be changed here. Duplicate it to make a new estimate."
error_estimate_has_bundles: "This estimate has bundles, which can only be edited in QuickBooks." error_estimate_has_bundles: "This estimate has bundles, which can only be edited in QuickBooks."
error_estimate_line_description: "Line %{line} needs a description, a product or service, or a rate" error_estimate_line_description: "Line %{line} needs a description, a product or service, or a rate"
error_estimate_line_number: "Line %{line} has a quantity or rate that isn't a number" error_estimate_line_number: "Line %{line} has a quantity or rate that isn't a number"
@@ -186,7 +178,6 @@ en:
text_clear_all_lines_confirmation: "Clear all lines?" text_clear_all_lines_confirmation: "Clear all lines?"
text_email_estimate_confirmation: "Email estimate #%{number} to %{email}?" text_email_estimate_confirmation: "Email estimate #%{number} to %{email}?"
text_estimate_duplicated_from: "Copied from estimate #%{number}. It's saved as a new estimate." text_estimate_duplicated_from: "Copied from estimate #%{number}. It's saved as a new estimate."
text_estimate_closed: "This estimate is closed (it was turned into an invoice). Changes here won't change the invoice."
text_estimate_expiration_days: "New estimates get an expiration date this many days after the estimate date, e.g. 30. Leave blank for no expiration date." text_estimate_expiration_days: "New estimates get an expiration date this many days after the estimate date, e.g. 30. Leave blank for no expiration date."
text_estimate_reload: "Reloading shows the latest version from QuickBooks; changes made on this page will be lost." text_estimate_reload: "Reloading shows the latest version from QuickBooks; changes made on this page will be lost."
text_estimate_send_needs_email: "Enter the customer's email to send it." text_estimate_send_needs_email: "Enter the customer's email to send it."
@@ -206,20 +197,25 @@ en:
label_active: "Active" label_active: "Active"
label_account: "Account" label_account: "Account"
label_accounts: "Accounts" label_accounts: "Accounts"
label_account_count: "Number of Accounts:"
label_back: "Back" label_back: "Back"
label_default_account: "Default Item Income Account" label_default_account: "Default Item Income Account"
label_description: "Description" label_description: "Description"
label_edit_item: "Edit Item" label_edit_item: "Edit Item"
label_item: "Item" label_item: "Item"
label_item_count: "Item Count:"
label_item_new: "New Item" label_item_new: "New Item"
label_items: "Items" label_items: "Items"
label_management_and_sync: "Management & Synchronization" label_management_and_sync: "Synchronization"
label_labor_items: "Labor products/services"
text_labor_items: "Products/services billed as labor hours, e.g. Labor. Used to create issues from an estimate's labor lines (and an appointment's minimum hours), to offer an invoice's labor lines to be replaced by imported time, and to total hours on estimates and invoices for the business report (sync estimates and invoices after changing). While none are chosen, products/services named Labor are used. Ctrl/Cmd-click to pick several."
label_qbo_connection: "QuickBooks connection"
label_qbo_records: "Records"
label_employee_plural: "Employees"
label_sync_changes: "Sync changes"
label_full_sync: "Full sync"
text_qbo_sync_info: "Sync changes reads what changed in QuickBooks since the last sync; Full sync and each type's Sync re-read every record (e.g. after changing the labor products/services, sync estimates and invoices). Webhooks keep things current in between."
text_default_account_info: "New products/services go in this income account; set it on the Accounts page."
label_never_synced: "Never synced" label_never_synced: "Never synced"
label_no: "No" label_no: "No"
label_sync_now_accounts: "Sync Accounts"
label_sync_now_items: "Sync Items"
label_type: "Type" label_type: "Type"
label_yes: "Yes" label_yes: "Yes"
error_default_account_not_selected: "Select an account to make it the default." error_default_account_not_selected: "Select an account to make it the default."
@@ -235,7 +231,6 @@ en:
error_estimate_already_invoiced: "Estimate #%{number} is already billed on invoice #%{invoice}." error_estimate_already_invoiced: "Estimate #%{number} is already billed on invoice #%{invoice}."
error_estimate_closed_billed: "Estimate #%{number} is already billed (%{status})." error_estimate_closed_billed: "Estimate #%{number} is already billed (%{status})."
error_estimate_rejected: "Estimate #%{number} was rejected, so it can't be billed." error_estimate_rejected: "Estimate #%{number} was rejected, so it can't be billed."
text_estimate_billed_on: "This estimate is billed on:"
error_invoice_changed_in_quickbooks: "This invoice was changed in QuickBooks after you opened it, so it wasn't saved." error_invoice_changed_in_quickbooks: "This invoice was changed in QuickBooks after you opened it, so it wasn't saved."
error_invoice_has_bundles: "This invoice has bundles, which can only be edited in QuickBooks." error_invoice_has_bundles: "This invoice has bundles, which can only be edited in QuickBooks."
error_invoice_not_saved: "QuickBooks didn't save the invoice" error_invoice_not_saved: "QuickBooks didn't save the invoice"
@@ -253,7 +248,6 @@ en:
label_new_invoice: "New invoice" label_new_invoice: "New invoice"
label_open_estimates: "Open estimates" label_open_estimates: "Open estimates"
label_replace_lines: "Replace these lines" label_replace_lines: "Replace these lines"
label_replaceable_items: "Replaced by imported time"
label_time_badge: "Time" label_time_badge: "Time"
notice_invoice_saved_and_sent: "Invoice #%{number} saved in QuickBooks and emailed to %{email}" notice_invoice_saved_and_sent: "Invoice #%{number} saved in QuickBooks and emailed to %{email}"
notice_invoice_saved_in_quickbooks: "Invoice #%{number} saved in QuickBooks" notice_invoice_saved_in_quickbooks: "Invoice #%{number} saved in QuickBooks"
@@ -262,7 +256,6 @@ 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_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)
@@ -276,7 +269,6 @@ en:
label_estimate_issue_fields: "Issue fields" label_estimate_issue_fields: "Issue fields"
label_estimate_issue_settings: "Issues from estimates" label_estimate_issue_settings: "Issues from estimates"
label_estimate_item: "Item" label_estimate_item: "Item"
label_estimate_item_codes: "Estimate item codes"
label_estimate_line_already_created: "Already created" label_estimate_line_already_created: "Already created"
label_issue_template: "Template" label_issue_template: "Template"
label_no_issue_template: "(no template)" label_no_issue_template: "(no template)"
@@ -288,7 +280,6 @@ en:
text_estimate_issue_fields_info: "Entered once and applied to every created issue whose tracker uses the field. Fields marked * are required by the selected trackers." text_estimate_issue_fields_info: "Entered once and applied to every created issue whose tracker uses the field. Fields marked * are required by the selected trackers."
text_estimate_issues_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. Edit anything before creating. New issues are related to each other and to issues already created from this estimate." text_estimate_issues_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. Edit anything before creating. New issues are related to each other and to issues already created from this estimate."
text_estimate_issues_template_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. A template supplies the issue's description. New issues are related to each other and to issues already created from this estimate." text_estimate_issues_template_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. A template supplies the issue's description. New issues are related to each other and to issues already created from this estimate."
text_estimate_item_codes_info: "QBO item names that can become issues, one per line (e.g. Labor, Alignments). Matches the full item name or any part of a Category:Item name, ignoring case. Their quantities are also an estimate's labor hours (an appointment's hours can't be less)."
# Payments # Payments
button_print_payment: "Print" button_print_payment: "Print"
@@ -311,6 +302,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 labor products/services. 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."
+4
View File
@@ -74,6 +74,7 @@ resources :qbo_payments, only: [:index, :new, :create, :show] do
get :pdf get :pdf
end end
collection do collection do
get :sync
get :open_invoices get :open_invoices
end end
end end
@@ -93,3 +94,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,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.
# Cached from QuickBooks by the sync and the webhook: each estimate's total and status (Converted or Closed
# estimates are billed, so they're shown as View instead of Edit), and the man-hours on estimates and invoices
# (quantities of the labor products/services) for the business report.
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 :estimates, :txn_status, :string unless column_exists?(:estimates, :txn_status)
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, :txn_status if column_exists?(:estimates, :txn_status)
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
@@ -26,57 +26,34 @@ module RedmineQboBilling
class EstimateIssueBuilder class EstimateIssueBuilder
include Redmine::I18n include Redmine::I18n
DEFAULT_ITEM_CODES = ['Labor'].freeze
Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, keyword_init: true) do Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, keyword_init: true) do
def created? def created?
existing_issue.present? existing_issue.present?
end end
end end
# Item codes from the plugin settings, one per line (commas also accepted). Until they're set here, the
# ones redmine_qbo_calendar used are kept.
def self.item_codes
raw = setting('issue_item_codes', 'item_codes').to_s
codes = raw.split(/[\n,]/).map(&:strip).reject(&:blank?)
codes.presence || DEFAULT_ITEM_CODES
end
def self.default_tracker_id def self.default_tracker_id
setting('issue_default_tracker_id', 'default_tracker_id').to_i setting('issue_default_tracker_id').to_i
end end
def self.default_project_id def self.default_project_id
setting('issue_default_project_id', 'default_project_id').to_i setting('issue_default_project_id').to_i
end end
# This plugin's setting, or redmine_qbo_calendar's old one while this one is blank def self.setting(key)
def self.setting(key, calendar_key) (Setting.plugin_redmine_qbo || {})[key]
ours = (Setting.plugin_redmine_qbo || {})[key]
return ours if ours.present?
calendar = Setting.respond_to?(:plugin_redmine_qbo_calendar) ? (Setting.plugin_redmine_qbo_calendar || {}) : {}
calendar[calendar_key]
rescue StandardError rescue StandardError
nil nil
end end
# A line matches a code if its QBO item name equals the code, or any part of a # The estimate's labor hours: the quantities of its labor lines (LaborItems)
# "Category:Item" name does. Case-insensitive.
def self.item_matches?(item_name, codes = item_codes)
name = item_name.to_s.strip.downcase
parts = name.split(':').map(&:strip)
codes.map { |c| c.strip.downcase }.any? { |code| name == code || parts.include?(code) }
end
# The estimate's labor hours: the quantities of its lines whose item matches an item code
# (e.g. for an appointment's hours, which shouldn't be less) # (e.g. for an appointment's hours, which shouldn't be less)
def self.labor_hours(estimate) def self.labor_hours(estimate)
return 0.0 if estimate.nil? return 0.0 if estimate.nil?
Array(estimate.line_items).sum do |line| Array(estimate.line_items).sum do |line|
detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil
next 0.0 if detail.nil? || detail.item_ref.nil? || !item_matches?(detail.item_ref.name) next 0.0 if detail.nil? || !LaborItems.match?(detail.item_ref)
detail.quantity.to_f detail.quantity.to_f
end end
end end
@@ -172,7 +149,8 @@ module RedmineQboBilling
def build_proposals def build_proposals
return [] if estimate.blank? return [] if estimate.blank?
codes = self.class.item_codes ids = LaborItems.ids
codes = LaborItems.codes
links = QboEstimateLineIssue.where(estimate_id: estimate.id).includes(:issue).index_by(&:line_id) links = QboEstimateLineIssue.where(estimate_id: estimate.id).includes(:issue).index_by(&:line_id)
Array(estimate.line_items).each_with_index.filter_map do |line, index| Array(estimate.line_items).each_with_index.filter_map do |line, index|
@@ -180,7 +158,7 @@ module RedmineQboBilling
next if detail.nil? || detail.item_ref.nil? next if detail.nil? || detail.item_ref.nil?
item_name = detail.item_ref.name.to_s.strip item_name = detail.item_ref.name.to_s.strip
next unless self.class.item_matches?(item_name, codes) next unless LaborItems.match?(detail.item_ref, ids: ids, codes: codes)
# The subject comes from the line's description, so lines without one are skipped # The subject comes from the line's description, so lines without one are skipped
description = line.description.to_s.strip description = line.description.to_s.strip
+15 -2
View File
@@ -121,6 +121,7 @@ module RedmineQboBilling
remote = service.fetch_by_id(form.id) remote = service.fetch_by_id(form.id)
raise Error, I18n.t(:notice_estimate_not_found) unless remote raise Error, I18n.t(:notice_estimate_not_found) unless remote
raise Conflict, I18n.t(:error_estimate_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s raise Conflict, I18n.t(:error_estimate_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
raise Error, I18n.t(:error_estimate_billed) if billed?(remote)
raise Error, I18n.t(:error_estimate_has_bundles) if group_lines?(remote) raise Error, I18n.t(:error_estimate_has_bundles) if group_lines?(remote)
raise Error, I18n.t(:error_estimate_linked_to_issues) if linked_issues(form.id).any? raise Error, I18n.t(:error_estimate_linked_to_issues) if linked_issues(form.id).any?
@@ -150,6 +151,16 @@ module RedmineQboBilling
# ---- QuickBooks estimate -> form ---- # ---- QuickBooks estimate -> form ----
# Statuses QuickBooks gives an estimate that has been turned into an invoice
BILLED_STATUSES = %w[Converted Closed].freeze
# True once the estimate is billed: converted or closed, or linked to an invoice. Billed estimates (including
# redmine_qbo_lineitems' once they're invoiced) can't be changed here.
def billed?(remote)
BILLED_STATUSES.include?(remote.txn_status.to_s) ||
Array(remote.linked_transactions).any? { |t| t.txn_type.to_s == 'Invoice' }
end
def form_from_remote(remote) def form_from_remote(remote)
EstimateForm.new( EstimateForm.new(
id: remote.id.to_s, id: remote.id.to_s,
@@ -175,8 +186,10 @@ module RedmineQboBilling
invoiced_on: Array(remote.linked_transactions).select { |t| t.txn_type.to_s == 'Invoice' }.map { |t| invoiced_on: Array(remote.linked_transactions).select { |t| t.txn_type.to_s == 'Invoice' }.map { |t|
[t.txn_id.to_s, InvoiceWriter.invoice_number(t.txn_id)] [t.txn_id.to_s, InvoiceWriter.invoice_number(t.txn_id)]
}.uniq, }.uniq,
# Read-only when it has bundles, or once an issue is linked to it (the work is under way) # Read-only once it's billed (converted, closed or on an invoice), when it has bundles, or once an issue
locked: (:bundles if group_lines?(remote)) || (:linked if linked_issues(remote.id).any?) # is linked to it (the work is under way)
locked: (:billed if billed?(remote)) || (:bundles if group_lines?(remote)) ||
(:linked if linked_issues(remote.id).any?)
) )
end end
+1 -9
View File
@@ -29,7 +29,7 @@ module RedmineQboBilling
# Estimates in these states can still be imported (Converted/Closed ones are already invoiced, Rejected ones lost) # Estimates in these states can still be imported (Converted/Closed ones are already invoiced, Rejected ones lost)
OPEN_ESTIMATE_STATUSES = ['', 'Pending', 'Accepted'].freeze OPEN_ESTIMATE_STATUSES = ['', 'Pending', 'Accepted'].freeze
# How QuickBooks marks an invoiced estimate: Converted when it made the invoice, Closed when closed by hand # How QuickBooks marks an invoiced estimate: Converted when it made the invoice, Closed when closed by hand
BILLED_ESTIMATE_STATUSES = %w[Converted Closed].freeze BILLED_ESTIMATE_STATUSES = EstimateWriter::BILLED_STATUSES
# How far back to look for billable time if QuickBooks won't filter time activities by customer # How far back to look for billable time if QuickBooks won't filter time activities by customer
TIME_LOOKBACK = 400 TIME_LOOKBACK = 400
@@ -39,14 +39,6 @@ module RedmineQboBilling
EstimateWriter EstimateWriter
end end
# The plugin setting "Replaced by imported time": only lines with these products/services are offered
# under Replace these lines when time is imported (e.g. an estimate's Labor lines); empty offers every line
def replaceable_item_ids
Array(Setting.plugin_redmine_qbo['replaceable_item_ids']).map(&:to_s).reject(&:blank?).uniq
rescue StandardError
[]
end
# A blank invoice for the customer, dated today # A blank invoice for the customer, dated today
def new_form(customer: nil, user: User.current) def new_form(customer: nil, user: User.current)
EstimateForm.new( EstimateForm.new(
+79
View File
@@ -0,0 +1,79 @@
#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 labor products/services (plugin setting "Labor products/services", e.g. Labor). They are used to:
# * create issues from an estimate's labor lines (and work out its labor hours for appointments)
# * offer an invoice's labor lines to be replaced by imported time
# * total the man-hours on estimates and invoices for the business report
#
# While none are chosen, products/services named "Labor" are used (the full name or any part of a
# "Category:Item" name, ignoring case).
module LaborItems
DEFAULT_CODES = ['Labor'].freeze
module_function
# The chosen products/services' QuickBooks ids
def ids(settings = plugin_settings)
Array(settings['labor_item_ids']).map(&:to_s).reject(&:blank?).uniq
end
# Item names matched while no products/services are chosen
def codes
DEFAULT_CODES
end
# True when a line's product/service (its ItemRef) is labor
def match?(item_ref, ids: self.ids, codes: nil)
return false if item_ref.nil?
return ids.include?(item_ref.value.to_s) if ids.any?
name_matches?(item_ref.name, codes || self.codes)
end
def name_matches?(item_name, codes)
name = item_name.to_s.strip.downcase
return false if name.empty?
parts = name.split(':').map(&:strip)
codes.map { |c| c.strip.downcase }.any? { |code| name == code || parts.include?(code) }
end
# The labor products/services as ids: the chosen ones, else the local items whose names match the codes
# (for the settings page and the invoice's Replace these lines list)
def item_ids
chosen = ids
return chosen if chosen.any?
list = codes
Item.where(active: true).pluck(:id, :name).select { |_, name| name_matches?(name, list) }.map { |id, _| id.to_s }
rescue StandardError
[]
end
# Names to show, e.g. when an estimate has no labor lines
def names
chosen = ids
return codes if chosen.empty?
Item.where(id: chosen).pluck(:name).presence || chosen
rescue StandardError
chosen
end
def plugin_settings
Setting.plugin_redmine_qbo || {}
rescue StandardError
{}
end
end
end
+43
View File
@@ -0,0 +1,43 @@
#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 labor lines (the plugin setting
# "Labor products/services", see LaborItems), including lines inside bundles.
module ManHours
module_function
def hours(document, item_ids: LaborItems.ids, codes: nil)
return 0.0 if document.nil?
ids = Array(item_ids).map(&:to_s).reject(&:blank?)
codes ||= LaborItems.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 && LaborItems.match?(detail.item_ref, ids: ids, codes: 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
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