Compare commits

...
12 Commits
Author SHA1 Message Date
rickyandClaude Opus 5.5 40eb6205c4 2026.11.22
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:09:07 -05:00
rickyandClaude Opus 5.5 0c5bac855e Business report: Sales tax section at the bottom
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:09:07 -05:00
rickyandClaude Opus 5.5 663639b8fd 2026.11.21
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:45:29 -05:00
rickyandClaude Opus 5.5 ec4e5f681d Business report: sales tax invoiced and collected
A Sales tax section: tax invoiced (on invoices dated in the period,
accrual) and tax collected (on invoices paid in full in the period,
counted on the day each was paid in full, cash), with counts, a line
chart and a month-by-month table. Only invoices are counted; sales tax
is filed from QuickBooks' Sales Tax Liability report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:45:29 -05:00
rickyandClaude Opus 5.5 a72b0fa73b Business report without sales tax; invoices paid in full; paid dates
Estimates and invoices written are reported without sales tax (new
estimates.tax_amount, filled in by the estimate sync), and a new
Invoices paid in full figure counts invoices on the day they were paid
in full. Payments stay as received, so collected vs. invoiced compares
them with the invoices' totals with tax.

Paid invoices show the day they were paid in full on the customer's
invoice list and the invoice page ("Paid 11/03/2026").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:34:21 -05:00
rickyandClaude Opus 5.5 5b6c1ed2c2 Cache invoices' sales tax and the day they were paid in full
New invoices columns tax_amount and paid_on, filled in by the invoice
sync. An invoice is paid in full on the later of its date and the
dates of the payments and credit memos applied to it (local payments
first; QuickBooks only for ones not synced yet and credit memos), so
reports such as the monthly sales commission don't have to read
invoices from QuickBooks. A full sync fills them in for older
invoices; it now syncs payments before invoices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:34:21 -05:00
rickyandClaude Opus 5.5 4f6f81c87a 2026.11.20
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:43:36 -05:00
rickyandClaude Opus 5.5 9fa199aa98 Refunds for canceled orders and returned parts (SOP-OPS-014)
A Refund page on the customer: the canceled order's estimate fills in
the parts the 30% restocking fee is worked out on. Refunding makes the
fee invoice, pays it from the customer's credit, records the rest as a
Check (company check) or Expense (card refund on the terminal) with the
category Accounts Receivable, applies the credit to it so the balance
comes back to $0.00, and optionally marks the estimate Rejected,
cancels its work orders with the reason as a note and emails the
customer. Each refund has a page with a PDF of it.

