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
+258 -120

No files matched your search

+48 -84
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. #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 class VehiclesController < ApplicationController
include AuthHelper # Checks the vehicle permissions declared in init.rb (also requires login)
# This tells Redmine to check global permissions for the current controller/action
before_action :authorize_global 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 def allowed_params
params.require(:vehicle).permit(:year, :make, :model, :customer_id, :notes, :vin) params.require(:vehicle).permit(:year, :make, :model, :customer_id, :notes, :vin)
end end
# display a list of all vehicles # Vehicles for one customer (also as JSON for the issue form), or search results
def index def index
if params[:customer_id] if params[:customer_id].present?
begin @customer = Customer.find_by(id: params[:customer_id])
@vehicles = Customer.find_by_id(params[:customer_id]).vehicles.paginate(page: params[:page]) return render_404 unless @customer
rescue ActiveRecord::RecordNotFound
flash[:error] = t :alert_vehicle_not_found vehicles = @customer.vehicles.order(:year, :make, :model)
render_404 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
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
end end
# search for a vehicle by vin # Form for a new vehicle, pre-filled with the customer when coming from a customer or appointment
if params[:search]
@vehicles = Vehicle.search(params[:search]).paginate(page: params[:page])
if only_one_non_zero?(@vehicles)
redirect_to @vehicles.first
end
end
end
# return an HTML form for creating a new vehicle
def new def new
@vehicle = Vehicle.new @vehicle = Vehicle.new(customer: Customer.find_by(id: params[:customer_id]))
@customer = Customer.find_by_id(params[:customer_id]) if params[:customer_id]
end end
# create a new vehicle
def create def create
@vehicle = Vehicle.new(allowed_params) @vehicle = Vehicle.new(allowed_params)
if @vehicle.save if @vehicle.save
flash[:notice] = t :notice_vehicle_created flash[:notice] = t :notice_vehicle_created
redirect_to @vehicle redirect_to @vehicle
else else
flash[:error] = @vehicle.errors.full_messages.to_sentence # A duplicate VIN: point to the vehicle that already has it
redirect_to Vehicle.find_by_vin @vehicle.vin @existing_vehicle = Vehicle.find_by(vin: @vehicle.vin) if @vehicle.errors.of_kind?(:vin, :taken)
render :new, status: :unprocessable_entity
end end
end end
# display a specific vehicle
def show def show
begin
@vehicle = Vehicle.includes(issues: [:estimate, :invoices]).find(params[:id])
@vin = @vehicle.vin.scan(/.{1,9}/) if @vehicle.vin @vin = @vehicle.vin.scan(/.{1,9}/) if @vehicle.vin
@issues = @vehicle.issues @issues = @vehicle.issues
.joins(:status) .joins(:status)
.includes(:estimate, :invoices, :status, :project, :tracker, :priority) .includes(:estimate, :invoices, :status, :project, :tracker, :priority)
.order(id: :desc) .order(id: :desc)
@open_issues = @issues.select { |i| !i.status.is_closed } @open_issues = @issues.reject { |i| i.status.is_closed }
@closed_issues = @issues.select { |i| i.status.is_closed } @closed_issues = @issues.select { |i| i.status.is_closed }
flash[:error] = t :alert_no_customer if @vehicle.customer.nil? flash.now[:error] = t :alert_no_customer if @vehicle.customer.nil?
rescue
flash[:error] = t :alert_vehicle_not_found
render_404
end
end 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 def status
vehicle = Vehicle.find(params[:id]) # 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?
# decode the vin if it hasn't been done for some reason key = "redmine_qbo_vehicles/vin_decode_requested/#{@vehicle.id}"
unless vehicle.vin_decoded unless Rails.cache.exist?(key)
if vehicle.error.nil? Rails.cache.write(key, true, expires_in: DECODE_REQUEST_THROTTLE)
VehicleVinDecodeJob.perform_later(vehicle) VehicleVinDecodeJob.perform_later(@vehicle.id)
end end
end end
render json: { render json: { decoded: @vehicle.vin_decoded, error: @vehicle.error }
decoded: vehicle.vin_decoded,
error: vehicle.error
}
end end
# return an HTML form for editing a vehicle
def edit 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 end
# update a specific vehicle
def update def update
@customer = params[:customer]
begin
@vehicle = Vehicle.find_by_id(params[:id])
if @vehicle.update(allowed_params) if @vehicle.update(allowed_params)
flash[:notice] = t :notice_vehicle_updated flash[:notice] = t :notice_vehicle_updated
redirect_to @vehicle redirect_to @vehicle
else else
redirect_to edit_vehicle_path render :edit, status: :unprocessable_entity
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
end end
end end
# delete a specific vehicle # Vehicles with issues can't be deleted (see Vehicle has_many :issues), to keep their history
def destroy def destroy
begin if @vehicle.destroy
Vehicle.find_by_id(params[:id]).destroy
flash[:notice] = t :notice_vehicle_deleted flash[:notice] = t :notice_vehicle_deleted
redirect_to action: :index redirect_to @vehicle.customer ? customer_path(@vehicle.customer) : vehicles_path
rescue else
flash[:error] = t :alert_vehicle_not_deleted flash[:error] = t(:alert_vehicle_has_issues)
render_404 redirect_to @vehicle
end end
end end
private private
# checks to see if there is only one item in an array def find_vehicle
# @return true if array only has one item @vehicle = Vehicle.find(params[:id])
def only_one_non_zero?( array ) rescue ActiveRecord::RecordNotFound
found_non_zero = false render_404
array.each do |val|
if val!=0
return false if found_non_zero
found_non_zero = true
end
end
found_non_zero
end end
end end
+18 -4
View File
@@ -10,9 +10,16 @@
class VehicleVinDecodeJob < ApplicationJob class VehicleVinDecodeJob < ApplicationJob
queue_as :default 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}" log "Looking up VIN for vehicle ##{vehicle_id}"
vehicle = Vehicle.find_by(id: vehicle_id) vehicle = Vehicle.find_by(id: vehicle_id)
return unless vehicle&.vin.present? return unless vehicle&.vin.present?
@@ -20,13 +27,13 @@ class VehicleVinDecodeJob < ApplicationJob
unless result.success? unless result.success?
log "Failed to decode vin" 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 return
end end
details = result.data details = result.data
vehicle.update( save_decode(vehicle,
year: details.year.presence || vehicle.year, year: details.year.presence || vehicle.year,
make: details.make.presence || vehicle.make, make: details.make.presence || vehicle.make,
model: details.model.presence || vehicle.model, model: details.model.presence || vehicle.model,
@@ -40,6 +47,13 @@ class VehicleVinDecodeJob < ApplicationJob
private 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) def build_name(vehicle, details)
if details.year && details.make && details.model if details.year && details.make && details.model
suffix = vehicle.vin.to_s[9..] suffix = vehicle.vin.to_s[9..]
+47 -7
View File
@@ -13,7 +13,9 @@ class Vehicle < ApplicationRecord
include Redmine::Acts::Event include Redmine::Acts::Event
belongs_to :customer 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 :customer, presence: true
validates :vin, presence: true, uniqueness: true validates :vin, presence: true, uniqueness: true
before_validation :normalize_vin before_validation :normalize_vin
@@ -33,21 +35,49 @@ class Vehicle < ApplicationRecord
issues.includes(:invoices).flat_map(&:invoices).uniq.compact issues.includes(:invoices).flat_map(&:invoices).uniq.compact
end 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 def last_service
return issues field = self.class.mileage_custom_field
return nil unless field
issues
.joins(:custom_values) .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] }) .where.not(custom_values: { value: ['', nil] })
.order(created_on: :desc) .order(created_on: :desc)
.first .first
end 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 def last_service_date
return last_service.created_on&.to_date last_service_info&.dig(:date)
end end
def last_service_mileage 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 end
def make=(val) def make=(val)
@@ -68,9 +98,19 @@ class Vehicle < ApplicationRecord
nil nil
end 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) def self.search(query)
q = "%#{sanitize_sql_like(query)}%" term = query.to_s.strip
where( "vin LIKE :q OR make LIKE :q OR model LIKE :q OR year LIKE :q", q: q) 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 end
# Override the defult redmine seach method to rank results by id # Override the defult redmine seach method to rank results by id
+6 -1
View File
@@ -11,6 +11,10 @@
class VinDecoder class VinDecoder
Result = Struct.new(:success?, :data, :error) 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) def self.call(vin)
new(vin).call new(vin).call
end end
@@ -29,7 +33,8 @@ class VinDecoder
success(query.response) success(query.response)
rescue StandardError => e rescue StandardError => e
failure(e.message) log "VIN lookup error for #{@vin}: #{e.class}: #{e.message}"
raise TransientError, e.message
end end
private private
@@ -1,6 +1,6 @@
<% if User.current.allowed_to?(:add_vehicles, nil, global: true) %> <% if User.current.allowed_to?(:add_vehicles, nil, global: true) %>
<% if appointment.customer.present? %> <% if appointment.customer.present? %>
<% unless appointment.vehicle.present? &&%> <% unless appointment.vehicle.present? %>
<p> <p>
<%= link_to new_vehicle_path(customer_id: appointment.customer_id), class: 'icon icon-add' do %> <%= link_to new_vehicle_path(customer_id: appointment.customer_id), class: 'icon icon-add' do %>
<%= l(:label_add_vehicle) %> <%= l(:label_add_vehicle) %>
+4 -1
View File
@@ -1,7 +1,10 @@
<% if User.current.allowed_to?(:view_vehicles, nil, global: true) %>
<h4><%=t(:field_vehicles)%>:</h4> <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;"> <div style="float: right;">
<% if User.current.allowed_to?(:add_vehicles, nil, global: true) %> <% if User.current.allowed_to?(:add_vehicles, nil, global: true) %>
<%= button_to t(:button_new_vehicle), new_customer_vehicle_path(customer), method: :get %> <%= button_to t(:button_new_vehicle), new_customer_vehicle_path(customer), method: :get %>
<% end %> <% 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) %> <% if User.current.allowed_to?(:edit_vehicles, nil, global: true) %>
<%= button_to t(:label_edit), edit_vehicle_path(vehicle), method: :get %> <%= button_to t(:label_edit), edit_vehicle_path(vehicle), method: :get %>
<% end %> <% 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) } %> <%= button_to t(:label_delete), vehicle, method: :delete, data: { confirm: t(:warn_ru_sure) } %>
<% end %> <% end %>
</div> </div>
+13 -4
View File
@@ -3,11 +3,20 @@
<fieldset> <fieldset>
<%= form_for @vehicle do |f| %> <%= 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"> <div class="clearfix">
<%=t(:field_customer)%>: <%=t(:field_customer)%>:
<div class="input"> <div class="input">
<%= f.text_field :customer, class: "customer-name", autocomplete: "off", value: @customer.name, required: true,data: { autocomplete_url: "/customers/autocomplete" } %> <%= 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", value: @customer.id %> <%= f.hidden_field :customer_id, id: "customer_id" %>
</div> </div>
</div> </div>
@@ -47,8 +56,8 @@
rows: 8, rows: 8,
class: 'wiki-edit', class: 'wiki-edit',
style: 'width: 95%;', style: 'width: 95%;',
id: 'customer_appointment_description' %> id: 'vehicle_notes' %>
<%= wikitoolbar_for 'customer_appointment_description' %> <%= wikitoolbar_for 'vehicle_notes' %>
</p> </p>
</div> </div>
</div> </div>
+2 -2
View File
@@ -41,10 +41,10 @@
<% end %> <% end %>
<div class="actions"> <div class="actions">
<%= will_paginate vehicles %> <%= will_paginate vehicles, param_name: (local_assigns[:page_param] || :page) %>
</div> </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 %> <% else %>
<p><%=t(:label_no_vehicles)%> <%= params[:search] %>.</p> <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/> <br/>
<%= render partial: 'vehicles/form' %> <%= render partial: 'vehicles/form' %>
+13 -7
View File
@@ -14,7 +14,7 @@
<div class="splitcontent"> <div class="splitcontent">
<div class="splitcontentleft"> <div class="splitcontentleft">
<h4><%=t(:estimates)%>:</h4> <h4><%=t(:label_estimates)%>:</h4>
<%= render partial: 'estimates/list', locals: {estimates: @vehicle.estimates} %> <%= render partial: 'estimates/list', locals: {estimates: @vehicle.estimates} %>
</div> </div>
@@ -34,7 +34,9 @@
<script> <script>
(function() { (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' %>; const alreadyDecoded = <%= @vehicle.vin_decoded? ? 'true' : 'false' %>;
if (alreadyDecoded) return; if (alreadyDecoded) return;
@@ -46,10 +48,14 @@
const statusEl = document.getElementById("vin-status"); const statusEl = document.getElementById("vin-status");
const checkStatus = () => { const checkStatus = () => {
fetch(`/vehicles/${vehicleId}/status`, { fetch(statusUrl, {
headers: { 'Accept': 'application/json' } headers: { 'Accept': 'application/json' },
credentials: 'same-origin'
})
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
}) })
.then(res => res.json())
.then(data => { .then(data => {
// SUCCESS → reload // SUCCESS → reload
@@ -80,7 +86,7 @@
if (statusEl) { if (statusEl) {
statusEl.classList.remove("notice"); statusEl.classList.remove("notice");
statusEl.classList.add("warning"); 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"); console.warn("VIN decode polling timed out");
@@ -92,7 +98,7 @@
if (statusEl) { if (statusEl) {
statusEl.classList.remove("notice"); statusEl.classList.remove("notice");
statusEl.classList.add("error"); statusEl.classList.add("error");
statusEl.textContent = "Error checking VIN status."; statusEl.textContent = checkFailedMessage;
} }
console.error("Polling error:", err); console.error("Polling error:", err);
+42
View File
@@ -0,0 +1,42 @@
//The MIT License (MIT)
//
//Copyright (c) 2016 - 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.
// Refreshes the issue form's vehicle list when the customer changes, so only that customer's vehicles
// can be picked. redmine_qbo's customer autocomplete fires "change" on #customer_id through jQuery,
// so this listens with jQuery too.
(function ($) {
if (!$) return;
$(document).on('change', '#customer_id', function () {
var select = document.getElementById('issue_vehicle_id');
if (!select || !select.dataset.vehiclesUrl) return;
var customerId = this.value;
var previous = select.value;
function fill(vehicles) {
select.innerHTML = '';
select.appendChild(new Option('', ''));
vehicles.forEach(function (v) { select.appendChild(new Option(v.name, v.id)); });
if (vehicles.some(function (v) { return String(v.id) === previous; })) select.value = previous;
}
if (!customerId) { fill([]); return; }
// No ".json" in the URL: Redmine treats those as API requests and ignores the browser session
fetch(select.dataset.vehiclesUrl.replace('__CUSTOMER_ID__', encodeURIComponent(customerId)), {
headers: { 'Accept': 'application/json' },
credentials: 'same-origin'
})
.then(function (res) { return res.ok ? res.json() : null; })
.then(function (vehicles) { if (vehicles) fill(vehicles); }) // on failure, leave the list alone
.catch(function (err) { console.warn('Could not load vehicles', err); });
});
})(window.jQuery);
+19
View File
@@ -40,3 +40,22 @@ en:
notice_vehicle_created: "Vehicle was successfully created." notice_vehicle_created: "Vehicle was successfully created."
notice_vehicle_deleted: "Vehicle was successfully deleted." notice_vehicle_deleted: "Vehicle was successfully deleted."
notice_vehicle_updated: "Vehicle was successfully updated." notice_vehicle_updated: "Vehicle was successfully updated."
# Vehicle labels previously only defined in redmine_qbo
field_customer: "Customer"
label_delete: "Delete"
label_door: "Door"
label_estimates: "Estimates"
label_invoices: "Invoices"
label_matching: "Matching"
label_trim: "Trim"
warn_ru_sure: "Are you sure?"
alert_vehicle_has_issues: "This vehicle has issues, so it can't be deleted (that would lose its service history). If it was sold, change its customer instead."
error_vehicle_customer_mismatch: "Vehicle %{vehicle} belongs to a different customer. Pick one of this customer's vehicles."
error_vehicle_not_found_for_issue: "The selected vehicle no longer exists."
error_vin_status_check_failed: "Error checking VIN status."
label_mileage_custom_field: "Mileage field"
notice_vin_decode_timed_out: "VIN decode timed out. Please refresh or try again."
text_mileage_custom_field_info: "Issue custom field used for \"Last serviced\" mileage. Leave blank to use a field named Mileage."
text_vin_already_on_file: "A vehicle with this VIN is already on file:"
+5 -1
View File
@@ -26,11 +26,15 @@ Redmine::Plugin.register :redmine_qbo_vehicles do
raise 'Please install the redmine_qbo plugin (https://github.com/rickbarrette/redmine_qbo)' raise 'Please install the redmine_qbo plugin (https://github.com/rickbarrette/redmine_qbo)'
end end
# Which issue custom field holds the mileage shown as "Last serviced" (blank: a field named "Mileage")
settings default: { 'mileage_custom_field_id' => '' }, partial: 'settings/vehicles_settings'
# Add safe attributes for core models # Add safe attributes for core models
Issue.safe_attributes :vehicle_id Issue.safe_attributes :vehicle_id
# Global Permissions # Global Permissions
permission :view_vehicles, { vehicles: [:index, :show] }, global: true # status: VIN decode progress, polled by the vehicle page
permission :view_vehicles, { vehicles: [:index, :show, :status] }, global: true
permission :add_vehicles, { vehicles: [:new, :create] }, global: true permission :add_vehicles, { vehicles: [:new, :create] }, global: true
permission :edit_vehicles, { vehicles: [:edit, :update] }, global: true permission :edit_vehicles, { vehicles: [:edit, :update] }, global: true
permission :delete_vehicles, { vehicles: [:destroy] }, global: true permission :delete_vehicles, { vehicles: [:destroy] }, global: true
@@ -17,8 +17,12 @@ module Vehicles
def view_issues_form_details_bottom(context={}) def view_issues_form_details_bottom(context={})
# Load the customer's vehicles for selection in the issue form. # Load the customer's vehicles for selection in the issue form. The vehicle already on the issue is
vehicles = context[:issue].customer&.vehicles || [] # always included: after a vehicle is sold it belongs to another customer, and leaving it out
# would blank it on the next save, dropping the issue from that vehicle's history.
issue = context[:issue]
vehicles = (issue.customer&.vehicles.to_a || [])
vehicles |= [issue.vehicle] if issue.vehicle
context[:controller].send(:render_to_string, { context[:controller].send(:render_to_string, {
partial: 'issues/form_hook_vehicles', partial: 'issues/form_hook_vehicles',
@@ -26,8 +30,9 @@ module Vehicles
vehicle: context[:form].select( vehicle: context[:form].select(
:vehicle_id, :vehicle_id,
vehicles.map { |v| [v.name, v.id] }, vehicles.map { |v| [v.name, v.id] },
selected: context[:issue].vehicle&.id, { selected: context[:issue].vehicle&.id, include_blank: true },
include_blank: true # vehicles.js swaps in the customer id and reloads this list when the customer changes
{ data: { vehicles_url: customer_vehicles_path('__CUSTOMER_ID__') } }
) )
} }
}) })
+2 -1
View File
@@ -15,7 +15,8 @@ module Vehicles
def view_layouts_base_html_head(context = {}) def view_layouts_base_html_head(context = {})
safe_join([ safe_join([
stylesheet_link_tag('style', plugin: :redmine_qbo_vehicles, media: :all), stylesheet_link_tag('style', plugin: :redmine_qbo_vehicles, media: :all),
javascript_include_tag('copy', plugin: :redmine_qbo_vehicles) javascript_include_tag('copy', plugin: :redmine_qbo_vehicles),
javascript_include_tag('vehicles', plugin: :redmine_qbo_vehicles)
]) ])
end end
+17 -1
View File
@@ -17,7 +17,23 @@ module Vehicles
extend ActiveSupport::Concern extend ActiveSupport::Concern
prepended do prepended do
belongs_to :vehicle belongs_to :vehicle, optional: true
# The vehicle must belong to the issue's customer. Only checked when either changes, so older
# issues with a mismatch don't block unrelated edits.
validate :vehicle_matches_customer, if: -> { will_save_change_to_vehicle_id? || will_save_change_to_customer_id? }
end
private
def vehicle_matches_customer
return if vehicle_id.blank?
if vehicle.nil?
errors.add(:base, ::I18n.t(:error_vehicle_not_found_for_issue))
elsif customer_id.present? && vehicle.customer_id != customer_id
errors.add(:base, ::I18n.t(:error_vehicle_customer_mismatch, vehicle: vehicle.to_s))
end
end end
end end