Fold redmine_qbo_billing into redmine_qbo

Estimates, invoices and payments written in Redmine, issues from estimates,
and the QuickBooks product/service list and accounts are now part of this
plugin (the RedmineQboBilling code, its controllers, views, strings and
permissions), so there's one plugin and one version instead of two that had
to match.

- The customer page, estimate and invoice lists and the issue page render the
  Create Estimate / Create invoice / Receive payment and Edit links directly;
  the hooks that only existed to let billing add them are gone. Users without
  the billing permissions still get the links to QuickBooks.
- Migrations 043-046 create the items and accounts tables and the estimate
  line links, skipping whatever an existing database already has
  (redmine_qbo_lineitems' tables are used as they are), and copy calendar's
  existing estimate line links in.
- The billing settings are a section of this plugin's settings page.
- The hooks other plugins use stay: qbo_billing_issue_values,
  qbo_billing_validate, qbo_billing_issue_defaults, qbo_billing_issues_created
  and view_qbo_estimate_contextual.
- rake redmine_qbo:relate_estimate_issues

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-30 23:47:01 -04:00
1 parent 48a4185c16
commit 9121e079a0
67 files changed
+5570 -19

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
#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.
class AccountsController < ApplicationController
layout 'admin'
menu_item :redmine_qbo_items
# Accounts come from QuickBooks; choosing the default and syncing are admin-only
before_action :require_admin
def index
@accounts = Account.where(classification: 'Revenue').order(:name)
end
def set_default
account = Account.find_by(id: params[:default_account_id])
if account&.update(default: true)
flash[:notice] = l(:notice_default_account_updated)
else
flash[:error] = l(:error_default_account_not_selected)
end
redirect_to accounts_path
end
def sync
Account.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) }
end
end
+106
View File
@@ -0,0 +1,106 @@
#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.
class ItemsController < ApplicationController
layout 'admin'
menu_item :redmine_qbo_items
# The item catalog is pushed to QuickBooks, so managing it is admin-only. The autocomplete feeds the
# line item form on issues and is allowed with the "Add line items" or "Edit line items" permission.
before_action :require_admin, except: :autocomplete
before_action :authorize_global, only: :autocomplete
before_action :find_item, only: [:show, :edit, :update, :destroy]
# Used for autocomplete form
def autocomplete
term = ActiveRecord::Base.sanitize_sql_like(params[:q].to_s)
items = Item.where("description LIKE :t OR name LIKE :t OR sku LIKE :t", t: "%#{term}%")
.where(active: true)
.order(:description)
.limit(20)
render json: items.map { |i|
{ id: i.id, name: i.name, sku: i.sku, description: i.description, price: i.unit_price }
}
end
def create
@item = Item.new(item_params)
if @item.save
redirect_to item_path(@item), notice: l(:notice_successful_create)
else
render :new, status: :unprocessable_entity
end
rescue => e
log "Unexpected error creating item: #{e.message}"
# Regex now matches across line breaks
existing_id = e.message[/Duplicate Name Exists Error:[\s\S]*Id=(\d+)/, 1]&.to_i
if existing_id
flash[:error] = "Name already exists. Redirecting to existing item."
redirect_to item_path(existing_id)
else
flash[:error] = e.message
redirect_to new_item_path
end
end
def destroy
@item.destroy
redirect_to items_path, notice: l(:notice_successful_delete)
end
def edit
end
def index
@items = Item.order(:name)
end
def new
@item = Item.new
end
def show
end
def sync
Item.sync
redirect_to :home, flash: { notice: I18n.t(:label_syncing) }
end
def update
if @item.update(item_params)
redirect_to item_path(@item), notice: l(:notice_successful_update)
else
render :edit, status: :unprocessable_entity
end
end
private
def find_item
@item = Item.find(params[:id])
rescue ActiveRecord::RecordNotFound
render_404
end
def item_params
params.require(:item).permit(:name, :description, :sku, :unit_price, :active, :account_id, :type, :taxable)
end
def log(msg)
Rails.logger.info "[ItemsController] #{msg}"
end
end
+245
View File
@@ -0,0 +1,245 @@
#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.
# Writes, edits and emails QuickBooks estimates from Redmine, on a page laid out like QuickBooks' estimate screen.
class QboEstimatesController < ApplicationController
before_action :require_admin, only: :refresh_company
before_action :authorize_global, except: :refresh_company
before_action :require_sender_for_save_and_send, only: [:create, :update]
before_action :load_issue_preview, only: [:issues_preview, :create_issues]
helper :projects
helper :custom_fields
# Saving an estimate can take a few QuickBooks calls; any of them can fail with a message worth showing
QBO_ERRORS = [RedmineQboBilling::EstimateWriter::Error, Quickbooks::IntuitRequestException,
Quickbooks::InvalidModelException, Quickbooks::AuthorizationFailure,
# 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>)
def new
if 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
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def create
@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)
finish_save(saved, l(:notice_estimate_saved_in_quickbooks, number: saved.doc_number))
rescue *QBO_ERRORS => e
show_error(e, :new)
end
def edit
@form = RedmineQboBilling::EstimateWriter.load(params[:id])
@linked_issues = RedmineQboBilling::EstimateWriter.linked_issues(@form.id).visible.to_a
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def update
@form = RedmineQboBilling::EstimateForm.from_params(estimate_params, id: params[:id])
@form.sales_person = params.dig(:estimate, :sales_person).to_s
return show_invalid(:edit) unless @form.valid?
saved = RedmineQboBilling::EstimateWriter.save(@form, user: User.current)
finish_save(saved, l(:notice_estimate_saved_in_quickbooks, number: saved.doc_number))
rescue RedmineQboBilling::EstimateWriter::Conflict => e
@conflict = true
show_error(e, :edit)
rescue *QBO_ERRORS => e
show_error(e, :edit)
end
# Emails an estimate that's already saved (e.g. resending it)
def send_email
sent = RedmineQboBilling::EstimateWriter.send_email(params[:id], params[:email])
flash[:notice] = l(:notice_estimate_sent, number: sent.doc_number, email: sent.bill_email&.address || params[:email])
redirect_to edit_qbo_estimate_path(params[:id])
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_to edit_qbo_estimate_path(params[:id])
end
# Preview of the issues that can be created from the estimate's labor lines. Each line gets a tracker and
# (optionally) a template before anything is created. Opened from an appointment, the appointment's dates,
# technician and vehicle are used (redmine_qbo_calendar's :qbo_billing_issue_defaults).
def issues_preview
end
# Creates the issues selected on the preview page, all or nothing
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)
if created.any?
Redmine::Hook.call_hook(:qbo_billing_issues_created, { estimate: @estimate, issues: created, params: params })
flash[:notice] = l(:notice_estimate_issues_created, count: created.size)
redirect_to @return_path
else
# Rebuild the fields so the form keeps what was entered
@field_set = RedmineQboBilling::IssueFieldSet.new(project: @target_project, trackers: @trackers,
values: @custom_field_values)
render :issues_preview, status: :unprocessable_entity
end
end
# Customer details for the editor when a customer is picked: email, billing address and vehicles (VINs)
def customer_info
customer = Customer.find_by(id: params[:customer_id])
return render(json: {}, status: :not_found) unless customer
vehicles = customer.respond_to?(:vehicles) ? customer.vehicles.to_a : []
render json: {
id: customer.id,
name: customer.name,
email: RedmineQboBilling::EstimateWriter.customer_email(customer),
billing_address: RedmineQboBilling::EstimateWriter.customer_address(customer),
vehicles: vehicles.select { |v| v.vin.present? }.map { |v| { vin: v.vin, name: v.to_s } }
}
end
# Product/service search for the line table (the QuickBooks item list)
def items
term = "%#{ActiveRecord::Base.sanitize_sql_like(params[:q].to_s.strip)}%"
items = Item.where(active: true)
.where("name LIKE :t OR sku LIKE :t OR description LIKE :t", t: term)
.order(:name)
.limit(25)
render json: items.map { |item|
{ id: item.id, name: item.name, sku: item.sku, description: item.description,
price: item.unit_price&.to_s, taxable: item.taxable != false }
}
end
# Re-reads the QuickBooks custom fields and estimate settings (e.g. after renaming a custom field)
def refresh_company
RedmineQboBilling::Company.refresh!
flash[:notice] = l(:notice_estimate_settings_refreshed)
redirect_back_or_default home_path
end
private
# Everything the issues preview needs: the local estimate, defaults from other plugins, the target project,
# its trackers, templates and custom fields
def load_issue_preview
@estimate = Estimate.find_by(id: params[:id])
unless @estimate
EstimateSyncService.new.sync_by_id(params[:id])
@estimate = Estimate.find_by(id: params[:id])
end
return render_404 unless @estimate
@defaults = issue_defaults
@builder = RedmineQboBilling::EstimateIssueBuilder.new(@estimate, defaults: @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
chosen = @available_projects.detect { |p| p.id == params[:project_id].to_i } if params[:project_id].present?
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
return deny_access unless @target_project
@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)
@rows ||= {}
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
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 })
(results.detect { |r| r.is_a?(Hash) && r.any? } || {}).symbolize_keys
end
# The shared custom field values from the preview form: { custom_field_id => value }
def submitted_custom_field_values
values = params.dig(:issue, :custom_field_values)
values.respond_to?(:to_unsafe_h) ? values.to_unsafe_h : {}
end
def estimate_params
params.require(:estimate).permit(
:sync_token, :total_tax, :discount, :email_status, :txn_status,
*RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES,
lines: RedmineQboBilling::EstimateForm::Line::PARAMS
)
end
def save_and_send?
params[:save_and_send].present?
end
def require_sender_for_save_and_send
deny_access if save_and_send? && !RedmineQboBilling.sender?
end
# After saving: email it if asked, then reopen the saved estimate
def finish_save(saved, notice)
if save_and_send?
begin
sent = RedmineQboBilling::EstimateWriter.send_email(saved.id, @form.email)
notice = l(:notice_estimate_saved_and_sent, number: sent.doc_number, email: sent.bill_email&.address || @form.email)
rescue *QBO_ERRORS => e
flash[:error] = l(:error_estimate_saved_not_sent, message: qbo_message(e))
end
end
flash[:notice] = notice
redirect_to edit_qbo_estimate_path(saved.id)
end
def show_error(error, view)
logger.warn "[RedmineQboBilling] #{error.class}: #{qbo_message(error)}"
@form.errors.add(:base, qbo_message(error))
show_invalid(view)
end
# Shows the form again with what was typed. Empty rows are dropped so the line numbers in the
# error messages match the table, and the billing address (display only) is looked up again.
def show_invalid(view)
@form.lines = @form.filled_lines
customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present?
@form.billing_address = RedmineQboBilling::EstimateWriter.customer_address(customer) if customer
render view, status: :unprocessable_entity
end
# QuickBooks errors carry their detail separately from the message
def qbo_message(error)
detail = error.respond_to?(:detail) ? error.detail.to_s : ''
message = error.message.to_s
detail.present? && !message.include?(detail) ? "#{message}: #{detail}" : message
end
end
+142
View File
@@ -0,0 +1,142 @@
#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.
# 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
before_action :authorize_global
before_action :require_sender_for_save_and_send, only: [:create, :update]
before_action :find_customer, only: :import_options
QBO_ERRORS = QboEstimatesController::QBO_ERRORS
# A blank invoice, or one made from an estimate (?estimate_id=<estimate id>)
def new
@form =
if params[:estimate_id].present?
RedmineQboBilling::InvoiceWriter.from_estimate(params[:estimate_id], user: User.current)
else
customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present?
RedmineQboBilling::InvoiceWriter.new_form(customer: customer, user: User.current)
end
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def create
@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)
finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number))
rescue *QBO_ERRORS => e
show_error(e, :new)
end
def edit
@form = RedmineQboBilling::InvoiceWriter.load(params[:id])
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
def update
@form = RedmineQboBilling::EstimateForm.from_params(invoice_params, id: params[:id], document: 'invoice')
@form.sales_person = params.dig(:estimate, :sales_person).to_s
return show_invalid(:edit) unless @form.valid?
saved = RedmineQboBilling::InvoiceWriter.save(@form, user: User.current)
finish_save(saved, l(:notice_invoice_saved_in_quickbooks, number: saved.doc_number))
rescue RedmineQboBilling::InvoiceWriter::Conflict => e
@conflict = true
show_error(e, :edit)
rescue *QBO_ERRORS => e
show_error(e, :edit)
end
# Emails an invoice that's already saved (e.g. resending it)
def send_email
sent = RedmineQboBilling::InvoiceWriter.send_email(params[:id], params[:email])
flash[:notice] = l(:notice_invoice_sent, number: sent.doc_number, email: sent.bill_email&.address || params[:email])
redirect_to edit_qbo_invoice_path(params[:id])
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_to edit_qbo_invoice_path(params[:id])
end
# The customer's billable time and open estimates, for the Import panel
def import_options
render json: RedmineQboBilling::InvoiceWriter.import_options(@customer, issue_ids: Array(params[:issue_ids]))
rescue *QBO_ERRORS => e
render json: { error: qbo_message(e) }, status: :unprocessable_entity
end
private
def find_customer
@customer = Customer.find_by(id: params[:customer_id])
render(json: { error: l(:error_estimate_needs_customer) }, status: :not_found) unless @customer
end
def invoice_params
params.require(:estimate).permit(
:sync_token, :total_tax, :discount, :email_status, :txn_status, :balance,
*RedmineQboBilling::EstimateForm::HEADER_ATTRIBUTES,
linked_estimate_ids: [],
lines: RedmineQboBilling::EstimateForm::Line::PARAMS
)
end
def save_and_send?
params[:save_and_send].present?
end
def require_sender_for_save_and_send
deny_access if save_and_send? && !RedmineQboBilling.invoice_sender?
end
# After saving: email it if asked, then reopen the saved invoice
def finish_save(saved, notice)
if save_and_send?
begin
sent = RedmineQboBilling::InvoiceWriter.send_email(saved.id, @form.email)
notice = l(:notice_invoice_saved_and_sent, number: sent.doc_number, email: sent.bill_email&.address || @form.email)
rescue *QBO_ERRORS => e
flash[:error] = l(:error_estimate_saved_not_sent, message: qbo_message(e))
end
end
flash[:notice] = notice
redirect_to edit_qbo_invoice_path(saved.id)
end
def show_error(error, view)
logger.warn "[RedmineQboBilling] #{error.class}: #{qbo_message(error)}"
@form.errors.add(:base, qbo_message(error))
show_invalid(view)
end
# Shows the form again with what was typed (see QboEstimatesController#show_invalid)
def show_invalid(view)
@form.lines = @form.filled_lines
customer = Customer.find_by(id: @form.customer_id) if @form.customer_id.present?
@form.billing_address = RedmineQboBilling::EstimateWriter.customer_address(customer) if customer
render view, status: :unprocessable_entity
end
def qbo_message(error)
detail = error.respond_to?(:detail) ? error.detail.to_s : ''
message = error.message.to_s
detail.present? && !message.include?(detail) ? "#{message}: #{detail}" : message
end
end
@@ -0,0 +1,90 @@
#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.
# 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).
class QboPaymentsController < ApplicationController
before_action :authorize_global
QBO_ERRORS = QboEstimatesController::QBO_ERRORS
def new
customer = Customer.find_by(id: params[:customer_id]) if params[:customer_id].present?
@form = RedmineQboBilling::PaymentWriter.new_form(customer: customer, user: User.current)
load_choices
end
def create
@form = RedmineQboBilling::PaymentForm.from_params(payment_params)
return show_form unless @form.valid?
payment = RedmineQboBilling::PaymentWriter.save(@form)
flash[:notice] = l(:notice_payment_saved, amount: view_context.number_to_currency(payment.total))
redirect_to qbo_payment_path(payment.id)
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)
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_back_or_default home_path
end
# QuickBooks' PDF of the payment, shown in the browser to print
def pdf
data = RedmineQboBilling::PaymentWriter.pdf(params[:id])
send_data data, type: 'application/pdf', disposition: 'inline', filename: "payment-#{params[:id].to_i}.pdf"
rescue *QBO_ERRORS => e
flash[:error] = qbo_message(e)
redirect_to qbo_payment_path(params[:id])
end
# The customer's open invoices, oldest first, so the page can show how the payment will be applied
def open_invoices
customer = Customer.find_by(id: params[:customer_id])
return render(json: [], status: :not_found) unless customer
render json: RedmineQboBilling::PaymentWriter.open_invoices(customer)
rescue *QBO_ERRORS => e
render json: { error: qbo_message(e) }, status: :unprocessable_entity
end
private
def payment_params
params.require(:payment).permit(*RedmineQboBilling::PaymentForm::ATTRIBUTES, 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) : []
rescue *QBO_ERRORS => e
@open_invoices = []
flash.now[:error] = qbo_message(e)
end
def show_form
load_choices
render :new, status: :unprocessable_entity
end
def qbo_message(error)
detail = error.respond_to?(:detail) ? error.detail.to_s : ''
message = error.message.to_s
detail.present? && !message.include?(detail) ? "#{message}: #{detail}" : message
end
end