Compare commits

..
18 Commits
Author SHA1 Message Date
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
rickyandClaude Opus 5.5 42461e7899 2026.11.17
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:44:25 -05:00
rickyandClaude Opus 5.5 461fa79bc5 Show a saving indicator on estimates and invoices
Clicking Save, Save and send or Save draft shows a spinner in the action bar and locks the buttons until the page reloads, so a second click can't save or send twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:44:25 -05:00
ricky 2fb21c34bb 2026.11.16 2026-11-04 15:04:19 -05:00
rickyandClaude Opus 5.5 1c71e3a4c9 Add discounts, unlocking paid invoices and editing payments
- Estimates and invoices take a discount, as a percent of the subtotal or an
  amount, saved as QuickBooks' discount line and taken off before sales tax.
  Duplicated estimates and invoices made from an estimate keep it. The box is
  hidden when discounts are off in QuickBooks.
- A paid invoice can be unlocked for editing after a confirmation. The
  payments stay linked, and the total can't go below what's been paid.
  Unlocking needs the new "Edit partially paid invoices" or "Edit paid
  invoices" permission, checked again when saving.
- Saved payments can be edited: date, method, reference, memo, amount and the
  invoices they pay. Each invoice keeps its amount unless the amount or the
  invoices change. Payments that also apply credit memos stay read-only.
- Locked estimates and invoices are readable again (disabled boxes had faint
  or invisible text, especially in Safari).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:04:19 -05:00
ricky 89f4797bbe 2026.11.15 2026-11-04 12:41:32 -05:00
rickyandClaude Opus 5.5 3bbceacda4 Don't take the sales person from a retired custom field
When an estimate didn't have the company's sales person field, the plugin fell back to
any field named like "Sales Rep", e.g. a retired "Sales Rep old" dropdown, which
QuickBooks returns as its option number. Invoices made from those estimates got "4"
as their sales person. Only the company's field is read now; an estimate without it
has no sales person, so the invoice gets the user who creates it. Matching by name is
left for when QuickBooks' settings can't be read, and never picks a hidden field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:41:32 -05:00
ricky d75dee2866 2026.11.14 2026-11-04 10:33:03 -05:00
rickyandClaude Opus 5.5 c8e2d2d92e Save new estimates and invoices as drafts
A draft is kept in Redmine only, however incomplete, so nothing is in QuickBooks
until it's saved from the editor. QuickBooks can't apply a deposit to an invoice
that's still being written, which made it read-only. Saving to QuickBooks deletes
the draft.

Drafts are listed on the customer's page, on a Drafts page linked from Customers,
and on a new invoice or estimate for a customer who already has one. Anyone with
Write invoices (or Write estimates) can continue or delete invoice (or estimate)
drafts. Adds the qbo_drafts table (migration 052).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:33:03 -05:00
ricky a1fb88e77c 2026.11.13 2026-11-04 10:07:54 -05:00
rickyandClaude Opus 5.5 0a7b2e34b8 Fix the settings page before QuickBooks is connected
The token expiry came back as "never synced" text, which the page treated as a
time, so it failed. It's now empty, shown as N/A.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:07:54 -05:00
rickyandClaude Opus 5.5 895733f534 Let admins hide QuickBooks custom fields from estimates and invoices
QuickBooks doesn't tell apps which custom fields are inactive, and a field stays on
its old estimates after it's turned off, so an inactive "Sales Rep old" kept showing
and was filled in with the sales person. The billing settings now list the fields
found, with a box to hide each; hidden fields are left out of the editor, the sales
person and other plugins' field lookups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:07:54 -05:00
ricky fa1b4eed06 2026.11.12 2026-11-04 09:47:36 -05:00
rickyandClaude Opus 5.5 95e76a41fd Use QuickBooks' newer custom fields once estimates show them
QuickBooks keeps listing the legacy sales form fields (DefinitionIds 1-3) in the
preferences after a company moves to its newer custom fields, often renamed or inactive
(e.g. "Sales Rep old"). Once estimates show any newer field, only those are used.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:47:36 -05:00
ricky 92b2a18eb6 2026.11.11 2026-11-03 22:12:47 -05:00
rickyandClaude Opus 5.5 084df36061 Link the Customer column in issue lists to the customer
Only for users with View customers, who can open the customer page; others see
the name as plain text. CSV and PDF exports are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 22:12:47 -05:00
rickyandClaude Opus 5.5 3b51625df4 Fix sorting and grouping time entries by Billed
The time entry Billed column sorted by time_entries.name, which doesn't exist, so
sorting or grouping by it failed. The issue list's Billed column is removed: issues
have no billed value, so showing or sorting it always failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 22:12:47 -05:00
42 changed files with 1200 additions and 118 deletions

No files matched your search

