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
+482 -74

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>
+30 -8
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>
<%= 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' } %>
<%# 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' %>