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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BiwYMjhoQvL7XsKKfRz4pM
This commit is contained in:
Claude committed 2026-10-28 23:04:46 -04:00
1 parent b021ca9f7d
commit 0a3c73482a
18 files changed
+268 -130

No files matched your search

+56 -92
View File
@@ -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
+18 -4
View File
@@ -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..]
+47 -7
View File
@@ -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
+6 -1
View File
@@ -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
@@ -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? %>
<p>
<%= link_to new_vehicle_path(customer_id: appointment.customer_id), class: 'icon icon-add' do %>
<%= l(:label_add_vehicle) %>
+5 -2
View File
@@ -1,7 +1,10 @@
<% if User.current.allowed_to?(:view_vehicles, nil, global: true) %>
<h4><%=t(:field_vehicles)%>:</h4>
<%= 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 } %>
<div style="float: right;">
<% if User.current.allowed_to?(:add_vehicles, nil, global: true) %>
<%= button_to t(:button_new_vehicle), new_customer_vehicle_path(customer), method: :get %>
<% end %>
</div>
</div>
<% end %>
@@ -0,0 +1,9 @@
<div class="box tabular">
<p>
<label for="settings_mileage_custom_field_id"><%= l(:label_mileage_custom_field) %></label>
<%= 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' %>
<em class="info"><%= l(:text_mileage_custom_field_info) %></em>
</p>
</div>
+2 -1
View File
@@ -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 %>
</div>
+13 -4
View File
@@ -3,11 +3,20 @@
<fieldset>
<%= form_for @vehicle do |f| %>
<%= error_messages_for 'vehicle' %>
<% if @existing_vehicle %>
<p class="flash warning">
<%= l(:text_vin_already_on_file) %>
<%= link_to @existing_vehicle.to_s, vehicle_path(@existing_vehicle) %>
</p>
<% end %>
<div class="clearfix">
<%=t(:field_customer)%>:
<div class="input">
<%= 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" %>
</div>
</div>
@@ -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' %>
</p>
</div>
</div>
+2 -2
View File
@@ -41,10 +41,10 @@
<% end %>
<div class="actions">
<%= will_paginate vehicles %>
<%= will_paginate vehicles, param_name: (local_assigns[:page_param] || :page) %>
</div>
<%=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 %>
<p><%=t(:label_no_vehicles)%> <%= params[:search] %>.</p>
+1 -1
View File
@@ -1,3 +1,3 @@
<h1><%=t(:label_edit_customer_vehicle)%></h1>
<h2><%=t(:label_edit_customer_vehicle)%></h2>
<br/>
<%= render partial: 'vehicles/form' %>
+13 -7
View File
@@ -14,7 +14,7 @@
<div class="splitcontent">
<div class="splitcontentleft">
<h4><%=t(:estimates)%>:</h4>
<h4><%=t(:label_estimates)%>:</h4>
<%= render partial: 'estimates/list', locals: {estimates: @vehicle.estimates} %>
</div>
@@ -34,7 +34,9 @@
<script>
(function() {
const vehicleId = <%= @vehicle.id %>;
const statusUrl = <%= raw status_vehicle_path(@vehicle).to_json %>;
const timedOutMessage = <%= raw l(:notice_vin_decode_timed_out).to_json %>;
const checkFailedMessage = <%= raw l(:error_vin_status_check_failed).to_json %>;
const alreadyDecoded = <%= @vehicle.vin_decoded? ? 'true' : 'false' %>;
if (alreadyDecoded) return;
@@ -46,10 +48,14 @@
const statusEl = document.getElementById("vin-status");
const checkStatus = () => {
fetch(`/vehicles/${vehicleId}/status`, {
headers: { 'Accept': 'application/json' }
fetch(statusUrl, {
headers: { 'Accept': 'application/json' },
credentials: 'same-origin'
})
.then(res => res.json())
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(data => {
// SUCCESS → reload
@@ -80,7 +86,7 @@
if (statusEl) {
statusEl.classList.remove("notice");
statusEl.classList.add("warning");
statusEl.textContent = "VIN decode timed out. Please refresh or try again.";
statusEl.textContent = timedOutMessage;
}
console.warn("VIN decode polling timed out");
@@ -92,7 +98,7 @@
if (statusEl) {
statusEl.classList.remove("notice");
statusEl.classList.add("error");
statusEl.textContent = "Error checking VIN status.";
statusEl.textContent = checkFailedMessage;
}
console.error("Polling error:", err);