Files
redmine_qbo/lib/redmine_qbo_billing/estimate_form.rb
T
rickyandClaude Opus 5.5 1c71e3a4c9 Add discounts, unlocking paid invoices and editing payments
- Estimates and invoices take a discount, as a percent of the subtotal or an
  amount, saved as QuickBooks' discount line and taken off before sales tax.
  Duplicated estimates and invoices made from an estimate keep it. The box is
  hidden when discounts are off in QuickBooks.
- A paid invoice can be unlocked for editing after a confirmation. The
  payments stay linked, and the total can't go below what's been paid.
  Unlocking needs the new "Edit partially paid invoices" or "Edit paid
  invoices" permission, checked again when saving.
- Saved payments can be edited: date, method, reference, memo, amount and the
  invoices they pay. Each invoice keeps its amount unless the amount or the
  invoices change. Payments that also apply credit memos stay read-only.
- Locked estimates and invoices are readable again (disabled boxes had faint
  or invisible text, especially in Safari).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:04:19 -05:00

303 lines
11 KiB
Ruby

#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. The discount is a percent of the subtotal
# (discount_type "percent") or a dollar amount ("amount"), saved as QuickBooks' discount line.
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number customer_memo private_note
discount_type discount_value].freeze
DISCOUNT_TYPES = %w[percent amount].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
# (discount: the discount amount QuickBooks worked out when it was last saved)
:billing_address, :total, :total_tax, :discount, :email_status, :txn_status, :duplicated_from,
:balance, :converted_from,
# Invoices: a paid invoice opened for editing anyway (Unlock), and the amount paid on it
:unlocked, :amount_paid,
# 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
validate :validate_discount
# 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 ||= []
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
@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.custom_fields = custom_field_hash(params['custom_fields'])
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 discount_type
DISCOUNT_TYPES.include?(@discount_type.to_s) ? @discount_type.to_s : 'percent'
end
def percent_discount?
discount_type == 'percent'
end
# "10%" reads as 10
def discount_value_number
self.class.decimal(discount_value.to_s.delete('%'))
end
# A discount is given when a value above zero is entered
def discount?
(discount_value_number || 0).positive?
end
# The discount in dollars, as QuickBooks works it out: a percent of the subtotal, rounded to the cent
def discount_amount
return BigDecimal('0') unless discount?
percent_discount? ? (subtotal * discount_value_number / 100).round(2) : discount_value_number.round(2)
end
# Invoices: nothing left owing (a payment covers it all)
def fully_paid?
balance.present? && self.class.decimal(balance).to_d <= 0
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_discount
return if discount_value.blank?
value = discount_value_number
if value.nil? || value.negative? || (percent_discount? && value > 100)
invalid(:label_discount_from_quickbooks)
elsif discount_amount > subtotal
errors.add(:base, I18n.t(:error_discount_too_large))
end
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