Handle QuickBooks custom fields generically; no vehicle code left

redmine_qbo now works the same for any business; vehicle behaviour lives in redmine_qbo_vehicles.

- Every enabled QuickBooks text custom field gets a box on the estimate/invoice editor (the sales person
  is still filled in automatically). Forms keep custom_fields { field_id => value } instead of vin and
  mileage; Duplicate and Create invoice copy them all.
- Company: custom_field_matching(pattern) and editable_custom_fields; the VIN and Mileage name patterns
  are gone.
- Hooks are keyed by custom field id: qbo_billing_field_options (box suggestions) and
  qbo_billing_field_defaults (values for a document's work orders) replace the VIN hooks;
  qbo_billing_issue_values returns { field_id => { issue_id => value } }.
- Editor script API for plugins: window.qboEditor, the qbo:customer-changed and qbo:imported events, and
  the view_qbo_estimate_form_bottom hook to add a script. The VIN/mileage filling and the several-vehicle
  warning moved to redmine_qbo_vehicles.
- EstimateWriter.create_estimate(custom_fields:), custom_field_value and custom_field_values replace
  the vin/mileage arguments and vin_for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-31 11:34:10 -04:00
1 parent cb705d9525
commit 388ac915d7
14 files changed
+192 -164

No files matched your search

+33 -23
View File
@@ -27,35 +27,45 @@ module RedmineQboBilling
end
end
# VINs to suggest in the estimate/invoice VIN box for a customer, from plugins answering
# :qbo_billing_vin_options, { customer: } => [{ vin:, name: }, ...] (e.g. redmine_qbo_vehicles: the
# customer's vehicles)
def self.vin_options(customer)
return [] unless customer
# Suggestions for the editor's custom field boxes for a customer, from plugins answering
# :qbo_billing_field_options, { customer: } => { field_id => [{ value:, label: }, ...] }
# (e.g. redmine_qbo_vehicles: the customer's vehicles for its VIN field). Returns { "2" => [...] }.
def self.field_options(customer)
return {} unless customer
Redmine::Hook.call_hook(:qbo_billing_vin_options, { customer: customer }).flatten.compact.filter_map do |option|
option = option.to_h.symbolize_keys
vin = option[:vin].to_s.strip
{ vin: vin, name: option[:name].to_s.presence || vin } unless vin.empty?
end.uniq { |o| o[:vin].upcase }
Redmine::Hook.call_hook(:qbo_billing_field_options, { customer: customer }).each_with_object({}) do |result, merged|
next unless result.is_a?(Hash)
result.each do |field, options|
id = (field.respond_to?(:id) ? field.id : field).to_s
list = Array(options).filter_map do |option|
option = option.to_h.symbolize_keys
value = option[:value].to_s.strip
{ value: value, label: option[:label].to_s.presence || value } unless value.empty?
end
(merged[id] ||= []).concat(list).uniq! { |o| o[:value].upcase }
end
end
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] VIN suggestions failed: #{e.message}"
[]
Rails.logger.warn "[RedmineQboBilling] Custom field suggestions failed: #{e.message}"
{}
end
# The VIN for a document's work orders, from plugins answering
# :qbo_billing_default_vin, { customer:, issues: } => a VIN or nil (e.g. redmine_qbo_vehicles: the work
# orders' vehicle when they share one)
# Used for an invoice made from an estimate that has no VIN (issues: the estimate's work orders). New
# estimates and invoices start with a blank VIN.
def self.default_vin(customer, issues: [])
return nil unless customer
# Custom field values for a document's work orders, from plugins answering
# :qbo_billing_field_defaults, { customer:, issues: } => { field_id => value }
# (e.g. redmine_qbo_vehicles: the work orders' VIN). Used for an invoice made from an estimate, for the
# fields the estimate leaves blank. New estimates and invoices start blank. Returns { "2" => "..." }.
def self.field_defaults(customer, issues: [])
return {} unless customer
Redmine::Hook.call_hook(:qbo_billing_default_vin, { customer: customer, issues: Array(issues) })
.flatten.compact.map { |vin| vin.to_s.strip }.reject(&:empty?).first
Redmine::Hook.call_hook(:qbo_billing_field_defaults, { customer: customer, issues: Array(issues) })
.each_with_object({}) do |result, merged|
next unless result.is_a?(Hash)
EstimateForm.custom_field_hash(result).each { |id, value| merged[id] ||= value if value.present? }
end
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Default VIN failed: #{e.message}"
nil
Rails.logger.warn "[RedmineQboBilling] Custom field defaults failed: #{e.message}"
{}
end
# True when the user may write estimates
+16 -14
View File
@@ -10,23 +10,23 @@
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.
# in Redmine: the sales form custom fields, whether estimate numbers are typed by hand, and the default
# messages. Every enabled text custom field gets a box on the estimate/invoice editor; the sales person
# (found by name) is filled in automatically. Other plugins find the fields they fill by name
# (custom_field_matching), e.g. redmine_qbo_vehicles' VIN.
#
# 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)
# While no custom fields are found, look again sooner (e.g. right after adding one 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
# The sales person field is found loosely, e.g. "Sales Person", "Salesperson", "Sales Rep"
SALES_PERSON_NAME = /sales|\brep\b/i
MILEAGE_NAME = /mileage|odometer|\bmiles\b/i
Field = Struct.new(:id, :name)
@@ -37,17 +37,20 @@ module RedmineQboBilling
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 }
# The first enabled custom field whose name matches, e.g. a plugin's VIN field (/\bvin\b/i), or nil
def custom_field_matching(pattern)
custom_fields.detect { |f| f.name.to_s =~ pattern }
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 }
# The custom fields edited on the estimate/invoice editor: all of them except the sales person, which is
# filled in automatically
def editable_custom_fields
sales = sales_person_field
custom_fields.reject { |f| sales && f.id.to_i == sales.id.to_i }
end
def sales_person_field
custom_fields.detect { |f| f.name.to_s =~ SALES_PERSON_NAME && f.name.to_s !~ VIN_NAME }
custom_fields.detect { |f| f.name.to_s =~ SALES_PERSON_NAME }
end
# When on, QuickBooks leaves estimate numbers to the user; when off it numbers them itself
@@ -79,8 +82,7 @@ module RedmineQboBilling
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 }
complete = Array(fresh[:custom_fields]).any?
Rails.cache.write(CACHE_KEY, fresh, expires_in: complete ? CACHE_TIME : MISSING_FIELD_CACHE_TIME)
fresh
end
+20 -1
View File
@@ -93,12 +93,15 @@ module RedmineQboBilling
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
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number customer_memo private_note].freeze
# "estimate" or "invoice"
attr_writer :document
attr_accessor :id, :sync_token, *HEADER_ATTRIBUTES, :sales_person, :lines,
# QuickBooks custom field values by field id: { "2" => "1FTFW1E50NFA12345" } (the sales person
# is kept apart, in sales_person)
:custom_fields,
# 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
@@ -121,6 +124,21 @@ module RedmineQboBilling
super
self.lines ||= []
self.linked_estimate_ids ||= []
self.custom_fields = self.class.custom_field_hash(custom_fields)
end
# { "2" => "value" } from a hash keyed by field id (string, integer or Company::Field)
def self.custom_field_hash(values)
(values || {}).to_h.each_with_object({}) do |(field, value), hash|
id = field.respond_to?(:id) ? field.id : field
hash[id.to_s] = value.to_s.strip if id.to_s =~ /\A\d+\z/
end
end
# A custom field's value (by field id or Company::Field)
def custom_field(field)
id = field.respond_to?(:id) ? field.id : field
custom_fields[id.to_s].to_s
end
def document
@@ -142,6 +160,7 @@ module RedmineQboBilling
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.custom_fields = custom_field_hash(params['custom_fields'])
form.lines = params['lines'].to_h.values.map { |row| Line.from_params(row) }
form
end
+32 -25
View File
@@ -47,15 +47,15 @@ module RedmineQboBilling
# 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)
# custom_fields: QuickBooks custom field values by field id (see Company.custom_field_matching)
def create_estimate(customer:, lines:, private_note: nil, custom_fields: {}, 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,
custom_fields: custom_fields,
customer_memo: Company.estimate_message,
private_note: private_note.to_s,
lines: lines.map do |line|
@@ -72,7 +72,7 @@ module RedmineQboBilling
save(form, user: user)
end
# A new estimate copied from an existing one: same customer, lines, VIN and messages, dated today, with a
# A new estimate copied from an existing one: same customer, lines, custom fields 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)
@@ -85,8 +85,7 @@ module RedmineQboBilling
txn_date: today.iso8601,
expiration_date: default_expiration_date(today)&.iso8601,
sales_person: user.name,
vin: source.vin,
mileage: source.mileage,
custom_fields: source.custom_fields.dup,
customer_memo: source.customer_memo,
private_note: source.private_note,
lines: source.lines.map do |line|
@@ -142,20 +141,31 @@ module RedmineQboBilling
saved
end
# The VIN on an estimate, read with QuickBooks' newer custom fields (a plain fetch, e.g. Estimate#details,
# leaves them out). Cached for a minute, since creating issues asks once per issue.
def vin_for(estimate_id)
return nil if estimate_id.blank?
# An estimate's custom field value (by field id or Company::Field), read with QuickBooks' newer custom
# fields (a plain fetch, e.g. Estimate#details, leaves them out), or nil. Cached for a minute, since
# creating issues from an estimate may ask once per issue.
def custom_field_value(estimate_id, field)
return nil if estimate_id.blank? || field.nil?
Rails.cache.fetch("redmine_qbo:estimate_vin:#{estimate_id}", expires_in: 1.minute) do
id = field.respond_to?(:id) ? field.id : field
values = Rails.cache.fetch("redmine_qbo:estimate_custom_fields:#{estimate_id}", expires_in: 1.minute) do
remote = QboEstimateService.with_service { |service| service.fetch_by_id(estimate_id) }
remote ? custom_value(remote, Company.vin_field, Company::VIN_NAME).to_s.strip : ''
end.presence
remote ? custom_field_values(remote) : {}
end
values[id.to_s].presence
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read estimate #{estimate_id}'s VIN: #{e.message}"
Rails.logger.warn "[RedmineQboBilling] Could not read estimate #{estimate_id}'s custom fields: #{e.message}"
nil
end
# A QuickBooks estimate's or invoice's text custom field values by field id: { "2" => "..." }
def custom_field_values(remote)
Array(remote.custom_fields).each_with_object({}) do |f, values|
next unless f.type.to_s == 'StringType' || f.string_value.present?
values[f.id.to_s] = f.string_value.to_s
end
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) }
@@ -187,8 +197,7 @@ module RedmineQboBilling
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),
custom_fields: custom_field_values(remote),
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) }),
@@ -229,10 +238,10 @@ module RedmineQboBilling
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)
def custom_value(remote, field, name_pattern = nil)
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) }
(name_pattern && fields.detect { |f| f.name.to_s =~ name_pattern })
match&.string_value.to_s
end
@@ -259,7 +268,8 @@ module RedmineQboBilling
estimate
end
# Keeps every custom field already on the estimate, then sets the VIN, and the sales person on create
# Keeps every custom field already on the estimate, then sets the ones edited on the form, 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)
@@ -269,12 +279,9 @@ module RedmineQboBilling
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)
Company.editable_custom_fields.each do |field|
next unless form.custom_fields.key?(field.id.to_s)
fields[field.id.to_i] = string_field(field.id, field.name, form.custom_field(field))
end
sales = Company.sales_person_field
+10 -11
View File
@@ -55,7 +55,7 @@ module RedmineQboBilling
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.
# customer, lines, subtotals and custom fields. 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
@@ -70,10 +70,10 @@ module RedmineQboBilling
form.customer_id = source.customer_id
form.email = source.email.presence || form.email
form.billing_address = source.billing_address.presence || form.billing_address
# The estimate's VIN, or else a plugin's for the estimate's work orders (e.g. their vehicle)
form.vin = source.vin.presence ||
RedmineQboBilling.default_vin(customer, issues: Issue.where(estimate_id: source.id.to_s).to_a)
form.mileage = source.mileage
# The estimate's custom fields; ones it leaves blank come from plugins for its work orders (e.g.
# redmine_qbo_vehicles: their VIN)
defaults = RedmineQboBilling.field_defaults(customer, issues: Issue.where(estimate_id: source.id.to_s).to_a)
form.custom_fields = defaults.merge(source.custom_fields.reject { |_, value| value.blank? })
# 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
@@ -146,8 +146,7 @@ module RedmineQboBilling
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),
custom_fields: writer.custom_field_values(remote),
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) }),
@@ -286,8 +285,8 @@ module RedmineQboBilling
# ---- 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)
# What can be pulled into an invoice for the customer: billable time and open estimates, and the custom
# field values 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)
@@ -361,8 +360,8 @@ module RedmineQboBilling
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,
# The estimate's own VIN, used when its work orders give none
vin: writer.custom_value(e, Company.vin_field, Company::VIN_NAME).to_s.strip,
# The estimate's own custom field values (plugins' editor scripts may use them, e.g. its VIN)
custom_fields: writer.custom_field_values(e),
lines: lines.map { |l| line_hash(l) }
}
end
+7 -7
View File
@@ -13,10 +13,10 @@ module RedmineQboBilling
# them:
#
# :qbo_billing_issue_values, { issues: [Issue, ...] }
# Return a hash of field => { issue_id => value }, e.g. redmine_qbo_vehicles returns
# { vin: { 116 => "1C4HJXDG5JW123456" }, mileage: { 116 => "48210" } } (mileage from the issue custom
# field named "Mileage"). The invoice's VIN and mileage boxes are filled from them when time or
# estimates are imported (the highest mileage wins).
# Return a hash of QuickBooks custom field id => { issue_id => value }, e.g. redmine_qbo_vehicles returns
# { "2" => { 116 => "1C4HJXDG5JW123456" } } for the VIN field. They're given to the editor's script with
# imported time and estimates (the qbo:imported event), and to other plugins (e.g. redmine_qbo_lineitems'
# estimates); the plugin's own editor script decides how to fill its fields.
#
# :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
@@ -51,7 +51,7 @@ module RedmineQboBilling
ids.empty? ? [] : Issue.where(id: ids).to_a
end
# { vin: { "116" => "..." }, mileage: { "116" => "..." } } from every plugin listening
# { "2" => { "116" => "..." } } (custom field id => values by issue) from every plugin listening
def values_for(issues)
issues = Array(issues)
return {} if issues.empty?
@@ -60,12 +60,12 @@ module RedmineQboBilling
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? })
(merged[field.to_s] ||= {}).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: "..." } }
# The same values by issue, for the editor: { "116" => { "2" => "..." } }
def by_issue(issues)
values_for(issues).each_with_object({}) do |(field, by_id), result|
by_id.each { |id, value| (result[id] ||= {})[field] = value }