mirror of
https://github.com/rickbarrette/redmine_qbo.git
synced 2026-11-22 11:00:36 -05:00
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>
298 lines
14 KiB
Ruby
298 lines
14 KiB
Ruby
#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
|
|
# Turns the labor lines of a QuickBooks estimate into proposed issues, and creates the ones the user selects
|
|
# 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. 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
|
|
# - With a parent issue, the issues are created as its subtasks and take its customer, plus its custom field
|
|
# values where the page left them empty (the same rules as the subtask_field_copier plugin, which is used
|
|
# when installed). Plugins copy their own fields from the parent in :qbo_billing_build_issue.
|
|
#
|
|
# Other plugins fill in more through hooks:
|
|
# :qbo_billing_issue_defaults, { estimate:, params:, parent_issue: } => a hash of start_date, due_date,
|
|
# assignee, description, project, return_path, return_label, plus anything a plugin's own fields need.
|
|
# Every plugin's hash is merged.
|
|
# :qbo_billing_build_issue, { issue:, estimate:, defaults:, parent: } for each new issue before it's saved,
|
|
# to set plugins' own fields (e.g. redmine_qbo_vehicles sets the vehicle, else the parent's)
|
|
# :view_qbo_estimate_issues_form, { estimate:, defaults:, project: } (view hook) draws plugins' fields on
|
|
# the page, applied to every issue; posted as issue_plugin_fields[name], they reach :qbo_billing_build_issue
|
|
# in defaults (e.g. redmine_qbo_vehicles' Vehicle, preselected from the estimate's VIN)
|
|
# :qbo_billing_issues_created, { estimate:, issues:, params: } after issues are created
|
|
class EstimateIssueBuilder
|
|
include Redmine::I18n
|
|
|
|
Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, :parts, :notes, keyword_init: true) do
|
|
def created?
|
|
existing_issue.present?
|
|
end
|
|
end
|
|
|
|
def self.default_tracker_id
|
|
setting('issue_default_tracker_id').to_i
|
|
end
|
|
|
|
def self.default_project_id
|
|
setting('issue_default_project_id').to_i
|
|
end
|
|
|
|
def self.setting(key)
|
|
(Setting.plugin_redmine_qbo || {})[key]
|
|
rescue StandardError
|
|
nil
|
|
end
|
|
|
|
# The estimate's labor hours: the quantities of its labor lines (LaborItems)
|
|
# (e.g. for an appointment's hours, which shouldn't be less)
|
|
def self.labor_hours(estimate)
|
|
return 0.0 if estimate.nil?
|
|
|
|
Array(estimate.line_items).sum do |line|
|
|
detail = line.respond_to?(:sales_line_item_detail) ? line.sales_line_item_detail : nil
|
|
next 0.0 if detail.nil? || !LaborItems.match?(detail.item_ref)
|
|
detail.quantity.to_f
|
|
end
|
|
end
|
|
|
|
# Relates every issue in the list to every other one ("Related to"), skipping pairs that already
|
|
# have any relation. Used for issues created from the same estimate, whichever batch they came from.
|
|
# Issues loaded fresh have no open journal, so this adds no history entries and sends no
|
|
# "issue updated" emails. A failed relation (e.g. cross-project relations disabled) is logged, not fatal.
|
|
# Returns the number of relations created.
|
|
def self.relate_all(issues)
|
|
issues = issues.compact.uniq(&:id)
|
|
return 0 if issues.size < 2
|
|
|
|
ids = issues.map(&:id)
|
|
already_related = IssueRelation.where(issue_from_id: ids, issue_to_id: ids)
|
|
.pluck(:issue_from_id, :issue_to_id)
|
|
.map(&:minmax)
|
|
.to_set
|
|
|
|
issues.combination(2).count do |issue_from, issue_to|
|
|
next false if already_related.include?([issue_from.id, issue_to.id].minmax)
|
|
|
|
relation = IssueRelation.new(issue_from: issue_from, issue_to: issue_to,
|
|
relation_type: IssueRelation::TYPE_RELATES)
|
|
next true if relation.save
|
|
|
|
Rails.logger.warn "[EstimateIssueBuilder] Could not relate ##{issue_from.id} and ##{issue_to.id}: " \
|
|
"#{relation.errors.full_messages.join(', ')}"
|
|
false
|
|
end
|
|
end
|
|
|
|
attr_reader :estimate, :defaults, :parent, :errors
|
|
|
|
# estimate: redmine_qbo's local Estimate (its QuickBooks details give the lines)
|
|
# defaults: start_date, due_date, assignee, description and plugins' own values (from :qbo_billing_issue_defaults)
|
|
# parent: an issue to create the issues under as subtasks (optional; the caller checks the user may see it)
|
|
def initialize(estimate, defaults: {}, parent: nil)
|
|
@estimate = estimate
|
|
@defaults = (defaults || {}).to_h.symbolize_keys
|
|
@parent = parent
|
|
@errors = []
|
|
end
|
|
|
|
def proposals
|
|
@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.
|
|
def create_issues(project:, rows:, custom_field_values: {}, author: User.current)
|
|
@errors = []
|
|
rows = (rows || {}).to_h.transform_keys(&:to_s)
|
|
|
|
selected = proposals.reject(&:created?).select { |p| rows.dig(p.line_id, 'selected') == '1' }
|
|
if selected.empty?
|
|
@errors << l(:error_no_estimate_lines_selected)
|
|
return []
|
|
end
|
|
|
|
allowed_trackers = Issue.allowed_target_trackers(project, author).to_a
|
|
|
|
built = selected.map do |proposal|
|
|
[proposal, build_issue(proposal, rows[proposal.line_id] || {}, project, author, allowed_trackers, custom_field_values)]
|
|
end
|
|
|
|
Issue.transaction do
|
|
built.each do |proposal, issue|
|
|
next if issue.save
|
|
|
|
@errors << "#{proposal.description.truncate(60)}: #{issue.errors.full_messages.join(', ')}"
|
|
end
|
|
raise ActiveRecord::Rollback if @errors.any?
|
|
|
|
built.each do |proposal, issue|
|
|
# Clear a link left behind by an issue that no longer exists, then record the new one
|
|
QboEstimateLineIssue.where(estimate_id: estimate.id, line_id: proposal.line_id)
|
|
.where.not(issue_id: Issue.select(:id)).delete_all
|
|
QboEstimateLineIssue.create!(estimate_id: estimate.id, line_id: proposal.line_id, issue: issue)
|
|
end
|
|
|
|
relate_issues(built.map(&:last))
|
|
end
|
|
|
|
@errors.any? ? [] : built.map(&:last)
|
|
rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
|
|
# Someone else created issues from the same lines at the same moment
|
|
@errors << l(:error_estimate_lines_already_created)
|
|
[]
|
|
end
|
|
|
|
private
|
|
|
|
def build_proposals
|
|
return [] if estimate.blank?
|
|
|
|
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) })
|
|
|
|
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?
|
|
|
|
item_name = detail.item_ref.name.to_s.strip
|
|
next unless LaborItems.match?(detail.item_ref, ids: ids, codes: codes)
|
|
|
|
# The subject comes from the line's description, so lines without one are skipped
|
|
description = line.description.to_s.strip
|
|
next if description.blank?
|
|
|
|
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,
|
|
parts: job ? job.parts : [],
|
|
notes: notes
|
|
)
|
|
end
|
|
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)
|
|
skip_ids = parent ? parent.self_and_ancestors.pluck(:id) : []
|
|
earlier = QboEstimateLineIssue.where(estimate_id: estimate.id)
|
|
.where.not(issue_id: new_issues.map(&:id) + skip_ids)
|
|
.includes(:issue)
|
|
.filter_map(&:issue)
|
|
self.class.relate_all(earlier + new_issues)
|
|
end
|
|
|
|
def build_issue(proposal, row, project, author, allowed_trackers, custom_field_values)
|
|
issue = Issue.new(project: project, author: author)
|
|
issue.tracker = allowed_trackers.detect { |t| t.id == row['tracker_id'].to_i }
|
|
|
|
# Shared custom field values. Going through safe_attributes means fields the tracker doesn't
|
|
# use, or that this user can't edit (hidden / read-only by workflow), are ignored.
|
|
if custom_field_values.present? && issue.tracker
|
|
issue.send(:safe_attributes=, { 'custom_field_values' => custom_field_values.to_h }, author)
|
|
end
|
|
issue.subject = (row['subject'].presence || proposal.description).to_s.strip.truncate(255)
|
|
|
|
template = IssueTemplateSupport.find(row['template'], project)
|
|
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
|
|
|
|
issue.start_date = defaults[:start_date] if defaults[:start_date]
|
|
issue.due_date = defaults[:due_date] if defaults[:due_date]
|
|
|
|
# Only assign someone who can be assigned in this project
|
|
assignee = defaults[:assignee]
|
|
issue.assigned_to = assignee if assignee && issue.assignable_users.include?(assignee)
|
|
|
|
# A subtask belongs to its parent's customer; otherwise the estimate's
|
|
if issue.respond_to?(:customer_id=)
|
|
issue.customer_id = parent&.customer_id.presence || estimate.customer_id
|
|
end
|
|
issue.estimate_id = estimate.id if issue.respond_to?(:estimate_id=)
|
|
|
|
# Plugins set their own fields (e.g. redmine_qbo_vehicles: the vehicle)
|
|
Redmine::Hook.call_hook(:qbo_billing_build_issue, { issue: issue, estimate: estimate, defaults: defaults, parent: parent })
|
|
|
|
if parent
|
|
issue.parent_issue_id = parent.id
|
|
copy_from_parent(issue, author)
|
|
end
|
|
|
|
issue
|
|
end
|
|
|
|
# Fills the subtask's empty fields from the parent: custom fields (those the author can see on the parent
|
|
# and edit on the subtask), and with subtask_field_copier its registered fields. Values entered on the page win.
|
|
def copy_from_parent(issue, author)
|
|
if defined?(::SubtaskFieldCopier)
|
|
::SubtaskFieldCopier.copy_from_parent(issue, parent, author, {})
|
|
return
|
|
end
|
|
|
|
parent_values = parent.visible_custom_field_values(author).index_by(&:custom_field_id)
|
|
copied = issue.editable_custom_field_values(author).each_with_object({}) do |custom_value, values|
|
|
value = parent_values[custom_value.custom_field_id]&.value
|
|
next if Array(value).all?(&:blank?) || Array(custom_value.value).any?(&:present?)
|
|
|
|
values[custom_value.custom_field_id.to_s] = value
|
|
end
|
|
issue.custom_field_values = copied if copied.any?
|
|
end
|
|
|
|
def default_description
|
|
defaults[:description].presence ||
|
|
"The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number}"
|
|
end
|
|
end
|
|
end
|