Add preview page for creating issues from an estimate

- "Create Issues from Estimate" now opens a preview listing each
  matching estimate line: include checkbox, subject (from the line
  description), tracker dropdown, template dropdown and estimated
  hours (from the line quantity)
- Admins set which QBO item codes to look for (e.g. Labor, Alignments)
  and a default tracker in the plugin settings
- Optional redmine_issue_templates support: templates supply the issue
  description; titles still come from the line description
- New appointment_estimate_issues table records which issue came from
  which estimate line, so a line can't be turned into an issue twice;
  deleting the issue frees the line again
- Creation is all-or-nothing; errors are shown on the preview page
- Removes the old Labor-only create_issues_from_labor_lines code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-28 20:34:06 -04:00
1 parent 73115da2b9
commit 184c1e2464
15 files changed
+613 -92

No files matched your search

+1
View File
@@ -13,6 +13,7 @@ module RedmineQboCalendar
# Patches
Customer.prepend(RedmineQboCalendar::Patches::CustomerPatch)
User.prepend(RedmineQboCalendar::Patches::UserPatch)
Issue.prepend(RedmineQboCalendar::Patches::IssuePatch)
CalendarsController.prepend(RedmineQboCalendar::Patches::CalendarsControllerPatch)
ApplicationHelper.prepend(RedmineQboCalendar::Patches::ApplicationHelperPatch)
@@ -0,0 +1,188 @@
#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 RedmineQboCalendar
# Turns the lines of an appointment's QBO estimate into proposed issues, and creates the ones
# the user selects on the preview page.
#
# - Only lines whose item matches an admin-configured item code (e.g. "Labor", "Alignments") are proposed
# - Subject = the line's description; estimated hours = the line's quantity
# - 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
class EstimateIssueBuilder
include Redmine::I18n
DEFAULT_ITEM_CODES = ['Labor'].freeze
Proposal = Struct.new(:line_id, :item_name, :description, :hours, :existing_issue, keyword_init: true) do
def created?
existing_issue.present?
end
end
# Item codes from the plugin settings, one per line (commas also accepted)
def self.item_codes
raw = settings['item_codes'].to_s
codes = raw.split(/[\n,]/).map(&:strip).reject(&:blank?)
codes.presence || DEFAULT_ITEM_CODES
end
def self.default_tracker_id
settings['default_tracker_id'].to_i
end
def self.settings
Setting.plugin_redmine_qbo_calendar || {}
rescue StandardError
{}
end
# A line matches a code if its QBO item name equals the code, or any part of a
# "Category:Item" name does. Case-insensitive.
def self.item_matches?(item_name, codes = item_codes)
name = item_name.to_s.strip.downcase
parts = name.split(':').map(&:strip)
codes.map { |c| c.strip.downcase }.any? { |code| name == code || parts.include?(code) }
end
attr_reader :appointment, :errors
def initialize(appointment)
@appointment = appointment
@errors = []
end
def estimate
appointment.estimate
end
def proposals
@proposals ||= build_proposals
end
# rows: { line_id => { 'selected' => '1', 'subject' => ..., 'tracker_id' => ..., 'template' => 'global:3', 'estimated_hours' => ... } }
# Returns the created issues, or [] with #errors filled in.
def create_issues(project:, rows:, 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)]
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
AppointmentEstimateIssue.where(estimate_id: estimate.id, line_id: proposal.line_id)
.where.not(issue_id: Issue.select(:id)).delete_all
AppointmentEstimateIssue.create!(
customer_appointment: appointment,
estimate_id: estimate.id,
line_id: proposal.line_id,
issue: issue
)
end
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?
codes = self.class.item_codes
links = AppointmentEstimateIssue.where(estimate_id: estimate.id).includes(:issue).index_by(&:line_id)
Array(estimate.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 self.class.item_matches?(item_name, 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 = line_key(line, index)
quantity = detail.respond_to?(:quantity) ? detail.quantity.to_f : 0.0
Proposal.new(
line_id: line_id,
item_name: item_name,
description: description,
hours: quantity.positive? ? quantity : nil,
existing_issue: links[line_id]&.issue
)
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
def build_issue(proposal, row, project, author, allowed_trackers)
issue = Issue.new(project: project, author: author)
issue.tracker = allowed_trackers.detect { |t| t.id == row['tracker_id'].to_i }
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
hours = row.key?('estimated_hours') ? row['estimated_hours'] : proposal.hours
issue.estimated_hours = hours.presence
issue.start_date = appointment.start_date
issue.due_date = appointment.due_date
# Only assign the appointment's technician if they can be assigned in this project
if appointment.user && issue.assignable_users.include?(appointment.user)
issue.assigned_to = appointment.user
end
# Customer / vehicle / estimate fields are added to issues by redmine_qbo
issue.customer_id = appointment.customer_id if issue.respond_to?(:customer_id=)
issue.vehicle_id = appointment.vehicle_id if issue.respond_to?(:vehicle_id=)
issue.estimate_id = appointment.estimate_id if issue.respond_to?(:estimate_id=)
issue
end
def default_description
"The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number} " \
"for Appointment: #{appointment.subject}"
end
end
end
@@ -0,0 +1,58 @@
#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 RedmineQboCalendar
# 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)
module_function
def installed?
defined?(::IssueTemplate) && defined?(::GlobalIssueTemplate) && defined?(::IssueTemplateSetting)
end
def enabled_for?(project)
!!(installed? && project&.module_enabled?(:issue_templates))
end
# Templates usable in the project: its own, those shared by parent projects, and global ones.
def templates_for(project)
return [] unless enabled_for?(project)
own = ::IssueTemplate.get_templates_for_project_tracker(project.id).to_a
inherited = Array(::IssueTemplateSetting.find_or_create(project.id).get_inherit_templates).to_a
global = ::GlobalIssueTemplate.get_templates_for_project_tracker(project.id).to_a
(own + inherited).uniq.map { |t| option('project', t) } + global.map { |t| option('global', t) }
rescue StandardError => e
Rails.logger.warn "[IssueTemplateSupport] Could not load templates: #{e.class}: #{e.message}"
[]
end
def find(key, project)
return nil if key.blank?
templates_for(project).detect { |t| t.key == key }
end
def option(group, template)
Option.new(
key: "#{group}:#{template.id}",
title: template.title,
tracker_id: template.tracker_id,
is_default: template.is_default?,
description: template.description,
group: group
)
end
end
end
@@ -0,0 +1,23 @@
#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 RedmineQboCalendar
module Patches
module IssuePatch extend ActiveSupport::Concern
prepended do
# Deleting an issue frees its estimate line so it can be created again
has_one :appointment_estimate_issue, dependent: :delete
has_one :customer_appointment, through: :appointment_estimate_issue
end
end
end
end