Compare commits

..
Author SHA1 Message Date
rickyandClaude Opus 5.5 67d0ee43eb 2026.11.30
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:24:13 -05:00
rickyandClaude Opus 5.5 386daac307 Keep the subject column readable on the Create issues page
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:13:04 -05:00
rickyandClaude Opus 5.5 7894e09f05 Build issue descriptions and pick templates from the estimate's jobs
Creating issues from an estimate now groups its lines into jobs
(subtotals end a job; parts go with the labor line before them, or the
job's first labor line when listed first), adds the estimate's notes and
the job's parts to each issue's description, preselects the template
whose note has matching "Match:" phrases, and uses a named labor
service's name (e.g. Standard Alignment) as the subject.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 21:11:00 -05:00
rickyandClaude Opus 5.5 0aa95918f6 Fill {{customer}}, {{estimate}} and hooked macros in issue notes
A journal patch fills macros when a note is saved or edited, so note
templates can use them like issue templates do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 20:26:25 -05:00
rickyandClaude Opus 5.5 6006bd98f0 2026.11.29
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:15:33 -05:00
rickyandClaude Opus 5.5 eb8bfc724b Fill {{customer}}, {{estimate}} and hooked macros in issues
Issue templates can use {{name}} macros in the subject and description;
they're filled when the issue is saved, once they have a value. Other
plugins add macros through the new :qbo_issue_macros hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 08:15:33 -05:00
rickyandClaude Opus 5.5 8ce702cb44 2026.11.28
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:47:15 -05:00
rickyandClaude Opus 5.5 ae0ffc7c1c Leave other plugins' features to hooks
Refund emails and PDFs take the shop name and mail settings from
:qbo_mail_settings instead of reading redmine_qbo_reminders' settings; the
customer page's ticked boxes use generic data-ticked-field/data-ticked-params
instead of knowing redmine_qbo_calendar's Add appointment link; and Create
issues carries the params plugins name in :qbo_billing_issue_carry_params
instead of appointment_id.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 07:37:57 -05:00
27 changed files with 956 additions and 114 deletions

No files matched your search

+12 -3
View File
@@ -35,6 +35,8 @@ For production deployments, **use a tagged release**.
* Optionally associate a **QuickBooks Estimate** with the Issue.
* Automatically associates a **QuickBooks Invoice** with the Issue.
* **Macros** in an issue's subject, description or notes are filled in when it's saved, e.g. an issue template's `Estimate {{estimate}} for {{customer}}`: `{{customer}}` is the customer's name and `{{estimate}}` the estimate number. A macro without a value yet (no estimate linked) stays as typed and fills on a later save; in a note, which isn't saved again, it stays as typed unless the note is edited. Companion plugins add more through the `:qbo_issue_macros` hook (redmine_qbo_vehicles: `{{vehicle}}`).
---
@@ -162,7 +164,7 @@ Refunds for canceled orders and returned parts, following SOP-OPS-014, so they d
1. makes the restocking fee invoice, its line showing the math ("Restocking fee: 30% × $307.99 parts on E1068 = $92.40"), and pays it from the customer's credit, oldest first (unless QuickBooks already applied the credit to it on its own);
2. records the rest of the credit as a refund with the category **Accounts Receivable**, from the bank account in the settings, described "Refund for deposit on E1068": a **Check** for a check, an **Expense** for a card refund;
3. applies the customer's remaining credit to that check or expense, so the deposit, the fee invoice and the refund reconcile, and reads back the customer's balance (it should be $0.00).
* As ticked on the page, it also marks the estimate **Rejected**, sets the order's work orders to the canceled status with the reason as a note, and emails the customer a summary (through redmine_qbo_reminders' mail settings when that plugin is set up, otherwise Redmine's).
* As ticked on the page, it also marks the estimate **Rejected**, sets the order's work orders to the canceled status with the reason as a note, and emails the customer a summary (with the shop name and mail settings another plugin gives through `:qbo_mail_settings`, e.g. redmine_qbo_reminders', otherwise Redmine's).
* Each refund has its own page, listed on the customer page: what was refunded and how, with the fee invoice (opened in Redmine), a **PDF** of the refund (QuickBooks has no PDF of a check or an expense), the fee invoice's PDF, and **Email the customer** to send the summary again. If a QuickBooks step fails, the refund stops there and its page says which step and what was already done, to finish in QuickBooks.
* It refunds all of the customer's remaining credit held as unapplied payments. Credit held as credit memos isn't refunded here.
@@ -224,7 +226,11 @@ Administration → Items lists the QuickBooks product/service list (synced from
* **Write estimates**: create and edit estimates
* **Edit estimates linked to issues**: unlock an estimate an issue is linked to and change it (on top of Write estimates)
* **Email estimates**: email estimates to customers (Save and send, and the Email link)
* **Create issues from estimates**: the Create issues page (was redmine_qbo_calendar's "Create issues from appointment estimates")
* **Create issues from estimates**: the Create issues page (was redmine_qbo_calendar's "Create issues from appointment estimates"). Each labor line becomes an issue:
* **Jobs:** a subtotal line ends a job. Parts and notes belong to the labor line before them, or to the job's first labor line when they come before it (parts first, then labor). Notes at the top of the estimate (e.g. the diagnosis) go with every job. With parts first and no subtotal between two jobs the page warns that some parts may be under the wrong job.
* **Description:** the template's (or the default) description, then "From the estimate": the notes and the job's parts. A template can place them itself with `{{estimate_notes}}` and `{{estimate_parts}}` (filled once, when the issue is created).
* **Subject:** the labor line's description; for a named labor service (anything but "Labor", e.g. Standard Alignment) its name, with the line's description added to the notes.
* **Template matching** (with redmine_issue_templates): a template whose note has a line like `Match: ball joints, tf jl ball joints` is preselected, with its tracker, when the labor line's name or text, or its parts' product names, contain one of the phrases (whole words, ignoring case, punctuation and plural "s"). The longest phrase wins, so a "TF JL Ball Joints" part picks the JL template over a plain "ball joints" one.
* **View payments**: a customer's Payments list, the payment page and its PDF
* **Receive payments**: the Receive payment page, plus everything View payments allows
* **View business reports**: the Business report
@@ -277,7 +283,10 @@ Hook|:qbo_billing_issues_created, { estimate:, issues:, params: } | Called after
Hook|:qbo_billing_field_defaults, { customer:, issues: } | Return `{ field_id => value }` for a document's work orders: used when an invoice is made from an estimate, for the fields it leaves blank. New estimates and invoices start blank (redmine_qbo_vehicles: the work orders' VIN and highest mileage)
Hook|:qbo_billing_field_options, { customer: } | Return `{ field_id => [{ value:, label: }, ...] }` to suggest in the editor's custom field boxes for a customer (redmine_qbo_vehicles: the customer's vehicles for the VIN box)
View|:view_qbo_estimate_form_bottom, { form:, document: } | Add your plugin's script to the estimate/invoice editor. It can use `window.qboEditor` (`field(id)`, `fieldNamed(/name/)`, `setFieldOptions(id, options)`) and listen for `qbo:customer-changed` and `qbo:imported` on the form (redmine_qbo_vehicles fills the VIN and mileage)
View|checkboxes with `data-new-issue-param="issue[field]"` and `data-appointment-param="field"` on the customer page | Ticking one adds `issue[field]=value` to the New issue link and `field=value` to redmine_qbo_calendar's Add appointment link (`#appointment_link`), one per field (redmine_qbo's estimates: `estimate_id`, redmine_qbo_vehicles' vehicles: `vehicle_id`)
View|checkboxes with `data-ticked-field="field"`, links with `data-ticked-params` on the customer page | Ticking a box adds its value to every link with `data-ticked-params`, named by that format: `issue[%s]` for the New issue link, `%s` for a plain param (e.g. redmine_qbo_calendar's Add appointment link). One box per field (redmine_qbo's estimates: `estimate_id`, redmine_qbo_vehicles' vehicles: `vehicle_id`)
Hook|:qbo_issue_macros, { issue: } | Return `{ 'name' => text }` to fill `{{name}}` in an issue's subject, description and notes when they're saved (redmine_qbo_vehicles: `{{vehicle}}`). Leave a name out, or give nil, while it has no value; the macro then waits for a later save
Hook|:qbo_billing_issue_carry_params | Return names of request params the Create issues from estimate page keeps through its form (redmine_qbo_calendar: `appointment_id`)
Hook|:qbo_mail_settings | Return any of `shop_name`, `from`, `reply_to` and `delivery` (options for ActionMailer's `mail()`, e.g. an SMTP server) for customer emails such as refund summaries (redmine_qbo_reminders: its shop name and email settings). Blank ones fall back to Redmine's settings
View Hook|:view_qbo_estimate_contextual, { estimate_id:, customer_id:, custom_fields:, doc_number: } | Adds links to an estimate page's action area (e.g. redmine_qbo_calendar's Add appointment); `custom_fields` is `{ field_id => value }`
View Hook|:view_qbo_invoice_contextual, { invoice_id:, customer_id:, doc_number: } | Adds links to an invoice page's action area (e.g. redmine_qbo_labels' Print label)
+5 -5
View File
@@ -21,16 +21,16 @@ class QboRefundMailer < ActionMailer::Base
def refund_summary(refund, email)
@refund = refund
@customer = refund.customer
reminders = defined?(RedmineQboReminders::Settings) ? RedmineQboReminders::Settings.current : nil
@shop_name = reminders&.[]('shop_name').to_s.presence || Setting.app_title
delivery = reminders ? reminders.delivery_options : {}
settings = RedmineQboBilling.mail_settings
@shop_name = settings[:shop_name].presence || Setting.app_title
delivery = settings[:delivery] || {}
if delivery.empty? && !ActionMailer::Base.perform_deliveries
raise DeliveryOff, I18n.t(:text_refund_email_off)
end
options = { to: email, from: reminders&.from.presence || Setting.mail_from.to_s,
options = { to: email, from: settings[:from].presence || Setting.mail_from.to_s,
subject: I18n.t(:text_refund_email_subject, shop: @shop_name, amount: RedmineQboBilling::RefundWriter.money(refund.refund_amount)) }
options[:reply_to] = reminders.reply_to if reminders&.reply_to
options[:reply_to] = settings[:reply_to] if settings[:reply_to]
message = mail(options.merge(delivery)) do |format|
format.text
end
@@ -1,40 +1,33 @@
<%#
Adds what's ticked on the customer page to its links: "New issue" (#dynamic-new-issue-link in the contextual area)
and redmine_qbo_calendar's "Add appointment" (#appointment_link). A checkbox takes part with
data-new-issue-param="issue[field]" (New issue) and data-appointment-param="field" (Add appointment); one is
ticked per field: this plugin's estimates (estimate_id), and other plugins' lists (e.g. redmine_qbo_vehicles'
vehicle_id).
Adds what's ticked on the customer page to its links. A checkbox takes part with data-ticked-field="field"
(one is ticked per field), e.g. this plugin's estimates (estimate_id) and other plugins' lists. A link takes
part with data-ticked-params, how each field is named in its URL: "issue[%s]" for New issue
(#dynamic-new-issue-link), "%s" for a plain param. Other plugins' links on the page work the same way.
%>
<script>
(function () {
var LINKS = [['dynamic-new-issue-link', 'data-new-issue-param'], ['appointment_link', 'data-appointment-param']];
var ANY = 'input[data-new-issue-param], input[data-appointment-param]';
var BOX = 'input[data-ticked-field]';
function boxes(attr, param) {
return Array.prototype.filter.call(document.querySelectorAll('input[' + attr + ']'), function (cb) {
return !param || cb.getAttribute(attr) === param;
function boxes(field) {
return Array.prototype.filter.call(document.querySelectorAll(BOX), function (cb) {
return !field || cb.getAttribute('data-ticked-field') === field;
});
}
// Boxes for the same field (the same estimate list, the same vehicle list)
function sameField(box) {
for (var i = 0; i < LINKS.length; i++) {
var attr = LINKS[i][1], param = box.getAttribute(attr);
if (param) return boxes(attr, param);
}
return [box];
function fields() {
return boxes().map(function (cb) { return cb.getAttribute('data-ticked-field'); })
.filter(function (field, i, all) { return all.indexOf(field) === i; });
}
function updateLinks() {
LINKS.forEach(function (pair) {
var link = document.getElementById(pair[0]);
if (!link) return;
Array.prototype.forEach.call(document.querySelectorAll('a[data-ticked-params]'), function (link) {
// Cache the pristine base URL on first run
if (!link.dataset.baseUrl) link.dataset.baseUrl = link.getAttribute('href');
var url = new URL(link.dataset.baseUrl, window.location.origin);
boxes(pair[1]).forEach(function (cb) {
var param = cb.getAttribute(pair[1]);
var ticked = boxes(pair[1], param).filter(function (b) { return b.checked; })[0];
var format = link.getAttribute('data-ticked-params');
fields().forEach(function (field) {
var param = format.replace('%s', field);
var ticked = boxes(field).filter(function (b) { return b.checked; })[0];
if (ticked) {
url.searchParams.set(param, ticked.value);
} else {
@@ -48,9 +41,9 @@
// One box per field: ticking one unticks the others for the same field
document.addEventListener('change', function (event) {
var box = event.target;
if (!box.matches || !box.matches(ANY)) return;
if (!box.matches || !box.matches(BOX)) return;
if (box.checked) {
sameField(box).forEach(function (cb) { if (cb !== box) cb.checked = false; });
boxes(box.getAttribute('data-ticked-field')).forEach(function (cb) { if (cb !== box) cb.checked = false; });
}
updateLinks();
});
+1 -1
View File
@@ -6,7 +6,7 @@
<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 %>
id: 'dynamic-new-issue-link', class: 'icon icon-add', target: :_blank, data: { ticked_params: 'issue[%s]' } %>
<%# 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; Open in
+2 -2
View File
@@ -5,8 +5,8 @@
<% estimates.sort.reverse.each do |estimate| %>
<%# One cell each (qbo_estimates/_status_styles lines them up in columns, so the icons line up) %>
<div class="row">
<%# Ticking an estimate adds it to the customer page's New issue and Add appointment links (customers/_new_issue_link_script) %>
<span class="qbo-list-check"><%= check_box_tag "estimate_ids[]", estimate.id, false, data: { new_issue_param: 'issue[estimate_id]', appointment_param: 'estimate_id' }, class: "estimate-checkbox" if local_assigns[:new_issue_checkboxes] %></span>
<%# Ticking an estimate adds it to the customer page's links (customers/_new_issue_link_script) %>
<span class="qbo-list-check"><%= check_box_tag "estimate_ids[]", estimate.id, false, data: { ticked_field: 'estimate_id' }, class: "estimate-checkbox" if local_assigns[:new_issue_checkboxes] %></span>
<b class="qbo-list-number"><%= link_to "##{estimate.doc_number}", estimate_path(estimate), target: :_blank %></b>
<span class="qbo-list-date"><%= estimate.txn_date %></span>
<%# QuickBooks status, cached by the estimate sync (kept current by the webhook) %>
@@ -1,6 +1,6 @@
<% html_title l(:button_create_estimate_issues) %>
<%# Extra params to carry through (e.g. appointment_id from redmine_qbo_calendar) %>
<% carry = request.query_parameters.merge(request.request_parameters).slice('appointment_id') %>
<%# Params other plugins carry through the page (:qbo_billing_issue_carry_params, e.g. redmine_qbo_calendar's appointment) %>
<% carry = request.query_parameters.merge(request.request_parameters).slice(*Redmine::Hook.call_hook(:qbo_billing_issue_carry_params, {}).flatten.compact.map(&:to_s)) %>
<div class="contextual">
<%= link_to sprite_icon('angle-left', @return_label), @return_path, class: 'icon icon-angle-left' %>
@@ -98,6 +98,10 @@
<%= hidden_field_tag :parent_issue_id, @parent_issue&.id || @parent_issue_id, id: nil %>
<% carry.each do |key, value| %><%= hidden_field_tag key, value, id: nil %><% end %>
<% if @builder.ambiguous_parts? %>
<p class="warning estimate-parts-ambiguous"><%= l(:warning_estimate_parts_ambiguous) %></p>
<% end %>
<table class="list estimate-issues-preview">
<thead>
<tr>
@@ -132,8 +136,11 @@
<%
row = (@rows[proposal.line_id] || {}).to_h
selected = row.empty? || row['selected'] == '1'
tracker_id = (row['tracker_id'].presence || @default_tracker&.id).to_i
template_key = row.key?('template') ? row['template'] : default_template_for.call(tracker_id)
# A template whose "Match:" note fits the line and its parts picks the tracker and template
suggested = templates_enabled ? @builder.suggested_template(proposal, @templates) : nil
suggested = nil unless suggested && @trackers.any? { |t| t.id == suggested.tracker_id }
tracker_id = (row['tracker_id'].presence || suggested&.tracker_id || @default_tracker&.id).to_i
template_key = row.key?('template') ? row['template'] : (suggested&.key || default_template_for.call(tracker_id))
hours = row.key?('estimated_hours') ? row['estimated_hours'] : proposal.hours
%>
<tr class="estimate-line">
@@ -145,6 +152,12 @@
<td class="subject">
<%= text_field_tag "#{field}[subject]", row['subject'] || proposal.description,
maxlength: 255, class: 'estimate-line-subject', id: nil %>
<% if proposal.parts.present? %>
<div class="estimate-line-parts"><em class="info">
<%= l(:label_estimate_line_parts) %>
<%= proposal.parts.map { |part| "#{part.quantity} × #{part.item_name.presence || part.description.lines.first.to_s.strip}" }.join(', ') %>
</em></div>
<% end %>
</td>
<td>
<%= select_tag "#{field}[tracker_id]",
@@ -209,6 +222,7 @@
<p class="estimate-issues-hint">
<% if templates_enabled %>
<%= l(:text_estimate_issues_template_hint) %>
<%= l(:text_estimate_issues_template_match_hint) %>
<% else %>
<%= l(:text_estimate_issues_hint) %>
<% end %>
@@ -308,6 +322,9 @@
.estimate-preview-subtitle { font-weight: normal; font-size: 0.8em; color: #777; }
table.estimate-issues-preview td.subject { text-align: left; }
table.estimate-issues-preview td.subject input { width: 98%; }
table.estimate-issues-preview td.subject { min-width: 16em; }
table.estimate-issues-preview select.estimate-line-template { max-width: 18em; }
table.estimate-issues-preview .estimate-line-parts { font-size: 0.9em; margin-top: 2px; }
table.estimate-issues-preview tr.created td { color: #888; }
.estimate-issues-hint { color: #777; font-size: 0.9em; }
.estimate-issue-fields .estimate-issue-fields-info { padding-left: 0; }
+6
View File
@@ -302,6 +302,11 @@ en:
label_estimate_issue_settings: "Issues from estimates"
label_estimate_item: "Item"
label_estimate_line_already_created: "Already created"
label_estimate_issue_details: "From the estimate"
label_estimate_issue_notes: "Notes"
label_estimate_issue_parts: "Parts"
label_estimate_line_parts: "Parts:"
warning_estimate_parts_ambiguous: "This estimate lists parts before a labor line and has no subtotal between some jobs, so some parts may be listed under the wrong job. Check the parts below, or add a subtotal after each job in QuickBooks."
label_issue_template: "Template"
label_no_issue_template: "(no template)"
notice_estimate_accepted: "Estimate #%{number} is now Accepted in QuickBooks."
@@ -314,6 +319,7 @@ en:
text_default_tracker_info: "Pre-selected for each proposed issue. Leave blank to use the project's first tracker."
text_estimate_issue_fields_info: "Entered once and applied to every created issue whose tracker uses the field. Fields marked * are required by the selected trackers."
text_estimate_issues_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. Edit anything before creating. New issues are related to each other and to issues already created from this estimate."
text_estimate_issues_template_match_hint: "A template whose note has a line like \"Match: ball joints, tf jl ball joints\" is picked when the estimate line or its parts' names contain one of those words; each issue's description also gets the estimate's notes and the line's parts."
text_estimate_issues_template_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. A template supplies the issue's description. New issues are related to each other and to issues already created from this estimate."
# Payments
+1 -1
View File
@@ -14,7 +14,7 @@ Redmine::Plugin.register :redmine_qbo do
name 'Redmine QBO plugin'
author 'Rick Barrette'
description 'A pluging for Redmine to connect with QuickBooks Online: customers, time activities for billable hours when an issue is closed, and estimates, invoices and payments written in Redmine'
version '2026.11.27'
version '2026.11.30'
url 'https://github.com/rickbarrette/redmine_qbo'
author_url 'https://barrettefabrication.com'
settings default: {empty: true}, partial: 'qbo/settings'
+1
View File
@@ -12,6 +12,7 @@ module RedmineQbo
def self.setup
# === Models ===
Issue.prepend RedmineQbo::Patches::IssuePatch
Journal.prepend RedmineQbo::Patches::JournalPatch
User.prepend RedmineQbo::Patches::UserPatch
# === Queries ===
+67
View File
@@ -0,0 +1,67 @@
#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
# Fills {{name}} macros in an issue's subject and description (e.g. from an issue template:
# "Estimate {{estimate}} for {{customer}}") when the issue is saved. Built in: {{customer}} and
# {{estimate}}. Other plugins add their own through the :qbo_issue_macros hook (e.g.
# redmine_qbo_vehicles' {{vehicle}}).
#
# A macro without a value yet (no estimate linked) stays as typed, so it fills on a later save.
# Names nobody provides are left alone, which keeps Redmine's own wiki macros such as {{toc}} working.
#
# Issue notes are filled too (e.g. from a note template), when the note is saved or edited; see
# Patches::JournalPatch. A note isn't saved again later, so a macro without a value stays as typed there.
module IssueMacros
PATTERN = /\{\{\s*([a-z][a-z0-9_]*)\s*\}\}/i
FIELDS = %i[subject description].freeze
module_function
def fill(issue)
texts = FIELDS.to_h { |field| [field, issue.send(field).to_s] }
return unless texts.values.any? { |text| text.match?(PATTERN) }
known = values(issue)
return if known.empty?
texts.each do |field, text|
filled = substitute(text, known)
issue.send("#{field}=", filled) unless filled == text
end
end
# The text with this issue's macros filled in (e.g. a note); the text itself when there's nothing to fill
def fill_text(issue, text)
return text unless text.to_s.match?(PATTERN)
known = values(issue)
known.empty? ? text : substitute(text, known)
end
def substitute(text, known)
text.gsub(PATTERN) { known[Regexp.last_match(1).downcase] || Regexp.last_match(0) }
end
# { 'name' => text } for every macro with a value for this issue
def values(issue)
found = {
'customer' => issue.customer&.name,
'estimate' => issue.estimate&.to_s
}
Redmine::Hook.call_hook(:qbo_issue_macros, { issue: issue }).each do |result|
next unless result.is_a?(Hash)
result.each { |name, value| found[name.to_s.downcase] = value }
end
found.transform_values { |value| value.to_s.strip.presence }.compact
end
end
end
+56 -54
View File
@@ -1,55 +1,57 @@
#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
module IssuePatch
extend ActiveSupport::Concern
prepended do
belongs_to :customer
belongs_to :estimate
has_and_belongs_to_many :invoices
before_save :titlize_subject
after_commit :enqueue_billing, on: :update
end
# Enqueue a background job to bill the time spent on this issue to QuickBooks if the issue is closed and assigned to an employee
def enqueue_billing
log "Checking if issue needs billing for ##{id}"
return unless closed? && customer.present? && assigned_to&.employee_id.present?
log "Enqueuing billing for issue ##{id}"
BillIssueTimeJob.perform_later(id)
end
# Capitalize each word of the subject for consistent billing descriptions, without lowercasing
# the rest of the word (keeps LED, JL, 4x4 as typed). Only runs when the subject changes.
def titlize_subject
return unless subject.present? && will_save_change_to_subject?
log "Titlizing subject for issue ##{id}"
self.subject = RedmineQbo::TitleCase.call(subject)
end
# Generate a shareable token linking this issue to the customer for QuickBooks
def share_token
CustomerToken.get_token(self)
end
private
def log(msg)
Rails.logger.info "[IssuePatch] #{msg}"
end
end
end
#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
module IssuePatch
extend ActiveSupport::Concern
prepended do
belongs_to :customer
belongs_to :estimate
has_and_belongs_to_many :invoices
# {{customer}}, {{estimate}} and other plugins' macros (e.g. from an issue template)
before_validation { RedmineQbo::IssueMacros.fill(self) }
before_save :titlize_subject
after_commit :enqueue_billing, on: :update
end
# Enqueue a background job to bill the time spent on this issue to QuickBooks if the issue is closed and assigned to an employee
def enqueue_billing
log "Checking if issue needs billing for ##{id}"
return unless closed? && customer.present? && assigned_to&.employee_id.present?
log "Enqueuing billing for issue ##{id}"
BillIssueTimeJob.perform_later(id)
end
# Capitalize each word of the subject for consistent billing descriptions, without lowercasing
# the rest of the word (keeps LED, JL, 4x4 as typed). Only runs when the subject changes.
def titlize_subject
return unless subject.present? && will_save_change_to_subject?
log "Titlizing subject for issue ##{id}"
self.subject = RedmineQbo::TitleCase.call(subject)
end
# Generate a shareable token linking this issue to the customer for QuickBooks
def share_token
CustomerToken.get_token(self)
end
private
def log(msg)
Rails.logger.info "[IssuePatch] #{msg}"
end
end
end
end
+32
View File
@@ -0,0 +1,32 @@
#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
# Fills {{customer}}, {{estimate}} and hooked macros in an issue note (e.g. from a note template)
# when the note is saved, including when it's edited later
module JournalPatch
extend ActiveSupport::Concern
prepended do
before_save :fill_qbo_macros
end
private
def fill_qbo_macros
return unless journalized.is_a?(Issue) && notes.to_s.match?(RedmineQbo::IssueMacros::PATTERN)
filled = RedmineQbo::IssueMacros.fill_text(journalized, notes)
self.notes = filled unless filled == notes
end
end
end
end
+12
View File
@@ -30,6 +30,18 @@ module RedmineQboBilling
# Suggestions for the editor's custom field boxes for a customer, from plugins answering
# :qbo_billing_field_options, { customer: } => { field_id => [{ value:, label: }, ...] }
# (e.g. redmine_qbo_vehicles: the customer's vehicles for its VIN field). Returns { "2" => [...] }.
# The shop's name and how customer emails (refund summaries) are sent, from other plugins (e.g.
# redmine_qbo_reminders: its shop name and SMTP server) through :qbo_mail_settings. Each returns any of
# shop_name:, from:, reply_to:, delivery: (options for ActionMailer's mail(), e.g. an SMTP server); blank
# ones fall back to Redmine's own settings.
def self.mail_settings
Redmine::Hook.call_hook(:qbo_mail_settings, {}).select { |result| result.is_a?(Hash) }
.reduce({}) { |merged, result| merged.merge(result.symbolize_keys.compact_blank) }
rescue StandardError => e
Rails.logger.warn "[RedmineQboBilling] Could not read mail settings from plugins: #{e.message}"
{}
end
def self.field_options(customer)
return {} unless customer
@@ -13,7 +13,11 @@ module RedmineQboBilling
# on the "Create issues from estimate" page (moved here from redmine_qbo_calendar).
#
# - Only lines with a labor product/service (LaborItems, e.g. "Labor") are proposed
# - Subject = the line's description; estimated hours = the line's quantity
# - Subject = the line's description; estimated hours = the line's quantity. For a named labor service
# (e.g. "Standard Alignment", where the description is a list of what's included) the subject is the
# product/service name and the description goes with the line's notes
# - Each line's parts and notes (EstimateJobs) are added to its issue's description (EstimateIssueDetails),
# and #suggested_template picks a template from the line and its parts (TemplateMatcher)
# - Lines already turned into issues are shown but can't be created again
# - Creation is all-or-nothing: if any issue fails validation, none are saved
# - All issues created from the same estimate are related to each other, across batches
@@ -34,7 +38,7 @@ module RedmineQboBilling
class EstimateIssueBuilder
include Redmine::I18n
Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, keyword_init: true) do
Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, :parts, :notes, keyword_init: true) do
def created?
existing_issue.present?
end
@@ -110,6 +114,21 @@ module RedmineQboBilling
@proposals ||= build_proposals
end
# The estimate's lines grouped into jobs (each labor line's parts and notes)
def jobs
@jobs ||= EstimateJobs.new(estimate.present? ? estimate.line_items : [])
end
# True when parts came first and two jobs had no subtotal between them, so a job's parts may be wrong
def ambiguous_parts?
jobs.ambiguous?
end
# The template (an IssueTemplateSupport option) whose "Match:" phrases fit the line and its parts, or nil
def suggested_template(proposal, templates)
TemplateMatcher.best(templates, proposal.item_name, proposal.description, Array(proposal.parts).map(&:item_name))
end
# rows: { line_id => { 'selected' => '1', 'subject' => ..., 'tracker_id' => ..., 'template' => 'global:3', 'estimated_hours' => ... } }
# custom_field_values: { custom_field_id => value }, applied to every issue whose tracker uses the field
# Returns the created issues, or [] with #errors filled in.
@@ -162,8 +181,10 @@ module RedmineQboBilling
ids = LaborItems.ids
codes = LaborItems.codes
links = QboEstimateLineIssue.where(estimate_id: estimate.id).includes(:issue).index_by(&:line_id)
line_items = Array(estimate.line_items)
@jobs = EstimateJobs.new(line_items, labor: ->(ref) { LaborItems.match?(ref, ids: ids, codes: codes) })
Array(estimate.line_items).each_with_index.filter_map do |line, index|
line_items.each_with_index.filter_map do |line, index|
detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil
next if detail.nil? || detail.item_ref.nil?
@@ -174,27 +195,29 @@ module RedmineQboBilling
description = line.description.to_s.strip
next if description.blank?
line_id = line_key(line, index)
line_id = EstimateJobs.line_key(line, index)
quantity = detail.respond_to?(:quantity) ? detail.quantity.to_f : 0.0
job = @jobs.job(line_id)
notes = @jobs.notes + (job ? job.notes : [])
# A named labor service: its name is the subject, its description (what's included) a note
if item_name.present? && !LaborItems.name_matches?(item_name, LaborItems::DEFAULT_CODES)
notes += [description]
description = item_name.split(':').last.strip
end
Proposal.new(
line_id: line_id,
item_name: item_name,
description: description,
hours: quantity.positive? ? quantity : nil,
existing_issue: links[line_id]&.issue
existing_issue: links[line_id]&.issue,
parts: job ? job.parts : [],
notes: notes
)
end
end
# QBO line Ids are stable for the life of the estimate; fall back to line number / position
def line_key(line, index)
key = line.respond_to?(:id) ? line.id : nil
key = line.line_num if key.blank? && line.respond_to?(:line_num)
key = "pos-#{index}" if key.blank?
key.to_s
end
# Relates the new issues to each other and to every issue created earlier from the same estimate,
# except their parent and its ancestors (Redmine doesn't allow relating a subtask to its parent)
def relate_issues(new_issues)
@@ -218,7 +241,8 @@ module RedmineQboBilling
issue.subject = (row['subject'].presence || proposal.description).to_s.strip.truncate(255)
template = IssueTemplateSupport.find(row['template'], project)
issue.description = template&.description.presence || default_description
issue.description = EstimateIssueDetails.apply(template&.description.presence || default_description,
notes: proposal.notes, parts: proposal.parts)
hours = row.key?('estimated_hours') ? row['estimated_hours'] : proposal.hours
issue.estimated_hours = hours.presence
@@ -0,0 +1,54 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module RedmineQboBilling
# Adds an estimate's notes and a job's parts to a new issue's description (issues created from an estimate).
#
# A template can place them with {{estimate_notes}} and {{estimate_parts}}; otherwise they're added at the
# end under "From the estimate". These are filled once, when the issue is created: later saves can't see
# the estimate's lines (unlike redmine_qbo's issue macros such as {{estimate}}).
module EstimateIssueDetails
NOTES = /\{\{\s*estimate_notes\s*\}\}/i
PARTS = /\{\{\s*estimate_parts\s*\}\}/i
module_function
def apply(text, notes:, parts:)
text = text.to_s
notes_text = notes_markdown(notes)
parts_text = parts_markdown(parts)
placed = text.match?(NOTES) || text.match?(PARTS)
text = text.gsub(NOTES) { notes_text }.gsub(PARTS) { parts_text }
return text if placed
sections = []
sections << "**#{I18n.t(:label_estimate_issue_notes)}**\n\n#{notes_text}" if notes_text.present?
sections << "**#{I18n.t(:label_estimate_issue_parts)}**\n\n#{parts_text}" if parts_text.present?
return text if sections.empty?
[text.rstrip, '---', "### #{I18n.t(:label_estimate_issue_details)}", *sections].reject(&:empty?).join("\n\n")
end
# Each note as a quote, its lines kept
def notes_markdown(notes)
Array(notes).map { |note| note.to_s.strip.lines.map { |l| "> #{l.rstrip}" }.join("\n") }.reject(&:empty?).join("\n>\n")
end
# "* 2 × **Item** — description; part number"
def parts_markdown(parts)
Array(parts).map do |part|
description = part.description.to_s.lines.map(&:strip).reject(&:empty?).join('; ')
line = "* #{part.quantity.presence || 1} × **#{part.item_name.presence || '—'}**"
description.present? ? "#{line} — #{description}" : line
end.join("\n")
end
end
end
+141
View File
@@ -0,0 +1,141 @@
#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
# Groups an estimate's lines into jobs: each labor line with the parts and notes that go with it, for
# the issues created from the estimate.
#
# - A subtotal line ends a job (so does the end of the estimate)
# - A part or note belongs to the labor line before it; parts before the first labor line of a job
# belong to that first labor line (estimates written parts first, then labor)
# - Notes (description-only lines) before the first item are the estimate's own (e.g. the diagnosis)
# and go with every job
# - Parts in a job without a labor line (e.g. tires and wheels) belong to no issue
#
# Parts first with no subtotal between two jobs can't be told apart (the second job's parts follow the
# first labor line); #ambiguous? says when that may have happened.
class EstimateJobs
Part = Struct.new(:quantity, :item_name, :description, keyword_init: true)
Job = Struct.new(:line_id, :parts, :notes, keyword_init: true)
# QBO line Ids are stable for the life of the estimate; fall back to line number / position
def self.line_key(line, index)
key = line.respond_to?(:id) ? line.id : nil
key = line.line_num if key.blank? && line.respond_to?(:line_num)
key = "pos-#{index}" if key.blank?
key.to_s
end
attr_reader :notes
# labor: ->(item_ref) { true when the line's product/service is labor }
def initialize(line_items, labor: ->(item_ref) { LaborItems.match?(item_ref) })
@labor = labor
@jobs = {}
@notes = []
@ambiguous = false
group(Array(line_items))
end
def job(line_id)
@jobs[line_id.to_s]
end
def ambiguous?
@ambiguous
end
private
def group(lines)
started = false
reset_job
lines.each_with_index do |line, index|
case kind(line)
when :subtotal
reset_job
when :note
text = line.description.to_s.strip
next if text.empty?
started ? add(:notes, text) : @notes << text
when :labor
started = true
labor_line(self.class.line_key(line, index))
when :part
started = true
add(:parts, part(line))
end
end
end
def kind(line)
type = line.respond_to?(:detail_type) ? line.detail_type.to_s : ''
return :subtotal if type == 'SubTotalLineDetail'
return :note if type == 'DescriptionOnly'
return :part if type == 'GroupLineDetail'
detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil
return :ignore if detail.nil? || detail.item_ref.nil?
@labor.call(detail.item_ref) ? :labor : :part
end
def reset_job
@current = nil
@labor_count = 0
@pending = { parts: [], notes: [] }
end
def labor_line(line_id)
job = Job.new(line_id: line_id, parts: [], notes: [])
@labor_count += 1
if @current.nil?
job.parts.concat(@pending[:parts])
job.notes.concat(@pending[:notes])
elsif @pending[:parts].any?
# Parts came first, then a second labor line with no subtotal in between
@ambiguous = true
end
@current = job
@jobs[line_id] = job
end
def add(kind, item)
if @current
@current.send(kind) << item
else
@pending[kind] << item
end
end
def part(line)
if line.respond_to?(:detail_type) && line.detail_type.to_s == 'GroupLineDetail'
detail = line.group_line_detail
return Part.new(quantity: quantity(detail&.quantity), item_name: detail&.group_item_ref&.name.to_s,
description: line.description.to_s.strip)
end
detail = line.sales_line_item_detail
Part.new(quantity: quantity(detail.quantity), item_name: detail.item_ref.name.to_s.strip,
description: line.description.to_s.strip)
end
def quantity(value)
return '' if value.nil?
number = BigDecimal(value.to_s)
number == number.to_i ? number.to_i.to_s : number.to_s('F')
rescue ArgumentError
value.to_s
end
end
end
@@ -12,7 +12,7 @@ module RedmineQboBilling
# Optional support for redmine_issue_templates (https://github.com/agileware-jp/redmine_issue_templates).
# Everything here returns empty results when that plugin isn't installed or isn't enabled on the project.
module IssueTemplateSupport
Option = Struct.new(:key, :title, :tracker_id, :is_default, :description, :group, keyword_init: true)
Option = Struct.new(:key, :title, :tracker_id, :is_default, :description, :group, :match_phrases, keyword_init: true)
module_function
@@ -51,7 +51,8 @@ module RedmineQboBilling
tracker_id: template.tracker_id,
is_default: template.is_default?,
description: template.description,
group: group
group: group,
match_phrases: TemplateMatcher.phrases(template.try(:note))
)
end
end
+1 -2
View File
@@ -132,8 +132,7 @@ module RedmineQboBilling
end
def shop_name
reminders = defined?(RedmineQboReminders::Settings) ? RedmineQboReminders::Settings.current : nil
reminders&.[]('shop_name').to_s.presence || Setting.app_title
RedmineQboBilling.mail_settings[:shop_name].presence || Setting.app_title
rescue StandardError
Setting.app_title
end
@@ -0,0 +1,56 @@
#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
# Picks the issue template for an estimate line. A template opts in with a line in its note
# (redmine_issue_templates' "Note" field), e.g.
#
# Match: ball joints, tf jl ball joints, jl ball joints
#
# The line's text and its parts' product names are searched for each phrase (whole words, ignoring
# case, punctuation and plural "s"). The template with the longest phrase found wins, so
# "TF JL Ball Joints" beats "ball joints"; on a tie, the first template in the list.
module TemplateMatcher
MATCH_LINE = /^\s*match\s*:\s*(.+)$/i
module_function
# The phrases from a template's note
def phrases(note)
line = note.to_s.lines.map { |l| l.match(MATCH_LINE) }.compact.first
return [] unless line
line[1].split(',').map { |phrase| phrase.strip.downcase }.reject(&:empty?).uniq
end
# templates: IssueTemplateSupport options (with match_phrases); texts: the line's description, part names...
def best(templates, *texts)
haystack = " #{normalize(texts.flatten.compact.join(' '))} "
return nil if haystack.strip.empty?
best, best_length = nil, 0
Array(templates).each do |template|
Array(template.match_phrases).each do |phrase|
words = normalize(phrase)
next if words.empty? || words.length <= best_length
next unless haystack.include?(" #{words} ")
best, best_length = template, words.length
end
end
best
end
# Lower case words without punctuation or a plural "s"
def normalize(text)
text.to_s.downcase.scan(/[a-z0-9]+/).map { |word| word.length > 3 ? word.sub(/s\z/, '') : word }.join(' ')
end
end
end
@@ -62,6 +62,13 @@ class CustomersControllerTest < Redmine::IntegrationTest
assert_redirected_to '/customers/9101'
end
def test_new_issue_picks_up_ticked_boxes
grant(:view_customers, :add_issues)
get '/customers/9101'
assert_select 'a#dynamic-new-issue-link[data-ticked-params=?]', 'issue[%s]'
assert_includes response.body, "a[data-ticked-params]"
end
def test_show_lists_open_and_closed_issues
grant(:view_customers)
get '/customers/9101'
@@ -247,4 +247,35 @@ class QboEstimatesControllerTest < Redmine::IntegrationTest
post '/qbo_estimates/598/create_issues', params: { project_id: 1, lines: {} }
assert_response :unprocessable_entity
end
def test_issues_preview_suggests_templates_and_lists_parts
Estimate.where(id: 598).delete_all
Estimate.create!(id: 598, doc_number: '1068', customer_id: 9101)
Estimate.any_instance.stubs(:line_items).returns([
qbo_sales_line(2, 31, 'Sales', 1, 315, description: 'Running boards'),
qbo_sales_line(3, 10, 'Labor', 2, 190, description: 'Install side steps'),
qbo_sales_line(4, 32, 'Sales', 1, 99, description: 'Light bar'),
qbo_sales_line(5, 10, 'Labor', 1, 190, description: 'Install light bar')
])
Setting.stubs(:plugin_redmine_qbo).returns('issue_default_project_id' => '1', 'issue_default_tracker_id' => '1')
option = RedmineQboBilling::IssueTemplateSupport::Option
RedmineQboBilling::IssueTemplateSupport.stubs(:enabled_for?).returns(true)
RedmineQboBilling::IssueTemplateSupport.stubs(:templates_for).returns([
option.new(key: 'project:1', title: 'Default', tracker_id: 1, is_default: true, group: 'project', match_phrases: []),
option.new(key: 'project:2', title: 'Side Steps', tracker_id: 2, is_default: false, group: 'project',
match_phrases: ['side steps', 'running boards'])
])
login_with(:create_estimate_issues, :add_issues)
get '/qbo_estimates/598/issues_preview'
assert_response :success
# Install side steps: matched template and its tracker
assert_select 'select[name="lines[3][tracker_id]"] option[selected][value="2"]'
assert_select 'select[name="lines[3][template]"] option[selected][value="project:2"]'
# Install light bar: no match, the tracker's default template
assert_select 'select[name="lines[5][template]"] option[selected][value="project:1"]'
assert_select '.estimate-line-parts', text: /1 × Sales/
# Parts first, then two labor lines with no subtotal between them
assert_select '.estimate-parts-ambiguous'
end
end
+7
View File
@@ -167,6 +167,13 @@ module QboFakeServiceHelper
line
end
def qbo_subtotal_line(id = nil)
line = Quickbooks::Model::InvoiceLineItem.new
line.id = id.to_s if id
line.detail_type = 'SubTotalLineDetail'
line
end
def qbo_discount_line(amount, percent: nil, account: nil)
line = Quickbooks::Model::InvoiceLineItem.new
line.amount = BigDecimal(amount.to_s)
+89 -1
View File
@@ -97,7 +97,10 @@ class EstimateIssueBuilderTest < ActiveSupport::TestCase
builder = Builder.new(@estimate, defaults: { description: 'From the appointment' })
created = builder.create_issues(project: @project, rows: rows(1, subject: 'Custom subject'), author: @author)
assert_equal 'Custom Subject', created.first.subject
assert_equal 'From the appointment', created.first.description
# The default description, then the line's parts (the brake pads follow the lift kit labor line)
description = created.first.description.gsub("\r\n", "\n")
assert description.start_with?("From the appointment\n")
assert_match '4 × **Brake pads** — Pads', description
end
def test_unassignable_user_is_left_off
@@ -130,4 +133,89 @@ class EstimateIssueBuilderTest < ActiveSupport::TestCase
assert_equal 0, Builder.relate_all(issues)
assert_equal 0, Builder.relate_all([issues.first])
end
# ---- jobs: parts, notes and templates ----
def estimate_with_jobs
subtotal = qbo_subtotal_line
@estimate.stubs(:line_items).returns([
qbo_note_line(20, "Severe play in ball joints\nRecommend ball joints"),
qbo_sales_line(21, 10, 'Labor', 4, 190, description: 'Install Ball Joints'),
qbo_sales_line(22, 30, 'TF JL Ball Joints', 1, 300, description: "Ball joint kit\n3452010"),
subtotal,
qbo_sales_line(23, 31, 'Sales', 1, 315, description: 'Running boards'),
qbo_sales_line(24, 10, 'Labor', 2, 190, description: 'Install side steps')
])
end
def template(key, description, note: '')
RedmineQboBilling::IssueTemplateSupport::Option.new(
key: key, title: key, tracker_id: 1, description: description,
match_phrases: RedmineQboBilling::TemplateMatcher.phrases(note)
)
end
def test_proposals_carry_their_job
estimate_with_jobs
builder = Builder.new(@estimate)
proposal = builder.proposals.first
assert_equal ['TF JL Ball Joints'], proposal.parts.map(&:item_name)
assert_equal ['Running boards'], builder.proposals.last.parts.map(&:description)
assert_not builder.ambiguous_parts?
end
def test_the_description_gets_the_estimate_notes_and_parts
estimate_with_jobs
RedmineQboBilling::IssueTemplateSupport.stubs(:find).returns(template('jl', 'Template body IAW Estimate #{{estimate}}'))
created = Builder.new(@estimate).create_issues(project: @project, rows: rows(21, template: 'jl'), author: @author)
description = created.first.reload.description
assert description.start_with?('Template body IAW Estimate #1068')
assert_match "Severe play in ball joints", description
assert_match "1 × **TF JL Ball Joints** — Ball joint kit; 3452010", description
assert_operator description.index('Template body'), :<, description.index('TF JL Ball Joints')
end
def test_a_template_can_place_the_notes_and_parts
estimate_with_jobs
body = "Findings:\n{{estimate_notes}}\n\nParts:\n{{estimate_parts}}\n\nEnd"
RedmineQboBilling::IssueTemplateSupport.stubs(:find).returns(template('jl', body))
description = Builder.new(@estimate).create_issues(project: @project, rows: rows(21, template: 'jl'), author: @author)
.first.reload.description.gsub("\r\n", "\n")
assert_match(/\AFindings:\n.*Severe play.*\n\nParts:\n.*TF JL Ball Joints.*\n\nEnd\z/m, description)
assert_no_match(/From the estimate/, description)
end
def test_the_default_description_gets_them_too
estimate_with_jobs
description = Builder.new(@estimate).create_issues(project: @project, rows: rows(24), author: @author).first.reload.description
assert_match 'Estimate #1068', description
assert_match 'Running boards', description
end
def test_nothing_is_added_when_a_job_has_no_notes_or_parts
created = Builder.new(@estimate).create_issues(project: @project, rows: rows(3), author: @author)
assert_no_match(/From the estimate/, created.first.reload.description)
end
def test_suggested_template_uses_the_line_and_its_parts
estimate_with_jobs
templates = [template('jk', 'JK', note: 'Match: ball joints, tf jk ball joints'),
template('jl', 'JL', note: 'Match: ball joints, tf jl ball joints'),
template('steps', 'Steps', note: 'Match: side steps, running boards')]
builder = Builder.new(@estimate)
assert_equal %w[jl steps], builder.proposals.map { |p| builder.suggested_template(p, templates)&.key }
end
def test_a_named_labor_service_uses_its_name
Setting.stubs(:plugin_redmine_qbo).returns('labor_item_ids' => %w[10 40])
@estimate.stubs(:line_items).returns([
qbo_sales_line(30, 40, 'Standard Alignment', 1, 200, description: "• Load vehicle onto machine\n• Print out alignment")
])
builder = Builder.new(@estimate)
proposal = builder.proposals.first
assert_equal 'Standard Alignment', proposal.description
assert_equal ["• Load vehicle onto machine\n• Print out alignment"], proposal.notes
templates = [template('align', 'Align', note: 'Match: standard alignment')]
assert_equal 'align', builder.suggested_template(proposal, templates).key
end
end
+96
View File
@@ -0,0 +1,96 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
# Grouping an estimate's lines into jobs: each labor line with its parts and notes (RedmineQboBilling::EstimateJobs)
class EstimateJobsTest < ActiveSupport::TestCase
include QboFakeServiceHelper
Jobs = RedmineQboBilling::EstimateJobs
def subtotal
qbo_subtotal_line
end
def labor(id, text, hours = 1)
qbo_sales_line(id, 10, 'Labor', hours, 190, description: text)
end
def part(id, name, text, quantity = 1)
qbo_sales_line(id, 20 + id, name, quantity, 50, description: text)
end
def jobs_for(lines)
Jobs.new(lines, labor: ->(ref) { ref.name == 'Labor' })
end
def parts_of(jobs, line_id)
jobs.job(line_id).parts.map(&:item_name)
end
def test_labor_then_parts_then_subtotal
jobs = jobs_for([labor(1, 'Replace Ball Joints', 4), part(2, 'TF JK Ball Joints', "Ball joint kit\n3442002"), subtotal,
labor(3, 'Replace Front Axle Seals'), part(4, 'JK Front Axle Seal', 'Seal 710863', 2),
part(5, '80W-90 Gear Oil', 'Gear oil - quart', 2), subtotal])
assert_equal ['TF JK Ball Joints'], parts_of(jobs, '1')
assert_equal ['JK Front Axle Seal', '80W-90 Gear Oil'], parts_of(jobs, '3')
seal = jobs.job('3').parts.first
assert_equal ['2', 'Seal 710863'], [seal.quantity, seal.description]
assert_not jobs.ambiguous?
end
def test_parts_before_the_labor_line_belong_to_it
jobs = jobs_for([part(1, 'Sales', 'Running boards'), labor(2, 'Install side steps', 2)])
assert_equal ['Sales'], parts_of(jobs, '2')
assert_not jobs.ambiguous?
end
def test_parts_first_jobs_split_by_subtotals
jobs = jobs_for([part(1, 'Sales', 'Coilovers'), labor(2, 'Install coilovers'), subtotal,
part(3, 'Sales', 'Steering kit'), labor(4, 'Install steering')])
assert_equal ['Sales'], parts_of(jobs, '2')
assert_equal ['Steering kit'], jobs.job('4').parts.map(&:description)
end
def test_a_second_labor_line_takes_the_parts_after_it
jobs = jobs_for([labor(1, 'Install Ball Joints', 4), part(2, 'TF JL Ball Joints', 'Kit 3452010'),
labor(3, 'Standard Alignment'), part(4, 'TPMS Sensor', 'Sensor', 4)])
assert_equal ['TF JL Ball Joints'], parts_of(jobs, '1')
assert_equal ['TPMS Sensor'], parts_of(jobs, '3')
assert_not jobs.ambiguous?
end
def test_parts_first_with_no_subtotal_between_jobs_is_ambiguous
jobs = jobs_for([part(1, 'Sales', 'Coilovers'), labor(2, 'Install coilovers'),
part(3, 'Sales', 'Steering kit'), labor(4, 'Install steering')])
assert jobs.ambiguous?
end
def test_notes_at_the_top_are_for_every_job_and_notes_in_a_job_are_its_own
jobs = jobs_for([qbo_note_line(1, '2015 JKU'), qbo_note_line(2, "Severe play in ball joints\nRecommend ball joints"),
labor(3, 'Replace Ball Joints'), part(4, 'Sales', 'Tires'), qbo_note_line(5, 'Take offs, customer provided'),
subtotal, labor(6, 'Standard Alignment')])
assert_equal ['2015 JKU', "Severe play in ball joints\nRecommend ball joints"], jobs.notes
assert_equal ['Take offs, customer provided'], jobs.job('3').notes
assert_equal [], jobs.job('6').notes
end
def test_parts_with_no_labor_line_are_left_out
jobs = jobs_for([part(1, 'Sales', 'Wheels', 4), part(2, 'Sales', 'Tires', 4), subtotal, labor(3, 'Replace Steering')])
assert_equal [], parts_of(jobs, '3')
assert_nil jobs.job('99')
end
def test_whole_number_quantities_drop_the_decimals
jobs = jobs_for([labor(1, 'Install'), part(2, 'Sales', 'Bolts', 6), part(3, 'Sales', 'Wire', 2.5)])
assert_equal %w[6 2.5], jobs.job('1').parts.map(&:quantity)
end
end
+121
View File
@@ -0,0 +1,121 @@
#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.
require File.expand_path('../test_helper', __dir__)
# {{customer}}, {{estimate}} and hooked macros in issue subjects and descriptions (RedmineQbo::IssueMacros)
class IssueMacrosTest < ActiveSupport::TestCase
fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations, :journals
CUSTOMER_ID = 9311
ESTIMATE_ID = 9411
class MacroHook < Redmine::Hook::Listener
cattr_accessor :value
def qbo_issue_macros(_context = {})
value ? { 'Truck' => value } : nil
end
end
def setup
User.current = User.find(1)
Estimate.where(id: ESTIMATE_ID).delete_all
Customer.where(id: CUSTOMER_ID).delete_all
@customer = Customer.new(id: CUSTOMER_ID, name: 'Jane Customer', phone_number: '555-0100')
@customer.skip_qbo_push = true
@customer.save!
@estimate = Estimate.create!(id: ESTIMATE_ID, doc_number: '1068', customer_id: CUSTOMER_ID)
@issue = Issue.find(1)
@issue.update_columns(customer_id: nil, estimate_id: nil)
MacroHook.value = nil
end
def teardown
MacroHook.value = nil
end
def test_customer_and_estimate_fill_the_description
@issue.description = "Estimate {{estimate}} for {{ Customer }}.\n{{toc}} {{unknown}}"
@issue.customer = @customer
@issue.estimate = @estimate
assert @issue.save, @issue.errors.full_messages.join(', ')
assert_equal "Estimate 1068 for Jane Customer.\r\n{{toc}} {{unknown}}", @issue.reload.description
end
def test_a_macro_without_a_value_waits_for_a_later_save
@issue.description = 'Estimate {{estimate}} for {{customer}}'
@issue.customer = @customer
@issue.save!
assert_equal 'Estimate {{estimate}} for Jane Customer', @issue.reload.description
@issue.estimate = @estimate
@issue.save!
assert_equal 'Estimate 1068 for Jane Customer', @issue.reload.description
end
def test_the_subject_too
@issue.subject = 'Work order {{estimate}}'
@issue.estimate = @estimate
@issue.save!
assert_equal 'Work Order 1068', @issue.reload.subject
end
def test_other_plugins_add_macros_through_the_hook
@issue.description = 'Inspect the {{truck}}'
@issue.valid?
assert_equal 'Inspect the {{truck}}', @issue.description
MacroHook.value = '2018 Jeep Wrangler'
@issue.valid?
assert_equal 'Inspect the 2018 Jeep Wrangler', @issue.description
end
def test_text_without_macros_is_left_alone
@issue.description = 'Nothing to fill'
RedmineQbo::IssueMacros.expects(:values).never
@issue.valid?
assert_equal 'Nothing to fill', @issue.description
end
def test_a_new_note_is_filled_when_the_issue_is_saved
@issue.estimate = @estimate
@issue.customer = @customer
@issue.save!
@issue.init_journal(User.find(1), 'Called {{customer}} about estimate {{estimate}}')
@issue.save!
assert_equal 'Called Jane Customer about estimate 1068', @issue.journals.order(:id).last.notes
end
def test_a_note_uses_values_set_in_the_same_save
@issue.init_journal(User.find(1), 'Estimate {{estimate}}')
@issue.estimate = @estimate
@issue.save!
assert_equal 'Estimate 1068', @issue.journals.order(:id).last.notes
end
def test_an_edited_note_is_filled
@issue.update_columns(customer_id: CUSTOMER_ID)
journal = Journal.create!(journalized: @issue, user: User.find(1), notes: 'Plain note')
journal.update!(notes: 'Spoke with {{customer}}')
assert_equal 'Spoke with Jane Customer', journal.reload.notes
end
def test_a_note_macro_without_a_value_stays_as_typed
journal = Journal.create!(journalized: @issue, user: User.find(1), notes: 'Estimate {{estimate}} and {{toc}}')
assert_equal 'Estimate {{estimate}} and {{toc}}', journal.reload.notes
end
def test_hooked_macros_fill_notes
MacroHook.value = '2018 Jeep Wrangler'
journal = Journal.create!(journalized: @issue, user: User.find(1), notes: 'Test drove the {{truck}}')
assert_equal 'Test drove the 2018 Jeep Wrangler', journal.reload.notes
end
end
+17
View File
@@ -103,6 +103,23 @@ class QboHelpersTest < ActiveSupport::TestCase
end
end
def test_refund_email_with_another_plugins_mail_settings
RedmineQboBilling.stubs(:mail_settings).returns(shop_name: 'Example Garage', from: 'Example Garage <shop@example.com>',
reply_to: 'office@example.com')
mail = QboRefundMailer.refund_summary(refund, 'jane@example.com')
assert_equal ['shop@example.com'], mail.from
assert_equal ['office@example.com'], mail.reply_to
assert_match 'Example Garage', mail.subject
end
def test_mail_settings_from_plugins
Redmine::Hook.stubs(:call_hook).with(:qbo_mail_settings, {})
.returns([{ shop_name: '', from: 'a@example.com' }, nil, { 'shop_name' => 'Example Garage' }])
assert_equal({ from: 'a@example.com', shop_name: 'Example Garage' }, RedmineQboBilling.mail_settings)
Redmine::Hook.stubs(:call_hook).with(:qbo_mail_settings, {}).raises(StandardError, 'boom')
assert_equal({}, RedmineQboBilling.mail_settings)
end
def test_refund_email_when_delivery_is_off
ActionMailer::Base.stubs(:perform_deliveries).returns(false)
assert_raises(QboRefundMailer::DeliveryOff) { QboRefundMailer.refund_summary(refund, 'jane@example.com').message }
+61
View File
@@ -0,0 +1,61 @@
#The MIT License (MIT)
#
#Copyright (c) 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
require File.expand_path('../test_helper', __dir__)
# Picking an issue template from an estimate line's text and part names (RedmineQboBilling::TemplateMatcher)
class TemplateMatcherTest < ActiveSupport::TestCase
Matcher = RedmineQboBilling::TemplateMatcher
Option = RedmineQboBilling::IssueTemplateSupport::Option
def option(key, note)
Option.new(key: key, title: key, tracker_id: 1, match_phrases: Matcher.phrases(note))
end
def setup
@templates = [
option('jk', "Match: ball joints, tf jk ball joints, jk ball joints"),
option('jl', "Match: ball joints, tf jl ball joints, jl ball joints, jt ball joints"),
option('align', "Used for alignments\nmatch: standard alignment, alignment"),
option('brakes', 'Match: front brakes, brake pads'),
option('plain', 'Just a memo, no match line')
]
end
def test_phrases_come_from_a_match_line_in_the_note
assert_equal ['standard alignment', 'alignment'], Matcher.phrases("Used for alignments\nMATCH: Standard Alignment, alignment ,")
assert_equal [], Matcher.phrases('No match line here')
assert_equal [], Matcher.phrases(nil)
end
def test_the_longest_matching_phrase_wins
assert_equal 'jl', Matcher.best(@templates, 'Install Ball Joints', 'TF JL Ball Joints').key
assert_equal 'jk', Matcher.best(@templates, 'Replace Ball Joints', 'TF JK Ball Joints').key
end
def test_ties_go_to_the_first_template
assert_equal 'jk', Matcher.best(@templates, 'Replace Ball Joints').key
end
def test_plurals_and_punctuation_still_match
assert_equal 'brakes', Matcher.best(@templates, 'Replace front brake').key
assert_equal 'brakes', Matcher.best(@templates, 'Brake-pads (front)').key
assert_equal 'align', Matcher.best(@templates, 'STANDARD ALIGNMENT').key
end
def test_whole_words_only
assert_nil Matcher.best(@templates, 'Misalignmentx')
end
def test_no_match
assert_nil Matcher.best(@templates, 'Replace fuel filler')
assert_nil Matcher.best([], 'Standard alignment')
end
end