Compare commits

...
13 Commits
Author SHA1 Message Date
rickyandClaude Opus 5.5 b1ad2d5b40 2026.11.4
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:17:15 -04:00
Claude 03af3457ab Show invoice statuses
Invoices get a status badge on the customer page's invoice list and the invoice page: Paid, Partially
paid, Overdue, Open or Voided (zero total), worked out from the total, balance and due date like
QuickBooks' invoice list (RedmineQboBilling::InvoiceStatus; QuickBooks keeps no status on invoices).
The list uses the cached balance and due date; the invoice page uses QuickBooks' current figures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 14:10:11 -04:00
Claude 0d35cffb83 Cost performance index on the business report
CPI = invoiced hours / spent hours, for the period and for each month, colour-coded: green at 1.00 or
more, yellow below 1, red below 0.80. It replaces the invoiced-vs-spent percentage (the same figure).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 13:51:19 -04:00
rickyandClaude Opus 5.5 e348042fef 2026.11.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 13:17:51 -04:00
Claude 846fcad292 Keep the description selected after Tab in every browser
Browsers like Safari and Firefox place the cursor in a textarea after its focus event, undoing the
selection, so Tab from the product into the description left the cursor at the start. The box is now
selected on focus, once more after the browser has placed its cursor, and again on the Tab key's release,
each only while nothing has been typed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 13:11:01 -04:00
Claude d91e80199e Subtotal from the keyboard: sub, subtotal or = in a product box
Typing sub, subtotal or = in a line's product box, then Tab or Enter, adds a subtotal there: an otherwise
empty line becomes the subtotal; a line with a description, quantity or rate keeps them and gets the
subtotal after it. The next line's product box gets the focus. Lines with a product are left alone.
Tabbing into a box now selects its text right away, so the first key typed already replaces it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 13:06:03 -04:00
Claude d054b0d872 Math in the amount box
Arithmetic typed into a line's amount (e.g. 300*1.1) is rounded to the nearest penny and sets the rate from
the quantity, as a typed amount already did.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:59:11 -04:00
Claude 632d81b98b Math in the rate and quantity boxes
Typing arithmetic into a line's rate or quantity (33*1.3, (120+15)/2; + - * /, x for times, parentheses)
works it out when leaving the box, and before saving; the amount updates while typing. Math in the rate is
rounded to the nearest penny, half up and exactly (1.005 -> 1.01). It's parsed, never run as code; broken
math is left as typed. A click right after a Tab no longer selects the box's text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:58:30 -04:00
Claude 331a2d1da7 Keyboard estimate entry: Tab picks the product; Tab selects the text
- In a line's product box, Tab picks the product the typed text points to: an exact name, else the only
  match, else the only name starting with it ("lab" -> Labor). Tabbing before the search comes back
  fills the line when it does; ambiguous text is left as typed; an item highlighted in the list still wins.
- Tabbing into a line's description, quantity or rate selects its text so typing replaces it (a click
  still places the cursor).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:56:49 -04:00
Claude 66d96c9e4c Send an estimate's lines with status changes
QuickBooks refused the Accepted update with "At least 1 line item is required": a sparse estimate update
still needs its lines. Status changes (Accepted when issues are created, Closed when an invoice is saved)
now go through EstimateWriter.status_update, which sends the estimate's lines back exactly as QuickBooks
returned them, so nothing else changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:47:09 -04:00
Claude 6ac0e27cb2 Report when an estimate can't be marked Accepted; show every status on the estimate page
- Accepting sends Accepted by (the customer) with the accepted date, as QuickBooks' own Accept does, and
  checks what QuickBooks returns. If it keeps the old status or refuses, the Create issues page shows a
  warning with QuickBooks' message instead of only logging it.
