From fc503fca686c05e389c93315d03e6c24bdf3ce3d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 30 Oct 2026 23:11:33 -0400 Subject: [PATCH] Estimate hours rule, linked issues, issue creation via redmine_qbo_billing - An appointment's hours can't be less than its estimate's labor hours (checked when the estimate or hours change, so the quick status buttons still work on older appointments). Picking an estimate on the form, or arriving from an estimate page, raises the hours to match. - The appointment page lists the issues linked to its estimate. - Creating issues from an estimate moved to redmine_qbo_billing (now required): Create Issues from Estimate opens its page with this appointment's dates, technician, vehicle and project (via qbo_billing_issue_defaults). The builder, preview page, settings and rake task are removed here; the old settings stay registered so billing can read them until its own are saved. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM --- README.md | 6 + .../customer_appointments_controller.rb | 71 +---- app/models/customer_appointment.rb | 26 ++ .../customer_appointments/_form.html.erb | 16 ++ .../issues_preview.html.erb | 251 ------------------ app/views/customer_appointments/show.html.erb | 10 +- .../settings/_qbo_calendar_settings.html.erb | 31 +-- config/locales/en.yml | 30 +-- config/routes.rb | 5 +- init.rb | 16 +- lib/redmine_qbo_calendar.rb | 1 + .../estimate_issue_builder.rb | 239 ----------------- .../hooks/billing_hook_listener.rb | 43 +++ lib/redmine_qbo_calendar/issue_field_set.rb | 72 ----- .../issue_template_support.rb | 58 ---- lib/tasks/redmine_qbo_calendar.rake | 24 -- 16 files changed, 135 insertions(+), 764 deletions(-) delete mode 100644 app/views/customer_appointments/issues_preview.html.erb delete mode 100644 lib/redmine_qbo_calendar/estimate_issue_builder.rb create mode 100644 lib/redmine_qbo_calendar/hooks/billing_hook_listener.rb delete mode 100644 lib/redmine_qbo_calendar/issue_field_set.rb delete mode 100644 lib/redmine_qbo_calendar/issue_template_support.rb delete mode 100644 lib/tasks/redmine_qbo_calendar.rake diff --git a/README.md b/README.md index 098b693..c7b8fd2 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ This plugin allows for adding customer appointment capability to the Redmine cal * **Redmine:** 6.1+ * **Parent Plugin:** [Redmine QuickBooks Online](https://github.com/rickbarrette/redmine_qbo) (must be installed and configured) + +* **Billing Plugin:** [Redmine QuickBooks Billing](https://github.com/rickbarrette/redmine_qbo_billing). It creates issues from an appointment's estimate and works out the estimate's labor hours. --- @@ -26,6 +28,10 @@ This plugin allows for adding customer appointment capability to the Redmine cal Add appointments to the redmine calanedar with the abiltiy to attach a QBO customer, QBO Vehicle, QBO Estimate, ect. +* An appointment's hours can't be less than its estimate's labor hours (the lines matching redmine_qbo_billing's estimate item codes). Picking an estimate raises the hours to match. +* The appointment page lists the issues linked to its estimate, and **Create Issues from Estimate** opens redmine_qbo_billing's Create issues page with the appointment's dates, technician and vehicle. +* Estimate pages in redmine_qbo_billing get an **Add appointment** link. + --- ## Installation diff --git a/app/controllers/customer_appointments_controller.rb b/app/controllers/customer_appointments_controller.rb index eb03965..27644a6 100644 --- a/app/controllers/customer_appointments_controller.rb +++ b/app/controllers/customer_appointments_controller.rb @@ -11,13 +11,10 @@ class CustomerAppointmentsController < ApplicationController before_action :require_login before_action :find_project, except: [:index] - before_action :find_appointment, only: [ :show, :edit, :update, :destroy, :issues_preview, :create_issues ] + before_action :find_appointment, only: [ :show, :edit, :update, :destroy ] # This tells Redmine to check global permissions for the current controller/action before_action :authorize_global - helper :projects - helper :custom_fields - def customer_options customer = Customer.find_by(id: params[:customer_id]) @@ -27,31 +24,11 @@ class CustomerAppointmentsController < ApplicationController } end - # 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 - load_issue_preview - return if performed? - - @rows = params[:lines].respond_to?(:to_unsafe_h) ? params[:lines].to_unsafe_h : {} - @custom_field_values = submitted_custom_field_values - created_issues = @builder.create_issues(project: @target_project, rows: @rows, - custom_field_values: @custom_field_values) - - if created_issues.any? - flash[:notice] = l(:notice_appointment_issues_created, count: created_issues.size) - redirect_to customer_appointment_path(@appointment) - else - # Rebuild the fields so the form keeps what was entered - @field_set = RedmineQboCalendar::IssueFieldSet.new(project: @target_project, trackers: @trackers, - values: @custom_field_values) - render :issues_preview, status: :unprocessable_entity - end + # The estimate's labor hours (redmine_qbo_billing's item codes), so the form can make sure the + # appointment's hours aren't less + def estimate_hours + estimate = Estimate.find_by(id: params[:estimate_id]) + render json: { hours: CustomerAppointment.estimate_labor_hours(estimate) } end def index @@ -88,6 +65,8 @@ class CustomerAppointmentsController < ApplicationController def show @appointment = CustomerAppointment.find(params[:id]) + # Issues linked to the appointment's estimate (made from it, or linked by hand) + @estimate_issues = @appointment.estimate_id ? Issue.visible.where(estimate_id: @appointment.estimate_id).order(:id).to_a : [] end def new @@ -138,6 +117,9 @@ class CustomerAppointmentsController < ApplicationController if params[:estimate_id].present? && customer.estimates.exists?(id: params[:estimate_id]) @appointment.estimate_id = params[:estimate_id] + # At least the estimate's labor hours + labor = CustomerAppointment.estimate_labor_hours(@appointment.estimate) + @appointment.estimated_hours = labor if labor > @appointment.estimated_hours.to_i end if params[:vehicle_id].present? && customer.respond_to?(:vehicles) && customer.vehicles.exists?(id: params[:vehicle_id]) @appointment.vehicle_id = params[:vehicle_id] @@ -170,37 +152,6 @@ class CustomerAppointmentsController < ApplicationController nil 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 default project - # from the plugin settings, then the first project the user can add issues to - default_project = @available_projects.detect { |p| p.id == RedmineQboCalendar::EstimateIssueBuilder.default_project_id } - @target_project = - if @project - @project if @available_projects.include?(@project) - elsif @available_projects.include?(@appointment.project) - @appointment.project - else - default_project || @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) - @field_set = RedmineQboCalendar::IssueFieldSet.new(project: @target_project, trackers: @trackers) - @rows ||= {} - end - - # The shared custom field values from the preview form: { custom_field_id => value } - def submitted_custom_field_values - values = params.dig(:issue, :custom_field_values) - values.respond_to?(:to_unsafe_h) ? values.to_unsafe_h : {} - end - def find_project @project = Project.find(params[:project_id]) if params[:project_id].present? end diff --git a/app/models/customer_appointment.rb b/app/models/customer_appointment.rb index 4780b7c..fb2c270 100644 --- a/app/models/customer_appointment.rb +++ b/app/models/customer_appointment.rb @@ -26,6 +26,9 @@ class CustomerAppointment < ActiveRecord::Base # Prevent scheduling on non-working days or holidays validate :validate_working_day + # The hours can't be less than the attached estimate's labor hours + validate :validate_hours_cover_estimate + # Capitalize the first letter only; titleize mangled vehicle names and acronyms (JL -> Jl, LED -> Led) normalizes :subject, with: ->(subject) { subject.strip.sub(/\A[a-z]/, &:upcase) } @@ -77,12 +80,35 @@ class CustomerAppointment < ActiveRecord::Base subject end + # The estimate's labor hours rounded up to whole hours (appointment hours are whole numbers): the + # quantities of its lines whose item matches redmine_qbo_billing's item codes (e.g. Labor). 0 if the + # estimate can't be read from QuickBooks. + def self.estimate_labor_hours(estimate) + return 0 if estimate.nil? + RedmineQboBilling::EstimateIssueBuilder.labor_hours(estimate).ceil + rescue StandardError => e + Rails.logger.warn "[CustomerAppointment] Could not read labor hours for estimate #{estimate&.id}: #{e.message}" + 0 + end + private def log(msg) Rails.logger.info "[CustomerAppointment] #{msg}" end + # Checked when the estimate or the hours change, so changing just the status (the quick status buttons) + # never fails on an older appointment + def validate_hours_cover_estimate + return if estimate.nil? + return unless new_record? || will_save_change_to_estimate_id? || will_save_change_to_estimated_hours? + + labor = self.class.estimate_labor_hours(estimate) + return if labor.zero? || estimated_hours.to_i >= labor + + errors.add(:base, I18n.t(:error_hours_less_than_estimate, hours: labor, estimate: estimate.doc_number)) + end + # Validates that the appointment date does not land on a weekend or holiday def validate_working_day return if date.blank? diff --git a/app/views/customer_appointments/_form.html.erb b/app/views/customer_appointments/_form.html.erb index 0d92995..b1d0df6 100644 --- a/app/views/customer_appointments/_form.html.erb +++ b/app/views/customer_appointments/_form.html.erb @@ -48,6 +48,22 @@ <%= submit_tag l(:button_save) %> <% end %> +<%# When an estimate is picked, the hours are raised to at least its labor hours %> +<%= javascript_tag do %> + $(function () { + var $estimate = $('#appointment_estimate_id'); + var $hours = $('#customer_appointment_estimated_hours'); + if (!$estimate.length || !$hours.length) return; + $estimate.on('change', function () { + if (!this.value) return; + $.getJSON('<%= j estimate_hours_customer_appointments_path %>', { estimate_id: this.value }).done(function (data) { + var hours = parseInt(data.hours, 10) || 0; + if (hours > (parseInt($hours.val(), 10) || 0)) $hours.val(hours); + }); + }); + }); +<% end %> + +<% if @appointment.estimate %> +

<%= l(:label_estimate_issues, estimate: @appointment.estimate.doc_number) %>

+ <%= render partial: 'issues/list_simple', locals: { issues: @estimate_issues } %> +<% end %> + <%= call_hook :show_customer_appointment, { appointment: @appointment } %> diff --git a/app/views/settings/_qbo_calendar_settings.html.erb b/app/views/settings/_qbo_calendar_settings.html.erb index 2f59ac0..008355a 100644 --- a/app/views/settings/_qbo_calendar_settings.html.erb +++ b/app/views/settings/_qbo_calendar_settings.html.erb @@ -1,26 +1,5 @@ -
- <%= l(:label_estimate_issue_settings) %> - -

- - <%= text_area_tag 'settings[item_codes]', settings['item_codes'], rows: 5, cols: 30, id: 'settings_item_codes' %> - <%= l(:text_estimate_item_codes_info) %> -

- -

- - <%= select_tag 'settings[default_project_id]', - project_tree_options_for_select(Project.active.sorted, - selected: Project.find_by(id: settings['default_project_id'].to_i)), - include_blank: true, id: 'settings_default_project_id' %> - <%= l(:text_default_project_info) %> -

- -

- - <%= 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' %> - <%= l(:text_default_tracker_info) %> -

-
+<%# The issues-from-estimate settings moved to redmine_qbo_billing %> +

+ <%= l(:text_estimate_issue_settings_moved) %> + <%= link_to l(:label_redmine_qbo_billing_settings), plugin_settings_path(id: 'redmine_qbo_billing') %> +

diff --git a/config/locales/en.yml b/config/locales/en.yml index 2182860..6ada001 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -21,11 +21,7 @@ en: day_name_thursday: "Thursday" day_name_tuesday: "Tuesday" day_name_wednesday: "Wednesday" - button_create_issues: "Create issues" button_create_issues_from_estimate: "Create Issues from 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_non_working_day: "Cannot be scheduled on a non-working day" field_customer_name: Customer @@ -40,7 +36,6 @@ en: label_add_appointment: Add Appointment label_appointment: Appointment label_appointment_new: "New Appointment" - label_appointment_has_no_estimate: "This appointment has no estimate attached" label_appointments: Appointments label_appointment_history: Appointment History label_upcoming_customer_appointments: Upcoming Appointments @@ -60,16 +55,7 @@ en: label_edit_appointment: Edit Appointment label_end_date: End Date label_estimated_hours: Estimated Time - label_default_project: "Default project" - label_default_tracker: "Default tracker" - label_estimate_issue_settings: "Issues from estimates" - label_estimate_issue_fields: "Issue fields" - label_estimate_item: "Item" - label_estimate_item_codes: "Estimate item codes" - label_estimate_line_already_created: "Already created" label_event: Event - label_issue_template: "Template" - label_no_issue_template: "(no template)" label_hide_past_weeks: "Hide Past Weeks" label_holiday_edit: Edit Holiday label_holiday_new: New Holiday @@ -93,20 +79,14 @@ en: label_week_3rd: "3rd" label_week_4th: "4th" label_week_last: "Last" - notice_appointment_issues_created: - one: "1 issue created from the estimate" - other: "%{count} issues created from the estimate" notice_unable_delete_holiday: "Unable to delete holiday" permission_add_customer_appointments: "Add customer appointments" - permission_create_customer_appointment_issues: "Create issues from appointment estimates" permission_delete_customer_appointments: "Delete customer appointments" permission_edit_customer_appointments: "Edit customer appointments" permission_manage_customer_appointments: Manage Customer Appointments permission_view_customer_appointments: "View customer appointments" - text_default_project_info: "Where issues from estimates are created when the appointment has no project. Users who can't add issues there get their first allowed project. It can still be changed on the preview page." - text_default_tracker_info: "Pre-selected for each proposed issue. Leave blank to use the project's first tracker." - text_estimate_issue_fields_info: "Entered once and applied to every created issue whose tracker uses the field. Fields marked * are required by the selected trackers." - text_estimate_issues_hint: "The subject comes from the estimate line's description and estimated hours from its quantity. Edit anything before creating. New issues are related to each other and to issues already created from this estimate." - text_estimate_issues_template_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_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 \ No newline at end of file + title_customer_appointments: Customer Appointments + error_hours_less_than_estimate: "The hours can't be less than the %{hours} labor hours on estimate #%{estimate}" + label_estimate_issues: "Issues for estimate #%{estimate}" + label_redmine_qbo_billing_settings: "Redmine QBO Billing settings" + text_estimate_issue_settings_moved: "Creating issues from estimates moved to redmine_qbo_billing: the item codes, default project and default tracker are set there." diff --git a/config/routes.rb b/config/routes.rb index 1cbb025..c90aa4a 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -14,12 +14,9 @@ RedmineApp::Application.routes.draw do resources :customer_appointments do collection do get :customer_options + get :estimate_hours get :history end - member do - get :issues_preview - post :create_issues - end end end \ No newline at end of file diff --git a/init.rb b/init.rb index 690cfb4..ddaa106 100644 --- a/init.rb +++ b/init.rb @@ -20,6 +20,8 @@ Redmine::Plugin.register :redmine_qbo_calendar do requires_redmine version_or_higher: '7.0.0' # Item codes: which QBO estimate items can become issues (e.g. Labor, Alignments) + # The issues-from-estimate settings moved to redmine_qbo_billing, which reads these old values until its + # own are saved, so they're still registered here settings default: { 'item_codes' => "Labor", 'default_tracker_id' => '', 'default_project_id' => '' }, partial: 'settings/qbo_calendar_settings' @@ -33,13 +35,21 @@ Redmine::Plugin.register :redmine_qbo_calendar do raise 'Please install the redmine_qbo plugin (https://github.com/rickbarrette/redmine_qbo)' end + # Creating issues from estimates and estimate labor hours live in redmine_qbo_billing (it sorts before this + # plugin, so Redmine has already loaded it) + begin + requires_redmine_plugin :redmine_qbo_billing, version_or_higher: '2026.10.0' + rescue Redmine::PluginNotFound + raise 'Please install the redmine_qbo_billing plugin (https://github.com/rickbarrette/redmine_qbo_billing)' + end + # Global Permissions permission :view_customer_appointments, { customer_appointments: [:index, :show, :history] }, global: true # customer_options feeds the vehicle/estimate dropdowns on the new and edit forms - 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 :add_customer_appointments, { customer_appointments: [:new, :create, :customer_options, :estimate_hours] }, global: true + permission :edit_customer_appointments, { customer_appointments: [:edit, :update, :customer_options, :estimate_hours] }, global: true permission :delete_customer_appointments, { customer_appointments: [:destroy] }, global: true - permission :create_customer_appointment_issues, { customer_appointments: [:issues_preview, :create_issues] }, global: true + # Creating issues from an appointment's estimate is redmine_qbo_billing's "Create issues from estimates" # Register top menu items menu :top_menu, :calendar, { controller: :calendars, action: :show }, caption: :label_calendar, if: Proc.new {User.current.logged?} diff --git a/lib/redmine_qbo_calendar.rb b/lib/redmine_qbo_calendar.rb index 6c7a7eb..c579292 100644 --- a/lib/redmine_qbo_calendar.rb +++ b/lib/redmine_qbo_calendar.rb @@ -21,6 +21,7 @@ module RedmineQboCalendar RedmineQboCalendar::Hooks::ViewHookListener RedmineQboCalendar::Hooks::CustomerActionsHookListener RedmineQboCalendar::Hooks::CustomerShowHookListener + RedmineQboCalendar::Hooks::BillingHookListener Rails.configuration.to_prepare do ApplicationController.prepend_view_path( File.expand_path("app/views", __dir__) ) diff --git a/lib/redmine_qbo_calendar/estimate_issue_builder.rb b/lib/redmine_qbo_calendar/estimate_issue_builder.rb deleted file mode 100644 index a3b98fb..0000000 --- a/lib/redmine_qbo_calendar/estimate_issue_builder.rb +++ /dev/null @@ -1,239 +0,0 @@ -#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 - # - All issues created from the same estimate are related to each other, across batches - 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.default_project_id - settings['default_project_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 - - # 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 :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' => ... } } - # 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 - 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 - - 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? - - 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 - - # Relates the new issues to each other and to every issue created earlier from the same estimate. - def relate_issues(new_issues) - earlier = AppointmentEstimateIssue.where(estimate_id: estimate.id) - .where.not(issue_id: new_issues.map(&:id)) - .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 = 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 diff --git a/lib/redmine_qbo_calendar/hooks/billing_hook_listener.rb b/lib/redmine_qbo_calendar/hooks/billing_hook_listener.rb new file mode 100644 index 0000000..ff8200c --- /dev/null +++ b/lib/redmine_qbo_calendar/hooks/billing_hook_listener.rb @@ -0,0 +1,43 @@ +#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 Hooks + + # Hooks for redmine_qbo_billing + class BillingHookListener < Redmine::Hook::Listener + + # "Create issues" opened from an appointment (?appointment_id=): the issues get the appointment's dates, + # technician, vehicle and project, and the page returns to the appointment + def qbo_billing_issue_defaults(context = {}) + appointment_id = context.dig(:params, :appointment_id) + return nil if appointment_id.blank? + return nil unless User.current.allowed_to?(:view_customer_appointments, nil, global: true) + + appointment = CustomerAppointment.find_by(id: appointment_id) + estimate = context[:estimate] + return nil unless appointment && estimate && appointment.estimate_id.to_s == estimate.id.to_s + + { + start_date: appointment.start_date, + due_date: appointment.due_date, + assignee: appointment.user, + vehicle_id: appointment.vehicle_id, + project: appointment.project, + description: "The purpose of this work is to bill the time spent on this issue for Estimate ##{estimate.doc_number} " \ + "for Appointment: #{appointment.subject}", + return_path: Rails.application.routes.url_helpers.customer_appointment_path(appointment), + return_label: appointment.subject + } + end + + end + end +end diff --git a/lib/redmine_qbo_calendar/issue_field_set.rb b/lib/redmine_qbo_calendar/issue_field_set.rb deleted file mode 100644 index ca0265e..0000000 --- a/lib/redmine_qbo_calendar/issue_field_set.rb +++ /dev/null @@ -1,72 +0,0 @@ -#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 - # The issue custom fields shown on the "Create Issues from Estimate" preview page. - # - # For every tracker the user may pick, a sample new issue is built in the target project to find - # which custom fields the user can edit, and which are required (either the field's own - # "Required" flag or a workflow rule for that tracker / role). Values are entered once on the page - # and applied to every created issue whose tracker uses that field. - class IssueFieldSet - # File uploads can't be handled by this shared form - UNSUPPORTED_FORMATS = %w[attachment].freeze - - Field = Struct.new(:custom_field, :custom_value, :tracker_ids, :required_tracker_ids, keyword_init: true) do - def id - custom_field.id - end - - def required_for_any? - required_tracker_ids.any? - end - end - - attr_reader :fields - - # values: the submitted { custom_field_id => value } hash, used to refill the form after errors - def initialize(project:, trackers:, user: User.current, values: {}) - @fields = [] - by_id = {} - - Array(trackers).each do |tracker| - issue = Issue.new(project: project, author: user) - issue.tracker = tracker - - issue.editable_custom_field_values(user).each do |custom_value| - custom_field = custom_value.custom_field - next if UNSUPPORTED_FORMATS.include?(custom_field.field_format) - - field = by_id[custom_field.id] ||= Field.new( - custom_field: custom_field, - custom_value: custom_value, - tracker_ids: [], - required_tracker_ids: [] - ) - field.tracker_ids << tracker.id - if custom_field.is_required? || issue.required_attribute?(custom_field.id.to_s, user) - field.required_tracker_ids << tracker.id - end - end - end - - @fields = by_id.values.sort_by { |f| [f.required_for_any? ? 0 : 1, f.custom_field.position.to_i] } - - values = (values || {}).to_h.transform_keys(&:to_s) - @fields.each do |field| - field.custom_value.value = values[field.id.to_s] if values.key?(field.id.to_s) - end - end - - def any? - @fields.any? - end - end -end diff --git a/lib/redmine_qbo_calendar/issue_template_support.rb b/lib/redmine_qbo_calendar/issue_template_support.rb deleted file mode 100644 index c8648d8..0000000 --- a/lib/redmine_qbo_calendar/issue_template_support.rb +++ /dev/null @@ -1,58 +0,0 @@ -#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 diff --git a/lib/tasks/redmine_qbo_calendar.rake b/lib/tasks/redmine_qbo_calendar.rake deleted file mode 100644 index 141f956..0000000 --- a/lib/tasks/redmine_qbo_calendar.rake +++ /dev/null @@ -1,24 +0,0 @@ -#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. - -namespace :redmine_qbo_calendar do - desc 'Relate all issues created from the same QBO estimate to each other (one-time catch-up; safe to re-run)' - task relate_estimate_issues: :environment do - total = 0 - estimates = AppointmentEstimateIssue.distinct.pluck(:estimate_id) - - estimates.each do |estimate_id| - issues = AppointmentEstimateIssue.where(estimate_id: estimate_id).includes(:issue).filter_map(&:issue) - total += RedmineQboCalendar::EstimateIssueBuilder.relate_all(issues) - end - - puts "Checked #{estimates.size} estimate(s), created #{total} relation(s)." - end -end