Fold redmine_qbo_billing into redmine_qbo

Estimates, invoices and payments written in Redmine, issues from estimates,
and the QuickBooks product/service list and accounts are now part of this
plugin (the RedmineQboBilling code, its controllers, views, strings and
permissions), so there's one plugin and one version instead of two that had
to match.

- The customer page, estimate and invoice lists and the issue page render the
  Create Estimate / Create invoice / Receive payment and Edit links directly;
  the hooks that only existed to let billing add them are gone. Users without
  the billing permissions still get the links to QuickBooks.
- Migrations 043-046 create the items and accounts tables and the estimate
  line links, skipping whatever an existing database already has
  (redmine_qbo_lineitems' tables are used as they are), and copy calendar's
  existing estimate line links in.
- The billing settings are a section of this plugin's settings page.
- The hooks other plugins use stay: qbo_billing_issue_values,
  qbo_billing_validate, qbo_billing_issue_defaults, qbo_billing_issues_created
  and view_qbo_estimate_contextual.
- rake redmine_qbo:relate_estimate_issues

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-30 23:47:01 -04:00
1 parent 48a4185c16
commit 9121e079a0
67 files changed
+5570 -19

No files matched your search

+152
View File
@@ -0,0 +1,152 @@
#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
# What the QuickBooks company is set up with, read from its Preferences so nothing has to be configured
# in Redmine: the estimate custom fields (found by name), whether estimate numbers are typed by hand,
# and the default message shown on estimates.
#
# QuickBooks only shares its first three text custom fields with apps (dropdown fields aren't
# available), so a "Sales Person" dropdown has to be changed to a text field to be filled in here.
module Company
CACHE_KEY = 'redmine_qbo_billing:company'
CACHE_TIME = 1.hour
# While the VIN or sales person field is missing, look again sooner (e.g. right after adding it in QuickBooks)
MISSING_FIELD_CACHE_TIME = 5.minutes
# Recent estimates also show which custom fields exist, for companies whose preferences don't list them
RECENT_ESTIMATES = 20
# Custom field names are matched loosely, e.g. "VIN", "Vin #", "Sales Person", "Salesperson", "Sales Rep"
VIN_NAME = /\bvin\b/i
SALES_PERSON_NAME = /sales|\brep\b/i
MILEAGE_NAME = /mileage|odometer|\bmiles\b/i
Field = Struct.new(:id, :name)
module_function
# All enabled sales form custom fields, in QuickBooks' order
def custom_fields
Array(settings[:custom_fields]).map { |f| Field.new(f[:id], f[:name]) }
end
def vin_field
custom_fields.detect { |f| f.name.to_s =~ VIN_NAME }
end
# Optional: a text field named like "Mileage" or "Odometer"
def mileage_field
custom_fields.detect { |f| f.name.to_s =~ MILEAGE_NAME && f.name.to_s !~ VIN_NAME }
end
def sales_person_field
custom_fields.detect { |f| f.name.to_s =~ SALES_PERSON_NAME && f.name.to_s !~ VIN_NAME }
end
# When on, QuickBooks leaves estimate numbers to the user; when off it numbers them itself
def custom_txn_numbers?
settings[:custom_txn_numbers] == true
end
# The "default message shown on estimates" from QuickBooks' sales settings
def estimate_message
settings[:estimate_message].to_s
end
# The "default message shown on invoices" (and other sales forms)
def invoice_message
settings[:invoice_message].to_s
end
# Forgets the cached preferences, e.g. after a custom field was renamed in QuickBooks
def refresh!
Rails.cache.delete(CACHE_KEY)
settings
end
# Cached for an hour (five minutes while a field is missing). A failed lookup isn't cached.
def settings
cached = Rails.cache.read(CACHE_KEY)
return cached if cached
fresh = fetch_settings
return {} unless fresh
names = fresh[:custom_fields].map { |f| f[:name].to_s }
complete = names.any? { |n| n =~ VIN_NAME } && names.any? { |n| n =~ SALES_PERSON_NAME && n !~ VIN_NAME }
Rails.cache.write(CACHE_KEY, fresh, expires_in: complete ? CACHE_TIME : MISSING_FIELD_CACHE_TIME)
fresh
end
def fetch_settings
QboConnectionService.with_qbo_service(entity: 'Preferences') do |service|
prefs = service.query.entries.first
return nil unless prefs
forms = prefs.sales_forms
{
custom_fields: merge_fields(parse_custom_fields(forms&.custom_fields), custom_fields_from_estimates),
custom_txn_numbers: forms&.custom_txn_numbers? == 'true' || forms&.custom_txn_numbers? == true,
estimate_message: forms&.estimate_message.to_s,
invoice_message: forms&.default_customer_message.to_s
}
end
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read QuickBooks preferences: #{e.message}"
nil
end
# Fields named in the preferences come first; fields only seen on estimates are added after them.
# QuickBooks' newer custom fields (e.g. on Advanced and sandbox companies) may not be in the preferences.
def merge_fields(from_preferences, from_estimates)
ids = from_preferences.map { |f| f[:id] }
from_preferences + from_estimates.reject { |f| ids.include?(f[:id]) }
end
# The text custom fields on the most recently changed estimates
def custom_fields_from_estimates
estimates = QboEstimateService.with_service do |service|
service.query('SELECT * FROM Estimate ORDERBY MetaData.LastUpdatedTime DESC', per_page: RECENT_ESTIMATES).entries
end
Array(estimates).flat_map { |e| Array(e.custom_fields) }
.select { |f| f.id.to_i > 0 && f.name.present? && (f.type.blank? || f.type.to_s == 'StringType') }
.map { |f| { id: f.id.to_i, name: f.name.to_s.strip } }
.uniq { |f| f[:id] }
.sort_by { |f| f[:id] }
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read custom fields from recent estimates: #{e.message}"
[]
end
# Preferences list the custom fields as name/value pairs:
# SalesFormsPrefs.UseSalesCustom2 => true (field 2 is turned on)
# SalesFormsPrefs.SalesCustomName2 => "VIN" (field 2's name)
# The number is the field's DefinitionId on estimates.
def parse_custom_fields(entries)
enabled = {}
names = {}
Array(entries).each do |entry|
case entry.name.to_s
when /UseSalesCustom(\d+)\z/
enabled[$1.to_i] = entry.boolean_value.to_s == 'true'
when /SalesCustomName(\d+)\z/
names[$1.to_i] = entry.string_value.to_s.strip
end
end
names.keys.sort.filter_map do |id|
next if names[id].blank? || enabled[id] == false
{ id: id, name: names[id] }
end
end
end
end
+235
View File
@@ -0,0 +1,235 @@
#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
# What the estimate and invoice editor shows and posts: the header fields and the lines.
# EstimateWriter and InvoiceWriter turn it into a QuickBooks estimate or invoice and back.
class EstimateForm
include ActiveModel::Model
include ActiveModel::Validations
# One row of the line table. A row with a product/service is a sales line; a row with only a
# description (e.g. the estimate notes on the first line) becomes a description-only line.
# A subtotal row (kind "subtotal") totals the lines above it, back to the previous subtotal.
# On invoices, a row imported from a QuickBooks time activity keeps its id (time_activity_id) so the
# invoice line stays linked to it and QuickBooks marks the time as billed.
class Line
include ActiveModel::Model
SUBTOTAL = 'subtotal'.freeze
# The fields each row posts (the controller permits exactly these)
PARAMS = %i[id kind item_id item_name description quantity rate taxable time_activity_id].freeze
attr_accessor :id, :kind, :item_id, :item_name, :description, :quantity, :rate, :taxable, :time_activity_id
def self.from_params(hash)
hash = hash.to_h.stringify_keys
new(
id: hash['id'].presence,
kind: hash['kind'].to_s == SUBTOTAL ? SUBTOTAL : nil,
item_id: hash['item_id'].presence,
item_name: hash['item_name'].to_s.strip,
description: hash['description'].to_s.strip,
quantity: hash['quantity'].to_s.strip,
rate: hash['rate'].to_s.strip,
taxable: hash['taxable'].to_s == '1',
time_activity_id: hash['time_activity_id'].presence
)
end
def quantity_value
EstimateForm.decimal(quantity)
end
def rate_value
EstimateForm.decimal(rate)
end
def subtotal?
kind == SUBTOTAL
end
# Quantity defaults to 1 when only a rate is given, like QuickBooks. Subtotals add nothing themselves.
def amount
return BigDecimal('0') if subtotal? || rate_value.nil?
((quantity_value || BigDecimal('1')) * rate_value).round(2)
end
def taxable?
taxable == true || taxable.to_s == '1' || taxable.to_s == 'true'
end
def item?
!subtotal? && item_id.present?
end
# No product and no price: a note line
def description_only?
!subtotal? && !item? && rate_value.nil?
end
# Empty rows (e.g. the spare row at the bottom of the table) are dropped
def blank?
!subtotal? && !item? && item_name.blank? && description.blank? && rate.blank?
end
# Typed in the product box but never picked from the list
def unmatched_item?
!subtotal? && !item? && item_name.present?
end
def number_invalid?
return false if subtotal?
(quantity.present? && quantity_value.nil?) || (rate.present? && rate_value.nil?)
end
end
# due_date is an invoice's; expiration_date an estimate's
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number vin mileage customer_memo private_note].freeze
# "estimate" or "invoice"
attr_writer :document
attr_accessor :id, :sync_token, *HEADER_ATTRIBUTES, :sales_person, :lines,
# Invoices: estimates whose lines are on this invoice (they're linked and closed when saved)
:linked_estimate_ids,
# Read-only details shown on the editor
:billing_address, :total, :total_tax, :discount, :email_status, :txn_status, :duplicated_from,
:balance, :converted_from,
# Estimates: the invoices it's billed on ([[id, number], ...])
:invoiced_on,
# nil, :bundles (has bundle lines), :linked (an issue is linked to the estimate) or
# :paid (a payment is applied to the invoice)
:locked
validate :validate_customer
validate :validate_lines
validate :validate_dates
validate :validate_email
# Plugins can block a save (e.g. redmine_qbo_vehicles: one vehicle per invoice); see IssueValues
validate :validate_with_plugins
def initialize(attributes = {})
super
self.lines ||= []
self.linked_estimate_ids ||= []
end
def document
@document || 'estimate'
end
def invoice?
document == 'invoice'
end
# Builds the form from posted params (estimate[...], with lines keyed by row in table order)
def self.from_params(params, id: nil, document: 'estimate')
params = params.to_h.stringify_keys
form = new(id: id.presence, sync_token: params['sync_token'].presence, document: document)
HEADER_ATTRIBUTES.each { |attr| form.public_send("#{attr}=", params[attr.to_s].to_s.strip) }
form.total_tax = params['total_tax'].presence
form.discount = params['discount'].presence
form.email_status = params['email_status'].presence
form.txn_status = params['txn_status'].presence
form.balance = params['balance'].presence
form.linked_estimate_ids = Array(params['linked_estimate_ids']).map(&:to_s).reject(&:blank?).uniq
form.lines = params['lines'].to_h.values.map { |row| Line.from_params(row) }
form
end
def self.decimal(value)
text = value.to_s.strip.delete(',').delete('$')
return nil if text.empty?
BigDecimal(text)
rescue ArgumentError
nil
end
def self.date(value)
return value if value.is_a?(Date)
text = value.to_s.strip
text.empty? ? nil : Date.iso8601(text)
rescue ArgumentError
nil
end
def persisted?
id.present?
end
def filled_lines
lines.reject(&:blank?)
end
def subtotal
filled_lines.sum(BigDecimal('0'), &:amount)
end
def sent?
email_status.to_s == 'EmailSent'
end
def txn_date_value
self.class.date(txn_date)
end
def expiration_date_value
self.class.date(expiration_date)
end
def due_date_value
self.class.date(due_date)
end
private
# Messages are added to base so they read as full sentences in Redmine's error box
def invalid(label_key)
errors.add(:base, I18n.t(:error_estimate_field_invalid, field: I18n.t(label_key)))
end
def validate_customer
errors.add(:base, I18n.t(:error_estimate_needs_customer)) if customer_id.blank?
end
def validate_lines
if filled_lines.empty?
errors.add(:base, I18n.t(:error_estimate_needs_a_line))
return
end
filled_lines.each_with_index do |line, index|
number = index + 1
errors.add(:base, I18n.t(:error_estimate_line_unmatched_item, line: number, name: line.item_name)) if line.unmatched_item?
errors.add(:base, I18n.t(:error_estimate_line_number, line: number)) if line.number_invalid?
errors.add(:base, I18n.t(:error_estimate_line_description, line: number)) if line.description_only? && line.description.blank?
end
end
def validate_dates
invalid(invoice? ? :label_invoice_date : :label_estimate_date) if txn_date_value.nil?
invalid(:label_expiration_date) if expiration_date.present? && expiration_date_value.nil?
invalid(:label_due_date) if due_date.present? && due_date_value.nil?
end
def validate_with_plugins
IssueValues.plugin_errors(self).each { |message| errors.add(:base, message) }
end
def validate_email
return if email.blank?
# QuickBooks takes several addresses separated by commas
addresses = email.split(',').map(&:strip)
invalid(:label_customer_email) unless addresses.all? { |a| a.match?(/\A[^@\s]+@[^@\s]+\z/) }
end
end
end
@@ -0,0 +1,271 @@
#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
# Turns the labor lines of a QuickBooks estimate into proposed issues, and creates the ones the user selects
# on the "Create issues from estimate" page (moved here from redmine_qbo_calendar).
#
# - Only lines whose item matches a configured item code (e.g. "Labor", "Alignments") are proposed
# - Subject = the line's description; estimated hours = the line's quantity
# - Lines already turned into issues are shown but can't be created again
# - Creation is all-or-nothing: if any issue fails validation, none are saved
# - All issues created from the same estimate are related to each other, across batches
#
# Other plugins fill in more through hooks:
# :qbo_billing_issue_defaults, { estimate:, params: } => a hash of start_date, due_date, assignee,
# vehicle_id, description, project, return_path, return_label (e.g. redmine_qbo_calendar, when the page is
# opened from an appointment)
# :qbo_billing_issues_created, { estimate:, issues:, params: } after issues are created
class EstimateIssueBuilder
include Redmine::I18n
DEFAULT_ITEM_CODES = ['Labor'].freeze
Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, keyword_init: true) do
def created?
existing_issue.present?
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
setting('issue_default_tracker_id', 'default_tracker_id').to_i
end
def self.default_project_id
setting('issue_default_project_id', 'default_project_id').to_i
end
# This plugin's setting, or redmine_qbo_calendar's old one while this one is blank
def self.setting(key, calendar_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
nil
end
# A line matches a code if its QBO item name equals the code, or any part of a
# "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)
def self.labor_hours(estimate)
return 0.0 if estimate.nil?
Array(estimate.line_items).sum do |line|
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)
detail.quantity.to_f
end
end
# Relates every issue in the list to every other one ("Related to"), skipping pairs that already
# have any relation. Used for issues created from the same estimate, whichever batch they came from.
# Issues loaded fresh have no open journal, so this adds no history entries and sends no
# "issue updated" emails. A failed relation (e.g. cross-project relations disabled) is logged, not fatal.
# Returns the number of relations created.
def self.relate_all(issues)
issues = issues.compact.uniq(&:id)
return 0 if issues.size < 2
ids = issues.map(&:id)
already_related = IssueRelation.where(issue_from_id: ids, issue_to_id: ids)
.pluck(:issue_from_id, :issue_to_id)
.map(&:minmax)
.to_set
issues.combination(2).count do |issue_from, issue_to|
next false if already_related.include?([issue_from.id, issue_to.id].minmax)
relation = IssueRelation.new(issue_from: issue_from, issue_to: issue_to,
relation_type: IssueRelation::TYPE_RELATES)
next true if relation.save
Rails.logger.warn "[EstimateIssueBuilder] Could not relate ##{issue_from.id} and ##{issue_to.id}: " \
"#{relation.errors.full_messages.join(', ')}"
false
end
end
attr_reader :estimate, :defaults, :errors
# estimate: redmine_qbo's local Estimate (its QuickBooks details give the lines)
# defaults: start_date, due_date, assignee, vehicle_id, description (from another plugin's hook)
def initialize(estimate, defaults: {})
@estimate = estimate
@defaults = (defaults || {}).to_h.symbolize_keys
@errors = []
end
def proposals
@proposals ||= build_proposals
end
# rows: { line_id => { 'selected' => '1', 'subject' => ..., 'tracker_id' => ..., 'template' => 'global:3', 'estimated_hours' => ... } }
# custom_field_values: { custom_field_id => value }, applied to every issue whose tracker uses the field
# Returns the created issues, or [] with #errors filled in.
def create_issues(project:, rows:, custom_field_values: {}, author: User.current)
@errors = []
rows = (rows || {}).to_h.transform_keys(&:to_s)
selected = proposals.reject(&:created?).select { |p| rows.dig(p.line_id, 'selected') == '1' }
if selected.empty?
@errors << l(:error_no_estimate_lines_selected)
return []
end
allowed_trackers = Issue.allowed_target_trackers(project, author).to_a
built = selected.map do |proposal|
[proposal, build_issue(proposal, rows[proposal.line_id] || {}, project, author, allowed_trackers, custom_field_values)]
end
Issue.transaction do
built.each do |proposal, issue|
next if issue.save
@errors << "#{proposal.description.truncate(60)}: #{issue.errors.full_messages.join(', ')}"
end
raise ActiveRecord::Rollback if @errors.any?
built.each do |proposal, issue|
# Clear a link left behind by an issue that no longer exists, then record the new one
QboEstimateLineIssue.where(estimate_id: estimate.id, line_id: proposal.line_id)
.where.not(issue_id: Issue.select(:id)).delete_all
QboEstimateLineIssue.create!(estimate_id: estimate.id, line_id: proposal.line_id, issue: issue)
end
relate_issues(built.map(&:last))
end
@errors.any? ? [] : built.map(&:last)
rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
# Someone else created issues from the same lines at the same moment
@errors << l(:error_estimate_lines_already_created)
[]
end
private
def build_proposals
return [] if estimate.blank?
codes = self.class.item_codes
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|
detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil
next if detail.nil? || detail.item_ref.nil?
item_name = detail.item_ref.name.to_s.strip
next unless self.class.item_matches?(item_name, codes)
# The subject comes from the line's description, so lines without one are skipped
description = line.description.to_s.strip
next if description.blank?
line_id = line_key(line, index)
quantity = detail.respond_to?(:quantity) ? detail.quantity.to_f : 0.0
Proposal.new(
line_id: line_id,
item_name: item_name,
description: description,
hours: quantity.positive? ? quantity : nil,
existing_issue: links[line_id]&.issue
)
end
end
# QBO line Ids are stable for the life of the estimate; fall back to line number / position
def line_key(line, index)
key = line.respond_to?(:id) ? line.id : nil
key = line.line_num if key.blank? && line.respond_to?(:line_num)
key = "pos-#{index}" if key.blank?
key.to_s
end
# Relates the new issues to each other and to every issue created earlier from the same estimate.
def relate_issues(new_issues)
earlier = QboEstimateLineIssue.where(estimate_id: estimate.id)
.where.not(issue_id: new_issues.map(&:id))
.includes(:issue)
.filter_map(&:issue)
self.class.relate_all(earlier + new_issues)
end
def build_issue(proposal, row, project, author, allowed_trackers, custom_field_values)
issue = Issue.new(project: project, author: author)
issue.tracker = allowed_trackers.detect { |t| t.id == row['tracker_id'].to_i }
# Shared custom field values. Going through safe_attributes means fields the tracker doesn't
# use, or that this user can't edit (hidden / read-only by workflow), are ignored.
if custom_field_values.present? && issue.tracker
issue.send(:safe_attributes=, { 'custom_field_values' => custom_field_values.to_h }, author)
end
issue.subject = (row['subject'].presence || proposal.description).to_s.strip.truncate(255)
template = IssueTemplateSupport.find(row['template'], project)
issue.description = template&.description.presence || default_description
hours = row.key?('estimated_hours') ? row['estimated_hours'] : proposal.hours
issue.estimated_hours = hours.presence
issue.start_date = defaults[:start_date] if defaults[:start_date]
issue.due_date = defaults[:due_date] if defaults[:due_date]
# Only assign someone who can be assigned in this project
assignee = defaults[:assignee]
issue.assigned_to = assignee if assignee && issue.assignable_users.include?(assignee)
# Customer / vehicle / estimate fields are added to issues by redmine_qbo and redmine_qbo_vehicles
issue.customer_id = estimate.customer_id if issue.respond_to?(:customer_id=)
issue.vehicle_id = vehicle_id if issue.respond_to?(:vehicle_id=)
issue.estimate_id = estimate.id if issue.respond_to?(:estimate_id=)
issue
end
# The vehicle from the hook, or the customer's vehicle whose VIN is on the estimate
def vehicle_id
return defaults[:vehicle_id] if defaults[:vehicle_id].present?
customer = estimate.customer
return nil unless customer.respond_to?(:vehicles)
vin = EstimateWriter.custom_value(estimate.details, Company.vin_field, Company::VIN_NAME).to_s.strip
return nil if vin.empty?
customer.vehicles.detect { |v| v.vin.to_s.casecmp?(vin) }&.id
rescue StandardError
nil
end
def default_description
defaults[:description].presence ||
"The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number}"
end
end
end
+423
View File
@@ -0,0 +1,423 @@
#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
# Reads QuickBooks estimates into an EstimateForm and writes forms back as estimates.
#
# Subtotal rows are saved the way QuickBooks saves the subtotals added on its own estimate screen: a
# description-only line reading "Subtotal: $342.60", which prints where it was placed. The subtotal
# QuickBooks always adds after the last line isn't shown (QuickBooks adds it back). Discount lines are kept
# as they are, and estimates with bundle (group) lines are read-only so a bundle can't be broken up.
#
# Estimate numbers are never typed: QuickBooks numbers new estimates, or when its custom transaction
# numbers are on, the next number is filled in when the estimate is created.
module EstimateWriter
class Error < StandardError; end
# The estimate was saved in QuickBooks (by someone else, or in another tab) after the form was opened
class Conflict < Error; end
# How QuickBooks writes a subtotal line, e.g. "Subtotal: $1,342.60"
SUBTOTAL_TEXT = /\ASubtotal:\s*-?\$?-?[\d,]*(\.\d+)?\s*\z/i
module_function
# A blank estimate for the customer, filled in the way QuickBooks starts a new estimate
def new_form(customer: nil, user: User.current)
EstimateForm.new(
customer_id: customer&.id,
customer_name: customer&.name,
email: customer_email(customer),
billing_address: customer_address(customer),
txn_date: user.today.iso8601,
expiration_date: default_expiration_date(user.today)&.iso8601,
sales_person: user.name,
customer_memo: Company.estimate_message,
lines: Array.new(2) { EstimateForm::Line.new(quantity: '', taxable: true) }
)
end
# Creates an estimate for another plugin (e.g. redmine_qbo_lineitems billing an issue's line items), so
# estimates are only ever built here. Each line is a hash of :description, :item_id, :quantity, :rate,
# :taxable (a line with only a description is a note line). Returns the saved QuickBooks estimate.
def create_estimate(customer:, lines:, private_note: nil, vin: nil, mileage: nil, user: nil, txn_date: Date.today)
form = EstimateForm.new(
customer_id: customer.id,
customer_name: customer.name,
email: customer_email(customer),
txn_date: txn_date.iso8601,
expiration_date: default_expiration_date(txn_date)&.iso8601,
vin: vin.to_s,
mileage: mileage.to_s,
customer_memo: Company.estimate_message,
private_note: private_note.to_s,
lines: lines.map do |line|
line = line.to_h.symbolize_keys
EstimateForm::Line.new(
item_id: line[:item_id]&.to_s.presence,
description: line[:description].to_s,
quantity: plain_number(line[:quantity]),
rate: plain_number(line[:rate]),
taxable: line.fetch(:taxable, true) ? true : false
)
end
)
save(form, user: user)
end
# A new estimate copied from an existing one: same customer, lines, VIN and messages, dated today, with a
# new number, the current user as sales person, and no discounts or bundles (those stay in QuickBooks)
def duplicate_form(id, user: User.current)
source = load(id)
today = user.today
EstimateForm.new(
customer_id: source.customer_id,
customer_name: source.customer_name,
email: source.email,
billing_address: source.billing_address,
txn_date: today.iso8601,
expiration_date: default_expiration_date(today)&.iso8601,
sales_person: user.name,
vin: source.vin,
mileage: source.mileage,
customer_memo: source.customer_memo,
private_note: source.private_note,
lines: source.lines.map do |line|
EstimateForm::Line.new(kind: line.kind, item_id: line.item_id, item_name: line.item_name,
description: line.description, quantity: line.quantity, rate: line.rate,
taxable: line.taxable)
end
).tap { |form| form.duplicated_from = source.doc_number }
end
# Issues linked to the estimate (redmine_qbo's issue estimate field)
def linked_issues(estimate_id)
return Issue.none if estimate_id.blank?
Issue.where(estimate_id: estimate_id.to_s)
end
# Loads the estimate from QuickBooks for editing
def load(id)
remote = QboEstimateService.with_service { |service| service.fetch_by_id(id) }
raise Error, I18n.t(:notice_estimate_not_found) unless remote
form_from_remote(remote)
end
# Creates or updates the estimate in QuickBooks and returns the saved QuickBooks estimate.
# The sales person is the user who creates the estimate; editing keeps the original one.
def save(form, user: User.current)
customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
saved = QboEstimateService.with_service do |service|
if form.persisted?
remote = service.fetch_by_id(form.id)
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 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?
estimate = Quickbooks::Model::Estimate.new
estimate.id = remote.id
estimate.sync_token = remote.sync_token
apply(form, estimate, customer: customer, remote: remote, user: user)
service.update(estimate, sparse: true)
else
estimate = Quickbooks::Model::Estimate.new
apply(form, estimate, customer: customer, remote: nil, user: user)
service.create(estimate)
end
end
raise Error, I18n.t(:error_estimate_not_saved) unless saved
sync_local(saved)
saved
end
# Emails the estimate; QuickBooks uses its own estimate email template
def send_email(id, email)
sent = QboEstimateService.with_service { |service| service.send_estimate(id, email) }
raise Error, I18n.t(:error_estimate_not_sent) unless sent
sent
end
# ---- QuickBooks estimate -> form ----
def form_from_remote(remote)
EstimateForm.new(
id: remote.id.to_s,
sync_token: remote.sync_token.to_s,
customer_id: remote.customer_ref&.value.to_s,
customer_name: remote.customer_ref&.name.presence || Customer.find_by(id: remote.customer_ref&.value)&.name,
email: remote.bill_email&.address.to_s,
billing_address: format_address(remote.billing_address),
txn_date: remote.txn_date&.iso8601,
expiration_date: remote.expiration_date&.iso8601,
doc_number: remote.doc_number.to_s,
sales_person: custom_value(remote, Company.sales_person_field, Company::SALES_PERSON_NAME),
vin: custom_value(remote, Company.vin_field, Company::VIN_NAME),
mileage: custom_value(remote, Company.mileage_field, Company::MILEAGE_NAME),
customer_memo: remote.customer_memo.to_s,
private_note: remote.private_note.to_s,
lines: tidy_subtotals(Array(remote.line_items).filter_map { |line| line_from_remote(line) }),
total: remote.total,
total_tax: remote.txn_tax_detail&.total_tax,
discount: discount_total(remote),
email_status: remote.email_status.to_s,
txn_status: remote.txn_status.to_s,
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)]
}.uniq,
# Read-only when it has bundles, or once an issue is linked to it (the work is under way)
locked: (:bundles if group_lines?(remote)) || (:linked if linked_issues(remote.id).any?)
)
end
def line_from_remote(line)
if line.sales_item?
detail = line.sales_line_item_detail
EstimateForm::Line.new(
id: line.id.to_s,
item_id: detail&.item_ref&.value.to_s.presence,
item_name: detail&.item_ref&.name.to_s,
description: line.description.to_s,
quantity: plain_number(detail&.quantity),
rate: plain_number(detail&.unit_price),
taxable: detail&.tax_code_ref&.value.to_s == 'TAX',
time_activity_id: linked_time_activity_id(line)
)
elsif line.description_only? && line.description.to_s.strip.match?(SUBTOTAL_TEXT)
EstimateForm::Line.new(id: line.id.to_s, kind: EstimateForm::Line::SUBTOTAL)
elsif line.description_only?
EstimateForm::Line.new(id: line.id.to_s, description: line.description.to_s)
end
# QuickBooks' own subtotal (always after the last line), discount and group lines aren't edited here
end
# The custom field's value, found by the field QuickBooks' preferences name, or by name on the estimate
def custom_value(remote, field, name_pattern)
fields = Array(remote.custom_fields)
match = fields.detect { |f| field && f.id.to_i == field.id.to_i } ||
fields.detect { |f| f.name.to_s =~ name_pattern && (name_pattern == Company::VIN_NAME || f.name.to_s !~ Company::VIN_NAME) }
match&.string_value.to_s
end
# ---- form -> QuickBooks estimate ----
def apply(form, estimate, customer:, remote:, user:)
estimate.customer_id = customer.id
# QuickBooks copies the customer's billing address only when an estimate is created
if remote.nil? || remote.customer_ref&.value.to_s != customer.id.to_s
address = customer_details(customer)&.billing_address
estimate.billing_address = address if address
end
estimate.bill_email = Quickbooks::Model::EmailAddress.new(form.email) if form.email.present?
estimate.txn_date = form.txn_date_value
estimate.expiration_date = form.expiration_date_value
# Numbers aren't typed. With QuickBooks' custom transaction numbers on, it doesn't number estimates
# made by apps, so the next number is filled in here.
estimate.doc_number = next_doc_number if remote.nil? && Company.custom_txn_numbers?
estimate.customer_memo = form.customer_memo.to_s
estimate.private_note = form.private_note.to_s
estimate.custom_fields = build_custom_fields(form, remote, user)
estimate.line_items = build_lines(form, remote)
estimate
end
# Keeps every custom field already on the estimate, then sets the VIN, and the sales person on create
# (left empty for estimates made without a user, e.g. by a background job)
# sales_person: who to name instead of the user (e.g. an invoice names the estimate's sales person)
def build_custom_fields(form, remote, user, sales_person: nil)
fields = {}
Array(remote&.custom_fields).each do |f|
next unless f.type.to_s == 'StringType' || f.string_value.present?
fields[f.id.to_i] = string_field(f.id, f.name, f.string_value)
end
if (vin = Company.vin_field)
fields[vin.id.to_i] = string_field(vin.id, vin.name, form.vin.to_s.strip.upcase)
end
if (mileage = Company.mileage_field)
fields[mileage.id.to_i] = string_field(mileage.id, mileage.name, form.mileage.to_s.strip)
end
sales = Company.sales_person_field
name = sales_person.presence || user&.name
if sales && remote.nil? && name.present?
fields[sales.id.to_i] = string_field(sales.id, sales.name, name)
end
fields.values
end
def string_field(id, name, value)
field = Quickbooks::Model::CustomField.new
field.id = id.to_i
field.name = name
field.type = 'StringType'
field.string_value = value.to_s
field
end
def build_lines(form, remote)
remote_ids = Array(remote&.line_items).map { |l| l.id.to_s }
section = BigDecimal('0')
lines = tidy_subtotals(form.filled_lines).map.with_index(1) do |line, number|
built = build_line(line, number, keep_id: remote_ids.include?(line.id.to_s), section_total: section)
section = line.subtotal? ? BigDecimal('0') : section + (line.description_only? ? BigDecimal('0') : built.amount)
built
end
# Discounts keep their place after the lines
Array(remote&.line_items).select(&:discount_item?).each do |discount|
discount.line_num = lines.size + 1
lines << discount
end
lines
end
def build_line(line, number, keep_id:, section_total: BigDecimal('0'))
remote = Quickbooks::Model::InvoiceLineItem.new
remote.id = line.id if keep_id
remote.line_num = number
# Saved like QuickBooks saves its subtotals: a description line with the total of its section
if line.subtotal?
remote.description = subtotal_text(section_total)
remote.description_only!
return remote
end
remote.description = line.description
if line.description_only?
remote.description_only!
return remote
end
rate = line.rate_value
rate ||= Item.find_by(id: line.item_id)&.unit_price if line.item?
rate ||= BigDecimal('0')
quantity = line.quantity_value || BigDecimal('1')
remote.amount = (quantity * rate).round(2)
link_time_activity(remote, line.time_activity_id)
remote.sales_item! do |detail|
detail.item_ref = Quickbooks::Model::BaseReference.new(line.item_id) if line.item?
detail.quantity = quantity
detail.unit_price = rate
detail.tax_code_ref = Quickbooks::Model::BaseReference.new(line.taxable? ? 'TAX' : 'NON')
end
remote
end
# ---- helpers ----
TIME_ACTIVITY = 'TimeActivity'.freeze
# The time activity an invoice line bills, if any
def linked_time_activity_id(line)
return nil unless line.respond_to?(:linked_transactions)
Array(line.linked_transactions).detect { |t| t.txn_type.to_s == TIME_ACTIVITY }&.txn_id&.to_s
end
# Links an invoice line to the time activity it bills (TxnLineId is always 1 for time activities)
def link_time_activity(remote_line, time_activity_id)
return if time_activity_id.blank? || !remote_line.respond_to?(:linked_transactions=)
remote_line.linked_transactions = [
Quickbooks::Model::LinkedTransaction.new(txn_id: time_activity_id.to_s, txn_type: TIME_ACTIVITY, txn_line_id: '1')
]
end
# Drops subtotals with nothing to total (at the top, or right after another subtotal)
def tidy_subtotals(lines)
tidy = []
lines.each do |line|
next if line.subtotal? && (tidy.empty? || tidy.last.subtotal?)
tidy << line
end
tidy
end
# "Subtotal: $1,342.60", as QuickBooks writes it
def subtotal_text(amount)
value = BigDecimal(amount.to_s).round(2)
whole, cents = format('%.2f', value.abs).split('.')
"Subtotal: #{'-' if value.negative?}$#{whole.reverse.scan(/\d{1,3}/).join(',').reverse}.#{cents}"
end
# Discount lines aren't edited here but count toward the total shown
def discount_total(remote)
discounts = Array(remote.line_items).select(&:discount_item?)
discounts.empty? ? nil : discounts.sum(BigDecimal('0')) { |l| l.amount || BigDecimal('0') }
end
def group_lines?(remote)
Array(remote.line_items).any?(&:group_line_detail?)
end
# Updates the local estimate record so it shows on the customer page right away
def sync_local(saved)
EstimateSyncService.new.sync_by_id(saved.id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Saved estimate #{saved.id} but could not sync it locally: #{e.message}"
end
# The plugin setting "Estimates expire after (days)"; blank or 0 leaves the expiration date empty
def expiration_days
Setting.plugin_redmine_qbo['expiration_days'].to_i
rescue StandardError
0
end
def default_expiration_date(from)
expiration_days.positive? ? from + expiration_days : nil
end
# One more than the highest estimate (or invoice) number used so far
def next_doc_number(model = Estimate)
numbers = model.order(id: :desc).limit(500).pluck(:doc_number).filter_map { |n| Integer(n.to_s, 10) rescue nil }
numbers.empty? ? nil : (numbers.max + 1).to_s
end
def customer_details(customer)
customer&.details
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not load customer #{customer&.id} from QuickBooks: #{e.message}"
nil
end
def customer_email(customer)
customer_details(customer)&.email_address&.address.to_s
end
def customer_address(customer)
format_address(customer_details(customer)&.billing_address)
end
# Address lines as QuickBooks prints them: street lines, then "City, ST 12345"
def format_address(address)
return '' unless address
street = [address.line1, address.line2, address.line3, address.line4, address.line5].map { |l| l.to_s.strip }.reject(&:empty?)
region = [address.country_sub_division_code, address.postal_code].map { |l| l.to_s.strip }.reject(&:empty?).join(' ')
locality = [address.city.to_s.strip, region].reject(&:empty?).join(', ')
(street + [locality]).reject(&:empty?).join("\n")
end
# 2.0 -> "2", 12.50 -> "12.5"; the editor formats rates for display
def plain_number(value)
return '' if value.nil? || value.to_s.strip.empty?
BigDecimal(value.to_s).to_s('F').sub(/\.0+\z/, '').sub(/(\.\d*?)0+\z/, '\1')
end
end
end
@@ -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.
module RedmineQboBilling
module Hooks
# Each work order's mileage, from Redmine's own issue custom field named "Mileage" (any capitalisation),
# so an invoice's mileage box fills in when its time or estimates are imported. Answers the same
# qbo_billing_issue_values hook other plugins use (see IssueValues).
class IssueMileageListener < Redmine::Hook::Listener
def qbo_billing_issue_values(context = {})
issue_ids = Array(context[:issues]).map(&:id)
field = IssueCustomField.all.detect { |f| f.name.to_s.strip.casecmp?('mileage') }
return {} if field.nil? || issue_ids.empty?
values = CustomValue.where(customized_type: 'Issue', customized_id: issue_ids, custom_field_id: field.id)
.where.not(value: [nil, ''])
.pluck(:customized_id, :value)
{ mileage: values.to_h }
end
end
end
end
@@ -0,0 +1,29 @@
#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
module Hooks
# Adds the product/service list and income accounts to redmine_qbo's syncs
class QboHookListener < Redmine::Hook::Listener
# Called by WebhookProcessJob
def qbo_additional_entities(context = {})
["Item", "Account"]
end
# Called by the QboSyncDispatcher. Accounts first: items reference their income account.
def qbo_full_sync(context = {})
[Account, Item]
end
end
end
end
+401
View File
@@ -0,0 +1,401 @@
#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
# Reads QuickBooks invoices into an EstimateForm (document "invoice") and writes forms back as invoices.
# Lines, subtotals, discounts, custom fields and addresses work exactly as on estimates (EstimateWriter).
#
# On top of that an invoice can take lines from elsewhere:
# * an estimate converted to an invoice, or open estimates imported into it (e.g. the ones
# redmine_qbo_lineitems makes for parts that weren't quoted). Those estimates are linked to the invoice
# and closed when it's saved.
# * billable QuickBooks time activities (the ones redmine_qbo makes from an issue's time entries). Each
# becomes a line linked to its time activity, so QuickBooks marks the time as billed.
#
# An invoice with a payment applied to it is read-only, so a paid invoice can't be changed under the payment.
module InvoiceWriter
Error = EstimateWriter::Error
Conflict = EstimateWriter::Conflict
ESTIMATE = 'Estimate'.freeze
TIME_ACTIVITY = EstimateWriter::TIME_ACTIVITY
# Estimates in these states can still be imported (Converted/Closed ones are already invoiced, Rejected ones lost)
OPEN_ESTIMATE_STATUSES = ['', 'Pending', 'Accepted'].freeze
# How QuickBooks marks an invoiced estimate: Converted when it made the invoice, Closed when closed by hand
BILLED_ESTIMATE_STATUSES = %w[Converted Closed].freeze
# How far back to look for billable time if QuickBooks won't filter time activities by customer
TIME_LOOKBACK = 400
module_function
def writer
EstimateWriter
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
def new_form(customer: nil, user: User.current)
EstimateForm.new(
document: 'invoice',
customer_id: customer&.id,
customer_name: customer&.name,
email: writer.customer_email(customer),
billing_address: writer.customer_address(customer),
txn_date: user.today.iso8601,
sales_person: user.name,
customer_memo: Company.invoice_message,
lines: Array.new(2) { EstimateForm::Line.new(quantity: '', taxable: true) }
)
end
# A new invoice from an estimate, like QuickBooks' "Create invoice" on an estimate: the estimate's
# customer, lines, subtotals and VIN. The estimate is linked and closed when the invoice is saved.
def from_estimate(estimate_id, user: User.current)
remote = QboEstimateService.with_service { |service| service.fetch_by_id(estimate_id) }
raise Error, I18n.t(:notice_estimate_not_found) unless remote
# An estimate is billed once
billed = billing_error(remote)
raise Error, billed if billed
source = writer.form_from_remote(remote)
customer = Customer.find_by(id: source.customer_id)
new_form(customer: customer, user: user).tap do |form|
form.customer_name = source.customer_name if customer.nil?
form.customer_id = source.customer_id
form.email = source.email.presence || form.email
form.billing_address = source.billing_address.presence || form.billing_address
form.vin = source.vin
form.mileage = source.mileage
# The estimate's writer sells the job; with no one on the estimate, whoever writes the invoice
form.sales_person = source.sales_person.presence || user.name
form.private_note = source.private_note
form.lines = copy_lines(source.lines)
form.linked_estimate_ids = [source.id.to_s]
form.converted_from = source.doc_number
end
end
def load(id)
remote = QboInvoiceService.with_service { |service| service.fetch_by_id(id) }
raise Error, I18n.t(:notice_invoice_not_found) unless remote
form_from_remote(remote)
end
# Creates or updates the invoice in QuickBooks, closes the estimates it was made from, and returns the
# saved QuickBooks invoice. The sales person is the one on the estimate it was made from (the first linked
# estimate that names one), or else the user who creates it; editing keeps the original one.
def save(form, user: User.current)
customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
saved = QboInvoiceService.with_service do |service|
if form.persisted?
remote = service.fetch_by_id(form.id)
raise Error, I18n.t(:notice_invoice_not_found) unless remote
raise Conflict, I18n.t(:error_invoice_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
raise Error, I18n.t(:error_invoice_has_bundles) if writer.group_lines?(remote)
raise Error, I18n.t(:error_invoice_paid) if paid?(remote)
check_not_billed(form.linked_estimate_ids - linked_ids(remote, ESTIMATE))
invoice = Quickbooks::Model::Invoice.new
invoice.id = remote.id
invoice.sync_token = remote.sync_token
apply(form, invoice, customer: customer, remote: remote, user: user)
service.update(invoice, sparse: true)
else
check_not_billed(form.linked_estimate_ids)
invoice = Quickbooks::Model::Invoice.new
apply(form, invoice, customer: customer, remote: nil, user: user,
sales_person: estimate_sales_person(form.linked_estimate_ids))
service.create(invoice)
end
end
raise Error, I18n.t(:error_invoice_not_saved) unless saved
sync_local(saved)
close_estimates(linked_ids(saved, ESTIMATE).presence || form.linked_estimate_ids)
saved
end
def send_email(id, email)
sent = QboInvoiceService.with_service { |service| service.send_invoice(id, email) }
raise Error, I18n.t(:error_invoice_not_sent) unless sent
sent
end
# ---- QuickBooks invoice -> form ----
def form_from_remote(remote)
EstimateForm.new(
document: 'invoice',
id: remote.id.to_s,
sync_token: remote.sync_token.to_s,
customer_id: remote.customer_ref&.value.to_s,
customer_name: remote.customer_ref&.name.presence || Customer.find_by(id: remote.customer_ref&.value)&.name,
email: remote.bill_email&.address.to_s,
billing_address: writer.format_address(remote.billing_address),
txn_date: remote.txn_date&.iso8601,
due_date: remote.due_date&.iso8601,
doc_number: remote.doc_number.to_s,
sales_person: writer.custom_value(remote, Company.sales_person_field, Company::SALES_PERSON_NAME),
vin: writer.custom_value(remote, Company.vin_field, Company::VIN_NAME),
mileage: writer.custom_value(remote, Company.mileage_field, Company::MILEAGE_NAME),
customer_memo: remote.customer_memo.to_s,
private_note: remote.private_note.to_s,
lines: writer.tidy_subtotals(Array(remote.line_items).filter_map { |line| writer.line_from_remote(line) }),
linked_estimate_ids: linked_ids(remote, ESTIMATE),
total: remote.total,
total_tax: remote.txn_tax_detail&.total_tax,
discount: writer.discount_total(remote),
balance: remote.balance,
email_status: remote.email_status.to_s,
locked: (:bundles if writer.group_lines?(remote)) || (:paid if paid?(remote))
)
end
# A payment is applied once the balance is less than the total
def paid?(remote)
return false if remote.balance.nil? || remote.total.nil?
BigDecimal(remote.balance.to_s) < BigDecimal(remote.total.to_s)
end
def linked_ids(remote, type)
Array(remote&.linked_transactions).select { |t| t.txn_type.to_s == type }.map { |t| t.txn_id.to_s }.uniq
end
# ---- form -> QuickBooks invoice ----
def apply(form, invoice, customer:, remote:, user:, sales_person: nil)
invoice.customer_id = customer.id
if remote.nil? || remote.customer_ref&.value.to_s != customer.id.to_s
address = writer.customer_details(customer)&.billing_address
invoice.billing_address = address if address
end
invoice.bill_email = Quickbooks::Model::EmailAddress.new(form.email) if form.email.present?
invoice.txn_date = form.txn_date_value
# Left out when empty: QuickBooks works it out from the customer's terms
invoice.due_date = form.due_date_value if form.due_date_value
invoice.doc_number = writer.next_doc_number(Invoice) if remote.nil? && Company.custom_txn_numbers?
invoice.customer_memo = form.customer_memo.to_s
invoice.private_note = form.private_note.to_s
invoice.custom_fields = writer.build_custom_fields(form, remote, user, sales_person: sales_person)
invoice.line_items = writer.build_lines(form, remote)
invoice.linked_transactions = header_links(form, remote)
invoice
end
# The invoice-level links: the estimates it was made from, and every time activity a line bills
# (QuickBooks wants time linked both on the line and on the invoice)
def header_links(form, remote)
estimates = (linked_ids(remote, ESTIMATE) + form.linked_estimate_ids).uniq
times = form.filled_lines.filter_map(&:time_activity_id).map(&:to_s).uniq
estimates.map { |id| link(id, ESTIMATE) } + times.map { |id| link(id, TIME_ACTIVITY) }
end
def link(id, type)
Quickbooks::Model::LinkedTransaction.new(txn_id: id.to_s, txn_type: type)
end
# The sales person on the first of the estimates that names one (estimates redmine_qbo_lineitems makes
# have none), so the invoice credits whoever wrote the estimate
def estimate_sales_person(estimate_ids)
field = Company.sales_person_field
return nil if field.nil? || Array(estimate_ids).empty?
QboEstimateService.with_service do |service|
Array(estimate_ids).each do |id|
estimate = service.fetch_by_id(id)
name = estimate && writer.custom_value(estimate, field, Company::SALES_PERSON_NAME)
return name if name.present?
end
nil
end
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read the estimate's sales person: #{e.message}"
nil
end
# ---- billing an estimate once ----
# Why the estimate can't be billed, or nil: it's already on an invoice (linked to one, or closed, which is
# how QuickBooks marks an invoiced estimate), or the customer rejected it
def billing_error(estimate)
number = estimate.doc_number.to_s
invoice_id = linked_ids(estimate, 'Invoice').first
if invoice_id
I18n.t(:error_estimate_already_invoiced, number: number, invoice: invoice_number(invoice_id))
elsif BILLED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s)
I18n.t(:error_estimate_closed_billed, number: number, status: estimate.txn_status.to_s)
elsif estimate.txn_status.to_s == 'Rejected'
I18n.t(:error_estimate_rejected, number: number)
end
end
# Checked against QuickBooks when saving, since an estimate can be invoiced elsewhere (another tab, another
# user, QuickBooks itself) after the invoice page was opened. Estimates already on this invoice aren't checked.
def check_not_billed(estimate_ids)
ids = Array(estimate_ids).map(&:to_s).reject(&:blank?).uniq
return if ids.empty?
errors = QboEstimateService.with_service do |service|
ids.filter_map do |id|
estimate = service.fetch_by_id(id)
estimate ? billing_error(estimate) : I18n.t(:notice_estimate_not_found)
end
end
raise Error, errors.join(' ') if errors.any?
end
# The invoice's number when it's synced locally, else its QuickBooks id
def invoice_number(invoice_id)
Invoice.find_by(id: invoice_id)&.doc_number.presence || invoice_id.to_s
rescue StandardError
invoice_id.to_s
end
# Marks the estimates as closed (invoiced), as QuickBooks does when it converts one. Done separately
# so it also happens if QuickBooks doesn't close a linked estimate by itself.
def close_estimates(ids)
Array(ids).uniq.each do |id|
QboEstimateService.with_service do |service|
estimate = service.fetch_by_id(id)
# Already Converted or Closed is left as QuickBooks set it
next if estimate.nil? || BILLED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s)
update = Quickbooks::Model::Estimate.new
update.id = estimate.id
update.sync_token = estimate.sync_token
update.customer_ref = estimate.customer_ref
update.txn_status = 'Closed'
service.update(update, sparse: true)
end
EstimateSyncService.new.sync_by_id(id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not close estimate #{id}: #{e.message}"
end
end
# ---- importing ----
# What can be pulled into an invoice for the customer: billable time and open estimates, and the VIN and
# mileage plugins give for their work orders (and for issues already on the invoice: issue_ids)
def import_options(customer, issue_ids: [])
times = open_time_activities(customer)
estimates = open_estimates(customer)
ids = (times.map { |t| t[:issue_id] } + estimates.map { |e| e[:issue_id] } + Array(issue_ids)).compact.map(&:to_s).uniq
issues = ids.empty? ? [] : Issue.where(id: ids).to_a
{ time_activities: times, estimates: estimates, issue_values: IssueValues.by_issue(issues) }
end
# The customer's QuickBooks time activities that are still billable (not yet on an invoice)
def open_time_activities(customer)
activities = QboConnectionService.with_qbo_service(entity: 'TimeActivity') do |service|
begin
service.query("SELECT * FROM TimeActivity WHERE CustomerRef = '#{customer.id.to_i}' ORDERBY TxnDate", per_page: 1000).entries
rescue StandardError
# Not every company lets time be filtered by customer: look at recent time instead
since = (Date.today - TIME_LOOKBACK).iso8601
service.query("SELECT * FROM TimeActivity WHERE TxnDate >= '#{since}' ORDERBY TxnDate", per_page: 1000).entries
end
end
Array(activities).select { |a| a.customer_ref&.value.to_s == customer.id.to_s && a.billable_status.to_s == 'Billable' }
.map { |a| time_activity_hash(a) }
end
def time_activity_hash(activity)
hours = activity_hours(activity)
rate = EstimateForm.decimal(activity.hourly_rate) || BigDecimal('0')
item = Item.find_by(id: activity.item_ref&.value) if activity.item_ref&.value.present?
{
id: activity.id.to_s,
date: activity.txn_date.to_s,
employee: activity.employee_ref&.name || activity.vendor_ref&.name,
item_id: activity.item_ref&.value.to_s.presence,
item_name: activity.item_ref&.name.presence || item&.name,
description: activity.description.to_s,
issue_id: issue_reference(activity.description),
quantity: writer.plain_number(hours),
rate: writer.plain_number(rate),
amount: (hours * rate).round(2).to_s('F'),
taxable: item ? item.taxable != false : false
}
end
# Hours and minutes, or start and end time less the break
def activity_hours(activity)
if activity.hours || activity.minutes
(BigDecimal(activity.hours.to_i.to_s) + BigDecimal(activity.minutes.to_i.to_s) / 60).round(4)
elsif activity.start_time && activity.end_time
minutes = ((activity.end_time.to_time - activity.start_time.to_time) / 60).round -
(activity.break_hours.to_i * 60 + activity.break_minutes.to_i)
(BigDecimal([minutes, 0].max.to_s) / 60).round(4)
else
BigDecimal('0')
end
end
# The customer's open estimates, each with its lines ready to add to an invoice
def open_estimates(customer)
estimates = QboEstimateService.with_service do |service|
service.query("SELECT * FROM Estimate WHERE CustomerRef = '#{customer.id.to_i}' ORDERBY TxnDate DESC", per_page: 100).entries
end
Array(estimates).select { |e| billing_error(e).nil? && OPEN_ESTIMATE_STATUSES.include?(e.txn_status.to_s) && !writer.group_lines?(e) }.map do |e|
lines = writer.tidy_subtotals(Array(e.line_items).filter_map { |line| writer.line_from_remote(line) })
linked_issue = writer.linked_issues(e.id).first
{
id: e.id.to_s,
doc_number: e.doc_number.to_s,
date: e.txn_date.to_s,
total: e.total.to_s,
issue: linked_issue&.then { |i| "#{i.tracker} ##{i.id}: #{i.subject}" },
# Lines from this estimate go next to the invoice's time for the same issue
issue_id: issue_reference(lines.detect { |l| l.description.present? }&.description) || linked_issue&.id&.to_s,
lines: lines.map { |l| line_hash(l) }
}
end
end
def issue_reference(text)
IssueValues.issue_reference(text)
end
def line_hash(line)
{ kind: line.kind, item_id: line.item_id, item_name: line.item_name, description: line.description,
quantity: line.quantity, rate: line.rate, taxable: line.taxable? }
end
# ---- helpers ----
# Lines copied to a new document: no line ids, everything else as it was
def copy_lines(lines)
lines.map do |line|
EstimateForm::Line.new(kind: line.kind, item_id: line.item_id, item_name: line.item_name,
description: line.description, quantity: line.quantity, rate: line.rate,
taxable: line.taxable, time_activity_id: line.time_activity_id)
end
end
def sync_local(saved)
InvoiceSyncService.new.sync_by_id(saved.id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Saved invoice #{saved.id} but could not sync it locally: #{e.message}"
end
end
end
@@ -0,0 +1,72 @@
#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 issue custom fields shown on the "Create issues from estimate" page.
#
# For every tracker the user may pick, a sample new issue is built in the target project to find
# which custom fields the user can edit, and which are required (either the field's own
# "Required" flag or a workflow rule for that tracker / role). Values are entered once on the page
# and applied to every created issue whose tracker uses that field.
class IssueFieldSet
# File uploads can't be handled by this shared form
UNSUPPORTED_FORMATS = %w[attachment].freeze
Field = Struct.new(:custom_field, :custom_value, :tracker_ids, :required_tracker_ids, keyword_init: true) do
def id
custom_field.id
end
def required_for_any?
required_tracker_ids.any?
end
end
attr_reader :fields
# values: the submitted { custom_field_id => value } hash, used to refill the form after errors
def initialize(project:, trackers:, user: User.current, values: {})
@fields = []
by_id = {}
Array(trackers).each do |tracker|
issue = Issue.new(project: project, author: user)
issue.tracker = tracker
issue.editable_custom_field_values(user).each do |custom_value|
custom_field = custom_value.custom_field
next if UNSUPPORTED_FORMATS.include?(custom_field.field_format)
field = by_id[custom_field.id] ||= Field.new(
custom_field: custom_field,
custom_value: custom_value,
tracker_ids: [],
required_tracker_ids: []
)
field.tracker_ids << tracker.id
if custom_field.is_required? || issue.required_attribute?(custom_field.id.to_s, user)
field.required_tracker_ids << tracker.id
end
end
end
@fields = by_id.values.sort_by { |f| [f.required_for_any? ? 0 : 1, f.custom_field.position.to_i] }
values = (values || {}).to_h.transform_keys(&:to_s)
@fields.each do |field|
field.custom_value.value = values[field.id.to_s] if values.key?(field.id.to_s)
end
end
def any?
@fields.any?
end
end
end
@@ -0,0 +1,58 @@
#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
# Optional support for redmine_issue_templates (https://github.com/agileware-jp/redmine_issue_templates).
# Everything here returns empty results when that plugin isn't installed or isn't enabled on the project.
module IssueTemplateSupport
Option = Struct.new(:key, :title, :tracker_id, :is_default, :description, :group, keyword_init: true)
module_function
def installed?
defined?(::IssueTemplate) && defined?(::GlobalIssueTemplate) && defined?(::IssueTemplateSetting)
end
def enabled_for?(project)
!!(installed? && project&.module_enabled?(:issue_templates))
end
# Templates usable in the project: its own, those shared by parent projects, and global ones.
def templates_for(project)
return [] unless enabled_for?(project)
own = ::IssueTemplate.get_templates_for_project_tracker(project.id).to_a
inherited = Array(::IssueTemplateSetting.find_or_create(project.id).get_inherit_templates).to_a
global = ::GlobalIssueTemplate.get_templates_for_project_tracker(project.id).to_a
(own + inherited).uniq.map { |t| option('project', t) } + global.map { |t| option('global', t) }
rescue StandardError => e
Rails.logger.warn "[IssueTemplateSupport] Could not load templates: #{e.class}: #{e.message}"
[]
end
def find(key, project)
return nil if key.blank?
templates_for(project).detect { |t| t.key == key }
end
def option(group, template)
Option.new(
key: "#{group}:#{template.id}",
title: template.title,
tracker_id: template.tracker_id,
is_default: template.is_default?,
description: template.description,
group: group
)
end
end
end
+84
View File
@@ -0,0 +1,84 @@
#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 work orders (Redmine issues) behind an estimate or invoice, and the two hooks other plugins use with
# them:
#
# :qbo_billing_issue_values, { issues: [Issue, ...] }
# Return a hash of field => { issue_id => value }, e.g. redmine_qbo_vehicles returns
# { vin: { 116 => "1C4HJXDG5JW123456" } }. This plugin answers it too with { mileage: ... } from the
# issue custom field named "Mileage" (Hooks::IssueMileageListener).
# The invoice's VIN and mileage boxes are filled from them when time or estimates are imported.
#
# :qbo_billing_validate, { document: "invoice" or "estimate", form: EstimateForm, issues: [Issue, ...] }
# Return an error message (or a list of them) to stop the save, e.g. redmine_qbo_vehicles refuses an
# invoice whose work orders are for more than one vehicle. Return nil to allow it.
module IssueValues
# The issue a line came from: redmine_qbo writes "Install #116: some job" on time activities, and
# redmine_qbo_lineitems starts its estimates with "Added from: Install #116: some job"
ISSUE_REFERENCE = /#(\d+):/
ADDED_FROM = /\A\s*Added from:/i
module_function
def issue_reference(text)
text.to_s.lines.first.to_s[ISSUE_REFERENCE, 1]
end
# Issues behind the document: the ones its time lines and "Added from" notes name, and the ones linked
# to its estimates (an invoice's linked estimates, or the estimate itself)
def issue_ids(form)
ids = form.filled_lines.filter_map do |line|
next if line.subtotal?
issue_reference(line.description) if line.time_activity_id.present? || line.description.to_s.match?(ADDED_FROM)
end
estimate_ids = Array(form.linked_estimate_ids).dup
estimate_ids << form.id if !form.invoice? && form.persisted?
ids += Issue.where(estimate_id: estimate_ids.map(&:to_s)).pluck(:id).map(&:to_s) if estimate_ids.any?
ids.map(&:to_s).uniq
end
def issues(form)
ids = issue_ids(form)
ids.empty? ? [] : Issue.where(id: ids).to_a
end
# { vin: { "116" => "..." }, mileage: { "116" => "..." } } from every plugin listening
def values_for(issues)
issues = Array(issues)
return {} if issues.empty?
Redmine::Hook.call_hook(:qbo_billing_issue_values, { issues: issues }).each_with_object({}) do |result, merged|
next unless result.is_a?(Hash)
result.each do |field, by_issue|
next unless by_issue.is_a?(Hash)
(merged[field.to_sym] ||= {}).merge!(by_issue.transform_keys(&:to_s).transform_values(&:to_s).reject { |_, v| v.strip.empty? })
end
end
end
# The same values by issue, for the import panel: { "116" => { vin: "...", mileage: "..." } }
def by_issue(issues)
values_for(issues).each_with_object({}) do |(field, by_id), result|
by_id.each { |id, value| (result[id] ||= {})[field] = value }
end
end
# Error messages from plugins that want this save stopped
def plugin_errors(form)
context = { document: form.document, form: form, issues: issues(form) }
Redmine::Hook.call_hook(:qbo_billing_validate, context).flatten.compact.map(&:to_s).reject(&:empty?)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] A plugin's validation failed: #{e.message}"
[]
end
end
end
@@ -0,0 +1,40 @@
#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
module Patches
# quickbooks-ruby's invoice lines have no LinkedTxn, which QuickBooks needs on each line that bills a
# time activity ("When linking a TimeActivity to an Invoice you must also link it to a sales line item").
# This adds it, placed right after Amount where QuickBooks' schema has it.
module InvoiceLineItemLinkedTxn
module_function
def apply!
klass = Quickbooks::Model::InvoiceLineItem
return if klass.method_defined?(:linked_transactions)
klass.class_eval do
xml_accessor :linked_transactions, from: 'LinkedTxn', as: [Quickbooks::Model::LinkedTransaction]
end
# Move the new element from the end to after Amount, so it's written in schema order
attrs = klass.instance_variable_get(:@roxml_attrs)
return unless attrs.is_a?(Array)
linked = attrs.detect { |a| a.respond_to?(:accessor) && a.accessor == 'linked_transactions' }
amount_index = attrs.index { |a| a.respond_to?(:accessor) && a.accessor == 'amount' }
return unless linked && amount_index
attrs.delete(linked)
attrs.insert(amount_index + 1, linked)
end
end
end
end
+61
View File
@@ -0,0 +1,61 @@
#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
# What the Receive payment page posts: who paid, how, and how much. PaymentWriter turns it into a
# QuickBooks payment, applied to the customer's oldest open invoices first, or kept as a deposit.
class PaymentForm
include ActiveModel::Model
include ActiveModel::Validations
ATTRIBUTES = %i[customer_id customer_name txn_date payment_method_id reference amount deposit memo].freeze
attr_accessor(*ATTRIBUTES)
# Invoices ticked on the page: the payment goes on these (oldest first). None ticked: all open invoices.
attr_accessor :invoice_ids
validate :validate_payment
def self.from_params(params)
params = params.to_h.stringify_keys
new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] }).tap do |form|
form.invoice_ids = Array(params['invoice_ids']).map(&:to_s).reject(&:blank?).uniq
end
end
def initialize(attributes = {})
super
self.invoice_ids ||= []
end
def amount_value
EstimateForm.decimal(amount)
end
def txn_date_value
EstimateForm.date(txn_date)
end
# A deposit is kept unapplied (credit on the customer's account) instead of paying invoices
def deposit?
deposit == true || deposit.to_s == '1'
end
private
def validate_payment
errors.add(:base, I18n.t(:error_estimate_needs_customer)) if customer_id.blank?
errors.add(:base, I18n.t(:error_payment_needs_method)) if payment_method_id.blank?
value = amount_value
errors.add(:base, I18n.t(:error_payment_amount)) if value.nil? || value <= 0
errors.add(:base, I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_payment_date))) if txn_date_value.nil?
end
end
end
+144
View File
@@ -0,0 +1,144 @@
#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
# Receives customer payments in QuickBooks: payment type and amount, applied to the customer's open
# invoices oldest first (the way QuickBooks applies them on its own screen), or only to the invoices ticked
# on the page, or saved unapplied as a deposit. Whatever doesn't fit stays unapplied as a credit.
module PaymentWriter
Error = EstimateWriter::Error
METHODS_CACHE_KEY = 'redmine_qbo_billing:payment_methods'
module_function
def new_form(customer: nil, user: User.current)
PaymentForm.new(customer_id: customer&.id, customer_name: customer&.name, txn_date: user.today.iso8601)
end
# QuickBooks' payment methods (Cash, Check, Credit Card...), cached for an hour: [[name, id], ...]
def payment_methods
cached = Rails.cache.read(METHODS_CACHE_KEY)
return cached if cached
methods = with_service('PaymentMethod') { |service| service.query.entries }
list = Array(methods).select { |m| m.active? != false && m.active? != 'false' }
.map { |m| [m.name.to_s, m.id.to_s] }
.sort_by { |name, _| name.downcase }
Rails.cache.write(METHODS_CACHE_KEY, list, expires_in: 1.hour) if list.any?
list
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read payment methods: #{e.message}"
[]
end
# The customer's invoices with a balance, oldest first (by date, then number)
def open_invoices(customer)
invoices = with_service('Invoice') do |service|
service.query("SELECT * FROM Invoice WHERE CustomerRef = '#{customer.id.to_i}' ORDERBY TxnDate", per_page: 1000).entries
end
Array(invoices).select { |i| BigDecimal(i.balance.to_s.presence || '0') > 0 }
.sort_by { |i| [i.txn_date || Date.new(1900), i.doc_number.to_s.rjust(12, '0')] }
.map do |i|
{ id: i.id.to_s, doc_number: i.doc_number.to_s, date: i.txn_date.to_s, due_date: i.due_date.to_s,
total: i.total.to_s, balance: BigDecimal(i.balance.to_s).to_s('F') }
end
end
# Spreads the amount over the invoices in order: [[invoice, applied], ...] and what's left over
def allocate(amount, invoices)
left = BigDecimal(amount.to_s)
applied = []
invoices.each do |invoice|
break if left <= 0
take = [left, BigDecimal(invoice[:balance].to_s)].min
next if take <= 0
applied << [invoice, take]
left -= take
end
[applied, left]
end
# Creates the payment in QuickBooks and returns it. Open invoices are read again here, so the payment
# goes on what's open right now.
def save(form)
customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
amount = form.amount_value.round(2)
applied =
if form.deposit?
[]
else
invoices = open_invoices(customer)
invoices = invoices.select { |i| form.invoice_ids.include?(i[:id]) } if form.invoice_ids.any?
allocate(amount, invoices).first
end
payment = Quickbooks::Model::Payment.new
payment.customer_id = customer.id
payment.txn_date = form.txn_date_value
payment.payment_method_ref = Quickbooks::Model::BaseReference.new(form.payment_method_id)
payment.payment_ref_number = form.reference if form.reference.present?
payment.private_note = form.memo if form.memo.present?
payment.total = amount
payment.line_items = applied.map do |invoice, take|
line = Quickbooks::Model::Line.new
line.amount = take
line.invoice_id = invoice[:id]
line
end
saved = with_service('Payment') { |service| service.create(payment) }
raise Error, I18n.t(:error_payment_not_saved) unless saved
# Invoice balances changed: update the local invoices
applied.each { |invoice, _| sync_invoice(invoice[:id]) }
saved
end
def load(id)
payment = with_service('Payment') { |service| service.fetch_by_id(id) }
raise Error, I18n.t(:notice_payment_not_found) unless payment
payment
end
# The payment as QuickBooks prints it (its payment receipt)
def pdf(id)
with_service('Payment') { |service| service.pdf(Struct.new(:id).new(id)) }
end
# The invoices a payment was applied to: [[invoice_id, number, amount], ...]
def applied_invoices(payment)
Array(payment.line_items).flat_map do |line|
Array(line.linked_transactions).select { |t| t.txn_type.to_s == 'Invoice' }.map do |t|
[t.txn_id.to_s, InvoiceWriter.invoice_number(t.txn_id), line.amount]
end
end
end
def payment_method_name(payment)
ref = payment.payment_method_ref
return '' unless ref
ref.name.presence || payment_methods.detect { |_, id| id == ref.value.to_s }&.first || ref.value.to_s
end
def with_service(entity, &block)
QboConnectionService.with_qbo_service(entity: entity, &block)
end
def sync_invoice(id)
InvoiceSyncService.new.sync_by_id(id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not sync invoice #{id} after a payment: #{e.message}"
end
end
end
@@ -0,0 +1,20 @@
#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
# quickbooks-ruby's estimate service, with QuickBooks' newer custom fields and emailing (QboServiceExtras)
class QboEstimateService < Quickbooks::Service::Estimate
include QboServiceExtras
def send_estimate(estimate_id, email_address = nil)
send_document(estimate_id, email_address)
end
end
end
@@ -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.
module RedmineQboBilling
# quickbooks-ruby's invoice service, with QuickBooks' newer custom fields and emailing (QboServiceExtras).
# (Its own email call is named "send", which hides Ruby's Object#send, so send_invoice is used instead.)
class QboInvoiceService < Quickbooks::Service::Invoice
include QboServiceExtras
def send_invoice(invoice_id, email_address = nil)
send_document(invoice_id, email_address)
end
end
end
@@ -0,0 +1,57 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module RedmineQboBilling
# What the plugin's estimate and invoice services add to quickbooks-ruby's: QuickBooks' newer custom
# fields on every request, emailing the document, and an authenticated service for a block.
module QboServiceExtras
# QuickBooks only includes its newer custom fields (the ones made under Settings > Custom fields, which
# aren't listed in the company preferences) when asked for them, on minor version 70 or later
MINOR_VERSION = 75
ENHANCED_CUSTOM_FIELDS = 'enhancedAllCustomFields'.freeze
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# Runs the block with an authenticated service, refreshing the QuickBooks token when needed
def with_service
qbo = QboConnectionService.current!
qbo.perform_authenticated_request do |access_token|
yield new(company_id: qbo.realm_id, access_token: access_token)
end
end
end
# Emails the document to the customer (to email_address, or the document's billing email when blank).
# QuickBooks uses its own email template, marks the document as sent and returns it.
def send_document(id, email_address = nil)
query = email_address.present? ? "?sendTo=#{CGI.escape(email_address.to_s.strip)}" : ""
url = "#{url_for_resource(model::REST_RESOURCE)}/#{id}/send#{query}"
response = do_http_post(url, "", {}, { 'Content-Type' => 'application/octet-stream' })
return nil unless response.code.to_i == 200
model.from_xml(parse_singular_entity_response(model, response.plain_body))
end
private
# Every request from these services (reads, queries, saves, emails) asks for all custom fields. Only
# these services do, so redmine_qbo's own calls are unchanged.
def add_query_string_to_url(url, params = {})
params = params.is_a?(Hash) ? params.dup : {}
params['minorversion'] = [Quickbooks.minorversion.to_i, MINOR_VERSION].max
params['include'] = ENHANCED_CUSTOM_FIELDS
delimiter = url.include?('?') ? '&' : '?'
url + delimiter + params.map { |key, value| "#{key}=#{value}" }.join('&')
end
end
end