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) %>
+ + <%= 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) %> +
+