mirror of
https://github.com/rickbarrette/redmine_qbo.git
synced 2026-11-19 10:40:36 -05:00
Compare commits
31
Commits
2026.11.4
...
2026.11.16
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2fb21c34bb | ||
|
|
1c71e3a4c9 | ||
|
|
89f4797bbe | ||
|
|
3bbceacda4 | ||
|
|
d75dee2866 | ||
|
|
c8e2d2d92e | ||
|
|
a1fb88e77c | ||
|
|
0a7b2e34b8 | ||
|
|
895733f534 | ||
|
|
fa1b4eed06 | ||
|
|
95e76a41fd | ||
|
|
92b2a18eb6 | ||
|
|
084df36061 | ||
|
|
3b51625df4 | ||
|
|
7cfc8a370e | ||
|
|
d2cdd798cd | ||
|
|
159420fac1 | ||
|
|
dbee228cdf | ||
|
|
ec00684edd | ||
|
|
839ac976e6 | ||
|
|
dc72b11766 | ||
|
|
778111825b | ||
|
|
4ba96e2dfd | ||
|
|
88160a985d | ||
|
|
e2a871b1e8 | ||
|
|
489edd97fa | ||
|
|
64e4a149ab | ||
|
|
6a638fe7bb | ||
|
|
51159d5034 | ||
|
|
8f2cef2bc8 | ||
|
|
bd29ec2978 |
No files matched your search
@@ -3,7 +3,6 @@ source 'https://rubygems.org'
|
||||
gem 'quickbooks-ruby'
|
||||
gem 'oauth2'
|
||||
gem 'roxml'
|
||||
gem 'will_paginate'
|
||||
gem 'rexml'
|
||||
gem 'combine_pdf'
|
||||
|
||||
|
||||
@@ -69,8 +69,10 @@ This ensures Time Activities are recorded under the correct employee in QuickBoo
|
||||
The plugin provides basic Customer management:
|
||||
|
||||
* Create Customers directly from Redmine
|
||||
|
||||
* Browse every Customer on the **Customers** page: a Redmine list with phone numbers, issue counts and last update, sortable by column and paged with Redmine's own pagination (and its per-page choices)
|
||||
|
||||
* Search Customers by **name or phone number**
|
||||
* Search Customers by **name or phone number**: the best matches come first (click a column to sort them instead), and a single match opens that Customer
|
||||
|
||||
* View and edit Customer information
|
||||
|
||||
@@ -101,7 +103,7 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
|
||||
|
||||
## Billing: Estimates, Invoices and Payments
|
||||
|
||||
* **New estimate** from the customer page: Create Estimate opens the Redmine editor. The customer page no longer links to QuickBooks' estimate or payment screens; the customer's name still opens their QuickBooks account page as a fallback.
|
||||
* **New estimate** from the customer page: Create Estimate opens the Redmine editor. The customer page no longer links to QuickBooks' estimate or payment screens; **Open in QuickBooks** opens their QuickBooks account page as a fallback.
|
||||
* **Edit** any estimate from the Edit link next to it on the customer page or the issue page.
|
||||
* **Keyboard entry**: in a line's product box, Tab picks the product the text points to (an exact name, the only match, or the only name starting with it, e.g. "lab" → Labor) and fills the line. Tabbing into the description, quantity or rate selects it, so typing replaces it. The quantity, rate and amount boxes take simple math (e.g. `33*1.3`, `(120+15)/2`; `+ - * /`, `x` for times, parentheses), worked out when you leave the box; math in the rate or amount is rounded to the nearest penny, and an amount sets the rate from the quantity. Typing `sub`, `subtotal` or `=` in a product box, then Tab or Enter, adds a subtotal there (an empty line becomes the subtotal; a line with a description keeps it and gets the subtotal after it) and moves on to the next line.
|
||||
* **Duplicate** an estimate to start a similar one: same customer, lines, subtotals, custom fields and messages, dated today, with the current user as sales person.
|
||||
@@ -119,7 +121,7 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
|
||||
|
||||
* **Create invoice** on an estimate's page makes an invoice from it (customer, lines, subtotals, custom fields), like QuickBooks' "Create invoice". **Create invoice** on the customer page starts a blank one, and the Edit link next to each invoice on the customer page opens it.
|
||||
* **Import time & estimates** lists the customer's billable QuickBooks time (the time activities redmine_qbo makes from an issue's time entries) and their open estimates (e.g. the ones redmine_qbo_lineitems makes for parts that weren't quoted).
|
||||
* Tick the time to bill and, under **Replace these lines**, the lines it replaces (e.g. the estimate's labor lines). Only lines with one of the **labor products/services** from the plugin settings are offered there. The time goes where the first ticked line was and the ticked lines are removed, so the invoice reads in the same order.
|
||||
* Tick the time to bill and, under **Replace these lines**, the lines it replaces (e.g. the estimate's labor lines). Only lines with one of the **labor products/services** from the plugin settings are offered there. Each time entry takes the place of one ticked line: the one whose description is its issue's subject (issues created from an estimate are named after the line, so "Install #134: Install Lift Kit" replaces the "Install Lift Kit" line), then any others in order. Extra time goes after the last replaced line and extra ticked lines are removed, so the invoice keeps the estimate's order and subtotals.
|
||||
* Ticked estimates go right after the time for the same issue: a redmine_qbo_lineitems estimate starting "Added from: Install #116: …" lands after the time for #116, without that note line, since the time line already names the issue. Estimates with no matching time keep the note and go at the end.
|
||||
* **Undo import** puts the lines back until the invoice is saved.
|
||||
* **An estimate is billed once**: an estimate that's on an invoice (linked to one, or closed) or was rejected can't be made into an invoice or imported, and its page shows the invoice it's billed on. This is checked against QuickBooks again when the invoice is saved, so an estimate invoiced meanwhile (in another tab, by someone else, or in QuickBooks) stops the save.
|
||||
@@ -140,11 +142,13 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
|
||||
|
||||
### Business report
|
||||
|
||||
**Business report** in the top menu compares, for a period (this or last month, quarter or year, or custom dates):
|
||||
**Business report** in the top menu compares, for a period (this or last week, month, quarter or year, or custom dates; weeks start on the day set in Redmine's *Start calendars on* setting, Monday when it follows the language):
|
||||
|
||||
* **Sales**: estimates written, invoices written and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices.
|
||||
* **Hours**: estimated hours on estimates, issues' estimated time, invoiced hours on invoices and time spent, with spent vs. estimated, and the **cost performance index** (CPI = invoiced hours ÷ spent hours): green at 1.00 or more, yellow below 1, red below 0.80. Each month shows its CPI too.
|
||||
* **Charts**: above each set of bars, a line chart of the same figures in the same colors (Chart.js 4.5.1, MIT licensed, bundled with the plugin in assets/javascripts so it doesn't clash with other plugins' copies such as redmine_indicator's Chart.js 2), with a point per day for a week, per week for up to about three months, and per month beyond. Hovering a point shows its figures. **Compare with last year** adds last year's lines, dashed and faded, without reloading: days and weeks go back 52 weeks so weekdays line up, months go back to the same month. Clicking a figure in the legend hides it (and its last-year line); clicking *last year* stops comparing. Today's line stops at today.
|
||||
* **By month**: every figure month by month, with totals.
|
||||
* **Projects**: pick one or more open projects (Ctrl/Cmd-click; closed and archived projects aren't listed) to count only their issues' estimated time and spent time, in the totals, charts and months; none picked counts every project. Estimates, invoices and payments have no project in QuickBooks, so they always cover the whole business (as do the CPI's invoiced hours). **Remember these projects** saves the choice in your Redmine preferences, and the report opens with it until you save another (saving none goes back to every project).
|
||||
|
||||
Estimates, invoices and payments count by their QuickBooks date. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. While estimates, invoices or payments are syncing, the report says so (with how many have been read) and refreshes every 30 seconds; the settings page's Synchronization table shows the same per type. Estimates and invoices synced before these figures were added have no total or hours until a full sync (the report says how many); run one again after changing the labor products/services.
|
||||
|
||||
@@ -214,7 +218,7 @@ Available hooks:
|
||||
|
||||
|Type|Hook|Note
|
||||
|--|--|--|
|
||||
View Hook|:view_customers_show_contextual, { customer: @customer } | Used to add action links to the customer page's top-right action area (return links styled like Redmine's, e.g. `link_to sprite_icon('add', 'Label'), path, class: 'icon icon-add'`). Replaces `customer_actions_top` / `customer_actions_bottom`
|
||||
View Hook|:view_customers_show_contextual, { customer: @customer } | Used to add action links to the customer page's action area, under the title (return links styled like Redmine's, e.g. `link_to sprite_icon('add', 'Label'), path, class: 'icon icon-add'`). Replaces `customer_actions_top` / `customer_actions_bottom`
|
||||
View Hook|:pdf_left, { issue: issue } | Used to add text to left side of PDF
|
||||
View Hook|:pdf_right, { issue: issue } | Used to add text to right side of PDF
|
||||
View Hook|:show_customer_view_right, { customer: customer } | Used to show partials on right side of customer view
|
||||
|
||||
@@ -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
|
||||
@@ -117,13 +117,33 @@ class CustomersController < ApplicationController
|
||||
@filtered_invoices = Invoice.all.where(customer_id: params[:selected_customer])
|
||||
end
|
||||
|
||||
# Most matches a search lists (best first)
|
||||
SEARCH_LIMIT = 200
|
||||
|
||||
# Every customer, sortable and paged like Redmine's lists; a search narrows it to the best matches (a single
|
||||
# match opens that customer). Sorting a search's results by a column replaces the best-first order.
|
||||
def index
|
||||
if params[:search]
|
||||
@customers = CustomerSearchService.call(name: params[:search], limit: 200).paginate(page: params[:page])
|
||||
if only_one_non_zero?(@customers)
|
||||
redirect_to @customers.first
|
||||
end
|
||||
sort_init 'name', 'asc'
|
||||
sort_update 'name' => "#{Customer.table_name}.name",
|
||||
'phone' => "#{Customer.table_name}.phone_number",
|
||||
'mobile' => "#{Customer.table_name}.mobile_phone_number",
|
||||
'updated' => "#{Customer.table_name}.updated_at"
|
||||
|
||||
@search = params[:search].to_s.strip
|
||||
if @search.present?
|
||||
scope = CustomerSearchService.call(name: @search, limit: SEARCH_LIMIT)
|
||||
@best_first = params[:sort].blank?
|
||||
else
|
||||
scope = Customer.all
|
||||
end
|
||||
scope = scope.reorder(sort_clause).order(:id) unless @best_first
|
||||
|
||||
@customer_count = scope.count
|
||||
return redirect_to(scope.first) if @search.present? && @customer_count == 1
|
||||
|
||||
@customer_pages = Paginator.new @customer_count, per_page_option, params['page']
|
||||
@customers = scope.limit(@customer_pages.per_page).offset(@customer_pages.offset).to_a
|
||||
@issue_counts = Issue.where(customer_id: @customers.map(&:id)).group(:customer_id).count
|
||||
end
|
||||
|
||||
def load_issue_data
|
||||
@@ -157,17 +177,6 @@ class CustomersController < ApplicationController
|
||||
end
|
||||
end
|
||||
|
||||
def only_one_non_zero?(array)
|
||||
found_non_zero = false
|
||||
array.each do |val|
|
||||
if val != 0
|
||||
return false if found_non_zero
|
||||
found_non_zero = true
|
||||
end
|
||||
end
|
||||
found_non_zero
|
||||
end
|
||||
|
||||
def share
|
||||
issue = Issue.visible.find(params[:id])
|
||||
token = issue.share_token
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -116,13 +125,19 @@ class QboEstimatesController < ApplicationController
|
||||
customer = Customer.find_by(id: params[:customer_id])
|
||||
return render(json: {}, status: :not_found) unless customer
|
||||
|
||||
render json: {
|
||||
info = {
|
||||
id: customer.id,
|
||||
name: customer.name,
|
||||
email: RedmineQboBilling::EstimateWriter.customer_email(customer),
|
||||
billing_address: RedmineQboBilling::EstimateWriter.customer_address(customer),
|
||||
field_options: RedmineQboBilling.field_options(customer)
|
||||
}
|
||||
# A new invoice warns about the customer's open issues
|
||||
if params[:document] == 'invoice'
|
||||
info[:open_issues_html] = render_to_string(partial: 'qbo_invoices/open_issues', formats: [:html],
|
||||
locals: { customer: customer })
|
||||
end
|
||||
render json: info
|
||||
end
|
||||
|
||||
# Product/service search for the line table (the QuickBooks item list)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -15,10 +15,48 @@ class QboReportsController < ApplicationController
|
||||
|
||||
before_action :authorize_global
|
||||
|
||||
# The user's preference holding the projects the report opens with
|
||||
PROJECTS_PREF = :qbo_report_project_ids
|
||||
|
||||
def index
|
||||
# Projects for the issues and spent time: the projects picker can choose some of the open ones
|
||||
@projects = Project.visible.active.to_a
|
||||
@project_ids = report_project_ids
|
||||
@report = RedmineQboBilling::BusinessReport.new(period: params[:period].presence || 'this_year',
|
||||
from: params[:from], to: params[:to], today: User.current.today)
|
||||
from: params[:from], to: params[:to], today: User.current.today,
|
||||
week_start: RedmineQboBilling::BusinessReport.week_start_from_setting(Setting.start_of_week),
|
||||
project_ids: @project_ids)
|
||||
# Last year's lines on the charts
|
||||
@compare = params[:compare] == '1'
|
||||
# Syncs still running for what the report counts: its figures are incomplete until they finish
|
||||
@syncing = QboSyncStatus.by_entity(%w[Estimate Invoice Payment]).values.sort_by(&:entity)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# The form's projects (none picked is every project), or the user's saved ones when the address has none.
|
||||
# "Remember these projects" saves the form's choice. Only open projects the user can see are kept.
|
||||
def report_project_ids
|
||||
visible = @projects.map(&:id)
|
||||
if params.key?(:project_ids)
|
||||
ids = Array(params[:project_ids]).map(&:to_i) & visible
|
||||
save_project_ids(ids) if params[:save_projects] == '1'
|
||||
else
|
||||
ids = saved_project_ids & visible
|
||||
end
|
||||
@saved_project_ids = saved_project_ids & visible
|
||||
ids
|
||||
end
|
||||
|
||||
def saved_project_ids
|
||||
return [] unless User.current.logged?
|
||||
Array(User.current.pref[PROJECTS_PREF]).map(&:to_i)
|
||||
end
|
||||
|
||||
def save_project_ids(ids)
|
||||
return unless User.current.logged?
|
||||
pref = User.current.pref
|
||||
pref[PROJECTS_PREF] = ids
|
||||
pref.save
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,71 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2016 - 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.
|
||||
|
||||
# Estimates, invoices and payments on Redmine's activity page. They come from QuickBooks and belong to no
|
||||
# project, so they show on the overall activity page only (not a project's, nor a user's), and each kind only to
|
||||
# users with one of its global permissions.
|
||||
module QboActivity
|
||||
extend ActiveSupport::Concern
|
||||
|
||||
class_methods do
|
||||
# event_type: the activity type registered in init.rb (e.g. 'qbo_estimates'); icon: the event's CSS class
|
||||
# and icon in this plugin's sprite (assets/images/icons.svg); permissions: any one of these shows it
|
||||
def qbo_activity(event_type, icon:, permissions:, title:, description:, url:)
|
||||
# These models can load before Redmine adds acts_as_event to every model
|
||||
include Redmine::Acts::Event unless respond_to?(:acts_as_event)
|
||||
acts_as_event title: title, description: description, url: url, type: icon,
|
||||
datetime: :activity_datetime, author: nil
|
||||
class_attribute :qbo_activity_permissions, instance_writer: false, default: permissions
|
||||
class_attribute :qbo_activity_event_type, instance_writer: false, default: event_type
|
||||
end
|
||||
|
||||
def qbo_activity_visible_to?(user)
|
||||
qbo_activity_permissions.any? { |permission| user.allowed_to?(permission, nil, global: true) }
|
||||
end
|
||||
|
||||
# What Redmine::Activity::Fetcher reads for a project's activity page; these never show there
|
||||
def activity_provider_options
|
||||
{ qbo_activity_event_type => { permission: qbo_activity_permissions.first } }
|
||||
end
|
||||
|
||||
# Documents dated from..to (the page's days, to not included), newest first. From the QuickBooks date, so
|
||||
# a sync bringing in old documents doesn't pile them onto the day it ran.
|
||||
def find_events(event_type, user, from, to, options)
|
||||
return [] if options[:project] || options[:author] || !qbo_activity_visible_to?(user)
|
||||
|
||||
scope = includes(:customer).where.not(txn_date: nil)
|
||||
scope = scope.where('txn_date >= ?', from.to_date) if from
|
||||
scope = scope.where('txn_date < ?', to.to_date) if to
|
||||
scope = scope.order(txn_date: :desc, id: :desc).limit(options[:limit]) if options[:limit]
|
||||
scope.to_a
|
||||
end
|
||||
end
|
||||
|
||||
# When it happened: the time it reached Redmine when that was its QuickBooks date (created or changed in
|
||||
# QuickBooks and sent by the webhook moments later), else midday on its QuickBooks date (e.g. a full sync)
|
||||
def activity_datetime
|
||||
return created_at if created_at && created_at.getlocal.to_date == txn_date
|
||||
|
||||
Time.local(txn_date.year, txn_date.month, txn_date.day, 12)
|
||||
end
|
||||
|
||||
# Activity events have a project; these don't
|
||||
def project
|
||||
nil
|
||||
end
|
||||
|
||||
def activity_money(amount)
|
||||
ActiveSupport::NumberHelper.number_to_currency(amount) if amount
|
||||
end
|
||||
|
||||
def activity_customer
|
||||
customer&.name.presence || I18n.t(:label_none)
|
||||
end
|
||||
end
|
||||
@@ -17,6 +17,12 @@ class Estimate < QboBaseModel
|
||||
self.primary_key = :id
|
||||
qbo_sync push: false
|
||||
|
||||
include QboActivity
|
||||
qbo_activity 'qbo_estimates', icon: 'qbo-estimate', permissions: %i[view_customers write_estimates],
|
||||
title: ->(e) { I18n.t(:label_activity_estimate, number: e.doc_number, customer: e.activity_customer) },
|
||||
description: ->(e) { [e.activity_money(e[:total_amount]), e[:txn_status]].compact.join(' · ') },
|
||||
url: ->(e) { { controller: 'estimates', action: 'show', id: e.id } }
|
||||
|
||||
def name
|
||||
to_s
|
||||
end
|
||||
|
||||
@@ -17,11 +17,26 @@ class Invoice < QboBaseModel
|
||||
self.primary_key = :id
|
||||
qbo_sync push: false
|
||||
|
||||
include QboActivity
|
||||
qbo_activity 'qbo_invoices', icon: 'qbo-invoice', permissions: %i[view_customers write_invoices],
|
||||
title: ->(i) { I18n.t(:label_activity_invoice, number: i.doc_number, customer: i.activity_customer) },
|
||||
description: ->(i) { i.activity_description },
|
||||
url: ->(i) { { controller: 'invoices', action: 'show', id: i.id } }
|
||||
|
||||
# Return the invoice's document number as its string representation
|
||||
def to_s
|
||||
doc_number
|
||||
end
|
||||
|
||||
# Amount and where it stands, e.g. "$1,250.00 · Partially paid ($400.00 owed)"
|
||||
def activity_description
|
||||
state = status
|
||||
owed = activity_money(self[:balance]) if state && self[:balance].to_d.positive?
|
||||
[activity_money(self[:total_amount]),
|
||||
(I18n.t(:"label_invoice_status_#{state}", default: state.to_s.humanize) if state),
|
||||
(I18n.t(:text_activity_invoice_owed, amount: owed) if owed && state != :open && state != :overdue)].compact.join(' · ')
|
||||
end
|
||||
|
||||
# Paid, partially paid, overdue, open or voided, from the cached total, balance and due date
|
||||
# (RedmineQboBilling::InvoiceStatus); nil when the balance isn't cached
|
||||
def status(today: User.current.today)
|
||||
|
||||
@@ -18,6 +18,19 @@ class Payment < QboBaseModel
|
||||
self.primary_key = :id
|
||||
qbo_sync push: false
|
||||
|
||||
include QboActivity
|
||||
qbo_activity 'qbo_payments', icon: 'qbo-payment', permissions: %i[view_payments receive_payments],
|
||||
title: ->(p) { I18n.t(:label_activity_payment, customer: p.activity_customer, amount: p.activity_money(p.total_amount)) },
|
||||
description: ->(p) { p.activity_description },
|
||||
url: ->(p) { { controller: 'qbo_payments', action: 'show', id: p.id } }
|
||||
|
||||
# Money not yet applied to an invoice, when there is some
|
||||
def activity_description
|
||||
return '' unless unapplied_amount.to_d.positive?
|
||||
|
||||
I18n.t(:text_activity_payment_unapplied, amount: activity_money(unapplied_amount))
|
||||
end
|
||||
|
||||
def to_s
|
||||
"#{txn_date} #{total_amount}"
|
||||
end
|
||||
|
||||
+3
-2
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -27,6 +27,7 @@ class InvoiceAttachmentService
|
||||
unless issue.invoices.exists?(@invoice.id)
|
||||
issue.invoices << @invoice
|
||||
issue.save! if issue.changed?
|
||||
journalize(issue)
|
||||
log "Attached invoice ##{@invoice.id} to issue ##{issue.id}"
|
||||
end
|
||||
end
|
||||
@@ -34,6 +35,18 @@ class InvoiceAttachmentService
|
||||
|
||||
private
|
||||
|
||||
# Records the new invoice in the issue's history (shown by RedmineQbo::Patches::IssuesHelperPatch).
|
||||
# The webhook has no Redmine user, so the entry is by Anonymous. Saving the journal also sends
|
||||
# Redmine's usual issue-updated emails.
|
||||
def journalize(issue)
|
||||
journal = Journal.new(journalized: issue, user: User.anonymous, notes: '')
|
||||
journal.details << JournalDetail.new(property: 'invoice', prop_key: @invoice.id.to_s, value: @invoice.to_s.presence || @invoice.id.to_s)
|
||||
journal.save
|
||||
rescue => e
|
||||
# The invoice is attached either way; a missing history entry shouldn't fail the sync
|
||||
log "Couldn't add invoice ##{@invoice.id} to the history of issue ##{issue.id}: #{e.message}"
|
||||
end
|
||||
|
||||
# Extract issue IDs from the invoice's private note and line descriptions
|
||||
def extract_issue_ids
|
||||
ids = []
|
||||
|
||||
@@ -1,24 +1,71 @@
|
||||
<h2><%=t(:field_customers)%> <span style="float:right"> <%= render partial: 'customers/search' %> </span> </h2>
|
||||
<% if @customers.present? %>
|
||||
<br/>
|
||||
<% @customers.each do |c| %>
|
||||
<div class="row">
|
||||
<div class="span6 columns">
|
||||
<%= link_to c, customer_path(c.id) %>
|
||||
</div>
|
||||
</div>
|
||||
<% html_title l(:label_customers) %>
|
||||
<% phone = ->(digits) { digits.present? ? number_to_phone(digits.gsub(/\D/, '').to_i, area_code: true) : '' } %>
|
||||
|
||||
<div class="contextual">
|
||||
<% 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 %>
|
||||
|
||||
<p><%=t(:label_matching)%> <%= @customers.count %> <%=t(:field_customers)%> </p>
|
||||
|
||||
<div class="actions">
|
||||
<%= will_paginate @customers %>
|
||||
</div>
|
||||
|
||||
<% else %>
|
||||
<p><%=t(:label_no_customers)%> <%= params[:search] %>.</p>
|
||||
<h2><%= l(:label_customers) %></h2>
|
||||
|
||||
<%= form_tag(customers_path, method: :get, id: 'customer-search-form') do %>
|
||||
<p class="qbo-customer-search">
|
||||
<%= text_field_tag :search, @search, class: 'customer-name', size: 40, placeholder: t(:label_search_customers),
|
||||
autocomplete: 'off', data: { autocomplete_url: '/customers/autocomplete' } %>
|
||||
<%= submit_tag l(:label_search), name: nil %>
|
||||
<% if @search.present? %>
|
||||
<%= link_to sprite_icon('reload', l(:button_clear)), customers_path, class: 'icon icon-reload' %>
|
||||
<% end %>
|
||||
</p>
|
||||
<% end %>
|
||||
|
||||
<div>
|
||||
<%= render partial: 'qbo/stats' %>
|
||||
</div>
|
||||
<% if @customers.empty? %>
|
||||
<p class="nodata"><%= @search.present? ? l(:label_no_customers, search: @search) : l(:label_no_data) %></p>
|
||||
<% else %>
|
||||
<% if @best_first %>
|
||||
<p class="info"><%= l(:text_customers_best_match, count: @customer_count) %></p>
|
||||
<% end %>
|
||||
<div class="autoscroll">
|
||||
<table class="list customers odd-even">
|
||||
<thead>
|
||||
<tr>
|
||||
<%= sort_header_tag('name', caption: l(:field_name)) %>
|
||||
<%= sort_header_tag('phone', caption: l(:label_primary_phone)) %>
|
||||
<%= sort_header_tag('mobile', caption: l(:label_mobile_phone)) %>
|
||||
<th><%= l(:label_issue_plural) %></th>
|
||||
<%= sort_header_tag('updated', caption: l(:field_updated_on), default_order: 'desc') %>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% @customers.each do |customer| %>
|
||||
<tr class="<%= cycle('odd', 'even') %>">
|
||||
<td class="name"><%= link_to customer.name, customer_path(customer.id) %></td>
|
||||
<td class="phone"><%= phone.call(customer.phone_number) %></td>
|
||||
<td class="phone"><%= phone.call(customer.mobile_phone_number) %></td>
|
||||
<td class="issues"><%= @issue_counts[customer.id] || 0 %></td>
|
||||
<td class="updated_on"><%= format_time(customer.updated_at) if customer.updated_at %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<span class="pagination"><%= pagination_links_full @customer_pages, @customer_count %></span>
|
||||
<% end %>
|
||||
|
||||
<p class="qbo-customer-stats"><%= render partial: 'qbo/stats' %></p>
|
||||
|
||||
<style>
|
||||
table.customers td.name { text-align: left; }
|
||||
table.customers td.phone, table.customers td.updated_on { white-space: nowrap; }
|
||||
table.customers td.issues { width: 1%; text-align: center; }
|
||||
.qbo-customer-search input { vertical-align: middle; }
|
||||
</style>
|
||||
@@ -1,11 +1,16 @@
|
||||
<div class="contextual">
|
||||
<% html_title @customer.to_s %>
|
||||
|
||||
<h2><%= link_to l(:label_customers), customers_path %> » <%= @customer.to_s %></h2>
|
||||
|
||||
<%# Under the title rather than beside it, so a long name and the many actions don't crowd each other %>
|
||||
<div class="contextual qbo-under-title">
|
||||
<%# New issue for this customer; picks up what's ticked on this page (an estimate, other plugins' items) %>
|
||||
<%= link_to sprite_icon('add', l(:label_new_issue)), new_issue_path(issue: { customer_id: @customer.id }),
|
||||
id: 'dynamic-new-issue-link', class: 'icon icon-add', target: :_blank %>
|
||||
<%# Plugins add their customer actions here (e.g. redmine_qbo_calendar's Add appointment) %>
|
||||
<%= call_hook :view_customers_show_contextual, { customer: @customer } %>
|
||||
<%# Estimates, invoices and payments are handled here, each shown to users with its permission. The customer's
|
||||
name below links to their QuickBooks account page as a fallback. %>
|
||||
<%# Estimates, invoices and payments are handled here, each shown to users with its permission; Open in
|
||||
QuickBooks goes to their QuickBooks account page for anything else. %>
|
||||
<% if RedmineQboBilling.writer? %>
|
||||
<%= render partial: 'qbo_estimates/customer_link', locals: { customer: @customer } %>
|
||||
<% end %>
|
||||
@@ -22,9 +27,10 @@
|
||||
<%= link_to sprite_icon('edit', l(:button_edit)), edit_customer_path(@customer),
|
||||
class: 'icon icon-edit', accesskey: accesskey(:edit) %>
|
||||
<% end %>
|
||||
<%= link_to sprite_icon('link', l(:button_open_in_quickbooks)),
|
||||
"https://#{RedmineQbo.sandbox_mode? ? 'sandbox' : 'app'}.qbo.intuit.com/app/customerdetail?nameId=#{@customer.id}",
|
||||
class: 'icon icon-link', target: :_blank, rel: 'noopener' %>
|
||||
</div>
|
||||
|
||||
<h2><%=t(:field_customer)%> #<%= @customer.id %> - <%= link_to @customer.to_s, "https://#{RedmineQbo.sandbox_mode? ? "sandbox" : "app"}.qbo.intuit.com/app/customerdetail?nameId=#{@customer.id}", target: :_blank %> </h2>
|
||||
<div class="issue">
|
||||
|
||||
<div class="splitcontent">
|
||||
@@ -52,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">
|
||||
|
||||
@@ -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 %>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,11 @@
|
||||
<% html_title l(:label_qbo_drafts) %>
|
||||
|
||||
<h2><%= link_to l(:label_customers), customers_path %> » <%= 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 %>
|
||||
@@ -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>
|
||||
@@ -283,6 +302,15 @@
|
||||
<%= 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">
|
||||
<% 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 %>
|
||||
<% 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',
|
||||
|
||||
@@ -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 %>
|
||||
|
||||
@@ -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 {
|
||||
@@ -415,10 +427,18 @@ $(function () {
|
||||
});
|
||||
|
||||
$('#qbo-estimate-clear-lines').on('click', function () {
|
||||
if (!window.confirm($(this).data('confirmText'))) return;
|
||||
rows().remove();
|
||||
addRow(); addRow();
|
||||
changed();
|
||||
function clearLines() {
|
||||
rows().remove();
|
||||
addRow(); addRow();
|
||||
changed();
|
||||
}
|
||||
// redmine_dark_mode asks in a dark dialog on dark pages; otherwise the browser's own box
|
||||
var message = $(this).data('confirmText');
|
||||
if (window.RedmineDarkMode && window.RedmineDarkMode.confirm) {
|
||||
window.RedmineDarkMode.confirm(message, clearLines);
|
||||
} else if (window.confirm(message)) {
|
||||
clearLines();
|
||||
}
|
||||
});
|
||||
|
||||
// Drag lines by the handle to reorder them; they're saved in table order
|
||||
@@ -446,7 +466,9 @@ $(function () {
|
||||
var id = $(this).val();
|
||||
if (!id) return;
|
||||
dirty = true;
|
||||
$.getJSON($form.data('customerInfoUrl'), { customer_id: id }).done(function (info) {
|
||||
$.getJSON($form.data('customerInfoUrl'), { customer_id: id, document: $form.data('document') }).done(function (info) {
|
||||
// A new invoice's open issues notice follows the customer
|
||||
if (info.open_issues_html !== undefined) $('#qbo-open-issues').replaceWith(info.open_issues_html);
|
||||
// Replace the email only if it was the previous customer's (or empty)
|
||||
if (!$email.val().trim() || $email.val() === loadedEmail) $email.val(info.email || '');
|
||||
loadedEmail = info.email || '';
|
||||
@@ -548,6 +570,24 @@ $(function () {
|
||||
return ids;
|
||||
};
|
||||
|
||||
// Pairs imported time with the invoice lines ticked under "Replace these lines": first by description,
|
||||
// since issues created from an estimate take the line's description as their subject and the time names
|
||||
// it ("Install #134: Install Lift Kit" <-> "Install Lift Kit"); what's left is paired in order.
|
||||
// Returns { pairs: [{ time, line }], extraTimes: [...], extraLines: [...] }.
|
||||
var pairTimeWithLines = function (times, lines) {
|
||||
var norm = function (text) { return String(text || '').split('\n')[0].toLowerCase().replace(/\s+/g, ' ').trim(); };
|
||||
var subject = function (activity) { return norm(String(activity.description || '').replace(/^[^\n]*?#\d+:\s*/, '')); };
|
||||
var lineText = function (line) { return norm($(line).find('.qbo-line-description-input').val()); };
|
||||
var freeTimes = times.slice(), freeLines = [], pairs = [];
|
||||
lines.forEach(function (line) {
|
||||
var text = lineText(line);
|
||||
var i = text ? freeTimes.findIndex(function (t) { return subject(t) === text; }) : -1;
|
||||
if (i >= 0) { pairs.push({ time: freeTimes[i], line: line }); freeTimes.splice(i, 1); } else { freeLines.push(line); }
|
||||
});
|
||||
while (freeTimes.length && freeLines.length) pairs.push({ time: freeTimes.shift(), line: freeLines.shift() });
|
||||
return { pairs: pairs, extraTimes: freeTimes, extraLines: freeLines };
|
||||
};
|
||||
|
||||
// Rows go after the last filled line, above the spare empty rows
|
||||
var insertAfterFilled = function ($rows) {
|
||||
var $filled = rows().filter(function () { return !rowIsBlank($(this)); });
|
||||
@@ -642,15 +682,24 @@ $(function () {
|
||||
// Kept so the import can be undone before saving (clones keep what was typed)
|
||||
undoState = { rows: rows().clone(), linked: $('#qbo-linked-estimates').children().clone() };
|
||||
|
||||
// Time goes where the first ticked line was; the ticked lines are removed
|
||||
// Each time entry replaces one ticked line, in that line's place (see pairTimeWithLines). Time left over
|
||||
// goes after the last replaced line; ticked lines left over are removed (ticked means replace).
|
||||
if (times.length) {
|
||||
var $timeRows = $(times.map(function (activity) {
|
||||
return makeRow($.extend({}, activity, { time_activity_id: activity.id }))[0];
|
||||
}));
|
||||
var $replaced = $('#qbo-import-replace input:checked').map(function () { return $(this).data('row')[0]; });
|
||||
var $anchor = rows().filter(function () { return $replaced.index(this) >= 0; }).first();
|
||||
if ($anchor.length) { $anchor.before($timeRows); } else { insertAfterFilled($timeRows); }
|
||||
$replaced.remove();
|
||||
var ticked = $('#qbo-import-replace input:checked').map(function () { return $(this).data('row')[0]; }).get();
|
||||
ticked = rows().get().filter(function (row) { return ticked.indexOf(row) >= 0; }); // table order
|
||||
var pairing = pairTimeWithLines(times, ticked);
|
||||
var timeRow = function (activity) { return makeRow($.extend({}, activity, { time_activity_id: activity.id })); };
|
||||
var $last = $();
|
||||
pairing.pairs.forEach(function (pair) {
|
||||
var $row = timeRow(pair.time);
|
||||
$(pair.line).replaceWith($row);
|
||||
if (!$last.length || $row.index() > $last.index()) $last = $row;
|
||||
});
|
||||
pairing.extraLines.forEach(function (line) { $(line).remove(); });
|
||||
if (pairing.extraTimes.length) {
|
||||
var $extra = $(pairing.extraTimes.map(function (activity) { return timeRow(activity)[0]; }));
|
||||
if ($last.length) { $last.after($extra); } else { insertAfterFilled($extra); }
|
||||
}
|
||||
}
|
||||
|
||||
// Each estimate's lines go right after the time for the same issue (e.g. lineitems' "Added from:
|
||||
@@ -706,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; });
|
||||
|
||||
@@ -724,6 +783,7 @@ $(function () {
|
||||
}
|
||||
// Math still in a box is worked out before saving
|
||||
rows().each(function () { tidyNumbers($(this)); });
|
||||
tidyDiscount();
|
||||
dirty = false;
|
||||
});
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
|
||||
@@ -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 } %>
|
||||
@@ -0,0 +1,17 @@
|
||||
<%# A new invoice's customer still has open issues (work orders), so they're not left behind once billed.
|
||||
Replaced when the customer is changed (customer_info's open_issues_html). %>
|
||||
<%
|
||||
issues = customer ? customer.issues.open.visible.order(id: :desc).to_a : []
|
||||
%>
|
||||
<div id="qbo-open-issues">
|
||||
<% if issues.any? %>
|
||||
<div class="warning qbo-estimate-notice">
|
||||
<%= l(:text_invoice_customer_open_issues, count: issues.size) %>
|
||||
<ul>
|
||||
<% issues.each do |issue| %>
|
||||
<li><%= link_to_issue(issue, truncate: 60) %> (<%= issue.status %>)</li>
|
||||
<% end %>
|
||||
</ul>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
@@ -1,4 +1,6 @@
|
||||
<% html_title l(:label_new_invoice) %>
|
||||
|
||||
<%= 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_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, draft: @draft } %>
|
||||
@@ -0,0 +1,2 @@
|
||||
<%# A saved payment, on the same page as Receive payment %>
|
||||
<%= render template: 'qbo_payments/new' %>
|
||||
@@ -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>
|
||||
|
||||
@@ -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 %> »
|
||||
<% if customer %><%= link_to customer.name, customer_path(customer) %> »<% end %>
|
||||
<%= l(:button_receive_payment) %>
|
||||
<% if editing %>
|
||||
<%= link_to l(:label_payments), qbo_payments_path(customer_id: @form.customer_id) %> »
|
||||
<% 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 %>
|
||||
|
||||
|
||||
@@ -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' %>
|
||||
|
||||
@@ -7,6 +7,44 @@
|
||||
<% bar = ->(value, max) { max > 0 ? (value.to_f / max * 100).round(1) : 0 } %>
|
||||
<% fmt_hours = ->(h) { format('%.1f', h.to_f) } %>
|
||||
<% pct = ->(v) { v.nil? ? '–' : "#{v}%" } %>
|
||||
<%# Line charts: a label and a tooltip title per point, from the chart's granularity %>
|
||||
<% chart = @report.chart %>
|
||||
<% months_abbr = ::I18n.t('date.abbr_month_names') %>
|
||||
<% days_abbr = ::I18n.t('date.abbr_day_names') %>
|
||||
<% one_year = @report.from.year == @report.to.year %>
|
||||
<% point_label = lambda do |date|
|
||||
case chart[:granularity]
|
||||
when :day then "#{days_abbr[date.wday]} #{date.day}"
|
||||
when :week then "#{months_abbr[date.month]} #{date.day}"
|
||||
else one_year ? months_abbr[date.month] : "#{months_abbr[date.month]} #{date.year}"
|
||||
end
|
||||
end %>
|
||||
<% point_title = lambda do |first, last|
|
||||
case chart[:granularity]
|
||||
when :day then format_date(first)
|
||||
when :week then "#{format_date(first)} – #{format_date(last)}"
|
||||
else "#{::I18n.t('date.month_names')[first.month]} #{first.year}"
|
||||
end
|
||||
end %>
|
||||
<% previous_ends = chart[:previous_points].each_with_index.map { |p, i| Date.parse(p) + (Date.parse(chart[:ends][i]) - Date.parse(chart[:points][i])) } %>
|
||||
<% chart_points = {
|
||||
labels: chart[:points].map { |p| point_label.call(Date.parse(p)) },
|
||||
titles: chart[:points].each_with_index.map { |p, i| point_title.call(Date.parse(p), Date.parse(chart[:ends][i])) },
|
||||
previous_titles: chart[:previous_points].each_with_index.map { |p, i| point_title.call(Date.parse(p), previous_ends[i]) },
|
||||
last_year: l(:label_report_last_year)
|
||||
} %>
|
||||
<% chart_series = lambda do |keys|
|
||||
keys.map do |key, label, color|
|
||||
{ label: label, color: color, current: chart[:current][key], previous: chart[:previous][key] }
|
||||
end
|
||||
end %>
|
||||
<% sales_series = chart_series.call([[:estimates, l(:label_report_estimates_written), '#628db6'],
|
||||
[:invoices, l(:label_report_invoices_written), '#e8a33d'],
|
||||
[:payments, l(:label_report_payments_received), '#5aa05a']]) %>
|
||||
<% hours_series = chart_series.call([[:estimate_hours, l(:label_report_estimate_hours), '#628db6'],
|
||||
[:issue_hours, l(:label_report_issue_hours), '#9b7fc0'],
|
||||
[:invoice_hours, l(:label_report_invoice_hours), '#e8a33d'],
|
||||
[:spent_hours, l(:label_report_spent_hours), '#5aa05a']]) %>
|
||||
|
||||
<h2><%= l(:label_business_report) %></h2>
|
||||
|
||||
@@ -22,10 +60,40 @@
|
||||
<%= date_field_tag 'to', @report.to.iso8601, id: 'qbo-report-to' %>
|
||||
</span>
|
||||
<%= submit_tag l(:button_apply), name: nil %>
|
||||
<label class="qbo-report-compare">
|
||||
<%= check_box_tag 'compare', '1', @compare, id: 'qbo-report-compare' %>
|
||||
<%= l(:label_report_compare_last_year) %>
|
||||
</label>
|
||||
<%# Projects for the issues and spent time; the blank value sends project_ids when none are picked (every project) %>
|
||||
<div class="qbo-report-projects">
|
||||
<label for="qbo-report-project-ids"><%= l(:label_project_plural) %></label>
|
||||
<%= hidden_field_tag 'project_ids[]', '', id: nil %>
|
||||
<%= select_tag 'project_ids[]',
|
||||
project_tree_options_for_select(@projects, selected: @projects.select { |p| @project_ids.include?(p.id) }),
|
||||
multiple: true, size: [[@projects.size, 3].max, 8].min, id: 'qbo-report-project-ids' %>
|
||||
<span class="qbo-report-projects-options">
|
||||
<em class="info"><%= l(:text_report_projects) %></em>
|
||||
<label>
|
||||
<%= check_box_tag 'save_projects', '1', false, id: 'qbo-report-save-projects' %>
|
||||
<%= l(:label_report_remember_projects) %>
|
||||
</label>
|
||||
<% if @saved_project_ids.any? %>
|
||||
<em class="info"><%= l(:text_report_saved_projects, projects: @projects.select { |p| @saved_project_ids.include?(p.id) }.map(&:name).join(', ')) %></em>
|
||||
<% end %>
|
||||
</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<% end %>
|
||||
|
||||
<p class="qbo-report-range"><%= format_date(@report.from) %> – <%= format_date(@report.to) %></p>
|
||||
<p class="qbo-report-range">
|
||||
<%= format_date(@report.from) %> – <%= format_date(@report.to) %>
|
||||
<% if @report.projects_filtered? %>
|
||||
· <%= l(:label_project_plural) %>: <%= @projects.select { |p| @project_ids.include?(p.id) }.map(&:name).join(', ') %>
|
||||
<% end %>
|
||||
</p>
|
||||
<% if @report.projects_filtered? %>
|
||||
<p class="info qbo-report-projects-note"><%= l(:text_report_projects_filtered) %></p>
|
||||
<% end %>
|
||||
|
||||
<% if Array(@syncing).any? %>
|
||||
<% sync_labels = { 'Estimate' => l(:label_estimates), 'Invoice' => l(:label_invoices), 'Payment' => l(:label_payments) } %>
|
||||
@@ -58,6 +126,9 @@
|
||||
<div class="splitcontent">
|
||||
<div class="splitcontentleft">
|
||||
<h3><%= l(:label_report_money) %></h3>
|
||||
<div class="qbo-report-chart">
|
||||
<canvas id="qbo-chart-sales" data-kind="money" data-series="<%= sales_series.to_json %>"></canvas>
|
||||
</div>
|
||||
<table class="list qbo-report">
|
||||
<tbody>
|
||||
<% [[:estimates, l(:label_report_estimates_written)], [:invoices, l(:label_report_invoices_written)],
|
||||
@@ -79,6 +150,9 @@
|
||||
|
||||
<div class="splitcontentright">
|
||||
<h3><%= l(:label_report_hours) %></h3>
|
||||
<div class="qbo-report-chart">
|
||||
<canvas id="qbo-chart-hours" data-kind="hours" data-series="<%= hours_series.to_json %>"></canvas>
|
||||
</div>
|
||||
<table class="list qbo-report">
|
||||
<tbody>
|
||||
<% [[:estimate_hours, l(:label_report_estimate_hours)], [:issue_hours, l(:label_report_issue_hours)],
|
||||
@@ -181,6 +255,12 @@
|
||||
table.qbo-report-months .hours-start { border-left: 2px solid #ddd; }
|
||||
table.qbo-report-months tfoot td { border-top: 2px solid #ccc; }
|
||||
#qbo-report-form select, #qbo-report-form input { vertical-align: middle; }
|
||||
#qbo-report-form .qbo-report-compare { margin-left: 12px; white-space: nowrap; }
|
||||
#qbo-report-form .qbo-report-projects { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 6px 10px; margin-top: 8px; }
|
||||
#qbo-report-form .qbo-report-projects select { min-width: 220px; max-width: 100%; }
|
||||
#qbo-report-form .qbo-report-projects-options { display: flex; flex-direction: column; gap: 4px; }
|
||||
#qbo-report-form .qbo-report-projects-options label { white-space: nowrap; }
|
||||
.qbo-report-chart { position: relative; height: 260px; margin: 4px 4px 16px; }
|
||||
</style>
|
||||
|
||||
<%= javascript_tag do %>
|
||||
@@ -190,4 +270,168 @@
|
||||
$dates.on('change', function() { $period.val('custom'); });
|
||||
$period.on('change', function() { if ($period.val() !== 'custom') { $('#qbo-report-form').submit(); } });
|
||||
});
|
||||
|
||||
// Line charts (Chart.js 4): the same figures and colors as the bars, a point per day,
|
||||
// week or month. "Compare with last year" adds last year's lines, dashed and faded, without reloading.
|
||||
(function() {
|
||||
var points = <%= raw chart_points.to_json %>;
|
||||
// The currency layout the tables use, e.g. "$%n"
|
||||
var currencyFormat = <%= raw number_to_currency(0, precision: 0).to_s.sub('0', '%n').to_json %>;
|
||||
var charts = [];
|
||||
|
||||
function money(v, decimals) {
|
||||
var n = Number(v || 0).toLocaleString(undefined, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
|
||||
return currencyFormat.replace('%n', n);
|
||||
}
|
||||
function hours(v) { return Number(v || 0).toFixed(1); }
|
||||
function faded(hex) {
|
||||
var n = parseInt(hex.slice(1), 16);
|
||||
return 'rgba(' + (n >> 16 & 255) + ',' + (n >> 8 & 255) + ',' + (n & 255) + ',0.45)';
|
||||
}
|
||||
|
||||
// Grid lines and text from the page's colours, so a dark mode (e.g. redmine_dark_mode) can set
|
||||
// --qbo-chart-grid and --qbo-chart-text; Chart.js' own colours otherwise
|
||||
function chartColors() {
|
||||
var style = getComputedStyle(document.documentElement);
|
||||
return { grid: style.getPropertyValue('--qbo-chart-grid').trim() || 'rgba(0,0,0,0.1)',
|
||||
text: style.getPropertyValue('--qbo-chart-text').trim() || '#666' };
|
||||
}
|
||||
function applyColors(chart) {
|
||||
var c = chartColors();
|
||||
['x', 'y'].forEach(function(axis) {
|
||||
var scale = chart.options.scales[axis];
|
||||
scale.grid.color = c.grid;
|
||||
scale.border.color = c.grid;
|
||||
scale.ticks.color = c.text;
|
||||
});
|
||||
chart.options.plugins.legend.labels.color = c.text;
|
||||
}
|
||||
|
||||
function draw(Chart, canvas, compare) {
|
||||
var series = JSON.parse(canvas.getAttribute('data-series'));
|
||||
var isMoney = canvas.getAttribute('data-kind') === 'money';
|
||||
var colors = chartColors();
|
||||
var datasets = [];
|
||||
series.forEach(function(s) {
|
||||
datasets.push({ label: s.label, data: s.current, borderColor: s.color, backgroundColor: s.color,
|
||||
fill: false, cubicInterpolationMode: 'monotone', pointRadius: 3, pointHoverRadius: 5, spanGaps: false, order: 1 });
|
||||
});
|
||||
series.forEach(function(s) {
|
||||
datasets.push({ label: s.label + ' (' + points.last_year + ')', data: s.previous, previous: true,
|
||||
borderColor: faded(s.color), backgroundColor: faded(s.color), borderDash: [6, 4],
|
||||
borderWidth: 2, fill: false, cubicInterpolationMode: 'monotone', pointRadius: 2, pointHoverRadius: 4,
|
||||
hidden: !compare, order: 2 });
|
||||
});
|
||||
return new Chart(canvas, {
|
||||
type: 'line',
|
||||
data: { labels: points.labels, datasets: datasets },
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: {
|
||||
// One entry per figure (clicking it hides this year's and last year's line), plus a single
|
||||
// dashed "last year" entry while comparing (clicking it turns comparing off)
|
||||
legend: {
|
||||
position: 'bottom',
|
||||
labels: {
|
||||
boxWidth: 12,
|
||||
color: colors.text,
|
||||
generateLabels: function(chart) {
|
||||
var items = Chart.defaults.plugins.legend.labels.generateLabels(chart).filter(function(item) {
|
||||
return !chart.data.datasets[item.datasetIndex].previous;
|
||||
});
|
||||
if (chart.data.datasets.some(function(ds) { return ds.previous && !ds.hidden; })) {
|
||||
items.push({ text: points.last_year, fillStyle: 'rgba(0,0,0,0)', strokeStyle: '#999', lineWidth: 2,
|
||||
lineDash: [4, 3], hidden: false, datasetIndex: -1 });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
},
|
||||
onClick: function(e, item, legend) {
|
||||
var chart = legend.chart;
|
||||
if (item.datasetIndex === -1) { $('#qbo-report-compare').prop('checked', false).trigger('change'); return; }
|
||||
var visible = !chart.isDatasetVisible(item.datasetIndex);
|
||||
chart.setDatasetVisibility(item.datasetIndex, visible);
|
||||
// last year's line follows (shown only while comparing)
|
||||
chart.getDatasetMeta(item.datasetIndex + series.length).hidden = visible ? null : true;
|
||||
chart.update();
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
callbacks: {
|
||||
title: function(items) {
|
||||
if (!items.length) { return ''; }
|
||||
var i = items[0].dataIndex, lines = [points.titles[i]];
|
||||
if (items.some(function(it) { return it.dataset.previous; })) {
|
||||
lines.push(points.last_year + ': ' + points.previous_titles[i]);
|
||||
}
|
||||
return lines;
|
||||
},
|
||||
label: function(item) {
|
||||
return item.dataset.label + ': ' + (isMoney ? money(item.raw, 2) : hours(item.raw));
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
x: { grid: { color: colors.grid }, border: { color: colors.grid }, ticks: { color: colors.text } },
|
||||
y: { beginAtZero: true, grid: { color: colors.grid }, border: { color: colors.grid },
|
||||
ticks: { color: colors.text, precision: isMoney ? 0 : 1, callback: function(v) { return isMoney ? money(v, 0) : v; } } }
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Chart.js from the module: its default export or a named one. Chart.js 2 has no register() and is skipped.
|
||||
function chartClass(mod) {
|
||||
var found = [mod && mod.default, mod && mod.Chart, mod && mod.default && mod.default.Chart];
|
||||
for (var i = 0; i < found.length; i++) {
|
||||
if (typeof found[i] === 'function' && typeof found[i].register === 'function') { return found[i]; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function setCompare(on) {
|
||||
charts.forEach(function(chart) {
|
||||
var n = chart.data.datasets.length / 2;
|
||||
for (var j = 0; j < n; j++) {
|
||||
chart.data.datasets[j + n].hidden = !on;
|
||||
// a figure hidden from the legend keeps last year's line hidden too
|
||||
chart.getDatasetMeta(j + n).hidden = chart.isDatasetVisible(j) ? null : true;
|
||||
}
|
||||
chart.update();
|
||||
});
|
||||
// Keep the choice in the address, so reloading or changing the period keeps it
|
||||
if (window.history && history.replaceState) {
|
||||
var url = new URL(window.location.href);
|
||||
if (on) { url.searchParams.set('compare', '1'); } else { url.searchParams.delete('compare'); }
|
||||
history.replaceState(null, '', url);
|
||||
}
|
||||
}
|
||||
|
||||
$(function() {
|
||||
var $compare = $('#qbo-report-compare');
|
||||
// Chart.js 4 ships with this plugin (assets/javascripts), so the charts don't depend on how Redmine or
|
||||
// other plugins provide it (redmine_indicator puts Chart.js 2 on every page)
|
||||
import(<%= raw asset_path('plugin_assets/redmine_qbo/chart-4.5.1.min.js').to_json %>).then(function(mod) {
|
||||
var Chart = chartClass(mod);
|
||||
if (!Chart) {
|
||||
console.warn('Business report: Chart.js did not load', Object.keys(mod || {}));
|
||||
$('.qbo-report-chart').hide();
|
||||
return;
|
||||
}
|
||||
$('.qbo-report-chart canvas').each(function() { charts.push(draw(Chart, this, $compare.is(':checked'))); });
|
||||
window.qboReportCharts = charts;
|
||||
}).catch(function(error) {
|
||||
console.warn('Business report: Chart.js did not load', error);
|
||||
$('.qbo-report-chart').hide();
|
||||
});
|
||||
$compare.on('change', function() { setCompare(this.checked); });
|
||||
// Switching between light and dark (redmine_dark_mode) recolours the charts
|
||||
document.addEventListener('redmine:color-scheme', function() {
|
||||
charts.forEach(function(chart) { applyColors(chart); chart.update('none'); });
|
||||
});
|
||||
});
|
||||
})();
|
||||
<% end %>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0"?>
|
||||
<!-- Activity icons (Tabler outline icons, MIT), in the layout of Redmine's own sprite -->
|
||||
<svg xmlns="http://www.w3.org/2000/svg" class="icon--sprite">
|
||||
<defs>
|
||||
<symbol viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" id="icon--qbo-estimate">
|
||||
<path d="M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"/>
|
||||
<path d="M9 5a2 2 0 0 1 2 -2h2a2 2 0 0 1 2 2a2 2 0 0 1 -2 2h-2a2 2 0 0 1 -2 -2z"/>
|
||||
<path d="M9 12h.01"/>
|
||||
<path d="M13 12h2"/>
|
||||
<path d="M9 16h.01"/>
|
||||
<path d="M13 16h2"/>
|
||||
</symbol>
|
||||
<symbol viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" id="icon--qbo-invoice">
|
||||
<path d="M14 3v4a1 1 0 0 0 1 1h4"/>
|
||||
<path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"/>
|
||||
<path d="M9 7h1"/>
|
||||
<path d="M9 13h6"/>
|
||||
<path d="M13 17h2"/>
|
||||
</symbol>
|
||||
<symbol viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" id="icon--qbo-payment">
|
||||
<path d="M7 11a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v6a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z"/>
|
||||
<path d="M12 14a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"/>
|
||||
<path d="M17 9v-2a2 2 0 0 0 -2 -2h-10a2 2 0 0 0 -2 2v6a2 2 0 0 0 2 2h2"/>
|
||||
</symbol>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.3 KiB |
+14
@@ -0,0 +1,14 @@
|
||||
/*!
|
||||
* Chart.js v4.5.1
|
||||
* https://www.chartjs.org
|
||||
* (c) 2025 Chart.js Contributors
|
||||
* Released under the MIT License
|
||||
*/
|
||||
function t(){}const e=(()=>{let t=0;return()=>t++})();function i(t){return null==t}function s(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function n(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function o(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function a(t,e){return o(t)?t:e}function r(t,e){return void 0===t?e:t}const l=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function h(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function c(t,e,i,o){let a,r,l;if(s(t))if(r=t.length,o)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;a<r;a++)e.call(i,t[a],a);else if(n(t))for(l=Object.keys(t),r=l.length,a=0;a<r;a++)e.call(i,t[l[a]],l[a])}function d(t,e){let i,s,n,o;if(!t||!e||t.length!==e.length)return!1;for(i=0,s=t.length;i<s;++i)if(n=t[i],o=e[i],n.datasetIndex!==o.datasetIndex||n.index!==o.index)return!1;return!0}function u(t){if(s(t))return t.map(u);if(n(t)){const e=Object.create(null),i=Object.keys(t),s=i.length;let n=0;for(;n<s;++n)e[i[n]]=u(t[i[n]]);return e}return t}function f(t){return-1===["__proto__","prototype","constructor"].indexOf(t)}function g(t,e,i,s){if(!f(t))return;const o=e[t],a=i[t];n(o)&&n(a)?p(o,a,s):e[t]=u(a)}function p(t,e,i){const o=s(e)?e:[e],a=o.length;if(!n(t))return t;const r=(i=i||{}).merger||g;let l;for(let e=0;e<a;++e){if(l=o[e],!n(l))continue;const s=Object.keys(l);for(let e=0,n=s.length;e<n;++e)r(s[e],t,l,i)}return t}function m(t,e){return p(t,e,{merger:x})}function x(t,e,i){if(!f(t))return;const s=e[t],o=i[t];n(s)&&n(o)?m(s,o):Object.prototype.hasOwnProperty.call(e,t)||(e[t]=u(o))}const b={"":t=>t,x:t=>t.x,y:t=>t.y};function _(t,e){const i=b[e]||(b[e]=function(t){const e=function(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function y(t){return t.charAt(0).toUpperCase()+t.slice(1)}const v=t=>void 0!==t,M=t=>"function"==typeof t,w=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};const k=Math.PI,S=2*k,P=S+k,D=Number.POSITIVE_INFINITY,O=k/180,C=k/2,A=k/4,T=2*k/3,L=Math.log10,E=Math.sign;function R(t,e,i){return Math.abs(t-e)<i}function I(t){const e=Math.round(t);t=R(t,e,t/1e3)?e:t;const i=Math.pow(10,Math.floor(L(t))),s=t/i;return(s<=1?1:s<=2?2:s<=5?5:10)*i}function F(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function z(t,e,i){let s,n,o;for(s=0,n=t.length;s<n;s++)o=t[s][i],isNaN(o)||(e.min=Math.min(e.min,o),e.max=Math.max(e.max,o))}function V(t){return t*(k/180)}function B(t){return t*(180/k)}function W(t){if(!o(t))return;let e=1,i=0;for(;Math.round(t*e)/e!==t;)e*=10,i++;return i}function N(t,e){const i=e.x-t.x,s=e.y-t.y,n=Math.sqrt(i*i+s*s);let o=Math.atan2(s,i);return o<-.5*k&&(o+=S),{angle:o,distance:n}}function H(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function j(t,e){return(t-e+P)%S-k}function $(t){return(t%S+S)%S}function Y(t,e,i,s){const n=$(t),o=$(e),a=$(i),r=$(o-n),l=$(a-n),h=$(n-o),c=$(n-a);return n===o||n===a||s&&o===a||r>l&&h<c}function U(t,e,i){return Math.max(e,Math.min(i,t))}function X(t,e,i,s=1e-6){return t>=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function q(t,e,i){i=i||(i=>t[i]<e);let s,n=t.length-1,o=0;for(;n-o>1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const K=(t,e,i,s)=>q(t,i,s?s=>{const n=t[s][e];return n<i||n===i&&t[s+1][e]===i}:s=>t[s][e]<i),G=(t,e,i)=>q(t,i,(s=>t[s][e]>=i));const J=["push","pop","shift","splice","unshift"];function Z(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(J.forEach((e=>{delete t[e]})),delete t._chartjs)}function Q(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const tt="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function et(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,tt.call(window,(()=>{s=!1,t.apply(e,i)})))}}const it=t=>"start"===t?"left":"end"===t?"right":"center",st=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2;function nt(t,e,s){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(K(h,d,u).lo,s?n:K(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!i(t[l.axis])));o-=Math.max(0,t)}o=U(o,0,n-1)}if(p){let t=Math.max(K(h,r.axis,f,!0).hi+1,s?0:K(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!i(t[l.axis])));t+=Math.max(0,e)}a=U(t,o,n)-o}else a=n-o}return{start:o,count:a}}function ot(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.Line truncated
|
||||
/*!
|
||||
* @kurkle/color v0.3.2
|
||||
* https://github.com/kurkle/color#readme
|
||||
* (c) 2023 Jukka Kurkela
|
||||
* Released under the MIT License
|
||||
*/
|
||||
function ut(t){return t+.5|0}const ft=(t,e,i)=>Math.max(Math.min(t,i),e);function gt(t){return ft(ut(2.55*t),0,255)}function pt(t){return ft(ut(255*t),0,255)}function mt(t){return ft(ut(t/2.55)/100,0,1)}function xt(t){return ft(ut(100*t),0,100)}const bt={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},_t=[..."0123456789ABCDEF"],yt=t=>_t[15&t],vt=t=>_t[(240&t)>>4]+_t[15&t],Mt=t=>(240&t)>>4==(15&t);function wt(t){var e=(t=>Mt(t.r)&&Mt(t.g)&&Mt(t.b)&&Mt(t.a))(t)?yt:vt;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const kt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function St(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Pt(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Dt(t,e,i){const s=St(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function Ot(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e<i?6:0):e===n?(i-t)/s+2:(t-e)/s+4}(e,i,s,h,n),r=60*r+.5),[0|r,l||0,a]}function Ct(t,e,i,s){return(Array.isArray(e)?t(e[0],e[1],e[2]):t(e,i,s)).map(pt)}function At(t,e,i){return Ct(St,t,e,i)}function Tt(t){return(t%360+360)%360}function Lt(t){const e=kt.exec(t);let i,s=255;if(!e)return;e[5]!==i&&(s=e[6]?gt(+e[5]):pt(+e[5]));const n=Tt(+e[2]),o=+e[3]/100,a=+e[4]/100;return i="hwb"===e[1]?function(t,e,i){return Ct(Dt,t,e,i)}(n,o,a):"hsv"===e[1]?function(t,e,i){return Ct(Pt,t,e,i)}(n,o,a):At(n,o,a),{r:i[0],g:i[1],b:i[2],a:s}}const Et={x:"dark",Z:"light",Y:"re",X:"blu",W:"gr",V:"medium",U:"slate",A:"ee",T:"ol",S:"or",B:"ra",C:"lateg",D:"ights",R:"in",Q:"turquois",E:"hi",P:"ro",O:"al",N:"le",M:"de",L:"yello",F:"en",K:"ch",G:"arks",H:"ea",I:"ightg",J:"wh"},Rt={OiceXe:"f0f8ff",antiquewEte:"faebd7",aqua:"ffff",aquamarRe:"7fffd4",azuY:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"0",blanKedOmond:"ffebcd",Xe:"ff",XeviTet:"8a2be2",bPwn:"a52a2a",burlywood:"deb887",caMtXe:"5f9ea0",KartYuse:"7fff00",KocTate:"d2691e",cSO:"ff7f50",cSnflowerXe:"6495ed",cSnsilk:"fff8dc",crimson:"dc143c",cyan:"ffff",xXe:"8b",xcyan:"8b8b",xgTMnPd:"b8860b",xWay:"a9a9a9",xgYF:"6400",xgYy:"a9a9a9",xkhaki:"bdb76b",xmagFta:"8b008b",xTivegYF:"556b2f",xSange:"ff8c00",xScEd:"9932cc",xYd:"8b0000",xsOmon:"e9967a",xsHgYF:"8fbc8f",xUXe:"483d8b",xUWay:"2f4f4f",xUgYy:"2f4f4f",xQe:"ced1",xviTet:"9400d3",dAppRk:"ff1493",dApskyXe:"bfff",dimWay:"696969",dimgYy:"696969",dodgerXe:"1e90ff",fiYbrick:"b22222",flSOwEte:"fffaf0",foYstWAn:"228b22",fuKsia:"ff00ff",gaRsbSo:"dcdcdc",ghostwEte:"f8f8ff",gTd:"ffd700",gTMnPd:"daa520",Way:"808080",gYF:"8000",gYFLw:"adff2f",gYy:"808080",honeyMw:"f0fff0",hotpRk:"ff69b4",RdianYd:"cd5c5c",Rdigo:"4b0082",ivSy:"fffff0",khaki:"f0e68c",lavFMr:"e6e6fa",lavFMrXsh:"fff0f5",lawngYF:"7cfc00",NmoncEffon:"fffacd",ZXe:"add8e6",ZcSO:"f08080",Zcyan:"e0ffff",ZgTMnPdLw:"fafad2",ZWay:"d3d3d3",ZgYF:"90ee90",ZgYy:"d3d3d3",ZpRk:"ffb6c1",ZsOmon:"ffa07a",ZsHgYF:"20b2aa",ZskyXe:"87cefa",ZUWay:"778899",ZUgYy:"778899",ZstAlXe:"b0c4de",ZLw:"ffffe0",lime:"ff00",limegYF:"32cd32",lRF:"faf0e6",magFta:"ff00ff",maPon:"800000",VaquamarRe:"66cdaa",VXe:"cd",VScEd:"ba55d3",VpurpN:"9370db",VsHgYF:"3cb371",VUXe:"7b68ee",VsprRggYF:"fa9a",VQe:"48d1cc",VviTetYd:"c71585",midnightXe:"191970",mRtcYam:"f5fffa",mistyPse:"ffe4e1",moccasR:"ffe4b5",navajowEte:"ffdead",navy:"80",Tdlace:"fdf5e6",Tive:"808000",TivedBb:"6b8e23",Sange:"ffa500",SangeYd:"ff4500",ScEd:"da70d6",pOegTMnPd:"eee8aa",pOegYF:"98fb98",pOeQe:"afeeee",pOeviTetYd:"db7093",papayawEp:"ffefd5",pHKpuff:"ffdab9",peru:"cd853f",pRk:"ffc0cb",plum:"dda0dd",powMrXe:"b0e0e6",purpN:"800080",YbeccapurpN:"663399",Yd:"ff0000",Psybrown:"bc8f8f",PyOXe:"4169e1",saddNbPwn:"8b4513",sOmon:"fa8072",sandybPwn:"f4a460",sHgYF:"2e8b57",sHshell:"fff5ee",siFna:"a0522d",silver:"c0c0c0",skyXe:"87ceeb",UXe:"6a5acd",UWay:"708090",UgYy:"708090",snow:"fffafa",sprRggYF:"ff7f",stAlXe:"4682b4",tan:"d2b48c",teO:"8080",tEstN:"d8bfd8",tomato:"ff6347",Qe:"40e0d0",viTet:"ee82ee",JHt:"f5deb3",wEte:"ffffff",wEtesmoke:"f5f5f5",Lw:"ffff00",LwgYF:"9acd32"};let It;function Ft(t){It||(It=function(){const t={},e=Object.keys(Rt),i=Object.keys(Et);let s,n,o,a,r;for(s=0;s<e.length;s++){for(a=r=e[s],n=0;n<i.length;n++)o=i[n],r=r.replace(o,Et[o]);o=parseInt(Rt[a],16),t[r]=[o>>16&255,o>>8&255,255&o]}return t}(),It.transparent=[0,0,0,0]);const e=It[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const zt=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Vt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Bt=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Wt(t,e,i){if(t){let s=Ot(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=ALine truncated
|
||||
@@ -2,4 +2,18 @@
|
||||
.ui-autocomplete .autocomplete-meta {
|
||||
color: #888;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
}
|
||||
/* Contextual links on their own line under the page title (customer and vehicle pages), where a long title and
|
||||
many links would otherwise crowd each other */
|
||||
#content .contextual.qbo-under-title {
|
||||
float: none;
|
||||
text-align: right;
|
||||
white-space: normal;
|
||||
margin: -4px 0 10px;
|
||||
padding-left: 0;
|
||||
}
|
||||
|
||||
/* Estimates, invoices and payments on the activity page belong to no project: no " - " after an empty name */
|
||||
div#activity span.project:empty:after {
|
||||
content: none;
|
||||
}
|
||||
+68
-2
@@ -65,7 +65,8 @@ en:
|
||||
label_new_customer: "New Customer"
|
||||
label_new_issue: "New Issue"
|
||||
label_qbo_never_synced: "Never Synced"
|
||||
label_no_customers: "There are no customers matching the search term(s)."
|
||||
label_no_customers: "No customers match \"%{search}\"."
|
||||
text_customers_best_match: "%{count} best matches, closest first. Click a column to sort them by it instead."
|
||||
label_no_estimates: "No Estimates"
|
||||
label_no_invoices: "No Invoices"
|
||||
label_oauth2_refresh_token_expires_at: "Refresh Token Expires At"
|
||||
@@ -116,6 +117,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"
|
||||
|
||||
@@ -128,6 +132,33 @@ 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"
|
||||
|
||||
@@ -148,6 +179,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)"
|
||||
@@ -255,8 +294,11 @@ en:
|
||||
notice_invoice_sent: "Invoice #%{number} emailed to %{email}"
|
||||
text_email_invoice_confirmation: "Email invoice #%{number} to %{email}?"
|
||||
text_invoice_from_estimate: "Made from estimate #%{number}. The estimate is closed when the invoice is saved."
|
||||
text_invoice_customer_open_issues:
|
||||
one: "This customer has an open issue. Make sure its work is finished and billed so it isn't left open:"
|
||||
other: "This customer has %{count} open issues. Make sure their work is finished and billed so none are left open:"
|
||||
text_line_bills_time: "Bills a QuickBooks time activity; saving marks the time as billed"
|
||||
text_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). The time goes where the first ticked line is."
|
||||
text_replace_lines: "Tick the lines the time replaces (e.g. the estimate's labor lines). Each time entry takes the place of the line with its issue's description (e.g. Install Lift Kit), then any others in order."
|
||||
|
||||
# Issues from estimates (moved from redmine_qbo_calendar)
|
||||
button_create_estimate_issues_submit: "Create issues"
|
||||
@@ -288,6 +330,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"
|
||||
@@ -309,6 +357,8 @@ en:
|
||||
permission_view_business_reports: "View business reports"
|
||||
label_business_report: "Business report"
|
||||
label_report_period: "Period"
|
||||
label_report_period_this_week: "This week"
|
||||
label_report_period_last_week: "Last week"
|
||||
label_report_period_this_month: "This month"
|
||||
label_report_period_last_month: "Last month"
|
||||
label_report_period_this_quarter: "This quarter"
|
||||
@@ -319,6 +369,8 @@ en:
|
||||
label_report_money: "Sales"
|
||||
label_report_hours: "Hours"
|
||||
label_report_by_month: "By month"
|
||||
label_report_compare_last_year: "Compare with last year"
|
||||
label_report_last_year: "last year"
|
||||
label_report_estimates_written: "Estimates written"
|
||||
label_report_invoices_written: "Invoices written"
|
||||
label_report_payments_received: "Payments received"
|
||||
@@ -339,6 +391,10 @@ en:
|
||||
text_qbo_sync_queued: "waiting to sync"
|
||||
text_report_needs_sync: "%{count} estimates or invoices in this period don't have their total or hours yet. Run a full sync from QuickBooks to fill them in."
|
||||
text_report_notes: "Estimates, invoices and payments count by their QuickBooks date; their hours are the quantities of the labor products/services. Issues' estimated time counts issues created in the period, without subtasks. Spent time counts time logged in the period."
|
||||
label_report_remember_projects: "Remember these projects"
|
||||
text_report_projects: "For issues' estimated time and spent time. None picked: every project. Ctrl/Cmd-click to pick several."
|
||||
text_report_saved_projects: "Opens with: %{projects}"
|
||||
text_report_projects_filtered: "Only issues' estimated time and spent time are limited to these projects. Estimates, invoices and payments come from QuickBooks, which has no projects, so they cover the whole business (and so does the CPI's invoiced hours)."
|
||||
notice_payment_not_found: "Payment not found in QuickBooks"
|
||||
notice_payment_saved: "Payment of %{amount} saved in QuickBooks"
|
||||
text_no_payment_methods: "QuickBooks' payment methods couldn't be read. Check the QuickBooks connection."
|
||||
@@ -346,3 +402,13 @@ en:
|
||||
text_payment_pick_invoices: "Tick invoices to fill in the amount and pay just those. With none ticked, the payment goes on the oldest invoices first."
|
||||
text_payment_reference: "e.g. the check number"
|
||||
text_payment_unapplied_deposit: "Not applied to any invoice: it's a credit on the customer's account."
|
||||
|
||||
# Activity page
|
||||
label_qbo_estimate_plural: "Estimates"
|
||||
label_qbo_invoice_plural: "Invoices"
|
||||
label_qbo_payment_plural: "Payments"
|
||||
label_activity_estimate: "Estimate #%{number}: %{customer}"
|
||||
label_activity_invoice: "Invoice #%{number}: %{customer}"
|
||||
label_activity_payment: "Payment from %{customer}: %{amount}"
|
||||
text_activity_invoice_owed: "%{amount} owed"
|
||||
text_activity_payment_unapplied: "%{amount} not applied to an invoice"
|
||||
+4
-1
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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.4'
|
||||
version '2026.11.16'
|
||||
url 'https://github.com/rickbarrette/redmine_qbo'
|
||||
author_url 'https://barrettefabrication.com'
|
||||
settings default: {empty: true}, partial: 'qbo/settings'
|
||||
@@ -27,9 +27,6 @@ Redmine::Plugin.register :redmine_qbo do
|
||||
User.safe_attributes :employee_id
|
||||
TimeEntry.safe_attributes :billed
|
||||
|
||||
# set per_page globally
|
||||
WillPaginate.per_page = 20
|
||||
|
||||
# Global Permissions
|
||||
# autocomplete and the filter_* actions feed the customer, estimate and invoice pickers on issue forms
|
||||
permission :view_customers, { customers: [:index, :show, :autocomplete,
|
||||
@@ -43,18 +40,30 @@ 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)
|
||||
|
||||
# Estimates, invoices and payments on the activity page (QboActivity): the overall page only, for users with
|
||||
# View customers or Write estimates / invoices, and View or Receive payments
|
||||
# (plugin: picks their icons from this plugin's sprite, assets/images/icons.svg)
|
||||
activity_provider :qbo_estimates, class_name: 'Estimate', plugin: :redmine_qbo
|
||||
activity_provider :qbo_invoices, class_name: 'Invoice', plugin: :redmine_qbo
|
||||
activity_provider :qbo_payments, class_name: 'Payment', plugin: :redmine_qbo
|
||||
|
||||
# Register top menu items
|
||||
menu :top_menu, :customers, { controller: :customers, action: :index }, caption: :label_customers, if: Proc.new {User.current.allowed_to?(:view_customers, nil, global: true)}
|
||||
menu :top_menu, :qbo_reports, { controller: :qbo_reports, action: :index }, caption: :label_business_report,
|
||||
|
||||
@@ -18,11 +18,16 @@ module RedmineQbo
|
||||
IssueQuery.prepend RedmineQbo::Patches::QueryPatch
|
||||
TimeEntryQuery.prepend RedmineQbo::Patches::TimeEntryQueryPatch
|
||||
|
||||
# === Activity: estimates, invoices and payments, for users who may see them ===
|
||||
Redmine::Activity::Fetcher.prepend RedmineQbo::Patches::ActivityFetcherPatch
|
||||
|
||||
# === Controllers ===
|
||||
RedmineQbo::Patches::IssuesControllerPatch.apply
|
||||
RedmineQbo::Patches::AttachmentsControllerPatch.apply
|
||||
|
||||
# === Helpers / Exports ===
|
||||
IssuesHelper.prepend RedmineQbo::Patches::IssuesHelperPatch
|
||||
QueriesHelper.prepend RedmineQbo::Patches::QueriesHelperPatch
|
||||
Redmine::Export::PDF::IssuesPdfHelper.prepend RedmineQbo::Patches::PdfPatch
|
||||
|
||||
# === Hooks ===
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#The MIT License (MIT)
|
||||
#
|
||||
#Copyright (c) 2016 - 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
|
||||
# The activity page lists every activity type for the whole site, and a project's page those its members may
|
||||
# see. QuickBooks estimates, invoices and payments (QboActivity) belong to no project: they're kept to the
|
||||
# overall page, and to users with one of their permissions, so nobody gets a checkbox for activity they can't see.
|
||||
module ActivityFetcherPatch
|
||||
def event_types
|
||||
return @event_types if @qbo_activity_checked
|
||||
|
||||
@qbo_activity_checked = true
|
||||
@event_types = super.select do |event_type|
|
||||
providers = Redmine::Activity.providers[event_type].map(&:constantize)
|
||||
qbo = providers.select { |provider| provider.respond_to?(:qbo_activity_visible_to?) }
|
||||
qbo.empty? || (project.nil? && qbo.any? { |provider| provider.qbo_activity_visible_to?(user) })
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,69 @@
|
||||
#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
|
||||
# Shows the customer and estimate by name, and invoices attached by the QuickBooks webhook, in an
|
||||
# issue's history, emails and PDF. Redmine records the customer and estimate by id, like its own
|
||||
# fields, but only looks up names for the fields it knows about. The ids stay in the database, so
|
||||
# existing history entries show names too.
|
||||
module IssuesHelperPatch
|
||||
JOURNAL_NAMED_FIELDS = { 'customer_id' => 'Customer', 'estimate_id' => 'Estimate' }.freeze
|
||||
|
||||
def show_detail(detail, no_html = false, options = {})
|
||||
return qbo_invoice_detail(detail, no_html, options) if detail.property == 'invoice'
|
||||
|
||||
model = detail.property == 'attr' && JOURNAL_NAMED_FIELDS[detail.prop_key]
|
||||
return super unless model
|
||||
|
||||
# Hand Redmine a copy with names in place of ids, so it formats it like any other change
|
||||
named = JournalDetail.new(property: detail.property, prop_key: detail.prop_key,
|
||||
old_value: qbo_journal_name(model, detail.old_value),
|
||||
value: qbo_journal_name(model, detail.value))
|
||||
named.id = detail.id
|
||||
named.journal_id = detail.journal_id
|
||||
super(named, no_html, options)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# "Invoice 1042 added", recorded when the QuickBooks webhook attaches an invoice to the issue
|
||||
# (see InvoiceAttachmentService). The number links to the invoice PDF while the invoice exists.
|
||||
def qbo_invoice_detail(detail, no_html, options)
|
||||
label = l(:field_invoice)
|
||||
value = detail.value
|
||||
old_value = detail.old_value
|
||||
|
||||
unless no_html
|
||||
label = content_tag('strong', label)
|
||||
if value.present?
|
||||
value = Invoice.exists?(detail.prop_key) ? link_to(value, invoice_url(detail.prop_key, only_path: options[:only_path] != false)) : content_tag('i', value)
|
||||
end
|
||||
old_value = content_tag('del', content_tag('i', old_value)) if old_value.present?
|
||||
end
|
||||
|
||||
if detail.value.present?
|
||||
l(:text_journal_added, label: label, value: value).html_safe
|
||||
else
|
||||
l(:text_journal_deleted, label: label, old: old_value).html_safe
|
||||
end
|
||||
end
|
||||
|
||||
# The record's name, or the id when it no longer exists. Cached for the request, since a
|
||||
# history can mention the same customer many times.
|
||||
def qbo_journal_name(model, id)
|
||||
return id if id.blank?
|
||||
|
||||
@qbo_journal_names ||= {}
|
||||
@qbo_journal_names[[model, id]] ||= model.constantize.find_by(id: id)&.to_s.presence || id
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -16,17 +16,24 @@ module RedmineQboBilling
|
||||
# hours: man-hours on estimates, issues' estimated time, man-hours invoiced, time spent
|
||||
# with a month-by-month breakdown. Estimates, invoices and payments count by their QuickBooks date, issues by
|
||||
# the day they were created (only issues without subtasks, so parents' totals aren't counted twice), and
|
||||
# spent time by the day it was spent.
|
||||
# spent time by the day it was spent. project_ids limits the issues and spent time to those projects; the
|
||||
# QuickBooks figures have no project, so they always cover the whole business.
|
||||
class BusinessReport
|
||||
PERIODS = %w[this_month last_month this_quarter last_quarter this_year last_year custom].freeze
|
||||
PERIODS = %w[this_week last_week this_month last_month this_quarter last_quarter this_year last_year custom].freeze
|
||||
WEEK_DAYS = { 1 => :monday, 6 => :saturday, 7 => :sunday }.freeze
|
||||
# Chart points: a day each for up to two weeks, a week each up to about three months, else a month each
|
||||
DAILY_UP_TO = 14
|
||||
WEEKLY_UP_TO = 93
|
||||
MONEY = %i[estimates invoices payments].freeze
|
||||
HOURS = %i[estimate_hours issue_hours invoice_hours spent_hours].freeze
|
||||
|
||||
attr_reader :from, :to, :period
|
||||
attr_reader :from, :to, :period, :project_ids
|
||||
|
||||
# The dates for a period, from today: [from, to]. "custom" uses the given dates (either can be blank).
|
||||
def self.range_for(period, today: Date.current, from: nil, to: nil)
|
||||
def self.range_for(period, today: Date.current, from: nil, to: nil, week_start: :monday)
|
||||
case period.to_s
|
||||
when 'this_week' then [today.beginning_of_week(week_start), today.end_of_week(week_start)]
|
||||
when 'last_week' then w = today - 7; [w.beginning_of_week(week_start), w.end_of_week(week_start)]
|
||||
when 'this_month' then [today.beginning_of_month, today.end_of_month]
|
||||
when 'last_month' then m = today.prev_month; [m.beginning_of_month, m.end_of_month]
|
||||
when 'this_quarter' then [today.beginning_of_quarter, today.end_of_quarter]
|
||||
@@ -49,11 +56,94 @@ module RedmineQboBilling
|
||||
|
||||
# data (for tests): { estimates: [[date, total, hours]], invoices: [[date, total, hours, balance]],
|
||||
# payments: [[date, total]], issues: [[date, estimated_hours]], time_entries: [[date, hours]] }
|
||||
def initialize(period: 'this_year', from: nil, to: nil, today: Date.current, data: nil)
|
||||
# week_start: the first day of a week (:monday, :saturday or :sunday); see week_start_from_setting.
|
||||
# previous_data (for tests): last year's data, like data.
|
||||
# project_ids: the projects whose issues and spent time count; blank for every project.
|
||||
def initialize(period: 'this_year', from: nil, to: nil, today: Date.current, data: nil, week_start: :monday,
|
||||
previous_data: nil, project_ids: nil)
|
||||
@period = PERIODS.include?(period.to_s) ? period.to_s : 'this_year'
|
||||
@from, @to = self.class.range_for(@period, today: today, from: from, to: to)
|
||||
@week_start = week_start
|
||||
@from, @to = self.class.range_for(@period, today: today, from: from, to: to, week_start: week_start)
|
||||
@today = today
|
||||
@data = data
|
||||
@previous_data = previous_data
|
||||
@project_ids = Array(project_ids).map(&:to_i).select(&:positive?).uniq
|
||||
end
|
||||
|
||||
# Whether the issues and spent time are limited to some projects
|
||||
def projects_filtered?
|
||||
project_ids.any?
|
||||
end
|
||||
|
||||
# Redmine's "Start calendars on" setting (1 Monday, 6 Saturday, 7 Sunday); Monday when it follows the language
|
||||
def self.week_start_from_setting(value)
|
||||
WEEK_DAYS[value.to_i] || :monday
|
||||
end
|
||||
|
||||
# ---- charts ----
|
||||
|
||||
# :day, :week or :month, from the length of the period
|
||||
def granularity
|
||||
days = (to - from).to_i + 1
|
||||
return :day if days <= DAILY_UP_TO
|
||||
days <= WEEKLY_UP_TO ? :week : :month
|
||||
end
|
||||
|
||||
# The chart's points as [first day, last day] pairs covering the period
|
||||
def buckets
|
||||
@buckets ||= begin
|
||||
list = []
|
||||
case granularity
|
||||
when :day
|
||||
(from..to).each { |day| list << [day, day] }
|
||||
when :week
|
||||
start = from.beginning_of_week(@week_start)
|
||||
while start <= to
|
||||
list << [[start, from].max, [start + 6, to].min]
|
||||
start += 7
|
||||
end
|
||||
else
|
||||
start = from.beginning_of_month
|
||||
while start <= to
|
||||
list << [[start, from].max, [start.end_of_month, to].min]
|
||||
start = start.next_month
|
||||
end
|
||||
end
|
||||
list
|
||||
end
|
||||
end
|
||||
|
||||
# The same points a year earlier. Days and weeks go back 52 weeks, so a Monday lines up with a Monday;
|
||||
# months go back to the same month.
|
||||
def previous_buckets
|
||||
@previous_buckets ||= if granularity == :month
|
||||
buckets.map { |a, b| [a.prev_year, b.prev_year] }
|
||||
else
|
||||
buckets.map { |a, b| [a - 364, b - 364] }
|
||||
end
|
||||
end
|
||||
|
||||
# Everything the line charts need: the points' start dates, this period's figures per point (nil after
|
||||
# today, so the line stops there), and last year's for the same points (the toggle shows them).
|
||||
# { granularity:, points: ["2026-10-26", ...],
|
||||
# current: { estimates: [...], invoices:, payments:, estimate_hours:, issue_hours:, invoice_hours:, spent_hours: },
|
||||
# previous: { same keys } }
|
||||
def chart
|
||||
current = sums_by_bucket(data, buckets)
|
||||
current.each_value { |values| buckets.each_with_index { |(a, _), i| values[i] = nil if a > @today } }
|
||||
{
|
||||
granularity: granularity,
|
||||
points: buckets.map { |a, _| a.iso8601 },
|
||||
ends: buckets.map { |_, b| b.iso8601 },
|
||||
previous_points: previous_buckets.map { |a, _| a.iso8601 },
|
||||
current: current,
|
||||
previous: sums_by_bucket(previous_data, previous_buckets)
|
||||
}
|
||||
end
|
||||
|
||||
# Last year's data for the chart's points
|
||||
def previous_data
|
||||
@previous_data ||= load_data(previous_buckets.first[0], previous_buckets.last[1])
|
||||
end
|
||||
|
||||
def data
|
||||
@@ -146,17 +236,41 @@ module RedmineQboBilling
|
||||
|
||||
private
|
||||
|
||||
def load_data
|
||||
# { money key or hours key => [sum per bucket] } for the data, in buckets ([first day, last day] pairs)
|
||||
def sums_by_bucket(rows, bucket_list)
|
||||
sums = (MONEY + HOURS).index_with { |_| Array.new(bucket_list.size, 0.0) }
|
||||
find = lambda do |date|
|
||||
bucket_list.index { |a, b| date >= a && date <= b }
|
||||
end
|
||||
columns = {
|
||||
estimates: [:estimates, 1], invoices: [:invoices, 1], payments: [:payments, 1],
|
||||
estimate_hours: [:estimates, 2], issue_hours: [:issues, 1], invoice_hours: [:invoices, 2], spent_hours: [:time_entries, 1]
|
||||
}
|
||||
columns.each do |key, (source, col)|
|
||||
Array(rows[source]).each do |row|
|
||||
i = find.call(row[0]) or next
|
||||
sums[key][i] += MONEY.include?(key) ? to_d(row[col]).to_f : row[col].to_f
|
||||
end
|
||||
end
|
||||
sums.transform_values { |values| values.map { |v| v.round(2) } }
|
||||
end
|
||||
|
||||
def load_data(from = self.from, to = self.to)
|
||||
dates = from..to
|
||||
times = from.in_time_zone.beginning_of_day..to.in_time_zone.end_of_day
|
||||
leaf = "#{Issue.table_name}.rgt IS NULL OR #{Issue.table_name}.rgt - #{Issue.table_name}.lft = 1"
|
||||
issues = Issue.where(created_on: times).where(leaf).where.not(estimated_hours: nil)
|
||||
time_entries = TimeEntry.where(spent_on: dates)
|
||||
if projects_filtered?
|
||||
issues = issues.where(project_id: project_ids)
|
||||
time_entries = time_entries.where(project_id: project_ids)
|
||||
end
|
||||
{
|
||||
estimates: Estimate.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours),
|
||||
invoices: Invoice.where(txn_date: dates).pluck(:txn_date, :total_amount, :hours, :balance),
|
||||
payments: Payment.where(txn_date: dates).pluck(:txn_date, :total_amount),
|
||||
issues: Issue.where(created_on: times).where(leaf).where.not(estimated_hours: nil)
|
||||
.pluck(:created_on, :estimated_hours).map { |t, h| [t.in_time_zone.to_date, h] },
|
||||
time_entries: TimeEntry.where(spent_on: dates).pluck(:spent_on, :hours)
|
||||
issues: issues.pluck(:created_on, :estimated_hours).map { |t, h| [t.in_time_zone.to_date, h] },
|
||||
time_entries: time_entries.pluck(:spent_on, :hours)
|
||||
}
|
||||
end
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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') }
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 ||= []
|
||||
|
||||
@@ -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|
|
||||
|
||||
Reference in new issue
Block a user