New permission: Issue refunds. New settings under Billing » Refunds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 20:43:36 -05:00
rickyandClaude Opus 5.5 16f9441568 2026.11.19
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:42:08 -05:00
rickyandClaude Opus 5.5 5c48646041 Invoice page hook for plugin actions
:view_qbo_invoice_contextual, { invoice_id:, customer_id:, doc_number: }
in the invoice page's top-right actions, like the estimate page's hook
(used by redmine_qbo_labels' Print label).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 08:42:08 -05:00
rickyandClaude Opus 5.5 90adb96d54 2026.11.18
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:17:38 -05:00
rickyandClaude Opus 5.5 8a947483db Estimate/invoice numbers on issue PDF; create estimate issues as subtasks
- Issue PDF: show the issue's estimate number and invoice number(s)
- Create issues from estimate: optional parent task. The issues are created as
  its subtasks, take its customer, and start from its project, vehicle and
  custom field values (subtask_field_copier's rules when installed)
- Issue page: shortcut to create the estimate's issues as subtasks of the issue
- Create issues page: editable start and due dates, pre-filled from the
  appointment or the parent task
- Always show plugins' fields (e.g. the vehicle) on the Create issues page

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:17:38 -05:00
40 changed files with 2349 additions and 63 deletions

No files matched your search

+23 -5
View File
@@ -97,7 +97,7 @@ Customer records are automatically updated in the local database when changes oc
### Estimates, Invoices and Payments
Estimates and invoices keep their number, date, customer, total and **man-hours** (the quantities of the labor products/services, including lines inside bundles). Payments keep their customer, date, amount and unapplied amount. These cached figures feed the business report.
Estimates and invoices keep their number, date, customer, total, sales tax and **man-hours** (the quantities of the labor products/services, including lines inside bundles). Payments keep their customer, date, amount and unapplied amount. These cached figures feed the business report.
---
@@ -128,7 +128,7 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
* Time lines are linked to their time activities, so QuickBooks marks the time as billed. Estimates the invoice was made from, or imported into it, are linked and closed when it's saved.
* **Custom fields from the work orders**: the issues behind an invoice are the ones its time lines and lineitems estimates name. Plugins can fill custom fields from them when they're imported, and block a save (e.g. redmine_qbo_vehicles fills the VIN and mileage and allows one vehicle per invoice). On its own, redmine_qbo leaves the boxes as typed.
* **Sales person**: an invoice credits the sales person on the estimate it was made from (the first linked estimate that names one); if none does, the user who writes the invoice.
* Invoices show their status, worked out from the balance and due date like QuickBooks' invoice list: **Paid**, **Partially paid**, **Overdue**, **Open** or **Voided** (a zero total), on the customer page's invoice list and the invoice page.
* Invoices show their status, worked out from the balance and due date like QuickBooks' invoice list: **Paid**, **Partially paid**, **Overdue**, **Open** or **Voided** (a zero total), on the customer page's invoice list and the invoice page. A paid invoice shows the day it was paid in full (e.g. **Paid 11/03/2026**): the later of its date and the last payment or credit memo applied to it.
* Invoices with a payment applied open read-only. The due date is left to QuickBooks (from the customer's terms) unless one is picked. The "default message shown on invoices" fills in the message.
### Payments
@@ -140,17 +140,32 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
* The saved payment's page shows where it was applied and has **Print**, QuickBooks' payment PDF.
* **Payments** on the customer page lists all of the customer's payments from QuickBooks, newest first: date, method, reference no., the invoices each was applied to (or Deposit), memo, amount and what's still unapplied, with totals. Each date opens the payment's page and **Print** opens its PDF.
### Refunds
Refunds for canceled orders and returned parts, following SOP-OPS-014, so they don't have to be made in QuickBooks:
* **Refund** on the customer page. Pick the canceled order's estimate: its parts (the lines that aren't labor, including those in bundles, before tax) fill in the amount the restocking fee is worked out on, and can be changed (e.g. only some parts are returned). Labor carries no fee.
* Choose how the money goes back: **Company check** (with its number) or **Card** (a partial refund on the terminal). There are no cash refunds. The page shows the customer's credit, the fee and the exact amount to refund.
* **Refund** then, in QuickBooks:
1. makes the restocking fee invoice, its line showing the math ("Restocking fee: 30% × $307.99 parts on E1068 = $92.40"), and pays it from the customer's credit, oldest first (unless QuickBooks already applied the credit to it on its own);
2. records the rest of the credit as a refund with the category **Accounts Receivable**, from the bank account in the settings, described "Refund for deposit on E1068": a **Check** for a check, an **Expense** for a card refund;
3. applies the customer's remaining credit to that check or expense, so the deposit, the fee invoice and the refund reconcile, and reads back the customer's balance (it should be $0.00).
* As ticked on the page, it also marks the estimate **Rejected**, sets the order's work orders to the canceled status with the reason as a note, and emails the customer a summary (through redmine_qbo_reminders' mail settings when that plugin is set up, otherwise Redmine's).
* 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.
### 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):
* **Sales**: estimates written, invoices written and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices.
* **Sales**: estimates written, invoices written, invoices paid in full (on the day each was paid in full) and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices. Estimates and invoices are without sales tax (QuickBooks' tax on each is cached with it); payments are as received, so collected vs. invoiced compares them with the invoices' totals with tax.
* **Sales tax**: **tax invoiced**, the sales tax on invoices dated in the period, paid or not (accrual), and **tax collected**, the sales tax on invoices paid in full in the period, counted on the day each was paid in full (cash), each with how many invoices carried tax, a line chart and a month-by-month table. A partly paid invoice's tax counts as collected once it's paid in full. Only invoices are counted: sales receipts, refund receipts and credit memos aren't kept in Redmine, so file sales tax from QuickBooks' *Sales Tax Liability* report.
* **Hours**: estimated hours on estimates, issues' estimated time, invoiced hours on invoices and time spent, with spent vs. estimated, and the **cost performance index** (CPI = invoiced hours ÷ spent hours): green at 1.00 or more, yellow below 1, red below 0.80. Each month shows its CPI too.
* **Charts**: above each set of bars, a line chart of the same figures in the same colors (Chart.js 4.5.1, MIT licensed, bundled with the plugin in assets/javascripts so it doesn't clash with other plugins' copies such as redmine_indicator's Chart.js 2), with a point per day for a week, per week for up to about three months, and per month beyond. Hovering a point shows its figures. **Compare with last year** adds last year's lines, dashed and faded, without reloading: days and weeks go back 52 weeks so weekdays line up, months go back to the same month. Clicking a figure in the legend hides it (and its last-year line); clicking *last year* stops comparing. Today's line stops at today.
* **By month**: every figure month by month, with totals.
* **By month**: every sales and hours figure month by month, with totals (the sales tax has its own table).
* **Projects**: pick one or more open projects (Ctrl/Cmd-click; closed and archived projects aren't listed) to count only their issues' estimated time and spent time, in the totals, charts and months; none picked counts every project. Estimates, invoices and payments have no project in QuickBooks, so they always cover the whole business (as do the CPI's invoiced hours). **Remember these projects** saves the choice in your Redmine preferences, and the report opens with it until you save another (saving none goes back to every project).
Estimates, invoices and payments count by their QuickBooks date. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. While estimates, invoices or payments are syncing, the report says so (with how many have been read) and refreshes every 30 seconds; the settings page's Synchronization table shows the same per type. Estimates and invoices synced before these figures were added have no total or hours until a full sync (the report says how many); run one again after changing the labor products/services.
Estimates, invoices and payments count by their QuickBooks date; invoices paid in full and tax collected by the day each invoice was paid in full. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. While estimates, invoices or payments are syncing, the report says so (with how many have been read) and refreshes every 30 seconds; the settings page's Synchronization table shows the same per type. Estimates and invoices synced before these figures were added have no total, hours or sales tax, and paid invoices no paid-in-full day, until a full sync (the report says how many); run one again after changing the labor products/services.
### QuickBooks custom fields
@@ -192,11 +207,13 @@ 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
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).
* Item and account counts, the default income account and their syncs are under Synchronization.
3. Writing an estimate
@@ -235,6 +252,7 @@ Hook|:qbo_billing_field_options, { customer: } | Return `{ field_id => [{ value:
View|:view_qbo_estimate_form_bottom, { form:, document: } | Add your plugin's script to the estimate/invoice editor. It can use `window.qboEditor` (`field(id)`, `fieldNamed(/name/)`, `setFieldOptions(id, options)`) and listen for `qbo:customer-changed` and `qbo:imported` on the form (redmine_qbo_vehicles fills the VIN and mileage)
View|checkboxes with `data-new-issue-param="issue[field]"` on the customer page | Ticking one adds `issue[field]=value` to the New issue link, one per field (redmine_qbo's estimates, redmine_qbo_vehicles' vehicles)
View Hook|:view_qbo_estimate_contextual, { estimate_id:, customer_id:, custom_fields:, doc_number: } | Adds links to an estimate page's action area (e.g. redmine_qbo_calendar's Add appointment); `custom_fields` is `{ field_id => value }`
View Hook|:view_qbo_invoice_contextual, { invoice_id:, customer_id:, doc_number: } | Adds links to an invoice page's action area (e.g. redmine_qbo_labels' Print label)
Other plugins create estimates with `RedmineQboBilling::EstimateWriter.create_estimate(customer:, lines:, private_note:, custom_fields:, user:)`; `custom_fields` is `{ field_id => value }`, and each line is a hash of `description`, `item_id`, `quantity`, `rate` and `taxable`.
+75 -8
View File
@@ -101,7 +101,8 @@ class QboEstimatesController < ApplicationController
def create_issues
@rows = params[:lines].respond_to?(:to_unsafe_h) ? params[:lines].to_unsafe_h : {}
@custom_field_values = submitted_custom_field_values
created = @builder.create_issues(project: @target_project, rows: @rows, custom_field_values: @custom_field_values)
# A parent was entered but can't be used: create nothing rather than top-level issues
created = @parent_issue_error ? [] : @builder.create_issues(project: @target_project, rows: @rows, custom_field_values: @custom_field_values)
if created.any?
Redmine::Hook.call_hook(:qbo_billing_issues_created, { estimate: @estimate, issues: created, params: params })
@@ -174,31 +175,97 @@ class QboEstimatesController < ApplicationController
end
return render_404 unless @estimate
# Values plugins' fields posted with the form (e.g. redmine_qbo_vehicles' vehicle) override their defaults
@defaults = issue_defaults.merge(submitted_plugin_fields)
@builder = RedmineQboBilling::EstimateIssueBuilder.new(@estimate, defaults: @defaults)
load_parent_issue
@defaults = build_defaults
@return_path = @defaults[:return_path].presence || edit_qbo_estimate_path(@estimate.id)
@return_label = @defaults[:return_label].presence || "#{l(:label_estimate)} ##{@estimate.doc_number}"
@available_projects = Project.allowed_to(User.current, :add_issues).sorted.to_a
# A project chosen on the page wins, then the one from another plugin (e.g. the appointment's), then the
# default project from the settings, then the first project the user can add issues to
# A project chosen on the page wins, then the parent issue's, then the one from another plugin (e.g. the
# appointment's), then the default project from the settings, then the first project the user can add issues to
chosen = @available_projects.detect { |p| p.id == params[:project_id].to_i } if params[:project_id].present?
from_parent = @parent_issue.project if @parent_issue && @available_projects.include?(@parent_issue.project)
from_hook = @defaults[:project] if @available_projects.include?(@defaults[:project])
default_project = @available_projects.detect { |p| p.id == RedmineQboBilling::EstimateIssueBuilder.default_project_id }
@target_project = chosen || from_hook || default_project || @available_projects.first
@target_project = chosen || from_parent || from_hook || default_project || @available_projects.first
return deny_access unless @target_project
# Subtasks need the "Manage subtasks" permission in the project they're created in
@can_add_subtasks = User.current.allowed_to?(:manage_subtasks, @target_project)
if @parent_issue && !@can_add_subtasks
@parent_issue_error = l(:error_estimate_parent_not_allowed, project: @target_project.name)
@parent_issue = nil
@defaults = build_defaults
end
@builder = RedmineQboBilling::EstimateIssueBuilder.new(@estimate, defaults: @defaults, parent: @parent_issue)
@trackers = Issue.allowed_target_trackers(@target_project, User.current).to_a
@default_tracker = @trackers.detect { |t| t.id == RedmineQboBilling::EstimateIssueBuilder.default_tracker_id } || @trackers.first
@templates = RedmineQboBilling::IssueTemplateSupport.templates_for(@target_project)
@field_set = RedmineQboBilling::IssueFieldSet.new(project: @target_project, trackers: @trackers)
# With a parent issue, the shared fields start out with the parent's values
@field_set = RedmineQboBilling::IssueFieldSet.new(project: @target_project, trackers: @trackers,
values: parent_custom_field_values)
@rows ||= {}
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
# The optional parent issue (parent_issue_id, "#123" or "123"): the new issues become its subtasks.
# Only an issue the user can see; an unknown one is reported and nothing is created.
def load_parent_issue
@parent_issue_id = params[:parent_issue_id].to_s.delete('#').strip
return if @parent_issue_id.blank?
@parent_issue = Issue.visible.find_by(id: @parent_issue_id.to_i) if @parent_issue_id.match?(/\A\d+\z/)
@parent_issue_error = l(:error_estimate_parent_not_found, id: @parent_issue_id) unless @parent_issue
end
# What the new issues start from:
# - dates: another plugin's (e.g. the appointment's), else the parent issue's
# - vehicle: the parent issue's, else another plugin's (e.g. the appointment's)
# Values posted with the form (the dates, plugins' fields such as redmine_qbo_vehicles' vehicle) win.
def build_defaults
parent_dates = {}
parent_vehicle = {}
if @parent_issue
parent_dates = { start_date: @parent_issue.start_date, due_date: @parent_issue.due_date }.compact
if @parent_issue.respond_to?(:vehicle_id) && @parent_issue.vehicle_id.present?
parent_vehicle = { vehicle_id: @parent_issue.vehicle_id.to_s }
end
end
parent_dates.merge(issue_defaults.compact).merge(parent_vehicle).merge(submitted_plugin_fields).merge(submitted_dates)
end
# The Start date / Due date entered on the page, only when the form was posted. A blank one means no date.
def submitted_dates
return {} unless request.post? && params[:issue_dates].respond_to?(:to_unsafe_h)
values = params[:issue_dates].to_unsafe_h
%w[start_date due_date].each_with_object({}) do |key, dates|
dates[key.to_sym] = parse_date(values[key]) if values.key?(key)
end
end
def parse_date(value)
Date.iso8601(value.to_s.strip) if value.present?
rescue ArgumentError
nil
end
# The parent issue's custom field values the user can see, to start the shared fields from: { id => value }
def parent_custom_field_values
return {} unless @parent_issue
@parent_issue.visible_custom_field_values.each_with_object({}) do |custom_value, values|
next if Array(custom_value.value).all?(&:blank?)
values[custom_value.custom_field_id.to_s] = custom_value.value
end
end
# The first non-empty hash a plugin returns for :qbo_billing_issue_defaults
def issue_defaults
results = Redmine::Hook.call_hook(:qbo_billing_issue_defaults, { estimate: @estimate, params: params })
+108
View File
@@ -0,0 +1,108 @@
#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.
# Customer refunds (SOP-OPS-014): the Refund page for a customer with credit, and a refund once it's made
class QboRefundsController < ApplicationController
before_action :authorize_global
QBO_ERRORS = QboEstimatesController::QBO_ERRORS
def new
@customer = Customer.find_by(id: params[:customer_id])
return render_404 unless @customer
@form = RedmineQboBilling::RefundForm.new(customer_id: @customer.id.to_s, estimate_id: params[:estimate_id].to_s,
txn_date: User.current.today.iso8601, method: 'check',
close_estimate: '1', cancel_issues: '1', email_customer: '1')
@form.parts_amount = estimate_parts(@form.estimate_id)
load_page
end
def create
@form = RedmineQboBilling::RefundForm.from_params(params.require(:refund).permit(*RedmineQboBilling::RefundForm::ATTRIBUTES))
@customer = Customer.find_by(id: @form.customer_id)
return render_404 unless @customer
return show_form unless @form.valid?
refund = RedmineQboBilling::RefundWriter.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_form
end
def show
@refund = QboRefund.find_by(id: params[:id])
return render_404 unless @refund
@customer = @refund.customer
end
# The refund as a PDF, shown in the browser to print or save
def pdf
refund = QboRefund.find_by(id: params[:id])
return render_404 unless refund
document = RedmineQboBilling::RefundPdf.new(refund)
send_data document.render, type: 'application/pdf', disposition: 'inline', filename: document.filename
end
# Emails the customer the refund's summary (again, or after fixing their email in QuickBooks)
def email
refund = QboRefund.find_by(id: params[:id])
return render_404 unless refund&.done?
warning = RedmineQboBilling::RefundWriter.email_customer(refund, refund.customer, QboRefundMailer)
if warning
flash[:error] = warning
else
flash[:notice] = l(:notice_refund_emailed, email: refund.emailed_to)
end
redirect_to qbo_refund_path(refund)
end
private
# The estimate's parts (its lines that aren't labor), before tax, for the restocking fee
def estimate_parts(estimate_id)
return '' if estimate_id.blank?
estimate = RedmineQboBilling::RefundGateway.new.estimate(estimate_id)
estimate ? format('%.2f', RedmineQboBilling::RefundWriter.parts_amount(estimate)) : ''
rescue *QBO_ERRORS => e
flash.now[:error] = qbo_message(e)
''
end
def load_page
@estimates = RedmineQboBilling::RefundWriter.estimate_choices(@customer)
@preview = RedmineQboBilling::RefundWriter.preview(@customer, parts: @form.parts_value || BigDecimal('0'))
@statuses = IssueStatus.sorted.to_a
rescue *QBO_ERRORS => e
@preview = nil
flash.now[:error] = qbo_message(e)
end
def show_form
load_page
render :new, status: :unprocessable_entity
end
def qbo_message(error)
detail = error.respond_to?(:detail) ? error.detail.to_s : ''
message = error.message.to_s
detail.present? && !message.include?(detail) ? "#{message}: #{detail}" : message
end
end
+3 -2
View File
@@ -10,12 +10,13 @@
class QboSyncDispatcher
# Payments before invoices: an invoice's paid-in-full day is worked out from the local payments' dates
SYNC_JOBS = [
Customer,
Estimate,
Payment,
Invoice,
Employee,
Payment
Employee
].freeze
# Dispatches all synchronization jobs to perform a full sync of QuickBooks entities with the local database.
+40
View File
@@ -0,0 +1,40 @@
#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.
# Emails a customer the summary of their refund (SOP-OPS-014). It goes out like redmine_qbo_reminders' appointment
# reminders when that plugin is installed (its From, Reply-To and SMTP server, e.g. the shop's sales mailbox);
# otherwise through Redmine's own email settings, from Redmine's emission address. Not Redmine's Mailer, which only
# writes to Redmine users and adds Redmine's headers and footer.
class QboRefundMailer < ActionMailer::Base
layout false
self.raise_delivery_errors = true
class DeliveryOff < StandardError; end
def refund_summary(refund, email)
@refund = refund
@customer = refund.customer
reminders = defined?(RedmineQboReminders::Settings) ? RedmineQboReminders::Settings.current : nil
@shop_name = reminders&.[]('shop_name').to_s.presence || Setting.app_title
delivery = reminders ? reminders.delivery_options : {}
if delivery.empty? && !ActionMailer::Base.perform_deliveries
raise DeliveryOff, I18n.t(:text_refund_email_off)
end
options = { to: email, from: reminders&.from.presence || Setting.mail_from.to_s,
subject: I18n.t(:text_refund_email_subject, shop: @shop_name, amount: RedmineQboBilling::RefundWriter.money(refund.refund_amount)) }
options[:reply_to] = reminders.reply_to if reminders&.reply_to
message = mail(options.merge(delivery)) do |format|
format.text
end
message.perform_deliveries = true unless delivery.empty?
message
end
end
+54
View File
@@ -0,0 +1,54 @@
#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.
# A customer refund (SOP-OPS-014), as it was made: the restocking fee, the refund, and each step's outcome
class QboRefund < ApplicationRecord
METHODS = %w[check card].freeze
STATUSES = %w[done incomplete].freeze
belongs_to :customer
belongs_to :user, optional: true
validates :customer_id, presence: true
validates :method, inclusion: { in: METHODS }
validates :status, inclusion: { in: STATUSES }
scope :recent, -> { order(created_at: :desc, id: :desc) }
def done?
status == 'done'
end
def check?
method == 'check'
end
def method_name
I18n.t("label_refund_method_#{method}")
end
def canceled_issue_ids
Array(JSON.parse(self[:canceled_issue_ids].presence || '[]')).map(&:to_i)
rescue JSON::ParserError
[]
end
def canceled_issue_ids=(ids)
self[:canceled_issue_ids] = Array(ids).map(&:to_i).uniq.to_json
end
# The QuickBooks screen for the refund check or expense
def purchase_url
return nil if purchase_id.blank?
page = check? ? 'check' : 'expense'
"https://#{RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'}.qbo.intuit.com/app/#{page}?txnId=#{purchase_id}"
end
end
+2
View File
@@ -30,6 +30,8 @@ class EstimateSyncService < SyncServiceBase
map_attribute :txn_status
# Man-hours: quantities of the labor products/services (plugin settings)
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
# Sales tax, so the business report can compare estimates and invoices without it
map_attribute(:tax_amount) { |remote| RedmineQboBilling::InvoicePaidOn.tax(remote) }
map_belongs_to :customer
end
+3
View File
@@ -27,6 +27,9 @@ class InvoiceSyncService < SyncServiceBase
# Man-hours: quantities of the labor products/services (plugin settings)
map_attribute(:hours) { |remote| RedmineQboBilling::ManHours.hours(remote) }
map_attribute :qbo_updated_at, "meta_data.last_updated_time"
# Sales tax, and the day it was paid in full (nil while open), for reports such as monthly paid sales
map_attribute(:tax_amount) { |remote| RedmineQboBilling::InvoicePaidOn.tax(remote) }
map_attribute(:paid_on) { |remote| RedmineQboBilling::InvoicePaidOn.paid_on(remote) }
map_belongs_to :customer
end
+24
View File
@@ -23,6 +23,9 @@
<% if RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @customer.id), class: 'icon icon-add' %>
<% end %>
<% if RedmineQboBilling.refunder? %>
<%= link_to sprite_icon('arrow-narrow-left', l(:label_refund)), new_qbo_refund_path(customer_id: @customer.id), class: 'icon icon-arrow-narrow-left' %>
<% end %>
<% if User.current.allowed_to?(:edit_customers, nil, global: true) %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_customer_path(@customer),
class: 'icon icon-edit', accesskey: accesskey(:edit) %>
@@ -65,6 +68,27 @@
<%= render partial: 'qbo_drafts/list', locals: { drafts: customer_drafts, show_customer: false } %>
<% end %>
<%# Refunds made from Redmine (SOP-OPS-014) %>
<% if RedmineQboBilling.refunder? %>
<% customer_refunds = QboRefund.where(customer_id: @customer.id).recent.limit(10).to_a %>
<% if customer_refunds.any? %>
<h4><%= l(:label_refunds) %>:</h4>
<table class="list">
<tbody>
<% 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><%= refund.method_name %></td>
<td style="text-align: right"><%= RedmineQboBilling::RefundWriter.money(refund.refund_amount) %></td>
<td><%= refund.done? ? '' : l(:label_refund_incomplete) %></td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
<% end %>
</div>
<div class="splitcontentleft">
+1 -1
View File
@@ -18,7 +18,7 @@
<b><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b> <%= invoice.txn_date %>
<%# Paid / partially paid / overdue / open / voided, from the cached balance and due date %>
<% if (status = invoice.status) %>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status) %></span>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status, paid_on: invoice.paid_on) %></span>
<% end %>
<%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %>
</div>
+6
View File
@@ -10,6 +10,12 @@
<div class="value">
<%= estimate_link %>
<%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: issue.estimate } if issue.estimate && RedmineQboBilling.writer? %>
<%# Create the estimate's remaining labor lines as subtasks of this issue %>
<% if issue.estimate && User.current.allowed_to?(:create_estimate_issues, nil, global: true) && User.current.allowed_to?(:manage_subtasks, issue.project) %>
<%= link_to sprite_icon('add', l(:button_create_estimate_subtasks)),
issues_preview_qbo_estimate_path(issue.estimate.id, parent_issue_id: issue.id),
class: 'icon-only icon-add', title: l(:button_create_estimate_subtasks) %>
<% end %>
</div>
</div>
+37
View File
@@ -66,3 +66,40 @@
<em class="info"><%= l(:text_default_tracker_info) %></em>
</p>
</fieldset>
<%# Refunds (SOP-OPS-014): the restocking fee, and where the refund check or card refund is recorded %>
<% refunds = RedmineQboBilling::RefundWriter %>
<% accounts = Account.where(active: true).order(:name).pluck(:name, :id) %>
<fieldset class="box tabular">
<legend><%= l(:label_refund_settings) %></legend>
<p>
<label for="settings_restocking_fee_rate"><%= l(:label_restocking_fee_rate) %></label>
<%= number_field_tag 'settings[restocking_fee_rate]', refunds.plain(refunds.fee_rate), id: 'settings_restocking_fee_rate',
min: 0, max: 100, step: 0.01, style: 'width: 6em' %>%
<em class="info"><%= l(:text_restocking_fee_rate) %></em>
</p>
<p>
<label for="settings_restocking_item_id"><%= l(:label_restocking_item) %></label>
<%= select_tag 'settings[restocking_item_id]', options_from_collection_for_select(Item.sellable.order(:name), :id, :name, @settings['restocking_item_id']),
include_blank: true, id: 'settings_restocking_item_id' %>
<em class="info"><%= l(:text_restocking_item) %></em>
</p>
<p>
<label for="settings_refund_check_account_id"><%= l(:label_refund_check_account) %></label>
<%= select_tag 'settings[refund_check_account_id]', options_for_select(accounts, @settings['refund_check_account_id'].to_s),
include_blank: l(:label_refund_first_bank_account), id: 'settings_refund_check_account_id' %>
<em class="info"><%= l(:text_refund_check_account) %></em>
</p>
<p>
<label for="settings_refund_card_account_id"><%= l(:label_refund_card_account) %></label>
<%= select_tag 'settings[refund_card_account_id]', options_for_select(accounts, @settings['refund_card_account_id'].to_s),
include_blank: l(:label_refund_first_bank_account), id: 'settings_refund_card_account_id' %>
<em class="info"><%= l(:text_refund_card_account) %></em>
</p>
<p>
<label for="settings_refund_canceled_status_id"><%= l(:label_refund_canceled_status) %></label>
<%= select_tag 'settings[refund_canceled_status_id]', options_from_collection_for_select(IssueStatus.sorted, :id, :name, @settings['refund_canceled_status_id'].to_s),
include_blank: refunds.canceled_status ? "#{refunds.canceled_status.name} (#{l(:label_default)})" : true, id: 'settings_refund_canceled_status_id' %>
<em class="info"><%= l(:text_refund_canceled_status) %></em>
</p>
</fieldset>
+2 -1
View File
@@ -20,7 +20,8 @@
due_date: RedmineQboBilling::EstimateForm.date(form.due_date),
today: User.current.today) %>
<% if status %>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status) %></span>
<% paid_on = Invoice.where(id: form.id).pick(:paid_on) if status == :paid && form.id.present? %>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status, paid_on: paid_on) %></span>
<% end %>
<% elsif !invoice && form.txn_status.present? %>
<span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span>
+61 -11
View File
@@ -14,26 +14,58 @@
</span>
</h2>
<%# Target project: changing it reloads the page with that project's trackers and templates %>
<% if @available_projects.size > 1 %>
<%= form_tag issues_preview_qbo_estimate_path(@estimate.id), method: :get, id: 'estimate-issues-project-form' do %>
<% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %>
<p>
<label for="project_id"><strong><%= l(:field_project) %>:</strong></label>
<%# Target project and parent task: changing either reloads the page (the project's trackers and templates;
the parent's project, vehicle and custom field values) %>
<%= form_tag issues_preview_qbo_estimate_path(@estimate.id), method: :get, id: 'estimate-issues-project-form' do %>
<% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %>
<p>
<label for="project_id"><strong><%= l(:field_project) %>:</strong></label>
<% if @available_projects.size > 1 %>
<%= select_tag :project_id,
options_from_collection_for_select(@available_projects, :id, :name, @target_project.id),
onchange: 'this.form.submit();' %>
<noscript><%= submit_tag l(:button_apply), name: nil %></noscript>
<% else %>
<%= link_to_project @target_project %>
<%= hidden_field_tag :project_id, @target_project.id, id: nil %>
<% end %>
</p>
<% if @can_add_subtasks || @parent_issue_id.present? %>
<p class="estimate-issues-parent">
<label for="parent_issue_id"><strong><%= l(:field_parent_issue) %>:</strong></label>
<%= text_field_tag :parent_issue_id, @parent_issue&.id || @parent_issue_id, size: 10,
placeholder: l(:label_estimate_parent_placeholder) %>
<% if @parent_issue %>
<%= link_to_issue(@parent_issue, truncate: 60) %>
<%= link_to sprite_icon('del', l(:button_clear)),
issues_preview_qbo_estimate_path(@estimate.id, carry.merge(project_id: @target_project.id)),
class: 'icon-only icon-del', title: l(:button_clear) %>
<br><em class="info"><%= l(:text_estimate_parent_info) %></em>
<% end %>
</p>
<% end %>
<% else %>
<p><strong><%= l(:field_project) %>:</strong> <%= link_to_project @target_project %></p>
<noscript><p><%= submit_tag l(:button_apply), name: nil %></p></noscript>
<% end %>
<% if @builder.errors.any? %>
<% if @can_add_subtasks || @parent_issue_id.present? %>
<%= javascript_tag do %>
(function () {
var field = document.getElementById('parent_issue_id');
if (!field) return;
var submitted = false;
function reload() { if (!submitted) { submitted = true; field.form.submit(); } }
observeAutocompleteField('parent_issue_id',
<%= raw auto_complete_issues_path(project_id: @target_project, scope: Setting.cross_project_subtasks, status: 'o').to_json %>,
{ select: function (event, ui) { field.value = ui.item.value; reload(); } });
field.addEventListener('change', reload);
})();
<% end %>
<% end %>
<% errors = [@parent_issue_error, *@builder.errors].compact %>
<% if errors.any? %>
<div id="errorExplanation">
<ul>
<% @builder.errors.each do |message| %>
<% errors.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
@@ -63,6 +95,7 @@
id: 'estimate-issues-form',
data: { templates: template_data.to_json } do %>
<%= hidden_field_tag :project_id, @target_project.id %>
<%= hidden_field_tag :parent_issue_id, @parent_issue&.id || @parent_issue_id, id: nil %>
<% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %>
<table class="list estimate-issues-preview">
@@ -136,6 +169,21 @@
</tbody>
</table>
<%# Dates for every issue: from the appointment the page was opened from, else the parent task; blank means none %>
<fieldset class="box tabular estimate-issue-dates">
<legend><%= l(:label_estimate_issue_dates) %></legend>
<p>
<label for="estimate_issue_start_date"><%= l(:field_start_date) %></label>
<%= date_field_tag 'issue_dates[start_date]', @defaults[:start_date], id: 'estimate_issue_start_date', size: 10 %>
<%= calendar_for('estimate_issue_start_date') %>
</p>
<p>
<label for="estimate_issue_due_date"><%= l(:field_due_date) %></label>
<%= date_field_tag 'issue_dates[due_date]', @defaults[:due_date], id: 'estimate_issue_due_date', size: 10 %>
<%= calendar_for('estimate_issue_due_date') %>
</p>
</fieldset>
<%# Fields entered once and applied to every issue: plugins' own (e.g. redmine_qbo_vehicles' vehicle, posted as
issue_plugin_fields[...]) and the custom fields for the chosen trackers %>
<% plugin_fields = call_hook(:view_qbo_estimate_issues_form, { estimate: @estimate, defaults: @defaults, project: @target_project }) %>
@@ -234,6 +282,8 @@
var visibleCount = 0;
fieldBox.querySelectorAll('.estimate-issue-field').forEach(function (field) {
// Plugins' fields (e.g. the vehicle) apply to every tracker
if (!field.hasAttribute('data-tracker-ids')) { visibleCount++; return; }
var used = idList(field.dataset.trackerIds).some(function (id) { return trackerIds.indexOf(id) >= 0; });
var required = idList(field.dataset.requiredTrackerIds).some(function (id) { return trackerIds.indexOf(id) >= 0; });
field.style.display = used ? '' : 'none';
+2
View File
@@ -1,6 +1,8 @@
<% html_title "#{l(:label_invoice)} ##{@form.doc_number}" %>
<div class="contextual">
<%# Plugins add invoice actions here (e.g. redmine_qbo_labels' Print label) %>
<%= call_hook :view_qbo_invoice_contextual, { invoice_id: @form.id, customer_id: @form.customer_id, doc_number: @form.doc_number } %>
<% 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 %>
@@ -0,0 +1,15 @@
<% 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)) %>
<% 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) %>
<% end -%>
<%= t(:label_refund_amount) %>: <%= money.(@refund.refund_amount) %>
<%= @refund.check? ? t(:text_refund_email_check, number: @refund.check_number) : t(:text_refund_email_card) %>
<%= t(:text_refund_email_terms) %>
<%= @shop_name %>
+122
View File
@@ -0,0 +1,122 @@
<%# Refund for a canceled order or returned parts (SOP-OPS-014) %>
<% html_title l(:label_refund) %>
<% money = ->(amount) { RedmineQboBilling::RefundWriter.money(amount) } %>
<% preview = @preview %>
<h2>
<%= link_to l(:label_customers), customers_path %> &#187;
<%= link_to @customer.name, customer_path(@customer) %> &#187;
<%= l(:label_refund) %>
</h2>
<%= error_messages_for @form %>
<p class="warning"><%= l(:text_refund_final_sale) %></p>
<% if preview && preview.credits.empty? %>
<p class="nodata"><%= l(:text_refund_no_credit) %></p>
<% end %>
<%# Picking the canceled order's estimate reloads the page with its parts filled in %>
<%= form_tag new_qbo_refund_path, method: :get, id: 'qbo-refund-estimate' do %>
<%= hidden_field_tag 'customer_id', @customer.id, id: nil %>
<div class="box tabular">
<p>
<label for="qbo_refund_estimate"><%= l(:label_refund_estimate) %></label>
<%= select_tag 'estimate_id', options_for_select(@estimates, @form.estimate_id), include_blank: l(:label_refund_no_estimate),
id: 'qbo_refund_estimate', onchange: 'this.form.submit()' %>
<noscript><%= submit_tag l(:button_apply), name: nil %></noscript>
<em class="info"><%= l(:text_refund_estimate) %></em>
</p>
</div>
<% end %>
<%= form_tag qbo_refunds_path, method: :post, id: 'qbo-refund-form' do %>
<%= hidden_field_tag 'refund[customer_id]', @customer.id, id: nil %>
<%= hidden_field_tag 'refund[estimate_id]', @form.estimate_id, id: nil %>
<div class="box tabular">
<p>
<label for="qbo_refund_parts"><%= l(:label_refund_parts) %></label>
$<%= text_field_tag 'refund[parts_amount]', @form.parts_amount, id: 'qbo_refund_parts', size: 12, inputmode: 'decimal',
autocomplete: 'off', data: { rate: preview&.fee_rate.to_s } %>
<em class="info"><%= l(:text_refund_parts, rate: RedmineQboBilling::RefundWriter.plain(preview&.fee_rate || RedmineQboBilling::RefundWriter.fee_rate)) %></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_reason) %></em>
</p>
<p>
<label><%= l(:label_refund_also) %></label>
<% [[:close_estimate, :label_refund_close_estimate], [:cancel_issues, :label_refund_cancel_issues], [:email_customer, :label_refund_email_customer]].each do |flag, label| %>
<% needs_estimate = flag != :email_customer %>
<label class="block">
<%= hidden_field_tag "refund[#{flag}]", '0', id: nil %>
<%= check_box_tag "refund[#{flag}]", '1', @form.send(:"#{flag}?") && (!needs_estimate || @form.estimate_id.present?),
id: "qbo_refund_#{flag}", disabled: needs_estimate && @form.estimate_id.blank? %>
<%= l(label) %>
</label>
<% end %>
<% if @customer.email.blank? %><em class="info"><%= l(:text_refund_no_email) %></em><% end %>
</p>
</div>
<% if preview %>
<fieldset class="box" id="qbo-refund-preview">
<legend><%= l(:label_refund_summary) %></legend>
<table class="list">
<thead><tr><th><%= l(:label_refund_credit_from) %></th><th><%= l(:label_payment_reference) %></th><th><%= l(:label_memo) %></th><th><%= l(:label_amount) %></th></tr></thead>
<tbody>
<% preview.credits.each do |credit| %>
<tr>
<td><%= link_to format_date(credit.date), qbo_payment_path(credit.payment_id) %></td>
<td><%= credit.reference %></td>
<td><%= credit.memo %></td>
<td style="text-align: right"><%= money.(credit.amount) %></td>
</tr>
<% end %>
</tbody>
<tfoot>
<tr><td colspan="3"><%= l(:label_refund_credit) %></td><td style="text-align: right" id="qbo-refund-credit" data-credit="<%= preview.credit_total.to_s('F') %>"><%= money.(preview.credit_total) %></td></tr>
<tr><td colspan="3"><%= l(:label_refund_fee_rate, rate: RedmineQboBilling::RefundWriter.plain(preview.fee_rate)) %></td><td style="text-align: right" id="qbo-refund-fee">-<%= money.(preview.fee) %></td></tr>
<tr><td colspan="3"><strong><%= l(:label_refund_amount) %></strong></td><td style="text-align: right"><strong id="qbo-refund-amount"><%= money.(preview.refund) %></strong></td></tr>
</tfoot>
</table>
<p><em class="info"><%= l(:text_refund_summary) %></em></p>
</fieldset>
<% end %>
<p><%= submit_tag l(:button_refund), data: { confirm: l(:text_refund_confirm) }, disabled: preview.nil? || preview.credits.empty? %></p>
<% end %>
<%= javascript_tag do %>
$(function() {
var money = function(n) { return '$' + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ','); };
function update() {
var parts = parseFloat(($('#qbo_refund_parts').val() || '0').replace(/[$,\s]/g, '')) || 0;
var rate = parseFloat($('#qbo_refund_parts').data('rate')) || 0;
var credit = parseFloat($('#qbo-refund-credit').data('credit')) || 0;
var fee = Math.round(parts * rate) / 100;
$('#qbo-refund-fee').text('-' + money(fee));
$('#qbo-refund-amount').text(money(Math.max(credit - fee, 0)));
}
function method() { $('#qbo-refund-check-number').toggle($('#qbo_refund_method_check').is(':checked')); }
$('#qbo_refund_parts').on('input', update);
$('input[name="refund[method]"]').on('change', method);
update(); method();
});
<% end %>
+64
View File
@@ -0,0 +1,64 @@
<%# A refund as it was made (SOP-OPS-014) %>
<% html_title l(:label_refund) %>
<% money = ->(amount) { RedmineQboBilling::RefundWriter.money(amount) } %>
<h2>
<%= link_to l(:label_customers), customers_path %> &#187;
<% if @customer %><%= link_to @customer.name, customer_path(@customer) %> &#187;<% end %>
<%= l(:label_refund) %> <%= format_date(@refund.txn_date) %>
</h2>
<div class="contextual">
<%= link_to sprite_icon('application-pdf', 'PDF'), pdf_qbo_refund_path(@refund), class: 'icon icon-pdf', target: :_blank %>
<% if @refund.fee_invoice_id.present? %>
<%= link_to sprite_icon('application-pdf', l(:label_refund_fee_invoice_pdf)), invoice_path(@refund.fee_invoice_id), class: 'icon icon-pdf', target: :_blank %>
<% end %>
</div>
<% if @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>
<% else %>
<p class="conflict"><%= l(:text_refund_incomplete) %></p>
<% end %>
<% if @refund.message.present? %>
<div class="warning"><%= simple_format(h(@refund.message)) %></div>
<% 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>
<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) %>
<% 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 %>
</p>
<p>
<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' %>
<% end %>
</p>
<% if @refund.estimate_number.present? %>
<p><label><%= l(:label_refund_close_estimate) %></label> <%= checked_image @refund.estimate_closed? %></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>
<% end %>
<p>
<label><%= l(:label_refund_email_customer) %></label> <%= @refund.emailed_to.presence || '—' %>
<% if @refund.done? %>
· <%= link_to sprite_icon('email', l(@refund.emailed_to.present? ? :button_refund_email_again : :button_refund_email)),
email_qbo_refund_path(@refund), method: :post, class: 'icon icon-email',
data: { confirm: l(:text_refund_email_confirm) } %>
<% end %>
</p>
<p><label><%= l(:field_author) %></label> <%= @refund.user ? link_to_user(@refund.user) : '' %> <%= format_time(@refund.created_at) %></p>
</div>
+61 -2
View File
@@ -2,7 +2,7 @@
<% money = @report.money %>
<% hours = @report.hours %>
<% ratios = @report.ratios %>
<% max_money = [money[:estimates][:total], money[:invoices][:total], money[:payments][:total]].max.to_f %>
<% max_money = [money[:estimates][:total], money[:invoices][:total], money[:paid][:total], money[:payments][:total]].max.to_f %>
<% max_hours = hours.values.max.to_f %>
<% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %>
<% fmt_hours = ->(h) { format('%.1f', h.to_f) } %>
@@ -40,7 +40,12 @@
end %>
<% sales_series = chart_series.call([[:estimates, l(:label_report_estimates_written), '#628db6'],
[:invoices, l(:label_report_invoices_written), '#e8a33d'],
[:paid, l(:label_report_invoices_paid), '#c0504d'],
[:payments, l(:label_report_payments_received), '#5aa05a']]) %>
<% taxes = @report.taxes %>
<% max_tax = taxes.values.map { |t| t[:total] }.max.to_f %>
<% tax_series = chart_series.call([[:tax_invoiced, l(:label_report_tax_invoiced), '#e8a33d'],
[:tax_collected, l(:label_report_tax_collected), '#c0504d']]) %>
<% hours_series = chart_series.call([[:estimate_hours, l(:label_report_estimate_hours), '#628db6'],
[:issue_hours, l(:label_report_issue_hours), '#9b7fc0'],
[:invoice_hours, l(:label_report_invoice_hours), '#e8a33d'],
@@ -132,7 +137,7 @@
<table class="list qbo-report">
<tbody>
<% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)],
[:payments, l(:label_report_payments_received)]].each do |key, label| %>
[:paid, l(:label_report_invoices_paid)], [:payments, l(:label_report_payments_received)]].each do |key, label| %>
<tr>
<td class="name"><%= label %> <span class="count">(<%= money[key][:count] %>)</span></td>
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(money[key][:total], max_money) %>%"></div></td>
@@ -146,6 +151,7 @@
<%= l(:label_report_collected_of_invoiced) %>: <strong><%= pct.call(ratios[:collected_of_invoiced]) %></strong><br />
<%= l(:label_report_open_balance) %>: <strong><%= number_to_currency(money[:invoices][:balance]) %></strong>
</p>
<p><em class="info"><%= l(:text_report_without_tax) %></em></p>
</div>
<div class="splitcontentright">
@@ -188,6 +194,7 @@
<th class="month"><%= l(:label_month) %></th>
<th><%= l(:label_report_estimates_written) %></th>
<th><%= l(:label_report_invoices_written) %></th>
<th><%= l(:label_report_invoices_paid) %></th>
<th><%= l(:label_report_payments_received) %></th>
<th class="hours-start"><%= l(:label_report_estimate_hours) %></th>
<th><%= l(:label_report_issue_hours) %></th>
@@ -202,6 +209,7 @@
<td class="month"><%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %></td>
<td><%= number_to_currency(row[:estimates]) %></td>
<td><%= number_to_currency(row[:invoices]) %></td>
<td><%= number_to_currency(row[:paid]) %></td>
<td><%= number_to_currency(row[:payments]) %></td>
<td class="hours-start"><%= fmt_hours.call(row[:estimate_hours]) %></td>
<td><%= fmt_hours.call(row[:issue_hours]) %></td>
@@ -216,6 +224,7 @@
<td class="month"><strong><%= l(:label_total) %></strong></td>
<td><strong><%= number_to_currency(money[:estimates][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:invoices][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:paid][:total]) %></strong></td>
<td><strong><%= number_to_currency(money[:payments][:total]) %></strong></td>
<td class="hours-start"><strong><%= fmt_hours.call(hours[:estimate_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:issue_hours]) %></strong></td>
@@ -226,6 +235,54 @@
</tfoot>
</table>
</div>
<h3><%= l(:label_report_taxes) %></h3>
<div class="splitcontent">
<div class="splitcontentleft">
<div class="qbo-report-chart">
<canvas id="qbo-chart-taxes" data-kind="money" data-series="<%= tax_series.to_json %>"></canvas>
</div>
<table class="list qbo-report">
<tbody>
<% [[:tax_invoiced, l(:label_report_tax_invoiced)], [:tax_collected, l(:label_report_tax_collected)]].each do |key, label| %>
<tr>
<td class="name"><%= label %> <span class="count">(<%= l(:label_report_taxed_invoices, count: taxes[key][:count]) %>)</span></td>
<td class="bar"><div class="qbo-bar qbo-bar-<%= key %>" style="width: <%= bar.call(taxes[key][:total], max_tax) %>%"></div></td>
<td class="value"><%= number_to_currency(taxes[key][:total]) %></td>
</tr>
<% end %>
</tbody>
</table>
<p><em class="info"><%= l(:text_report_taxes) %></em></p>
</div>
<div class="splitcontentright">
<table class="list qbo-report-months qbo-report-tax-months">
<thead>
<tr>
<th class="month"><%= l(:label_month) %></th>
<th><%= l(:label_report_tax_invoiced) %></th>
<th><%= l(:label_report_tax_collected) %></th>
</tr>
</thead>
<tbody>
<% @report.months.each do |row| %>
<tr>
<td class="month"><%= ::I18n.t('date.abbr_month_names')[row[:month].month] %> <%= row[:month].year %></td>
<td><%= number_to_currency(row[:tax_invoiced]) %></td>
<td><%= number_to_currency(row[:tax_collected]) %></td>
</tr>
<% end %>
</tbody>
<tfoot>
<tr class="total">
<td class="month"><strong><%= l(:label_total) %></strong></td>
<td><strong><%= number_to_currency(taxes[:tax_invoiced][:total]) %></strong></td>
<td><strong><%= number_to_currency(taxes[:tax_collected][:total]) %></strong></td>
</tr>
</tfoot>
</table>
</div>
</div>
<p class="info"><%= l(:text_report_notes) %></p>
<style>
@@ -237,6 +294,8 @@
.qbo-bar { height: 14px; border-radius: 2px; min-width: 1px; background: #628db6; }
.qbo-bar-invoices, .qbo-bar-invoice_hours { background: #e8a33d; }
.qbo-bar-payments, .qbo-bar-spent_hours { background: #5aa05a; }
.qbo-bar-paid, .qbo-bar-tax_collected { background: #c0504d; }
.qbo-bar-tax_invoiced { background: #e8a33d; }
.qbo-bar-issue_hours { background: #9b7fc0; }
.qbo-report-ratios { margin: 8px 4px; line-height: 1.7; }
.qbo-report-cpi { margin: 10px 4px 4px; }
+118
View File
@@ -11,6 +11,11 @@
# English strings go here for Rails i18n
# Usage I18n.t(:label)
en:
button_create_estimate_subtasks: "Create subtasks from estimate"
error_estimate_parent_not_found: "Parent task #%{id} wasn't found, or you can't see it."
error_estimate_parent_not_allowed: "You aren't allowed to add subtasks in %{project}."
label_estimate_parent_placeholder: "Optional"
text_estimate_parent_info: "The issues are created as subtasks. They get the parent's customer, and the vehicle and custom field values below start from the parent's; any left empty are filled from the parent."
notice_qbo_oauth_state_mismatch: "QuickBooks connection was not completed: the request could not be verified. Please try connecting again."
permission_bill_issues: "Bill issue time to QuickBooks"
permission_share_issues_with_customers: "Share issues with customers"
@@ -284,6 +289,7 @@ en:
label_invoice_date: "Invoice date"
label_invoice_no: "Invoice no."
label_invoice_status_paid: "Paid"
label_invoice_status_paid_on: "Paid %{date}"
label_invoice_status_partial: "Partially paid"
label_invoice_status_overdue: "Overdue"
label_invoice_status_open: "Open"
@@ -313,6 +319,7 @@ en:
label_default_project: "Default project"
label_default_tracker: "Default tracker"
label_estimate_issue_fields: "Issue fields"
label_estimate_issue_dates: "Dates"
label_estimate_issue_settings: "Issues from estimates"
label_estimate_item: "Item"
label_estimate_line_already_created: "Already created"
@@ -377,6 +384,15 @@ en:
label_report_last_year: "last year"
label_report_estimates_written: "Estimates written"
label_report_invoices_written: "Invoices written"
label_report_invoices_paid: "Invoices paid in full"
label_report_taxes: "Sales tax"
label_report_tax_invoiced: "Tax invoiced"
label_report_tax_collected: "Tax collected"
label_report_taxed_invoices:
one: "1 invoice"
other: "%{count} invoices"
text_report_taxes: "Tax invoiced is the sales tax on invoices dated in the period (accrual); tax collected is the sales tax on invoices paid in full in the period (cash), counted on the day each was paid in full. Sales receipts and refunds aren't included: file from QuickBooks' Sales Tax Liability report."
text_report_without_tax: "Estimates and invoices are without sales tax; invoices paid in full count on the day they were paid in full. Payments are as received, so collected vs. invoiced compares them with the invoices' totals with tax."
label_report_payments_received: "Payments received"
label_report_estimate_hours: "Estimated (estimates)"
label_report_issue_hours: "Estimated (issues)"
@@ -416,3 +432,105 @@ en:
label_activity_payment: "Payment from %{customer}: %{amount}"
text_activity_invoice_owed: "%{amount} owed"
text_activity_payment_unapplied: "%{amount} not applied to an invoice"
# ---- Refunds (SOP-OPS-014) ----
permission_issue_refunds: "Issue refunds"
label_refund: "Refund"
label_refunds: "Refunds"
label_refund_incomplete: "Incomplete"
label_refund_estimate: "Canceled order"
label_refund_no_estimate: "None (customer credit only)"
label_refund_your_order: "your order"
label_refund_parts: "Parts"
label_refund_method: "Refund by"
label_refund_method_check: "Company check"
label_refund_method_card: "Card (on the terminal)"
label_refund_check_number: "Check no."
label_refund_date: "Refund date"
label_refund_reason: "Reason"
label_refund_also: "Also"
label_refund_close_estimate: "Mark the estimate Rejected in QuickBooks"
label_refund_cancel_issues: "Cancel the order's work orders"
label_refund_email_customer: "Email the customer a summary"
label_refund_summary: "Refund"
label_refund_credit_from: "Credit from payment"
label_refund_credit: "Customer credit"
label_refund_fee_rate: "Restocking fee (%{rate}% of parts)"
label_refund_amount: "Refund"
label_refund_fee_invoice: "Invoice #%{number}"
label_refund_open_check: "Check in QuickBooks"
label_refund_open_expense: "Expense in QuickBooks"
label_refund_settings: "Refunds"
label_refund_balance_after: "Customer balance afterwards"
label_refund_recorded_by: "Recorded by"
label_refund_received_by: "Received by (customer signature)"
label_refund_fee_invoice_pdf: "Fee invoice PDF"
label_refund_pdf_fee: "Restocking fee: %{rate}% × %{parts} parts"
label_refund_pdf_work_orders: "Work orders canceled"
label_refund_pdf_estimate: "Estimate"
text_refund_pdf_estimate_rejected: "E%{number} marked Rejected in QuickBooks"
label_restocking_fee_rate: "Restocking fee"
label_restocking_item: "Restocking fee product/service"
label_refund_check_account: "Refund checks from"
label_refund_card_account: "Card refunds from"
label_refund_first_bank_account: "The first bank account"
label_refund_canceled_status: "Canceled work order status"
button_refund: "Refund"
button_refund_email: "Email the customer"
button_refund_email_again: "Email again"
notice_refund_emailed: "Refund summary emailed to %{email}."
notice_refund_done: "Refund of %{amount} recorded in QuickBooks."
error_refund_method: "Choose how the refund is paid: company check or card."
error_refund_check_number: "Enter the check number."
error_refund_reason: "Enter the reason for the refund."
error_refund_parts_amount: "Parts must be an amount of $0.00 or more."
error_refund_estimate_customer: "That estimate is for another customer."
error_refund_no_fee_item: "Pick the restocking fee product/service in the QuickBooks plugin settings (Billing » Refunds)."
error_refund_no_credit: "This customer has no credit (unapplied payments) to refund."
error_refund_fee_over_credit: "The restocking fee (%{fee}) isn't less than the customer's credit (%{credit}), so there's nothing to refund."
error_refund_no_ar_account: "QuickBooks has no Accounts Receivable account."
error_refund_no_bank_account: "QuickBooks has no bank account to record the refund from. Pick one in the plugin settings."
error_refund_fee_not_saved: "QuickBooks didn't save the restocking fee invoice."
error_refund_fee_unpaid: "The customer's credit didn't cover the restocking fee invoice (%{amount} still open)."
error_refund_nothing_left: "No credit is left to refund after the restocking fee."
error_refund_not_saved: "QuickBooks didn't save the refund."
error_refund_step_fee: "The restocking fee invoice couldn't be made or paid from the customer's credit: %{error}. Nothing was refunded. Finish or undo it in QuickBooks."
error_refund_step_refund: "The refund couldn't be recorded in QuickBooks: %{error}. The restocking fee invoice (if any) is made. Record the refund in QuickBooks (Check or Expense, category Accounts Receivable) and apply the customer's credit to it."
text_refund_final_sale: "Custom fabricated assemblies and discontinued or closeout items are final sale. Don't refund them without Shop Manager approval (SOP-OPS-014). No cash refunds: card payments are refunded on the terminal, everything else by company check."
text_refund_no_credit: "This customer has no credit (unapplied payments) to refund."
text_refund_estimate: "The order being canceled. Its parts fill in the restocking fee, and the refund refers to it."
text_refund_parts: "The parts returned or canceled, before tax. The restocking fee is %{rate}% of this; labor carries no fee. Enter 0 to refund without a fee."
text_refund_method: "The way the order was paid: card payments are refunded on the card terminal (a partial refund, of the amount below); cash and check payments by company check."
text_refund_reason: "Goes on the refund in QuickBooks and on the canceled work orders."
text_refund_summary: "The restocking fee invoice is paid from the customer's credit, and the rest is refunded. Refund exactly this amount on the terminal or check."
text_refund_email_confirm: "Email the customer this refund's summary?"
text_refund_confirm: "Make the restocking fee invoice and record the refund in QuickBooks?"
text_refund_no_email: "The customer has no email in QuickBooks."
text_refund_balance: "Done. The customer's QuickBooks balance is now %{balance}."
text_refund_balance_unknown: "Done, but the customer's QuickBooks balance couldn't be read. Check it's $0.00 in QuickBooks."
text_refund_incomplete: "This refund is incomplete. See below which step failed, and finish it in QuickBooks."
text_refund_fee_line: "Restocking fee: %{rate}% × %{parts} parts%{on} = %{fee}"
text_refund_line: "Refund for deposit on E%{number}"
text_refund_line_credit: "Refund of customer credit"
text_refund_line_card: "(card refund on the terminal)"
text_refund_private_note: "Refund made in Redmine (SOP-OPS-014). Reason: %{reason}"
text_refund_issue_note: "Order canceled and refunded: %{reason}. Restocking fee %{fee}, refunded %{refund} by %{method}."
text_refund_issues_not_canceled: "Some work orders couldn't be set to canceled: %{issues}"
text_refund_no_canceled_status: "The work orders weren't canceled: pick the canceled status in the plugin settings."
text_refund_estimate_not_closed: "The estimate couldn't be marked Rejected in QuickBooks: %{error}"
text_refund_email_failed: "The customer wasn't emailed: %{error}"
text_refund_email_off: "Redmine's email delivery is turned off."
text_refund_email_subject: "Your refund from %{shop}: %{amount}"
text_refund_email_greeting: "Hello %{name},"
text_refund_email_intro: "We've processed the refund for %{order}."
text_refund_email_check: "It's being paid by company check (no. %{number})."
text_refund_email_card: "It's been refunded to the card you paid with. It can take a few business days to show on your statement."
text_refund_email_terms: "As in our posted terms, returned and canceled parts carry a restocking fee. Labor that wasn't done isn't charged."
text_restocking_fee_rate: "Of the parts returned or canceled (SOP-OPS-014: 30%)."
text_restocking_item: "The QuickBooks product/service on the restocking fee invoice (e.g. \"Restocking Fee\"). It sets the income account the fee is booked to."
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."
+8
View File
@@ -71,6 +71,14 @@ end
# Estimate and invoice drafts, kept in Redmine until they're saved to QuickBooks (continued on the editors)
resources :qbo_drafts, only: [:index, :destroy]
# Customer refunds (SOP-OPS-014): /qbo_refunds/new?customer_id=
resources :qbo_refunds, only: [:new, :create, :show] do
member do
get :pdf
post :email
end
end
# Receive payment pages, and a customer's payments (/qbo_payments?customer_id=)
resources :qbo_payments, only: [:index, :new, :create, :show, :edit, :update] do
member do
+55
View File
@@ -0,0 +1,55 @@
#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.
# Customer refunds (SOP-OPS-014): the restocking fee invoice, the refund check or card refund, and what was
# done in QuickBooks and Redmine, so a refund can be looked up (and finished by hand if a step failed)
class CreateQboRefunds < ActiveRecord::Migration[7.0]
def up
return if table_exists?(:qbo_refunds)
create_table :qbo_refunds do |t|
t.bigint :customer_id, null: false
# The canceled order's estimate, if any
t.bigint :estimate_id
t.string :estimate_number
t.integer :user_id
t.date :txn_date
# check or card
t.string :method, null: false, limit: 10
t.string :check_number
t.text :reason
t.decimal :parts_amount, precision: 15, scale: 2, null: false, default: 0
t.decimal :fee_rate, precision: 6, scale: 2, null: false, default: 0
t.decimal :fee_amount, precision: 15, scale: 2, null: false, default: 0
# The customer's credit before the refund, and what was refunded
t.decimal :credit_amount, precision: 15, scale: 2, null: false, default: 0
t.decimal :refund_amount, precision: 15, scale: 2, null: false, default: 0
# The QuickBooks fee invoice and the refund check or expense
t.string :fee_invoice_id
t.string :fee_invoice_number
t.string :purchase_id
# The customer's QuickBooks balance afterwards
t.decimal :balance_after, precision: 15, scale: 2
t.boolean :estimate_closed, null: false, default: false
# The work orders set to canceled (JSON list of issue ids)
t.text :canceled_issue_ids
t.string :emailed_to
# done, or incomplete (a step failed: message says which)
t.string :status, null: false, default: 'incomplete', limit: 20
t.text :message
t.timestamps
end
add_index :qbo_refunds, :customer_id
end
def down
drop_table :qbo_refunds if table_exists?(:qbo_refunds)
end
end
@@ -0,0 +1,20 @@
#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.
# An invoice's sales tax and the day it was paid in full, cached like its total and balance, so reports (e.g.
# redmine_qbo_commission's monthly paid sales) don't have to read invoices from QuickBooks. A full invoice sync
# fills them in for invoices synced before.
class AddInvoiceTaxAndPaidOn < ActiveRecord::Migration[7.0]
def change
add_column :invoices, :tax_amount, :decimal, precision: 15, scale: 2 unless column_exists?(:invoices, :tax_amount)
add_column :invoices, :paid_on, :date unless column_exists?(:invoices, :paid_on)
add_index :invoices, :paid_on unless index_exists?(:invoices, :paid_on)
end
end
+17
View File
@@ -0,0 +1,17 @@
#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.
# An estimate's sales tax, cached like its total, so the business report can compare estimates and invoices
# without tax. A full estimate sync fills it in for estimates synced before.
class AddEstimateTax < ActiveRecord::Migration[7.0]
def change
add_column :estimates, :tax_amount, :decimal, precision: 15, scale: 2 unless column_exists?(:estimates, :tax_amount)
end
end
+3 -1
View File
@@ -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.17'
version '2026.11.22'
url 'https://github.com/rickbarrette/redmine_qbo'
author_url 'https://barrettefabrication.com'
settings default: {empty: true}, partial: 'qbo/settings'
@@ -54,6 +54,8 @@ 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
permission :view_business_reports, { qbo_reports: [:index] }, global: true
# The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController)
+3
View File
@@ -103,6 +103,9 @@ module RedmineQbo
left << [l(:field_status), issue.status]
left << [l(:field_priority), issue.priority]
left << [l(:field_customer), issue.customer&.name]
left << [l(:field_estimate), issue.estimate.doc_number] if issue.estimate
invoice_numbers = issue.invoices.map(&:doc_number).compact_blank
left << [invoice_numbers.size > 1 ? l(:label_invoices) : l(:field_invoice), invoice_numbers.join(', ')] if invoice_numbers.any?
left << [l(:field_assigned_to), issue.assigned_to] unless issue.disabled_core_fields.include?(:assigned_to_id)
log "Calling :pdf_left hook"
+5
View File
@@ -83,6 +83,11 @@ module RedmineQboBilling
user.allowed_to?(:receive_payments, nil, global: true)
end
# True when the user may refund customers' credit (SOP-OPS-014)
def self.refunder?(user = User.current)
user.allowed_to?(:issue_refunds, nil, global: true)
end
# True when the user may see customer payments (receiving them includes seeing them)
def self.payment_viewer?(user = User.current)
user.allowed_to?(:view_payments, nil, global: true) || payment_receiver?(user)
+72 -25
View File
@@ -12,7 +12,9 @@
module RedmineQboBilling
# Business figures for a date range, from the estimates, invoices and payments cached from QuickBooks and from
# Redmine's issues and spent time:
# money: estimates written, invoices written, payments received (totals and counts)
# money: estimates written, invoices written, invoices paid in full, payments received (totals and counts);
# estimates and invoices without sales tax (it isn't the shop's revenue), payments as received
# taxes: sales tax on invoices written (by their date) and on invoices paid in full (by that day)
# hours: man-hours on estimates, issues' estimated time, man-hours invoiced, time spent
# with a month-by-month breakdown. Estimates, invoices and payments count by their QuickBooks date, issues by
# the day they were created (only issues without subtasks, so parents' totals aren't counted twice), and
@@ -24,8 +26,9 @@ module RedmineQboBilling
# Chart points: a day each for up to two weeks, a week each up to about three months, else a month each
DAILY_UP_TO = 14
WEEKLY_UP_TO = 93
MONEY = %i[estimates invoices payments].freeze
MONEY = %i[estimates invoices paid payments].freeze
HOURS = %i[estimate_hours issue_hours invoice_hours spent_hours].freeze
TAXES = %i[tax_invoiced tax_collected].freeze
attr_reader :from, :to, :period, :project_ids
@@ -54,8 +57,9 @@ module RedmineQboBilling
nil
end
# data (for tests): { estimates: [[date, total, hours]], invoices: [[date, total, hours, balance]],
# payments: [[date, total]], issues: [[date, estimated_hours]], time_entries: [[date, hours]] }
# data (for tests): { estimates: [[date, total, hours, tax]], invoices: [[date, total, hours, balance, tax]],
# paid: [[paid_on, total, tax]], payments: [[date, total]], issues: [[date, estimated_hours]],
# time_entries: [[date, hours]] }. Tax may be left off (none).
# week_start: the first day of a week (:monday, :saturday or :sunday); see week_start_from_setting.
# previous_data (for tests): last year's data, like data.
# project_ids: the projects whose issues and spent time count; blank for every project.
@@ -150,13 +154,45 @@ module RedmineQboBilling
@data ||= load_data
end
# { estimates: { total:, count: }, invoices: { total:, count:, balance: }, payments: { total:, count: } }
# Where each money figure's rows are and how much each row counts: estimates, invoices and invoices paid in
# full without their sales tax, payments as received
MONEY_ROWS = {
estimates: [:estimates, ->(r) { to_money(r[1]) - to_money(r[3]) }],
invoices: [:invoices, ->(r) { to_money(r[1]) - to_money(r[4]) }],
paid: [:paid, ->(r) { to_money(r[1]) - to_money(r[2]) }],
payments: [:payments, ->(r) { to_money(r[1]) }]
}.freeze
# Sales tax on invoices written (by their date) and on invoices paid in full (by that day)
TAX_ROWS = {
tax_invoiced: [:invoices, ->(r) { to_money(r[4]) }],
tax_collected: [:paid, ->(r) { to_money(r[2]) }]
}.freeze
def self.to_money(value)
BigDecimal(value.to_s.presence || '0')
rescue ArgumentError
BigDecimal('0')
end
# { estimates: { total:, count: }, invoices: { total:, count:, balance:, with_tax: }, paid: { total:, count: },
# payments: { total:, count: } }. Invoices' balance (still owed) and with_tax are what the customers pay.
def money
@money ||= {
estimates: { total: money_sum(data[:estimates], 1), count: data[:estimates].size },
invoices: { total: money_sum(data[:invoices], 1), count: data[:invoices].size, balance: money_sum(data[:invoices], 3) },
payments: { total: money_sum(data[:payments], 1), count: data[:payments].size }
}
@money ||= MONEY_ROWS.to_h do |key, (source, value)|
rows = Array(data[source])
[key, { total: rows.sum(BigDecimal('0')) { |r| value.call(r) }, count: rows.size }]
end.tap do |figures|
figures[:invoices][:balance] = money_sum(data[:invoices], 3)
figures[:invoices][:with_tax] = money_sum(data[:invoices], 1)
end
end
# { tax_invoiced: { total:, count: }, tax_collected: { total:, count: } }: count is the invoices that had tax
def taxes
@taxes ||= TAX_ROWS.to_h do |key, (source, value)|
amounts = Array(data[source]).map { |r| value.call(r) }
[key, { total: amounts.sum(BigDecimal('0')), count: amounts.count(&:positive?) }]
end
end
# { estimate_hours:, issue_hours:, invoice_hours:, spent_hours: }
@@ -193,7 +229,8 @@ module RedmineQboBilling
def ratios
{
invoiced_of_estimated: percent(money[:invoices][:total], money[:estimates][:total]),
collected_of_invoiced: percent(money[:payments][:total], money[:invoices][:total]),
# Payments include sales tax, so they're compared with the invoices' totals with tax
collected_of_invoiced: percent(money[:payments][:total], money[:invoices][:with_tax]),
invoiced_of_spent: percent(hours[:invoice_hours], hours[:spent_hours]),
spent_of_estimated: percent(hours[:spent_hours], hours[:issue_hours])
}
@@ -208,7 +245,7 @@ module RedmineQboBilling
last = [to, @today].min
last = from if last < from
while month <= last
rows << { month: month }.merge((MONEY + HOURS).index_with { |_| 0 })
rows << { month: month }.merge((MONEY + HOURS + TAXES).index_with { |_| 0 })
month = month.next_month
end
index = rows.index_by { |r| [r[:month].year, r[:month].month] }
@@ -218,9 +255,12 @@ module RedmineQboBilling
r[key] += kind == :money ? to_d(row[col]) : row[col].to_f
end
end
add.call(data[:estimates], :estimates, 1, :money)
add.call(data[:invoices], :invoices, 1, :money)
add.call(data[:payments], :payments, 1, :money)
MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
Array(data[source]).each do |row|
r = index[[row[0].year, row[0].month]] or next
r[key] += value.call(row)
end
end
add.call(data[:estimates], :estimate_hours, 2, :hours)
add.call(data[:issues], :issue_hours, 1, :hours)
add.call(data[:invoices], :invoice_hours, 2, :hours)
@@ -229,27 +269,33 @@ module RedmineQboBilling
end
end
# Estimates and invoices in the range that synced before totals and hours were cached (a full sync fills them)
# Estimates and invoices in the range that synced before totals, hours and sales tax were cached (a full sync
# fills them)
def unsynced_count
data[:estimates].count { |r| r[1].nil? || r[2].nil? } + data[:invoices].count { |r| r[1].nil? || r[2].nil? }
data[:estimates].count { |r| r[1].nil? || r[2].nil? || (r.size > 3 && r[3].nil?) } +
data[:invoices].count { |r| r[1].nil? || r[2].nil? || (r.size > 4 && r[4].nil?) }
end
private
# { money key or hours key => [sum per bucket] } for the data, in buckets ([first day, last day] pairs)
def sums_by_bucket(rows, bucket_list)
sums = (MONEY + HOURS).index_with { |_| Array.new(bucket_list.size, 0.0) }
sums = (MONEY + HOURS + TAXES).index_with { |_| Array.new(bucket_list.size, 0.0) }
find = lambda do |date|
bucket_list.index { |a, b| date >= a && date <= b }
end
columns = {
estimates: [:estimates, 1], invoices: [:invoices, 1], payments: [:payments, 1],
estimate_hours: [:estimates, 2], issue_hours: [:issues, 1], invoice_hours: [:invoices, 2], spent_hours: [:time_entries, 1]
}
MONEY_ROWS.merge(TAX_ROWS).each do |key, (source, value)|
Array(rows[source]).each do |row|
i = find.call(row[0]) or next
sums[key][i] += value.call(row).to_f
end
end
columns = { estimate_hours: [:estimates, 2], issue_hours: [:issues, 1], invoice_hours: [:invoices, 2],
spent_hours: [:time_entries, 1] }
columns.each do |key, (source, col)|
Array(rows[source]).each do |row|
i = find.call(row[0]) or next
sums[key][i] += MONEY.include?(key) ? to_d(row[col]).to_f : row[col].to_f
sums[key][i] += row[col].to_f
end
end
sums.transform_values { |values| values.map { |v| v.round(2) } }
@@ -266,8 +312,9 @@ module RedmineQboBilling
time_entries = time_entries.where(project_id: project_ids)
end
{
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours),
invoices: Invoice.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :balance),
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :tax_amount),
invoices: Invoice.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :balance, :tax_amount),
paid: Invoice.where(paid_on: dates).where('total_amount > 0').pluck(:paid_on, :total_amount, :tax_amount),
payments: Payment.where(txn_date: dates).pluck(:txn_date, :total_amount),
issues: issues.pluck(:created_on, :estimated_hours).map { |t, h| [t.in_time_zone.to_date, h] },
time_entries: time_entries.pluck(:spent_on, :hours)
@@ -17,6 +17,9 @@ module RedmineQboBilling
# - Lines already turned into issues are shown but can't be created again
# - Creation is all-or-nothing: if any issue fails validation, none are saved
# - All issues created from the same estimate are related to each other, across batches
# - With a parent issue, the issues are created as its subtasks and take its customer, plus its vehicle and
# custom field values where the page left them empty (the same rules as the subtask_field_copier plugin,
# which is used when installed)
#
# Other plugins fill in more through hooks:
# :qbo_billing_issue_defaults, { estimate:, params: } => a hash of start_date, due_date, assignee,
@@ -91,13 +94,15 @@ module RedmineQboBilling
end
end
attr_reader :estimate, :defaults, :errors
attr_reader :estimate, :defaults, :parent, :errors
# estimate: redmine_qbo's local Estimate (its QuickBooks details give the lines)
# defaults: start_date, due_date, assignee, description and plugins' own values (from :qbo_billing_issue_defaults)
def initialize(estimate, defaults: {})
# parent: an issue to create the issues under as subtasks (optional; the caller checks the user may see it)
def initialize(estimate, defaults: {}, parent: nil)
@estimate = estimate
@defaults = (defaults || {}).to_h.symbolize_keys
@parent = parent
@errors = []
end
@@ -190,10 +195,12 @@ module RedmineQboBilling
key.to_s
end
# Relates the new issues to each other and to every issue created earlier from the same estimate.
# Relates the new issues to each other and to every issue created earlier from the same estimate,
# except their parent and its ancestors (Redmine doesn't allow relating a subtask to its parent)
def relate_issues(new_issues)
skip_ids = parent ? parent.self_and_ancestors.pluck(:id) : []
earlier = QboEstimateLineIssue.where(estimate_id: estimate.id)
.where.not(issue_id: new_issues.map(&:id))
.where.not(issue_id: new_issues.map(&:id) + skip_ids)
.includes(:issue)
.filter_map(&:issue)
self.class.relate_all(earlier + new_issues)
@@ -223,15 +230,45 @@ module RedmineQboBilling
assignee = defaults[:assignee]
issue.assigned_to = assignee if assignee && issue.assignable_users.include?(assignee)
issue.customer_id = estimate.customer_id if issue.respond_to?(:customer_id=)
# A subtask belongs to its parent's customer; otherwise the estimate's
if issue.respond_to?(:customer_id=)
issue.customer_id = parent&.customer_id.presence || estimate.customer_id
end
issue.estimate_id = estimate.id if issue.respond_to?(:estimate_id=)
# Plugins set their own fields (e.g. redmine_qbo_vehicles: the vehicle)
Redmine::Hook.call_hook(:qbo_billing_build_issue, { issue: issue, estimate: estimate, defaults: defaults })
if parent
issue.parent_issue_id = parent.id
copy_from_parent(issue, author)
end
issue
end
# Fills the subtask's empty fields from the parent: custom fields (those the author can see on the parent
# and edit on the subtask) and plugins' registered fields (customer, vehicle). Values entered on the page win.
def copy_from_parent(issue, author)
if defined?(::SubtaskFieldCopier)
::SubtaskFieldCopier.copy_from_parent(issue, parent, author, {})
return
end
parent_values = parent.visible_custom_field_values(author).index_by(&:custom_field_id)
copied = issue.editable_custom_field_values(author).each_with_object({}) do |custom_value, values|
value = parent_values[custom_value.custom_field_id]&.value
next if Array(value).all?(&:blank?) || Array(custom_value.value).any?(&:present?)
values[custom_value.custom_field_id.to_s] = value
end
issue.custom_field_values = copied if copied.any?
if issue.respond_to?(:vehicle_id=) && issue.vehicle_id.blank? && parent.respond_to?(:vehicle_id)
issue.vehicle_id = parent.vehicle_id
end
end
def default_description
defaults[:description].presence ||
"The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number}"
@@ -0,0 +1,65 @@
#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
# An invoice's sales tax and the day it was paid in full, worked out from the QuickBooks invoice when it's synced
# (InvoiceSyncService).
#
# An invoice is paid in full on the later of its own date and the dates of the payments and credit memos applied
# to it, so a deposit taken before the work counts on the day the job was invoiced. The payments' dates come from
# the local payments (synced from QuickBooks); QuickBooks is only asked for the ones not synced yet and for credit
# memos.
module InvoicePaidOn
APPLIED_TYPES = %w[Payment CreditMemo].freeze
IDS_PER_QUERY = 100
module_function
def tax(remote)
tax = remote.respond_to?(:txn_tax_detail) ? remote.txn_tax_detail&.total_tax : nil
tax.nil? ? BigDecimal('0') : BigDecimal(tax.to_s)
end
# The day the invoice was paid in full, or nil while it's open (or voided: a $0 total)
def paid_on(remote, dates: nil)
return nil unless remote.txn_date
return nil unless BigDecimal(remote.balance.to_s.presence || '1').zero?
return nil unless BigDecimal(remote.total.to_s.presence || '0').positive?
dates ||= applied_dates(applied(remote))
[remote.txn_date, *applied(remote).map { |type, id| dates[[type, id]] }.compact].max
end
# [["Payment", "123"], ...] applied to the invoice
def applied(remote)
Array(remote.linked_transactions).select { |link| APPLIED_TYPES.include?(link.txn_type.to_s) }
.map { |link| [link.txn_type.to_s, link.txn_id.to_s] }
end
# { ["Payment", "123"] => Date }: local payments first, the rest read from QuickBooks
def applied_dates(links)
dates = {}
payment_ids = links.select { |type, _| type == 'Payment' }.map(&:last)
Payment.where(id: payment_ids).pluck(:id, :txn_date).each { |id, date| dates[['Payment', id.to_s]] = date if date }
missing = links.reject { |link| dates.key?(link) }
missing.group_by(&:first).each do |type, list|
list.map(&:last).uniq.each_slice(IDS_PER_QUERY) do |ids|
query = "SELECT * FROM #{type} WHERE Id IN (#{ids.map { |id| "'#{id.gsub(/\D/, '')}'" }.join(',')})"
records = QboConnectionService.with_qbo_service(entity: type) { |service| service.query(query).entries }
Array(records).each { |record| dates[[type, record.id.to_s]] = record.txn_date }
end
end
dates
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read the dates of what was applied to an invoice: #{e.message}"
dates
end
end
end
+6 -2
View File
@@ -34,8 +34,12 @@ module RedmineQboBilling
balance < total ? :partial : :open
end
def label(status)
status ? I18n.t("label_invoice_status_#{status}") : ''
# "Paid", or with the day it was paid in full, "Paid 11/03/2026"
def label(status, paid_on: nil)
return '' unless status
return I18n.t(:label_invoice_status_paid_on, date: I18n.l(paid_on)) if status == :paid && paid_on
I18n.t("label_invoice_status_#{status}")
end
def to_d(value)
+59
View File
@@ -0,0 +1,59 @@
#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 page posts (SOP-OPS-014): the canceled order's estimate, the parts the restocking fee is
# worked out on, how the money goes back (card terminal or company check), and what else to do in
# QuickBooks and Redmine.
class RefundForm
include ActiveModel::Model
include ActiveModel::Validations
ATTRIBUTES = %i[customer_id estimate_id txn_date parts_amount method check_number reason
close_estimate cancel_issues email_customer].freeze
attr_accessor(*ATTRIBUTES)
validate :validate_refund
def self.from_params(params)
params = params.to_h.stringify_keys
new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] })
end
def parts_value
parts_amount.blank? ? BigDecimal('0') : EstimateForm.decimal(parts_amount)
end
def txn_date_value
EstimateForm.date(txn_date)
end
def check?
method == 'check'
end
%i[close_estimate cancel_issues email_customer].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_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?
value = parts_value
errors.add(:base, I18n.t(:error_refund_parts_amount)) if value.nil? || value.negative?
errors.add(:base, I18n.t(:error_estimate_field_invalid, field: I18n.t(:label_refund_date))) if txn_date_value.nil?
end
end
end
+127
View File
@@ -0,0 +1,127 @@
#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
# The QuickBooks calls a refund makes (RefundWriter), kept apart so the steps can be tested without QuickBooks.
class RefundGateway
# The customer's payments with money not yet applied (deposits and other credit), oldest first
def unapplied_payments(customer_id)
payments = with_service('Payment') do |service|
service.all("SELECT * FROM Payment WHERE CustomerRef = '#{customer_id.to_i}'")
end
Array(payments).select { |p| BigDecimal(p.unapplied_amount.to_s.presence || '0').positive? }
.sort_by { |p| [p.txn_date || Date.new(1900), p.id.to_i] }
end
def estimate(id)
QboEstimateService.with_service { |service| service.fetch_by_id(id) }
end
def create_invoice(invoice)
with_service('Invoice') { |service| service.create(invoice) }
end
def invoice(id)
with_service('Invoice') { |service| service.fetch_by_id(id) }
end
# Applies amount of the payment's unapplied money to a transaction (an invoice, or the refund check or
# expense). QuickBooks replaces a payment's lines on a sparse update, so its lines are sent back with
# the new one (added to the line already linked to that transaction, if any). Returns the saved payment.
def apply_payment(payment, amount, txn_id, txn_type)
lines = Array(payment.line_items).map { |line| copy_line(line) }
same = lines.find do |line|
Array(line.linked_transactions).any? { |t| t.txn_id.to_s == txn_id.to_s && t.txn_type.to_s == txn_type }
end
if same
same.amount = BigDecimal(same.amount.to_s) + amount
else
lines << self.class.linked_line(amount, txn_id, txn_type)
end
update = Quickbooks::Model::Payment.new
update.id = payment.id
update.sync_token = payment.sync_token
update.customer_ref = payment.customer_ref
update.total = payment.total
update.line_items = lines
with_service('Payment') { |service| service.update(update, sparse: true) }
end
def create_purchase(purchase)
with_service('Purchase') { |service| service.create(purchase) }
end
# The first active account of a QuickBooks account type ('Accounts Receivable', 'Bank')
def account_id(type)
account = with_service('Account') do |service|
service.query("SELECT * FROM Account WHERE AccountType = '#{type}' AND Active = true").entries.first
end
account&.id&.to_s
end
def customer_balance(customer_id)
customer = with_service('Customer') { |service| service.fetch_by_id(customer_id) }
BigDecimal(customer&.balance.to_s.presence || '0')
end
# Marks the canceled order's estimate Rejected, so it can't be invoiced later
def reject_estimate(estimate)
update = EstimateWriter.status_update(estimate, 'Rejected')
QboEstimateService.with_service { |service| service.update(update, sparse: true) }
end
def sync_invoice(id)
InvoiceSyncService.new.sync_by_id(id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not cache invoice #{id} after a refund: #{e.message}"
end
def sync_payment(id)
PaymentSyncService.new.sync_by_id(id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not cache payment #{id} after a refund: #{e.message}"
end
def sync_estimate(id)
EstimateSyncService.new.sync_by_id(id)
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not cache estimate #{id} after a refund: #{e.message}"
end
def self.linked_line(amount, txn_id, txn_type)
line = Quickbooks::Model::Line.new
line.amount = amount
link = Quickbooks::Model::LinkedTransaction.new
link.txn_id = txn_id.to_s
link.txn_type = txn_type
line.linked_transactions = [link]
line
end
private
def copy_line(line)
copy = Quickbooks::Model::Line.new
copy.amount = BigDecimal(line.amount.to_s)
copy.linked_transactions = Array(line.linked_transactions).map do |t|
link = Quickbooks::Model::LinkedTransaction.new
link.txn_id = t.txn_id
link.txn_type = t.txn_type
link
end
copy
end
def with_service(entity, &block)
QboConnectionService.with_qbo_service(entity: entity, &block)
end
end
end
+123
View File
@@ -0,0 +1,123 @@
#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
# A refund as a PDF (SOP-OPS-014): what was refunded and how, from what Redmine recorded when it was made, so it
# can be printed or filed without opening QuickBooks (QuickBooks has no PDF of a check or an expense).
class RefundPdf
include Redmine::I18n
WIDTH = 190
def initialize(refund)
@refund = refund
end
def render
pdf = ::Redmine::Export::PDF::ITCPDF.new(current_language)
pdf.set_title(title)
pdf.alias_nb_pages
pdf.footer_date = format_date(User.current.today)
pdf.add_page
pdf.SetFontStyle('B', 14)
pdf.RDMMultiCell(WIDTH, 7, shop_name)
pdf.SetFontStyle('B', 12)
pdf.RDMMultiCell(WIDTH, 7, title)
pdf.ln(3)
details(pdf)
pdf.ln(4)
amounts(pdf)
pdf.ln(4)
notes(pdf)
signature(pdf) if @refund.check?
pdf.output
end
def title
"#{l(:label_refund)} · #{@refund.customer&.name} · #{format_date(@refund.txn_date)}"
end
def filename
"refund-#{@refund.txn_date}-#{@refund.customer&.name.to_s.parameterize.presence || @refund.customer_id}.pdf"
end
private
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)],
[l(:label_refund_reason), @refund.reason.to_s]]
rows.each { |label, value| row(pdf, label, value) }
end
def amounts(pdf)
pdf.SetFontStyle('B', 10)
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 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?
money_row(pdf, label, -fee)
end
pdf.SetFontStyle('B', 11)
money_row(pdf, "#{l(:label_refund_amount)} · #{method_text}", @refund.refund_amount, border: 'T')
pdf.SetFontStyle('', 10)
unless @refund.balance_after.nil?
money_row(pdf, l(:label_refund_balance_after), @refund.balance_after)
end
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?
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
# For a refund check: the customer signs for it
def signature(pdf)
pdf.ln(14)
pdf.SetFontStyle('', 10)
pdf.RDMCell(110, 6, l(:label_refund_received_by), 'T', 0)
pdf.RDMCell(10, 6, '', 0, 0)
pdf.RDMCell(70, 6, l(:label_date), 'T', 1)
end
def method_text
@refund.check? ? "#{@refund.method_name} ##{@refund.check_number}" : @refund.method_name
end
def row(pdf, label, value)
pdf.SetFontStyle('B', 10)
pdf.RDMCell(50, 6, label.to_s, 0, 0)
pdf.SetFontStyle('', 10)
pdf.RDMMultiCell(WIDTH - 50, 6, value.to_s)
end
def money_row(pdf, label, amount, border: 0)
pdf.RDMCell(WIDTH - 40, 7, label.to_s, border, 0)
pdf.RDMCell(40, 7, RefundWriter.money(amount), border, 1, 'R')
end
def shop_name
reminders = defined?(RedmineQboReminders::Settings) ? RedmineQboReminders::Settings.current : nil
reminders&.[]('shop_name').to_s.presence || Setting.app_title
rescue StandardError
Setting.app_title
end
end
end
+329
View File
@@ -0,0 +1,329 @@
#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
# Customer refunds for canceled orders and returned parts (SOP-OPS-014), the way the SOP does them in QuickBooks:
#
# 1. A restocking fee invoice for 30% of the parts (labor carries no fee), its line showing the math, paid
# from the customer's credit (their deposit), oldest first.
# 2. The rest of the customer's credit is refunded: a company check, or a partial refund on the card terminal.
# 3. The refund is recorded in QuickBooks with the category Accounts Receivable, from the bank account in the
# settings, described "Refund for deposit on E1234": a Check for a check, an Expense for a card refund.
# 4. The credit left on the customer's payments is applied to that check or expense, so the deposit, the fee
# invoice and the refund reconcile and the customer's balance comes back to $0.00.
#
# Then, as asked on the page: the canceled order's estimate is marked Rejected in QuickBooks, its work orders are
# set to the canceled status with the reason as a note, and the customer is emailed a summary.
#
# Each refund is recorded (QboRefund). Steps 1 to 4 stop at the first failure, and the record says which step
# failed and what was already done, so it can be finished in QuickBooks. The later steps only add warnings.
module RefundWriter
class Error < StandardError; end
Credit = Struct.new(:payment_id, :date, :reference, :memo, :amount, keyword_init: true)
Preview = Struct.new(:credits, :credit_total, :parts_amount, :fee_rate, :fee, :refund, keyword_init: true)
CLOSED_ESTIMATE_STATUSES = %w[Closed Converted Rejected].freeze
CANCELED_STATUS_NAMES = %w[Canceled Cancelled].freeze
module_function
def settings
Setting.plugin_redmine_qbo || {}
rescue StandardError
{}
end
# The restocking fee rate in percent (plugin setting, SOP-OPS-014: 30)
def fee_rate
rate = BigDecimal(settings['restocking_fee_rate'].to_s.strip, exception: false)
rate.nil? || rate.negative? ? BigDecimal('30') : rate
end
# The product/service on the restocking fee invoice (plugin setting)
def fee_item
Item.find_by(id: settings['restocking_item_id']) if settings['restocking_item_id'].present?
end
def fee(parts, rate = fee_rate)
(parts.to_d * rate.to_d / 100).round(2, BigDecimal::ROUND_HALF_UP)
end
# The parts on an estimate: its lines that aren't labor (with the lines inside bundles), before tax
def parts_amount(estimate)
labor_ids = LaborItems.ids
parts_lines(Array(estimate&.line_items), labor_ids).sum(BigDecimal('0')) { |line| BigDecimal(line.amount.to_s.presence || '0') }
end
def parts_lines(lines, labor_ids)
lines.flat_map do |line|
if line.respond_to?(:group_line_detail) && line.group_line_detail
parts_lines(Array(line.group_line_detail.line_items), labor_ids)
elsif (ref = sales_detail(line)&.item_ref) && ref.value.present?
LaborItems.match?(ref, ids: labor_ids) ? [] : [line]
else
[]
end
end
end
# A sales line's detail: estimates and invoices name it SalesLineItemDetail (InvoiceLineItem), other
# transactions SalesItemLineDetail (Line)
def sales_detail(line)
if line.respond_to?(:sales_line_item_detail) then line.sales_line_item_detail
elsif line.respond_to?(:sales_item_line_detail) then line.sales_item_line_detail
end
end
# The customer's credit: their payments' unapplied money, oldest first
def credits(customer, gateway: RefundGateway.new)
gateway.unapplied_payments(customer.id).map do |payment|
Credit.new(payment_id: payment.id.to_s, date: payment.txn_date, reference: payment.payment_ref_number.to_s,
memo: payment.private_note.to_s, amount: BigDecimal(payment.unapplied_amount.to_s))
end
end
# The customer's estimates to pick the canceled order from, newest first: [[label, id], ...]
def estimate_choices(customer)
Estimate.where(customer_id: customer.id).order(txn_date: :desc, id: :desc).limit(50).map do |estimate|
total = estimate.respond_to?(:total_amount) && estimate.total_amount ? " · $#{format('%.2f', estimate.total_amount)}" : ''
["E#{estimate.doc_number} · #{estimate.txn_date}#{total}", estimate.id.to_s]
end
end
# What the page shows before the refund is made: the credit, the fee and what will be refunded
def preview(customer, parts:, gateway: RefundGateway.new)
list = credits(customer, gateway: gateway)
total = list.sum(BigDecimal('0'), &:amount)
rate = fee_rate
amount = fee(parts, rate)
Preview.new(credits: list, credit_total: total, parts_amount: parts.to_d, fee_rate: rate, fee: amount,
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}" : ''
I18n.t(:text_refund_fee_line, rate: plain(rate), parts: money(parts), on: on, fee: money(amount))
end
# "Refund for deposit on E1068" (SOP-OPS-014 step 3)
def refund_description(estimate_number, card:)
text = estimate_number.present? ? I18n.t(:text_refund_line, number: estimate_number) : I18n.t(:text_refund_line_credit)
card ? "#{text} #{I18n.t(:text_refund_line_card)}" : text
end
# Makes the refund; returns the QboRefund (done, or incomplete with the step that failed 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
estimate = load_estimate(form, customer, gateway)
rate = fee_rate
parts = form.parts_value
fee_amount = fee(parts, rate)
item = fee_item
raise Error, I18n.t(:error_refund_no_fee_item) if fee_amount.positive? && item.nil?
payments = gateway.unapplied_payments(customer.id)
credit = payments.sum(BigDecimal('0')) { |p| BigDecimal(p.unapplied_amount.to_s) }
raise Error, I18n.t(:error_refund_no_credit) unless credit.positive?
raise Error, I18n.t(:error_refund_fee_over_credit, fee: money(fee_amount), credit: money(credit)) if fee_amount >= credit
ar_account = gateway.account_id('Accounts Receivable')
raise Error, I18n.t(:error_refund_no_ar_account) unless ar_account
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
record = QboRefund.create!(customer_id: customer.id, estimate_id: estimate&.id, estimate_number: estimate&.doc_number,
user: user, txn_date: form.txn_date_value, method: form.method,
check_number: form.check? ? form.check_number : nil, reason: form.reason,
parts_amount: parts, fee_rate: rate, fee_amount: fee_amount, credit_amount: credit,
status: 'incomplete')
warnings = []
if fee_amount.positive?
fee_paid = step(record, :fee) { charge_fee(record, customer, item, gateway) }
return record unless fee_paid
end
refunded = step(record, :refund) { record_refund(record, customer, form, ar_account, bank_account, gateway) }
return record unless refunded
begin
record.update!(balance_after: gateway.customer_balance(customer.id))
rescue StandardError
warnings << I18n.t(:text_refund_balance_unknown)
end
warnings << close_estimate(record, estimate, gateway) if form.close_estimate? && estimate
warnings << cancel_issues(record, estimate, form, user) if form.cancel_issues? && estimate
warnings << email_customer(record, customer, mailer) if form.email_customer?
record.update!(status: 'done', message: warnings.compact.join("\n").presence)
record
end
# The canceled order's estimate, which must be the customer's
def load_estimate(form, customer, gateway)
return nil if form.estimate_id.blank?
estimate = gateway.estimate(form.estimate_id)
raise Error, I18n.t(:notice_estimate_not_found) unless estimate
raise Error, I18n.t(:error_refund_estimate_customer) unless estimate.customer_ref&.value.to_s == customer.id.to_s
estimate
end
# Runs one of the steps that must all succeed; on failure records which step and why
def step(record, name)
yield
true
rescue StandardError => e
detail = e.respond_to?(:detail) && e.detail.present? ? "#{e.message}: #{e.detail}" : e.message
Rails.logger.error "[RedmineQboBilling] Refund #{record.id}, #{name}: #{detail}"
record.update!(message: I18n.t(:"error_refund_step_#{name}", error: detail))
false
end
# Step 1: the restocking fee invoice, paid from the customer's credit
def charge_fee(record, customer, item, gateway)
invoice = Quickbooks::Model::Invoice.new
invoice.customer_id = customer.id
invoice.txn_date = record.txn_date
invoice.private_note = I18n.t(:text_refund_private_note, reason: record.reason)
line = Quickbooks::Model::InvoiceLineItem.new
line.amount = record.fee_amount
line.description = fee_description(record.parts_amount, record.fee_rate, record.fee_amount, record.estimate_number)
line.sales_item! do |detail|
detail.item_id = item.id
detail.quantity = 1
detail.unit_price = record.fee_amount
end
invoice.line_items = [line]
saved = gateway.create_invoice(invoice)
raise Error, I18n.t(:error_refund_fee_not_saved) unless saved&.id
record.update!(fee_invoice_id: saved.id.to_s, fee_invoice_number: saved.doc_number.to_s)
# QuickBooks may already have applied the customer's credit to the new invoice ("Automatically apply credits")
owed = BigDecimal(gateway.invoice(saved.id).balance.to_s.presence || '0')
gateway.unapplied_payments(customer.id).each do |payment|
break unless owed.positive?
take = [owed, BigDecimal(payment.unapplied_amount.to_s)].min
next unless take.positive?
gateway.apply_payment(payment, take, saved.id, 'Invoice')
gateway.sync_payment(payment.id)
owed -= take
end
raise Error, I18n.t(:error_refund_fee_unpaid, amount: money(owed)) if owed.positive?
gateway.sync_invoice(saved.id)
end
# Steps 2 to 4: the refund check or expense for the rest of the credit, and the credit applied to it
def record_refund(record, customer, form, ar_account, bank_account, gateway)
payments = gateway.unapplied_payments(customer.id)
amount = payments.sum(BigDecimal('0')) { |p| BigDecimal(p.unapplied_amount.to_s) }
raise Error, I18n.t(:error_refund_nothing_left) unless amount.positive?
card = !form.check?
purchase = Quickbooks::Model::Purchase.new
purchase.payment_type = card ? 'Cash' : 'Check'
purchase.doc_number = record.check_number unless card
purchase.txn_date = record.txn_date
purchase.account_ref = Quickbooks::Model::BaseReference.new(bank_account.to_s)
payee = Quickbooks::Model::BaseReference.new(customer.id.to_s)
payee.type = 'Customer'
purchase.entity_ref = payee
purchase.private_note = I18n.t(:text_refund_private_note, reason: record.reason)
line = Quickbooks::Model::PurchaseLineItem.new
line.amount = amount
line.description = refund_description(record.estimate_number, card: card)
line.account_based_expense! do |detail|
detail.account_ref = Quickbooks::Model::BaseReference.new(ar_account.to_s)
detail.customer_ref = Quickbooks::Model::BaseReference.new(customer.id.to_s)
end
purchase.line_items = [line]
saved = gateway.create_purchase(purchase)
raise Error, I18n.t(:error_refund_not_saved) unless saved&.id
record.update!(purchase_id: saved.id.to_s, refund_amount: amount)
# The credit is applied to the check ("Check") or the expense ("Expense")
payments.each do |payment|
gateway.apply_payment(payment, BigDecimal(payment.unapplied_amount.to_s), saved.id, card ? 'Expense' : 'Check')
gateway.sync_payment(payment.id)
end
end
# Marks the canceled order's estimate Rejected; returns a warning, or nil
def close_estimate(record, estimate, gateway)
return nil if CLOSED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s)
gateway.reject_estimate(estimate)
gateway.sync_estimate(estimate.id)
record.update!(estimate_closed: true)
nil
rescue StandardError => e
I18n.t(:text_refund_estimate_not_closed, error: e.message)
end
# Sets the estimate's open work orders to the canceled status, with the reason as a note (Work Orders §5)
def cancel_issues(record, estimate, form, user)
status = canceled_status
return I18n.t(:text_refund_no_canceled_status) unless status
ids = Issue.where(estimate_id: estimate.id).pluck(:id) + QboEstimateLineIssue.where(estimate_id: estimate.id).pluck(:issue_id)
note = I18n.t(:text_refund_issue_note, reason: form.reason, fee: money(record.fee_amount),
refund: money(record.refund_amount), method: record.method_name)
failed = []
canceled = Issue.where(id: ids.uniq).includes(:status).reject(&:closed?).filter_map do |issue|
issue.init_journal(user, note)
issue.status = status
if issue.save
issue.id
else
failed << "##{issue.id} (#{issue.errors.full_messages.join(', ')})"
nil
end
end
record.update!(canceled_issue_ids: canceled)
failed.any? ? I18n.t(:text_refund_issues_not_canceled, issues: failed.join('; ')) : nil
end
# The work order status for canceled orders (plugin setting, else a closed status named Canceled)
def canceled_status
id = settings['refund_canceled_status_id']
(IssueStatus.find_by(id: id) if id.present?) ||
IssueStatus.where(is_closed: true).detect { |s| CANCELED_STATUS_NAMES.include?(s.name.to_s.strip) }
end
# Emails the customer a summary; returns a warning, or nil
def email_customer(record, customer, mailer)
email = customer.email.to_s.strip
return I18n.t(:text_refund_no_email) if email.blank?
mailer.refund_summary(record, email).deliver_now
record.update!(emailed_to: email)
nil
rescue StandardError => e
I18n.t(:text_refund_email_failed, error: e.message)
end
def money(amount)
whole, cents = format('%.2f', amount.to_d.abs).split('.')
"#{'-' if amount.to_d.negative?}$#{whole.reverse.scan(/\d{1,3}/).join(',').reverse}.#{cents}"
end
def plain(number)
number = number.to_d
number == number.to_i ? number.to_i.to_s : number.to_s('F')
end
end
end
+101
View File
@@ -0,0 +1,101 @@
#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 QboRefundsTest < Redmine::IntegrationTest
include QboRefundTestHelper
def setup
@customer = create_customer
Customer.any_instance.stubs(:email).returns('jane@example.com')
RedmineQboBilling::RefundWriter.stubs(:fee_item).returns(fee_item)
@gateway = FakeGateway.new(payments: [deposit(50, 500)], estimate: estimate)
RedmineQboBilling::RefundGateway.stubs(:new).returns(@gateway)
RedmineQboBilling::RefundWriter.stubs(:estimate_choices).returns([['E1068 · 2026-10-06', '598']])
QboRefundMailer.stubs(:refund_summary).returns(stub(deliver_now: true))
end
def test_needs_the_permission
log_user('jsmith', 'jsmith')
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}"
assert_response :forbidden
Role.find(1).add_permission!(:issue_refunds)
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}"
assert_response :success
end
def test_refund_page_fills_in_the_estimates_parts
log_user('admin', 'admin')
get "/qbo_refunds/new?customer_id=#{CUSTOMER_ID}&estimate_id=598"
assert_response :success
assert_select 'input[name=?][value=?]', 'refund[parts_amount]', '307.99'
assert_select '#qbo-refund-credit', text: '$500.00'
assert_select '#qbo-refund-fee', text: '-$92.40'
assert_select '#qbo-refund-amount', text: '$407.60'
assert_select 'input[name=?][value=check][checked]', 'refund[method]'
end
def test_refund
log_user('admin', 'admin')
post '/qbo_refunds', params: { refund: { customer_id: CUSTOMER_ID, estimate_id: '598', parts_amount: '307.99',
method: 'check', check_number: '5001', txn_date: '2026-11-16',
reason: 'Canceled', close_estimate: '1', cancel_issues: '0', email_customer: '1' } }
refund = QboRefund.last
assert_redirected_to "/qbo_refunds/#{refund.id}"
assert refund.done?, refund.message
assert_equal BigDecimal('407.60'), refund.refund_amount
follow_redirect!
assert_select 'p', text: /\$407\.60 · Company check #5001/
assert_select 'a[href*="app/check?txnId="]'
assert_select 'a[href=?]', "/qbo_invoices/#{refund.fee_invoice_id}/edit"
assert_select 'a[href=?]', '/qbo_estimates/598/edit'
assert_select 'a[href*="app/invoice?txnId="]', count: 0
get "/customers/#{CUSTOMER_ID}"
assert_select 'a[href=?]', "/qbo_refunds/#{refund.id}"
end
def test_form_errors
log_user('admin', 'admin')
post '/qbo_refunds', params: { refund: { customer_id: CUSTOMER_ID, parts_amount: '10', method: 'check',
check_number: '', txn_date: '2026-11-16', reason: '' } }
assert_response :unprocessable_entity
assert_select '#errorExplanation', text: /check number/
assert_select '#errorExplanation', text: /reason/
assert_equal 0, QboRefund.count
end
def test_email_again
log_user('admin', 'admin')
refund = QboRefund.create!(customer_id: CUSTOMER_ID, method: 'check', check_number: '5001', status: 'done',
refund_amount: 100, txn_date: Date.new(2026, 11, 16))
post "/qbo_refunds/#{refund.id}/email"
assert_redirected_to "/qbo_refunds/#{refund.id}"
assert_equal 'jane@example.com', refund.reload.emailed_to
end
def test_pdf
log_user('admin', 'admin')
refund = QboRefund.create!(customer_id: CUSTOMER_ID, method: 'check', check_number: '5001', status: 'done',
estimate_number: '1068', reason: 'Canceled', parts_amount: 307.99, fee_rate: 30,
fee_amount: 92.40, fee_invoice_number: '1502', credit_amount: 500, refund_amount: 407.60,
balance_after: 0, txn_date: Date.new(2026, 11, 16), user_id: 1)
get "/qbo_refunds/#{refund.id}/pdf"
assert_response :success
assert_equal 'application/pdf', response.media_type
assert response.body.start_with?('%PDF')
assert_match(/refund-2026-11-16-jane-customer\.pdf/, response.headers['Content-Disposition'])
get "/qbo_refunds/#{refund.id}"
assert_select 'a[href=?]', "/qbo_refunds/#{refund.id}/pdf"
end
end
+169
View File
@@ -0,0 +1,169 @@
#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/test_helper', __dir__)
module QboRefundTestHelper
CUSTOMER_ID = 9101
# Stands in for QuickBooks: the customer's payments, and what the refund made
class FakeGateway
attr_reader :payments, :invoices, :purchases, :applied, :rejected
attr_accessor :auto_apply, :fail_on, :estimate_record, :balance
def initialize(payments: [], estimate: nil)
@payments = payments
@estimate_record = estimate
@invoices = []
@purchases = []
@applied = []
@rejected = []
@auto_apply = false
@balance = BigDecimal('0')
end
def unapplied_payments(_customer_id)
payments.select { |p| p.unapplied_amount.to_d.positive? }.sort_by { |p| [p.txn_date, p.id.to_i] }
end
def estimate(id)
estimate_record if estimate_record && estimate_record.id.to_s == id.to_s
end
def create_invoice(invoice)
raise Quickbooks::IntuitRequestException, 'QuickBooks is down' if fail_on == :invoice
invoice.id = (700 + invoices.size).to_s
invoice.doc_number = (1500 + invoices.size).to_s
invoice.total = invoice.line_items.sum(BigDecimal('0')) { |l| l.amount.to_d }
invoice.balance = invoice.total
invoices << invoice
# QuickBooks' "Automatically apply credits"
if auto_apply
unapplied_payments(nil).each do |p|
take = [invoice.balance, p.unapplied_amount.to_d].min
next unless take.positive?
apply_payment(p, take, invoice.id, 'Invoice')
end
end
invoice
end
def invoice(id)
invoices.find { |i| i.id.to_s == id.to_s }
end
def apply_payment(payment, amount, txn_id, txn_type)
raise Quickbooks::IntuitRequestException, 'Link refused' if fail_on == :link
payment.unapplied_amount = payment.unapplied_amount.to_d - amount
invoice(txn_id).balance = invoice(txn_id).balance.to_d - amount if txn_type == 'Invoice'
applied << [payment.id, amount, txn_id.to_s, txn_type]
payment
end
def create_purchase(purchase)
raise Quickbooks::IntuitRequestException, 'QuickBooks is down' if fail_on == :purchase
purchase.id = (800 + purchases.size).to_s
purchases << purchase
purchase
end
def account_id(type)
{ 'Accounts Receivable' => '84', 'Bank' => '35' }[type]
end
def customer_balance(_customer_id)
balance
end
def reject_estimate(estimate)
rejected << estimate.id.to_s
end
def sync_invoice(_id); end
def sync_payment(_id); end
def sync_estimate(_id); end
end
class FakeMailer
Delivery = Struct.new(:refund, :email) do
def deliver_now
FakeMailer.sent << [refund.id, email]
end
end
def self.sent
@sent ||= []
end
def self.refund_summary(refund, email)
Delivery.new(refund, email)
end
end
def self.included(base)
base.fixtures :projects, :users, :email_addresses, :members, :member_roles, :roles, :issues, :trackers,
:projects_trackers, :issue_statuses, :enabled_modules, :enumerations, :workflows
base.setup do
QboRefund.delete_all
Customer.where(id: CUSTOMER_ID).delete_all
FakeMailer.sent.clear
end
end
def create_customer
customer = Customer.new(id: CUSTOMER_ID, name: 'Jane Customer')
customer.skip_qbo_push = true
customer.save!
customer
end
def deposit(id, amount, date: Date.new(2026, 11, 2))
payment = Quickbooks::Model::Payment.new
payment.id = id.to_s
payment.txn_date = date
payment.total = BigDecimal(amount.to_s)
payment.unapplied_amount = BigDecimal(amount.to_s)
payment.customer_ref = Quickbooks::Model::BaseReference.new(CUSTOMER_ID.to_s)
payment
end
def item_line(item_id, name, amount)
line = Quickbooks::Model::InvoiceLineItem.new
line.amount = BigDecimal(amount.to_s)
line.sales_item! { |d| d.item_ref = Quickbooks::Model::BaseReference.new(item_id.to_s, name: name) }
line
end
# E1068: $1,900 labor and $307.99 of parts
def estimate(id: 598, status: 'Accepted', customer_id: CUSTOMER_ID)
estimate = Quickbooks::Model::Estimate.new
estimate.id = id.to_s
estimate.doc_number = '1068'
estimate.txn_status = status
estimate.customer_ref = Quickbooks::Model::BaseReference.new(customer_id.to_s)
estimate.line_items = [item_line(1, 'Labor', 1900), item_line(2, 'TF HD JK Ball Joints', '307.99')]
estimate
end
def fee_item
Struct.new(:id, :name).new('55', 'Restocking Fee')
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',
reason: 'Customer canceled the order', close_estimate: '1',
cancel_issues: '1', email_customer: '1' }.merge(attributes))
end
end
+68
View File
@@ -0,0 +1,68 @@
#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 BusinessReportTest < ActiveSupport::TestCase
Report = RedmineQboBilling::BusinessReport
NOV = Date.new(2026, 11, 1)
def report(data)
full = { estimates: [], invoices: [], paid: [], payments: [], issues: [], time_entries: [] }.merge(data)
Report.new(period: 'custom', from: NOV, to: NOV.end_of_month, today: Date.new(2026, 11, 20), data: full,
previous_data: full.transform_values { [] })
end
def test_estimates_and_invoices_without_tax
r = report(estimates: [[NOV + 1, '1080', 10, '80'], [NOV + 2, '500', 2]],
invoices: [[NOV + 3, '1070', 5, '0', '70'], [NOV + 4, '200', 1, '200', '0']],
payments: [[NOV + 5, '1070']])
assert_equal BigDecimal('1500'), r.money[:estimates][:total]
assert_equal BigDecimal('1200'), r.money[:invoices][:total]
assert_equal BigDecimal('1270'), r.money[:invoices][:with_tax]
assert_equal BigDecimal('200'), r.money[:invoices][:balance]
assert_equal BigDecimal('1070'), r.money[:payments][:total]
# $1,070 collected of $1,270 invoiced with tax
assert_equal 84, r.ratios[:collected_of_invoiced]
assert_equal 80, r.ratios[:invoiced_of_estimated]
end
def test_invoices_paid_in_full
r = report(paid: [[NOV + 3, '1070', '70'], [NOV + 9, '500', nil]])
assert_equal BigDecimal('1500'), r.money[:paid][:total]
assert_equal 2, r.money[:paid][:count]
november = r.months.find { |m| m[:month] == NOV }
assert_equal BigDecimal('1500'), november[:paid]
assert_equal 1500.0, r.chart[:current][:paid].compact.sum
end
def test_rows_missing_tax_are_unsynced
r = report(estimates: [[NOV + 1, '100', 1, nil]], invoices: [[NOV + 1, '100', 1, '0', '0']])
assert_equal 1, r.unsynced_count
end
def test_paid_badge_shows_the_day
assert_equal 'Paid', RedmineQboBilling::InvoiceStatus.label(:paid)
assert_match(/\APaid \S+/, RedmineQboBilling::InvoiceStatus.label(:paid, paid_on: Date.new(2026, 11, 3)))
assert_equal 'Open', RedmineQboBilling::InvoiceStatus.label(:open, paid_on: Date.new(2026, 11, 3))
end
def test_taxes
r = report(invoices: [[NOV + 3, '1070', 5, '0', '70'], [NOV + 4, '200', 1, '200', '0'], [NOV + 6, '535', 2, '0', '35']],
paid: [[NOV + 9, '1070', '70'], [Date.new(2026, 11, 10), '500', nil]])
assert_equal({ total: BigDecimal('105'), count: 2 }, r.taxes[:tax_invoiced])
assert_equal({ total: BigDecimal('70'), count: 1 }, r.taxes[:tax_collected])
november = r.months.find { |m| m[:month] == NOV }
assert_equal BigDecimal('105'), november[:tax_invoiced]
assert_equal BigDecimal('70'), november[:tax_collected]
assert_equal 105.0, r.chart[:current][:tax_invoiced].compact.sum
assert_equal 70.0, r.chart[:current][:tax_collected].compact.sum
end
end
+79
View File
@@ -0,0 +1,79 @@
#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 InvoicePaidOnTest < ActiveSupport::TestCase
PaidOn = RedmineQboBilling::InvoicePaidOn
def setup
Payment.where(id: [9301, 9302]).delete_all
end
def link(type, id)
link = Quickbooks::Model::LinkedTransaction.new
link.txn_type = type
link.txn_id = id.to_s
link
end
def invoice(date: Date.new(2026, 10, 30), total: 2207.99, balance: 0, links: [], tax: nil)
invoice = Quickbooks::Model::Invoice.new
invoice.id = '601'
invoice.txn_date = date
invoice.total = BigDecimal(total.to_s)
invoice.balance = BigDecimal(balance.to_s)
invoice.linked_transactions = links
if tax
invoice.txn_tax_detail = Quickbooks::Model::TransactionTaxDetail.new
invoice.txn_tax_detail.total_tax = BigDecimal(tax.to_s)
end
invoice
end
def local_payment(id, date)
payment = Payment.new(id: id, txn_date: date, total_amount: 100)
payment.skip_qbo_push = true
payment.save!(validate: false)
end
def test_tax
assert_equal BigDecimal('80.30'), PaidOn.tax(invoice(tax: '80.30'))
assert_equal BigDecimal('0'), PaidOn.tax(invoice)
end
def test_paid_in_full_on_the_last_payment
local_payment(9301, Date.new(2026, 10, 8)) # deposit before the invoice
local_payment(9302, Date.new(2026, 11, 3)) # final payment
remote = invoice(links: [link('Payment', 9301), link('Payment', 9302), link('Estimate', 598)])
QboConnectionService.expects(:with_qbo_service).never
assert_equal Date.new(2026, 11, 3), PaidOn.paid_on(remote)
end
def test_deposit_before_the_invoice_counts_on_the_invoice_date
local_payment(9301, Date.new(2026, 10, 8))
assert_equal Date.new(2026, 10, 30), PaidOn.paid_on(invoice(links: [link('Payment', 9301)]))
end
def test_payments_not_synced_and_credit_memos_are_read_from_quickbooks
memo = Quickbooks::Model::CreditMemo.new
memo.id = '70'
memo.txn_date = Date.new(2026, 11, 9)
service = mock('service')
service.stubs(:query).returns(stub(entries: [memo]))
QboConnectionService.expects(:with_qbo_service).with(entity: 'CreditMemo').yields(service).returns([memo])
assert_equal Date.new(2026, 11, 9), PaidOn.paid_on(invoice(links: [link('CreditMemo', 70)]))
end
def test_open_and_voided_invoices_arent_paid
assert_nil PaidOn.paid_on(invoice(balance: 10))
assert_nil PaidOn.paid_on(invoice(total: 0))
end
end
+177
View File
@@ -0,0 +1,177 @@
#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 RefundWriterTest < ActiveSupport::TestCase
include QboRefundTestHelper
Writer = RedmineQboBilling::RefundWriter
def setup
User.current = User.find(1)
@customer = create_customer
Customer.any_instance.stubs(:email).returns('jane@example.com')
Writer.stubs(:fee_item).returns(fee_item)
@gateway = FakeGateway.new(payments: [deposit(50, 300), deposit(51, '307.99', date: Date.new(2026, 11, 5))], estimate: estimate)
end
def refund(form = refund_form, gateway: @gateway)
Writer.refund!(form, user: User.find(1), gateway: gateway, mailer: FakeMailer)
end
def test_fee
assert_equal BigDecimal('92.40'), Writer.fee(BigDecimal('307.99'), 30)
assert_equal BigDecimal('0'), Writer.fee(0, 30)
end
def test_parts_amount_leaves_out_labor
assert_equal BigDecimal('307.99'), Writer.parts_amount(estimate)
end
def test_parts_inside_bundles
bundle = Quickbooks::Model::InvoiceLineItem.new
bundle.amount = BigDecimal('500')
bundle.group_line_detail!
bundle.group_line_detail.line_items = [item_line(1, 'Labor', 380), item_line(3, 'Brake Pads', 120)]
subtotal = Quickbooks::Model::InvoiceLineItem.new
subtotal.amount = BigDecimal('9999')
subtotal.detail_type = 'SubTotalLineDetail'
subtotal.sub_total_line_detail = Quickbooks::Model::SubTotalLineDetail.new
e = estimate
e.line_items = e.line_items + [bundle, subtotal]
assert_equal BigDecimal('427.99'), Writer.parts_amount(e)
end
def test_refund_by_check
record = refund
assert record.done?, record.message
# $92.40 fee (30% of $307.99) out of $607.99 credit: $515.59 refunded
assert_equal BigDecimal('92.40'), record.fee_amount
assert_equal BigDecimal('607.99'), record.credit_amount
assert_equal BigDecimal('515.59'), record.refund_amount
invoice = @gateway.invoices.first
line = invoice.line_items.first
assert_equal 'Restocking fee: 30% × $307.99 parts on E1068 = $92.40', line.description
assert_equal '55', line.sales_line_item_detail.item_ref.value
assert_equal BigDecimal('0'), invoice.balance
purchase = @gateway.purchases.first
assert_equal 'Check', purchase.payment_type
assert_equal '5001', purchase.doc_number
assert_equal '35', purchase.account_ref.value
assert_equal 'Customer', purchase.entity_ref.type
assert_equal CUSTOMER_ID.to_s, purchase.entity_ref.value
expense = purchase.line_items.first
assert_equal 'Refund for deposit on E1068', expense.description
assert_equal '84', expense.account_based_expense_line_detail.account_ref.value
assert_equal BigDecimal('515.59'), expense.amount
# Oldest deposit pays the fee first; what's left of both goes on the check
assert_equal [['50', BigDecimal('92.40'), invoice.id, 'Invoice'],
['50', BigDecimal('207.60'), purchase.id, 'Check'],
['51', BigDecimal('307.99'), purchase.id, 'Check']], @gateway.applied
assert @gateway.payments.all? { |p| p.unapplied_amount.zero? }
assert_equal BigDecimal('0'), record.balance_after
assert_equal ['598'], @gateway.rejected
assert record.estimate_closed?
assert_equal [[record.id, 'jane@example.com']], FakeMailer.sent
assert_equal 'jane@example.com', record.emailed_to
end
def test_card_refund_is_an_expense
record = refund(refund_form(method: 'card', check_number: ''))
assert record.done?, record.message
purchase = @gateway.purchases.first
assert_equal 'Cash', purchase.payment_type
assert_nil purchase.doc_number
assert_equal 'Refund for deposit on E1068 (card refund on the terminal)', purchase.line_items.first.description
assert_equal %w[Invoice Expense Expense], @gateway.applied.map(&:last)
assert_nil record.check_number
end
def test_credit_quickbooks_already_applied_to_the_fee
@gateway.auto_apply = true
record = refund
assert record.done?, record.message
assert_equal BigDecimal('515.59'), record.refund_amount
# The fee was paid once, by QuickBooks
assert_equal 1, @gateway.applied.count { |a| a.last == 'Invoice' }
end
def test_no_fee_refunds_everything
record = refund(refund_form(parts_amount: '0', estimate_id: ''))
assert record.done?, record.message
assert_empty @gateway.invoices
assert_equal BigDecimal('607.99'), record.refund_amount
assert_equal 'Refund of customer credit', @gateway.purchases.first.line_items.first.description
assert_empty @gateway.rejected
end
def test_checks_before_making_anything
assert_raises(Writer::Error) { refund(refund_form, gateway: FakeGateway.new(estimate: estimate)) }
assert_raises(Writer::Error) { refund(refund_form(parts_amount: '5000')) }
assert_raises(Writer::Error) { refund(refund_form, gateway: FakeGateway.new(payments: [deposit(50, 300)], estimate: estimate(customer_id: 1))) }
Writer.stubs(:fee_item).returns(nil)
assert_raises(Writer::Error) { refund }
assert_equal 0, QboRefund.count
assert_empty @gateway.invoices
end
def test_records_the_step_that_failed
@gateway.fail_on = :purchase
record = refund
assert_not record.done?
assert_match(/refund couldn't be recorded/i, record.message)
assert_equal 1, @gateway.invoices.size
assert record.fee_invoice_id.present?
assert_nil record.purchase_id
assert_empty FakeMailer.sent
assert_empty @gateway.rejected
end
def test_cancels_the_work_orders
issue = Issue.find(1)
issue.update_columns(estimate_id: 598) if Issue.column_names.include?('estimate_id')
canceled = IssueStatus.find(5) # Closed (fixtures)
Writer.stubs(:canceled_status).returns(canceled)
record = refund
assert record.done?, record.message
assert_includes record.canceled_issue_ids, 1
issue.reload
assert_equal canceled, issue.status
assert_match(/Order canceled and refunded: Customer canceled the order/, issue.journals.last.notes)
end
def test_warnings_dont_undo_the_refund
Customer.any_instance.stubs(:email).returns('')
Writer.stubs(:canceled_status).returns(nil)
record = refund
assert record.done?
assert_match(/no email/i, record.message)
assert_match(/canceled status/i, record.message)
end
def test_the_email
record = refund
ActionMailer::Base.deliveries.clear
message = QboRefundMailer.refund_summary(record, 'jane@example.com')
message.deliver_now
assert_equal ['jane@example.com'], message.to
assert_match(/Your refund from .*: \$515\.59/, message.subject)
body = message.body.to_s
assert_includes body, 'Hello Jane Customer,'
assert_includes body, "We've processed the refund for E1068."
assert_includes body, 'Parts: $307.99'
assert_includes body, 'Restocking fee (30% of parts): $92.40'
assert_includes body, 'Refund: $515.59'
assert_includes body, 'company check (no. 5001)'
end
end