- The estimate page's header shows the status badge for every status, Pending included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:43:17 -04:00
Claude 338b4db237 Mark an estimate Accepted when issues are created from it
Creating issues from an estimate means the work is going ahead, so a pending estimate becomes Accepted in
QuickBooks (sparse update with today's accepted date, like closing an estimate) and the local estimate is
synced, so its status badge updates. Accepted, Closed, Converted and Rejected estimates are left alone. A
failure is logged and doesn't affect the created issues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
2026-10-31 12:36:05 -04:00
rickyandClaude Opus 5.5 ec6fecbd85 Show each estimate's status on the customer page
The estimate lists (customer page, and redmine_qbo_vehicles' vehicle page) show the QuickBooks status
badge (Pending, Accepted, Closed, Converted, Rejected) after the date. It's the status the estimate
sync already caches, kept current by the webhook. The badge styles are shared with the estimate
page's header (qbo_estimates/_status_styles).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 12:32:31 -04:00
16 changed files with 379 additions and 46 deletions

No files matched your search

+4 -2
View File
@@ -103,10 +103,11 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
* **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; the customer's name still 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. * **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. * **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.
* **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit. * **Read-only once linked to an issue**: an estimate that an issue is linked to can be viewed, emailed and duplicated, but not changed, so the work doesn't drift from what was quoted. The list shows a View link for these instead of Edit.
* **Read-only once billed**: an estimate that's Converted or Closed in QuickBooks, or linked to an invoice, can't be changed here either (including redmine_qbo_lineitems' estimates once they're invoiced). Its page lists the invoices it's on; it can still be viewed, emailed and duplicated, and it shows View instead of Edit in lists. * **Read-only once billed**: an estimate that's Converted or Closed in QuickBooks, or linked to an invoice, can't be changed here either (including redmine_qbo_lineitems' estimates once they're invoiced). Its page lists the invoices it's on; it can still be viewed, emailed and duplicated, and it shows View instead of Edit in lists.
* **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line with one of the **labor products/services** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Opened from an appointment, the issues get the appointment's dates, technician and vehicle. * **Create issues** from an estimate's labor lines (moved here from redmine_qbo_calendar): each line with one of the **labor products/services** (e.g. Labor) becomes an issue with the line's description as subject and its quantity as estimated hours. Pick the project, trackers, templates and shared custom fields first. Lines already turned into issues can't be created twice, and issues from the same estimate are related to each other. Creating issues marks a pending estimate **Accepted** in QuickBooks (dated today), since the work is going ahead; estimates that are already accepted, closed, converted or rejected keep their status. Opened from an appointment, the issues get the appointment's dates, technician and vehicle.
* **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link. * **Email** the estimate with QuickBooks' own estimate email, with **Save and send** or the Email link.
* The page follows QuickBooks' estimate screen: customer, customer email, billing address, estimate date, expiration date, estimate number, then the product/service lines (#, product/service, description, qty, rate, amount, tax), the message displayed on the estimate, the memo, and the totals. * The page follows QuickBooks' estimate screen: customer, customer email, billing address, estimate date, expiration date, estimate number, then the product/service lines (#, product/service, description, qty, rate, amount, tax), the message displayed on the estimate, the memo, and the totals.
* Lines work like QuickBooks: the product list opens when the box is clicked, picking a product fills in its description, rate and tax, typing an amount works out the rate, a spare empty line is always at the bottom, and lines are reordered by dragging them by the handle. * Lines work like QuickBooks: the product list opens when the box is clicked, picking a product fills in its description, rate and tax, typing an amount works out the rate, a spare empty line is always at the bottom, and lines are reordered by dragging them by the handle.
@@ -125,6 +126,7 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
* Time lines are linked to their time activities, so QuickBooks marks the time as billed. Estimates the invoice was made from, or imported into it, are linked and closed when it's saved. * Time lines are linked to their time activities, so QuickBooks marks the time as billed. Estimates the invoice was made from, or imported into it, are linked and closed when it's saved.
* **Custom fields from the work orders**: the issues behind an invoice are the ones its time lines and lineitems estimates name. Plugins can fill custom fields from them when they're imported, and block a save (e.g. redmine_qbo_vehicles fills the VIN and mileage and allows one vehicle per invoice). On its own, redmine_qbo leaves the boxes as typed. * **Custom fields from the work orders**: the issues behind an invoice are the ones its time lines and lineitems estimates name. Plugins can fill custom fields from them when they're imported, and block a save (e.g. redmine_qbo_vehicles fills the VIN and mileage and allows one vehicle per invoice). On its own, redmine_qbo leaves the boxes as typed.
* **Sales person**: an invoice credits the sales person on the estimate it was made from (the first linked estimate that names one); if none does, the user who writes the invoice. * **Sales person**: an invoice credits the sales person on the estimate it was made from (the first linked estimate that names one); if none does, the user who writes the invoice.
* Invoices show their status, worked out from the balance and due date like QuickBooks' invoice list: **Paid**, **Partially paid**, **Overdue**, **Open** or **Voided** (a zero total), on the customer page's invoice list and the invoice page.
* Invoices with a payment applied open read-only. The due date is left to QuickBooks (from the customer's terms) unless one is picked. The "default message shown on invoices" fills in the message. * Invoices with a payment applied open read-only. The due date is left to QuickBooks (from the customer's terms) unless one is picked. The "default message shown on invoices" fills in the message.
### Payments ### Payments
@@ -141,7 +143,7 @@ Estimates and invoices keep their number, date, customer, total and **man-hours*
**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 month, quarter or year, or custom dates):
* **Sales**: estimates written, invoices written and payments received (totals and counts), invoiced vs. estimated, collected vs. invoiced, and what's still owed on those invoices. * **Sales**: estimates written, invoices written 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 invoiced vs. spent and spent vs. estimated. * **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.
* **By month**: every figure month by month, with totals. * **By month**: every figure month by month, with totals.
Estimates, invoices and payments count by their QuickBooks date. Issues' estimated time counts issues created in the period, leaving out parents so subtasks aren't counted twice. Spent time counts time logged in the period. While estimates, invoices or payments are syncing, the report says so (with how many have been read) and refreshes every 30 seconds; the settings page's Synchronization table shows the same per type. Estimates and invoices synced before these figures were added have no total or hours until a full sync (the report says how many); run one again after changing the labor products/services. Estimates, invoices and payments count by their QuickBooks date. 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.
@@ -96,7 +96,11 @@ class QboEstimatesController < ApplicationController
if created.any? if created.any?
Redmine::Hook.call_hook(:qbo_billing_issues_created, { estimate: @estimate, issues: created, params: params }) Redmine::Hook.call_hook(:qbo_billing_issues_created, { estimate: @estimate, issues: created, params: params })
# The work is going ahead: a pending estimate becomes Accepted in QuickBooks
accepted = RedmineQboBilling::EstimateWriter.accept(@estimate.id, user: User.current)
flash[:notice] = l(:notice_estimate_issues_created, count: created.size) flash[:notice] = l(:notice_estimate_issues_created, count: created.size)
flash[:notice] += " #{l(:notice_estimate_accepted, number: @estimate.doc_number)}" if accepted.accepted?
flash[:warning] = l(:warning_estimate_not_accepted, number: @estimate.doc_number, message: accepted.message) if accepted.failed?
redirect_to @return_path redirect_to @return_path
else else
# Rebuild the fields so the form keeps what was entered # Rebuild the fields so the form keeps what was entered
+7
View File
@@ -22,4 +22,11 @@ class Invoice < QboBaseModel
doc_number doc_number
end 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)
RedmineQboBilling::InvoiceStatus.status(total: self[:total_amount], balance: self[:balance],
due_date: self[:due_date], today: today)
end
end end
+7
View File
@@ -1,12 +1,19 @@
<% unless estimates.empty? %> <% unless estimates.empty? %>
<%= render partial: 'qbo_estimates/status_styles' %>
<div class="qbo-estimate-list">
<% estimates.sort.reverse.each do |estimate| %> <% estimates.sort.reverse.each do |estimate| %>
<div class="row"> <div class="row">
<%= check_box_tag "estimate_ids[]", estimate.id, false, onchange: "updateLink()", data: { text: "Estimate ##{estimate.doc_number}", new_issue_param: 'issue[estimate_id]' }, class: "estimate-checkbox appointment" %> <%= check_box_tag "estimate_ids[]", estimate.id, false, onchange: "updateLink()", data: { text: "Estimate ##{estimate.doc_number}", new_issue_param: 'issue[estimate_id]' }, class: "estimate-checkbox appointment" %>
<b><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b> <%= estimate.txn_date %> <b><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b> <%= estimate.txn_date %>
<%# QuickBooks status, cached by the estimate sync (kept current by the webhook) %>
<% if estimate.txn_status.present? %>
<span class="qbo-estimate-status qbo-estimate-status-<%= estimate.txn_status.downcase %>"><%= estimate.txn_status %></span>
<% end %>
<%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %> <%= render partial: 'qbo_estimates/estimate_actions', locals: { estimate: estimate } if RedmineQboBilling.writer? %>
</div> </div>
<% end %> <% end %>
</div>
<% else %> <% else %>
<p><%=t(:label_no_estimates)%>.</p> <p><%=t(:label_no_estimates)%>.</p>
+7
View File
@@ -1,4 +1,5 @@
<% unless invoices.empty? %> <% unless invoices.empty? %>
<%= render partial: 'qbo_estimates/status_styles' %>
<%= form_with(url: invoice_path, method: :get) do |form| %> <%= form_with(url: invoice_path, method: :get) do |form| %>
@@ -10,13 +11,19 @@
<hr> <hr>
<% end %> <% end %>
<div class="qbo-invoice-list">
<% invoices.sort.reverse.each do |invoice| %> <% invoices.sort.reverse.each do |invoice| %>
<div class="row"> <div class="row">
<%= check_box_tag "invoice_ids[]", invoice.id, false, onchange: "updateLink()", data: { url: invoice_path(invoice), text: "Invoice ##{invoice.to_s}" }, class: "invoice-checkbox appointment" if invoices.count > 1 %> <%= check_box_tag "invoice_ids[]", invoice.id, false, onchange: "updateLink()", data: { url: invoice_path(invoice), text: "Invoice ##{invoice.to_s}" }, class: "invoice-checkbox appointment" if invoices.count > 1 %>
<b><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b> <%= invoice.txn_date %> <b><%= link_to "##{invoice.doc_number}", invoice_path(invoice), target: :_blank %></b> <%= invoice.txn_date %>
<%# Paid / partially paid / overdue / open / voided, from the cached balance and due date %>
<% if (status = invoice.status) %>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status) %></span>
<% end %>
<%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %> <%= render partial: 'qbo_invoices/invoice_actions', locals: { invoice: invoice } if RedmineQboBilling.invoice_writer? %>
</div> </div>
<% end %> <% end %>
</div>
<% if invoices.count > 1 %> <% if invoices.count > 1 %>
<%= form.submit t(:button_bulk_pdf) %> <%= form.submit t(:button_bulk_pdf) %>
+8 -4
View File
@@ -15,10 +15,14 @@
<% if form.sent? %> <% if form.sent? %>
<span class="qbo-estimate-status qbo-estimate-status-sent"><%= l(:label_estimate_sent) %></span> <span class="qbo-estimate-status qbo-estimate-status-sent"><%= l(:label_estimate_sent) %></span>
<% end %> <% end %>
<% if invoice && form.locked == :paid %> <% if invoice %>
<% fully_paid = form.balance.to_d.zero? %> <% status = RedmineQboBilling::InvoiceStatus.status(total: form.total, balance: form.balance,
<span class="qbo-estimate-status qbo-estimate-status-<%= fully_paid ? 'closed' : 'accepted' %>"><%= l(fully_paid ? :label_invoice_paid : :label_invoice_partially_paid) %></span> due_date: RedmineQboBilling::EstimateForm.date(form.due_date),
<% elsif !invoice && form.txn_status.present? && form.txn_status != 'Pending' %> today: User.current.today) %>
<% if status %>
<span class="qbo-estimate-status qbo-invoice-status-<%= status %>"><%= RedmineQboBilling::InvoiceStatus.label(status) %></span>
<% end %>
<% elsif !invoice && form.txn_status.present? %>
<span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span> <span class="qbo-estimate-status qbo-estimate-status-<%= form.txn_status.downcase %>"><%= form.txn_status %></span>
<% end %> <% end %>
<% else %> <% else %>
+169 -23
View File
@@ -44,13 +44,47 @@ $(function () {
var dirty = false; var dirty = false;
// ---- numbers ---- // ---- numbers ----
// A number, or simple arithmetic typed into a quantity or rate box (e.g. 33*1.3, (120+15)/2): + - * / and
// parentheses only, worked out here (never run as code). null when empty, NaN when it can't be read.
function isMath(text) { return /[*\/()+x×]/.test(text) || /.-/.test(text); }
function evaluateMath(text) {
var tokens = text.replace(/[x×]/g, '*').match(/\d*\.?\d+|[-+*\/()]/g);
if (!tokens || tokens.join('') !== text.replace(/[x×]/g, '*')) return NaN;
var i = 0;
var peek = function () { return tokens[i]; };
var expr, term, factor;
factor = function () {
var t = tokens[i++];
if (t === '-') return -factor();
if (t === '+') return factor();
if (t === '(') { var v = expr(); if (tokens[i++] !== ')') return NaN; return v; }
return t !== undefined && /^\d*\.?\d+$/.test(t) ? parseFloat(t) : NaN;
};
term = function () {
var v = factor();
while (peek() === '*' || peek() === '/') { var op = tokens[i++], r = factor(); v = op === '*' ? v * r : v / r; }
return v;
};
expr = function () {
var v = term();
while (peek() === '+' || peek() === '-') { var op = tokens[i++], r = term(); v = op === '+' ? v + r : v - r; }
return v;
};
var result = expr();
return i === tokens.length && isFinite(result) ? result : NaN;
}
function parseNumber(value) { function parseNumber(value) {
var text = String(value == null ? '' : value).replace(/[$,\s]/g, ''); var text = String(value == null ? '' : value).replace(/[$,\s]/g, '');
if (text === '') return null; if (text === '') return null;
if (isMath(text)) return evaluateMath(text);
var n = Number(text); var n = Number(text);
return isFinite(n) ? n : NaN; return isFinite(n) ? n : NaN;
} }
function round(n, places) { var f = Math.pow(10, places); return Math.round(n * f) / f; } // Rounds half up exactly (1.005 -> 1.01; multiplying first would give 1.00)
function round(n, places) {
if (/e/i.test(String(n))) { var f = Math.pow(10, places); return Math.round(n * f) / f; }
return Number(Math.round(Number(n + 'e' + places)) + 'e-' + places);
}
function plain(n, places) { return String(round(n, places)); } function plain(n, places) { return String(round(n, places)); }
// ---- rows ---- // ---- rows ----
@@ -135,6 +169,70 @@ $(function () {
} }
// ---- product/service search ---- // ---- product/service search ----
// Fills a line from a product/service: name, id, description (unless the user typed their own), rate,
// quantity 1 if empty, taxable
function applyItem($input, item) {
var $row = $input.closest('tr');
var $description = $row.find('.qbo-line-description-input');
var previous = $row.data('itemDescription');
$input.val(item.name);
$row.find('.qbo-line-item-id').val(item.id);
$row.removeClass('qbo-line-unmatched');
// Keep a description the user typed; replace one that came from the previous product
if (!$description.val().trim() || $description.val() === previous) {
$description.val(item.description || '');
autoGrow($description[0]);
// Tabbed into it already (the product was filled in after the search came back): keep it selected
if (document.activeElement === $description[0]) $description[0].select();
}
$row.data('itemDescription', item.description || '');
if (item.price !== null && item.price !== undefined && item.price !== '') {
$row.find('.qbo-line-rate-input').val(plain(parseFloat(item.price), 5));
tidyNumbers($row);
}
if (!$row.find('.qbo-line-qty-input').val().trim()) $row.find('.qbo-line-qty-input').val('1');
$row.find('.qbo-line-taxable').prop('checked', item.taxable !== false);
changed();
}
// Keyboard subtotal: typed in a line's product box, then Tab or Enter
var SUBTOTAL_SHORTCUTS = ['sub', 'subtotal', '='];
// Puts a subtotal where the shortcut was typed: an otherwise empty line becomes the subtotal; a line with a
// description, quantity or rate keeps them (the shortcut text is cleared) and the subtotal goes after it.
// Then the next line's product box gets the focus, to carry on typing.
function insertSubtotalAt($row) {
var $subtotal = $(subtotalTemplate.replace(/__KEY__/g, String(nextKey++)));
var $product = $row.find('.qbo-line-item-name');
var otherwiseEmpty = !$row.find('.qbo-line-description-input').val().trim() &&
!$row.find('.qbo-line-qty-input').val().trim() && !$row.find('.qbo-line-rate-input').val().trim();
if (otherwiseEmpty) {
$row.replaceWith($subtotal);
} else {
$product.val('');
$row.removeClass('qbo-line-unmatched').after($subtotal);
}
renumber();
changed();
var $next = $subtotal.nextAll('tr.qbo-line').not('.qbo-line-subtotal').first();
if (!$next.length) $next = addRow();
$next.find('.qbo-line-item-name').trigger('focus');
}
// The product typed text points to: an exact name match, else the only result, else the only one whose name
// starts with the text (e.g. "lab" -> Labor). Nothing when it's ambiguous.
function bestItem(term, items) {
var t = term.trim().toLowerCase();
if (!t || !items || !items.length) return null;
var exact = items.filter(function (i) { return String(i.name).toLowerCase() === t; });
if (exact.length === 1) return exact[0];
if (items.length === 1) return items[0];
var starts = items.filter(function (i) { return String(i.name).toLowerCase().indexOf(t) === 0; });
return starts.length === 1 ? starts[0] : null;
}
function setupItemSearch($input) { function setupItemSearch($input) {
$input.autocomplete({ $input.autocomplete({
appendTo: 'body', appendTo: 'body',
@@ -143,6 +241,7 @@ $(function () {
source: function (request, response) { source: function (request, response) {
$.getJSON($form.data('itemsUrl'), { q: request.term }) $.getJSON($form.data('itemsUrl'), { q: request.term })
.done(function (items) { .done(function (items) {
$input.data('qboResults', { term: request.term, items: items });
response(items.map(function (item) { response(items.map(function (item) {
return { label: item.name, value: item.name, item: item }; return { label: item.name, value: item.name, item: item };
})); }));
@@ -150,31 +249,48 @@ $(function () {
.fail(function () { response([]); }); .fail(function () { response([]); });
}, },
select: function (event, ui) { select: function (event, ui) {
var $row = $input.closest('tr'); applyItem($input, ui.item.item);
var item = ui.item.item;
var $description = $row.find('.qbo-line-description-input');
var previous = $row.data('itemDescription');
$input.val(item.name);
$row.find('.qbo-line-item-id').val(item.id);
$row.removeClass('qbo-line-unmatched');
// Keep a description the user typed; replace one that came from the previous product
if (!$description.val().trim() || $description.val() === previous) {
$description.val(item.description || '');
autoGrow($description[0]);
}
$row.data('itemDescription', item.description || '');
if (item.price !== null && item.price !== undefined && item.price !== '') {
$row.find('.qbo-line-rate-input').val(plain(parseFloat(item.price), 5));
tidyNumbers($row);
}
if (!$row.find('.qbo-line-qty-input').val().trim()) $row.find('.qbo-line-qty-input').val('1');
$row.find('.qbo-line-taxable').prop('checked', item.taxable !== false);
changed();
return false; return false;
} }
}); });
// Typing "sub", "subtotal" or "=" then Tab or Enter makes a subtotal here (see insertSubtotalAt)
$input.on('keydown', function (event) {
if ((event.key !== 'Tab' && event.key !== 'Enter') || event.shiftKey) return;
var $row = $input.closest('tr');
if (SUBTOTAL_SHORTCUTS.indexOf($input.val().trim().toLowerCase()) < 0 || $row.find('.qbo-line-item-id').val()) return;
event.preventDefault();
event.stopImmediatePropagation();
var search = $input.autocomplete('instance');
clearTimeout(search.searching);
search.cancelSearch = true;
$input.autocomplete('close');
insertSubtotalAt($row);
});
// Tab picks the product the text points to (an item highlighted in the list is picked by the
// autocomplete itself). If the search hasn't come back yet, the line is filled in when it does.
$input.on('keydown', function (event) {
if (event.key !== 'Tab' || event.shiftKey) return;
var menu = $input.autocomplete('instance').menu;
if (menu && menu.active) return;
var $row = $input.closest('tr');
var term = $input.val();
if ($row.find('.qbo-line-item-id').val() || !term.trim()) return;
var known = $input.data('qboResults');
if (known && known.term.trim().toLowerCase() === term.trim().toLowerCase()) {
var pick = bestItem(term, known.items);
if (pick) applyItem($input, pick);
$input.autocomplete('close');
return;
}
$.getJSON($form.data('itemsUrl'), { q: term }).done(function (items) {
var pick = bestItem(term, items);
if (pick && $input.val() === term && !$row.find('.qbo-line-item-id').val()) applyItem($input, pick);
});
});
$input.autocomplete('instance')._renderItem = function (ul, entry) { $input.autocomplete('instance')._renderItem = function (ul, entry) {
var item = entry.item; var item = entry.item;
var $div = $('<div>'); var $div = $('<div>');
@@ -214,16 +330,42 @@ $(function () {
ensureSpareRow(); ensureSpareRow();
} }
// ---- keyboard ----
// Tabbing into a line's description, quantity or rate selects what's there, so typing replaces it (a click
// still places the cursor)
var tabbedAt = 0;
$(document).on('keydown', function (event) { if (event.key === 'Tab') tabbedAt = Date.now(); });
// A click right after a Tab is still a click
$(document).on('mousedown touchstart', function () { tabbedAt = 0; });
$tbody.on('focus', '.qbo-line-description-input, .qbo-line-qty-input, .qbo-line-rate-input', function () {
if (Date.now() - tabbedAt > 500) return;
// Right away, so the first key typed already replaces the text; and again once the browser has placed
// its cursor (a textarea, the description, puts it back at the start), unless typing has begun
var box = this, before = box.value;
$(box).data('qboTabbedValue', before);
box.select();
setTimeout(function () { if (document.activeElement === box && box.value === before) box.select(); }, 0);
});
// Some browsers (Safari, Firefox) place the cursor after that; the Tab key's release arrives here once they
// have, so select again if nothing was typed yet
$tbody.on('keyup', '.qbo-line-description-input, .qbo-line-qty-input, .qbo-line-rate-input', function (event) {
if (event.key !== 'Tab') return;
var tabbed = $(this).data('qboTabbedValue');
$(this).removeData('qboTabbedValue');
if (tabbed !== undefined && this.value === tabbed) this.select();
});
// ---- line events ---- // ---- line events ----
$tbody.on('input', '.qbo-line-qty-input, .qbo-line-rate-input, .qbo-line-description-input, .qbo-line-item-name', changed); $tbody.on('input', '.qbo-line-qty-input, .qbo-line-rate-input, .qbo-line-description-input, .qbo-line-item-name', changed);
$tbody.on('change', '.qbo-line-taxable', changed); $tbody.on('change', '.qbo-line-taxable', changed);
$tbody.on('input', '.qbo-line-description-input', function () { autoGrow(this); }); $tbody.on('input', '.qbo-line-description-input', function () { autoGrow(this); });
// Typing an amount works out the rate from the quantity // Typing an amount (or math, e.g. 300*1.1, rounded to the penny) works out the rate from the quantity
$tbody.on('input', '.qbo-line-amount-input', function () { $tbody.on('input', '.qbo-line-amount-input', function () {
var $row = $(this).closest('tr'); var $row = $(this).closest('tr');
var amount = parseNumber($(this).val()); var amount = parseNumber($(this).val());
if (amount === null || isNaN(amount)) return; if (amount === null || isNaN(amount)) return;
if (isMath($(this).val().replace(/[$,\s]/g, ''))) amount = round(amount, 2);
var qty = parseNumber($row.find('.qbo-line-qty-input').val()); var qty = parseNumber($row.find('.qbo-line-qty-input').val());
if (qty === null || isNaN(qty) || qty === 0) qty = 1; if (qty === null || isNaN(qty) || qty === 0) qty = 1;
$row.find('.qbo-line-rate-input').val(plain(amount / qty, 5)); $row.find('.qbo-line-rate-input').val(plain(amount / qty, 5));
@@ -236,6 +378,8 @@ $(function () {
var n = parseNumber(this.value); var n = parseNumber(this.value);
if (n === null || isNaN(n)) return; if (n === null || isNaN(n)) return;
var isRate = $(this).hasClass('qbo-line-rate-input'); var isRate = $(this).hasClass('qbo-line-rate-input');
// Math in the rate box is rounded to the nearest penny
if (isRate && isMath(this.value.replace(/[$,\s]/g, ''))) n = round(n, 2);
this.value = isRate && round(n, 2) === round(n, 5) ? n.toFixed(2) : plain(n, 5); this.value = isRate && round(n, 2) === round(n, 5) ? n.toFixed(2) : plain(n, 5);
}); });
} }
@@ -578,6 +722,8 @@ $(function () {
$email.trigger('focus'); $email.trigger('focus');
return; return;
} }
// Math still in a box is worked out before saving
rows().each(function () { tidyNumbers($(this)); });
dirty = false; dirty = false;
}); });
@@ -0,0 +1,17 @@
<%# QuickBooks status badges: the estimate page's header and the estimate lists (customer and vehicle pages) %>
<style>
.qbo-estimate-status { display: inline-block; font-size: .6em; font-weight: 600; vertical-align: middle; padding: 2px 8px; border-radius: 10px;
background: #eceef1; color: #393a3d; margin-left: 6px; }
.qbo-estimate-status-sent { background: #e6f4e4; color: #108000; }
.qbo-estimate-status-accepted { background: #e6f4e4; color: #108000; }
.qbo-estimate-status-closed, .qbo-estimate-status-converted { background: #e8eefa; color: #0d47a1; }
.qbo-estimate-status-rejected { background: #fdecea; color: #b71c1c; }
.qbo-estimate-list .qbo-estimate-status { font-size: .8em; padding: 1px 7px; margin-left: 4px; }
/* Invoices (RedmineQboBilling::InvoiceStatus) */
.qbo-invoice-status-paid { background: #e6f4e4; color: #108000; }
.qbo-invoice-status-partial { background: #fff4d6; color: #8a6100; }
.qbo-invoice-status-overdue { background: #fdecea; color: #b71c1c; }
.qbo-invoice-status-open { background: #e8eefa; color: #0d47a1; }
.qbo-invoice-status-voided { background: #eceef1; color: #6b6c72; text-decoration: line-through; }
.qbo-invoice-list .qbo-estimate-status { font-size: .8em; padding: 1px 7px; margin-left: 4px; }
</style>
+1 -6
View File
@@ -111,16 +111,10 @@
.qbo-estimate .qbo-button-primary { background: var(--qbo-green); border-color: var(--qbo-green); color: #fff; } .qbo-estimate .qbo-button-primary { background: var(--qbo-green); border-color: var(--qbo-green); color: #fff; }
.qbo-estimate .qbo-button-primary:hover { background: var(--qbo-green-dark); border-color: var(--qbo-green-dark); color: #fff; } .qbo-estimate .qbo-button-primary:hover { background: var(--qbo-green-dark); border-color: var(--qbo-green-dark); color: #fff; }
.qbo-estimate-status { display: inline-block; font-size: .6em; font-weight: 600; vertical-align: middle; padding: 2px 8px; border-radius: 10px;
background: #eceef1; color: #393a3d; margin-left: 6px; }
.qbo-estimate-status-sent { background: #e6f4e4; color: #108000; }
.qbo-estimate-status-accepted { background: #e6f4e4; color: #108000; }
.qbo-estimate-status-closed, .qbo-estimate-status-converted { background: #e8eefa; color: #0d47a1; }
/* Warnings with a list (linked issues, invoices): the text, then one item per line */ /* Warnings with a list (linked issues, invoices): the text, then one item per line */
div.warning.qbo-estimate-notice { text-align: left; } div.warning.qbo-estimate-notice { text-align: left; }
div.warning.qbo-estimate-notice ul { margin: 6px 0 0; padding-left: 22px; } div.warning.qbo-estimate-notice ul { margin: 6px 0 0; padding-left: 22px; }
div.warning.qbo-estimate-notice li { margin: 2px 0; } div.warning.qbo-estimate-notice li { margin: 2px 0; }
.qbo-estimate-status-rejected { background: #fdecea; color: #b71c1c; }
.qbo-estimate-edit-link { margin-left: 4px; vertical-align: middle; } .qbo-estimate-edit-link { margin-left: 4px; vertical-align: middle; }
/* Phones: each line becomes a small card (number, product and delete; description; qty, rate, amount and tax) */ /* Phones: each line becomes a small card (number, product and delete; description; qty, rate, amount and tax) */
@@ -160,3 +154,4 @@
.qbo-estimate-actions { padding: 10px 14px; } .qbo-estimate-actions { padding: 10px 14px; }
} }
</style> </style>
<%= render partial: 'qbo_estimates/status_styles' %>
+21 -1
View File
@@ -91,8 +91,16 @@
<% end %> <% end %>
</tbody> </tbody>
</table> </table>
<% cpi_badge = lambda do |cpi|
level = RedmineQboBilling::BusinessReport.cpi_level(cpi)
content_tag(:span, cpi.nil? ? '–' : format('%.2f', cpi), class: "qbo-cpi qbo-cpi-#{level || 'none'}")
end %>
<p class="qbo-report-cpi">
<span class="qbo-cpi-label" title="<%= l(:text_report_cpi) %>"><%= l(:label_report_cpi) %></span>
<%= cpi_badge.call(@report.cpi) %>
<em class="info"><%= l(:text_report_cpi) %></em>
</p>
<p class="qbo-report-ratios"> <p class="qbo-report-ratios">
<%= l(:label_report_invoiced_of_spent) %>: <strong><%= pct.call(ratios[:invoiced_of_spent]) %></strong><br />
<%= l(:label_report_spent_of_estimated) %>: <strong><%= pct.call(ratios[:spent_of_estimated]) %></strong> <%= l(:label_report_spent_of_estimated) %>: <strong><%= pct.call(ratios[:spent_of_estimated]) %></strong>
</p> </p>
</div> </div>
@@ -111,6 +119,7 @@
<th><%= l(:label_report_issue_hours) %></th> <th><%= l(:label_report_issue_hours) %></th>
<th><%= l(:label_report_invoice_hours) %></th> <th><%= l(:label_report_invoice_hours) %></th>
<th><%= l(:label_report_spent_hours) %></th> <th><%= l(:label_report_spent_hours) %></th>
<th class="cpi"><%= l(:label_report_cpi_short) %></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -124,6 +133,7 @@
<td><%= fmt_hours.call(row[:issue_hours]) %></td> <td><%= fmt_hours.call(row[:issue_hours]) %></td>
<td><%= fmt_hours.call(row[:invoice_hours]) %></td> <td><%= fmt_hours.call(row[:invoice_hours]) %></td>
<td><%= fmt_hours.call(row[:spent_hours]) %></td> <td><%= fmt_hours.call(row[:spent_hours]) %></td>
<td class="cpi"><%= cpi_badge.call(RedmineQboBilling::BusinessReport.cpi(row[:invoice_hours], row[:spent_hours])) %></td>
</tr> </tr>
<% end %> <% end %>
</tbody> </tbody>
@@ -137,6 +147,7 @@
<td><strong><%= fmt_hours.call(hours[:issue_hours]) %></strong></td> <td><strong><%= fmt_hours.call(hours[:issue_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:invoice_hours]) %></strong></td> <td><strong><%= fmt_hours.call(hours[:invoice_hours]) %></strong></td>
<td><strong><%= fmt_hours.call(hours[:spent_hours]) %></strong></td> <td><strong><%= fmt_hours.call(hours[:spent_hours]) %></strong></td>
<td class="cpi"><%= cpi_badge.call(@report.cpi) %></td>
</tr> </tr>
</tfoot> </tfoot>
</table> </table>
@@ -154,6 +165,15 @@
.qbo-bar-payments, .qbo-bar-spent_hours { background: #5aa05a; } .qbo-bar-payments, .qbo-bar-spent_hours { background: #5aa05a; }
.qbo-bar-issue_hours { background: #9b7fc0; } .qbo-bar-issue_hours { background: #9b7fc0; }
.qbo-report-ratios { margin: 8px 4px; line-height: 1.7; } .qbo-report-ratios { margin: 8px 4px; line-height: 1.7; }
.qbo-report-cpi { margin: 10px 4px 4px; }
.qbo-report-cpi .qbo-cpi-label { font-weight: 600; margin-right: 6px; }
.qbo-report-cpi .qbo-cpi { font-size: 1.3em; padding: 3px 12px; }
.qbo-report-cpi em.info { display: block; margin-top: 4px; }
.qbo-cpi { display: inline-block; font-weight: 700; padding: 1px 8px; border-radius: 10px; background: #eceef1; color: #393a3d; }
.qbo-cpi-poor { background: #fdecea; color: #b71c1c; }
.qbo-cpi-under { background: #fff4d6; color: #8a6100; }
.qbo-cpi-good { background: #e6f4e4; color: #108000; }
table.qbo-report-months td.cpi, table.qbo-report-months th.cpi { text-align: center; }
.qbo-report-range { color: #666; margin: 4px 0 10px; } .qbo-report-range { color: #666; margin: 4px 0 10px; }
.qbo-report-syncing ul { display: inline-block; text-align: left; margin: 6px 0 0; } .qbo-report-syncing ul { display: inline-block; text-align: left; margin: 6px 0 0; }
table.qbo-report-months td, table.qbo-report-months th { text-align: right; white-space: nowrap; } table.qbo-report-months td, table.qbo-report-months th { text-align: right; white-space: nowrap; }
+11 -3
View File
@@ -240,8 +240,11 @@ en:
label_invoice_balance: "Balance due %{balance}" label_invoice_balance: "Balance due %{balance}"
label_invoice_date: "Invoice date" label_invoice_date: "Invoice date"
label_invoice_no: "Invoice no." label_invoice_no: "Invoice no."
label_invoice_paid: "Paid" label_invoice_status_paid: "Paid"
label_invoice_partially_paid: "Partially paid" label_invoice_status_partial: "Partially paid"
label_invoice_status_overdue: "Overdue"
label_invoice_status_open: "Open"
label_invoice_status_voided: "Voided"
label_message_on_invoice: "Message displayed on invoice" label_message_on_invoice: "Message displayed on invoice"
label_new_invoice: "New invoice" label_new_invoice: "New invoice"
label_open_estimates: "Open estimates" label_open_estimates: "Open estimates"
@@ -269,6 +272,9 @@ en:
label_estimate_line_already_created: "Already created" label_estimate_line_already_created: "Already created"
label_issue_template: "Template" label_issue_template: "Template"
label_no_issue_template: "(no template)" label_no_issue_template: "(no template)"
notice_estimate_accepted: "Estimate #%{number} is now Accepted in QuickBooks."
warning_estimate_not_accepted: "The issues were created, but estimate #%{number} couldn't be marked Accepted in QuickBooks: %{message}"
error_estimate_not_accepted: "QuickBooks kept its status as %{status}"
notice_estimate_issues_created: notice_estimate_issues_created:
one: "1 issue created from the estimate" one: "1 issue created from the estimate"
other: "%{count} issues created from the estimate" other: "%{count} issues created from the estimate"
@@ -323,7 +329,9 @@ en:
label_report_invoiced_of_estimated: "Invoiced vs. estimated" label_report_invoiced_of_estimated: "Invoiced vs. estimated"
label_report_collected_of_invoiced: "Collected vs. invoiced" label_report_collected_of_invoiced: "Collected vs. invoiced"
label_report_open_balance: "Still owed on these invoices" label_report_open_balance: "Still owed on these invoices"
label_report_invoiced_of_spent: "Invoiced vs. spent hours" label_report_cpi: "Cost performance index (CPI)"
label_report_cpi_short: "CPI"
text_report_cpi: "Invoiced hours ÷ spent hours. 1.00 or more (green): every hour worked was billed; below 1 (yellow): some time wasn't billed; below 0.80 (red): a fifth or more wasn't."
label_report_spent_of_estimated: "Spent vs. issues' estimated hours" label_report_spent_of_estimated: "Spent vs. issues' estimated hours"
text_report_syncing: "QuickBooks is still syncing, so these figures are incomplete until it finishes. This page refreshes every 30 seconds." text_report_syncing: "QuickBooks is still syncing, so these figures are incomplete until it finishes. This page refreshes every 30 seconds."
text_qbo_sync_running: "syncing, %{count} read so far (started %{time})" text_qbo_sync_running: "syncing, %{count} read so far (started %{time})"
+1 -1
View File
@@ -14,7 +14,7 @@ Redmine::Plugin.register :redmine_qbo do
name 'Redmine QBO plugin' name 'Redmine QBO plugin'
author 'Rick Barrette' 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' 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.2' version '2026.11.4'
url 'https://github.com/rickbarrette/redmine_qbo' url 'https://github.com/rickbarrette/redmine_qbo'
author_url 'https://barrettefabrication.com' author_url 'https://barrettefabrication.com'
settings default: {empty: true}, partial: 'qbo/settings' settings default: {empty: true}, partial: 'qbo/settings'
@@ -79,6 +79,26 @@ module RedmineQboBilling
} }
end end
# Cost performance index: invoiced hours / spent hours (e.g. 0.85), or nil without spent time. Below
# CPI_WARNING (0.8) is poor, below 1 is under, 1 or more is on or over (more billed than worked).
CPI_WARNING = 0.8
def self.cpi(invoice_hours, spent_hours)
spent = spent_hours.to_f
spent.positive? ? (invoice_hours.to_f / spent).round(2) : nil
end
# :poor (below 0.8), :under (below 1) or :good (1 or more); nil without a CPI
def self.cpi_level(cpi)
return nil if cpi.nil?
return :poor if cpi < CPI_WARNING
cpi < 1 ? :under : :good
end
def cpi
self.class.cpi(hours[:invoice_hours], hours[:spent_hours])
end
# Percentages comparing the figures (nil when there's nothing to compare against) # Percentages comparing the figures (nil when there's nothing to compare against)
def ratios def ratios
{ {
@@ -166,6 +166,60 @@ module RedmineQboBilling
end end
end end
# Statuses an estimate moves from to Accepted when the work starts (issues are created from it)
ACCEPTABLE_STATUSES = ['', 'Pending'].freeze
# A sparse update that only changes an estimate's status. QuickBooks still requires the estimate's lines
# in it ("At least 1 line item is required"), so they're sent back exactly as QuickBooks returned them.
def status_update(estimate, status)
update = Quickbooks::Model::Estimate.new
update.id = estimate.id
update.sync_token = estimate.sync_token
update.customer_ref = estimate.customer_ref
update.line_items = Array(estimate.line_items)
update.txn_status = status
update
end
AcceptResult = Struct.new(:outcome, :message) do
def accepted?; outcome == :accepted; end
def failed?; outcome == :failed; end
end
# Marks the estimate Accepted in QuickBooks when issues are created from it (the customer went ahead with
# the work), accepted today by the customer, as QuickBooks' own Accept does. Only a pending estimate
# changes; Accepted, Closed, Converted or Rejected ones are left as they are. Returns an AcceptResult:
# :accepted, :unchanged, or :failed with QuickBooks' message (never raised: the issues stand).
def accept(estimate_id, user: User.current)
outcome, status = QboEstimateService.with_service do |service|
estimate = service.fetch_by_id(estimate_id)
next [:failed, I18n.t(:notice_estimate_not_found)] if estimate.nil?
next [:unchanged, estimate.txn_status.to_s] unless ACCEPTABLE_STATUSES.include?(estimate.txn_status.to_s)
update = status_update(estimate, 'Accepted')
update.accepted_date = user.today
update.accepted_by = estimate.customer_ref&.name.presence ||
Customer.find_by(id: estimate.customer_ref&.value)&.name
saved = service.update(update, sparse: true)
saved&.txn_status.to_s == 'Accepted' ? [:accepted, nil] : [:failed, saved&.txn_status.to_s.presence || 'no answer']
end
if outcome == :accepted
sync_local(Struct.new(:id).new(estimate_id))
AcceptResult.new(:accepted, nil)
elsif outcome == :unchanged
AcceptResult.new(:unchanged, status)
else
message = I18n.t(:error_estimate_not_accepted, status: status)
Rails.logger.warn "[RedmineQboBilling] Estimate #{estimate_id}: #{message}"
AcceptResult.new(:failed, message)
end
rescue StandardError => e
message = e.respond_to?(:detail) && e.detail.present? ? "#{e.message}: #{e.detail}" : e.message
Rails.logger.warn "[RedmineQboBilling] Could not mark estimate #{estimate_id} accepted: #{message}"
AcceptResult.new(:failed, message)
end
# Emails the estimate; QuickBooks uses its own estimate email template # Emails the estimate; QuickBooks uses its own estimate email template
def send_email(id, email) def send_email(id, email)
sent = QboEstimateService.with_service { |service| service.send_estimate(id, email) } sent = QboEstimateService.with_service { |service| service.send_estimate(id, email) }
+47
View File
@@ -0,0 +1,47 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module RedmineQboBilling
# An invoice's status, worked out from its total, balance and due date the way QuickBooks' invoice list
# shows it (QuickBooks keeps no status field on invoices):
# :voided - nothing to pay at all (a voided invoice has a zero total)
# :paid - nothing left owing
# :partial - some of it paid
# :overdue - money owing and past the due date
# :open - money owing, not yet due
# nil when the balance isn't known (e.g. an invoice synced before balances were kept).
module InvoiceStatus
STATUSES = %i[voided paid partial overdue open].freeze
module_function
def status(total:, balance:, due_date: nil, today: Date.current)
return nil if balance.nil? || balance.to_s.strip.empty?
total = to_d(total)
balance = to_d(balance)
return :voided if total.zero? && balance.zero?
return :paid if balance <= 0
return :overdue if due_date && due_date < today
balance < total ? :partial : :open
end
def label(status)
status ? I18n.t("label_invoice_status_#{status}") : ''
end
def to_d(value)
BigDecimal(value.to_s.presence || '0')
rescue ArgumentError
BigDecimal('0')
end
end
end
+1 -6
View File
@@ -270,12 +270,7 @@ module RedmineQboBilling
# Already Converted or Closed is left as QuickBooks set it # Already Converted or Closed is left as QuickBooks set it
next if estimate.nil? || BILLED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s) next if estimate.nil? || BILLED_ESTIMATE_STATUSES.include?(estimate.txn_status.to_s)
update = Quickbooks::Model::Estimate.new service.update(writer.status_update(estimate, 'Closed'), sparse: true)
update.id = estimate.id
update.sync_token = estimate.sync_token
update.customer_ref = estimate.customer_ref
update.txn_status = 'Closed'
service.update(update, sparse: true)
end end
EstimateSyncService.new.sync_by_id(id) EstimateSyncService.new.sync_by_id(id)
rescue StandardError => e rescue StandardError => e