From 1c71e3a4c94ce41d5aef3e5feee1950076fb833b Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Wed, 4 Nov 2026 15:04:19 -0500 Subject: [PATCH] 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 --- app/controllers/qbo_invoices_controller.rb | 20 ++- app/controllers/qbo_payments_controller.rb | 37 ++++- app/views/qbo_estimates/_form.html.erb | 24 +++- app/views/qbo_estimates/_header.html.erb | 12 +- app/views/qbo_estimates/_script.html.erb | 29 +++- app/views/qbo_estimates/_styles.html.erb | 10 +- app/views/qbo_payments/edit.html.erb | 2 + app/views/qbo_payments/index.html.erb | 3 + app/views/qbo_payments/new.html.erb | 38 ++++-- app/views/qbo_payments/show.html.erb | 3 + config/locales/en.yml | 17 +++ config/routes.rb | 2 +- init.rb | 5 +- lib/redmine_qbo_billing.rb | 7 + lib/redmine_qbo_billing/company.rb | 6 + lib/redmine_qbo_billing/estimate_form.rb | 52 ++++++- lib/redmine_qbo_billing/estimate_writer.rb | 61 +++++++-- lib/redmine_qbo_billing/invoice_writer.rb | 62 ++++++++- lib/redmine_qbo_billing/payment_form.rb | 14 +- lib/redmine_qbo_billing/payment_writer.rb | 152 +++++++++++++++++---- 20 files changed, 482 insertions(+), 74 deletions(-) create mode 100644 app/views/qbo_payments/edit.html.erb diff --git a/app/controllers/qbo_invoices_controller.rb b/app/controllers/qbo_invoices_controller.rb index b3117be..41deebb 100644 --- a/app/controllers/qbo_invoices_controller.rb +++ b/app/controllers/qbo_invoices_controller.rb @@ -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 diff --git a/app/controllers/qbo_payments_controller.rb b/app/controllers/qbo_payments_controller.rb index 493eb49..d9e34a4 100644 --- a/app/controllers/qbo_payments_controller.rb +++ b/app/controllers/qbo_payments_controller.rb @@ -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) diff --git a/app/views/qbo_estimates/_form.html.erb b/app/views/qbo_estimates/_form.html.erb index b1cd214..06233d4 100644 --- a/app/views/qbo_estimates/_form.html.erb +++ b/app/views/qbo_estimates/_form.html.erb @@ -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 %> <% form.linked_estimate_ids.each do |estimate_id| %> @@ -262,10 +270,18 @@ <%= l(:label_taxable_subtotal) %> - <% if form.discount.to_f != 0 %> - - <%= l(:label_discount_from_quickbooks) %> - -<%= number_to_currency(form.discount) %> + <% if show_discount %> + <%# A percent of the subtotal or a dollar amount; QuickBooks' discount line %> + + + + <%= 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) %> + + <%= "-#{number_to_currency(form.discount_amount)}" if form.discount? %> <% end %> diff --git a/app/views/qbo_estimates/_header.html.erb b/app/views/qbo_estimates/_header.html.erb index 825b0b8..49792c9 100644 --- a/app/views/qbo_estimates/_header.html.erb +++ b/app/views/qbo_estimates/_header.html.erb @@ -68,7 +68,17 @@ <% elsif form.locked == :paid %> -

<%= l(:error_invoice_paid) %>

+

+ <%= 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 %> +

+<% elsif form.unlocked && form.amount_paid.to_d > 0 %> +

<%= l(:text_invoice_unlocked, paid: number_to_currency(form.amount_paid)) %>

<% elsif form.locked == :bundles %>

<%= l(invoice ? :error_invoice_has_bundles : :error_estimate_has_bundles) %>

<% end %> diff --git a/app/views/qbo_estimates/_script.html.erb b/app/views/qbo_estimates/_script.html.erb index cc4eca6..1f19bf8 100644 --- a/app/views/qbo_estimates/_script.html.erb +++ b/app/views/qbo_estimates/_script.html.erb @@ -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; }); diff --git a/app/views/qbo_estimates/_styles.html.erb b/app/views/qbo_estimates/_styles.html.erb index 13ccfdc..c761618 100644 --- a/app/views/qbo_estimates/_styles.html.erb +++ b/app/views/qbo_estimates/_styles.html.erb @@ -2,7 +2,12 @@