mirror of
https://github.com/rickbarrette/redmine_qbo.git
synced 2026-11-17 18:20:36 -05:00
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>
This commit is contained in:
1 parent
89f4797bbe
commit
1c71e3a4c9
20 files changed
+482
-74
No files matched your search
@@ -75,6 +75,11 @@ module RedmineQboBilling
|
||||
settings[:custom_txn_numbers] == true
|
||||
end
|
||||
|
||||
# Whether QuickBooks has discounts turned on for sales forms (true when its settings couldn't be read)
|
||||
def discounts_allowed?
|
||||
settings[:allow_discount] != false
|
||||
end
|
||||
|
||||
# The "default message shown on estimates" from QuickBooks' sales settings
|
||||
def estimate_message
|
||||
settings[:estimate_message].to_s
|
||||
@@ -113,6 +118,7 @@ module RedmineQboBilling
|
||||
{
|
||||
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,
|
||||
allow_discount: forms.nil? || forms.allow_discount?.nil? ? nil : forms.allow_discount?.to_s == 'true',
|
||||
estimate_message: forms&.estimate_message.to_s,
|
||||
invoice_message: forms&.default_customer_message.to_s
|
||||
}
|
||||
|
||||
@@ -92,8 +92,12 @@ module RedmineQboBilling
|
||||
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 customer_memo private_note].freeze
|
||||
# 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
|
||||
@@ -105,8 +109,11 @@ module RedmineQboBilling
|
||||
# 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
|
||||
@@ -117,6 +124,7 @@ module RedmineQboBilling
|
||||
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
|
||||
|
||||
@@ -193,6 +201,35 @@ module RedmineQboBilling
|
||||
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
|
||||
@@ -240,6 +277,17 @@ module RedmineQboBilling
|
||||
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
|
||||
|
||||
@@ -13,8 +13,9 @@ module RedmineQboBilling
|
||||
#
|
||||
# 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.
|
||||
# QuickBooks always adds after the last line isn't shown (QuickBooks adds it back). The discount (a percent
|
||||
# or an amount) is QuickBooks' discount line after the lines, 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.
|
||||
@@ -72,8 +73,8 @@ module RedmineQboBilling
|
||||
save(form, user: user)
|
||||
end
|
||||
|
||||
# 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)
|
||||
# A new estimate copied from an existing one: same customer, lines, discount, custom fields and messages, dated
|
||||
# today, with a new number and the current user as sales person (bundles aren't copied)
|
||||
def duplicate_form(id, user: User.current)
|
||||
source = load(id)
|
||||
today = user.today
|
||||
@@ -88,6 +89,8 @@ module RedmineQboBilling
|
||||
custom_fields: source.custom_fields.dup,
|
||||
customer_memo: source.customer_memo,
|
||||
private_note: source.private_note,
|
||||
discount_type: source.discount_type,
|
||||
discount_value: source.discount_value,
|
||||
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,
|
||||
@@ -258,6 +261,7 @@ module RedmineQboBilling
|
||||
total: remote.total,
|
||||
total_tax: remote.txn_tax_detail&.total_tax,
|
||||
discount: discount_total(remote),
|
||||
**discount_fields(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|
|
||||
@@ -325,9 +329,16 @@ module RedmineQboBilling
|
||||
estimate.private_note = form.private_note.to_s
|
||||
estimate.custom_fields = build_custom_fields(form, remote, user)
|
||||
estimate.line_items = build_lines(form, remote)
|
||||
discount_before_tax(estimate, form)
|
||||
estimate
|
||||
end
|
||||
|
||||
# A discount comes off before sales tax: QuickBooks takes the discount from the subtotal, then works out
|
||||
# the tax on what's left (otherwise it taxes the full amount and discounts after)
|
||||
def discount_before_tax(document, form)
|
||||
document.apply_tax_after_discount = true if form.discount?
|
||||
end
|
||||
|
||||
# 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)
|
||||
@@ -371,14 +382,44 @@ module RedmineQboBilling
|
||||
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
|
||||
# The discount goes after the lines, as on QuickBooks' own screen
|
||||
discount = discount_line(form, remote, lines.size + 1)
|
||||
lines << discount if discount
|
||||
lines
|
||||
end
|
||||
|
||||
# QuickBooks' discount line for the form's discount, or nil (taken off before tax, see discount_before_tax). A percent discount is sent as a percent so
|
||||
# QuickBooks works it out from its own subtotal; the discount account already on the document is kept
|
||||
# (otherwise QuickBooks uses its default discount account).
|
||||
def discount_line(form, remote, number)
|
||||
return nil unless form.discount?
|
||||
|
||||
account = Array(remote&.line_items).detect(&:discount_item?)&.discount_line_detail&.discount_account_ref
|
||||
line = Quickbooks::Model::InvoiceLineItem.new
|
||||
line.line_num = number
|
||||
line.amount = form.discount_amount
|
||||
line.discount_item! do |detail|
|
||||
detail.percent_based = form.percent_discount?
|
||||
detail.discount_percent = form.discount_value_number if form.percent_discount?
|
||||
detail.discount_account_ref = account if account
|
||||
end
|
||||
line
|
||||
end
|
||||
|
||||
# The editor's discount fields from a document's discount lines: one percent line stays a percent;
|
||||
# an amount, or several discount lines, become their total in dollars
|
||||
def discount_fields(remote)
|
||||
discounts = Array(remote.line_items).select(&:discount_item?)
|
||||
return {} if discounts.empty?
|
||||
|
||||
detail = discounts.first.discount_line_detail
|
||||
if discounts.size == 1 && detail&.percent_based?.to_s == 'true' && detail.discount_percent
|
||||
{ discount_type: 'percent', discount_value: plain_number(detail.discount_percent) }
|
||||
else
|
||||
{ discount_type: 'amount', discount_value: plain_number(discount_total(remote)) }
|
||||
end
|
||||
end
|
||||
|
||||
def build_line(line, number, keep_id:, section_total: BigDecimal('0'))
|
||||
remote = Quickbooks::Model::InvoiceLineItem.new
|
||||
remote.id = line.id if keep_id
|
||||
@@ -449,7 +490,7 @@ module RedmineQboBilling
|
||||
"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
|
||||
# What the document's discount lines take off, in dollars
|
||||
def discount_total(remote)
|
||||
discounts = Array(remote.line_items).select(&:discount_item?)
|
||||
discounts.empty? ? nil : discounts.sum(BigDecimal('0')) { |l| l.amount || BigDecimal('0') }
|
||||
|
||||
@@ -19,7 +19,9 @@ module RedmineQboBilling
|
||||
# * 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.
|
||||
# An invoice with a payment applied to it is read-only, so a paid invoice isn't changed under the payment by
|
||||
# accident. It can be unlocked on purpose (e.g. to give a discount after a deposit); the payment stays
|
||||
# applied, and the total can't go below what's been paid.
|
||||
module InvoiceWriter
|
||||
Error = EstimateWriter::Error
|
||||
Conflict = EstimateWriter::Conflict
|
||||
@@ -77,6 +79,8 @@ module RedmineQboBilling
|
||||
# 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.discount_type = source.discount_type
|
||||
form.discount_value = source.discount_value
|
||||
form.lines = copy_lines(source.lines)
|
||||
form.linked_estimate_ids = [source.id.to_s]
|
||||
form.converted_from = source.doc_number
|
||||
@@ -92,7 +96,8 @@ module RedmineQboBilling
|
||||
# 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)
|
||||
# unlock: a paid invoice may be changed (the user unlocked it), as long as it still covers the payments
|
||||
def save(form, user: User.current, unlock: false)
|
||||
customer = Customer.find_by(id: form.customer_id)
|
||||
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
|
||||
|
||||
@@ -102,7 +107,7 @@ module RedmineQboBilling
|
||||
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_paid(form, remote, unlock, user)
|
||||
check_not_billed(form.linked_estimate_ids - linked_ids(remote, ESTIMATE))
|
||||
|
||||
invoice = Quickbooks::Model::Invoice.new
|
||||
@@ -154,7 +159,9 @@ module RedmineQboBilling
|
||||
total: remote.total,
|
||||
total_tax: remote.txn_tax_detail&.total_tax,
|
||||
discount: writer.discount_total(remote),
|
||||
**writer.discount_fields(remote),
|
||||
balance: remote.balance,
|
||||
amount_paid: amount_paid(remote),
|
||||
email_status: remote.email_status.to_s,
|
||||
locked: (:bundles if writer.group_lines?(remote)) || (:paid if paid?(remote))
|
||||
)
|
||||
@@ -166,6 +173,46 @@ module RedmineQboBilling
|
||||
BigDecimal(remote.balance.to_s) < BigDecimal(remote.total.to_s)
|
||||
end
|
||||
|
||||
# What's been paid on the invoice: its total less its balance
|
||||
def amount_paid(remote)
|
||||
return BigDecimal('0') unless paid?(remote)
|
||||
BigDecimal(remote.total.to_s) - BigDecimal(remote.balance.to_s)
|
||||
end
|
||||
|
||||
# Nothing left owing on it
|
||||
def fully_paid?(remote)
|
||||
paid?(remote) && BigDecimal(remote.balance.to_s) <= 0
|
||||
end
|
||||
|
||||
# A paid invoice is only changed when unlocked by a user allowed to (see
|
||||
# RedmineQboBilling.paid_invoice_editor?), and never to less than what's been paid on it
|
||||
def check_paid(form, remote, unlock, user)
|
||||
return unless paid?(remote)
|
||||
raise Error, I18n.t(:error_invoice_paid) unless unlock
|
||||
raise Error, I18n.t(:error_invoice_paid_not_allowed) unless RedmineQboBilling.paid_invoice_editor?(fully_paid?(remote), user)
|
||||
|
||||
paid = amount_paid(remote)
|
||||
total = estimated_total(form, remote)
|
||||
return if total >= paid - BigDecimal('0.005')
|
||||
|
||||
raise Error, I18n.t(:error_invoice_below_paid, total: money(total), paid: money(paid))
|
||||
end
|
||||
|
||||
# The invoice's new total, before QuickBooks works out the tax: the lines less the discount, plus the tax
|
||||
# it had, scaled to the new amount (the same lines give exactly the old total)
|
||||
def estimated_total(form, remote)
|
||||
before_tax = form.subtotal - form.discount_amount
|
||||
old_tax = BigDecimal(remote.txn_tax_detail&.total_tax.to_s.presence || '0')
|
||||
old_before_tax = BigDecimal(remote.total.to_s) - old_tax
|
||||
return before_tax if old_tax.zero? || old_before_tax <= 0
|
||||
|
||||
(before_tax + old_tax * before_tax / old_before_tax).round(2)
|
||||
end
|
||||
|
||||
def money(amount)
|
||||
ActiveSupport::NumberHelper.number_to_currency(amount)
|
||||
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
|
||||
@@ -188,16 +235,19 @@ module RedmineQboBilling
|
||||
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)
|
||||
writer.discount_before_tax(invoice, form)
|
||||
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)
|
||||
# The invoice-level links: the estimates it was made from, every time activity a line bills (QuickBooks
|
||||
# wants time linked both on the line and on the invoice), and whatever else QuickBooks linked to it, e.g.
|
||||
# the payments applied to it (left out, QuickBooks would unlink them)
|
||||
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) }
|
||||
others = Array(remote&.linked_transactions).reject { |t| [ESTIMATE, TIME_ACTIVITY].include?(t.txn_type.to_s) }
|
||||
estimates.map { |id| link(id, ESTIMATE) } + times.map { |id| link(id, TIME_ACTIVITY) } + others
|
||||
end
|
||||
|
||||
def link(id, type)
|
||||
|
||||
@@ -9,8 +9,8 @@
|
||||
#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.
|
||||
# What the Receive payment and Edit payment pages post: 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
|
||||
@@ -20,16 +20,24 @@ module RedmineQboBilling
|
||||
attr_accessor(*ATTRIBUTES)
|
||||
# Invoices ticked on the page: the payment goes on these (oldest first). None ticked: all open invoices.
|
||||
attr_accessor :invoice_ids
|
||||
# A saved payment being edited: its QuickBooks id and sync token, and why it can't be edited here (or nil)
|
||||
attr_accessor :id, :sync_token, :locked
|
||||
|
||||
validate :validate_payment
|
||||
|
||||
def self.from_params(params)
|
||||
def self.from_params(params, id: nil)
|
||||
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
|
||||
form.id = id.presence
|
||||
form.sync_token = params['sync_token'].presence
|
||||
end
|
||||
end
|
||||
|
||||
def persisted?
|
||||
id.present?
|
||||
end
|
||||
|
||||
def initialize(attributes = {})
|
||||
super
|
||||
self.invoice_ids ||= []
|
||||
|
||||
@@ -12,8 +12,13 @@ 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.
|
||||
#
|
||||
# A saved payment can be edited the same way (date, method, reference, memo, amount and the invoices it
|
||||
# pays); its customer stays. Left as it was, it keeps the amounts it already applied to each invoice.
|
||||
module PaymentWriter
|
||||
Error = EstimateWriter::Error
|
||||
Conflict = EstimateWriter::Conflict
|
||||
INVOICE = 'Invoice'.freeze
|
||||
|
||||
METHODS_CACHE_KEY = 'redmine_qbo_billing:payment_methods'
|
||||
|
||||
@@ -39,17 +44,21 @@ module RedmineQboBilling
|
||||
[]
|
||||
end
|
||||
|
||||
# The customer's invoices with a balance, oldest first (by date, then number)
|
||||
def open_invoices(customer)
|
||||
# The customer's invoices with a balance, oldest first (by date, then number). For a payment being edited
|
||||
# (payment:, the QuickBooks payment), what it paid on each invoice counts as still open, so the invoices it
|
||||
# pays are listed even when it paid them off.
|
||||
def open_invoices(customer, payment: nil)
|
||||
invoices = with_service('Invoice') do |service|
|
||||
service.query("SELECT * FROM Invoice WHERE CustomerRef = '#{customer.id.to_i}' ORDERBY TxnDate", per_page: 1000).entries
|
||||
end
|
||||
paid_here = payment ? applied_amounts(payment) : {}
|
||||
|
||||
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|
|
||||
Array(invoices).map { |i| [i, BigDecimal(i.balance.to_s.presence || '0') + paid_here.fetch(i.id.to_s, 0)] }
|
||||
.select { |_, balance| balance > 0 }
|
||||
.sort_by { |i, _| [i.txn_date || Date.new(1900), i.doc_number.to_s.rjust(12, '0')] }
|
||||
.map do |i, balance|
|
||||
{ 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') }
|
||||
total: i.total.to_s, balance: balance.to_s('F') }
|
||||
end
|
||||
end
|
||||
|
||||
@@ -67,45 +76,132 @@ module RedmineQboBilling
|
||||
[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.
|
||||
# Creates the payment in QuickBooks (or updates the one being edited) and returns it. Open invoices are
|
||||
# read again here, so the payment goes on what's open right now.
|
||||
def save(form)
|
||||
return update(form) if form.persisted?
|
||||
|
||||
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
|
||||
applied = allocation(form, customer, amount)
|
||||
|
||||
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
|
||||
fill(payment, form, amount, applied)
|
||||
payment.payment_ref_number = nil if form.reference.blank?
|
||||
payment.private_note = nil if form.memo.blank?
|
||||
|
||||
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, and cache the payment for reports
|
||||
applied.each { |invoice, _| sync_invoice(invoice[:id]) }
|
||||
applied.each { |invoice_id, _| sync_invoice(invoice_id) }
|
||||
sync_payment(saved.id)
|
||||
saved
|
||||
end
|
||||
|
||||
# A saved payment on the Edit payment page
|
||||
def load_form(id)
|
||||
payment = load(id)
|
||||
applied = applied_amounts(payment)
|
||||
PaymentForm.new(
|
||||
id: payment.id.to_s,
|
||||
sync_token: payment.sync_token.to_s,
|
||||
customer_id: payment.customer_ref&.value.to_s,
|
||||
customer_name: payment.customer_ref&.name.presence || Customer.find_by(id: payment.customer_ref&.value)&.name,
|
||||
txn_date: payment.txn_date&.iso8601,
|
||||
payment_method_id: payment.payment_method_ref&.value.to_s,
|
||||
reference: payment.payment_ref_number.to_s,
|
||||
amount: BigDecimal(payment.total.to_s).round(2).to_s('F'),
|
||||
deposit: applied.empty? ? '1' : '0',
|
||||
memo: payment.private_note.to_s,
|
||||
invoice_ids: applied.keys,
|
||||
locked: edit_blocked(payment)
|
||||
)
|
||||
end
|
||||
|
||||
# Saves the changes to a payment. Its customer stays. If the amount and the ticked invoices are the
|
||||
# same as before, each invoice keeps the amount it had; otherwise the amount is spread again, oldest first.
|
||||
def update(form)
|
||||
applied = nil
|
||||
previously = []
|
||||
saved = with_service('Payment') do |service|
|
||||
remote = service.fetch_by_id(form.id)
|
||||
raise Error, I18n.t(:notice_payment_not_found) unless remote
|
||||
raise Conflict, I18n.t(:error_payment_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
|
||||
blocked = edit_blocked(remote)
|
||||
raise Error, blocked if blocked
|
||||
|
||||
customer = Customer.find_by(id: remote.customer_ref&.value)
|
||||
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
|
||||
|
||||
amount = form.amount_value.round(2)
|
||||
before = applied_amounts(remote)
|
||||
applied =
|
||||
if !form.deposit? && before.any? && amount == BigDecimal(remote.total.to_s) && form.invoice_ids.sort == before.keys.sort
|
||||
before.to_a
|
||||
else
|
||||
allocation(form, customer, amount, payment: remote)
|
||||
end
|
||||
previously = before.keys
|
||||
|
||||
payment = Quickbooks::Model::Payment.new
|
||||
payment.id = remote.id
|
||||
payment.sync_token = remote.sync_token
|
||||
payment.customer_ref = remote.customer_ref
|
||||
fill(payment, form, amount, applied)
|
||||
service.update(payment, sparse: true)
|
||||
end
|
||||
raise Error, I18n.t(:error_payment_not_saved) unless saved
|
||||
|
||||
# Balances changed on the invoices it paid before and the ones it pays now
|
||||
(previously + applied.map(&:first)).uniq.each { |invoice_id| sync_invoice(invoice_id) }
|
||||
sync_payment(saved.id)
|
||||
saved
|
||||
end
|
||||
|
||||
# Where the payment goes: [[invoice_id, amount], ...] (nothing for a deposit)
|
||||
def allocation(form, customer, amount, payment: nil)
|
||||
return [] if form.deposit?
|
||||
|
||||
invoices = open_invoices(customer, payment: payment)
|
||||
invoices = invoices.select { |i| form.invoice_ids.include?(i[:id]) } if form.invoice_ids.any?
|
||||
allocate(amount, invoices).first.map { |invoice, take| [invoice[:id], take] }
|
||||
end
|
||||
|
||||
# The form's details on a QuickBooks payment, applied as given ([[invoice_id, amount], ...])
|
||||
def fill(payment, form, amount, applied)
|
||||
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.to_s
|
||||
payment.private_note = form.memo.to_s
|
||||
payment.total = amount
|
||||
payment.line_items = applied.map do |invoice_id, take|
|
||||
line = Quickbooks::Model::Line.new
|
||||
line.amount = take
|
||||
line.invoice_id = invoice_id
|
||||
line
|
||||
end
|
||||
payment
|
||||
end
|
||||
|
||||
# Why a payment can't be edited here, or nil: it also applies credit memos or other transactions, which
|
||||
# this page doesn't show (saving would drop them)
|
||||
def edit_blocked(payment)
|
||||
others = Array(payment.line_items).flat_map { |line| Array(line.linked_transactions) }
|
||||
.reject { |t| t.txn_type.to_s == INVOICE }
|
||||
others.any? ? I18n.t(:error_payment_not_editable, types: others.map { |t| t.txn_type.to_s }.uniq.join(', ')) : nil
|
||||
end
|
||||
|
||||
# What the payment pays on each invoice: { invoice_id => amount }
|
||||
def applied_amounts(payment)
|
||||
applied_invoices(payment).each_with_object(Hash.new(BigDecimal('0'))) do |(invoice_id, _, amount), sums|
|
||||
sums[invoice_id] += BigDecimal(amount.to_s.presence || '0')
|
||||
end.to_h
|
||||
end
|
||||
|
||||
# Every payment the customer has made, newest first (by date, then QuickBooks id), read from QuickBooks
|
||||
def customer_payments(customer)
|
||||
payments = with_service('Payment') do |service|
|
||||
|
||||
Reference in new issue
Block a user