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

@@ -11,7 +11,7 @@
class CustomerAppointmentsController < ApplicationController class CustomerAppointmentsController < ApplicationController
before_action :require_login before_action :require_login
before_action :find_project, except: [:index] before_action :find_project, except: [:index]
before_action :find_appointment, only: [ :show, :edit, :update, :destroy, :create_issues ] before_action :find_appointment, only: [ :show, :edit, :update, :destroy, :issues_preview, :create_issues ]
# This tells Redmine to check global permissions for the current controller/action # This tells Redmine to check global permissions for the current controller/action
before_action :authorize_global before_action :authorize_global
@@ -26,22 +26,26 @@ class CustomerAppointmentsController < ApplicationController
} }
end end
# Creates one issue per "Labor" line on the appointment's QBO estimate. # Preview of the issues that can be created from the appointment's QBO estimate.
# Each line gets a tracker and (optionally) a template before anything is created.
def issues_preview
load_issue_preview
end
# Creates the issues selected on the preview page, all or nothing.
def create_issues def create_issues
# Same fallback order as CustomerAppointment#create_issues_from_labor_lines load_issue_preview
target_project = @project || @appointment.project || Project.first return if performed?
# The user must also be allowed to add issues to the project they'll be created in @rows = params[:lines].respond_to?(:to_unsafe_h) ? params[:lines].to_unsafe_h : {}
return deny_access unless target_project && User.current.allowed_to?(:add_issues, target_project) created_issues = @builder.create_issues(project: @target_project, rows: @rows)
created_issues = @appointment.create_issues_from_labor_lines(project: target_project, author: User.current)
if created_issues.any? if created_issues.any?
flash[:notice] = l(:notice_appointment_issues_created, count: created_issues.size) flash[:notice] = l(:notice_appointment_issues_created, count: created_issues.size)
redirect_to customer_appointment_path(@appointment)
else else
flash[:error] = l(:error_no_labor_lines_found) render :issues_preview, status: :unprocessable_entity
end end
redirect_to customer_appointment_path(@appointment)
end end
def index def index
@@ -145,6 +149,28 @@ class CustomerAppointmentsController < ApplicationController
nil nil
end end
# Sets up everything the preview page needs: the target project, its trackers and templates.
def load_issue_preview
@builder = RedmineQboCalendar::EstimateIssueBuilder.new(@appointment)
@available_projects = Project.allowed_to(User.current, :add_issues).sorted.to_a
# A project chosen on the page wins, then the appointment's project, then the first allowed one
@target_project =
if @project
@project if @available_projects.include?(@project)
elsif @available_projects.include?(@appointment.project)
@appointment.project
else
@available_projects.first
end
return deny_access unless @target_project
@trackers = Issue.allowed_target_trackers(@target_project, User.current).to_a
@default_tracker = @trackers.detect { |t| t.id == RedmineQboCalendar::EstimateIssueBuilder.default_tracker_id } || @trackers.first
@templates = RedmineQboCalendar::IssueTemplateSupport.templates_for(@target_project)
@rows ||= {}
end
def find_project def find_project
@project = Project.find(params[:project_id]) if params[:project_id].present? @project = Project.find(params[:project_id]) if params[:project_id].present?
end end
+20
View File
@@ -0,0 +1,20 @@
#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.
# Link between a QBO estimate line and the issue created from it.
class AppointmentEstimateIssue < ActiveRecord::Base
belongs_to :customer_appointment, optional: true
belongs_to :issue
validates :estimate_id, :line_id, presence: true
validates :line_id, uniqueness: { scope: :estimate_id }
before_create { self.created_on ||= Time.current }
end
+4 -77
View File
@@ -16,6 +16,10 @@ class CustomerAppointment < ActiveRecord::Base
belongs_to :vehicle, optional: true belongs_to :vehicle, optional: true
belongs_to :estimate, optional: true belongs_to :estimate, optional: true
# Issues created from this appointment's estimate lines
has_many :appointment_estimate_issues, dependent: :nullify
has_many :created_issues, through: :appointment_estimate_issues, source: :issue
validates :subject, presence: true validates :subject, presence: true
validates :date, presence: true validates :date, presence: true
@@ -46,65 +50,6 @@ class CustomerAppointment < ActiveRecord::Base
!NON_SCHEDULED_STATUSES.include?(status.to_s) !NON_SCHEDULED_STATUSES.include?(status.to_s)
end end
# Scans the QBO Estimate's InvoiceLineItems for "Labor" sales items
# and generates a Redmine Issue for each matching line.
#
# @param project [Project] Target project (defaults to appointment's project)
# @param author [User] Author for the new issues
# @param tracker [Tracker] Target tracker (defaults to project's first tracker)
# @return [Array<Issue>] Created issues
def create_issues_from_labor_lines(project: self.project, author: User.current, tracker: nil)
return [] if estimate.blank?
target_project = project || self.project || Project.first
target_tracker = tracker || target_project&.trackers&.first
return [] unless target_project && target_tracker
created_issues = []
# estimate.line_items returns array of Quickbooks::Model::InvoiceLineItem
estimate.line_items.each do |line|
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
description = line.description.to_s.strip
# Match "Labor" (case-insensitive) and ensure description is present
next unless item_name.casecmp('Labor').zero?
next if description.blank?
# detail.quantity contains line quantity/hours; line.amount is total line cost fallback
qty = detail.respond_to?(:quantity) ? detail.quantity.to_f : 0.0
hours = qty.positive? ? qty : line.amount.to_f
issue = Issue.new(
project: target_project,
tracker: target_tracker,
assigned_to_id: self.user&.id,
author: author,
subject: description.truncate(255),
description: "The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number} for Appointment: #{subject}",
estimated_hours: hours,
start_date: self.start_date,
due_date: self.due_date,
vehicle: self.vehicle,
estimate: self.estimate,
customer: self.customer,
created_on: Time.current,
updated_on: Time.current
)
if issue.save
created_issues << issue
else
log "Failed to create issue for Estimate ##{estimate.id}: #{issue.errors.full_messages.join(', ')}"
end
end
created_issues
end
# Cast datetime to Date for Redmine Calendar compatibility # Cast datetime to Date for Redmine Calendar compatibility
def start_date def start_date
date&.to_date date&.to_date
@@ -155,22 +100,4 @@ class CustomerAppointment < ActiveRecord::Base
end end
end end
# Helper to parse item name across Quickbooks::Model::Line and Hash structures
def extract_item_name(line)
if line.respond_to?(:sales_line_item_detail) && line.sales_line_item_detail.present?
line.sales_line_item_detail.item_ref&.name
elsif line.is_a?(Hash)
line[:item_name] || line.dig('sales_line_item_detail', 'item_ref', 'name')
end
end
# Helper to parse description across Quickbooks::Model::Line and Hash structures
def extract_description(line)
if line.respond_to?(:description)
line.description
elsif line.is_a?(Hash)
line[:description] || line['description']
end
end
end end
@@ -0,0 +1,198 @@
<div class="contextual">
<%= link_to customer_appointment_path(@appointment) do %>
<i class="fa-solid fa-arrow-left"></i> <%= l(:label_appointment) %>
<% end %>
</div>
<h2>
<%= l(:button_create_issues_from_estimate) %>
<% if @appointment.estimate %>
<span class="estimate-preview-subtitle">
&middot; <%= l(:label_estimate) %> #<%= @appointment.estimate.doc_number %>
&middot; <%= @appointment.subject %>
</span>
<% end %>
</h2>
<%# Target project: changing it reloads the page with that project's trackers and templates %>
<% if @available_projects.size > 1 %>
<%= form_tag issues_preview_customer_appointment_path(@appointment), method: :get, id: 'estimate-issues-project-form' do %>
<p>
<label for="project_id"><strong><%= l(:field_project) %>:</strong></label>
<%= select_tag :project_id,
options_from_collection_for_select(@available_projects, :id, :name, @target_project.id),
onchange: 'this.form.submit();' %>
<noscript><%= submit_tag l(:button_apply), name: nil %></noscript>
</p>
<% end %>
<% else %>
<p><strong><%= l(:field_project) %>:</strong> <%= link_to_project @target_project %></p>
<% end %>
<% if @builder.errors.any? %>
<div id="errorExplanation">
<ul>
<% @builder.errors.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<% proposals = @builder.proposals %>
<% if @appointment.estimate.blank? %>
<p class="nodata"><%= l(:label_appointment_has_no_estimate) %></p>
<% elsif proposals.empty? %>
<p class="nodata">
<%= l(:error_no_labor_lines_found) %>
(<%= l(:label_estimate_item_codes) %>: <%= RedmineQboCalendar::EstimateIssueBuilder.item_codes.join(', ') %>)
<% if User.current.admin? %>
&middot; <%= link_to l(:label_settings), plugin_settings_path(id: 'redmine_qbo_calendar') %>
<% end %>
</p>
<% else %>
<%
templates_enabled = RedmineQboCalendar::IssueTemplateSupport.enabled_for?(@target_project)
template_data = @templates.map { |t| { key: t.key, title: t.title, tracker_id: t.tracker_id, is_default: t.is_default, group: t.group } }
default_template_for = ->(tracker_id) { @templates.detect { |t| t.tracker_id == tracker_id.to_i && t.is_default }&.key }
selectable_count = proposals.count { |p| !p.created? }
%>
<%= form_tag create_issues_customer_appointment_path(@appointment),
method: :post,
id: 'estimate-issues-form',
data: { templates: template_data.to_json } do %>
<%= hidden_field_tag :project_id, @target_project.id %>
<table class="list estimate-issues-preview">
<thead>
<tr>
<th class="checkbox">
<% if selectable_count > 0 %>
<input type="checkbox" id="estimate-issues-toggle-all" checked title="<%= l(:button_check_all) %>">
<% end %>
</th>
<th><%= l(:label_estimate_item) %></th>
<th><%= l(:field_subject) %></th>
<th><%= l(:field_tracker) %></th>
<% if templates_enabled %>
<th><%= l(:label_issue_template) %></th>
<% end %>
<th><%= l(:field_estimated_hours) %></th>
</tr>
</thead>
<tbody>
<% proposals.each do |proposal| %>
<% field = "lines[#{proposal.line_id}]" %>
<% if proposal.created? %>
<tr class="estimate-line created">
<td class="checkbox"><input type="checkbox" disabled></td>
<td><%= proposal.item_name %></td>
<td class="subject"><%= proposal.description %></td>
<td colspan="<%= templates_enabled ? 3 : 2 %>">
<%= l(:label_estimate_line_already_created) %>:
<%= link_to_issue(proposal.existing_issue, truncate: 60) %>
</td>
</tr>
<% else %>
<%
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)
hours = row.key?('estimated_hours') ? row['estimated_hours'] : proposal.hours
%>
<tr class="estimate-line">
<td class="checkbox">
<%= hidden_field_tag "#{field}[selected]", '0', id: nil %>
<%= check_box_tag "#{field}[selected]", '1', selected, class: 'estimate-line-select', id: nil %>
</td>
<td><%= proposal.item_name %></td>
<td class="subject">
<%= text_field_tag "#{field}[subject]", row['subject'] || proposal.description,
maxlength: 255, class: 'estimate-line-subject', id: nil %>
</td>
<td>
<%= select_tag "#{field}[tracker_id]",
options_from_collection_for_select(@trackers, :id, :name, tracker_id),
class: 'estimate-line-tracker', id: nil %>
</td>
<% if templates_enabled %>
<td>
<%# Options are filled by the script below to match the chosen tracker %>
<%= select_tag "#{field}[template]",
options_for_select([[l(:label_no_issue_template), '']] +
@templates.select { |t| t.tracker_id == tracker_id }.map { |t| [t.title, t.key] }, template_key),
class: 'estimate-line-template', id: nil %>
</td>
<% end %>
<td>
<%= number_field_tag "#{field}[estimated_hours]", hours, step: 0.25, min: 0, size: 6, id: nil %>
</td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
<p class="estimate-issues-hint">
<% if templates_enabled %>
<%= l(:text_estimate_issues_template_hint) %>
<% else %>
<%= l(:text_estimate_issues_hint) %>
<% end %>
</p>
<p>
<% if selectable_count > 0 %>
<%= submit_tag l(:button_create_issues), data: { disable_with: l(:label_loading) } %>
<% end %>
<%= link_to l(:button_cancel), customer_appointment_path(@appointment) %>
</p>
<% end %>
<%= javascript_tag do %>
(function () {
var form = document.getElementById('estimate-issues-form');
if (!form) return;
// Select / deselect all lines
var toggleAll = document.getElementById('estimate-issues-toggle-all');
if (toggleAll) {
toggleAll.addEventListener('change', function () {
form.querySelectorAll('.estimate-line-select').forEach(function (box) { box.checked = toggleAll.checked; });
});
}
// Keep each template dropdown limited to templates for the chosen tracker
var templates = [];
try { templates = JSON.parse(form.dataset.templates || '[]'); } catch (e) { templates = []; }
var noneLabel = <%= raw l(:label_no_issue_template).to_json %>;
function fillTemplates(templateSelect, trackerId, useDefault) {
var current = templateSelect.value;
var matches = templates.filter(function (t) { return String(t.tracker_id) === String(trackerId); });
templateSelect.innerHTML = '';
templateSelect.appendChild(new Option(noneLabel, ''));
matches.forEach(function (t) {
templateSelect.appendChild(new Option(t.title + (t.group === 'global' ? ' (global)' : ''), t.key));
});
var defaultTemplate = matches.find(function (t) { return t.is_default; });
if (useDefault) {
templateSelect.value = defaultTemplate ? defaultTemplate.key : '';
} else if (matches.some(function (t) { return t.key === current; })) {
templateSelect.value = current;
}
}
form.querySelectorAll('tr.estimate-line').forEach(function (row) {
var tracker = row.querySelector('.estimate-line-tracker');
var template = row.querySelector('.estimate-line-template');
if (!tracker || !template) return;
fillTemplates(template, tracker.value, false);
tracker.addEventListener('change', function () { fillTemplates(template, tracker.value, true); });
});
})();
<% end %>
<% end %>
@@ -15,9 +15,7 @@
<% end %> <% end %>
<% if @appointment.estimate && User.current.allowed_to?(:create_customer_appointment_issues, nil, global: true) %> <% if @appointment.estimate && User.current.allowed_to?(:create_customer_appointment_issues, nil, global: true) %>
<%= link_to create_issues_customer_appointment_path(@appointment), <%= link_to issues_preview_customer_appointment_path(@appointment) do %>
method: :post,
data: { confirm: l(:text_are_you_sure) } do %>
<i class="fa-solid fa-list-check"></i> <%= l(:button_create_issues_from_estimate) %> <i class="fa-solid fa-list-check"></i> <%= l(:button_create_issues_from_estimate) %>
<% end %> <% end %>
<% end %> <% end %>
@@ -0,0 +1,17 @@
<fieldset class="box tabular">
<legend><%= l(:label_estimate_issue_settings) %></legend>
<p>
<label for="settings_item_codes"><%= l(:label_estimate_item_codes) %></label>
<%= text_area_tag 'settings[item_codes]', settings['item_codes'], rows: 5, cols: 30, id: 'settings_item_codes' %>
<em class="info"><%= l(:text_estimate_item_codes_info) %></em>
</p>
<p>
<label for="settings_default_tracker_id"><%= l(:label_default_tracker) %></label>
<%= select_tag 'settings[default_tracker_id]',
options_from_collection_for_select(Tracker.sorted, :id, :name, settings['default_tracker_id'].to_i),
include_blank: true, id: 'settings_default_tracker_id' %>
<em class="info"><%= l(:text_default_tracker_info) %></em>
</p>
</fieldset>
@@ -622,3 +622,23 @@ table.appointment-history td.subject {
margin-left: 6px; margin-left: 6px;
text-decoration: none; text-decoration: none;
} }
/* Create issues from estimate preview */
.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 tr.created td {
color: #888;
}
.estimate-issues-hint {
color: #777;
font-size: 0.9em;
}
+16 -1
View File
@@ -21,8 +21,11 @@ en:
day_name_thursday: "Thursday" day_name_thursday: "Thursday"
day_name_tuesday: "Tuesday" day_name_tuesday: "Tuesday"
day_name_wednesday: "Wednesday" day_name_wednesday: "Wednesday"
button_create_issues: "Create issues"
button_create_issues_from_estimate: "Create Issues from Estimate" button_create_issues_from_estimate: "Create Issues from Estimate"
error_no_labor_lines_found: "No Labor lines with a description were found on the estimate" error_estimate_lines_already_created: "Some of these estimate lines were just turned into issues by someone else. Please review and try again."
error_no_estimate_lines_selected: "Select at least one estimate line"
error_no_labor_lines_found: "No lines with a description and a matching item code were found on the estimate"
error_holiday: "Cannot be scheduled on holiday: %{name}" error_holiday: "Cannot be scheduled on holiday: %{name}"
error_non_working_day: "Cannot be scheduled on a non-working day" error_non_working_day: "Cannot be scheduled on a non-working day"
field_customer_name: Customer field_customer_name: Customer
@@ -37,6 +40,7 @@ en:
label_add_appointment: Add Appointment label_add_appointment: Add Appointment
label_appointment: Appointment label_appointment: Appointment
label_appointment_new: "New Appointment" label_appointment_new: "New Appointment"
label_appointment_has_no_estimate: "This appointment has no estimate attached"
label_appointments: Appointments label_appointments: Appointments
label_appointment_history: Appointment History label_appointment_history: Appointment History
label_upcoming_customer_appointments: Upcoming Appointments label_upcoming_customer_appointments: Upcoming Appointments
@@ -56,7 +60,14 @@ en:
label_edit_appointment: Edit Appointment label_edit_appointment: Edit Appointment
label_end_date: End Date label_end_date: End Date
label_estimated_hours: Estimated Time label_estimated_hours: Estimated Time
label_default_tracker: "Default tracker"
label_estimate_issue_settings: "Issues from estimates"
label_estimate_item: "Item"
label_estimate_item_codes: "Estimate item codes"
label_estimate_line_already_created: "Already created"
label_event: Event label_event: Event
label_issue_template: "Template"
label_no_issue_template: "(no template)"
label_hide_past_weeks: "Hide Past Weeks" label_hide_past_weeks: "Hide Past Weeks"
label_holiday_edit: Edit Holiday label_holiday_edit: Edit Holiday
label_holiday_new: New Holiday label_holiday_new: New Holiday
@@ -90,4 +101,8 @@ en:
permission_edit_customer_appointments: "Edit customer appointments" permission_edit_customer_appointments: "Edit customer appointments"
permission_manage_customer_appointments: Manage Customer Appointments permission_manage_customer_appointments: Manage Customer Appointments
permission_view_customer_appointments: "View customer appointments" permission_view_customer_appointments: "View customer appointments"
text_default_tracker_info: "Pre-selected for each proposed issue. Leave blank to use the project's first tracker."
text_estimate_issues_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. Edit anything before creating."
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."
text_estimate_item_codes_info: "QBO item names that can become issues, one per line (e.g. Labor, Alignments). Matches the full item name or any part of a Category:Item name, ignoring case."
title_customer_appointments: Customer Appointments title_customer_appointments: Customer Appointments
+1
View File
@@ -17,6 +17,7 @@ RedmineApp::Application.routes.draw do
get :history get :history
end end
member do member do
get :issues_preview
post :create_issues post :create_issues
end end
end end
@@ -0,0 +1,25 @@
#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.
# Records which issue was created from which QBO estimate line, so a line can't be turned into
# an issue twice (even from a different appointment that uses the same estimate).
class CreateAppointmentEstimateIssues < ActiveRecord::Migration[7.0]
def change
create_table :appointment_estimate_issues do |t|
t.references :customer_appointment, index: true
t.bigint :estimate_id, null: false
t.string :line_id, null: false
t.references :issue, null: false, index: { unique: true }
t.datetime :created_on, null: false
end
add_index :appointment_estimate_issues, [:estimate_id, :line_id], unique: true, name: 'index_appointment_estimate_issues_on_line'
end
end
+5 -1
View File
@@ -19,6 +19,10 @@ Redmine::Plugin.register :redmine_qbo_calendar do
author_url 'https://barrettefabrication.com' author_url 'https://barrettefabrication.com'
requires_redmine version_or_higher: '7.0.0' requires_redmine version_or_higher: '7.0.0'
# Item codes: which QBO estimate items can become issues (e.g. Labor, Alignments)
settings default: { 'item_codes' => "Labor", 'default_tracker_id' => '' },
partial: 'settings/qbo_calendar_settings'
# Add Holidays index to the Redmine Administration Menu # Add Holidays index to the Redmine Administration Menu
menu :admin_menu, :holidays, { controller: 'holidays', action: 'index' }, caption: :label_holiday_plural, html: { class: 'icon icon-list' } menu :admin_menu, :holidays, { controller: 'holidays', action: 'index' }, caption: :label_holiday_plural, html: { class: 'icon icon-list' }
@@ -35,7 +39,7 @@ Redmine::Plugin.register :redmine_qbo_calendar do
permission :add_customer_appointments, { customer_appointments: [:new, :create, :customer_options] }, global: true permission :add_customer_appointments, { customer_appointments: [:new, :create, :customer_options] }, global: true
permission :edit_customer_appointments, { customer_appointments: [:edit, :update, :customer_options] }, global: true permission :edit_customer_appointments, { customer_appointments: [:edit, :update, :customer_options] }, global: true
permission :delete_customer_appointments, { customer_appointments: [:destroy] }, global: true permission :delete_customer_appointments, { customer_appointments: [:destroy] }, global: true
permission :create_customer_appointment_issues, { customer_appointments: [:create_issues] }, global: true permission :create_customer_appointment_issues, { customer_appointments: [:issues_preview, :create_issues] }, global: true
# Register top menu items # Register top menu items
menu :top_menu, :calendar, { controller: :calendars, action: :show }, caption: :label_calendar, if: Proc.new {User.current.logged?} menu :top_menu, :calendar, { controller: :calendars, action: :show }, caption: :label_calendar, if: Proc.new {User.current.logged?}
+1
View File
@@ -13,6 +13,7 @@ module RedmineQboCalendar
# Patches # Patches
Customer.prepend(RedmineQboCalendar::Patches::CustomerPatch) Customer.prepend(RedmineQboCalendar::Patches::CustomerPatch)
User.prepend(RedmineQboCalendar::Patches::UserPatch) User.prepend(RedmineQboCalendar::Patches::UserPatch)
Issue.prepend(RedmineQboCalendar::Patches::IssuePatch)
CalendarsController.prepend(RedmineQboCalendar::Patches::CalendarsControllerPatch) CalendarsController.prepend(RedmineQboCalendar::Patches::CalendarsControllerPatch)
ApplicationHelper.prepend(RedmineQboCalendar::Patches::ApplicationHelperPatch) 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