From 0a3c73482aad865ecb1424cf995be59d3889a647 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 28 Oct 2026 23:04:46 -0400 Subject: [PATCH] Fix access, VIN decoding, vehicle history and form bugs Access - VIN decode status (polled by the vehicle page) is part of View vehicles; it was admin-only, so staff saw "Error checking VIN status" - Customer page only lists vehicles to users with View vehicles - Controller relies on authorize_global (drops redmine_qbo's require_user) Vehicle history - Vehicles with issues can't be deleted (restrict_with_error), so their service history is never lost; sold vehicles move by changing customer - The issue form always offers the issue's current vehicle, so editing an old issue after the vehicle was sold no longer blanks it - Issues must use a vehicle owned by their customer, checked only when the vehicle or customer changes, so historical issues are untouched - The issue form's vehicle list refreshes when the customer changes VIN decoding - Status checks queue at most one re-decode per vehicle per 5 minutes (was one every 3 seconds while pending) and pass the id the job expects - Network failures are retried by the job; an invalid VIN or no match is recorded as final; the error is recorded once retries run out - Decode results save without validations, so vehicles whose customer was deleted in QBO still get decoded Bugs - Failed create/update re-render the form with errors (create used to redirect to a possibly missing vehicle); duplicate VINs link to the vehicle on file - New vehicle without a customer, unknown customer ids and missing vehicles no longer raise; real errors aren't masked as 404s - last_service_date no longer fails without a service; last service is one query per vehicle, using a configurable mileage field (plugin settings; defaults to a field named Mileage) - Search works on PostgreSQL (year matched exactly, not with LIKE), includes the vehicle name, and matches multi-word queries - Missing "estimates" label, stray && in the appointment hook, notes field id, hard-coded English messages, shared page parameter - Vehicle labels that lived only in redmine_qbo are now in this plugin Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM --- app/controllers/vehicles_controller.rb | 148 +++++++----------- app/jobs/vehicle_vin_decode_job.rb | 22 ++- app/models/vehicle.rb | 54 ++++++- app/services/vin_decoder.rb | 7 +- .../customer_appointments/_show_hook.html.erb | 2 +- app/views/customers/_show_hook.html.erb | 7 +- .../settings/_vehicles_settings.html.erb | 9 ++ app/views/vehicles/_details.html.erb | 3 +- app/views/vehicles/_form.html.erb | 17 +- app/views/vehicles/_list.html.erb | 4 +- app/views/vehicles/edit.html.erb | 2 +- app/views/vehicles/show.html.erb | 20 ++- assets/javascripts/vehicles.js | 42 +++++ config/locales/en.yml | 21 ++- init.rb | 6 +- .../hooks/issues_form_hook_listener.rb | 13 +- lib/vehicles/hooks/view_hook_listener.rb | 3 +- lib/vehicles/patches/issue_patch.rb | 18 ++- 18 files changed, 268 insertions(+), 130 deletions(-) create mode 100644 app/views/settings/_vehicles_settings.html.erb create mode 100644 assets/javascripts/vehicles.js diff --git a/app/controllers/vehicles_controller.rb b/app/controllers/vehicles_controller.rb index 1c3aa10..3486265 100644 --- a/app/controllers/vehicles_controller.rb +++ b/app/controllers/vehicles_controller.rb @@ -8,148 +8,112 @@ # #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. -# This controller class will handle map management class VehiclesController < ApplicationController - include AuthHelper - - # This tells Redmine to check global permissions for the current controller/action + # Checks the vehicle permissions declared in init.rb (also requires login) before_action :authorize_global - before_action :require_user + before_action :find_vehicle, only: [:show, :status, :edit, :update, :destroy] + + # How long to wait before the status check may queue another VIN decode for the same vehicle + DECODE_REQUEST_THROTTLE = 5.minutes def allowed_params params.require(:vehicle).permit(:year, :make, :model, :customer_id, :notes, :vin) end - # display a list of all vehicles + # Vehicles for one customer (also as JSON for the issue form), or search results def index - if params[:customer_id] - begin - @vehicles = Customer.find_by_id(params[:customer_id]).vehicles.paginate(page: params[:page]) - rescue ActiveRecord::RecordNotFound - flash[:error] = t :alert_vehicle_not_found - render_404 + if params[:customer_id].present? + @customer = Customer.find_by(id: params[:customer_id]) + return render_404 unless @customer + + vehicles = @customer.vehicles.order(:year, :make, :model) + respond_to do |format| + format.html { @vehicles = vehicles.paginate(page: params[:page]) } + format.json { render json: vehicles.map { |v| { id: v.id, name: v.name } } } end + return end - # search for a vehicle by vin - if params[:search] - @vehicles = Vehicle.search(params[:search]).paginate(page: params[:page]) - if only_one_non_zero?(@vehicles) - redirect_to @vehicles.first - end + if params[:search].present? + @vehicles = Vehicle.search_all(params[:search]).paginate(page: params[:page]) + redirect_to @vehicles.first if @vehicles.total_entries == 1 end end - # return an HTML form for creating a new vehicle + # Form for a new vehicle, pre-filled with the customer when coming from a customer or appointment def new - @vehicle = Vehicle.new - @customer = Customer.find_by_id(params[:customer_id]) if params[:customer_id] + @vehicle = Vehicle.new(customer: Customer.find_by(id: params[:customer_id])) end - # create a new vehicle def create @vehicle = Vehicle.new(allowed_params) + if @vehicle.save flash[:notice] = t :notice_vehicle_created redirect_to @vehicle else - flash[:error] = @vehicle.errors.full_messages.to_sentence - redirect_to Vehicle.find_by_vin @vehicle.vin + # A duplicate VIN: point to the vehicle that already has it + @existing_vehicle = Vehicle.find_by(vin: @vehicle.vin) if @vehicle.errors.of_kind?(:vin, :taken) + render :new, status: :unprocessable_entity end end - # display a specific vehicle def show - begin - @vehicle = Vehicle.includes(issues: [:estimate, :invoices]).find(params[:id]) - @vin = @vehicle.vin.scan(/.{1,9}/) if @vehicle.vin - @issues = @vehicle.issues - .joins(:status) - .includes(:estimate, :invoices, :status, :project, :tracker, :priority) - .order(id: :desc) - @open_issues = @issues.select { |i| !i.status.is_closed } - @closed_issues = @issues.select { |i| i.status.is_closed } + @vin = @vehicle.vin.scan(/.{1,9}/) if @vehicle.vin + @issues = @vehicle.issues + .joins(:status) + .includes(:estimate, :invoices, :status, :project, :tracker, :priority) + .order(id: :desc) + @open_issues = @issues.reject { |i| i.status.is_closed } + @closed_issues = @issues.select { |i| i.status.is_closed } - flash[:error] = t :alert_no_customer if @vehicle.customer.nil? - rescue - flash[:error] = t :alert_vehicle_not_found - render_404 - end + flash.now[:error] = t :alert_no_customer if @vehicle.customer.nil? end - # used by the polling JS in vehicle#show + # Used by the polling script on the vehicle page while the VIN is being decoded def status - vehicle = Vehicle.find(params[:id]) - - # decode the vin if it hasn't been done for some reason - unless vehicle.vin_decoded - if vehicle.error.nil? - VehicleVinDecodeJob.perform_later(vehicle) + # Queue a decode if it never happened (e.g. the job was lost), at most once per throttle window + if !@vehicle.vin_decoded? && @vehicle.error.blank? + key = "redmine_qbo_vehicles/vin_decode_requested/#{@vehicle.id}" + unless Rails.cache.exist?(key) + Rails.cache.write(key, true, expires_in: DECODE_REQUEST_THROTTLE) + VehicleVinDecodeJob.perform_later(@vehicle.id) end end - - render json: { - decoded: vehicle.vin_decoded, - error: vehicle.error - } + + render json: { decoded: @vehicle.vin_decoded, error: @vehicle.error } end - # return an HTML form for editing a vehicle def edit - begin - @vehicle = Vehicle.find_by_id(params[:id]) - @customer = @vehicle.customer - rescue - flash[:error] = t :alert_vehicle_not_found - render_404 - end end - # update a specific vehicle def update - @customer = params[:customer] - begin - @vehicle = Vehicle.find_by_id(params[:id]) - if @vehicle.update(allowed_params) - flash[:notice] = t :notice_vehicle_updated - redirect_to @vehicle - else - redirect_to edit_vehicle_path - end - #show any errors anyways - flash[:error] = @vehicle.errors.full_messages.to_sentence unless @vehicle.errors.empty? - rescue - flash[:error] = t :alert_vehicle_not_updated - render_404 + if @vehicle.update(allowed_params) + flash[:notice] = t :notice_vehicle_updated + redirect_to @vehicle + else + render :edit, status: :unprocessable_entity end end - # delete a specific vehicle + # Vehicles with issues can't be deleted (see Vehicle has_many :issues), to keep their history def destroy - begin - Vehicle.find_by_id(params[:id]).destroy + if @vehicle.destroy flash[:notice] = t :notice_vehicle_deleted - redirect_to action: :index - rescue - flash[:error] = t :alert_vehicle_not_deleted - render_404 + redirect_to @vehicle.customer ? customer_path(@vehicle.customer) : vehicles_path + else + flash[:error] = t(:alert_vehicle_has_issues) + redirect_to @vehicle end end private - # checks to see if there is only one item in an array - # @return true if array only has one item - def only_one_non_zero?( array ) - found_non_zero = false - array.each do |val| - if val!=0 - return false if found_non_zero - found_non_zero = true - end - end - found_non_zero + def find_vehicle + @vehicle = Vehicle.find(params[:id]) + rescue ActiveRecord::RecordNotFound + render_404 end end diff --git a/app/jobs/vehicle_vin_decode_job.rb b/app/jobs/vehicle_vin_decode_job.rb index d88e0c1..787a60c 100644 --- a/app/jobs/vehicle_vin_decode_job.rb +++ b/app/jobs/vehicle_vin_decode_job.rb @@ -10,9 +10,16 @@ class VehicleVinDecodeJob < ApplicationJob queue_as :default - retry_on StandardError, wait: 5.minutes, attempts: 5 + # Network trouble is retried; if it never succeeds, the error is shown on the vehicle page + retry_on VinDecoder::TransientError, wait: 2.minutes, attempts: 5 do |job, error| + vehicle_id = job.arguments.first + vehicle_id = vehicle_id.id if vehicle_id.respond_to?(:id) + Vehicle.find_by(id: vehicle_id)&.update_columns(error: error.message.to_s.truncate(255), vin_decoded: false) + end - def perform(vehicle_id) + # Takes a vehicle id (jobs queued by older versions may pass the Vehicle itself, which still works) + def perform(vehicle_or_id) + vehicle_id = vehicle_or_id.respond_to?(:id) ? vehicle_or_id.id : vehicle_or_id log "Looking up VIN for vehicle ##{vehicle_id}" vehicle = Vehicle.find_by(id: vehicle_id) return unless vehicle&.vin.present? @@ -20,13 +27,13 @@ class VehicleVinDecodeJob < ApplicationJob unless result.success? log "Failed to decode vin" - vehicle.update(vin_decoded: false, error: result.error) + save_decode(vehicle, vin_decoded: false, error: result.error.to_s.truncate(255)) return end details = result.data - vehicle.update( + save_decode(vehicle, year: details.year.presence || vehicle.year, make: details.make.presence || vehicle.make, model: details.model.presence || vehicle.model, @@ -40,6 +47,13 @@ class VehicleVinDecodeJob < ApplicationJob private + # Saves decode results without validations: a vehicle whose customer was deleted in QuickBooks + # would otherwise fail "customer must exist" and lose its decoded details. + def save_decode(vehicle, attributes) + vehicle.assign_attributes(attributes) + vehicle.save(validate: false) + end + def build_name(vehicle, details) if details.year && details.make && details.model suffix = vehicle.vin.to_s[9..] diff --git a/app/models/vehicle.rb b/app/models/vehicle.rb index 5ece192..b5f1f1e 100644 --- a/app/models/vehicle.rb +++ b/app/models/vehicle.rb @@ -13,7 +13,9 @@ class Vehicle < ApplicationRecord include Redmine::Acts::Event belongs_to :customer - has_many :issues + # A vehicle with issues can't be deleted, so its service history is never lost. When a vehicle is + # sold, change its customer instead: past issues keep their original customer and stay on this vehicle. + has_many :issues, dependent: :restrict_with_error validates :customer, presence: true validates :vin, presence: true, uniqueness: true before_validation :normalize_vin @@ -33,21 +35,49 @@ class Vehicle < ApplicationRecord issues.includes(:invoices).flat_map(&:invoices).uniq.compact end + # The issue custom field holding mileage: the one chosen in the plugin settings, else one named "Mileage" + def self.mileage_custom_field + settings = Setting.plugin_redmine_qbo_vehicles || {} + chosen = settings['mileage_custom_field_id'].to_i + (IssueCustomField.find_by(id: chosen) if chosen.positive?) || IssueCustomField.find_by(name: 'Mileage') + end + + # The most recent issue for this vehicle with a mileage recorded def last_service - return issues + field = self.class.mileage_custom_field + return nil unless field + + issues .joins(:custom_values) - .where(custom_values: { custom_field_id: CustomField.find_by(name: "Mileage")&.id }) + .where(custom_values: { custom_field_id: field.id }) .where.not(custom_values: { value: ['', nil] }) .order(created_on: :desc) .first end + # { date:, mileage: } from the most recent issue with a mileage, or nil. One query, cached per vehicle. + def last_service_info + return @last_service_info if defined?(@last_service_info) + + field = self.class.mileage_custom_field + row = if field + issues + .joins(:custom_values) + .where(custom_values: { custom_field_id: field.id }) + .where.not(custom_values: { value: ['', nil] }) + .order(created_on: :desc) + .pick(:created_on, 'custom_values.value') + end + + @last_service_info = row && { date: row[0]&.to_date, mileage: row[1].presence } + end + def last_service_date - return last_service.created_on&.to_date + last_service_info&.dig(:date) end def last_service_mileage - return last_service&.custom_values&.find_by(custom_field_id: CustomField.find_by(name: "Mileage")&.id)&.value.presence + last_service_info&.dig(:mileage) end def make=(val) @@ -68,9 +98,19 @@ class Vehicle < ApplicationRecord nil end + # Vehicles matching one search term. A 4-digit term also matches the year exactly (comparing the + # numeric year with LIKE fails on PostgreSQL). The name column covers "2018 Jeep Wrangler - ..." text. def self.search(query) - q = "%#{sanitize_sql_like(query)}%" - where( "vin LIKE :q OR make LIKE :q OR model LIKE :q OR year LIKE :q", q: q) + term = query.to_s.strip + q = "%#{sanitize_sql_like(term)}%" + scope = where("vin LIKE :q OR make LIKE :q OR model LIKE :q OR name LIKE :q", q: q) + scope = scope.or(where(year: term.to_i)) if term.match?(/\A\d{4}\z/) + scope + end + + # Vehicles matching every word of the query, e.g. "2018 jeep wrangler" + def self.search_all(query) + query.to_s.split.reduce(all) { |scope, term| scope.where(id: search(term).select(:id)) } end # Override the defult redmine seach method to rank results by id diff --git a/app/services/vin_decoder.rb b/app/services/vin_decoder.rb index 7587d75..2e00c85 100644 --- a/app/services/vin_decoder.rb +++ b/app/services/vin_decoder.rb @@ -11,6 +11,10 @@ class VinDecoder Result = Struct.new(:success?, :data, :error) + # Raised when the lookup itself fails (network trouble, NHTSA down). Unlike an invalid VIN or "no match", + # this is worth retrying, so it's raised for the job to retry instead of being returned as a failure. + class TransientError < StandardError; end + def self.call(vin) new(vin).call end @@ -29,7 +33,8 @@ class VinDecoder success(query.response) rescue StandardError => e - failure(e.message) + log "VIN lookup error for #{@vin}: #{e.class}: #{e.message}" + raise TransientError, e.message end private diff --git a/app/views/customer_appointments/_show_hook.html.erb b/app/views/customer_appointments/_show_hook.html.erb index e112378..e8f3a97 100644 --- a/app/views/customer_appointments/_show_hook.html.erb +++ b/app/views/customer_appointments/_show_hook.html.erb @@ -1,6 +1,6 @@ <% if User.current.allowed_to?(:add_vehicles, nil, global: true) %> <% if appointment.customer.present? %> - <% unless appointment.vehicle.present? &&%> + <% unless appointment.vehicle.present? %>

<%= link_to new_vehicle_path(customer_id: appointment.customer_id), class: 'icon icon-add' do %> <%= l(:label_add_vehicle) %> diff --git a/app/views/customers/_show_hook.html.erb b/app/views/customers/_show_hook.html.erb index 15763cf..40ed8f8 100644 --- a/app/views/customers/_show_hook.html.erb +++ b/app/views/customers/_show_hook.html.erb @@ -1,7 +1,10 @@ +<% if User.current.allowed_to?(:view_vehicles, nil, global: true) %>

<%=t(:field_vehicles)%>:

-<%= render partial: 'vehicles/list', locals: { vehicles: customer.vehicles.paginate(page: params[:page]), show_customer: false, show_checkbox: true } %> +<%# Own page parameter so this list doesn't page together with the other lists on the customer page %> +<%= render partial: 'vehicles/list', locals: { vehicles: customer.vehicles.paginate(page: params[:vehicles_page]), show_customer: false, show_checkbox: true, page_param: :vehicles_page } %>
<% if User.current.allowed_to?(:add_vehicles, nil, global: true) %> <%= button_to t(:button_new_vehicle), new_customer_vehicle_path(customer), method: :get %> <% end %> -
\ No newline at end of file + +<% end %> \ No newline at end of file diff --git a/app/views/settings/_vehicles_settings.html.erb b/app/views/settings/_vehicles_settings.html.erb new file mode 100644 index 0000000..5883e17 --- /dev/null +++ b/app/views/settings/_vehicles_settings.html.erb @@ -0,0 +1,9 @@ +
+

+ + <%= select_tag 'settings[mileage_custom_field_id]', + options_from_collection_for_select(IssueCustomField.sorted, :id, :name, settings['mileage_custom_field_id'].to_i), + include_blank: true, id: 'settings_mileage_custom_field_id' %> + <%= l(:text_mileage_custom_field_info) %> +

+
diff --git a/app/views/vehicles/_details.html.erb b/app/views/vehicles/_details.html.erb index b89817a..c28f4f5 100644 --- a/app/views/vehicles/_details.html.erb +++ b/app/views/vehicles/_details.html.erb @@ -57,7 +57,8 @@ <% if User.current.allowed_to?(:edit_vehicles, nil, global: true) %> <%= button_to t(:label_edit), edit_vehicle_path(vehicle), method: :get %> <% end %> - <% if User.current.allowed_to?(:delete_vehicles, nil, global: true) %> + <%# Vehicles with issues can't be deleted, to keep their service history %> + <% if User.current.allowed_to?(:delete_vehicles, nil, global: true) && !vehicle.issues.exists? %> <%= button_to t(:label_delete), vehicle, method: :delete, data: { confirm: t(:warn_ru_sure) } %> <% end %> \ No newline at end of file diff --git a/app/views/vehicles/_form.html.erb b/app/views/vehicles/_form.html.erb index 1cb4e54..2bb9784 100644 --- a/app/views/vehicles/_form.html.erb +++ b/app/views/vehicles/_form.html.erb @@ -3,11 +3,20 @@
<%= form_for @vehicle do |f| %> + <%= error_messages_for 'vehicle' %> + + <% if @existing_vehicle %> +

+ <%= l(:text_vin_already_on_file) %> + <%= link_to @existing_vehicle.to_s, vehicle_path(@existing_vehicle) %> +

+ <% end %> +
<%=t(:field_customer)%>:
- <%= f.text_field :customer, class: "customer-name", autocomplete: "off", value: @customer.name, required: true,data: { autocomplete_url: "/customers/autocomplete" } %> - <%= f.hidden_field :customer_id, id: "customer_id", value: @customer.id %> + <%= f.text_field :customer, class: "customer-name", autocomplete: "off", value: @vehicle.customer&.name, required: true,data: { autocomplete_url: "/customers/autocomplete" } %> + <%= f.hidden_field :customer_id, id: "customer_id" %>
@@ -47,8 +56,8 @@ rows: 8, class: 'wiki-edit', style: 'width: 95%;', - id: 'customer_appointment_description' %> - <%= wikitoolbar_for 'customer_appointment_description' %> + id: 'vehicle_notes' %> + <%= wikitoolbar_for 'vehicle_notes' %>

diff --git a/app/views/vehicles/_list.html.erb b/app/views/vehicles/_list.html.erb index 5ffad43..b421dad 100644 --- a/app/views/vehicles/_list.html.erb +++ b/app/views/vehicles/_list.html.erb @@ -41,10 +41,10 @@ <% end %>
- <%= will_paginate vehicles %> + <%= will_paginate vehicles, param_name: (local_assigns[:page_param] || :page) %>
-<%=t(:label_matching)%> <%=vehicles.count%> <%=t(:field_vehicles) %> +<%=t(:label_matching)%> <%= vehicles.respond_to?(:total_entries) ? vehicles.total_entries : vehicles.size %> <%=t(:field_vehicles) %> <% else %>

<%=t(:label_no_vehicles)%> <%= params[:search] %>.

diff --git a/app/views/vehicles/edit.html.erb b/app/views/vehicles/edit.html.erb index e27b1d1..7803874 100644 --- a/app/views/vehicles/edit.html.erb +++ b/app/views/vehicles/edit.html.erb @@ -1,3 +1,3 @@ -

<%=t(:label_edit_customer_vehicle)%>

+

<%=t(:label_edit_customer_vehicle)%>


<%= render partial: 'vehicles/form' %> diff --git a/app/views/vehicles/show.html.erb b/app/views/vehicles/show.html.erb index 146f145..3102005 100644 --- a/app/views/vehicles/show.html.erb +++ b/app/views/vehicles/show.html.erb @@ -14,7 +14,7 @@
-

<%=t(:estimates)%>:

+

<%=t(:label_estimates)%>:

<%= render partial: 'estimates/list', locals: {estimates: @vehicle.estimates} %>
@@ -34,7 +34,9 @@