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:
rickyandClaude Opus 5.5 committed 2026-11-04 15:04:19 -05:00
1 parent 89f4797bbe
commit 1c71e3a4c9
20 files changed
+479 -71

No files matched your search

+19 -1
View File
@@ -58,8 +58,10 @@ class QboInvoicesController < ApplicationController
show_error(e, :new)
end
# ?unlock=1 opens a paid invoice for editing anyway (after the editor's confirmation)
def edit
@form = RedmineQboBilling::InvoiceWriter.load(params[:id])
unlock_form if unlock?
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
@@ -68,9 +70,10 @@ class QboInvoicesController < ApplicationController
def update
@form = RedmineQboBilling::EstimateForm.from_params(invoice_params, id: params[:id], document: 'invoice')
@form.sales_person = params.dig(:estimate, :sales_person).to_s
unlock_form if unlock?
return show_invalid(:edit) unless @form.valid?
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current)
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current, unlock: unlock?)
finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number))
rescue RedmineQboBilling::InvoiceWriter::Conflict => e
@conflict = true
@@ -113,6 +116,21 @@ class QboInvoicesController < ApplicationController
)
end
def unlock?
params[:unlock].to_s == '1'
end
# Shows a paid invoice editable, with the amount paid on it (posted back with the form when saving), for
# users allowed to edit it (paid off or partly paid). InvoiceWriter.save checks again against QuickBooks.
def unlock_form
@form.amount_paid ||= RedmineQboBilling::EstimateForm.decimal(params.dig(:estimate, :amount_paid))
return unless @form.locked == :paid || @form.locked.nil?
return unless RedmineQboBilling.paid_invoice_editor?(@form.fully_paid?)
@form.locked = nil
@form.unlocked = true
end
def save_and_send?
params[:save_and_send].present?
end
+32 -5
View File
@@ -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.
# Receives customer payments in QuickBooks: payment type and amount, applied to open invoices oldest first, or
# saved as a deposit. A saved payment can be printed (QuickBooks' payment PDF). A customer's payments are
# listed on their payments page.
# saved as a deposit. A saved payment can be edited and printed (QuickBooks' payment PDF). A customer's
# payments are listed on their payments page.
class QboPaymentsController < ApplicationController
before_action :authorize_global, except: :sync
@@ -56,6 +56,31 @@ class QboPaymentsController < ApplicationController
show_form
end
def edit
@form = RedmineQboBilling::PaymentWriter.load_form(params[:id])
load_choices
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def update
@form = RedmineQboBilling::PaymentForm.from_params(payment_params, id: params[:id])
return show_form unless @form.valid?
payment = RedmineQboBilling::PaymentWriter.save(@form)
flash[:notice] = l(:notice_payment_updated, amount: view_context.number_to_currency(payment.total))
redirect_to qbo_payment_path(payment.id)
rescue RedmineQboBilling::PaymentWriter::Conflict => e
@conflict = true
@form.errors.add(:base, qbo_message(e))
show_form
rescue *QBO_ERRORS => e
logger.warn "[RedmineQboBilling] #{e.class}: #{qbo_message(e)}"
@form.errors.add(:base, qbo_message(e))
show_form
end
def show
@payment = RedmineQboBilling::PaymentWriter.load(params[:id])
@customer = Customer.find_by(id: @payment.customer_ref&.value)
@@ -86,13 +111,15 @@ class QboPaymentsController < ApplicationController
private
def payment_params
params.require(:payment).permit(*RedmineQboBilling::PaymentForm::ATTRIBUTES, invoice_ids: [])
params.require(:payment).permit(*RedmineQboBilling::PaymentForm::ATTRIBUTES, :sync_token, invoice_ids: [])
end
def load_choices
@payment_methods = RedmineQboBilling::PaymentWriter.payment_methods
customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present?
@open_invoices = customer ? RedmineQboBilling::PaymentWriter.open_invoices(customer) : []
# Editing: the invoices this payment pays count as open (by what it paid on them)
payment = RedmineQboBilling::PaymentWriter.load(@form.id) if @form.persisted?
@open_invoices = customer ? RedmineQboBilling::PaymentWriter.open_invoices(customer, payment: payment) : []
rescue *QBO_ERRORS => e
@open_invoices = []
flash.now[:error] = qbo_message(e)
@@ -100,7 +127,7 @@ class QboPaymentsController < ApplicationController
def show_form
load_choices
render :new, status: :unprocessable_entity
render(@form.persisted? ? :edit : :new, status: :unprocessable_entity)
end
def qbo_message(error)
+20 -4
View File
@@ -10,6 +10,9 @@
settings_read = company.settings.present?
# The same editor writes estimates and invoices
invoice = form.invoice?
# The discount box, unless QuickBooks has discounts turned off or the document is read-only (shown anyway
# for a document that has one)
show_discount = form.discount? || (company.discounts_allowed? && !form.locked)
# The draft being continued (QboDraft), if any; new documents can be saved as drafts
draft = local_assigns[:draft]
sender = invoice ? RedmineQboBilling.invoice_sender? : RedmineQboBilling.sender?
@@ -49,6 +52,11 @@
<%= hidden_field_tag 'estimate[sales_person]', form.sales_person, id: nil if form.persisted? || form.invoice? %>
<% if invoice %>
<%= hidden_field_tag 'estimate[balance]', form.balance, id: nil %>
<%# A paid invoice opened for editing (Unlock) stays unlocked if the page is shown again %>
<% if form.unlocked %>
<%= hidden_field_tag 'unlock', '1', id: nil %>
<%= hidden_field_tag 'estimate[amount_paid]', form.amount_paid, id: nil %>
<% end %>
<%# Estimates whose lines are on this invoice; the Import panel adds more %>
<span id="qbo-linked-estimates">
<% form.linked_estimate_ids.each do |estimate_id| %>
@@ -262,10 +270,18 @@
<th><%= l(:label_taxable_subtotal) %></th>
<td id="qbo-estimate-taxable-subtotal"></td>
</tr>
<% if form.discount.to_f != 0 %>
<tr>
<th><%= l(:label_discount_from_quickbooks) %></th>
<td>-<%= number_to_currency(form.discount) %></td>
<% if show_discount %>
<%# A percent of the subtotal or a dollar amount; QuickBooks' discount line %>
<tr class="qbo-estimate-discount">
<th>
<label for="qbo_estimate_discount_value"><%= l(:label_discount_from_quickbooks) %></label>
<%= text_field_tag 'estimate[discount_value]', form.discount_value, id: 'qbo_estimate_discount_value',
size: 6, inputmode: 'decimal', autocomplete: 'off', placeholder: '0' %>
<%= select_tag 'estimate[discount_type]',
options_for_select([[l(:label_discount_percent), 'percent'], [l(:label_discount_amount), 'amount']], form.discount_type),
id: 'qbo_estimate_discount_type', 'aria-label': l(:label_discount_type) %>
</th>
<td id="qbo-estimate-discount"><%= "-#{number_to_currency(form.discount_amount)}" if form.discount? %></td>
</tr>
<% end %>
<tr>
+11 -1
View File
@@ -68,7 +68,17 @@
</ul>
</div>
<% elsif form.locked == :paid %>
<p class="warning"><%= l(:error_invoice_paid) %></p>
<p class="warning">
<%= l(:error_invoice_paid) %>
<%# Opened for editing anyway after a confirmation (e.g. a discount after a deposit) %>
<% if RedmineQboBilling.paid_invoice_editor?(form.fully_paid?) %>
<%= link_to sprite_icon('unlock', l(:button_unlock_invoice)), edit_qbo_invoice_path(form.id, unlock: 1),
class: 'icon icon-unlock', id: 'qbo-unlock-invoice',
data: { confirm: l(:text_unlock_invoice_confirmation) } %>
<% end %>
</p>
<% elsif form.unlocked && form.amount_paid.to_d > 0 %>
<p class="warning"><%= l(:text_invoice_unlocked, paid: number_to_currency(form.amount_paid)) %></p>
<% elsif form.locked == :bundles %>
<p class="warning"><%= l(invoice ? :error_invoice_has_bundles : :error_estimate_has_bundles) %></p>
<% end %>
+26 -3
View File
@@ -36,8 +36,10 @@ $(function () {
var money = new Intl.NumberFormat(<%= raw (current_language.to_s.presence || 'en').to_json %>, { style: 'currency', currency: 'USD' });
var savedSubtotal = $form.data('savedSubtotal') === '' ? null : parseFloat($form.data('savedSubtotal'));
var savedTax = $form.data('savedTax') === '' ? null : parseFloat($form.data('savedTax'));
// Discounts are kept from QuickBooks as they are; QuickBooks works out a percent discount again on save
var discount = $form.data('discount') === '' ? 0 : parseFloat($form.data('discount'));
// The discount QuickBooks took off when the document was last saved (the tax shown is for that discount)
var savedDiscount = $form.data('discount') === '' ? 0 : parseFloat($form.data('discount'));
var $discountValue = $('#qbo_estimate_discount_value');
var $discountType = $('#qbo_estimate_discount_type');
var locked = $form.find('.qbo-estimate-sheet').prop('disabled');
// Row keys must be digits: Rails' strong parameters only keep a hash of rows when every key is a number
var nextKey = Date.now();
@@ -131,6 +133,13 @@ $(function () {
return round(qty * rate, 2);
}
// The discount in dollars: a percent of the subtotal or an amount, like QuickBooks works it out
function discountAmount(subtotal) {
var value = parseNumber(String($discountValue.val() || '').replace(/%/g, ''));
if (!$discountValue.length || value === null || isNaN(value) || value <= 0) return 0;
return $discountType.val() === 'percent' ? round(subtotal * value / 100, 2) : round(value, 2);
}
function recalc() {
var subtotal = 0, taxable = 0, section = 0;
rows().each(function () {
@@ -154,8 +163,11 @@ $(function () {
// QuickBooks works out the sales tax when the estimate is saved; show the saved tax until the lines change
var $tax = $('#qbo-estimate-tax');
var discount = discountAmount(subtotal);
$('#qbo-estimate-discount').text(discount > 0 ? '-' + money.format(discount) : '');
var total = round(subtotal - discount, 2);
if (savedTax !== null && savedSubtotal !== null && Math.abs(subtotal - savedSubtotal) < 0.005) {
if (savedTax !== null && savedSubtotal !== null && Math.abs(subtotal - savedSubtotal) < 0.005 &&
Math.abs(discount - savedDiscount) < 0.005) {
$tax.text(money.format(savedTax)).removeClass('qbo-pending');
total = round(total + savedTax, 2);
} else {
@@ -743,6 +755,16 @@ $(function () {
});
}
$discountValue.on('input', function () { dirty = true; recalc(); });
$discountType.on('change', function () { dirty = true; recalc(); });
// Math typed in the discount box (e.g. 1500-1250) is worked out, to the cent
function tidyDiscount() {
var text = String($discountValue.val() || '').replace(/[$,\s%]/g, '');
var value = parseNumber(text);
if (value !== null && !isNaN(value) && isMath(text)) $discountValue.val(plain(round(value, 2), 2));
}
$discountValue.on('blur', function () { tidyDiscount(); recalc(); });
// ---- saving ----
$form.on('input change', '.qbo-estimate-top input, .qbo-estimate-details input, .qbo-estimate-notes textarea', function () { dirty = true; });
@@ -761,6 +783,7 @@ $(function () {
}
// Math still in a box is worked out before saving
rows().each(function () { tidyNumbers($(this)); });
tidyDiscount();
dirty = false;
});
+9 -1
View File
@@ -2,7 +2,12 @@
<style>
.qbo-estimate { --qbo-border: #babec5; --qbo-muted: #6b6c72; --qbo-green: #2ca01c; --qbo-green-dark: #108000; --qbo-bar: #393a3d; }
.qbo-estimate-sheet { border: 1px solid #e3e5e8; border-radius: 4px; background: #fff; padding: 20px 24px 24px; margin: 0 0 0; min-width: 0; }
.qbo-estimate-sheet[disabled] { opacity: .75; }
.qbo-estimate-sheet[disabled] { opacity: .85; }
/* A locked document is still read here: browsers grey out disabled boxes' text (Safari nearly to nothing,
through -webkit-text-fill-color), so it's drawn in the normal text color */
.qbo-estimate-sheet[disabled] :is(input, textarea, select) { color: #393a3d; -webkit-text-fill-color: #393a3d; opacity: 1; }
/* ...but not hints in empty boxes, which would read as if they were filled in */
.qbo-estimate-sheet[disabled] :is(input, textarea)::placeholder { color: transparent; -webkit-text-fill-color: transparent; }
.qbo-estimate-sheet[disabled] .qbo-estimate-line-buttons, .qbo-estimate-sheet[disabled] .qbo-line-handle svg,
.qbo-estimate-sheet[disabled] .qbo-line-remove-button { display: none; }
.qbo-estimate-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; }
@@ -95,6 +100,9 @@
.qbo-estimate-totals { border-collapse: collapse; min-width: 300px; align-self: flex-start; font-variant-numeric: tabular-nums; }
.qbo-estimate-totals th { text-align: right; font-weight: normal; color: #393a3d; padding: 6px 16px 6px 0; }
.qbo-estimate-totals td { text-align: right; padding: 6px 0; min-width: 110px; }
.qbo-estimate-discount th { white-space: nowrap; }
.qbo-estimate-discount input { width: 5em; text-align: right; margin-left: 6px; }
.qbo-estimate-discount select { width: auto; }
.qbo-estimate-totals #qbo-estimate-tax.qbo-pending { color: var(--qbo-muted); font-style: italic; font-size: .9em; }
.qbo-estimate-totals .qbo-estimate-total th, .qbo-estimate-totals .qbo-estimate-total td { font-weight: 700; font-size: 1.15em; border-top: 1px solid #d4d7dc; padding-top: 10px; }
+2
View File
@@ -0,0 +1,2 @@
<%# A saved payment, on the same page as Receive payment %>
<%= render template: 'qbo_payments/new' %>
+3
View File
@@ -56,6 +56,9 @@
<td class="amount"><%= number_to_currency(payment.total) %></td>
<td class="amount"><%= unapplied > 0 ? number_to_currency(unapplied) : '' %></td>
<td class="buttons">
<% if RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_qbo_payment_path(payment.id), class: 'icon icon-edit' %>
<% end %>
<%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(payment.id),
class: 'icon icon-pdf', target: :_blank %>
</td>
+27 -5
View File
@@ -1,22 +1,44 @@
<% html_title l(:button_receive_payment) %>
<%# Receive payment, and Edit payment (edit.html.erb) for a saved one %>
<% editing = @form.persisted? %>
<% title = editing ? l(:label_edit_payment) : l(:button_receive_payment) %>
<% html_title title %>
<% customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present? %>
<h2>
<%= link_to l(:label_customers), customers_path %> &#187;
<% if customer %><%= link_to customer.name, customer_path(customer) %> &#187;<% end %>
<%= l(:button_receive_payment) %>
<% if editing %>
<%= link_to l(:label_payments), qbo_payments_path(customer_id: @form.customer_id) %> &#187;
<% end %>
<%= title %>
</h2>
<%= error_messages_for @form %>
<%= form_tag qbo_payments_path, id: 'qbo-payment-form',
<% if @conflict %>
<p class="warning">
<%= l(:text_payment_reload) %>
<%= link_to l(:button_reload_payment), edit_qbo_payment_path(@form.id) %>
</p>
<% end %>
<% if @form.locked %>
<p class="warning"><%= @form.locked %></p>
<% end %>
<%= form_tag (editing ? qbo_payment_path(@form.id) : qbo_payments_path), method: (editing ? :patch : :post), id: 'qbo-payment-form',
data: { open_invoices_url: open_invoices_qbo_payments_path, none_text: l(:label_no_open_invoices) } do %>
<%= hidden_field_tag 'payment[sync_token]', @form.sync_token, id: nil if editing %>
<div class="box tabular">
<p>
<label for="qbo_payment_customer_name"><%= l(:label_customer) %><span class="required"> *</span></label>
<%# A saved payment keeps its customer %>
<% if editing %>
<%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', size: 40, readonly: true, tabindex: -1 %>
<% else %>
<%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', class: 'customer-name',
autocomplete: 'off', size: 40, placeholder: l(:label_choose_a_customer),
data: { autocomplete_url: '/customers/autocomplete' } %>
<% end %>
<%= hidden_field_tag 'payment[customer_id]', @form.customer_id, id: 'customer_id' %>
</p>
<p>
@@ -94,8 +116,8 @@
</fieldset>
<p>
<%= submit_tag l(:button_save_payment) %>
<%= link_to l(:button_cancel), customer ? customer_path(customer) : home_path %>
<%= submit_tag l(:button_save_payment) unless @form.locked %>
<%= link_to l(:button_cancel), editing ? qbo_payment_path(@form.id) : (customer ? customer_path(customer) : home_path) %>
</p>
<% end %>
+3
View File
@@ -2,6 +2,9 @@
<% method_name = RedmineQboBilling::PaymentWriter.payment_method_name(@payment) %>
<div class="contextual">
<% if RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_qbo_payment_path(@payment.id), class: 'icon icon-edit' %>
<% end %>
<%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(@payment.id), class: 'icon icon-pdf', target: :_blank %>
<% if @customer && RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @customer.id), class: 'icon icon-add' %>
+17
View File
@@ -117,6 +117,9 @@ en:
permission_send_estimates: "Email estimates"
permission_write_invoices: "Write invoices"
permission_send_invoices: "Email invoices"
permission_edit_partially_paid_invoices: "Edit partially paid invoices"
permission_edit_paid_invoices: "Edit paid invoices"
error_invoice_paid_not_allowed: "You're not allowed to change invoices with this much paid on them"
permission_create_estimate_issues: "Create issues from estimates"
permission_receive_payments: "Receive payments"
@@ -176,6 +179,14 @@ en:
label_choose_a_customer: "Choose a customer"
label_customer_email: "Customer email"
label_discount_from_quickbooks: "Discount"
label_discount_amount: "$"
label_discount_percent: "%"
label_discount_type: "Discount type"
error_discount_too_large: "The discount can't be more than the subtotal"
error_invoice_below_paid: "The invoice total (about %{total} with tax) can't be less than the %{paid} already paid on it"
button_unlock_invoice: "Unlock to edit"
text_unlock_invoice_confirmation: "A payment has been applied to this invoice. Unlock it to make changes, such as a discount? The payment stays applied, and the total can't go below what's been paid."
text_invoice_unlocked: "Unlocked: %{paid} has been paid on this invoice. The payment stays applied when you save, and the total can't go below it."
label_drag_to_reorder: "Drag to reorder"
label_estimate_date: "Estimate date"
label_estimate_expiration_days: "Estimates expire after (days)"
@@ -319,6 +330,12 @@ en:
button_print_payment: "Print"
button_receive_payment: "Receive payment"
button_save_payment: "Save payment"
button_reload_payment: "Reload the payment"
label_edit_payment: "Edit payment"
notice_payment_updated: "Payment of %{amount} updated in QuickBooks"
error_payment_changed_in_quickbooks: "This payment was changed in QuickBooks after this page was opened"
error_payment_not_editable: "This payment also applies %{types}, which can't be shown here. Edit it in QuickBooks."
text_payment_reload: "Reload it to see the changes, then make yours again."
error_payment_amount: "Enter the amount received"
error_payment_needs_method: "Choose the payment method"
error_payment_not_saved: "QuickBooks didn't save the payment"
+1 -1
View File
@@ -72,7 +72,7 @@ end
resources :qbo_drafts, only: [:index, :destroy]
# Receive payment pages, and a customer's payments (/qbo_payments?customer_id=)
resources :qbo_payments, only: [:index, :new, :create, :show] do
resources :qbo_payments, only: [:index, :new, :create, :show, :edit, :update] do
member do
get :pdf
end
+4 -1
View File
@@ -48,8 +48,11 @@ Redmine::Plugin.register :redmine_qbo do
permission :write_invoices, { qbo_invoices: [:new, :create, :edit, :update, :import_options],
qbo_estimates: [:customer_info, :items], qbo_drafts: [:index, :destroy] }, global: true
permission :send_invoices, { qbo_invoices: [:send_email] }, global: true
# Unlocking an invoice with a payment applied (on top of Write invoices); see RedmineQboBilling.paid_invoice_editor?
permission :edit_partially_paid_invoices, {}, global: true
permission :edit_paid_invoices, {}, global: true
permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :pdf, :open_invoices],
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :edit, :update, :pdf, :open_invoices],
qbo_estimates: [:customer_info] }, global: true
permission :view_business_reports, { qbo_reports: [:index] }, global: true
# The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController)
+7
View File
@@ -93,6 +93,13 @@ module RedmineQboBilling
user.allowed_to?(:write_invoices, nil, global: true)
end
# True when the user may unlock and change an invoice with a payment applied: a paid-off one needs
# "Edit paid invoices", a partly paid one "Edit partially paid invoices" (both on top of "Write invoices")
def self.paid_invoice_editor?(fully_paid, user = User.current)
invoice_writer?(user) &&
user.allowed_to?(fully_paid ? :edit_paid_invoices : :edit_partially_paid_invoices, nil, global: true)
end
# True when the user may email invoices to customers
def self.invoice_sender?(user = User.current)
user.allowed_to?(:send_invoices, nil, global: true)
+6
View File
@@ -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
}
+50 -2
View File
@@ -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
+51 -10
View File
@@ -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') }
+56 -6
View File
@@ -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)
+11 -3
View File
@@ -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 ||= []
+124 -28
View File
@@ -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|