@@ -0,0 +1,75 @@
#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.
# Drafts on the new estimate and new invoice editors (see QboDraft). "Save draft" keeps what's filled in, even
# if it isn't complete, and reopens it (new?draft_id=). Saving to QuickBooks deletes the draft.
module QboDraftHandling
extend ActiveSupport::Concern
private
# The draft named by draft_id (in the URL, or the editor's hidden field), if the user may open it
def find_draft(document)
@draft = (QboDraft.visible.for_document(document).find_by(id: params[:draft_id]) if params[:draft_id].present?)
end
# The editor form filled in from a draft, with the details the editor shows but doesn't post
def form_from_draft(draft)
form = draft.form
customer = Customer.find_by(id: form.customer_id) if form.customer_id.present?
if customer
form.billing_address = RedmineQboBilling::EstimateWriter.customer_address(customer)
form.customer_name = customer.name if form.customer_name.blank?
end
# Invoices keep the sales person shown on the editor (e.g. from an estimate); estimates are always the user's
form.sales_person = (draft.invoice? && draft.fields['sales_person'].presence) || User.current.name
form.lines = form.lines.reject(&:blank?)
form.lines += Array.new([2 - form.lines.size, 1].max) { RedmineQboBilling::EstimateForm::Line.new(quantity: '', taxable: true) }
form
end
# Saves what's on the editor as a draft (no checks: a draft can be missing anything) and reopens it
def save_draft(document, fields)
draft = @draft || QboDraft.new(document: document)
fields = fields.to_h.stringify_keys
draft.fields = fields
draft.customer_id = (Customer.where(id: fields['customer_id']).pick(:id) if fields['customer_id'].present?)
draft.user = User.current
draft.save!
flash[:notice] = l(:notice_qbo_draft_saved)
redirect_to draft_editor_path(draft)
end
# Saved to QuickBooks: the draft isn't needed any more
def discard_draft
@draft&.destroy
@draft = nil
end
# A new document for a customer who already has drafts of it: the editor points them out
def load_customer_drafts(document, customer_id)
@customer_drafts =
if @draft.nil? && customer_id.present?
QboDraft.visible.for_document(document).where(customer_id: customer_id).newest_first.to_a
else
[]
end
end
# A draft_id that's gone (e.g. finished or deleted by someone else): say so and list the drafts
def draft_missing
flash[:error] = l(:error_qbo_draft_not_found)
redirect_to qbo_drafts_path
end
def draft_editor_path(draft)
draft.invoice? ? new_qbo_invoice_path(draft_id: draft.id) : new_qbo_estimate_path(draft_id: draft.id)
end
end
+31
View File
@@ -0,0 +1,31 @@
#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.
# Estimate and invoice drafts (QboDraft): all of them, and deleting one. Drafts are continued on the new
# estimate/invoice editor (new?draft_id=). Users see the drafts of the documents they may write.
class QboDraftsController < ApplicationController
before_action :authorize_global
def index
@drafts = QboDraft.visible.includes(:customer, :user).newest_first.to_a
end
def destroy
draft = QboDraft.visible.find_by(id: params[:id])
if draft
draft.destroy
flash[:notice] = l(:notice_qbo_draft_deleted)
else
flash[:error] = l(:error_qbo_draft_not_found)
end
redirect_back_or_default qbo_drafts_path
end
end
+86 -10
View File
@@ -10,6 +10,7 @@
# Writes, edits and emails QuickBooks estimates from Redmine, on a page laid out like QuickBooks' estimate screen.
class QboEstimatesController < ApplicationController
include QboDraftHandling
before_action :require_admin, only: :refresh_company
before_action :authorize_global, except: :refresh_company
@@ -25,26 +26,34 @@ class QboEstimatesController < ApplicationController
# redmine_qbo raises plain errors when QuickBooks isn't connected or the token can't be refreshed
RuntimeError].freeze
# A blank estimate, or a copy of another one (?duplicate=<estimate id>)
# A blank estimate, a copy of another one (?duplicate=<estimate id>), or a draft (?draft_id=, see QboDraft)
def new
if params[:duplicate].present?
if params[:draft_id].present?
return draft_missing unless find_draft('estimate')
@form = form_from_draft(@draft)
elsif params[:duplicate].present?
@form = RedmineQboBilling::EstimateWriter.duplicate_form(params[:duplicate], user: User.current)
else
customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present?
@form = RedmineQboBilling::EstimateWriter.new_form(customer: customer, user: User.current)
end
load_customer_drafts('estimate', @form.customer_id)
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def create
find_draft('estimate')
return save_draft('estimate', estimate_params) if params[:save_draft].present?
@form = RedmineQboBilling::EstimateForm.from_params(estimate_params)
# Shown again if the save fails; the sales person is always the user creating the estimate
@form.sales_person = User.current.name
return show_invalid(:new) unless @form.valid?
saved = RedmineQboBilling::EstimateWriter.save(@form, user: User.current)
discard_draft
finish_save(saved, l(:notice_estimate_saved_in_quickbooks, number: saved.doc_number))
rescue *QBO_ERRORS => e
show_error(e, :new)
@@ -92,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 })
@@ -165,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 })
+34 -2
View File
@@ -11,6 +11,7 @@
# Writes, edits and emails QuickBooks invoices from Redmine, with the same editor as estimates, plus importing
# billable time and open estimates. The customer and product searches are QboEstimatesController's.
class QboInvoicesController < ApplicationController
include QboDraftHandling
before_action :authorize_global
before_action :require_sender_for_save_and_send, only: [:create, :update]
@@ -18,8 +19,15 @@ class QboInvoicesController < ApplicationController
QBO_ERRORS = QboEstimatesController::QBO_ERRORS
# A blank invoice, or one made from an estimate (?estimate_id=<estimate id>)
# A blank invoice, one made from an estimate (?estimate_id=<estimate id>), or a draft (?draft_id=, see
# QboDraft). A draft stays in Redmine, so QuickBooks can't apply a deposit to it while it's being written.
def new
if params[:draft_id].present?
return draft_missing unless find_draft('invoice')
@form = form_from_draft(@draft)
return
end
@form =
if params[:estimate_id].present?
RedmineQboBilling::InvoiceWriter.from_estimate(params[:estimate_id], user: User.current)
@@ -27,25 +35,33 @@ class QboInvoicesController < ApplicationController
customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present?
RedmineQboBilling::InvoiceWriter.new_form(customer: customer, user: User.current)
end
load_customer_drafts('invoice', @form.customer_id)
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def create
find_draft('invoice')
# The sales person shown on the editor is kept with the draft
return save_draft('invoice', invoice_params.to_h.merge('sales_person' => params.dig(:estimate, :sales_person).to_s)) if params[:save_draft].present?
@form = RedmineQboBilling::EstimateForm.from_params(invoice_params, document: 'invoice')
# Display only (e.g. the estimate's sales person); InvoiceWriter.save works out what's saved
@form.sales_person = params.dig(:estimate, :sales_person).presence || User.current.name
return show_invalid(:new) unless @form.valid?
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current)
discard_draft
finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number))
rescue *QBO_ERRORS => e
show_error(e, :new)
end
# ?unlock=1 opens a paid invoice for editing anyway (after the editor's confirmation)
def edit
@form = RedmineQboBilling::InvoiceWriter.load(params[:id])
unlock_form if unlock?
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
@@ -54,9 +70,10 @@ class QboInvoicesController < ApplicationController
def update
@form = RedmineQboBilling::EstimateForm.from_params(invoice_params, id: params[:id], document: 'invoice')
@form.sales_person = params.dig(:estimate, :sales_person).to_s
unlock_form if unlock?
return show_invalid(:edit) unless @form.valid?
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current)
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current, unlock: unlock?)
finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number))
rescue RedmineQboBilling::InvoiceWriter::Conflict => e
@conflict = true
@@ -99,6 +116,21 @@ class QboInvoicesController < ApplicationController
)
end
def unlock?
params[:unlock].to_s == '1'
end
# Shows a paid invoice editable, with the amount paid on it (posted back with the form when saving), for
# users allowed to edit it (paid off or partly paid). InvoiceWriter.save checks again against QuickBooks.
def unlock_form
@form.amount_paid ||= RedmineQboBilling::EstimateForm.decimal(params.dig(:estimate, :amount_paid))
return unless @form.locked == :paid || @form.locked.nil?
return unless RedmineQboBilling.paid_invoice_editor?(@form.fully_paid?)
@form.locked = nil
@form.unlocked = true
end
def save_and_send?
params[:save_and_send].present?
end
+32 -5
View File
@@ -9,8 +9,8 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Receives customer payments in QuickBooks: payment type and amount, applied to open invoices oldest first, or
# saved as a deposit. A saved payment can be printed (QuickBooks' payment PDF). A customer's payments are
# listed on their payments page.
# saved as a deposit. A saved payment can be edited and printed (QuickBooks' payment PDF). A customer's
# payments are listed on their payments page.
class QboPaymentsController < ApplicationController
before_action :authorize_global, except: :sync
@@ -56,6 +56,31 @@ class QboPaymentsController < ApplicationController
show_form
end
def edit
@form = RedmineQboBilling::PaymentWriter.load_form(params[:id])
load_choices
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def update
@form = RedmineQboBilling::PaymentForm.from_params(payment_params, id: params[:id])
return show_form unless @form.valid?
payment = RedmineQboBilling::PaymentWriter.save(@form)
flash[:notice] = l(:notice_payment_updated, amount: view_context.number_to_currency(payment.total))
redirect_to qbo_payment_path(payment.id)
rescue RedmineQboBilling::PaymentWriter::Conflict => e
@conflict = true
@form.errors.add(:base, qbo_message(e))
show_form
rescue *QBO_ERRORS => e
logger.warn "[RedmineQboBilling] #{e.class}: #{qbo_message(e)}"
@form.errors.add(:base, qbo_message(e))
show_form
end
def show
@payment = RedmineQboBilling::PaymentWriter.load(params[:id])
@customer = Customer.find_by(id: @payment.customer_ref&.value)
@@ -86,13 +111,15 @@ class QboPaymentsController < ApplicationController
private
def payment_params
params.require(:payment).permit(*RedmineQboBilling::PaymentForm::ATTRIBUTES, invoice_ids: [])
params.require(:payment).permit(*RedmineQboBilling::PaymentForm::ATTRIBUTES, :sync_token, invoice_ids: [])
end
def load_choices
@payment_methods = RedmineQboBilling::PaymentWriter.payment_methods
customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present?
@open_invoices = customer ? RedmineQboBilling::PaymentWriter.open_invoices(customer) : []
# Editing: the invoices this payment pays count as open (by what it paid on them)
payment = RedmineQboBilling::PaymentWriter.load(@form.id) if @form.persisted?
@open_invoices = customer ? RedmineQboBilling::PaymentWriter.open_invoices(customer, payment: payment) : []
rescue *QBO_ERRORS => e
@open_invoices = []
flash.now[:error] = qbo_message(e)
@@ -100,7 +127,7 @@ class QboPaymentsController < ApplicationController
def show_form
load_choices
render :new, status: :unprocessable_entity
render(@form.persisted? ? :edit : :new, status: :unprocessable_entity)
end
def qbo_message(error)
+3 -2
View File
@@ -23,16 +23,17 @@ class Qbo < ActiveRecord::Base
return I18n.t(:label_qbo_never_synced)
end
# Token expiry times, or nil when QuickBooks isn't connected (the settings page shows N/A)
def self.oauth2_access_token_expires_at
QboConnectionService.current!.oauth2_access_token_expires_at
rescue
return I18n.t(:label_qbo_never_synced)
nil
end
def self.oauth2_refresh_token_expires_at
QboConnectionService.current!.oauth2_refresh_token_expires_at
rescue
return I18n.t(:label_qbo_never_synced)
nil
end
# Updates last sync time stamp
+74
View File
@@ -0,0 +1,74 @@
#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 new estimate or invoice saved part way, in Redmine only. Nothing is in QuickBooks until it's saved from
# the editor, so QuickBooks can't apply a deposit to an invoice that's still being written. Drafts are shared:
# anyone with Write estimates (or Write invoices) can continue or delete any estimate (or invoice) draft.
class QboDraft < ApplicationRecord
DOCUMENTS = %w[estimate invoice].freeze
belongs_to :customer, optional: true
# Who saved it last
belongs_to :user, optional: true
validates :document, inclusion: { in: DOCUMENTS }
scope :newest_first, -> { order(updated_at: :desc, id: :desc) }
scope :for_document, ->(document) { where(document: document.to_s) }
# The drafts a user may open: estimate drafts need Write estimates, invoice drafts Write invoices
scope :visible, lambda { |user = User.current|
documents = []
documents << 'estimate' if RedmineQboBilling.writer?(user)
documents << 'invoice' if RedmineQboBilling.invoice_writer?(user)
where(document: documents)
}
def self.writable_document?(document, user = User.current)
case document.to_s
when 'estimate' then RedmineQboBilling.writer?(user)
when 'invoice' then RedmineQboBilling.invoice_writer?(user)
else false
end
end
# The editor's fields as posted (estimate[...])
def fields
parsed = JSON.parse(data.presence || '{}')
parsed.is_a?(Hash) ? parsed : {}
rescue JSON::ParserError
{}
end
def fields=(hash)
self.data = hash.to_h.to_json
end
# The editor form, filled in as it was saved
def form
RedmineQboBilling::EstimateForm.from_params(fields, document: document)
end
def invoice?
document == 'invoice'
end
def customer_name
customer&.name.presence || fields['customer_name'].presence
end
def subtotal
form.subtotal
end
def line_count
form.filled_lines.count { |line| !line.subtotal? }
end
end
+5
View File
@@ -5,6 +5,11 @@
<% if User.current.allowed_to?(:add_customers, nil, global: true) %>
<%= link_to sprite_icon('add', l(:label_new_customer)), new_customer_path, class: 'icon icon-add' %>
<% end %>
<%# Estimate and invoice drafts, for users who may write either %>
<% if RedmineQboBilling.writer? || RedmineQboBilling.invoice_writer? %>
<% draft_count = QboDraft.visible.count %>
<%= link_to sprite_icon('document', "#{l(:label_qbo_drafts)} (#{draft_count})"), qbo_drafts_path, class: 'icon icon-document' %>
<% end %>
<% if User.current.admin? %>
<%= link_to sprite_icon('reload', l(:label_sync)), qbo_sync_path, class: 'icon icon-reload' %>
<% end %>
+7
View File
@@ -58,6 +58,13 @@
</div>
</div>
<%# Estimate and invoice drafts, kept in Redmine until they're saved to QuickBooks %>
<% customer_drafts = QboDraft.visible.where(customer_id: @customer.id).includes(:user).newest_first.to_a %>
<% if customer_drafts.any? %>
<h4><%= l(:label_qbo_drafts) %>:</h4>
<%= render partial: 'qbo_drafts/list', locals: { drafts: customer_drafts, show_customer: false } %>
<% end %>
</div>
<div class="splitcontentleft">
+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>
+30
View File
@@ -16,6 +16,36 @@
multiple: true, size: 8, id: 'settings_labor_item_ids' %>
<em class="info"><%= l(:text_labor_items) %></em>
</p>
<%# QuickBooks custom fields to leave out of estimates and invoices (see RedmineQboBilling::Company). Hidden
fields that aren't found right now (e.g. no recent estimate has them) are kept as hidden. %>
<% company = RedmineQboBilling::Company %>
<% qbo_fields = company.all_custom_fields %>
<% hidden_ids = company.hidden_field_ids %>
<% sales_field = company.sales_person_field %>
<p class="qbo-custom-fields-setting">
<label><%= l(:label_qbo_hidden_custom_fields) %></label>
<%= hidden_field_tag 'settings[hidden_custom_field_ids][]', '', id: nil %>
<% (hidden_ids - qbo_fields.map { |f| f.id.to_i }).each do |id| %>
<%= hidden_field_tag 'settings[hidden_custom_field_ids][]', id, id: nil %>
<% end %>
<% if qbo_fields.empty? %>
<%= l(:label_none) %>
<% else %>
<% qbo_fields.each do |field| %>
<label class="block">
<%= check_box_tag 'settings[hidden_custom_field_ids][]', field.id, hidden_ids.include?(field.id.to_i),
id: "settings_hidden_custom_field_#{field.id}" %>
<%= field.name %>
<% if sales_field && sales_field.id.to_i == field.id.to_i %>
<em>(<%= l(:text_qbo_sales_person_field) %>)</em>
<% end %>
</label>
<% end %>
<% end %>
<%= link_to sprite_icon('reload', l(:button_refresh_quickbooks_fields)), refresh_company_qbo_estimates_path,
method: :post, class: 'icon icon-reload' %>
<em class="info"><%= l(:text_qbo_hidden_custom_fields) %></em>
</p>
</div>
<% issue_builder = RedmineQboBilling::EstimateIssueBuilder %>
@@ -0,0 +1,18 @@
<%# On the new estimate/invoice editor: the draft being continued, or the customer's other drafts of this
document so a second one isn't started by accident %>
<% draft = local_assigns[:draft] %>
<% drafts = local_assigns[:drafts] || [] %>
<% if draft %>
<div class="flash notice qbo-draft-notice">
<%= l(:text_qbo_editing_draft, user: h(draft.user&.name || l(:label_user_anonymous)), age: time_tag(draft.updated_at)).html_safe %>
</div>
<% elsif drafts.any? %>
<div class="warning qbo-estimate-notice qbo-draft-notice">
<%= l(drafts.first.invoice? ? :text_qbo_customer_has_invoice_drafts : :text_qbo_customer_has_estimate_drafts, count: drafts.size) %>
<% drafts.each do |other| %>
<%= link_to l(:text_qbo_draft_link, user: other.user&.name || l(:label_user_anonymous),
subtotal: number_to_currency(other.subtotal), date: format_time(other.updated_at)),
other.invoice? ? new_qbo_invoice_path(draft_id: other.id) : new_qbo_estimate_path(draft_id: other.id) %>
<% end %>
</div>
<% end %>
+40
View File
@@ -0,0 +1,40 @@
<%# Estimate and invoice drafts (QboDraft) with Continue and Delete. show_customer: false on a customer's page. %>
<% show_customer = local_assigns.fetch(:show_customer, true) %>
<table class="list qbo-drafts">
<thead>
<tr>
<th><%= l(:label_qbo_draft_document) %></th>
<% if show_customer %><th><%= l(:field_customer) %></th><% end %>
<th class="qbo-draft-number"><%= l(:label_qbo_draft_lines) %></th>
<th class="qbo-draft-number"><%= l(:label_subtotal) %></th>
<th><%= l(:label_qbo_draft_saved_by) %></th>
<th></th>
</tr>
</thead>
<tbody>
<% drafts.each do |draft| %>
<tr>
<td><%= link_to l(draft.invoice? ? :label_qbo_invoice_draft : :label_qbo_estimate_draft),
draft.invoice? ? new_qbo_invoice_path(draft_id: draft.id) : new_qbo_estimate_path(draft_id: draft.id) %></td>
<% if show_customer %>
<td><%= draft.customer ? link_to(draft.customer.name, customer_path(draft.customer)) : (draft.customer_name || '–') %></td>
<% end %>
<td class="qbo-draft-number"><%= draft.line_count %></td>
<td class="qbo-draft-number"><%= number_to_currency(draft.subtotal) %></td>
<td><%= l(:text_qbo_draft_saved_by, user: h(draft.user&.name || l(:label_user_anonymous)), age: time_tag(draft.updated_at)).html_safe %></td>
<td class="buttons">
<%= link_to sprite_icon('edit', l(:button_qbo_continue_draft)),
draft.invoice? ? new_qbo_invoice_path(draft_id: draft.id) : new_qbo_estimate_path(draft_id: draft.id),
class: 'icon icon-edit' %>
<%= link_to sprite_icon('del', l(:button_delete)), qbo_draft_path(draft), method: :delete,
data: { confirm: l(:text_are_you_sure) }, class: 'icon icon-del' %>
</td>
</tr>
<% end %>
</tbody>
</table>
<style>
table.qbo-drafts td, table.qbo-drafts th { text-align: left; }
table.qbo-drafts .qbo-draft-number { text-align: right; white-space: nowrap; }
table.qbo-drafts td.buttons { white-space: nowrap; }
</style>
+11
View File
@@ -0,0 +1,11 @@
<% html_title l(:label_qbo_drafts) %>
<h2><%= link_to l(:label_customers), customers_path %> &#187; <%= l(:label_qbo_drafts) %></h2>
<p class="info"><%= l(:text_qbo_drafts_info) %></p>
<% if @drafts.any? %>
<%= render partial: 'qbo_drafts/list', locals: { drafts: @drafts } %>
<% else %>
<p class="nodata"><%= l(:label_no_data) %></p>
<% end %>
+37 -6
View File
@@ -10,6 +10,11 @@
settings_read = company.settings.present?
# The same editor writes estimates and invoices
invoice = form.invoice?
# The discount box, unless QuickBooks has discounts turned off or the document is read-only (shown anyway
# for a document that has one)
show_discount = form.discount? || (company.discounts_allowed? && !form.locked)
# The draft being continued (QboDraft), if any; new documents can be saved as drafts
draft = local_assigns[:draft]
sender = invoice ? RedmineQboBilling.invoice_sender? : RedmineQboBilling.sender?
cancel_path = customer ? customer_path(customer) : home_path
form_url =
@@ -38,6 +43,7 @@
warn_unsaved: User.current.pref.warn_on_leaving_unsaved != '0'
}) do %>
<%= hidden_field_tag 'estimate[sync_token]', form.sync_token, id: nil %>
<%= hidden_field_tag 'draft_id', draft.id, id: nil if draft %>
<%= hidden_field_tag 'estimate[total_tax]', form.total_tax, id: nil %>
<%= hidden_field_tag 'estimate[discount]', form.discount, id: nil %>
<%= hidden_field_tag 'estimate[email_status]', form.email_status, id: nil %>
@@ -46,6 +52,11 @@
<%= hidden_field_tag 'estimate[sales_person]', form.sales_person, id: nil if form.persisted? || form.invoice? %>
<% if invoice %>
<%= hidden_field_tag 'estimate[balance]', form.balance, id: nil %>
<%# A paid invoice opened for editing (Unlock) stays unlocked if the page is shown again %>
<% if form.unlocked %>
<%= hidden_field_tag 'unlock', '1', id: nil %>
<%= hidden_field_tag 'estimate[amount_paid]', form.amount_paid, id: nil %>
<% end %>
<%# Estimates whose lines are on this invoice; the Import panel adds more %>
<span id="qbo-linked-estimates">
<% form.linked_estimate_ids.each do |estimate_id| %>
@@ -259,10 +270,18 @@
<th><%= l(:label_taxable_subtotal) %></th>
<td id="qbo-estimate-taxable-subtotal"></td>
</tr>
<% if form.discount.to_f != 0 %>
<tr>
<th><%= l(:label_discount_from_quickbooks) %></th>
<td>-<%= number_to_currency(form.discount) %></td>
<% if show_discount %>
<%# A percent of the subtotal or a dollar amount; QuickBooks' discount line %>
<tr class="qbo-estimate-discount">
<th>
<label for="qbo_estimate_discount_value"><%= l(:label_discount_from_quickbooks) %></label>
<%= text_field_tag 'estimate[discount_value]', form.discount_value, id: 'qbo_estimate_discount_value',
size: 6, inputmode: 'decimal', autocomplete: 'off', placeholder: '0' %>
<%= select_tag 'estimate[discount_type]',
options_for_select([[l(:label_discount_percent), 'percent'], [l(:label_discount_amount), 'amount']], form.discount_type),
id: 'qbo_estimate_discount_type', 'aria-label': l(:label_discount_type) %>
</th>
<td id="qbo-estimate-discount"><%= "-#{number_to_currency(form.discount_amount)}" if form.discount? %></td>
</tr>
<% end %>
<tr>
@@ -279,14 +298,26 @@
</fieldset>
<%# Action bar, like the bar along the bottom of QuickBooks' estimate screen %>
<div class="qbo-estimate-actions">
<div class="qbo-estimate-actions" data-saving-text="<%= l(:text_qbo_saving) %>">
<%= link_to l(:button_cancel), cancel_path, class: 'qbo-button qbo-button-dark', id: 'qbo-estimate-cancel' %>
<% unless form.locked %>
<span class="qbo-estimate-actions-save">
<%# Shown while a save is on its way to QuickBooks (qbo_estimates/_script) %>
<span class="qbo-saving-status" role="status" aria-live="polite" hidden></span>
<% unless form.persisted? %>
<%# Kept in Redmine only, however incomplete (QboDraftHandling) %>
<% if draft %>
<%= link_to l(:button_qbo_delete_draft), qbo_draft_path(draft), method: :delete,
data: { confirm: l(:text_are_you_sure) }, class: 'qbo-button qbo-button-dark', id: 'qbo-delete-draft' %>
<% end %>
<%= submit_tag l(:button_qbo_save_draft), name: 'save_draft', class: 'qbo-button qbo-button-dark',
id: 'qbo-save-draft', formnovalidate: true, data: { saving_text: l(:text_qbo_saving_draft) } %>
<% end %>
<%= submit_tag l(:button_save), name: 'save', class: 'qbo-button qbo-button-dark' %>
<% if sender %>
<%= submit_tag l(:button_save_and_send), name: 'save_and_send', class: 'qbo-button qbo-button-primary',
id: 'qbo-estimate-save-and-send', data: { needs_email_text: l(:text_estimate_send_needs_email) } %>
id: 'qbo-estimate-save-and-send',
data: { needs_email_text: l(:text_estimate_send_needs_email), saving_text: l(:text_qbo_saving_and_sending) } %>
<% end %>
</span>
<% end %>
+11 -1
View File
@@ -68,7 +68,17 @@
</ul>
</div>
<% elsif form.locked == :paid %>
<p class="warning"><%= l(:error_invoice_paid) %></p>
<p class="warning">
<%= l(:error_invoice_paid) %>
<%# Opened for editing anyway after a confirmation (e.g. a discount after a deposit) %>
<% if RedmineQboBilling.paid_invoice_editor?(form.fully_paid?) %>
<%= link_to sprite_icon('unlock', l(:button_unlock_invoice)), edit_qbo_invoice_path(form.id, unlock: 1),
class: 'icon icon-unlock', id: 'qbo-unlock-invoice',
data: { confirm: l(:text_unlock_invoice_confirmation) } %>
<% end %>
</p>
<% elsif form.unlocked && form.amount_paid.to_d > 0 %>
<p class="warning"><%= l(:text_invoice_unlocked, paid: number_to_currency(form.amount_paid)) %></p>
<% elsif form.locked == :bundles %>
<p class="warning"><%= l(invoice ? :error_invoice_has_bundles : :error_estimate_has_bundles) %></p>
<% end %>
+61 -3
View File
@@ -36,8 +36,10 @@ $(function () {
var money = new Intl.NumberFormat(<%= raw (current_language.to_s.presence || 'en').to_json %>, { style: 'currency', currency: 'USD' });
var savedSubtotal = $form.data('savedSubtotal') === '' ? null : parseFloat($form.data('savedSubtotal'));
var savedTax = $form.data('savedTax') === '' ? null : parseFloat($form.data('savedTax'));
// Discounts are kept from QuickBooks as they are; QuickBooks works out a percent discount again on save
var discount = $form.data('discount') === '' ? 0 : parseFloat($form.data('discount'));
// The discount QuickBooks took off when the document was last saved (the tax shown is for that discount)
var savedDiscount = $form.data('discount') === '' ? 0 : parseFloat($form.data('discount'));
var $discountValue = $('#qbo_estimate_discount_value');
var $discountType = $('#qbo_estimate_discount_type');
var locked = $form.find('.qbo-estimate-sheet').prop('disabled');
// Row keys must be digits: Rails' strong parameters only keep a hash of rows when every key is a number
var nextKey = Date.now();
@@ -131,6 +133,13 @@ $(function () {
return round(qty * rate, 2);
}
// The discount in dollars: a percent of the subtotal or an amount, like QuickBooks works it out
function discountAmount(subtotal) {
var value = parseNumber(String($discountValue.val() || '').replace(/%/g, ''));
if (!$discountValue.length || value === null || isNaN(value) || value <= 0) return 0;
return $discountType.val() === 'percent' ? round(subtotal * value / 100, 2) : round(value, 2);
}
function recalc() {
var subtotal = 0, taxable = 0, section = 0;
rows().each(function () {
@@ -154,8 +163,11 @@ $(function () {
// QuickBooks works out the sales tax when the estimate is saved; show the saved tax until the lines change
var $tax = $('#qbo-estimate-tax');
var discount = discountAmount(subtotal);
$('#qbo-estimate-discount').text(discount > 0 ? '-' + money.format(discount) : '');
var total = round(subtotal - discount, 2);
if (savedTax !== null && savedSubtotal !== null && Math.abs(subtotal - savedSubtotal) < 0.005) {
if (savedTax !== null && savedSubtotal !== null && Math.abs(subtotal - savedSubtotal) < 0.005 &&
Math.abs(discount - savedDiscount) < 0.005) {
$tax.text(money.format(savedTax)).removeClass('qbo-pending');
total = round(total + savedTax, 2);
} else {
@@ -743,6 +755,16 @@ $(function () {
});
}
$discountValue.on('input', function () { dirty = true; recalc(); });
$discountType.on('change', function () { dirty = true; recalc(); });
// Math typed in the discount box (e.g. 1500-1250) is worked out, to the cent
function tidyDiscount() {
var text = String($discountValue.val() || '').replace(/[$,\s%]/g, '');
var value = parseNumber(text);
if (value !== null && !isNaN(value) && isMath(text)) $discountValue.val(plain(round(value, 2), 2));
}
$discountValue.on('blur', function () { tidyDiscount(); recalc(); });
// ---- saving ----
$form.on('input change', '.qbo-estimate-top input, .qbo-estimate-details input, .qbo-estimate-notes textarea', function () { dirty = true; });
@@ -751,7 +773,11 @@ $(function () {
if (event.key === 'Enter' && !$(this).closest('.ui-autocomplete').length) event.preventDefault();
});
// Set once a save is on its way, so more clicks don't save (or send) it twice
var saving = false;
$form.on('submit', function (event) {
if (saving) { event.preventDefault(); return; }
var submitter = event.originalEvent && event.originalEvent.submitter;
if (submitter && submitter.id === 'qbo-estimate-save-and-send' && !$email.val().trim()) {
event.preventDefault();
@@ -761,7 +787,39 @@ $(function () {
}
// Math still in a box is worked out before saving
rows().each(function () { tidyNumbers($(this)); });
tidyDiscount();
dirty = false;
// After every submit handler has run (and the form's values are already taken, so disabling the buttons
// doesn't drop which one was clicked): unless one stopped the save, show it's saving and lock the buttons
setTimeout(function () {
var stopped = event.originalEvent ? event.originalEvent.defaultPrevented : event.isDefaultPrevented();
if (stopped) return;
saving = true;
showSaving(submitter);
}, 0);
});
function showSaving(submitter) {
var $bar = $form.find('.qbo-estimate-actions');
var $clicked = submitter ? $(submitter) : $bar.find('input[type=submit][name=save]');
var text = $clicked.data('savingText') || $bar.data('savingText');
$bar.addClass('qbo-saving');
$bar.find('input[type=submit]').prop('disabled', true);
$bar.find('a.qbo-button').addClass('qbo-button-disabled').attr('aria-disabled', 'true');
$bar.find('.qbo-saving-status').text(text).prop('hidden', false);
}
// Coming back with the browser's Back button can show the page as it was left, still "saving"
window.addEventListener('pageshow', function (event) {
if (!event.persisted || !saving) return;
saving = false;
var $bar = $form.find('.qbo-estimate-actions');
$bar.removeClass('qbo-saving');
$bar.find('input[type=submit]').prop('disabled', false);
$bar.find('a.qbo-button').removeClass('qbo-button-disabled').removeAttr('aria-disabled');
$bar.find('.qbo-saving-status').prop('hidden', true);
});
window.addEventListener('beforeunload', function (event) {
+20 -1
View File
@@ -2,7 +2,12 @@
<style>
.qbo-estimate { --qbo-border: #babec5; --qbo-muted: #6b6c72; --qbo-green: #2ca01c; --qbo-green-dark: #108000; --qbo-bar: #393a3d; }
.qbo-estimate-sheet { border: 1px solid #e3e5e8; border-radius: 4px; background: #fff; padding: 20px 24px 24px; margin: 0 0 0; min-width: 0; }
.qbo-estimate-sheet[disabled] { opacity: .75; }
.qbo-estimate-sheet[disabled] { opacity: .85; }
/* A locked document is still read here: browsers grey out disabled boxes' text (Safari nearly to nothing,
through -webkit-text-fill-color), so it's drawn in the normal text color */
.qbo-estimate-sheet[disabled] :is(input, textarea, select) { color: #393a3d; -webkit-text-fill-color: #393a3d; opacity: 1; }
/* ...but not hints in empty boxes, which would read as if they were filled in */
.qbo-estimate-sheet[disabled] :is(input, textarea)::placeholder { color: transparent; -webkit-text-fill-color: transparent; }
.qbo-estimate-sheet[disabled] .qbo-estimate-line-buttons, .qbo-estimate-sheet[disabled] .qbo-line-handle svg,
.qbo-estimate-sheet[disabled] .qbo-line-remove-button { display: none; }
.qbo-estimate-top { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; }
@@ -95,6 +100,9 @@
.qbo-estimate-totals { border-collapse: collapse; min-width: 300px; align-self: flex-start; font-variant-numeric: tabular-nums; }
.qbo-estimate-totals th { text-align: right; font-weight: normal; color: #393a3d; padding: 6px 16px 6px 0; }
.qbo-estimate-totals td { text-align: right; padding: 6px 0; min-width: 110px; }
.qbo-estimate-discount th { white-space: nowrap; }
.qbo-estimate-discount input { width: 5em; text-align: right; margin-left: 6px; }
.qbo-estimate-discount select { width: auto; }
.qbo-estimate-totals #qbo-estimate-tax.qbo-pending { color: var(--qbo-muted); font-style: italic; font-size: .9em; }
.qbo-estimate-totals .qbo-estimate-total th, .qbo-estimate-totals .qbo-estimate-total td { font-weight: 700; font-size: 1.15em; border-top: 1px solid #d4d7dc; padding-top: 10px; }
@@ -111,6 +119,17 @@
.qbo-estimate .qbo-button-primary { background: var(--qbo-green); border-color: var(--qbo-green); color: #fff; }
.qbo-estimate .qbo-button-primary:hover { background: var(--qbo-green-dark); border-color: var(--qbo-green-dark); color: #fff; }
/* While saving: the buttons are locked and a spinner says what's happening */
.qbo-estimate .qbo-saving .qbo-button[disabled],
.qbo-estimate .qbo-saving .qbo-button-disabled { opacity: .6; cursor: progress; pointer-events: none; }
.qbo-estimate .qbo-saving-status { display: inline-flex; align-items: center; gap: 8px; color: #fff; font-weight: 600; margin-right: 8px; }
.qbo-estimate .qbo-saving-status[hidden] { display: none; }
.qbo-estimate .qbo-saving-status::before { content: ""; width: 16px; height: 16px; border-radius: 50%; box-sizing: border-box;
border: 2px solid rgba(255,255,255,.35); border-top-color: #fff; animation: qbo-saving-spin .8s linear infinite; }
@keyframes qbo-saving-spin { to { transform: rotate(360deg); } }
@media (prefers-reduced-motion: reduce) { .qbo-estimate .qbo-saving-status::before { animation-duration: 2.4s; } }
.qbo-estimate .qbo-saving { cursor: progress; }
/* Warnings with a list (linked issues, invoices): the text, then one item per line */
div.warning.qbo-estimate-notice { text-align: left; }
div.warning.qbo-estimate-notice ul { margin: 6px 0 0; padding-left: 22px; }
+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 -1
View File
@@ -1,4 +1,5 @@
<% html_title l(:label_new_estimate) %>
<%= render partial: 'qbo_estimates/header', locals: { form: @form } %>
<%= render partial: 'qbo_estimates/form', locals: { form: @form } %>
<%= render partial: 'qbo_drafts/editor_notice', locals: { draft: @draft, drafts: @customer_drafts } %>
<%= render partial: 'qbo_estimates/form', locals: { form: @form, draft: @draft } %>
+2 -1
View File
@@ -1,5 +1,6 @@
<% html_title l(:label_new_invoice) %>
<%= render partial: 'qbo_estimates/header', locals: { form: @form } %>
<%= render partial: 'qbo_drafts/editor_notice', locals: { draft: @draft, drafts: @customer_drafts } %>
<%= render partial: 'qbo_invoices/open_issues', locals: { customer: (Customer.find_by(id: @form.customer_id) if @form.customer_id.present?) } %>
<%= render partial: 'qbo_estimates/form', locals: { form: @form } %>
<%= render partial: 'qbo_estimates/form', locals: { form: @form, draft: @draft } %>
+2
View File
@@ -0,0 +1,2 @@
<%# A saved payment, on the same page as Receive payment %>
<%= render template: 'qbo_payments/new' %>
+3
View File
@@ -56,6 +56,9 @@
<td class="amount"><%= number_to_currency(payment.total) %></td>
<td class="amount"><%= unapplied > 0 ? number_to_currency(unapplied) : '' %></td>
<td class="buttons">
<% if RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_qbo_payment_path(payment.id), class: 'icon icon-edit' %>
<% end %>
<%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(payment.id),
class: 'icon icon-pdf', target: :_blank %>
</td>
+30 -8
View File
@@ -1,22 +1,44 @@
<% html_title l(:button_receive_payment) %>
<%# Receive payment, and Edit payment (edit.html.erb) for a saved one %>
<% editing = @form.persisted? %>
<% title = editing ? l(:label_edit_payment) : l(:button_receive_payment) %>
<% html_title title %>
<% customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present? %>
<h2>
<%= link_to l(:label_customers), customers_path %> &#187;
<% if customer %><%= link_to customer.name, customer_path(customer) %> &#187;<% end %>
<%= l(:button_receive_payment) %>
<% if editing %>
<%= link_to l(:label_payments), qbo_payments_path(customer_id: @form.customer_id) %> &#187;
<% end %>
<%= title %>
</h2>
<%= error_messages_for @form %>
<%= form_tag qbo_payments_path, id: 'qbo-payment-form',
<% if @conflict %>
<p class="warning">
<%= l(:text_payment_reload) %>
<%= link_to l(:button_reload_payment), edit_qbo_payment_path(@form.id) %>
</p>
<% end %>
<% if @form.locked %>
<p class="warning"><%= @form.locked %></p>
<% end %>
<%= form_tag (editing ? qbo_payment_path(@form.id) : qbo_payments_path), method: (editing ? :patch : :post), id: 'qbo-payment-form',
data: { open_invoices_url: open_invoices_qbo_payments_path, none_text: l(:label_no_open_invoices) } do %>
<%= hidden_field_tag 'payment[sync_token]', @form.sync_token, id: nil if editing %>
<div class="box tabular">
<p>
<label for="qbo_payment_customer_name"><%= l(:label_customer) %><span class="required"> *</span></label>
<%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', class: 'customer-name',
autocomplete: 'off', size: 40, placeholder: l(:label_choose_a_customer),
data: { autocomplete_url: '/customers/autocomplete' } %>
<%# A saved payment keeps its customer %>
<% if editing %>
<%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', size: 40, readonly: true, tabindex: -1 %>
<% else %>
<%= text_field_tag 'payment[customer_name]', @form.customer_name, id: 'qbo_payment_customer_name', class: 'customer-name',
autocomplete: 'off', size: 40, placeholder: l(:label_choose_a_customer),
data: { autocomplete_url: '/customers/autocomplete' } %>
<% end %>
<%= hidden_field_tag 'payment[customer_id]', @form.customer_id, id: 'customer_id' %>
</p>
<p>
@@ -94,8 +116,8 @@
</fieldset>
<p>
<%= submit_tag l(:button_save_payment) %>
<%= link_to l(:button_cancel), customer ? customer_path(customer) : home_path %>
<%= submit_tag l(:button_save_payment) unless @form.locked %>
<%= link_to l(:button_cancel), editing ? qbo_payment_path(@form.id) : (customer ? customer_path(customer) : home_path) %>
</p>
<% end %>
+3
View File
@@ -2,6 +2,9 @@
<% method_name = RedmineQboBilling::PaymentWriter.payment_method_name(@payment) %>
<div class="contextual">
<% if RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('edit', l(:button_edit)), edit_qbo_payment_path(@payment.id), class: 'icon icon-edit' %>
<% end %>
<%= link_to sprite_icon('application-pdf', l(:button_print_payment)), pdf_qbo_payment_path(@payment.id), class: 'icon icon-pdf', target: :_blank %>
<% if @customer && RedmineQboBilling.payment_receiver? %>
<%= link_to sprite_icon('add', l(:button_receive_payment)), new_qbo_payment_path(customer_id: @customer.id), class: 'icon icon-add' %>
+54
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"
@@ -117,6 +122,9 @@ en:
permission_send_estimates: "Email estimates"
permission_write_invoices: "Write invoices"
permission_send_invoices: "Email invoices"
permission_edit_partially_paid_invoices: "Edit partially paid invoices"
permission_edit_paid_invoices: "Edit paid invoices"
error_invoice_paid_not_allowed: "You're not allowed to change invoices with this much paid on them"
permission_create_estimate_issues: "Create issues from estimates"
permission_receive_payments: "Receive payments"
@@ -129,8 +137,39 @@ en:
button_email_estimate: "Email"
button_open_in_quickbooks: "Open in QuickBooks"
button_refresh_quickbooks_fields: "Refresh QuickBooks fields"
label_qbo_hidden_custom_fields: "Hide QuickBooks custom fields"
# Estimate and invoice drafts
label_qbo_drafts: "Drafts"
label_qbo_draft_document: "Draft"
label_qbo_draft_lines: "Lines"
label_qbo_draft_saved_by: "Last saved"
label_qbo_estimate_draft: "Estimate draft"
label_qbo_invoice_draft: "Invoice draft"
button_qbo_save_draft: "Save draft"
button_qbo_delete_draft: "Delete draft"
button_qbo_continue_draft: "Continue"
notice_qbo_draft_saved: "Draft saved. It's kept in Redmine only, until you save it to QuickBooks."
notice_qbo_draft_deleted: "Draft deleted."
error_qbo_draft_not_found: "That draft is gone. It may have been finished or deleted."
text_qbo_draft_saved_by: "%{user}, %{age} ago"
text_qbo_editing_draft: "Draft, not in QuickBooks yet. Last saved by %{user}, %{age} ago. Save it to send it to QuickBooks; that deletes the draft."
text_qbo_customer_has_estimate_drafts:
one: "This customer has an estimate draft:"
other: "This customer has %{count} estimate drafts:"
text_qbo_customer_has_invoice_drafts:
one: "This customer has an invoice draft:"
other: "This customer has %{count} invoice drafts:"
text_qbo_draft_link: "%{subtotal}, saved by %{user} %{date}"
text_qbo_drafts_info: "New estimates and invoices saved as drafts. They're kept in Redmine only, so nothing is in QuickBooks (and no deposit is applied to an invoice) until a draft is saved from the editor."
text_qbo_sales_person_field: "filled in with the sales person"
text_qbo_hidden_custom_fields: "Ticked fields are left off estimates and invoices. QuickBooks doesn't tell apps which custom fields are inactive, and a field stays on its old estimates after it's turned off, so tick ones you no longer use (e.g. a renamed \"Sales Rep old\"). The sales person goes in the first field shown whose name has \"sales\" or \"rep\" in it."
button_reload_estimate: "Reload the estimate"
button_save_and_send: "Save and send"
# Shown in the action bar while a save is on its way, with the buttons locked
text_qbo_saving: "Saving to QuickBooks…"
text_qbo_saving_and_sending: "Saving and sending…"
text_qbo_saving_draft: "Saving draft…"
error_estimate_changed_in_quickbooks: "This estimate was changed in QuickBooks after you opened it, so it wasn't saved."
error_estimate_field_invalid: "%{field} is not valid"
@@ -149,6 +188,14 @@ en:
label_choose_a_customer: "Choose a customer"
label_customer_email: "Customer email"
label_discount_from_quickbooks: "Discount"
label_discount_amount: "$"
label_discount_percent: "%"
label_discount_type: "Discount type"
error_discount_too_large: "The discount can't be more than the subtotal"
error_invoice_below_paid: "The invoice total (about %{total} with tax) can't be less than the %{paid} already paid on it"
button_unlock_invoice: "Unlock to edit"
text_unlock_invoice_confirmation: "A payment has been applied to this invoice. Unlock it to make changes, such as a discount? The payment stays applied, and the total can't go below what's been paid."
text_invoice_unlocked: "Unlocked: %{paid} has been paid on this invoice. The payment stays applied when you save, and the total can't go below it."
label_drag_to_reorder: "Drag to reorder"
label_estimate_date: "Estimate date"
label_estimate_expiration_days: "Estimates expire after (days)"
@@ -271,6 +318,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"
@@ -292,6 +340,12 @@ en:
button_print_payment: "Print"
button_receive_payment: "Receive payment"
button_save_payment: "Save payment"
button_reload_payment: "Reload the payment"
label_edit_payment: "Edit payment"
notice_payment_updated: "Payment of %{amount} updated in QuickBooks"
error_payment_changed_in_quickbooks: "This payment was changed in QuickBooks after this page was opened"
error_payment_not_editable: "This payment also applies %{types}, which can't be shown here. Edit it in QuickBooks."
text_payment_reload: "Reload it to see the changes, then make yours again."
error_payment_amount: "Enter the amount received"
error_payment_needs_method: "Choose the payment method"
error_payment_not_saved: "QuickBooks didn't save the payment"
+4 -1
View File
@@ -68,8 +68,11 @@ resources :qbo_invoices, only: [:new, :create, :edit, :update] do
end
end
# Estimate and invoice drafts, kept in Redmine until they're saved to QuickBooks (continued on the editors)
resources :qbo_drafts, only: [:index, :destroy]
# Receive payment pages, and a customer's payments (/qbo_payments?customer_id=)
resources :qbo_payments, only: [:index, :new, :create, :show] do
resources :qbo_payments, only: [:index, :new, :create, :show, :edit, :update] do
member do
get :pdf
end
+31
View File
@@ -0,0 +1,31 @@
#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.
# Estimate and invoice drafts: what's filled in on the editor, kept in Redmine until it's saved to QuickBooks
class CreateQboDrafts < ActiveRecord::Migration[7.0]
def up
return if table_exists?(:qbo_drafts)
create_table :qbo_drafts do |t|
t.string :document, null: false, limit: 20
t.bigint :customer_id
# Who saved it last
t.integer :user_id
# The editor's fields, as posted (JSON)
t.text :data, size: :medium
t.timestamps
end
add_index :qbo_drafts, [:document, :customer_id]
end
def down
drop_table :qbo_drafts if table_exists?(:qbo_drafts)
end
end
+9 -4
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.10'
version '2026.11.18'
url 'https://github.com/rickbarrette/redmine_qbo'
author_url 'https://barrettefabrication.com'
settings default: {empty: true}, partial: 'qbo/settings'
@@ -40,14 +40,19 @@ Redmine::Plugin.register :redmine_qbo do
# Billing (global): estimates, invoices, payments, issues from estimates
# customer_info and items feed the customer details and product/service search on the estimate/invoice editor
permission :write_estimates, { qbo_estimates: [:new, :create, :edit, :update, :customer_info, :items] }, global: true
# Drafts (QboDraft): each user sees the drafts of the documents they may write
permission :write_estimates, { qbo_estimates: [:new, :create, :edit, :update, :customer_info, :items],
qbo_drafts: [:index, :destroy] }, global: true
permission :send_estimates, { qbo_estimates: [:send_email] }, global: true
permission :create_estimate_issues, { qbo_estimates: [:issues_preview, :create_issues] }, global: true
permission :write_invoices, { qbo_invoices: [:new, :create, :edit, :update, :import_options],
qbo_estimates: [:customer_info, :items] }, global: true
qbo_estimates: [:customer_info, :items], qbo_drafts: [:index, :destroy] }, global: true
permission :send_invoices, { qbo_invoices: [:send_email] }, global: true
# Unlocking an invoice with a payment applied (on top of Write invoices); see RedmineQboBilling.paid_invoice_editor?
permission :edit_partially_paid_invoices, {}, global: true
permission :edit_paid_invoices, {}, global: true
permission :view_payments, { qbo_payments: [:index, :show, :pdf] }, global: true
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :pdf, :open_invoices],
permission :receive_payments, { qbo_payments: [:index, :new, :create, :show, :edit, :update, :pdf, :open_invoices],
qbo_estimates: [:customer_info] }, global: true
permission :view_business_reports, { qbo_reports: [:index] }, global: true
# The product/service list, accounts and their syncs are admin-only (see ItemsController, AccountsController)
+1
View File
@@ -27,6 +27,7 @@ module RedmineQbo
# === Helpers / Exports ===
IssuesHelper.prepend RedmineQbo::Patches::IssuesHelperPatch
QueriesHelper.prepend RedmineQbo::Patches::QueriesHelperPatch
Redmine::Export::PDF::IssuesPdfHelper.prepend RedmineQbo::Patches::PdfPatch
# === Hooks ===
+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"
@@ -0,0 +1,31 @@
#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 RedmineQbo
module Patches
# Links the Customer column in issue lists to the customer's page, for users who may open it
# (View customers). Others see the name as plain text. CSV and PDF exports are unchanged.
module QueriesHelperPatch
def column_value(column, item, value)
return super unless column.name == :customer && value.is_a?(Customer) && qbo_can_view_customers?
link_to(value.to_s, customer_path(value))
end
private
def qbo_can_view_customers?
return @qbo_can_view_customers if defined?(@qbo_can_view_customers)
@qbo_can_view_customers = User.current.allowed_to?(:view_customers, nil, global: true)
end
end
end
end
-1
View File
@@ -32,7 +32,6 @@ module RedmineQbo
unless @available_columns
@available_columns = self.class.available_columns.dup
@available_columns << QueryColumn.new(:customer, sortable: "#{Issue.table_name}.customer_id", groupable: true, caption: :field_customer)
@available_columns << QueryColumn.new(:billed, sortable: "#{TimeEntry.table_name}.billed", groupable: true, caption: :field_billed)
end
super
end
@@ -17,7 +17,7 @@ module RedmineQbo
def available_columns
unless @available_columns
@available_columns = self.class.available_columns.dup
@available_columns << QueryColumn.new(:billed, sortable: "#{TimeEntry.table_name}.name", groupable: true, caption: :field_billed)
@available_columns << QueryColumn.new(:billed, sortable: "#{TimeEntry.table_name}.billed", groupable: "#{TimeEntry.table_name}.billed", caption: :field_billed)
end
super
end
+7
View File
@@ -93,6 +93,13 @@ module RedmineQboBilling
user.allowed_to?(:write_invoices, nil, global: true)
end
# True when the user may unlock and change an invoice with a payment applied: a paid-off one needs
# "Edit paid invoices", a partly paid one "Edit partially paid invoices" (both on top of "Write invoices")
def self.paid_invoice_editor?(fully_paid, user = User.current)
invoice_writer?(user) &&
user.allowed_to?(fully_paid ? :edit_paid_invoices : :edit_partially_paid_invoices, nil, global: true)
end
# True when the user may email invoices to customers
def self.invoice_sender?(user = User.current)
user.allowed_to?(:send_invoices, nil, global: true)
+32 -3
View File
@@ -24,6 +24,8 @@ module RedmineQboBilling
MISSING_FIELD_CACHE_TIME = 5.minutes
# Recent estimates also show which custom fields exist, for companies whose preferences don't list them
RECENT_ESTIMATES = 20
# QuickBooks' legacy sales form custom fields; its newer custom fields have larger DefinitionIds
LEGACY_FIELD_IDS = (1..3).freeze
# The sales person field is found loosely, e.g. "Sales Person", "Salesperson", "Sales Rep"
SALES_PERSON_NAME = /sales|\brep\b/i
@@ -32,11 +34,26 @@ module RedmineQboBilling
module_function
# All enabled sales form custom fields, in QuickBooks' order
# The sales form custom fields the plugin uses, in QuickBooks' order: all those found, except the ones
# hidden in the plugin settings. Everything else (the editor, the sales person, other plugins' VIN and
# mileage) goes through here, so a hidden field is never shown or filled in.
def custom_fields
hidden = hidden_field_ids
all_custom_fields.reject { |f| hidden.include?(f.id.to_i) }
end
# Every custom field found, hidden ones included (listed on the plugin settings page)
def all_custom_fields
Array(settings[:custom_fields]).map { |f| Field.new(f[:id], f[:name]) }
end
# Fields hidden in the plugin settings. QuickBooks doesn't tell apps which custom fields are inactive,
# and a field stays on its old estimates after it's turned off (e.g. a renamed "Sales Rep old"), so the
# plugin can't leave those out by itself.
def hidden_field_ids
Array((Setting.plugin_redmine_qbo || {})['hidden_custom_field_ids']).map(&:to_i).reject(&:zero?)
end
# The first enabled custom field whose name matches, e.g. a plugin's VIN field (/\bvin\b/i), or nil
def custom_field_matching(pattern)
custom_fields.detect { |f| f.name.to_s =~ pattern }
@@ -58,6 +75,11 @@ module RedmineQboBilling
settings[:custom_txn_numbers] == true
end
# Whether QuickBooks has discounts turned on for sales forms (true when its settings couldn't be read)
def discounts_allowed?
settings[:allow_discount] != false
end
# The "default message shown on estimates" from QuickBooks' sales settings
def estimate_message
settings[:estimate_message].to_s
@@ -96,6 +118,7 @@ module RedmineQboBilling
{
custom_fields: merge_fields(parse_custom_fields(forms&.custom_fields), custom_fields_from_estimates),
custom_txn_numbers: forms&.custom_txn_numbers? == 'true' || forms&.custom_txn_numbers? == true,
allow_discount: forms.nil? || forms.allow_discount?.nil? ? nil : forms.allow_discount?.to_s == 'true',
estimate_message: forms&.estimate_message.to_s,
invoice_message: forms&.default_customer_message.to_s
}
@@ -105,9 +128,15 @@ module RedmineQboBilling
nil
end
# Fields named in the preferences come first; fields only seen on estimates are added after them.
# QuickBooks' newer custom fields (e.g. on Advanced and sandbox companies) may not be in the preferences.
# QuickBooks' newer custom fields (made under Settings > Custom fields) aren't in the preferences, which
# keep listing the legacy fields (DefinitionIds 1-3) after a company moves to the newer ones, often
# renamed or inactive (e.g. "Sales Rep old"). Once estimates show any newer field, those are the
# company's fields and the legacy ones are left out. Otherwise the legacy fields named in the
# preferences come first, then any only seen on estimates.
def merge_fields(from_preferences, from_estimates)
newer = from_estimates.reject { |f| LEGACY_FIELD_IDS.cover?(f[:id]) }
return newer if newer.any?
ids = from_preferences.map { |f| f[:id] }
from_preferences + from_estimates.reject { |f| ids.include?(f[:id]) }
end
+50 -2
View File
@@ -92,8 +92,12 @@ module RedmineQboBilling
end
end
# due_date is an invoice's; expiration_date an estimate's
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number customer_memo private_note].freeze
# due_date is an invoice's; expiration_date an estimate's. The discount is a percent of the subtotal
# (discount_type "percent") or a dollar amount ("amount"), saved as QuickBooks' discount line.
HEADER_ATTRIBUTES = %i[customer_id customer_name email txn_date expiration_date due_date doc_number customer_memo private_note
discount_type discount_value].freeze
DISCOUNT_TYPES = %w[percent amount].freeze
# "estimate" or "invoice"
attr_writer :document
@@ -105,8 +109,11 @@ module RedmineQboBilling
# Invoices: estimates whose lines are on this invoice (they're linked and closed when saved)
:linked_estimate_ids,
# Read-only details shown on the editor
# (discount: the discount amount QuickBooks worked out when it was last saved)
:billing_address, :total, :total_tax, :discount, :email_status, :txn_status, :duplicated_from,
:balance, :converted_from,
# Invoices: a paid invoice opened for editing anyway (Unlock), and the amount paid on it
:unlocked, :amount_paid,
# Estimates: the invoices it's billed on ([[id, number], ...])
:invoiced_on,
# nil, :bundles (has bundle lines), :linked (an issue is linked to the estimate) or
@@ -117,6 +124,7 @@ module RedmineQboBilling
validate :validate_lines
validate :validate_dates
validate :validate_email
validate :validate_discount
# Plugins can block a save (e.g. redmine_qbo_vehicles: one vehicle per invoice); see IssueValues
validate :validate_with_plugins
@@ -193,6 +201,35 @@ module RedmineQboBilling
filled_lines.sum(BigDecimal('0'), &:amount)
end
def discount_type
DISCOUNT_TYPES.include?(@discount_type.to_s) ? @discount_type.to_s : 'percent'
end
def percent_discount?
discount_type == 'percent'
end
# "10%" reads as 10
def discount_value_number
self.class.decimal(discount_value.to_s.delete('%'))
end
# A discount is given when a value above zero is entered
def discount?
(discount_value_number || 0).positive?
end
# The discount in dollars, as QuickBooks works it out: a percent of the subtotal, rounded to the cent
def discount_amount
return BigDecimal('0') unless discount?
percent_discount? ? (subtotal * discount_value_number / 100).round(2) : discount_value_number.round(2)
end
# Invoices: nothing left owing (a payment covers it all)
def fully_paid?
balance.present? && self.class.decimal(balance).to_d <= 0
end
def sent?
email_status.to_s == 'EmailSent'
end
@@ -240,6 +277,17 @@ module RedmineQboBilling
invalid(:label_due_date) if due_date.present? && due_date_value.nil?
end
def validate_discount
return if discount_value.blank?
value = discount_value_number
if value.nil? || value.negative? || (percent_discount? && value > 100)
invalid(:label_discount_from_quickbooks)
elsif discount_amount > subtotal
errors.add(:base, I18n.t(:error_discount_too_large))
end
end
def validate_with_plugins
IssueValues.plugin_errors(self).each { |message| errors.add(:base, message) }
end
@@ -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}"
+60 -13
View File
@@ -13,8 +13,9 @@ module RedmineQboBilling
#
# Subtotal rows are saved the way QuickBooks saves the subtotals added on its own estimate screen: a
# description-only line reading "Subtotal: $342.60", which prints where it was placed. The subtotal
# QuickBooks always adds after the last line isn't shown (QuickBooks adds it back). Discount lines are kept
# as they are, and estimates with bundle (group) lines are read-only so a bundle can't be broken up.
# QuickBooks always adds after the last line isn't shown (QuickBooks adds it back). The discount (a percent
# or an amount) is QuickBooks' discount line after the lines, and estimates with bundle (group) lines are
# read-only so a bundle can't be broken up.
#
# Estimate numbers are never typed: QuickBooks numbers new estimates, or when its custom transaction
# numbers are on, the next number is filled in when the estimate is created.
@@ -72,8 +73,8 @@ module RedmineQboBilling
save(form, user: user)
end
# A new estimate copied from an existing one: same customer, lines, custom fields and messages, dated today, with a
# new number, the current user as sales person, and no discounts or bundles (those stay in QuickBooks)
# A new estimate copied from an existing one: same customer, lines, discount, custom fields and messages, dated
# today, with a new number and the current user as sales person (bundles aren't copied)
def duplicate_form(id, user: User.current)
source = load(id)
today = user.today
@@ -88,6 +89,8 @@ module RedmineQboBilling
custom_fields: source.custom_fields.dup,
customer_memo: source.customer_memo,
private_note: source.private_note,
discount_type: source.discount_type,
discount_value: source.discount_value,
lines: source.lines.map do |line|
EstimateForm::Line.new(kind: line.kind, item_id: line.item_id, item_name: line.item_name,
description: line.description, quantity: line.quantity, rate: line.rate,
@@ -258,6 +261,7 @@ module RedmineQboBilling
total: remote.total,
total_tax: remote.txn_tax_detail&.total_tax,
discount: discount_total(remote),
**discount_fields(remote),
email_status: remote.email_status.to_s,
txn_status: remote.txn_status.to_s,
invoiced_on: Array(remote.linked_transactions).select { |t| t.txn_type.to_s == 'Invoice' }.map { |t|
@@ -291,11 +295,17 @@ module RedmineQboBilling
# QuickBooks' own subtotal (always after the last line), discount and group lines aren't edited here
end
# The custom field's value, found by the field QuickBooks' preferences name, or by name on the estimate
# The custom field's value on a QuickBooks estimate or invoice ("" when it isn't there)
def custom_value(remote, field, name_pattern = nil)
fields = Array(remote.custom_fields)
match = fields.detect { |f| field && f.id.to_i == field.id.to_i } ||
(name_pattern && fields.detect { |f| f.name.to_s =~ name_pattern })
# The company's field, by id. A document without it has no value: falling back to a similarly named
# field picked up retired ones, e.g. a "Sales Rep old" dropdown, which QuickBooks returns as its option
# number ("4"), and that number was copied onto invoices as the sales person.
return fields.detect { |f| f.id.to_i == field.id.to_i }&.string_value.to_s if field
# The field isn't known (QuickBooks' settings couldn't be read): found by name, never a hidden one
hidden = Company.hidden_field_ids
match = name_pattern && fields.detect { |f| f.name.to_s =~ name_pattern && !hidden.include?(f.id.to_i) }
match&.string_value.to_s
end
@@ -319,9 +329,16 @@ module RedmineQboBilling
estimate.private_note = form.private_note.to_s
estimate.custom_fields = build_custom_fields(form, remote, user)
estimate.line_items = build_lines(form, remote)
discount_before_tax(estimate, form)
estimate
end
# A discount comes off before sales tax: QuickBooks takes the discount from the subtotal, then works out
# the tax on what's left (otherwise it taxes the full amount and discounts after)
def discount_before_tax(document, form)
document.apply_tax_after_discount = true if form.discount?
end
# Keeps every custom field already on the estimate, then sets the ones edited on the form, and the sales
# person on create
# (left empty for estimates made without a user, e.g. by a background job)
@@ -365,14 +382,44 @@ module RedmineQboBilling
built
end
# Discounts keep their place after the lines
Array(remote&.line_items).select(&:discount_item?).each do |discount|
discount.line_num = lines.size + 1
lines << discount
end
# The discount goes after the lines, as on QuickBooks' own screen
discount = discount_line(form, remote, lines.size + 1)
lines << discount if discount
lines
end
# QuickBooks' discount line for the form's discount, or nil (taken off before tax, see discount_before_tax). A percent discount is sent as a percent so
# QuickBooks works it out from its own subtotal; the discount account already on the document is kept
# (otherwise QuickBooks uses its default discount account).
def discount_line(form, remote, number)
return nil unless form.discount?
account = Array(remote&.line_items).detect(&:discount_item?)&.discount_line_detail&.discount_account_ref
line = Quickbooks::Model::InvoiceLineItem.new
line.line_num = number
line.amount = form.discount_amount
line.discount_item! do |detail|
detail.percent_based = form.percent_discount?
detail.discount_percent = form.discount_value_number if form.percent_discount?
detail.discount_account_ref = account if account
end
line
end
# The editor's discount fields from a document's discount lines: one percent line stays a percent;
# an amount, or several discount lines, become their total in dollars
def discount_fields(remote)
discounts = Array(remote.line_items).select(&:discount_item?)
return {} if discounts.empty?
detail = discounts.first.discount_line_detail
if discounts.size == 1 && detail&.percent_based?.to_s == 'true' && detail.discount_percent
{ discount_type: 'percent', discount_value: plain_number(detail.discount_percent) }
else
{ discount_type: 'amount', discount_value: plain_number(discount_total(remote)) }
end
end
def build_line(line, number, keep_id:, section_total: BigDecimal('0'))
remote = Quickbooks::Model::InvoiceLineItem.new
remote.id = line.id if keep_id
@@ -443,7 +490,7 @@ module RedmineQboBilling
"Subtotal: #{'-' if value.negative?}$#{whole.reverse.scan(/\d{1,3}/).join(',').reverse}.#{cents}"
end
# Discount lines aren't edited here but count toward the total shown
# What the document's discount lines take off, in dollars
def discount_total(remote)
discounts = Array(remote.line_items).select(&:discount_item?)
discounts.empty? ? nil : discounts.sum(BigDecimal('0')) { |l| l.amount || BigDecimal('0') }
+56 -6
View File
@@ -19,7 +19,9 @@ module RedmineQboBilling
# * billable QuickBooks time activities (the ones redmine_qbo makes from an issue's time entries). Each
# becomes a line linked to its time activity, so QuickBooks marks the time as billed.
#
# An invoice with a payment applied to it is read-only, so a paid invoice can't be changed under the payment.
# An invoice with a payment applied to it is read-only, so a paid invoice isn't changed under the payment by
# accident. It can be unlocked on purpose (e.g. to give a discount after a deposit); the payment stays
# applied, and the total can't go below what's been paid.
module InvoiceWriter
Error = EstimateWriter::Error
Conflict = EstimateWriter::Conflict
@@ -77,6 +79,8 @@ module RedmineQboBilling
# The estimate's writer sells the job; with no one on the estimate, whoever writes the invoice
form.sales_person = source.sales_person.presence || user.name
form.private_note = source.private_note
form.discount_type = source.discount_type
form.discount_value = source.discount_value
form.lines = copy_lines(source.lines)
form.linked_estimate_ids = [source.id.to_s]
form.converted_from = source.doc_number
@@ -92,7 +96,8 @@ module RedmineQboBilling
# Creates or updates the invoice in QuickBooks, closes the estimates it was made from, and returns the
# saved QuickBooks invoice. The sales person is the one on the estimate it was made from (the first linked
# estimate that names one), or else the user who creates it; editing keeps the original one.
def save(form, user: User.current)
# unlock: a paid invoice may be changed (the user unlocked it), as long as it still covers the payments
def save(form, user: User.current, unlock: false)
customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
@@ -102,7 +107,7 @@ module RedmineQboBilling
raise Error, I18n.t(:notice_invoice_not_found) unless remote
raise Conflict, I18n.t(:error_invoice_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
raise Error, I18n.t(:error_invoice_has_bundles) if writer.group_lines?(remote)
raise Error, I18n.t(:error_invoice_paid) if paid?(remote)
check_paid(form, remote, unlock, user)
check_not_billed(form.linked_estimate_ids - linked_ids(remote, ESTIMATE))
invoice = Quickbooks::Model::Invoice.new
@@ -154,7 +159,9 @@ module RedmineQboBilling
total: remote.total,
total_tax: remote.txn_tax_detail&.total_tax,
discount: writer.discount_total(remote),
**writer.discount_fields(remote),
balance: remote.balance,
amount_paid: amount_paid(remote),
email_status: remote.email_status.to_s,
locked: (:bundles if writer.group_lines?(remote)) || (:paid if paid?(remote))
)
@@ -166,6 +173,46 @@ module RedmineQboBilling
BigDecimal(remote.balance.to_s) < BigDecimal(remote.total.to_s)
end
# What's been paid on the invoice: its total less its balance
def amount_paid(remote)
return BigDecimal('0') unless paid?(remote)
BigDecimal(remote.total.to_s) - BigDecimal(remote.balance.to_s)
end
# Nothing left owing on it
def fully_paid?(remote)
paid?(remote) && BigDecimal(remote.balance.to_s) <= 0
end
# A paid invoice is only changed when unlocked by a user allowed to (see
# RedmineQboBilling.paid_invoice_editor?), and never to less than what's been paid on it
def check_paid(form, remote, unlock, user)
return unless paid?(remote)
raise Error, I18n.t(:error_invoice_paid) unless unlock
raise Error, I18n.t(:error_invoice_paid_not_allowed) unless RedmineQboBilling.paid_invoice_editor?(fully_paid?(remote), user)
paid = amount_paid(remote)
total = estimated_total(form, remote)
return if total >= paid - BigDecimal('0.005')
raise Error, I18n.t(:error_invoice_below_paid, total: money(total), paid: money(paid))
end
# The invoice's new total, before QuickBooks works out the tax: the lines less the discount, plus the tax
# it had, scaled to the new amount (the same lines give exactly the old total)
def estimated_total(form, remote)
before_tax = form.subtotal - form.discount_amount
old_tax = BigDecimal(remote.txn_tax_detail&.total_tax.to_s.presence || '0')
old_before_tax = BigDecimal(remote.total.to_s) - old_tax
return before_tax if old_tax.zero? || old_before_tax <= 0
(before_tax + old_tax * before_tax / old_before_tax).round(2)
end
def money(amount)
ActiveSupport::NumberHelper.number_to_currency(amount)
end
def linked_ids(remote, type)
Array(remote&.linked_transactions).select { |t| t.txn_type.to_s == type }.map { |t| t.txn_id.to_s }.uniq
end
@@ -188,16 +235,19 @@ module RedmineQboBilling
invoice.private_note = form.private_note.to_s
invoice.custom_fields = writer.build_custom_fields(form, remote, user, sales_person: sales_person)
invoice.line_items = writer.build_lines(form, remote)
writer.discount_before_tax(invoice, form)
invoice.linked_transactions = header_links(form, remote)
invoice
end
# The invoice-level links: the estimates it was made from, and every time activity a line bills
# (QuickBooks wants time linked both on the line and on the invoice)
# The invoice-level links: the estimates it was made from, every time activity a line bills (QuickBooks
# wants time linked both on the line and on the invoice), and whatever else QuickBooks linked to it, e.g.
# the payments applied to it (left out, QuickBooks would unlink them)
def header_links(form, remote)
estimates = (linked_ids(remote, ESTIMATE) + form.linked_estimate_ids).uniq
times = form.filled_lines.filter_map(&:time_activity_id).map(&:to_s).uniq
estimates.map { |id| link(id, ESTIMATE) } + times.map { |id| link(id, TIME_ACTIVITY) }
others = Array(remote&.linked_transactions).reject { |t| [ESTIMATE, TIME_ACTIVITY].include?(t.txn_type.to_s) }
estimates.map { |id| link(id, ESTIMATE) } + times.map { |id| link(id, TIME_ACTIVITY) } + others
end
def link(id, type)
+11 -3
View File
@@ -9,8 +9,8 @@
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module RedmineQboBilling
# What the Receive payment page posts: who paid, how, and how much. PaymentWriter turns it into a
# QuickBooks payment, applied to the customer's oldest open invoices first, or kept as a deposit.
# What the Receive payment and Edit payment pages post: who paid, how, and how much. PaymentWriter turns it
# into a QuickBooks payment, applied to the customer's oldest open invoices first, or kept as a deposit.
class PaymentForm
include ActiveModel::Model
include ActiveModel::Validations
@@ -20,16 +20,24 @@ module RedmineQboBilling
attr_accessor(*ATTRIBUTES)
# Invoices ticked on the page: the payment goes on these (oldest first). None ticked: all open invoices.
attr_accessor :invoice_ids
# A saved payment being edited: its QuickBooks id and sync token, and why it can't be edited here (or nil)
attr_accessor :id, :sync_token, :locked
validate :validate_payment
def self.from_params(params)
def self.from_params(params, id: nil)
params = params.to_h.stringify_keys
new(ATTRIBUTES.to_h { |attr| [attr, params[attr.to_s].to_s.strip] }).tap do |form|
form.invoice_ids = Array(params['invoice_ids']).map(&:to_s).reject(&:blank?).uniq
form.id = id.presence
form.sync_token = params['sync_token'].presence
end
end
def persisted?
id.present?
end
def initialize(attributes = {})
super
self.invoice_ids ||= []
+124 -28
View File
@@ -12,8 +12,13 @@ module RedmineQboBilling
# Receives customer payments in QuickBooks: payment type and amount, applied to the customer's open
# invoices oldest first (the way QuickBooks applies them on its own screen), or only to the invoices ticked
# on the page, or saved unapplied as a deposit. Whatever doesn't fit stays unapplied as a credit.
#
# A saved payment can be edited the same way (date, method, reference, memo, amount and the invoices it
# pays); its customer stays. Left as it was, it keeps the amounts it already applied to each invoice.
module PaymentWriter
Error = EstimateWriter::Error
Conflict = EstimateWriter::Conflict
INVOICE = 'Invoice'.freeze
METHODS_CACHE_KEY = 'redmine_qbo_billing:payment_methods'
@@ -39,17 +44,21 @@ module RedmineQboBilling
[]
end
# The customer's invoices with a balance, oldest first (by date, then number)
def open_invoices(customer)
# The customer's invoices with a balance, oldest first (by date, then number). For a payment being edited
# (payment:, the QuickBooks payment), what it paid on each invoice counts as still open, so the invoices it
# pays are listed even when it paid them off.
def open_invoices(customer, payment: nil)
invoices = with_service('Invoice') do |service|
service.query("SELECT * FROM Invoice WHERE CustomerRef = '#{customer.id.to_i}' ORDERBY TxnDate", per_page: 1000).entries
end
paid_here = payment ? applied_amounts(payment) : {}
Array(invoices).select { |i| BigDecimal(i.balance.to_s.presence || '0') > 0 }
.sort_by { |i| [i.txn_date || Date.new(1900), i.doc_number.to_s.rjust(12, '0')] }
.map do |i|
Array(invoices).map { |i| [i, BigDecimal(i.balance.to_s.presence || '0') + paid_here.fetch(i.id.to_s, 0)] }
.select { |_, balance| balance > 0 }
.sort_by { |i, _| [i.txn_date || Date.new(1900), i.doc_number.to_s.rjust(12, '0')] }
.map do |i, balance|
{ id: i.id.to_s, doc_number: i.doc_number.to_s, date: i.txn_date.to_s, due_date: i.due_date.to_s,
total: i.total.to_s, balance: BigDecimal(i.balance.to_s).to_s('F') }
total: i.total.to_s, balance: balance.to_s('F') }
end
end
@@ -67,45 +76,132 @@ module RedmineQboBilling
[applied, left]
end
# Creates the payment in QuickBooks and returns it. Open invoices are read again here, so the payment
# goes on what's open right now.
# Creates the payment in QuickBooks (or updates the one being edited) and returns it. Open invoices are
# read again here, so the payment goes on what's open right now.
def save(form)
return update(form) if form.persisted?
customer = Customer.find_by(id: form.customer_id)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
amount = form.amount_value.round(2)
applied =
if form.deposit?
[]
else
invoices = open_invoices(customer)
invoices = invoices.select { |i| form.invoice_ids.include?(i[:id]) } if form.invoice_ids.any?
allocate(amount, invoices).first
end
applied = allocation(form, customer, amount)
payment = Quickbooks::Model::Payment.new
payment.customer_id = customer.id
payment.txn_date = form.txn_date_value
payment.payment_method_ref = Quickbooks::Model::BaseReference.new(form.payment_method_id)
payment.payment_ref_number = form.reference if form.reference.present?
payment.private_note = form.memo if form.memo.present?
payment.total = amount
payment.line_items = applied.map do |invoice, take|
line = Quickbooks::Model::Line.new
line.amount = take
line.invoice_id = invoice[:id]
line
end
fill(payment, form, amount, applied)
payment.payment_ref_number = nil if form.reference.blank?
payment.private_note = nil if form.memo.blank?
saved = with_service('Payment') { |service| service.create(payment) }
raise Error, I18n.t(:error_payment_not_saved) unless saved
# Invoice balances changed: update the local invoices, and cache the payment for reports
applied.each { |invoice, _| sync_invoice(invoice[:id]) }
applied.each { |invoice_id, _| sync_invoice(invoice_id) }
sync_payment(saved.id)
saved
end
# A saved payment on the Edit payment page
def load_form(id)
payment = load(id)
applied = applied_amounts(payment)
PaymentForm.new(
id: payment.id.to_s,
sync_token: payment.sync_token.to_s,
customer_id: payment.customer_ref&.value.to_s,
customer_name: payment.customer_ref&.name.presence || Customer.find_by(id: payment.customer_ref&.value)&.name,
txn_date: payment.txn_date&.iso8601,
payment_method_id: payment.payment_method_ref&.value.to_s,
reference: payment.payment_ref_number.to_s,
amount: BigDecimal(payment.total.to_s).round(2).to_s('F'),
deposit: applied.empty? ? '1' : '0',
memo: payment.private_note.to_s,
invoice_ids: applied.keys,
locked: edit_blocked(payment)
)
end
# Saves the changes to a payment. Its customer stays. If the amount and the ticked invoices are the
# same as before, each invoice keeps the amount it had; otherwise the amount is spread again, oldest first.
def update(form)
applied = nil
previously = []
saved = with_service('Payment') do |service|
remote = service.fetch_by_id(form.id)
raise Error, I18n.t(:notice_payment_not_found) unless remote
raise Conflict, I18n.t(:error_payment_changed_in_quickbooks) if remote.sync_token.to_s != form.sync_token.to_s
blocked = edit_blocked(remote)
raise Error, blocked if blocked
customer = Customer.find_by(id: remote.customer_ref&.value)
raise Error, I18n.t(:error_estimate_needs_customer) unless customer
amount = form.amount_value.round(2)
before = applied_amounts(remote)
applied =
if !form.deposit? && before.any? && amount == BigDecimal(remote.total.to_s) && form.invoice_ids.sort == before.keys.sort
before.to_a
else
allocation(form, customer, amount, payment: remote)
end
previously = before.keys
payment = Quickbooks::Model::Payment.new
payment.id = remote.id
payment.sync_token = remote.sync_token
payment.customer_ref = remote.customer_ref
fill(payment, form, amount, applied)
service.update(payment, sparse: true)
end
raise Error, I18n.t(:error_payment_not_saved) unless saved
# Balances changed on the invoices it paid before and the ones it pays now
(previously + applied.map(&:first)).uniq.each { |invoice_id| sync_invoice(invoice_id) }
sync_payment(saved.id)
saved
end
# Where the payment goes: [[invoice_id, amount], ...] (nothing for a deposit)
def allocation(form, customer, amount, payment: nil)
return [] if form.deposit?
invoices = open_invoices(customer, payment: payment)
invoices = invoices.select { |i| form.invoice_ids.include?(i[:id]) } if form.invoice_ids.any?
allocate(amount, invoices).first.map { |invoice, take| [invoice[:id], take] }
end
# The form's details on a QuickBooks payment, applied as given ([[invoice_id, amount], ...])
def fill(payment, form, amount, applied)
payment.txn_date = form.txn_date_value
payment.payment_method_ref = Quickbooks::Model::BaseReference.new(form.payment_method_id)
payment.payment_ref_number = form.reference.to_s
payment.private_note = form.memo.to_s
payment.total = amount
payment.line_items = applied.map do |invoice_id, take|
line = Quickbooks::Model::Line.new
line.amount = take
line.invoice_id = invoice_id
line
end
payment
end
# Why a payment can't be edited here, or nil: it also applies credit memos or other transactions, which
# this page doesn't show (saving would drop them)
def edit_blocked(payment)
others = Array(payment.line_items).flat_map { |line| Array(line.linked_transactions) }
.reject { |t| t.txn_type.to_s == INVOICE }
others.any? ? I18n.t(:error_payment_not_editable, types: others.map { |t| t.txn_type.to_s }.uniq.join(', ')) : nil
end
# What the payment pays on each invoice: { invoice_id => amount }
def applied_amounts(payment)
applied_invoices(payment).each_with_object(Hash.new(BigDecimal('0'))) do |(invoice_id, _, amount), sums|
sums[invoice_id] += BigDecimal(amount.to_s.presence || '0')
end.to_h
end
# Every payment the customer has made, newest first (by date, then QuickBooks id), read from QuickBooks
def customer_payments(customer)
payments = with_service('Payment') do |service|