mirror of
https://github.com/rickbarrette/redmine_qbo.git
synced 2026-11-19 10:40:36 -05:00
Compare commits
2
Commits
2026.11.23
...
2026.11.24
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cf5328cb21 | ||
|
|
c851929e02 |
No files matched your search
@@ -166,6 +166,16 @@ Refunds for canceled orders and returned parts, following SOP-OPS-014, so they d
|
||||
* Each refund has its own page, listed on the customer page: what was refunded and how, with the fee invoice (opened in Redmine), a **PDF** of the refund (QuickBooks has no PDF of a check or an expense), the fee invoice's PDF, and **Email the customer** to send the summary again. If a QuickBooks step fails, the refund stops there and its page says which step and what was already done, to finish in QuickBooks.
|
||||
* It refunds all of the customer's remaining credit held as unapplied payments. Credit held as credit memos isn't refunded here.
|
||||
|
||||
#### Refunding a paid invoice
|
||||
|
||||
Completed work that's billed and paid in full is refunded from its invoice, with a QuickBooks **Refund Receipt**, the way QuickBooks refunds a paid sale:
|
||||
|
||||
* **Refund** on a paid-in-full invoice (or pick it under **Paid invoice** on the customer's Refund page). The invoice's lines are listed (bundles opened up into their lines), each marked parts or labor, with what earlier refunds already took of it. Tick the lines to refund and change the **quantity** (e.g. 2 of 4 parts returned) or the **amount** (a partial refund, e.g. some of the labor). A line can't be refunded, over one or more refunds, for more than it was billed.
|
||||
* **Restocking fee** is optional: when ticked, it's the rate in the settings of the *parts* refunded. Labor carries no fee, so a refund of labor alone has none. Leave it off when the parts aren't coming back.
|
||||
* The page shows the lines, the invoice discount's share (if it had one), the estimated sales tax refunded, the fee and the refund. Choose **Company check** (with its number) or **Card**.
|
||||
* **Refund** records the refund receipt in QuickBooks: the refunded lines with their products/services and tax codes (so the income and sales tax come back off the books; QuickBooks works out the tax), the discount's share, the fee as a negative line with the restocking fee product/service, paid out of the refund check or card refund account in the settings, with the payment method (a QuickBooks payment method named Check, or one with Card/Visa/Mastercard/Amex/Discover in its name) and the check number. The invoice stays as it is, paid.
|
||||
* As ticked on the page, it also notes the refund on the invoice's work orders (their status is left alone) and emails the customer a summary. The refund's page, PDF and email list the lines refunded, and show the refund receipt's exact total: refund exactly that.
|
||||
|
||||
### Business report
|
||||
|
||||
**Business report** in the top menu compares, for a period (this or last week, month, quarter or year, or custom dates; weeks start on the day set in Redmine's *Start calendars on* setting, Monday when it follows the language):
|
||||
@@ -219,14 +229,14 @@ Administration → Items lists the QuickBooks product/service list (synced from
|
||||
* **View business reports**: the Business report
|
||||
* **Write invoices**: create and edit invoices, and import time and estimates into them
|
||||
* **Email invoices**: email invoices to customers
|
||||
* **Issue refunds**: the Refund page, refunds and their PDFs
|
||||
* **Issue refunds**: the Refund page (customer credit) and refunds of paid invoices, refunds and their PDFs
|
||||
* **Share issues with customers**: the Share link on issues (see Sharing an issue with the customer)
|
||||
|
||||
2. Settings (Administration -> Plugins -> Configure)
|
||||
* **Estimates expire after (days)**: new estimates get an expiration date this many days after the estimate date (e.g. 30). Leave blank for none.
|
||||
* **Labor products/services** (e.g. Labor): one list used three ways. An estimate's lines with them can become issues (their quantities are also the estimate's labor hours, which an appointment's hours can't be less than); an invoice's lines with them are offered under Replace these lines when time is imported; and their quantities are the hours on estimates and invoices in the business report. While none are chosen, products/services named Labor are used.
|
||||
* **Issues from estimates**: the default project and the default tracker.
|
||||
* **Refunds**: the restocking fee (SOP-OPS-014: 30%) and the product/service on its invoice (e.g. a "Restocking Fee" service, which sets the income account), the bank accounts refund checks and card refunds come out of (blank: the first bank account), and the status canceled work orders are set to (blank: a closed status named Canceled).
|
||||
* **Refunds**: the restocking fee (SOP-OPS-014: 30%) and the product/service on its invoice or refund receipt line (e.g. a "Restocking Fee" service, which sets the income account), the bank accounts refund checks and card refunds come out of (blank: the first bank account), and the status canceled work orders are set to (blank: a closed status named Canceled).
|
||||
* Item and account counts, the default income account and their syncs are under Synchronization.
|
||||
|
||||
3. Writing an estimate
|
||||
|
||||
@@ -8,7 +8,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.
|
||||
|
||||
# Customer refunds (SOP-OPS-014): the Refund page for a customer with credit, and a refund once it's made
|
||||
# Customer refunds (SOP-OPS-014): the Refund page for a customer with credit (a canceled order's deposit), the
|
||||
# Refund invoice page for completed work on a paid invoice, and a refund once it's made
|
||||
class QboRefundsController < ApplicationController
|
||||
before_action :authorize_global
|
||||
|
||||
@@ -43,6 +44,40 @@ class QboRefundsController < ApplicationController
|
||||
show_form
|
||||
end
|
||||
|
||||
# Refund of a paid invoice: its lines to pick from, the optional restocking fee, how the money goes back
|
||||
def new_invoice
|
||||
@form = RedmineQboBilling::InvoiceRefundForm.new(invoice_id: params[:invoice_id].to_s, txn_date: User.current.today.iso8601,
|
||||
method: 'check', charge_fee: '1', note_issues: '1', email_customer: '1')
|
||||
return unless load_invoice_page
|
||||
|
||||
@form.customer_id = @customer.id.to_s
|
||||
# Every line with something left to refund is ticked, at what's left of it
|
||||
@lines.select(&:refundable?).each do |line|
|
||||
@form.lines[line.key] = RedmineQboBilling::InvoiceRefundForm::LineChoice.new(
|
||||
refund: '1', quantity: (quantity = RedmineQboBilling::InvoiceRefundWriter.default_quantity(line)) && RedmineQboBilling::RefundWriter.plain(quantity),
|
||||
amount: format('%.2f', line.remaining_amount)
|
||||
)
|
||||
end
|
||||
load_invoice_plan
|
||||
end
|
||||
|
||||
def create_invoice
|
||||
@form = RedmineQboBilling::InvoiceRefundForm.from_params(params.require(:refund).permit(*RedmineQboBilling::InvoiceRefundForm.permitted))
|
||||
return unless load_invoice_page
|
||||
return show_invoice_form unless @form.valid?
|
||||
|
||||
refund = RedmineQboBilling::InvoiceRefundWriter.refund!(@form)
|
||||
if refund.done?
|
||||
flash[:notice] = l(:notice_refund_done, amount: RedmineQboBilling::RefundWriter.money(refund.refund_amount))
|
||||
else
|
||||
flash[:error] = refund.message
|
||||
end
|
||||
redirect_to qbo_refund_path(refund)
|
||||
rescue RedmineQboBilling::RefundWriter::Error, *QBO_ERRORS => e
|
||||
@form.errors.add(:base, qbo_message(e))
|
||||
show_invoice_form
|
||||
end
|
||||
|
||||
def show
|
||||
@refund = QboRefund.find_by(id: params[:id])
|
||||
return render_404 unless @refund
|
||||
@@ -88,6 +123,7 @@ class QboRefundsController < ApplicationController
|
||||
|
||||
def load_page
|
||||
@estimates = RedmineQboBilling::RefundWriter.estimate_choices(@customer)
|
||||
@invoices = RedmineQboBilling::InvoiceRefundWriter.invoice_choices(@customer)
|
||||
@preview = RedmineQboBilling::RefundWriter.preview(@customer, parts: @form.parts_value || BigDecimal('0'))
|
||||
@statuses = IssueStatus.sorted.to_a
|
||||
rescue *QBO_ERRORS => e
|
||||
@@ -100,6 +136,40 @@ class QboRefundsController < ApplicationController
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
# The paid invoice from QuickBooks, its customer and its lines; renders the error and returns false when it
|
||||
# can't be refunded
|
||||
def load_invoice_page
|
||||
gateway = RedmineQboBilling::RefundGateway.new
|
||||
@invoice = gateway.invoice(@form.invoice_id) if @form.invoice_id.present?
|
||||
@customer = Customer.find_by(id: @invoice&.customer_ref&.value)
|
||||
if @invoice.nil? || @customer.nil?
|
||||
render_404
|
||||
return false
|
||||
end
|
||||
unless RedmineQboBilling::InvoiceRefundWriter.paid_in_full?(@invoice)
|
||||
flash[:error] = l(:error_refund_invoice_not_paid)
|
||||
redirect_to edit_qbo_invoice_path(@invoice.id)
|
||||
return false
|
||||
end
|
||||
|
||||
@lines = RedmineQboBilling::InvoiceRefundWriter.lines(@invoice)
|
||||
@refunds = QboRefund.of_invoice(@invoice.id).recent.to_a
|
||||
true
|
||||
rescue *QBO_ERRORS => e
|
||||
flash[:error] = qbo_message(e)
|
||||
redirect_to(@form.customer_id.present? ? customer_path(@form.customer_id) : customers_path)
|
||||
false
|
||||
end
|
||||
|
||||
def load_invoice_plan
|
||||
@plan, = RedmineQboBilling::InvoiceRefundWriter.plan(@invoice, @form, invoice_lines: @lines)
|
||||
end
|
||||
|
||||
def show_invoice_form
|
||||
load_invoice_plan
|
||||
render :new_invoice, status: :unprocessable_entity
|
||||
end
|
||||
|
||||
def qbo_message(error)
|
||||
detail = error.respond_to?(:detail) ? error.detail.to_s : ''
|
||||
message = error.message.to_s
|
||||
|
||||
@@ -8,10 +8,16 @@
|
||||
#
|
||||
#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.
|
||||
|
||||
# A customer refund (SOP-OPS-014), as it was made: the restocking fee, the refund, and each step's outcome
|
||||
# A customer refund (SOP-OPS-014), as it was made: the restocking fee, the refund, and each step's outcome.
|
||||
# Two kinds: credit, a canceled order's deposit (RefundWriter), and invoice, completed work on a paid invoice
|
||||
# (InvoiceRefundWriter).
|
||||
class QboRefund < ApplicationRecord
|
||||
METHODS = %w[check card].freeze
|
||||
STATUSES = %w[done incomplete].freeze
|
||||
KINDS = %w[credit invoice].freeze
|
||||
|
||||
# A refunded invoice line, as recorded: its key on the invoice (InvoiceRefundWriter.line_key)
|
||||
RefundedLine = Struct.new(:key, :description, :quantity, :amount, :parts, keyword_init: true)
|
||||
|
||||
belongs_to :customer
|
||||
belongs_to :user, optional: true
|
||||
@@ -19,8 +25,15 @@ class QboRefund < ApplicationRecord
|
||||
validates :customer_id, presence: true
|
||||
validates :method, inclusion: { in: METHODS }
|
||||
validates :status, inclusion: { in: STATUSES }
|
||||
validates :kind, inclusion: { in: KINDS }
|
||||
|
||||
scope :recent, -> { order(created_at: :desc, id: :desc) }
|
||||
# The invoice's refunds that made a refund receipt in QuickBooks
|
||||
scope :of_invoice, ->(id) { where(kind: 'invoice', invoice_id: id).where.not(purchase_id: [nil, '']) }
|
||||
|
||||
def invoice?
|
||||
kind == 'invoice'
|
||||
end
|
||||
|
||||
def done?
|
||||
status == 'done'
|
||||
@@ -44,11 +57,47 @@ class QboRefund < ApplicationRecord
|
||||
self[:canceled_issue_ids] = Array(ids).map(&:to_i).uniq.to_json
|
||||
end
|
||||
|
||||
# The QuickBooks screen for the refund check or expense
|
||||
def noted_issue_ids
|
||||
Array(JSON.parse(self[:noted_issue_ids].presence || '[]')).map(&:to_i)
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
|
||||
def noted_issue_ids=(ids)
|
||||
self[:noted_issue_ids] = Array(ids).map(&:to_i).uniq.to_json
|
||||
end
|
||||
|
||||
def refunded_lines
|
||||
Array(JSON.parse(self[:refunded_lines].presence || '[]')).map do |line|
|
||||
RefundedLine.new(key: line['key'].to_s, description: line['description'].to_s, quantity: line['quantity'],
|
||||
amount: BigDecimal(line['amount'].to_s.presence || '0'), parts: line['parts'] == true)
|
||||
end
|
||||
rescue JSON::ParserError
|
||||
[]
|
||||
end
|
||||
|
||||
def refunded_lines=(lines)
|
||||
self[:refunded_lines] = Array(lines).map do |line|
|
||||
{ key: line.key.to_s, description: line.description.to_s, quantity: line.quantity&.to_s,
|
||||
amount: line.amount.to_d.to_s('F'), parts: line.parts ? true : false }
|
||||
end.to_json
|
||||
end
|
||||
|
||||
# What the order or invoice is called: "E1068", "Invoice #1234", or nil
|
||||
def document_label
|
||||
if invoice? then I18n.t(:label_refund_invoice_number, number: invoice_number)
|
||||
elsif estimate_number.present? then "E#{estimate_number}"
|
||||
end
|
||||
end
|
||||
|
||||
# The QuickBooks screen for the refund receipt, check or expense
|
||||
def purchase_url
|
||||
return nil if purchase_id.blank?
|
||||
|
||||
page = check? ? 'check' : 'expense'
|
||||
page = if invoice? then 'refundreceipt'
|
||||
elsif check? then 'check'
|
||||
else 'expense'
|
||||
end
|
||||
"https://#{RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'}.qbo.intuit.com/app/#{page}?txnId=#{purchase_id}"
|
||||
end
|
||||
end
|
||||
@@ -78,7 +78,13 @@
|
||||
<% customer_refunds.each do |refund| %>
|
||||
<tr>
|
||||
<td><%= link_to format_date(refund.txn_date), qbo_refund_path(refund) %></td>
|
||||
<td><%= refund.estimate_id.present? ? link_to("E#{refund.estimate_number}", RedmineQboBilling.writer? ? edit_qbo_estimate_path(refund.estimate_id) : estimate_path(refund.estimate_id)) : '' %></td>
|
||||
<td>
|
||||
<% if refund.invoice? %>
|
||||
<%= link_to refund.document_label, RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(refund.invoice_id) : invoice_path(refund.invoice_id) %>
|
||||
<% elsif refund.estimate_id.present? %>
|
||||
<%= link_to("E#{refund.estimate_number}", RedmineQboBilling.writer? ? edit_qbo_estimate_path(refund.estimate_id) : estimate_path(refund.estimate_id)) %>
|
||||
<% end %>
|
||||
</td>
|
||||
<td><%= refund.method_name %></td>
|
||||
<td style="text-align: right"><%= RedmineQboBilling::RefundWriter.money(refund.refund_amount) %></td>
|
||||
<td><%= refund.done? ? '' : l(:label_refund_incomplete) %></td>
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
<% if RedmineQboBilling.payment_receiver? && @form.balance.to_d > 0 %>
|
||||
<%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @form.customer_id), class: 'icon icon-add' %>
|
||||
<% end %>
|
||||
<%# Completed work that's paid in full is refunded with a refund receipt %>
|
||||
<% if RedmineQboBilling.refunder? && @form.total.to_d.positive? && @form.balance.to_d <= 0 %>
|
||||
<%= link_to sprite_icon('arrow-narrow-left', l(:label_refund)), new_invoice_qbo_refunds_path(invoice_id: @form.id), class: 'icon icon-arrow-narrow-left' %>
|
||||
<% end %>
|
||||
<%= link_to sprite_icon('application-pdf', l(:label_estimate_pdf)), invoice_path(@form.id), class: 'icon icon-pdf', target: :_blank %>
|
||||
<% if RedmineQboBilling.invoice_sender? && @form.email.present? %>
|
||||
<%= link_to sprite_icon('email', l(:button_email_estimate)), send_email_qbo_invoice_path(@form.id, email: @form.email),
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
<% money = ->(amount) { RedmineQboBilling::RefundWriter.money(amount) } -%>
|
||||
<%= t(:text_refund_email_greeting, name: @customer&.name.to_s) %>
|
||||
|
||||
<%= t(:text_refund_email_intro, shop: @shop_name, order: @refund.estimate_number.present? ? "E#{@refund.estimate_number}" : t(:label_refund_your_order)) %>
|
||||
<%= t(:text_refund_email_intro, shop: @shop_name, order: @refund.document_label || t(:label_refund_your_order)) %>
|
||||
|
||||
<% if @refund.invoice? -%>
|
||||
<% @refund.refunded_lines.each do |line| -%>
|
||||
<%= line.description %>: <%= money.(line.amount) %>
|
||||
<% end -%>
|
||||
<%= t(:label_refund_lines_amount) %>: <%= money.(@refund.lines_amount) %>
|
||||
<% if @refund.discount_amount.to_d.positive? -%>
|
||||
<%= t(:label_refund_discount) %>: -<%= money.(@refund.discount_amount) %>
|
||||
<% end -%>
|
||||
<%= t(:label_refund_tax) %>: <%= money.(@refund.tax_amount) %>
|
||||
<% end -%>
|
||||
<% if @refund.fee_amount.to_d.positive? -%>
|
||||
<%= t(:label_refund_parts) %>: <%= money.(@refund.parts_amount) %>
|
||||
<%= t(:label_refund_fee_rate, rate: RedmineQboBilling::RefundWriter.plain(@refund.fee_rate)) %>: <%= money.(@refund.fee_amount) %>
|
||||
@@ -10,6 +20,10 @@
|
||||
<%= t(:label_refund_amount) %>: <%= money.(@refund.refund_amount) %>
|
||||
<%= @refund.check? ? t(:text_refund_email_check, number: @refund.check_number) : t(:text_refund_email_card) %>
|
||||
|
||||
<% if !@refund.invoice? -%>
|
||||
<%= t(:text_refund_email_terms) %>
|
||||
<% elsif @refund.fee_amount.to_d.positive? -%>
|
||||
<%= t(:text_refund_email_terms_invoice) %>
|
||||
<% end -%>
|
||||
|
||||
<%= @shop_name %>
|
||||
@@ -13,6 +13,21 @@
|
||||
|
||||
<p class="warning"><%= l(:text_refund_final_sale) %></p>
|
||||
|
||||
<%# Completed work on a paid invoice is refunded from the invoice (a refund receipt), not from credit %>
|
||||
<% if @invoices.present? %>
|
||||
<%= form_tag new_invoice_qbo_refunds_path, method: :get, id: 'qbo-refund-invoice' do %>
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<label for="qbo_refund_invoice"><%= l(:label_refund_paid_invoice) %></label>
|
||||
<%= select_tag 'invoice_id', options_for_select(@invoices), include_blank: true, id: 'qbo_refund_invoice',
|
||||
onchange: 'if (this.value) this.form.submit()' %>
|
||||
<noscript><%= submit_tag l(:button_apply), name: nil %></noscript>
|
||||
<em class="info"><%= l(:text_refund_paid_invoice) %></em>
|
||||
</p>
|
||||
</div>
|
||||
<% end %>
|
||||
<% end %>
|
||||
|
||||
<% if preview && preview.credits.empty? %>
|
||||
<p class="nodata"><%= l(:text_refund_no_credit) %></p>
|
||||
<% end %>
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
<%# Refund of completed work on a paid invoice: a QuickBooks Refund Receipt (InvoiceRefundWriter) %>
|
||||
<% html_title "#{l(:label_refund)} #{l(:label_refund_invoice_number, number: @invoice.doc_number)}" %>
|
||||
<% writer = RedmineQboBilling::RefundWriter %>
|
||||
<% money = ->(amount) { writer.money(amount) } %>
|
||||
<% plan = @plan %>
|
||||
<% number = @invoice.doc_number.to_s %>
|
||||
|
||||
<h2>
|
||||
<%= link_to l(:label_customers), customers_path %> »
|
||||
<%= link_to @customer.name, customer_path(@customer) %> »
|
||||
<%= link_to l(:label_refund_invoice_number, number: number), edit_qbo_invoice_path(@invoice.id) %> »
|
||||
<%= l(:label_refund) %>
|
||||
</h2>
|
||||
|
||||
<%= error_messages_for @form %>
|
||||
|
||||
<p class="warning"><%= l(:text_refund_final_sale) %></p>
|
||||
|
||||
<% if @refunds.any? %>
|
||||
<div class="flash warning">
|
||||
<%= l(:text_refund_invoice_earlier) %>
|
||||
<%= safe_join(@refunds.map { |r| link_to("#{format_date(r.txn_date)} · #{money.(r.refund_amount)}", qbo_refund_path(r)) }, ', ') %>
|
||||
</div>
|
||||
<% end %>
|
||||
|
||||
<%= form_tag create_invoice_qbo_refunds_path, method: :post, id: 'qbo-refund-form' do %>
|
||||
<%= hidden_field_tag 'refund[customer_id]', @customer.id, id: nil %>
|
||||
<%= hidden_field_tag 'refund[invoice_id]', @invoice.id, id: nil %>
|
||||
|
||||
<fieldset class="box" id="qbo-refund-lines">
|
||||
<legend><%= l(:label_refund_invoice_lines, number: number, date: format_date(@invoice.txn_date)) %></legend>
|
||||
<table class="list" data-discount-rate="<%= plan.discount_rate.to_s('F') %>" data-tax-rate="<%= plan.tax_rate.to_s('F') %>"
|
||||
data-fee-rate="<%= plan.fee_rate.to_s('F') %>">
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th style="text-align: left"><%= l(:label_refund_line) %></th>
|
||||
<th></th>
|
||||
<th style="text-align: right"><%= l(:label_refund_line_billed) %></th>
|
||||
<th style="text-align: right"><%= l(:label_refund_line_refunded) %></th>
|
||||
<th><%= l(:label_refund_line_quantity) %></th>
|
||||
<th><%= l(:label_refund_line_amount) %></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @lines.each do |line| %>
|
||||
<% choice = @form.line(line.key) %>
|
||||
<% field = "refund[lines][#{line.key}]" %>
|
||||
<% dom = "qbo_refund_line_#{line.key.parameterize(separator: '_')}" %>
|
||||
<tr class="qbo-refund-line<%= ' disabled' unless line.refundable? %>" data-rate="<%= line.rate&.to_s('F') %>"
|
||||
data-parts="<%= line.parts ? 1 : 0 %>" data-taxable="<%= line.taxable ? 1 : 0 %>">
|
||||
<td>
|
||||
<% if line.refundable? %>
|
||||
<%= hidden_field_tag "#{field}[refund]", '0', id: nil %>
|
||||
<%= check_box_tag "#{field}[refund]", '1', choice&.refund?, id: dom, class: 'qbo-refund-pick' %>
|
||||
<% end %>
|
||||
</td>
|
||||
<td style="text-align: left">
|
||||
<label for="<%= dom %>">
|
||||
<% if line.item_name.present? %><strong><%= line.item_name %></strong><br><% end %>
|
||||
<%= line.description %>
|
||||
</label>
|
||||
</td>
|
||||
<td><span class="badge <%= line.parts ? 'badge-status-open' : 'badge-status-closed' %>"><%= l(line.parts ? :label_refund_parts : :label_refund_labor) %></span>
|
||||
<% if line.taxable %><span class="badge"><%= l(:label_refund_taxable) %></span><% end %></td>
|
||||
<td style="text-align: right">
|
||||
<% if line.quantity && line.rate %><%= writer.plain(line.quantity) %> × <%= money.(line.rate) %><br><% end %>
|
||||
<%= money.(line.amount) %>
|
||||
</td>
|
||||
<td style="text-align: right"><%= line.refunded_amount.positive? ? money.(line.refunded_amount) : '' %></td>
|
||||
<% if line.refundable? %>
|
||||
<td style="white-space: nowrap">
|
||||
<% if line.quantity && line.rate %>
|
||||
<%= text_field_tag "#{field}[quantity]", choice&.quantity, size: 5, inputmode: 'decimal', autocomplete: 'off',
|
||||
class: 'qbo-refund-quantity', 'aria-label': l(:label_refund_line_quantity) %>
|
||||
<em class="info">/ <%= writer.plain(line.remaining_quantity) %></em>
|
||||
<% end %>
|
||||
</td>
|
||||
<td style="white-space: nowrap">
|
||||
$<%= text_field_tag "#{field}[amount]", choice&.amount, size: 9, inputmode: 'decimal', autocomplete: 'off',
|
||||
class: 'qbo-refund-line-amount', 'aria-label': l(:label_refund_line_amount),
|
||||
data: { max: line.remaining_amount.to_s('F') } %>
|
||||
</td>
|
||||
<% else %>
|
||||
<td colspan="2"><em class="info"><%= l(:text_refund_line_done) %></em></td>
|
||||
<% end %>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
<p><em class="info"><%= l(:text_refund_invoice_lines) %></em></p>
|
||||
</fieldset>
|
||||
|
||||
<div class="box tabular">
|
||||
<p>
|
||||
<label for="qbo_refund_charge_fee"><%= l(:label_refund_charge_fee) %></label>
|
||||
<%= hidden_field_tag 'refund[charge_fee]', '0', id: nil %>
|
||||
<%= check_box_tag 'refund[charge_fee]', '1', @form.charge_fee?, id: 'qbo_refund_charge_fee' %>
|
||||
<%= l(:label_refund_fee_rate, rate: writer.plain(plan.fee_rate)) %>
|
||||
<em class="info"><%= l(:text_refund_charge_fee) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_method) %><span class="required"> *</span></label>
|
||||
<label class="inline"><%= radio_button_tag 'refund[method]', 'check', @form.method == 'check', id: 'qbo_refund_method_check' %> <%= l(:label_refund_method_check) %></label>
|
||||
<label class="inline"><%= radio_button_tag 'refund[method]', 'card', @form.method == 'card', id: 'qbo_refund_method_card' %> <%= l(:label_refund_method_card) %></label>
|
||||
<em class="info"><%= l(:text_refund_method) %></em>
|
||||
</p>
|
||||
<p id="qbo-refund-check-number">
|
||||
<label for="qbo_refund_check_number"><%= l(:label_refund_check_number) %><span class="required"> *</span></label>
|
||||
<%= text_field_tag 'refund[check_number]', @form.check_number, id: 'qbo_refund_check_number', size: 12, maxlength: 21 %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_refund_date"><%= l(:label_refund_date) %><span class="required"> *</span></label>
|
||||
<%= date_field_tag 'refund[txn_date]', @form.txn_date, id: 'qbo_refund_date' %>
|
||||
</p>
|
||||
<p>
|
||||
<label for="qbo_refund_reason"><%= l(:label_refund_reason) %><span class="required"> *</span></label>
|
||||
<%= text_area_tag 'refund[reason]', @form.reason, id: 'qbo_refund_reason', rows: 3, cols: 60, maxlength: 2000 %>
|
||||
<em class="info"><%= l(:text_refund_invoice_reason) %></em>
|
||||
</p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_also) %></label>
|
||||
<% [[:note_issues, :label_refund_note_issues], [:email_customer, :label_refund_email_customer]].each do |flag, label| %>
|
||||
<label class="block">
|
||||
<%= hidden_field_tag "refund[#{flag}]", '0', id: nil %>
|
||||
<%= check_box_tag "refund[#{flag}]", '1', @form.send(:"#{flag}?"), id: "qbo_refund_#{flag}" %>
|
||||
<%= l(label) %>
|
||||
</label>
|
||||
<% end %>
|
||||
<% if @customer.email.blank? %><em class="info"><%= l(:text_refund_no_email) %></em><% end %>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<fieldset class="box" id="qbo-refund-preview">
|
||||
<legend><%= l(:label_refund_summary) %></legend>
|
||||
<table class="list">
|
||||
<tbody>
|
||||
<tr><td><%= l(:label_refund_lines_amount) %></td><td style="text-align: right" id="qbo-refund-lines-amount"><%= money.(plan.lines_amount) %></td></tr>
|
||||
<tr id="qbo-refund-discount-row"<%= ' style="display: none"'.html_safe unless plan.discount_rate.positive? %>>
|
||||
<td><%= l(:label_refund_discount) %></td><td style="text-align: right" id="qbo-refund-discount">-<%= money.(plan.discount) %></td>
|
||||
</tr>
|
||||
<tr><td><%= l(:label_refund_tax_estimate) %></td><td style="text-align: right" id="qbo-refund-tax"><%= money.(plan.tax) %></td></tr>
|
||||
<tr><td><%= l(:label_refund_fee_on_parts) %> (<span id="qbo-refund-parts"><%= money.(plan.parts_amount) %></span>)</td>
|
||||
<td style="text-align: right" id="qbo-refund-fee">-<%= money.(plan.fee) %></td></tr>
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr><td><strong><%= l(:label_refund_amount) %></strong></td><td style="text-align: right"><strong id="qbo-refund-amount"><%= money.(plan.refund) %></strong></td></tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
<p><em class="info"><%= l(:text_refund_invoice_summary) %></em></p>
|
||||
</fieldset>
|
||||
|
||||
<p><%= submit_tag l(:button_refund), data: { confirm: l(:text_refund_invoice_confirm) }, disabled: @lines.none?(&:refundable?) %></p>
|
||||
<% end %>
|
||||
|
||||
<%= javascript_tag do %>
|
||||
$(function() {
|
||||
var table = $('#qbo-refund-lines table');
|
||||
var money = function(n) { return '$' + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ','); };
|
||||
var num = function(v) { return parseFloat(String(v || '').replace(/[$,\s]/g, '')) || 0; };
|
||||
var round = function(n) { return Math.round(n * 100) / 100; };
|
||||
function update() {
|
||||
var lines = 0, parts = 0, taxable = 0;
|
||||
$('tr.qbo-refund-line').each(function() {
|
||||
var row = $(this);
|
||||
if (!row.find('.qbo-refund-pick').is(':checked')) return;
|
||||
var amount = num(row.find('.qbo-refund-line-amount').val());
|
||||
lines += amount;
|
||||
if (row.data('parts') == 1) parts += amount;
|
||||
if (row.data('taxable') == 1) taxable += amount;
|
||||
});
|
||||
var discountRate = num(table.data('discount-rate')), taxRate = num(table.data('tax-rate'));
|
||||
var discount = round(lines * discountRate);
|
||||
var tax = round(taxable * (1 - discountRate) * taxRate);
|
||||
var fee = $('#qbo_refund_charge_fee').is(':checked') ? Math.round(parts * num(table.data('fee-rate'))) / 100 : 0;
|
||||
$('#qbo-refund-lines-amount').text(money(lines));
|
||||
$('#qbo-refund-discount').text('-' + money(discount));
|
||||
$('#qbo-refund-tax').text(money(tax));
|
||||
$('#qbo-refund-parts').text(money(parts));
|
||||
$('#qbo-refund-fee').text('-' + money(fee));
|
||||
$('#qbo-refund-amount').text(money(Math.max(lines - discount + tax - fee, 0)));
|
||||
}
|
||||
// A quantity refunds that many at the line's rate (the amount can still be changed after)
|
||||
$('.qbo-refund-quantity').on('input', function() {
|
||||
var row = $(this).closest('tr'), rate = num(row.data('rate'));
|
||||
if (rate) row.find('.qbo-refund-line-amount').val(round(num($(this).val()) * rate).toFixed(2));
|
||||
row.find('.qbo-refund-pick').prop('checked', num($(this).val()) > 0);
|
||||
update();
|
||||
});
|
||||
$('.qbo-refund-line-amount, #qbo_refund_charge_fee, .qbo-refund-pick').on('input change', update);
|
||||
function method() { $('#qbo-refund-check-number').toggle($('#qbo_refund_method_check').is(':checked')); }
|
||||
$('input[name="refund[method]"]').on('change', method);
|
||||
update(); method();
|
||||
});
|
||||
<% end %>
|
||||
@@ -15,7 +15,9 @@
|
||||
<% end %>
|
||||
</div>
|
||||
|
||||
<% if @refund.done? %>
|
||||
<% if @refund.done? && @refund.invoice? %>
|
||||
<p class="notice flash"><%= l(:text_refund_receipt_made, number: @refund.receipt_number.presence || @refund.purchase_id) %></p>
|
||||
<% elsif @refund.done? %>
|
||||
<p class="<%= @refund.balance_after.to_d.zero? ? 'notice flash' : 'warning' %>">
|
||||
<%= @refund.balance_after.nil? ? l(:text_refund_balance_unknown) : l(:text_refund_balance, balance: money.(@refund.balance_after)) %>
|
||||
</p>
|
||||
@@ -27,13 +29,39 @@
|
||||
<% end %>
|
||||
|
||||
<div class="box tabular">
|
||||
<p><label><%= l(:label_refund_estimate) %></label> <%= @refund.estimate_id.present? ? link_to("E#{@refund.estimate_number}", RedmineQboBilling.writer? ? edit_qbo_estimate_path(@refund.estimate_id) : estimate_path(@refund.estimate_id)) : l(:label_refund_no_estimate) %></p>
|
||||
<p><label><%= l(:label_refund_reason) %></label> <%= @refund.reason %></p>
|
||||
<p><label><%= l(:label_refund_credit) %></label> <%= money.(@refund.credit_amount) %></p>
|
||||
<% if @refund.invoice? %>
|
||||
<p><label><%= l(:label_refund_invoice) %></label>
|
||||
<%= link_to @refund.document_label, RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(@refund.invoice_id) : invoice_path(@refund.invoice_id) %>
|
||||
· <%= l(:label_refund_paid_on_invoice) %> <%= money.(@refund.credit_amount) %></p>
|
||||
<p><label><%= l(:label_refund_reason) %></label> <%= @refund.reason %></p>
|
||||
<p><label><%= l(:label_refund_lines_amount) %></label> <%= money.(@refund.lines_amount) %></p>
|
||||
<% if @refund.refunded_lines.any? %>
|
||||
<table class="list" style="max-width: 50em">
|
||||
<tbody>
|
||||
<% @refund.refunded_lines.each do |line| %>
|
||||
<tr>
|
||||
<td style="text-align: left"><%= line.description %></td>
|
||||
<td><%= l(line.parts ? :label_refund_parts : :label_refund_labor) %></td>
|
||||
<td style="text-align: right"><%= RedmineQboBilling::RefundWriter.plain(BigDecimal(line.quantity.to_s)) if line.quantity.present? %></td>
|
||||
<td style="text-align: right"><%= money.(line.amount) %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
<% end %>
|
||||
<% if @refund.discount_amount.to_d.positive? %>
|
||||
<p><label><%= l(:label_refund_discount) %></label> -<%= money.(@refund.discount_amount) %></p>
|
||||
<% end %>
|
||||
<p><label><%= l(:label_refund_tax) %></label> <%= money.(@refund.tax_amount) %></p>
|
||||
<% else %>
|
||||
<p><label><%= l(:label_refund_estimate) %></label> <%= @refund.estimate_id.present? ? link_to("E#{@refund.estimate_number}", RedmineQboBilling.writer? ? edit_qbo_estimate_path(@refund.estimate_id) : estimate_path(@refund.estimate_id)) : l(:label_refund_no_estimate) %></p>
|
||||
<p><label><%= l(:label_refund_reason) %></label> <%= @refund.reason %></p>
|
||||
<p><label><%= l(:label_refund_credit) %></label> <%= money.(@refund.credit_amount) %></p>
|
||||
<% end %>
|
||||
<p><label><%= l(:label_refund_parts) %></label> <%= money.(@refund.parts_amount) %></p>
|
||||
<p>
|
||||
<label><%= l(:label_refund_fee_rate, rate: RedmineQboBilling::RefundWriter.plain(@refund.fee_rate)) %></label>
|
||||
<%= money.(@refund.fee_amount) %>
|
||||
<%= @refund.fee_amount.to_d.positive? ? money.(@refund.fee_amount) : l(:label_refund_no_fee) %>
|
||||
<% if @refund.fee_invoice_id.present? %>
|
||||
· <%= link_to l(:label_refund_fee_invoice, number: @refund.fee_invoice_number), RedmineQboBilling.invoice_writer? ? edit_qbo_invoice_path(@refund.fee_invoice_id) : invoice_path(@refund.fee_invoice_id) %>
|
||||
<% end %>
|
||||
@@ -42,12 +70,17 @@
|
||||
<label><%= l(:label_refund_amount) %></label>
|
||||
<%= money.(@refund.refund_amount) %> · <%= @refund.method_name %><%= " ##{@refund.check_number}" if @refund.check? %>
|
||||
<% if @refund.purchase_url %>
|
||||
· <%= link_to l(@refund.check? ? :label_refund_open_check : :label_refund_open_expense), @refund.purchase_url, target: '_blank', rel: 'noopener' %>
|
||||
· <%= link_to l(@refund.invoice? ? :label_refund_open_receipt : (@refund.check? ? :label_refund_open_check : :label_refund_open_expense)),
|
||||
@refund.purchase_url, target: '_blank', rel: 'noopener' %>
|
||||
<% end %>
|
||||
</p>
|
||||
<% if @refund.estimate_number.present? %>
|
||||
<p><label><%= l(:label_refund_close_estimate) %></label> <%= checked_image @refund.estimate_closed? %></p>
|
||||
<% end %>
|
||||
<% if @refund.noted_issue_ids.any? %>
|
||||
<p><label><%= l(:label_refund_note_issues) %></label>
|
||||
<%= safe_join(Issue.where(id: @refund.noted_issue_ids).map { |issue| link_to_issue(issue, project: false) }, ', ') %></p>
|
||||
<% end %>
|
||||
<% if @refund.canceled_issue_ids.any? %>
|
||||
<p><label><%= l(:label_refund_cancel_issues) %></label>
|
||||
<%= safe_join(Issue.where(id: @refund.canceled_issue_ids).map { |issue| link_to_issue(issue, project: false) }, ', ') %></p>
|
||||
|
||||
@@ -508,3 +508,52 @@ en:
|
||||
text_refund_check_account: "The bank account refund checks are written from."
|
||||
text_refund_card_account: "The account card refunds come out of (where card payments are deposited)."
|
||||
text_refund_canceled_status: "Work orders of a canceled order are set to this status, with the reason as a note."
|
||||
|
||||
# Refunds of paid invoices: completed work, billed and paid in full (a QuickBooks Refund Receipt)
|
||||
label_refund_invoice: "Invoice"
|
||||
label_refund_invoice_number: "Invoice #%{number}"
|
||||
label_refund_paid_invoice: "Paid invoice"
|
||||
label_refund_invoice_lines: "Invoice #%{number} · %{date}"
|
||||
label_refund_line: "Line"
|
||||
label_refund_line_billed: "Billed"
|
||||
label_refund_line_refunded: "Refunded before"
|
||||
label_refund_line_quantity: "Qty to refund"
|
||||
label_refund_line_amount: "Amount to refund"
|
||||
label_refund_labor: "Labor"
|
||||
label_refund_taxable: "Taxable"
|
||||
label_refund_charge_fee: "Restocking fee"
|
||||
label_refund_note_issues: "Note the refund on the invoice's work orders"
|
||||
label_refund_lines_amount: "Lines refunded"
|
||||
label_refund_discount: "Invoice discount (its share)"
|
||||
label_refund_tax_estimate: "Sales tax (estimated)"
|
||||
label_refund_tax: "Sales tax"
|
||||
label_refund_fee_on_parts: "Restocking fee on parts"
|
||||
label_refund_paid_on_invoice: "paid"
|
||||
label_refund_no_fee: "None"
|
||||
label_refund_open_receipt: "Refund receipt in QuickBooks"
|
||||
label_refund_receipt: "Refund receipt"
|
||||
text_refund_paid_invoice: "Completed work that's billed and paid in full: open its invoice to refund some or all of it (a refund receipt in QuickBooks). The rest of this page refunds customer credit, e.g. a canceled order's deposit."
|
||||
text_refund_invoice_lines: "Tick the lines to refund. Change the quantity (parts returned) or the amount (a partial refund) as needed; a line can't be refunded for more than was billed, less what earlier refunds took."
|
||||
text_refund_line_done: "Already refunded"
|
||||
text_refund_charge_fee: "Charged on the parts refunded only; labor carries no fee. Leave it off when the parts aren't coming back, or there are none."
|
||||
text_refund_invoice_reason: "Goes on the refund receipt in QuickBooks and on the invoice's work orders."
|
||||
text_refund_invoice_summary: "QuickBooks works out the sales tax on the refund receipt, so the refund can differ from this estimate by a few cents. The refund's page shows the exact amount to refund on the terminal or check."
|
||||
text_refund_invoice_confirm: "Record this refund receipt in QuickBooks?"
|
||||
text_refund_invoice_earlier: "This invoice has been refunded before:"
|
||||
text_refund_receipt_made: "Done. Refund receipt %{number} is recorded in QuickBooks. Refund exactly the amount below."
|
||||
text_refund_receipt_number: "No. %{number}"
|
||||
text_refund_receipt_memo: "Refund for invoice #%{number}"
|
||||
text_refund_invoice_private_note: "Refund of invoice #%{number} made in Redmine (SOP-OPS-014). Reason: %{reason}"
|
||||
text_refund_invoice_issue_note: "Refunded %{amount} on invoice #%{number} by %{method}: %{reason}"
|
||||
text_refund_issues_not_noted: "The refund couldn't be noted on some work orders: %{issues}"
|
||||
text_refund_email_terms_invoice: "As in our posted terms, returned parts carry a restocking fee."
|
||||
error_refund_no_invoice: "Pick the invoice to refund."
|
||||
error_refund_no_lines: "Tick at least one line to refund."
|
||||
error_refund_line_gone: "A line to refund isn't on the invoice any more. Reload the page."
|
||||
error_refund_line_quantity: "%{line}: the quantity must be more than 0 and no more than %{quantity}."
|
||||
error_refund_line_amount: "%{line}: enter an amount to refund of more than $0.00."
|
||||
error_refund_line_over: "%{line}: no more than %{amount} is left to refund."
|
||||
error_refund_fee_over_lines: "The restocking fee (%{fee}) isn't less than what's refunded (%{amount})."
|
||||
error_refund_invoice_customer: "That invoice is for another customer."
|
||||
error_refund_invoice_not_paid: "Only an invoice that's paid in full can be refunded here. Take or refund the payment in QuickBooks."
|
||||
error_refund_step_receipt: "The refund receipt couldn't be recorded in QuickBooks: %{error}. Nothing was refunded."
|
||||
@@ -73,6 +73,10 @@ resources :qbo_refunds, only: [:new, :create, :show] do
|
||||
get :pdf
|
||||
post :email
|
||||
end
|
||||
collection do
|
||||
get :new_invoice
|
||||
post :create_invoice
|
||||
end
|
||||
end
|
||||
|
||||
# Receive payment pages, and a customer's payments (/qbo_payments?customer_id=)
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
#
|
||||
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
#
|
||||
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
# Refunds of paid invoices (completed, billed and paid-in-full work): a QuickBooks Refund Receipt for the lines
|
||||
# refunded, with an optional restocking fee, alongside the refunds of customer credit (canceled orders)
|
||||
class AddInvoiceRefunds < ActiveRecord::Migration[7.0]
|
||||
def up
|
||||
# credit: a canceled order's deposit (fee invoice + check/expense); invoice: a paid invoice (refund receipt)
|
||||
add_column :qbo_refunds, :kind, :string, null: false, default: 'credit', limit: 10 unless column_exists?(:qbo_refunds, :kind)
|
||||
add_column :qbo_refunds, :invoice_id, :bigint unless column_exists?(:qbo_refunds, :invoice_id)
|
||||
add_column :qbo_refunds, :invoice_number, :string unless column_exists?(:qbo_refunds, :invoice_number)
|
||||
# The Refund Receipt's number (its id is purchase_id)
|
||||
add_column :qbo_refunds, :receipt_number, :string unless column_exists?(:qbo_refunds, :receipt_number)
|
||||
# The refunded lines before the discount, fee and tax; the invoice discount's share; the tax refunded
|
||||
add_column :qbo_refunds, :lines_amount, :decimal, precision: 15, scale: 2, null: false, default: 0 unless column_exists?(:qbo_refunds, :lines_amount)
|
||||
add_column :qbo_refunds, :discount_amount, :decimal, precision: 15, scale: 2, null: false, default: 0 unless column_exists?(:qbo_refunds, :discount_amount)
|
||||
add_column :qbo_refunds, :tax_amount, :decimal, precision: 15, scale: 2, null: false, default: 0 unless column_exists?(:qbo_refunds, :tax_amount)
|
||||
# The lines refunded (JSON: key, description, quantity, amount, parts), so a line isn't refunded twice
|
||||
add_column :qbo_refunds, :refunded_lines, :text unless column_exists?(:qbo_refunds, :refunded_lines)
|
||||
# The work orders the refund was noted on (JSON list of issue ids)
|
||||
add_column :qbo_refunds, :noted_issue_ids, :text unless column_exists?(:qbo_refunds, :noted_issue_ids)
|
||||
add_index :qbo_refunds, :invoice_id unless index_exists?(:qbo_refunds, :invoice_id)
|
||||
end
|
||||
|
||||
def down
|
||||
remove_index :qbo_refunds, :invoice_id if index_exists?(:qbo_refunds, :invoice_id)
|
||||
%i[kind invoice_id invoice_number receipt_number lines_amount discount_amount tax_amount refunded_lines
|
||||
noted_issue_ids].each do |column|
|
||||
remove_column :qbo_refunds, column if column_exists?(:qbo_refunds, column)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -14,7 +14,7 @@ Redmine::Plugin.register :redmine_qbo do
|
||||
name 'Redmine QBO plugin'
|
||||
author 'Rick Barrette'
|
||||
description 'A pluging for Redmine to connect with QuickBooks Online: customers, time activities for billable hours when an issue is closed, and estimates, invoices and payments written in Redmine'
|
||||
version '2026.11.23'
|
||||
version '2026.11.24'
|
||||
url 'https://github.com/rickbarrette/redmine_qbo'
|
||||
author_url 'https://barrettefabrication.com'
|
||||
settings default: {empty: true}, partial: 'qbo/settings'
|
||||
@@ -53,8 +53,9 @@ Redmine::Plugin.register :redmine_qbo do
|
||||
permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true
|
||||
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :edit, :update, :pdf, :open_invoices],
|
||||
qbo_estimates: [:customer_info] }, global: true
|
||||
# Refunds for canceled orders and returned parts (SOP-OPS-014): restocking fee, refund check or card refund
|
||||
permission :issue_refunds, { qbo_refunds: [:new, :create, :show, :pdf, :email] }, global: true
|
||||
# Refunds for canceled orders, returned parts and paid invoices (SOP-OPS-014): restocking fee, refund check
|
||||
# or card refund
|
||||
permission :issue_refunds, { qbo_refunds: [:new, :create, :new_invoice, :create_invoice, :show, :pdf, :email] }, 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)
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
#
|
||||
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
#
|
||||
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
module RedmineQboBilling
|
||||
# What the Refund invoice page posts: the paid invoice, the lines refunded (each with its quantity and
|
||||
# amount), whether a restocking fee is charged on the parts among them, how the money goes back (card terminal
|
||||
# or company check), and what else to do.
|
||||
class InvoiceRefundForm
|
||||
include ActiveModel::Model
|
||||
include ActiveModel::Validations
|
||||
|
||||
ATTRIBUTES = %i[customer_id invoice_id txn_date method check_number reason charge_fee note_issues
|
||||
email_customer].freeze
|
||||
FLAGS = %i[charge_fee note_issues email_customer].freeze
|
||||
|
||||
# One invoice line as posted: refund ticked, the quantity and the amount refunded
|
||||
LineChoice = Struct.new(:refund, :quantity, :amount, keyword_init: true) do
|
||||
def refund?
|
||||
refund.to_s == '1' || refund == true
|
||||
end
|
||||
|
||||
def quantity_value
|
||||
quantity.blank? ? nil : EstimateForm.decimal(quantity)
|
||||
end
|
||||
|
||||
def amount_value
|
||||
amount.blank? ? nil : EstimateForm.decimal(amount)
|
||||
end
|
||||
end
|
||||
|
||||
attr_accessor(*ATTRIBUTES)
|
||||
# { line key => LineChoice }
|
||||
attr_writer :lines
|
||||
|
||||
validate :validate_refund
|
||||
|
||||
# params: the refund's permitted params, lines as { key => { refund:, quantity:, amount: } }
|
||||
def self.from_params(params)
|
||||
params = params.to_h.stringify_keys
|
||||
form = new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] })
|
||||
form.lines = (params['lines'] || {}).to_h.to_h do |key, line|
|
||||
line = line.to_h.stringify_keys
|
||||
[key.to_s, LineChoice.new(refund: line['refund'].to_s, quantity: line['quantity'].to_s.strip,
|
||||
amount: line['amount'].to_s.strip.delete('$,'))]
|
||||
end
|
||||
form
|
||||
end
|
||||
|
||||
def self.permitted
|
||||
ATTRIBUTES + [{ lines: {} }]
|
||||
end
|
||||
|
||||
def lines
|
||||
@lines ||= {}
|
||||
end
|
||||
|
||||
def line(key)
|
||||
lines[key.to_s]
|
||||
end
|
||||
|
||||
def chosen
|
||||
lines.select { |_, line| line.refund? }
|
||||
end
|
||||
|
||||
def txn_date_value
|
||||
EstimateForm.date(txn_date)
|
||||
end
|
||||
|
||||
def check?
|
||||
method == 'check'
|
||||
end
|
||||
|
||||
FLAGS.each do |flag|
|
||||
define_method(:"#{flag}?") { send(flag).to_s == '1' || send(flag) == true }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def validate_refund
|
||||
errors.add(:base, I18n.t(:error_estimate_needs_customer)) if customer_id.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_no_invoice)) if invoice_id.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_method)) unless QboRefund::METHODS.include?(method)
|
||||
errors.add(:base, I18n.t(:error_refund_check_number)) if check? && check_number.blank?
|
||||
errors.add(:base, I18n.t(:error_refund_reason)) if reason.blank?
|
||||
errors.add(:base, I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_refund_date))) if txn_date_value.nil?
|
||||
errors.add(:base, I18n.t(:error_refund_no_lines)) if chosen.empty?
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,348 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
#
|
||||
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
#
|
||||
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
module RedmineQboBilling
|
||||
# Refunds of completed work: an invoice that's billed and paid in full (SOP-OPS-014 for the restocking fee).
|
||||
# QuickBooks' way to refund a paid sale is a Refund Receipt, which this makes:
|
||||
#
|
||||
# * the invoice lines refunded (all or part of each), with their product/service and tax code, so the income
|
||||
# and the sales tax come back off the books the way they went on (QuickBooks works out the tax);
|
||||
# * the invoice's discount, if it had one, in proportion to what's refunded;
|
||||
# * the restocking fee, when it's charged, as a negative line with the restocking fee product/service:
|
||||
# its rate (plugin setting) of the parts refunded. Labor carries no fee, and work with no parts has none;
|
||||
# * paid out of the refund check or card refund bank account in the settings, by company check (its number)
|
||||
# or a refund on the card terminal.
|
||||
#
|
||||
# The invoice itself stays as it is, paid. Each refund is recorded (QboRefund, kind invoice) with the lines it
|
||||
# refunded, so a line can't be refunded for more than it was billed across several refunds. Then, as asked on
|
||||
# the page, the refund is noted on the invoice's work orders and the customer is emailed a summary.
|
||||
module InvoiceRefundWriter
|
||||
Error = RefundWriter::Error
|
||||
|
||||
# An invoice line that can be refunded, with what earlier refunds already took of it
|
||||
Line = Struct.new(:key, :item_id, :item_name, :description, :quantity, :rate, :amount, :taxable, :parts,
|
||||
:refunded_quantity, :refunded_amount, keyword_init: true) do
|
||||
def remaining_amount
|
||||
[amount - refunded_amount, BigDecimal('0')].max
|
||||
end
|
||||
|
||||
def remaining_quantity
|
||||
quantity && [quantity - refunded_quantity, BigDecimal('0')].max
|
||||
end
|
||||
|
||||
def refundable?
|
||||
remaining_amount.positive?
|
||||
end
|
||||
|
||||
def label
|
||||
[item_name.presence, description.presence].compact.uniq.join(' · ')
|
||||
end
|
||||
end
|
||||
|
||||
# A line being refunded: the invoice line, the quantity (nil when only an amount is refunded) and the amount
|
||||
Refunding = Struct.new(:line, :quantity, :amount, keyword_init: true)
|
||||
|
||||
# What a refund comes to: the lines, the invoice discount's share, the fee, the tax (estimated before
|
||||
# QuickBooks works it out) and the refund
|
||||
Plan = Struct.new(:refunding, :lines_amount, :parts_amount, :discount_rate, :discount, :fee_rate, :fee,
|
||||
:tax_rate, :tax, :refund, keyword_init: true)
|
||||
|
||||
module_function
|
||||
|
||||
def settings
|
||||
RefundWriter.settings
|
||||
end
|
||||
|
||||
# Billed and paid in full: a total, and nothing left owing
|
||||
def paid_in_full?(remote)
|
||||
total = BigDecimal(remote&.total.to_s.presence || '0')
|
||||
balance = BigDecimal(remote&.balance.to_s.presence || '0')
|
||||
total.positive? && balance <= 0
|
||||
end
|
||||
|
||||
# The customer's paid invoices to pick from on the Refund page, newest first: [[label, id], ...]
|
||||
def invoice_choices(customer)
|
||||
Invoice.where(customer_id: customer.id).where('balance <= 0 AND total_amount > 0')
|
||||
.order(txn_date: :desc, id: :desc).limit(50).map do |invoice|
|
||||
["##{invoice.doc_number} · #{invoice.txn_date} · #{RefundWriter.money(invoice.total_amount)}", invoice.id.to_s]
|
||||
end
|
||||
end
|
||||
|
||||
# The invoice's lines that can be refunded (bundles opened up into their lines), with what this invoice's
|
||||
# earlier refunds took of each
|
||||
def lines(remote, refunds: QboRefund.of_invoice(remote.id))
|
||||
taken = Hash.new { |hash, key| hash[key] = [BigDecimal('0'), BigDecimal('0')] }
|
||||
refunds.each do |refund|
|
||||
refund.refunded_lines.each do |line|
|
||||
taken[line.key][0] += BigDecimal(line.quantity.to_s.presence || '0')
|
||||
taken[line.key][1] += line.amount.to_d
|
||||
end
|
||||
end
|
||||
|
||||
labor_ids = LaborItems.ids
|
||||
sales_lines(Array(remote.line_items)).filter_map do |line, key|
|
||||
detail = RefundWriter.sales_detail(line)
|
||||
amount = BigDecimal(line.amount.to_s.presence || '0')
|
||||
next unless amount.positive?
|
||||
|
||||
ref = detail&.item_ref
|
||||
quantity = detail&.quantity.nil? ? nil : BigDecimal(detail.quantity.to_s)
|
||||
quantity = nil unless quantity&.positive?
|
||||
Line.new(key: key, item_id: ref&.value.to_s.presence, item_name: ref&.name.to_s, description: line.description.to_s,
|
||||
quantity: quantity, rate: detail&.unit_price.nil? ? nil : BigDecimal(detail.unit_price.to_s),
|
||||
amount: amount, taxable: detail&.tax_code_ref&.value.to_s == 'TAX',
|
||||
parts: ref.present? && ref.value.present? && !LaborItems.match?(ref, ids: labor_ids),
|
||||
refunded_quantity: taken[key][0], refunded_amount: taken[key][1])
|
||||
end
|
||||
end
|
||||
|
||||
# The sales lines with a key for each: its QuickBooks line id, or for a line in a bundle the bundle's id and
|
||||
# its place in it
|
||||
def sales_lines(lines, prefix = nil)
|
||||
lines.each_with_index.flat_map do |line, index|
|
||||
key = "#{prefix}#{line.id.presence || index + 1}"
|
||||
if line.respond_to?(:group_line_detail) && line.group_line_detail
|
||||
sales_lines(Array(line.group_line_detail.line_items), "#{key}.")
|
||||
elsif RefundWriter.sales_detail(line)
|
||||
[[line, key]]
|
||||
else
|
||||
[]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# The invoice's discount, as a share of its lines (0.1 for 10% off)
|
||||
def discount_rate(remote)
|
||||
discount = EstimateWriter.discount_total(remote).to_d
|
||||
subtotal = sales_lines(Array(remote.line_items)).sum(BigDecimal('0')) { |line, _| BigDecimal(line.amount.to_s.presence || '0') }
|
||||
return BigDecimal('0') unless discount.positive? && subtotal.positive?
|
||||
|
||||
[discount / subtotal, BigDecimal('1')].min
|
||||
end
|
||||
|
||||
# The invoice's sales tax, as a share of its taxable lines after the discount, to estimate the tax refunded
|
||||
def tax_rate(remote, invoice_lines = lines(remote, refunds: []))
|
||||
tax = BigDecimal(remote.txn_tax_detail&.total_tax.to_s.presence || '0')
|
||||
taxable = invoice_lines.select(&:taxable).sum(BigDecimal('0'), &:amount) * (1 - discount_rate(remote))
|
||||
tax.positive? && taxable.positive? ? tax / taxable : BigDecimal('0')
|
||||
end
|
||||
|
||||
# Works out the refund from the form's lines: [plan, errors]
|
||||
def plan(remote, form, invoice_lines: lines(remote))
|
||||
errors = []
|
||||
by_key = invoice_lines.index_by(&:key)
|
||||
refunding = form.chosen.filter_map do |key, choice|
|
||||
line = by_key[key]
|
||||
if line.nil?
|
||||
errors << I18n.t(:error_refund_line_gone)
|
||||
next
|
||||
end
|
||||
|
||||
refunding_line(line, choice, errors)
|
||||
end
|
||||
|
||||
lines_amount = refunding.sum(BigDecimal('0'), &:amount)
|
||||
parts = refunding.select { |r| r.line.parts }.sum(BigDecimal('0'), &:amount)
|
||||
rate = discount_rate(remote)
|
||||
discount = (lines_amount * rate).round(2, BigDecimal::ROUND_HALF_UP)
|
||||
fee_rate = RefundWriter.fee_rate
|
||||
fee = form.charge_fee? ? RefundWriter.fee(parts, fee_rate) : BigDecimal('0')
|
||||
tax_rate = tax_rate(remote, invoice_lines)
|
||||
taxable = refunding.select { |r| r.line.taxable }.sum(BigDecimal('0'), &:amount) * (1 - rate)
|
||||
tax = (taxable * tax_rate).round(2, BigDecimal::ROUND_HALF_UP)
|
||||
refund = lines_amount - discount + tax - fee
|
||||
if refunding.any? && fee >= lines_amount - discount
|
||||
errors << I18n.t(:error_refund_fee_over_lines, fee: RefundWriter.money(fee), amount: RefundWriter.money(lines_amount - discount))
|
||||
end
|
||||
|
||||
plan = Plan.new(refunding: refunding, lines_amount: lines_amount, parts_amount: parts, discount_rate: rate,
|
||||
discount: discount, fee_rate: fee_rate, fee: fee, tax_rate: tax_rate, tax: tax,
|
||||
refund: [refund, BigDecimal('0')].max)
|
||||
[plan, errors.uniq]
|
||||
end
|
||||
|
||||
# A line being refunded, from what was posted for it: the quantity and the amount (by default the quantity
|
||||
# at the line's rate, or what's left of the line). Adds to errors when it can't be refunded.
|
||||
def refunding_line(line, choice, errors)
|
||||
name = line.label.presence || line.key
|
||||
quantity = choice.quantity_value
|
||||
quantity = nil if line.quantity.nil? || line.rate.nil?
|
||||
amount = choice.amount_value
|
||||
amount ||= quantity ? (quantity * line.rate).round(2) : line.remaining_amount
|
||||
|
||||
if quantity && (quantity <= 0 || quantity > line.remaining_quantity)
|
||||
errors << I18n.t(:error_refund_line_quantity, line: name, quantity: RefundWriter.plain(line.remaining_quantity))
|
||||
return nil
|
||||
end
|
||||
if amount.nil? || amount <= 0
|
||||
errors << I18n.t(:error_refund_line_amount, line: name)
|
||||
return nil
|
||||
end
|
||||
if amount > line.remaining_amount
|
||||
errors << I18n.t(:error_refund_line_over, line: name, amount: RefundWriter.money(line.remaining_amount))
|
||||
return nil
|
||||
end
|
||||
|
||||
# A partial amount (not the quantity at the line's rate) is refunded as an amount alone, so it doesn't
|
||||
# use up the line's quantity
|
||||
quantity = nil if quantity && (quantity * line.rate).round(2) != amount
|
||||
Refunding.new(line: line, quantity: quantity, amount: amount)
|
||||
end
|
||||
|
||||
# The quantity to offer for a line: what's left of it, when that's what's left of its amount at its rate
|
||||
def default_quantity(line)
|
||||
quantity = line.remaining_quantity
|
||||
return nil unless quantity&.positive? && line.rate
|
||||
|
||||
(quantity * line.rate).round(2) == line.remaining_amount ? quantity : nil
|
||||
end
|
||||
|
||||
# Makes the refund receipt; returns the QboRefund (done, or incomplete with why in its message). Raises
|
||||
# Error, before anything is made in QuickBooks, when the refund can't be made as asked.
|
||||
def refund!(form, user: User.current, gateway: RefundGateway.new, mailer: QboRefundMailer)
|
||||
customer = Customer.find_by(id: form.customer_id)
|
||||
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
|
||||
|
||||
remote = gateway.invoice(form.invoice_id)
|
||||
raise Error, I18n.t(:notice_invoice_not_found) unless remote
|
||||
raise Error, I18n.t(:error_refund_invoice_customer) unless remote.customer_ref&.value.to_s == customer.id.to_s
|
||||
raise Error, I18n.t(:error_refund_invoice_not_paid) unless paid_in_full?(remote)
|
||||
|
||||
plan, errors = plan(remote, form)
|
||||
raise Error, errors.join(' ') if errors.any?
|
||||
raise Error, I18n.t(:error_refund_no_lines) if plan.refunding.empty?
|
||||
|
||||
item = RefundWriter.fee_item
|
||||
raise Error, I18n.t(:error_refund_no_fee_item) if plan.fee.positive? && item.nil?
|
||||
|
||||
bank_account = settings[form.check? ? 'refund_check_account_id' : 'refund_card_account_id'].presence || gateway.account_id('Bank')
|
||||
raise Error, I18n.t(:error_refund_no_bank_account) unless bank_account
|
||||
|
||||
paid = BigDecimal(remote.total.to_s) - BigDecimal(remote.balance.to_s.presence || '0')
|
||||
record = QboRefund.create!(kind: 'invoice', customer_id: customer.id, invoice_id: remote.id,
|
||||
invoice_number: remote.doc_number.to_s, user: user, txn_date: form.txn_date_value,
|
||||
method: form.method, check_number: form.check? ? form.check_number : nil,
|
||||
reason: form.reason, lines_amount: plan.lines_amount, discount_amount: plan.discount,
|
||||
parts_amount: plan.parts_amount, fee_rate: plan.fee_rate, fee_amount: plan.fee,
|
||||
tax_amount: plan.tax, credit_amount: paid, refund_amount: plan.refund,
|
||||
refunded_lines: refunded_lines(plan), status: 'incomplete')
|
||||
|
||||
made = RefundWriter.step(record, :receipt) do
|
||||
receipt = build_receipt(record, remote, plan, form, item, bank_account, gateway)
|
||||
saved = gateway.create_refund_receipt(receipt)
|
||||
raise Error, I18n.t(:error_refund_not_saved) unless saved&.id
|
||||
|
||||
tax = saved.txn_tax_detail&.total_tax
|
||||
record.update!(purchase_id: saved.id.to_s, receipt_number: saved.doc_number.to_s,
|
||||
refund_amount: saved.total.nil? ? plan.refund : BigDecimal(saved.total.to_s),
|
||||
tax_amount: tax.nil? ? plan.tax : BigDecimal(tax.to_s))
|
||||
end
|
||||
return record unless made
|
||||
|
||||
warnings = []
|
||||
warnings << note_issues(record, user) if form.note_issues?
|
||||
warnings << RefundWriter.email_customer(record, customer, mailer) if form.email_customer?
|
||||
record.update!(status: 'done', message: warnings.compact.join("\n").presence)
|
||||
record
|
||||
end
|
||||
|
||||
def refunded_lines(plan)
|
||||
plan.refunding.map do |r|
|
||||
QboRefund::RefundedLine.new(key: r.line.key, description: r.line.label, quantity: r.quantity,
|
||||
amount: r.amount, parts: r.line.parts)
|
||||
end
|
||||
end
|
||||
|
||||
# The QuickBooks Refund Receipt: the lines refunded, the discount's share, the restocking fee
|
||||
def build_receipt(record, remote, plan, form, fee_item, bank_account, gateway)
|
||||
receipt = Quickbooks::Model::RefundReceipt.new
|
||||
receipt.customer_ref = Quickbooks::Model::BaseReference.new(record.customer_id.to_s)
|
||||
receipt.txn_date = record.txn_date
|
||||
receipt.deposit_to_account_ref = Quickbooks::Model::BaseReference.new(bank_account.to_s)
|
||||
method_id = gateway.payment_method_id(form.check? ? :check : :card)
|
||||
receipt.payment_method_ref = Quickbooks::Model::BaseReference.new(method_id) if method_id
|
||||
receipt.payment_ref_number = record.check_number if form.check?
|
||||
receipt.bill_email = remote.bill_email if remote.bill_email&.address.present?
|
||||
receipt.customer_memo = I18n.t(:text_refund_receipt_memo, number: record.invoice_number)
|
||||
receipt.private_note = I18n.t(:text_refund_invoice_private_note, number: record.invoice_number, reason: record.reason)
|
||||
receipt.apply_tax_after_discount = true if plan.discount.positive?
|
||||
|
||||
lines = plan.refunding.map { |r| receipt_line(r) }
|
||||
lines << discount_line(plan) if plan.discount.positive?
|
||||
lines << fee_line(record, fee_item) if plan.fee.positive?
|
||||
lines.each_with_index { |line, index| line.line_num = index + 1 }
|
||||
receipt.line_items = lines
|
||||
receipt
|
||||
end
|
||||
|
||||
# A refunded line: the invoice line's product/service and tax code. Its quantity and rate go with it when
|
||||
# the amount is that quantity at the line's rate (refunding_line); a partial amount goes as an amount alone.
|
||||
def receipt_line(refunding)
|
||||
line = refunding.line
|
||||
remote = Quickbooks::Model::Line.new
|
||||
remote.description = line.description
|
||||
remote.amount = refunding.amount
|
||||
remote.sales_item! do |detail|
|
||||
detail.item_ref = Quickbooks::Model::BaseReference.new(line.item_id) if line.item_id
|
||||
if refunding.quantity
|
||||
detail.quantity = refunding.quantity
|
||||
detail.unit_price = line.rate
|
||||
end
|
||||
detail.tax_code_ref = Quickbooks::Model::BaseReference.new(line.taxable ? 'TAX' : 'NON')
|
||||
end
|
||||
remote
|
||||
end
|
||||
|
||||
def discount_line(plan)
|
||||
remote = Quickbooks::Model::Line.new
|
||||
remote.amount = plan.discount
|
||||
remote.discount! { |detail| detail.percent_based = false }
|
||||
remote
|
||||
end
|
||||
|
||||
# The restocking fee, kept back: a negative line, so the fee is income and the refund is less by it
|
||||
def fee_line(record, item)
|
||||
remote = Quickbooks::Model::Line.new
|
||||
remote.amount = -record.fee_amount
|
||||
remote.description = RefundWriter.fee_description(record.parts_amount, record.fee_rate, record.fee_amount,
|
||||
nil, on: record.document_label)
|
||||
remote.sales_item! do |detail|
|
||||
detail.item_id = item.id
|
||||
detail.quantity = 1
|
||||
detail.unit_price = -record.fee_amount
|
||||
detail.tax_code_ref = Quickbooks::Model::BaseReference.new('NON')
|
||||
end
|
||||
remote
|
||||
end
|
||||
|
||||
# Notes the refund on the invoice's work orders (their status is left alone); returns a warning, or nil
|
||||
def note_issues(record, user)
|
||||
issues = Invoice.find_by(id: record.invoice_id)&.issues.to_a
|
||||
return nil if issues.empty?
|
||||
|
||||
note = I18n.t(:text_refund_invoice_issue_note, amount: RefundWriter.money(record.refund_amount),
|
||||
number: record.invoice_number, method: record.method_name,
|
||||
reason: record.reason)
|
||||
failed = []
|
||||
noted = issues.filter_map do |issue|
|
||||
issue.init_journal(user, note)
|
||||
if issue.save
|
||||
issue.id
|
||||
else
|
||||
failed << "##{issue.id} (#{issue.errors.full_messages.join(', ')})"
|
||||
nil
|
||||
end
|
||||
end
|
||||
record.update!(noted_issue_ids: noted)
|
||||
failed.any? ? I18n.t(:text_refund_issues_not_noted, issues: failed.join('; ')) : nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -59,6 +59,19 @@ module RedmineQboBilling
|
||||
with_service('Purchase') { |service| service.create(purchase) }
|
||||
end
|
||||
|
||||
# A paid invoice's refund (InvoiceRefundWriter)
|
||||
def create_refund_receipt(receipt)
|
||||
with_service('RefundReceipt') { |service| service.create(receipt) }
|
||||
end
|
||||
|
||||
PAYMENT_METHOD_NAMES = { check: /\b(check|cheque)\b/i, card: /card|visa|mastercard|amex|discover/i }.freeze
|
||||
|
||||
# QuickBooks' payment method for a refund by :check or :card (the first whose name fits), or nil
|
||||
def payment_method_id(kind)
|
||||
pattern = PAYMENT_METHOD_NAMES[kind]
|
||||
PaymentWriter.payment_methods.detect { |name, _| name.match?(pattern) }&.last
|
||||
end
|
||||
|
||||
# The first active account of a QuickBooks account type ('Accounts Receivable', 'Bank')
|
||||
def account_id(type)
|
||||
account = with_service('Account') do |service|
|
||||
|
||||
@@ -55,7 +55,8 @@ module RedmineQboBilling
|
||||
def details(pdf)
|
||||
rows = [[l(:label_customer), @refund.customer&.name.to_s],
|
||||
[l(:label_refund_date), format_date(@refund.txn_date)],
|
||||
[l(:label_refund_estimate), @refund.estimate_number.present? ? "E#{@refund.estimate_number}" : l(:label_refund_no_estimate)],
|
||||
@refund.invoice? ? [l(:label_refund_invoice), @refund.document_label] :
|
||||
[l(:label_refund_estimate), @refund.estimate_number.present? ? "E#{@refund.estimate_number}" : l(:label_refund_no_estimate)],
|
||||
[l(:label_refund_reason), @refund.reason.to_s]]
|
||||
rows.each { |label, value| row(pdf, label, value) }
|
||||
end
|
||||
@@ -65,7 +66,11 @@ module RedmineQboBilling
|
||||
pdf.RDMCell(WIDTH, 6, l(:label_refund_summary), 'B', 1)
|
||||
pdf.SetFontStyle('', 10)
|
||||
fee = @refund.fee_amount.to_d
|
||||
money_row(pdf, l(:label_refund_credit), @refund.credit_amount)
|
||||
if @refund.invoice?
|
||||
invoice_lines(pdf)
|
||||
else
|
||||
money_row(pdf, l(:label_refund_credit), @refund.credit_amount)
|
||||
end
|
||||
if fee.positive?
|
||||
label = l(:label_refund_pdf_fee, rate: RefundWriter.plain(@refund.fee_rate), parts: RefundWriter.money(@refund.parts_amount))
|
||||
label += " · #{l(:label_refund_fee_invoice, number: @refund.fee_invoice_number)}" if @refund.fee_invoice_number.present?
|
||||
@@ -79,11 +84,24 @@ module RedmineQboBilling
|
||||
end
|
||||
end
|
||||
|
||||
# A paid invoice's refund: each line refunded, the discount's share and the sales tax
|
||||
def invoice_lines(pdf)
|
||||
@refund.refunded_lines.each do |line|
|
||||
quantity = line.quantity.present? ? " (#{RefundWriter.plain(BigDecimal(line.quantity.to_s))})" : ''
|
||||
money_row(pdf, "#{line.description.truncate(90)}#{quantity}", line.amount)
|
||||
end
|
||||
money_row(pdf, l(:label_refund_discount), -@refund.discount_amount.to_d) if @refund.discount_amount.to_d.positive?
|
||||
money_row(pdf, l(:label_refund_tax), @refund.tax_amount)
|
||||
end
|
||||
|
||||
def notes(pdf)
|
||||
pdf.SetFontStyle('', 9)
|
||||
issues = Issue.where(id: @refund.canceled_issue_ids).to_a
|
||||
row(pdf, l(:label_refund_pdf_work_orders), issues.map { |i| "#{i.tracker} ##{i.id}: #{i.subject}" }.join("\n")) if issues.any?
|
||||
row(pdf, l(:label_refund_pdf_estimate), l(:text_refund_pdf_estimate_rejected, number: @refund.estimate_number)) if @refund.estimate_closed?
|
||||
if @refund.invoice? && @refund.receipt_number.present?
|
||||
row(pdf, l(:label_refund_receipt), l(:text_refund_receipt_number, number: @refund.receipt_number))
|
||||
end
|
||||
row(pdf, l(:label_refund_recorded_by), "#{@refund.user&.name} · #{format_time(@refund.created_at)}")
|
||||
row(pdf, l(:label_refund_incomplete), @refund.message.to_s) unless @refund.done?
|
||||
end
|
||||
|
||||
@@ -108,9 +108,9 @@ module RedmineQboBilling
|
||||
refund: [total - amount, BigDecimal('0')].max)
|
||||
end
|
||||
|
||||
# "Restocking fee: 30% × $1,026.63 parts on E1068 = $308.00"
|
||||
def fee_description(parts, rate, amount, estimate_number)
|
||||
on = estimate_number.present? ? " on E#{estimate_number}" : ''
|
||||
# "Restocking fee: 30% × $1,026.63 parts on E1068 = $308.00" (on: what the parts are on instead, e.g. "Invoice #1234")
|
||||
def fee_description(parts, rate, amount, estimate_number, on: nil)
|
||||
on = on.present? ? " on #{on}" : (estimate_number.present? ? " on E#{estimate_number}" : '')
|
||||
I18n.t(:text_refund_fee_line, rate: plain(rate), parts: money(parts), on: on, fee: money(amount))
|
||||
end
|
||||
|
||||
|
||||
@@ -98,4 +98,97 @@ class QboRefundsTest < Redmine::IntegrationTest
|
||||
get "/qbo_refunds/#{refund.id}"
|
||||
assert_select 'a[href=?]', "/qbo_refunds/#{refund.id}/pdf"
|
||||
end
|
||||
|
||||
# ---- Paid invoices ----
|
||||
|
||||
def invoice_setup
|
||||
RedmineQboBilling::LaborItems.stubs(:ids).returns([])
|
||||
@gateway.invoices << paid_invoice
|
||||
end
|
||||
|
||||
def test_invoice_refund_page
|
||||
invoice_setup
|
||||
log_user('admin', 'admin')
|
||||
get '/qbo_refunds/new_invoice?invoice_id=950'
|
||||
assert_response :success
|
||||
assert_select 'h2', text: /Invoice #1234/
|
||||
assert_select 'input[type=checkbox][name=?][checked]', 'refund[lines][2][refund]'
|
||||
assert_select 'input[name=?][value=?]', 'refund[lines][2][quantity]', '4'
|
||||
assert_select 'input[name=?][value=?]', 'refund[lines][3][amount]', '80.00'
|
||||
assert_select 'input[name=?][checked]', 'refund[charge_fee]'
|
||||
# Everything ticked: $440.00 of lines, $14.00 tax, 30% of $200.00 parts
|
||||
assert_select '#qbo-refund-lines-amount', text: '$440.00'
|
||||
assert_select '#qbo-refund-tax', text: '$14.00'
|
||||
assert_select '#qbo-refund-fee', text: '-$60.00'
|
||||
assert_select '#qbo-refund-amount', text: '$394.00'
|
||||
end
|
||||
|
||||
def test_unpaid_invoice_isnt_refunded
|
||||
RedmineQboBilling::LaborItems.stubs(:ids).returns([])
|
||||
@gateway.invoices << paid_invoice(balance: 50)
|
||||
log_user('admin', 'admin')
|
||||
get '/qbo_refunds/new_invoice?invoice_id=950'
|
||||
assert_redirected_to '/qbo_invoices/950/edit'
|
||||
end
|
||||
|
||||
def test_invoice_refund
|
||||
invoice_setup
|
||||
log_user('admin', 'admin')
|
||||
post '/qbo_refunds/create_invoice', params: { refund: {
|
||||
customer_id: CUSTOMER_ID, invoice_id: '950', method: 'card', txn_date: '2026-11-18', reason: 'Returned pads',
|
||||
charge_fee: '0', note_issues: '1', email_customer: '0',
|
||||
lines: { '1' => { refund: '0', quantity: '2', amount: '240.00' }, '2' => { refund: '1', quantity: '2', amount: '60.00' },
|
||||
'3' => { refund: '0', quantity: '1', amount: '80.00' } }
|
||||
} }
|
||||
refund = QboRefund.last
|
||||
assert_redirected_to "/qbo_refunds/#{refund.id}"
|
||||
assert refund.done?, refund.message
|
||||
assert_equal BigDecimal('64.20'), refund.refund_amount
|
||||
follow_redirect!
|
||||
assert_select 'p', text: /Refund receipt 3000 is recorded/
|
||||
assert_select 'a[href*="app/refundreceipt?txnId=900"]'
|
||||
assert_select 'a[href=?]', '/qbo_invoices/950/edit'
|
||||
|
||||
get '/qbo_refunds/new_invoice?invoice_id=950'
|
||||
assert_select 'input[name=?][value=?]', 'refund[lines][2][quantity]', '2'
|
||||
assert_select '.flash.warning a[href=?]', "/qbo_refunds/#{refund.id}"
|
||||
|
||||
get "/qbo_refunds/#{refund.id}/pdf"
|
||||
assert_response :success
|
||||
|
||||
get "/customers/#{CUSTOMER_ID}"
|
||||
assert_select 'a[href=?]', '/qbo_invoices/950/edit', text: 'Invoice #1234'
|
||||
end
|
||||
|
||||
def test_invoice_refund_form_errors
|
||||
invoice_setup
|
||||
log_user('admin', 'admin')
|
||||
post '/qbo_refunds/create_invoice', params: { refund: {
|
||||
customer_id: CUSTOMER_ID, invoice_id: '950', method: 'check', check_number: '', txn_date: '2026-11-18', reason: '',
|
||||
lines: { '2' => { refund: '1', quantity: '9' } }
|
||||
} }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /check number/
|
||||
assert_select '#errorExplanation', text: /reason/
|
||||
|
||||
post '/qbo_refunds/create_invoice', params: { refund: {
|
||||
customer_id: CUSTOMER_ID, invoice_id: '950', method: 'check', check_number: '1', txn_date: '2026-11-18', reason: 'x',
|
||||
lines: { '2' => { refund: '1', quantity: '9' } }
|
||||
} }
|
||||
assert_response :unprocessable_entity
|
||||
assert_select '#errorExplanation', text: /no more than 4/
|
||||
assert_equal 0, QboRefund.count
|
||||
assert_empty @gateway.receipts
|
||||
end
|
||||
|
||||
def test_credit_refund_page_offers_paid_invoices
|
||||
Invoice.where(id: 950).delete_all
|
||||
Invoice.new(id: 950, doc_number: '1234', txn_date: Date.new(2026, 11, 2), customer_id: CUSTOMER_ID,
|
||||
total_amount: 454, balance: 0).save!(validate: false)
|
||||
log_user('admin', 'admin')
|
||||
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}"
|
||||
assert_select '#qbo_refund_invoice option[value="950"]', text: /#1234/
|
||||
ensure
|
||||
Invoice.where(id: 950).delete_all
|
||||
end
|
||||
end
|
||||
+74
-1
@@ -15,7 +15,7 @@ module QboRefundTestHelper
|
||||
|
||||
# Stands in for QuickBooks: the customer's payments, and what the refund made
|
||||
class FakeGateway
|
||||
attr_reader :payments, :invoices, :purchases, :applied, :rejected
|
||||
attr_reader :payments, :invoices, :purchases, :applied, :rejected, :receipts
|
||||
attr_accessor :auto_apply, :fail_on, :estimate_record, :balance
|
||||
|
||||
def initialize(payments: [], estimate: nil)
|
||||
@@ -25,6 +25,7 @@ module QboRefundTestHelper
|
||||
@purchases = []
|
||||
@applied = []
|
||||
@rejected = []
|
||||
@receipts = []
|
||||
@auto_apply = false
|
||||
@balance = BigDecimal('0')
|
||||
end
|
||||
@@ -78,6 +79,28 @@ module QboRefundTestHelper
|
||||
purchase
|
||||
end
|
||||
|
||||
# QuickBooks' refund receipt: tax at 7% on the taxable lines, after the discount's share
|
||||
def create_refund_receipt(receipt)
|
||||
raise Quickbooks::IntuitRequestException, 'QuickBooks is down' if fail_on == :receipt
|
||||
|
||||
sales = receipt.line_items.select { |l| l.detail_type.to_s == 'SalesItemLineDetail' }
|
||||
discount = receipt.line_items.select { |l| l.detail_type.to_s == 'DiscountLineDetail' }.sum(BigDecimal('0')) { |l| l.amount.to_d }
|
||||
lines = sales.sum(BigDecimal('0')) { |l| l.amount.to_d.positive? ? l.amount.to_d : 0 }
|
||||
taxable = sales.select { |l| l.sales_item_line_detail.tax_code_ref&.value == 'TAX' }.sum(BigDecimal('0')) { |l| l.amount.to_d }
|
||||
tax = (taxable * (lines.positive? ? 1 - discount / lines : 1) * BigDecimal('0.07')).round(2)
|
||||
receipt.id = (900 + receipts.size).to_s
|
||||
receipt.doc_number = (3000 + receipts.size).to_s
|
||||
receipt.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
|
||||
receipt.txn_tax_detail.total_tax = tax
|
||||
receipt.total = sales.sum(BigDecimal('0')) { |l| l.amount.to_d } - discount + tax
|
||||
receipts << receipt
|
||||
receipt
|
||||
end
|
||||
|
||||
def payment_method_id(kind)
|
||||
{ check: '2', card: '3' }[kind]
|
||||
end
|
||||
|
||||
def account_id(type)
|
||||
{ 'Accounts Receivable' => '84', 'Bank' => '35' }[type]
|
||||
end
|
||||
@@ -160,6 +183,56 @@ module QboRefundTestHelper
|
||||
Struct.new(:id, :name).new('55', 'Restocking Fee')
|
||||
end
|
||||
|
||||
def sales_line(id, item_id, name, quantity, rate, taxable: true, description: '')
|
||||
line = Quickbooks::Model::InvoiceLineItem.new
|
||||
line.id = id.to_s
|
||||
line.description = description
|
||||
line.amount = (BigDecimal(quantity.to_s) * BigDecimal(rate.to_s)).round(2)
|
||||
line.sales_item! do |d|
|
||||
d.item_ref = Quickbooks::Model::BaseReference.new(item_id.to_s, name: name)
|
||||
d.quantity = BigDecimal(quantity.to_s)
|
||||
d.unit_price = BigDecimal(rate.to_s)
|
||||
d.tax_code_ref = Quickbooks::Model::BaseReference.new(taxable ? 'TAX' : 'NON')
|
||||
end
|
||||
line
|
||||
end
|
||||
|
||||
# Invoice #1234, paid in full: 2 h labor at $120 (not taxed), 4 brake pads at $30 and a $80 rotor (taxed at
|
||||
# 7%: $14.00), $454.00 in all
|
||||
def paid_invoice(id: 950, balance: 0, customer_id: CUSTOMER_ID, discount: nil)
|
||||
invoice = Quickbooks::Model::Invoice.new
|
||||
invoice.id = id.to_s
|
||||
invoice.doc_number = '1234'
|
||||
invoice.txn_date = Date.new(2026, 11, 2)
|
||||
invoice.customer_ref = Quickbooks::Model::BaseReference.new(customer_id.to_s)
|
||||
invoice.line_items = [sales_line(1, 1, 'Labor', 2, 120, taxable: false, description: 'Brake job'),
|
||||
sales_line(2, 3, 'Brake Pads', 4, 30, description: 'Ceramic pads'),
|
||||
sales_line(3, 4, 'Rotor', 1, 80, description: 'Front rotor')]
|
||||
tax = BigDecimal('14')
|
||||
if discount
|
||||
line = Quickbooks::Model::InvoiceLineItem.new
|
||||
line.amount = BigDecimal(discount.to_s)
|
||||
line.discount_item! { |d| d.percent_based = false }
|
||||
invoice.line_items = invoice.line_items + [line]
|
||||
tax = (BigDecimal('200') * (1 - BigDecimal(discount.to_s) / 440) * BigDecimal('0.07')).round(2)
|
||||
end
|
||||
invoice.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
|
||||
invoice.txn_tax_detail.total_tax = tax
|
||||
invoice.total = BigDecimal('440') - BigDecimal((discount || 0).to_s) + tax
|
||||
invoice.balance = BigDecimal(balance.to_s)
|
||||
invoice
|
||||
end
|
||||
|
||||
def invoice_refund_form(attributes = {})
|
||||
form = RedmineQboBilling::InvoiceRefundForm.from_params(
|
||||
{ customer_id: CUSTOMER_ID.to_s, invoice_id: '950', txn_date: '2026-11-18', method: 'check',
|
||||
check_number: '5002', reason: 'Parts returned unused', charge_fee: '1', note_issues: '1',
|
||||
email_customer: '1', lines: { '2' => { refund: '1', quantity: '4' }, '3' => { refund: '1', quantity: '1' } } }
|
||||
.merge(attributes)
|
||||
)
|
||||
form
|
||||
end
|
||||
|
||||
def refund_form(attributes = {})
|
||||
RedmineQboBilling::RefundForm.new({ customer_id: CUSTOMER_ID.to_s, estimate_id: '598', txn_date: '2026-11-16',
|
||||
parts_amount: '307.99', method: 'check', check_number: '5001',
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2026 rick barrette
|
||||
#
|
||||
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
#
|
||||
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
#
|
||||
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
|
||||
require File.expand_path('../test_helper', __dir__)
|
||||
|
||||
class InvoiceRefundWriterTest < ActiveSupport::TestCase
|
||||
include QboRefundTestHelper
|
||||
Writer = RedmineQboBilling::InvoiceRefundWriter
|
||||
|
||||
def setup
|
||||
User.current = User.find(1)
|
||||
@customer = create_customer
|
||||
Customer.any_instance.stubs(:email).returns('jane@example.com')
|
||||
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(fee_item)
|
||||
RedmineQboBilling::LaborItems.stubs(:ids).returns([])
|
||||
@gateway = FakeGateway.new
|
||||
@gateway.invoices << paid_invoice
|
||||
end
|
||||
|
||||
def refund(form = invoice_refund_form, gateway: @gateway)
|
||||
Writer.refund!(form, user: User.find(1), gateway: gateway, mailer: FakeMailer)
|
||||
end
|
||||
|
||||
def receipt
|
||||
@gateway.receipts.last
|
||||
end
|
||||
|
||||
def test_lines
|
||||
lines = Writer.lines(paid_invoice, refunds: [])
|
||||
assert_equal %w[1 2 3], lines.map(&:key)
|
||||
assert_equal [false, true, true], lines.map(&:parts)
|
||||
assert_equal [false, true, true], lines.map(&:taxable)
|
||||
assert_equal BigDecimal('120'), lines[1].amount
|
||||
assert_equal BigDecimal('4'), lines[1].quantity
|
||||
assert_equal 'Brake Pads · Ceramic pads', lines[1].label
|
||||
end
|
||||
|
||||
def test_lines_inside_bundles
|
||||
invoice = paid_invoice
|
||||
bundle = Quickbooks::Model::InvoiceLineItem.new
|
||||
bundle.id = '7'
|
||||
bundle.amount = BigDecimal('150')
|
||||
bundle.group_line_detail!
|
||||
bundle.group_line_detail.line_items = [sales_line(nil, 1, 'Labor', 1, 100, taxable: false), sales_line(nil, 5, 'Shim Kit', 1, 50)]
|
||||
invoice.line_items = invoice.line_items + [bundle]
|
||||
lines = Writer.lines(invoice, refunds: [])
|
||||
assert_equal %w[1 2 3 7.1 7.2], lines.map(&:key)
|
||||
assert_equal [false, true], lines.last(2).map(&:parts)
|
||||
end
|
||||
|
||||
def test_paid_in_full_only
|
||||
assert Writer.paid_in_full?(paid_invoice)
|
||||
assert_not Writer.paid_in_full?(paid_invoice(balance: 10))
|
||||
end
|
||||
|
||||
# Returned parts by check: $200.00 of parts, a $60.00 fee (30%), $14.00 tax back: $154.00
|
||||
def test_refund_parts_with_fee
|
||||
record = refund
|
||||
assert record.done?, record.message
|
||||
assert record.invoice?
|
||||
assert_equal '1234', record.invoice_number
|
||||
assert_equal BigDecimal('200'), record.lines_amount
|
||||
assert_equal BigDecimal('200'), record.parts_amount
|
||||
assert_equal BigDecimal('60'), record.fee_amount
|
||||
assert_equal BigDecimal('14'), record.tax_amount
|
||||
assert_equal BigDecimal('154'), record.refund_amount
|
||||
assert_equal BigDecimal('454'), record.credit_amount
|
||||
assert_equal '900', record.purchase_id
|
||||
assert_equal '3000', record.receipt_number
|
||||
assert_equal %w[2 3], record.refunded_lines.map(&:key)
|
||||
|
||||
assert_equal '35', receipt.deposit_to_account_ref.value
|
||||
assert_equal '2', receipt.payment_method_ref.value
|
||||
assert_equal '5002', receipt.payment_ref_number
|
||||
assert_equal CUSTOMER_ID.to_s, receipt.customer_ref.value
|
||||
pads, rotor, fee = receipt.line_items
|
||||
assert_equal '3', pads.sales_item_line_detail.item_ref.value
|
||||
assert_equal BigDecimal('4'), pads.sales_item_line_detail.quantity
|
||||
assert_equal BigDecimal('30'), pads.sales_item_line_detail.unit_price
|
||||
assert_equal 'TAX', pads.sales_item_line_detail.tax_code_ref.value
|
||||
assert_equal BigDecimal('80'), rotor.amount
|
||||
assert_equal BigDecimal('-60'), fee.amount
|
||||
assert_equal '55', fee.sales_item_line_detail.item_ref.value
|
||||
assert_equal 'NON', fee.sales_item_line_detail.tax_code_ref.value
|
||||
assert_equal 'Restocking fee: 30% × $200.00 parts on Invoice #1234 = $60.00', fee.description
|
||||
assert_equal [[record.id, 'jane@example.com']], FakeMailer.sent
|
||||
end
|
||||
|
||||
def test_fee_is_optional
|
||||
record = refund(invoice_refund_form(charge_fee: '0'))
|
||||
assert record.done?, record.message
|
||||
assert_equal BigDecimal('0'), record.fee_amount
|
||||
assert_equal BigDecimal('214'), record.refund_amount
|
||||
assert_equal 2, receipt.line_items.size
|
||||
end
|
||||
|
||||
# Work with no parts: no fee, even when it's ticked, and no fee product/service needed
|
||||
def test_labor_only_has_no_fee
|
||||
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(nil)
|
||||
record = refund(invoice_refund_form(lines: { '1' => { refund: '1', quantity: '2' } }, method: 'card', check_number: ''))
|
||||
assert record.done?, record.message
|
||||
assert_equal BigDecimal('0'), record.parts_amount
|
||||
assert_equal BigDecimal('0'), record.fee_amount
|
||||
assert_equal BigDecimal('240'), record.refund_amount
|
||||
assert_equal 1, receipt.line_items.size
|
||||
assert_equal 'NON', receipt.line_items.first.sales_item_line_detail.tax_code_ref.value
|
||||
assert_equal '3', receipt.payment_method_ref.value
|
||||
assert_nil receipt.payment_ref_number
|
||||
assert_nil record.check_number
|
||||
end
|
||||
|
||||
# A goodwill refund of part of the labor: an amount alone, no quantity or rate
|
||||
def test_partial_amount
|
||||
record = refund(invoice_refund_form(lines: { '1' => { refund: '1', quantity: '2', amount: '100' } }))
|
||||
assert record.done?, record.message
|
||||
detail = receipt.line_items.first.sales_item_line_detail
|
||||
assert_equal BigDecimal('100'), receipt.line_items.first.amount
|
||||
assert_nil detail.quantity
|
||||
assert_nil detail.unit_price
|
||||
assert_equal '1', detail.item_ref.value
|
||||
# It doesn't use up the 2 hours: what's left is $140.00, offered without a quantity
|
||||
assert_nil record.refunded_lines.first.quantity
|
||||
labor = Writer.lines(paid_invoice).first
|
||||
assert_equal BigDecimal('2'), labor.remaining_quantity
|
||||
assert_equal BigDecimal('140'), labor.remaining_amount
|
||||
assert_nil Writer.default_quantity(labor)
|
||||
assert_equal BigDecimal('4'), Writer.default_quantity(Writer.lines(paid_invoice)[1])
|
||||
end
|
||||
|
||||
def test_a_line_isnt_refunded_twice
|
||||
first = refund(invoice_refund_form(lines: { '2' => { refund: '1', quantity: '2' } }))
|
||||
assert first.done?, first.message
|
||||
assert_equal BigDecimal('60'), first.lines_amount
|
||||
assert_equal BigDecimal('2'), receipt.line_items.first.sales_item_line_detail.quantity
|
||||
|
||||
lines = Writer.lines(paid_invoice)
|
||||
assert_equal BigDecimal('2'), lines[1].remaining_quantity
|
||||
assert_equal BigDecimal('60'), lines[1].remaining_amount
|
||||
|
||||
error = assert_raises(Writer::Error) { refund(invoice_refund_form(lines: { '2' => { refund: '1', quantity: '3' } })) }
|
||||
assert_match(/no more than 2/, error.message)
|
||||
error = assert_raises(Writer::Error) { refund(invoice_refund_form(lines: { '2' => { refund: '1', amount: '61' } })) }
|
||||
assert_match(/\$60\.00 is left/, error.message)
|
||||
assert refund(invoice_refund_form(lines: { '2' => { refund: '1', quantity: '2' } })).done?
|
||||
end
|
||||
|
||||
def test_discount_share
|
||||
@gateway.invoices.replace([paid_invoice(discount: 44)])
|
||||
record = refund(invoice_refund_form(charge_fee: '0'))
|
||||
assert record.done?, record.message
|
||||
# 10% off the invoice: $20.00 of the $200.00 refunded
|
||||
assert_equal BigDecimal('20'), record.discount_amount
|
||||
discount = receipt.line_items.detect { |l| l.detail_type.to_s == 'DiscountLineDetail' }
|
||||
assert_equal BigDecimal('20'), discount.amount
|
||||
assert receipt.apply_tax_after_discount?
|
||||
assert_equal BigDecimal('192.60'), record.refund_amount
|
||||
end
|
||||
|
||||
def test_checks_before_making_anything
|
||||
@gateway.invoices.replace([paid_invoice(balance: 100)])
|
||||
assert_raises(Writer::Error) { refund }
|
||||
@gateway.invoices.replace([paid_invoice(customer_id: 1)])
|
||||
assert_raises(Writer::Error) { refund }
|
||||
@gateway.invoices.replace([paid_invoice])
|
||||
assert_raises(Writer::Error) { refund(invoice_refund_form(lines: { '9' => { refund: '1' } })) }
|
||||
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(nil)
|
||||
assert_raises(Writer::Error) { refund }
|
||||
assert_equal 0, QboRefund.count
|
||||
assert_empty @gateway.receipts
|
||||
end
|
||||
|
||||
def test_records_when_quickbooks_fails
|
||||
@gateway.fail_on = :receipt
|
||||
record = refund
|
||||
assert_not record.done?
|
||||
assert_match(/refund receipt couldn't be recorded/i, record.message)
|
||||
assert_nil record.purchase_id
|
||||
assert_empty FakeMailer.sent
|
||||
# A refund that made nothing doesn't use up the lines
|
||||
assert_equal BigDecimal('120'), Writer.lines(paid_invoice)[1].remaining_amount
|
||||
end
|
||||
|
||||
def test_notes_the_work_orders
|
||||
Invoice.where(id: 950).delete_all
|
||||
invoice = Invoice.new(id: 950, doc_number: '1234', txn_date: Date.new(2026, 11, 2), customer_id: CUSTOMER_ID,
|
||||
total_amount: 454, balance: 0)
|
||||
invoice.save!(validate: false)
|
||||
invoice.issues << Issue.find(1)
|
||||
status = Issue.find(1).status_id
|
||||
record = refund
|
||||
assert record.done?, record.message
|
||||
assert_equal [1], record.noted_issue_ids
|
||||
issue = Issue.find(1)
|
||||
assert_equal status, issue.status_id
|
||||
assert_equal 'Refunded $154.00 on invoice #1234 by Company check: Parts returned unused', issue.journals.last.notes
|
||||
ensure
|
||||
Invoice.where(id: 950).delete_all
|
||||
end
|
||||
|
||||
def test_the_email
|
||||
record = refund
|
||||
message = QboRefundMailer.refund_summary(record, 'jane@example.com')
|
||||
body = message.body.to_s
|
||||
assert_includes body, "We've processed the refund for Invoice #1234."
|
||||
assert_includes body, 'Brake Pads · Ceramic pads: $120.00'
|
||||
assert_includes body, 'Lines refunded: $200.00'
|
||||
assert_includes body, 'Sales tax: $14.00'
|
||||
assert_includes body, 'Restocking fee (30% of parts): $60.00'
|
||||
assert_includes body, 'Refund: $154.00'
|
||||
assert_includes body, 'returned parts carry a restocking fee'
|
||||
assert_not_includes body, "Labor that wasn't done"
|
||||
end
|
||||
|
||||
def test_the_pdf
|
||||
record = refund
|
||||
document = RedmineQboBilling::RefundPdf.new(record)
|
||||
assert document.render.start_with?('%PDF')
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user