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
18 changed files with 693 additions and 25 deletions

No files matched your search

+7 -3
View File
@@ -36,7 +36,7 @@ For production deployments, **use a tagged release**.
* Automatically associates a **QuickBooks Invoice** with the Issue. * Automatically associates a **QuickBooks Invoice** with the Issue.
* **Macros** in an issue's subject or description 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. Companion plugins add more through the `:qbo_issue_macros` hook (redmine_qbo_vehicles: `{{vehicle}}`). * **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}}`).
--- ---
@@ -226,7 +226,11 @@ Administration → Items lists the QuickBooks product/service list (synced from
* **Write estimates**: create and edit estimates * **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) * **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) * **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 * **View payments**: a customer's Payments list, the payment page and its PDF
* **Receive payments**: the Receive payment page, plus everything View payments allows * **Receive payments**: the Receive payment page, plus everything View payments allows
* **View business reports**: the Business report * **View business reports**: the Business report
@@ -280,7 +284,7 @@ Hook|:qbo_billing_field_defaults, { customer:, issues: } | Return `{ field_id =>
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) 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|: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-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`) 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 and description when it's 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_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_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 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_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 }`
@@ -98,6 +98,10 @@
<%= hidden_field_tag :parent_issue_id, @parent_issue&.id || @parent_issue_id, id: nil %> <%= 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 %> <% 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"> <table class="list estimate-issues-preview">
<thead> <thead>
<tr> <tr>
@@ -132,8 +136,11 @@
<% <%
row = (@rows[proposal.line_id] || {}).to_h row = (@rows[proposal.line_id] || {}).to_h
selected = row.empty? || row['selected'] == '1' selected = row.empty? || row['selected'] == '1'
tracker_id = (row['tracker_id'].presence || @default_tracker&.id).to_i # A template whose "Match:" note fits the line and its parts picks the tracker and template
template_key = row.key?('template') ? row['template'] : default_template_for.call(tracker_id) 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 hours = row.key?('estimated_hours') ? row['estimated_hours'] : proposal.hours
%> %>
<tr class="estimate-line"> <tr class="estimate-line">
@@ -145,6 +152,12 @@
<td class="subject"> <td class="subject">
<%= text_field_tag "#{field}[subject]", row['subject'] || proposal.description, <%= text_field_tag "#{field}[subject]", row['subject'] || proposal.description,
maxlength: 255, class: 'estimate-line-subject', id: nil %> 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>
<td> <td>
<%= select_tag "#{field}[tracker_id]", <%= select_tag "#{field}[tracker_id]",
@@ -209,6 +222,7 @@
<p class="estimate-issues-hint"> <p class="estimate-issues-hint">
<% if templates_enabled %> <% if templates_enabled %>
<%= l(:text_estimate_issues_template_hint) %> <%= l(:text_estimate_issues_template_hint) %>
<%= l(:text_estimate_issues_template_match_hint) %>
<% else %> <% else %>
<%= l(:text_estimate_issues_hint) %> <%= l(:text_estimate_issues_hint) %>
<% end %> <% end %>
@@ -308,6 +322,9 @@
.estimate-preview-subtitle { font-weight: normal; font-size: 0.8em; color: #777; } .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 { text-align: left; }
table.estimate-issues-preview td.subject input { width: 98%; } 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; } table.estimate-issues-preview tr.created td { color: #888; }
.estimate-issues-hint { color: #777; font-size: 0.9em; } .estimate-issues-hint { color: #777; font-size: 0.9em; }
.estimate-issue-fields .estimate-issue-fields-info { padding-left: 0; } .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_issue_settings: "Issues from estimates"
label_estimate_item: "Item" label_estimate_item: "Item"
label_estimate_line_already_created: "Already created" 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_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." 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_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_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_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." 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 # Payments
+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.29' version '2026.11.30'
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'
+1
View File
@@ -12,6 +12,7 @@ module RedmineQbo
def self.setup def self.setup
# === Models === # === Models ===
Issue.prepend RedmineQbo::Patches::IssuePatch Issue.prepend RedmineQbo::Patches::IssuePatch
Journal.prepend RedmineQbo::Patches::JournalPatch
User.prepend RedmineQbo::Patches::UserPatch User.prepend RedmineQbo::Patches::UserPatch
# === Queries === # === Queries ===
+16 -1
View File
@@ -16,6 +16,9 @@ module RedmineQbo
# #
# A macro without a value yet (no estimate linked) stays as typed, so it fills on a later save. # 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. # 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 module IssueMacros
PATTERN = /\{\{\s*([a-z][a-z0-9_]*)\s*\}\}/i PATTERN = /\{\{\s*([a-z][a-z0-9_]*)\s*\}\}/i
FIELDS = %i[subject description].freeze FIELDS = %i[subject description].freeze
@@ -30,11 +33,23 @@ module RedmineQbo
return if known.empty? return if known.empty?
texts.each do |field, text| texts.each do |field, text|
filled = text.gsub(PATTERN) { known[Regexp.last_match(1).downcase] || Regexp.last_match(0) } filled = substitute(text, known)
issue.send("#{field}=", filled) unless filled == text issue.send("#{field}=", filled) unless filled == text
end end
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 # { 'name' => text } for every macro with a value for this issue
def values(issue) def values(issue)
found = { found = {
+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
@@ -13,7 +13,11 @@ module RedmineQboBilling
# on the "Create issues from estimate" page (moved here from redmine_qbo_calendar). # 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 # - 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 # - 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 # - 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 # - All issues created from the same estimate are related to each other, across batches
@@ -34,7 +38,7 @@ module RedmineQboBilling
class EstimateIssueBuilder class EstimateIssueBuilder
include Redmine::I18n 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? def created?
existing_issue.present? existing_issue.present?
end end
@@ -110,6 +114,21 @@ module RedmineQboBilling
@proposals ||= build_proposals @proposals ||= build_proposals
end 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' => ... } } # 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 # 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. # Returns the created issues, or [] with #errors filled in.
@@ -162,8 +181,10 @@ module RedmineQboBilling
ids = LaborItems.ids ids = LaborItems.ids
codes = LaborItems.codes codes = LaborItems.codes
links = QboEstimateLineIssue.where(estimate_id: estimate.id).includes(:issue).index_by(&:line_id) 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 detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil
next if detail.nil? || detail.item_ref.nil? next if detail.nil? || detail.item_ref.nil?
@@ -174,27 +195,29 @@ module RedmineQboBilling
description = line.description.to_s.strip description = line.description.to_s.strip
next if description.blank? 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 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( Proposal.new(
line_id: line_id, line_id: line_id,
item_name: item_name, item_name: item_name,
description: description, description: description,
hours: quantity.positive? ? quantity : nil, 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
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, # 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) # except their parent and its ancestors (Redmine doesn't allow relating a subtask to its parent)
def relate_issues(new_issues) def relate_issues(new_issues)
@@ -218,7 +241,8 @@ module RedmineQboBilling
issue.subject = (row['subject'].presence || proposal.description).to_s.strip.truncate(255) issue.subject = (row['subject'].presence || proposal.description).to_s.strip.truncate(255)
template = IssueTemplateSupport.find(row['template'], project) 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 hours = row.key?('estimated_hours') ? row['estimated_hours'] : proposal.hours
issue.estimated_hours = hours.presence 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). # 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. # Everything here returns empty results when that plugin isn't installed or isn't enabled on the project.
module IssueTemplateSupport 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 module_function
@@ -51,7 +51,8 @@ module RedmineQboBilling
tracker_id: template.tracker_id, tracker_id: template.tracker_id,
is_default: template.is_default?, is_default: template.is_default?,
description: template.description, description: template.description,
group: group group: group,
match_phrases: TemplateMatcher.phrases(template.try(:note))
) )
end end
end 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
@@ -247,4 +247,35 @@ class QboEstimatesControllerTest < Redmine::IntegrationTest
post '/qbo_estimates/598/create_issues', params: { project_id: 1, lines: {} } post '/qbo_estimates/598/create_issues', params: { project_id: 1, lines: {} }
assert_response :unprocessable_entity assert_response :unprocessable_entity
end 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 end
+7
View File
@@ -167,6 +167,13 @@ module QboFakeServiceHelper
line line
end 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) def qbo_discount_line(amount, percent: nil, account: nil)
line = Quickbooks::Model::InvoiceLineItem.new line = Quickbooks::Model::InvoiceLineItem.new
line.amount = BigDecimal(amount.to_s) 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' }) builder = Builder.new(@estimate, defaults: { description: 'From the appointment' })
created = builder.create_issues(project: @project, rows: rows(1, subject: 'Custom subject'), author: @author) created = builder.create_issues(project: @project, rows: rows(1, subject: 'Custom subject'), author: @author)
assert_equal 'Custom Subject', created.first.subject 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 end
def test_unassignable_user_is_left_off 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)
assert_equal 0, Builder.relate_all([issues.first]) assert_equal 0, Builder.relate_all([issues.first])
end 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 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
+35 -1
View File
@@ -12,7 +12,7 @@ require File.expand_path('../test_helper', __dir__)
# {{customer}}, {{estimate}} and hooked macros in issue subjects and descriptions (RedmineQbo::IssueMacros) # {{customer}}, {{estimate}} and hooked macros in issue subjects and descriptions (RedmineQbo::IssueMacros)
class IssueMacrosTest < ActiveSupport::TestCase class IssueMacrosTest < ActiveSupport::TestCase
fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations fixtures :projects, :users, :issues, :trackers, :issue_statuses, :enumerations, :journals
CUSTOMER_ID = 9311 CUSTOMER_ID = 9311
ESTIMATE_ID = 9411 ESTIMATE_ID = 9411
@@ -84,4 +84,38 @@ class IssueMacrosTest < ActiveSupport::TestCase
@issue.valid? @issue.valid?
assert_equal 'Nothing to fill', @issue.description assert_equal 'Nothing to fill', @issue.description
end 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 end
+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