5 Commits

Author SHA1 Message Date
bionickatana 23d8154f17 working on image feature 2026-10-01 09:56:32 -06:00
bionickatana 7d4e446d4a Finished instructions on building the application
CI / scan_ruby (push) Failing after 8s
CI / scan_js (push) Failing after 7s
CI / lint (push) Failing after 9s
2026-09-28 10:36:37 -06:00
bionickatana 393c7c50ae Added docker compose file
CI / scan_ruby (push) Failing after 7s
CI / scan_js (push) Failing after 6s
CI / lint (push) Failing after 9s
2026-09-28 10:35:01 -06:00
bionickatana 15a8d9e6f0 Merge pull request 'added backup/restore feature' (#1) from feature_backup-restore into main
CI / scan_ruby (push) Failing after 7s
CI / scan_js (push) Failing after 7s
CI / lint (push) Failing after 9s
Reviewed-on: #1
2026-09-28 10:02:25 -06:00
bionickatana d535c57347 added backup/restore feature
CI / scan_ruby (pull_request) Failing after 11s
CI / scan_js (pull_request) Failing after 7s
CI / lint (pull_request) Failing after 10s
2026-09-28 09:46:35 -06:00
32 changed files with 2030 additions and 17 deletions
+10 -3
View File
@@ -8,6 +8,8 @@ on:
jobs: jobs:
scan_ruby: scan_ruby:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: ruby:4.0.6-bullseye
steps: steps:
- name: Checkout code - name: Checkout code
@@ -20,12 +22,15 @@ jobs:
- name: Scan for common Rails security vulnerabilities using static analysis - name: Scan for common Rails security vulnerabilities using static analysis
run: bin/brakeman --no-pager run: bin/brakeman --no-pager
- name: Scan for known security vulnerabilities in gems used - name: Scan for known security vulnerabilities in gems used
run: bin/bundler-audit run: bin/bundler-audit
scan_js: scan_js:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: ruby:4.0.6-bullseye
steps: steps:
- name: Checkout code - name: Checkout code
@@ -41,6 +46,9 @@ jobs:
lint: lint:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container:
image: ruby:4.0.6-bullseye
env: env:
RUBOCOP_CACHE_ROOT: tmp/rubocop RUBOCOP_CACHE_ROOT: tmp/rubocop
steps: steps:
@@ -64,4 +72,3 @@ jobs:
- name: Lint code for consistent style - name: Lint code for consistent style
run: bin/rubocop -f github run: bin/rubocop -f github
+4
View File
@@ -33,3 +33,7 @@
# Ignore key files for decrypting credentials and more. # Ignore key files for decrypting credentials and more.
/config/*.key /config/*.key
# Ignore emacs backups
*.#
*#
+10
View File
@@ -0,0 +1,10 @@
# Directions to get a running docker image
Clone the repo using `git clone ssh://git@git.hintonclan.org:222/bionickatana/car-tracker.git`
Change directory into repo `cd car-tracker`
Run the docker build `docker compose build`
Start the server using compose: `docker compose up -d`
+54
View File
@@ -140,6 +140,12 @@ body > header .button_to,
color: var(--color-danger); color: var(--color-danger);
} }
.button--small {
min-block-size: 2rem;
padding: 0.35rem 0.65rem;
font-size: 0.88rem;
}
.back-link { .back-link {
font-weight: 700; font-weight: 700;
text-decoration: none; text-decoration: none;
@@ -437,6 +443,54 @@ textarea {
color: var(--color-danger); color: var(--color-danger);
} }
.form-errors--compact {
padding: 0.5rem 0.75rem;
}
.form-errors--compact ul {
margin-block: 0;
padding-inline-start: 1.1rem;
}
.entry-image-form {
display: grid;
gap: 0.75rem;
min-inline-size: min(18rem, 100%);
}
.entry-images {
display: flex;
flex-wrap: wrap;
gap: 0.75rem;
min-inline-size: 14rem;
}
.entry-image {
display: grid;
gap: 0.35rem;
inline-size: 8.5rem;
margin: 0;
}
.entry-image__thumbnail {
display: block;
inline-size: 7.5rem;
block-size: 7.5rem;
border: 1px solid var(--color-border);
border-radius: var(--radius-sm);
object-fit: cover;
}
.entry-image figcaption {
overflow-wrap: anywhere;
color: var(--color-muted);
font-size: 0.78rem;
}
.entry-images__actions {
margin-block: 0.75rem 0;
}
@media (max-width: 720px) { @media (max-width: 720px) {
body > header { body > header {
font-size: 0.9rem; font-size: 0.9rem;
+53
View File
@@ -0,0 +1,53 @@
require "stringio"
require "zlib"
class BackupsController < ApplicationController
def show
end
def download
send_backup(BackupExport.call(include_images: false), "car-tracker-backup")
end
def download_with_images
send_backup(BackupExport.call(include_images: true), "car-tracker-backup-with-images")
end
def restore
BackupImport.call(gunzip(uploaded_backup.read), mode: params[:mode])
redirect_to backup_path, notice: "Backup restored."
rescue BackupImport::Error, Zlib::GzipFile::Error => error
redirect_to backup_path, alert: "Backup could not be restored: #{restore_error_message(error)}"
end
private
def send_backup(content, basename)
send_data gzip(content),
filename: "#{basename}-#{Time.current.strftime('%Y%m%d%H%M%S')}.yml.gz",
type: "application/gzip",
disposition: "attachment"
end
def uploaded_backup
params.fetch(:backup_file)
rescue KeyError
raise BackupImport::Error, "Choose a backup file to restore."
end
def gzip(content)
buffer = StringIO.new
Zlib::GzipWriter.wrap(buffer) { |gzip| gzip.write(content) }
buffer.string
end
def gunzip(content)
Zlib::GzipReader.wrap(StringIO.new(content), &:read)
rescue Zlib::GzipFile::Error
raise BackupImport::Error, "Backup file must be a gzip-compressed YAML file."
end
def restore_error_message(error)
error.message.presence || "unknown error"
end
end
+88 -3
View File
@@ -1,4 +1,28 @@
require "digest/md5"
class FuelEntriesController < ApplicationController class FuelEntriesController < ApplicationController
def images
@vehicle = Vehicle.find(params[:vehicle_id])
@fuel_entry = @vehicle.fuel_entries.with_attached_images.find(params[:id])
if request.post?
attach_images(@fuel_entry)
return
end
render_images(@fuel_entry)
end
def new_images
@vehicle = Vehicle.find(params[:vehicle_id])
@fuel_entry = @vehicle.fuel_entries.find(params[:id])
render partial: "entry_images/form", locals: {
entry: @fuel_entry,
upload_path: images_vehicle_fuel_entry_path(@vehicle, @fuel_entry)
}
end
def create def create
@vehicle = Vehicle.find(params[:vehicle_id]) @vehicle = Vehicle.find(params[:vehicle_id])
@fuel_entry = @vehicle.fuel_entries.build(fuel_entry_params) @fuel_entry = @vehicle.fuel_entries.build(fuel_entry_params)
@@ -15,7 +39,68 @@ class FuelEntriesController < ApplicationController
private private
def fuel_entry_params def fuel_entry_params
params.require(:fuel_entry).permit(:odometer, :gallons_pumped, :price_paid, :date) params.require(:fuel_entry).permit(:odometer, :gallons_pumped, :price_paid, :date, images: [])
end
def image_params
params.require(:fuel_entry).permit(images: [])
end
def attach_images(entry)
uploads = Array(image_params[:images]).reject(&:blank?)
if uploads.empty?
entry.errors.add(:images, "must be selected")
render_image_form(entry, status: :unprocessable_entity)
return
end
validate_image_uploads(entry, uploads)
if entry.errors[:images].any? || entry.errors[:base].any?
render_image_form(entry, status: :unprocessable_entity)
else
entry.images.attach(uploads)
entry.save!(validate: false)
entry.images.reload
render_images(entry)
end
end
def validate_image_uploads(entry, uploads)
checksums = []
uploads.each do |upload|
entry.errors.add(:images, "must be 10 MB or smaller") if upload.size > EntryImageValidation::MAX_IMAGE_SIZE
entry.errors.add(:images, "must be JPEG or PNG") unless EntryImageValidation::ALLOWED_IMAGE_CONTENT_TYPES.include?(upload.content_type)
checksums << upload_checksum(upload)
end
existing_checksums = entry.images.map(&:checksum)
duplicate_existing = (checksums & existing_checksums).any?
duplicate_new = checksums.tally.any? { |_checksum, count| count > 1 }
return unless duplicate_existing || duplicate_new
entry.errors.add(:base, "This image is already attached to this entry")
end
def upload_checksum(upload)
Digest::MD5.base64digest(upload.read).tap do
upload.rewind
end
end
def render_image_form(entry, status: :ok)
render partial: "entry_images/form", formats: :html, locals: {
entry: entry,
upload_path: images_vehicle_fuel_entry_path(@vehicle, entry)
}, status: status
end
def render_images(entry)
render partial: "entry_images/images", formats: :html, locals: {
entry: entry,
delete_path_for: ->(image) { vehicle_fuel_entry_image_path(@vehicle, entry, image) },
add_path: new_images_vehicle_fuel_entry_path(@vehicle, entry)
}
end end
def save_fuel_entry def save_fuel_entry
@@ -40,8 +125,8 @@ class FuelEntriesController < ApplicationController
def prepare_vehicle_show def prepare_vehicle_show
@maintenance_schedules = @vehicle.maintenance_schedules.active.order(:maintenance_type) @maintenance_schedules = @vehicle.maintenance_schedules.active.order(:maintenance_type)
@maintenance_schedule_statuses = maintenance_schedule_statuses(@maintenance_schedules) @maintenance_schedule_statuses = maintenance_schedule_statuses(@maintenance_schedules)
@fuel_entries = @vehicle.fuel_entries.includes(:updated_by_user).order(date: :desc, created_at: :desc) @fuel_entries = @vehicle.fuel_entries.with_attached_images.includes(:updated_by_user).order(date: :desc, created_at: :desc)
@maintenance_entries = @vehicle.maintenance_entries.includes(:updated_by_user).order(date: :desc, created_at: :desc) @maintenance_entries = @vehicle.maintenance_entries.with_attached_images.includes(:updated_by_user).order(date: :desc, created_at: :desc)
@maintenance_entry = @vehicle.maintenance_entries.build(date: Date.current) @maintenance_entry = @vehicle.maintenance_entries.build(date: Date.current)
end end
@@ -0,0 +1,18 @@
class FuelEntryImagesController < ApplicationController
def destroy
attachment = fuel_entry.images.attachments.find(params[:attachment_id])
attachment.purge
redirect_to images_vehicle_fuel_entry_path(vehicle, fuel_entry), status: :see_other, notice: "Fuel image deleted."
end
private
def vehicle
@vehicle ||= Vehicle.find(params[:vehicle_id])
end
def fuel_entry
@fuel_entry ||= vehicle.fuel_entries.find(params[:fuel_entry_id])
end
end
@@ -1,6 +1,30 @@
require "digest/md5"
class MaintenanceEntriesController < ApplicationController class MaintenanceEntriesController < ApplicationController
ODOMETER_WARNING_THRESHOLD = 500 ODOMETER_WARNING_THRESHOLD = 500
def images
@vehicle = Vehicle.find(params[:vehicle_id])
@maintenance_entry = @vehicle.maintenance_entries.with_attached_images.find(params[:id])
if request.post?
attach_images(@maintenance_entry)
return
end
render_images(@maintenance_entry)
end
def new_images
@vehicle = Vehicle.find(params[:vehicle_id])
@maintenance_entry = @vehicle.maintenance_entries.find(params[:id])
render partial: "entry_images/form", locals: {
entry: @maintenance_entry,
upload_path: images_vehicle_maintenance_entry_path(@vehicle, @maintenance_entry)
}
end
def create def create
@vehicle = Vehicle.find(params[:vehicle_id]) @vehicle = Vehicle.find(params[:vehicle_id])
original_odometer = @vehicle.current_odometer original_odometer = @vehicle.current_odometer
@@ -19,7 +43,68 @@ class MaintenanceEntriesController < ApplicationController
private private
def maintenance_entry_params def maintenance_entry_params
params.require(:maintenance_entry).permit(:name, :notes, :odometer, :cost, :date) params.require(:maintenance_entry).permit(:name, :notes, :odometer, :cost, :date, images: [])
end
def image_params
params.require(:maintenance_entry).permit(images: [])
end
def attach_images(entry)
uploads = Array(image_params[:images]).reject(&:blank?)
if uploads.empty?
entry.errors.add(:images, "must be selected")
render_image_form(entry, status: :unprocessable_entity)
return
end
validate_image_uploads(entry, uploads)
if entry.errors[:images].any? || entry.errors[:base].any?
render_image_form(entry, status: :unprocessable_entity)
else
entry.images.attach(uploads)
entry.save!(validate: false)
entry.images.reload
render_images(entry)
end
end
def validate_image_uploads(entry, uploads)
checksums = []
uploads.each do |upload|
entry.errors.add(:images, "must be 10 MB or smaller") if upload.size > EntryImageValidation::MAX_IMAGE_SIZE
entry.errors.add(:images, "must be JPEG or PNG") unless EntryImageValidation::ALLOWED_IMAGE_CONTENT_TYPES.include?(upload.content_type)
checksums << upload_checksum(upload)
end
existing_checksums = entry.images.map(&:checksum)
duplicate_existing = (checksums & existing_checksums).any?
duplicate_new = checksums.tally.any? { |_checksum, count| count > 1 }
return unless duplicate_existing || duplicate_new
entry.errors.add(:base, "This image is already attached to this entry")
end
def upload_checksum(upload)
Digest::MD5.base64digest(upload.read).tap do
upload.rewind
end
end
def render_image_form(entry, status: :ok)
render partial: "entry_images/form", formats: :html, locals: {
entry: entry,
upload_path: images_vehicle_maintenance_entry_path(@vehicle, entry)
}, status: status
end
def render_images(entry)
render partial: "entry_images/images", formats: :html, locals: {
entry: entry,
delete_path_for: ->(image) { vehicle_maintenance_entry_image_path(@vehicle, entry, image) },
add_path: new_images_vehicle_maintenance_entry_path(@vehicle, entry)
}
end end
def save_maintenance_entry def save_maintenance_entry
@@ -55,8 +140,8 @@ class MaintenanceEntriesController < ApplicationController
def prepare_vehicle_show def prepare_vehicle_show
@maintenance_schedules = @vehicle.maintenance_schedules.active.order(:maintenance_type) @maintenance_schedules = @vehicle.maintenance_schedules.active.order(:maintenance_type)
@maintenance_schedule_statuses = maintenance_schedule_statuses(@maintenance_schedules) @maintenance_schedule_statuses = maintenance_schedule_statuses(@maintenance_schedules)
@fuel_entries = @vehicle.fuel_entries.includes(:updated_by_user).order(date: :desc, created_at: :desc) @fuel_entries = @vehicle.fuel_entries.with_attached_images.includes(:updated_by_user).order(date: :desc, created_at: :desc)
@maintenance_entries = @vehicle.maintenance_entries.includes(:updated_by_user).order(date: :desc, created_at: :desc) @maintenance_entries = @vehicle.maintenance_entries.with_attached_images.includes(:updated_by_user).order(date: :desc, created_at: :desc)
@fuel_entry = @vehicle.fuel_entries.build(date: Date.current) @fuel_entry = @vehicle.fuel_entries.build(date: Date.current)
end end
@@ -0,0 +1,18 @@
class MaintenanceEntryImagesController < ApplicationController
def destroy
attachment = maintenance_entry.images.attachments.find(params[:attachment_id])
attachment.purge
redirect_to images_vehicle_maintenance_entry_path(vehicle, maintenance_entry), status: :see_other, notice: "Maintenance image deleted."
end
private
def vehicle
@vehicle ||= Vehicle.find(params[:vehicle_id])
end
def maintenance_entry
@maintenance_entry ||= vehicle.maintenance_entries.find(params[:maintenance_entry_id])
end
end
+2 -2
View File
@@ -75,8 +75,8 @@ class VehiclesController < ApplicationController
def prepare_show def prepare_show
@maintenance_schedules = @vehicle.maintenance_schedules.active.order(:maintenance_type) @maintenance_schedules = @vehicle.maintenance_schedules.active.order(:maintenance_type)
@maintenance_schedule_statuses = maintenance_schedule_statuses(@maintenance_schedules) @maintenance_schedule_statuses = maintenance_schedule_statuses(@maintenance_schedules)
@fuel_entries = @vehicle.fuel_entries.includes(:updated_by_user).order(date: :desc, created_at: :desc) @fuel_entries = @vehicle.fuel_entries.with_attached_images.includes(:updated_by_user).order(date: :desc, created_at: :desc)
@maintenance_entries = @vehicle.maintenance_entries.includes(:updated_by_user).order(date: :desc, created_at: :desc) @maintenance_entries = @vehicle.maintenance_entries.with_attached_images.includes(:updated_by_user).order(date: :desc, created_at: :desc)
@fuel_entry ||= @vehicle.fuel_entries.build(date: Date.current) @fuel_entry ||= @vehicle.fuel_entries.build(date: Date.current)
@maintenance_entry ||= @vehicle.maintenance_entries.build(date: Date.current) @maintenance_entry ||= @vehicle.maintenance_entries.build(date: Date.current)
end end
@@ -0,0 +1,39 @@
module EntryImageValidation
extend ActiveSupport::Concern
MAX_IMAGE_SIZE = 10.megabytes
ALLOWED_IMAGE_CONTENT_TYPES = %w[image/jpeg image/png].freeze
included do
validate :images_are_valid
validate :images_are_not_duplicated
end
private
def images_are_valid
images.each do |image|
validate_image_size(image)
validate_image_content_type(image)
end
end
def images_are_not_duplicated
duplicate_checksum = images.map { |image| image.blob.checksum }.compact.tally.any? { |_checksum, count| count > 1 }
return unless duplicate_checksum
errors.add(:base, "This image is already attached to this entry")
end
def validate_image_size(image)
return if image.blob.byte_size <= MAX_IMAGE_SIZE
errors.add(:images, "must be 10 MB or smaller")
end
def validate_image_content_type(image)
return if ALLOWED_IMAGE_CONTENT_TYPES.include?(image.blob.content_type)
errors.add(:images, "must be JPEG or PNG")
end
end
+3
View File
@@ -1,6 +1,9 @@
class FuelEntry < ApplicationRecord class FuelEntry < ApplicationRecord
include EntryImageValidation
belongs_to :vehicle belongs_to :vehicle
belongs_to :updated_by_user, class_name: "User" belongs_to :updated_by_user, class_name: "User"
has_many_attached :images
validates :odometer, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } validates :odometer, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
validates :gallons_pumped, presence: true, numericality: { greater_than: 0 } validates :gallons_pumped, presence: true, numericality: { greater_than: 0 }
+3
View File
@@ -1,6 +1,9 @@
class MaintenanceEntry < ApplicationRecord class MaintenanceEntry < ApplicationRecord
include EntryImageValidation
belongs_to :vehicle belongs_to :vehicle
belongs_to :updated_by_user, class_name: "User" belongs_to :updated_by_user, class_name: "User"
has_many_attached :images
validates :name, :notes, :date, presence: true validates :name, :notes, :date, presence: true
validates :odometer, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 } validates :odometer, presence: true, numericality: { only_integer: true, greater_than_or_equal_to: 0 }
+125
View File
@@ -0,0 +1,125 @@
require "base64"
class BackupExport
FORMAT = "car_tracker_backup".freeze
VERSION = 2
def self.call(include_images: false)
new(include_images: include_images).call
end
def initialize(include_images: false)
@include_images = include_images
end
def call
{
"format" => FORMAT,
"version" => VERSION,
"exported_at" => Time.current.iso8601,
"vehicles" => vehicles
}.to_yaml
end
private
attr_reader :include_images
def vehicles
Vehicle.includes(
:maintenance_schedules,
{ fuel_entries: :updated_by_user },
{ maintenance_entries: :updated_by_user }
).order(:make, :model, :year, :vin).map do |vehicle|
vehicle_data(vehicle)
end
end
def vehicle_data(vehicle)
{
"vin" => vehicle.vin,
"licence_plate" => vehicle.licence_plate,
"make" => vehicle.make,
"model" => vehicle.model,
"year" => vehicle.year,
"color" => vehicle.color,
"current_odometer" => vehicle.current_odometer,
"fuel_tank_size" => decimal_string(vehicle.fuel_tank_size),
"active" => vehicle.active?,
"maintenance_schedules" => maintenance_schedules(vehicle),
"fuel_entries" => fuel_entries(vehicle),
"maintenance_entries" => maintenance_entries(vehicle)
}
end
def maintenance_schedules(vehicle)
vehicle.maintenance_schedules.sort_by(&:maintenance_type).map do |schedule|
{
"maintenance_type" => schedule.maintenance_type,
"mileage_interval" => schedule.mileage_interval,
"time_interval" => schedule.time_interval,
"baseline_odometer" => schedule.baseline_odometer,
"baseline_date" => date_string(schedule.baseline_date),
"active" => schedule.active?,
"last_status" => schedule.last_status,
"last_status_changed_at" => time_string(schedule.last_status_changed_at)
}
end
end
def fuel_entries(vehicle)
vehicle.fuel_entries.sort_by { |entry| [ entry.date, entry.odometer, entry.id ] }.map do |entry|
{
"date" => date_string(entry.date),
"odometer" => entry.odometer,
"gallons_pumped" => decimal_string(entry.gallons_pumped),
"price_paid" => decimal_string(entry.price_paid),
"updated_by_user" => user_data(entry.updated_by_user)
}.tap { |data| data["images"] = images(entry) if include_images }
end
end
def maintenance_entries(vehicle)
vehicle.maintenance_entries.sort_by { |entry| [ entry.date, entry.odometer, entry.name, entry.id ] }.map do |entry|
{
"name" => entry.name,
"notes" => entry.notes,
"date" => date_string(entry.date),
"odometer" => entry.odometer,
"cost" => decimal_string(entry.cost),
"updated_by_user" => user_data(entry.updated_by_user)
}.tap { |data| data["images"] = images(entry) if include_images }
end
end
def images(entry)
entry.images.map do |image|
{
"filename" => image.filename.to_s,
"content_type" => image.content_type,
"checksum" => image.checksum,
"byte_size" => image.byte_size,
"data_base64" => Base64.strict_encode64(image.download)
}
end
end
def user_data(user)
{
"name" => user.name,
"email" => user.email
}
end
def date_string(value)
value&.iso8601
end
def time_string(value)
value&.iso8601
end
def decimal_string(value)
value&.to_s("F")
end
end
+317
View File
@@ -0,0 +1,317 @@
require "base64"
require "digest/md5"
require "stringio"
class BackupImport
SUPPORTED_VERSIONS = [ 1, 2 ].freeze
MODES = %w[merge replace].freeze
class Error < StandardError; end
def self.call(yaml, mode:)
new(yaml, mode: mode).call
end
def initialize(yaml, mode:)
@yaml = yaml
@mode = mode.to_s
end
def call
validate_mode!
backup = load_backup
backup = migrate_backup(backup)
ActiveRecord::Base.transaction do
replace_app_data! if mode == "replace"
import_backup(backup)
end
end
private
attr_reader :yaml, :mode
def validate_mode!
return if MODES.include?(mode)
raise Error, "Choose a valid restore mode."
end
def load_backup
backup = YAML.safe_load(yaml, aliases: false)
raise Error, "Backup file is empty." unless backup.is_a?(Hash)
raise Error, "Backup format is not supported." unless backup["format"] == BackupExport::FORMAT
backup
rescue Psych::Exception
raise Error, "Backup file is not valid YAML."
end
def migrate_backup(backup)
version = backup["version"].to_i
return backup if SUPPORTED_VERSIONS.include?(version)
if version > SUPPORTED_VERSIONS.max
raise Error, "Backup version #{version} is newer than this application supports."
end
raise Error, "Backup version #{version} does not have an available migration path."
end
def replace_app_data!
UserSession.delete_all
FuelEntry.find_each { |entry| entry.images.purge }
MaintenanceEntry.find_each { |entry| entry.images.purge }
FuelEntry.delete_all
MaintenanceEntry.delete_all
MaintenanceSchedule.delete_all
Vehicle.delete_all
User.delete_all
end
def import_backup(backup)
vehicles = backup.fetch("vehicles") { raise Error, "Backup is missing vehicles." }
raise Error, "Backup vehicles must be a list." unless vehicles.is_a?(Array)
vehicles.each do |vehicle_data|
import_vehicle(vehicle_data)
end
end
def import_vehicle(vehicle_data)
vehicle = find_or_initialize_vehicle(vehicle_data)
incoming_odometer = integer_value(vehicle_data.fetch("current_odometer"))
vehicle.assign_attributes(vehicle_attributes(vehicle_data).merge(current_odometer: incoming_odometer))
vehicle.save!
import_schedules(vehicle, array_value(vehicle_data, "maintenance_schedules"))
import_fuel_entries(vehicle, array_value(vehicle_data, "fuel_entries"))
import_maintenance_entries(vehicle, array_value(vehicle_data, "maintenance_entries"))
recalculate_odometer(vehicle, incoming_odometer)
rescue KeyError => error
raise Error, "Vehicle is missing required field #{error.key}."
rescue ActiveRecord::RecordInvalid => error
raise Error, error.record.errors.full_messages.to_sentence
end
def find_or_initialize_vehicle(vehicle_data)
vin = string_value(vehicle_data.fetch("vin"))
raise Error, "Vehicle VIN is required." if vin.blank?
Vehicle.find_or_initialize_by(vin: vin.upcase)
end
def vehicle_attributes(vehicle_data)
{
licence_plate: string_value(vehicle_data.fetch("licence_plate")),
make: string_value(vehicle_data.fetch("make")),
model: string_value(vehicle_data.fetch("model")),
year: integer_value(vehicle_data.fetch("year")),
color: string_value(vehicle_data.fetch("color")),
fuel_tank_size: decimal_value(vehicle_data.fetch("fuel_tank_size")),
active: boolean_value(vehicle_data.fetch("active"))
}
end
def import_schedules(vehicle, schedules)
schedules.each do |schedule_data|
schedule = vehicle.maintenance_schedules.find_or_initialize_by(
maintenance_type: string_value(schedule_data.fetch("maintenance_type"))
)
schedule.assign_attributes(
mileage_interval: integer_value(schedule_data.fetch("mileage_interval")),
time_interval: integer_value(schedule_data.fetch("time_interval")),
baseline_odometer: integer_value(schedule_data.fetch("baseline_odometer")),
baseline_date: date_value(schedule_data.fetch("baseline_date")),
active: boolean_value(schedule_data.fetch("active")),
last_status: optional_string_value(schedule_data["last_status"]),
last_status_changed_at: optional_time_value(schedule_data["last_status_changed_at"])
)
schedule.save!
end
rescue KeyError => error
raise Error, "Maintenance schedule is missing required field #{error.key}."
end
def import_fuel_entries(vehicle, entries)
entries.each do |entry_data|
user = import_user(entry_data.fetch("updated_by_user"))
entry = matching_fuel_entry(vehicle, entry_data, user)
unless entry
FuelEntry.insert!({
vehicle_id: vehicle.id,
updated_by_user_id: user.id,
odometer: integer_value(entry_data.fetch("odometer")),
gallons_pumped: decimal_value(entry_data.fetch("gallons_pumped")),
price_paid: decimal_value(entry_data.fetch("price_paid")),
date: date_value(entry_data.fetch("date")),
created_at: Time.current,
updated_at: Time.current
})
entry = matching_fuel_entry(vehicle, entry_data, user)
end
import_images(entry, array_value(entry_data, "images"))
end
rescue KeyError => error
raise Error, "Fuel entry is missing required field #{error.key}."
end
def import_maintenance_entries(vehicle, entries)
entries.each do |entry_data|
user = import_user(entry_data.fetch("updated_by_user"))
entry = matching_maintenance_entry(vehicle, entry_data, user)
unless entry
MaintenanceEntry.insert!({
vehicle_id: vehicle.id,
updated_by_user_id: user.id,
name: string_value(entry_data.fetch("name")),
notes: string_value(entry_data.fetch("notes")),
odometer: integer_value(entry_data.fetch("odometer")),
cost: decimal_value(entry_data.fetch("cost")),
date: date_value(entry_data.fetch("date")),
created_at: Time.current,
updated_at: Time.current
})
entry = matching_maintenance_entry(vehicle, entry_data, user)
end
import_images(entry, array_value(entry_data, "images"))
end
rescue KeyError => error
raise Error, "Maintenance entry is missing required field #{error.key}."
end
def import_user(user_data)
raise Error, "Updated by user must be present." unless user_data.is_a?(Hash)
email = string_value(user_data.fetch("email")).downcase
user = User.find_or_initialize_by(email: email)
user.name = string_value(user_data.fetch("name"))
user.save!
user
rescue KeyError => error
raise Error, "User is missing required field #{error.key}."
end
def matching_fuel_entry(vehicle, entry_data, user)
vehicle.fuel_entries.where(
updated_by_user: user,
odometer: integer_value(entry_data.fetch("odometer")),
gallons_pumped: decimal_value(entry_data.fetch("gallons_pumped")),
price_paid: decimal_value(entry_data.fetch("price_paid")),
date: date_value(entry_data.fetch("date"))
).first
end
def matching_maintenance_entry(vehicle, entry_data, user)
vehicle.maintenance_entries.where(
updated_by_user: user,
name: string_value(entry_data.fetch("name")),
notes: string_value(entry_data.fetch("notes")),
odometer: integer_value(entry_data.fetch("odometer")),
cost: decimal_value(entry_data.fetch("cost")),
date: date_value(entry_data.fetch("date"))
).first
end
def import_images(entry, images)
images.each do |image_data|
filename = string_value(image_data.fetch("filename"))
checksum = string_value(image_data.fetch("checksum"))
next if image_attached?(entry, filename, checksum)
content_type = string_value(image_data.fetch("content_type"))
byte_size = integer_value(image_data.fetch("byte_size"))
validate_image_metadata!(content_type, byte_size)
content = Base64.strict_decode64(string_value(image_data.fetch("data_base64")))
raise Error, "Image byte size does not match backup metadata." unless content.bytesize == byte_size
raise Error, "Image checksum does not match backup metadata." unless Digest::MD5.base64digest(content) == checksum
entry.images.attach(
io: StringIO.new(content),
filename: filename,
content_type: content_type
)
end
rescue ArgumentError
raise Error, "Image data is not valid Base64."
rescue KeyError => error
raise Error, "Image is missing required field #{error.key}."
end
def image_attached?(entry, filename, checksum)
entry.images.any? do |image|
image.filename.to_s == filename && image.checksum == checksum
end
end
def validate_image_metadata!(content_type, byte_size)
unless EntryImageValidation::ALLOWED_IMAGE_CONTENT_TYPES.include?(content_type)
raise Error, "Images must be JPEG or PNG."
end
return if byte_size <= EntryImageValidation::MAX_IMAGE_SIZE
raise Error, "Images must be 10 MB or smaller."
end
def recalculate_odometer(vehicle, incoming_odometer)
max_odometer = [
incoming_odometer,
vehicle.fuel_entries.maximum(:odometer),
vehicle.maintenance_entries.maximum(:odometer)
].compact.max
vehicle.update!(current_odometer: max_odometer)
end
def array_value(data, key)
value = data.fetch(key, [])
raise Error, "#{key.humanize} must be a list." unless value.is_a?(Array)
value
end
def string_value(value)
value.to_s.strip
end
def optional_string_value(value)
value.present? ? value.to_s : nil
end
def integer_value(value)
Integer(value)
rescue ArgumentError, TypeError
raise Error, "Expected an integer value."
end
def decimal_value(value)
BigDecimal(value.to_s)
rescue ArgumentError, TypeError
raise Error, "Expected a decimal value."
end
def date_value(value)
Date.iso8601(value.to_s)
rescue Date::Error, TypeError
raise Error, "Expected an ISO 8601 date."
end
def optional_time_value(value)
value.present? ? Time.zone.iso8601(value.to_s) : nil
rescue ArgumentError, TypeError
raise Error, "Expected an ISO 8601 time."
end
def boolean_value(value)
return value if value == true || value == false
raise Error, "Expected a boolean value."
end
end
+58
View File
@@ -0,0 +1,58 @@
<main class="page-shell">
<% if notice.present? %>
<p class="flash flash--notice"><%= notice %></p>
<% end %>
<% if flash[:alert].present? %>
<p class="flash flash--warning"><%= flash[:alert] %></p>
<% end %>
<p><%= link_to "Back to vehicles", vehicles_path, class: "back-link" %></p>
<header class="page-header">
<div>
<p class="eyebrow">Data portability</p>
<h1>Backup / Restore</h1>
</div>
</header>
<section class="dashboard-section dashboard-section--primary">
<h2>Download Backup</h2>
<p>Download a gzip-compressed YAML backup of vehicles, users, maintenance schedules, fuel entries, and maintenance entries.</p>
<p>Authentication data, access keys, and browser sessions are not included.</p>
<div class="action-row">
<%= link_to "Download data backup", download_backup_path, class: "button button--primary" %>
<%= link_to "Download backup with images", download_with_images_backup_path, class: "button button--secondary" %>
</div>
</section>
<section class="dashboard-section">
<h2>Restore Backup</h2>
<p>Upload a `.yml.gz` backup exported from Car Tracker.</p>
<%= form_with url: restore_backup_path, multipart: true, class: "stacked-form" do |form| %>
<div class="field">
<%= form.label :backup_file, "Backup file" %>
<%= form.file_field :backup_file, accept: ".gz,.yml.gz,application/gzip", required: true %>
</div>
<fieldset class="field">
<legend>Restore mode</legend>
<label>
<%= radio_button_tag :mode, "merge", true %>
Merge data into this installation
</label>
<label>
<%= radio_button_tag :mode, "replace" %>
Replace all existing app data
</label>
</fieldset>
<p class="field-warning">Replace mode deletes existing vehicles, users, schedules, fuel entries, and maintenance entries before importing the backup.</p>
<div>
<%= form.submit "Restore backup", class: "button button--primary" %>
</div>
<% end %>
</section>
</main>
+26
View File
@@ -0,0 +1,26 @@
<%= turbo_frame_tag dom_id(entry, :images) do %>
<%= form_with url: upload_path, scope: entry.model_name.param_key, multipart: true, class: "entry-image-form" do |form| %>
<% if entry.errors[:images].any? || entry.errors[:base].any? %>
<div class="form-errors form-errors--compact">
<ul>
<% entry.errors[:base].each do |message| %>
<li><%= message %></li>
<% end %>
<% entry.errors[:images].each do |message| %>
<li>Images <%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :images, "Images" %>
<%= form.file_field :images, multiple: true, accept: "image/jpeg,image/png", required: true %>
</div>
<div class="action-row">
<%= form.submit "Upload images", class: "button button--primary button--small" %>
</div>
<% end %>
<% end %>
+23
View File
@@ -0,0 +1,23 @@
<%= turbo_frame_tag dom_id(entry, :images) do %>
<% if entry.images.attached? %>
<div class="entry-images">
<% entry.images.each do |image| %>
<figure class="entry-image">
<%= link_to rails_blob_path(image, disposition: "inline"), target: "_blank", rel: "noopener" do %>
<%= image_tag rails_blob_path(image, disposition: "inline"), alt: image.filename.to_s, class: "entry-image__thumbnail" %>
<% end %>
<figcaption><%= image.filename %></figcaption>
<%= button_to "Delete", delete_path_for.call(image), method: :delete, class: "button button--danger button--small" %>
</figure>
<% end %>
</div>
<% else %>
<span>No images attached.</span>
<% end %>
<p class="entry-images__actions">
<%= link_to "Add images", add_path, class: "button button--secondary button--small" %>
</p>
<% end %>
+4 -1
View File
@@ -8,7 +8,10 @@
<p class="eyebrow">Fleet dashboard</p> <p class="eyebrow">Fleet dashboard</p>
<h1>Vehicles</h1> <h1>Vehicles</h1>
</div> </div>
<%= link_to "New vehicle", new_vehicle_path, class: "button button--primary" %> <div class="action-row">
<%= link_to "Backup / Restore", backup_path, class: "button button--secondary" %>
<%= link_to "New vehicle", new_vehicle_path, class: "button button--primary" %>
</div>
</header> </header>
<nav class="filter-nav" aria-label="Vehicle filters"> <nav class="filter-nav" aria-label="Vehicle filters">
+38 -2
View File
@@ -103,7 +103,7 @@
<details class="dashboard-section dashboard-section--primary" open> <details class="dashboard-section dashboard-section--primary" open>
<summary>Record Fuel</summary> <summary>Record Fuel</summary>
<%= form_with model: [@vehicle, @fuel_entry], class: "stacked-form" do |form| %> <%= form_with model: [@vehicle, @fuel_entry], class: "stacked-form", multipart: true do |form| %>
<% if @fuel_entry.errors.any? %> <% if @fuel_entry.errors.any? %>
<section class="form-errors"> <section class="form-errors">
<h3><%= pluralize(@fuel_entry.errors.count, "error") %> prevented this fuel entry from being saved</h3> <h3><%= pluralize(@fuel_entry.errors.count, "error") %> prevented this fuel entry from being saved</h3>
@@ -136,6 +136,11 @@
<%= form.label :date %> <%= form.label :date %>
<%= form.date_field :date, max: Date.current, required: true %> <%= form.date_field :date, max: Date.current, required: true %>
</div> </div>
<div class="field">
<%= form.label :images, "Receipt images" %>
<%= form.file_field :images, multiple: true, accept: "image/jpeg,image/png" %>
</div>
</div> </div>
<div> <div>
@@ -148,7 +153,7 @@
<summary>Record Maintenance</summary> <summary>Record Maintenance</summary>
<% if @maintenance_schedules.any? %> <% if @maintenance_schedules.any? %>
<%= form_with model: [@vehicle, @maintenance_entry], class: "stacked-form", data: { <%= form_with model: [@vehicle, @maintenance_entry], class: "stacked-form", multipart: true, data: {
controller: "maintenance-odometer-warning", controller: "maintenance-odometer-warning",
maintenance_odometer_warning_current_odometer_value: @vehicle.current_odometer, maintenance_odometer_warning_current_odometer_value: @vehicle.current_odometer,
maintenance_odometer_warning_threshold_value: 500 maintenance_odometer_warning_threshold_value: 500
@@ -188,6 +193,11 @@
<%= form.label :date %> <%= form.label :date %>
<%= form.date_field :date, max: Date.current, required: true %> <%= form.date_field :date, max: Date.current, required: true %>
</div> </div>
<div class="field">
<%= form.label :images, "Service images" %>
<%= form.file_field :images, multiple: true, accept: "image/jpeg,image/png" %>
</div>
</div> </div>
<p class="field-warning" hidden data-maintenance-odometer-warning-target="warning"> <p class="field-warning" hidden data-maintenance-odometer-warning-target="warning">
@@ -305,6 +315,7 @@
<th>Odometer</th> <th>Odometer</th>
<th>Cost</th> <th>Cost</th>
<th>Notes</th> <th>Notes</th>
<th>Images</th>
<th>Updated by</th> <th>Updated by</th>
</tr> </tr>
</thead> </thead>
@@ -316,6 +327,18 @@
<td><%= number_with_delimiter(entry.odometer) %></td> <td><%= number_with_delimiter(entry.odometer) %></td>
<td><%= number_to_currency(entry.cost) %></td> <td><%= number_to_currency(entry.cost) %></td>
<td><%= entry.notes %></td> <td><%= entry.notes %></td>
<td>
<%= turbo_frame_tag dom_id(entry, :images) do %>
<% if entry.images.attached? %>
<div class="action-row">
<%= link_to "Show images (#{entry.images.size})", images_vehicle_maintenance_entry_path(@vehicle, entry), class: "button button--secondary button--small" %>
<%= link_to "Add images", new_images_vehicle_maintenance_entry_path(@vehicle, entry), class: "button button--secondary button--small" %>
</div>
<% else %>
<%= link_to "Add images", new_images_vehicle_maintenance_entry_path(@vehicle, entry), class: "button button--secondary button--small" %>
<% end %>
<% end %>
</td>
<td><%= entry.updated_by_user.name %></td> <td><%= entry.updated_by_user.name %></td>
</tr> </tr>
<% end %> <% end %>
@@ -339,6 +362,7 @@
<th>Odometer</th> <th>Odometer</th>
<th>Gallons</th> <th>Gallons</th>
<th>Price paid</th> <th>Price paid</th>
<th>Images</th>
<th>Updated by</th> <th>Updated by</th>
</tr> </tr>
</thead> </thead>
@@ -349,6 +373,18 @@
<td><%= number_with_delimiter(entry.odometer) %></td> <td><%= number_with_delimiter(entry.odometer) %></td>
<td><%= entry.gallons_pumped %></td> <td><%= entry.gallons_pumped %></td>
<td><%= number_to_currency(entry.price_paid) %></td> <td><%= number_to_currency(entry.price_paid) %></td>
<td>
<%= turbo_frame_tag dom_id(entry, :images) do %>
<% if entry.images.attached? %>
<div class="action-row">
<%= link_to "Show images (#{entry.images.size})", images_vehicle_fuel_entry_path(@vehicle, entry), class: "button button--secondary button--small" %>
<%= link_to "Add images", new_images_vehicle_fuel_entry_path(@vehicle, entry), class: "button button--secondary button--small" %>
</div>
<% else %>
<%= link_to "Add images", new_images_vehicle_fuel_entry_path(@vehicle, entry), class: "button button--secondary button--small" %>
<% end %>
<% end %>
</td>
<td><%= entry.updated_by_user.name %></td> <td><%= entry.updated_by_user.name %></td>
</tr> </tr>
<% end %> <% end %>
+18 -2
View File
@@ -14,12 +14,28 @@ Rails.application.routes.draw do
# get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker
resources :vehicles do resources :vehicles do
resources :fuel_entries, only: :create resources :fuel_entries, only: :create do
resources :maintenance_entries, only: :create get :images, on: :member
post :images, on: :member
get :new_images, on: :member
delete "images/:attachment_id", to: "fuel_entry_images#destroy", as: :image
end
resources :maintenance_entries, only: :create do
get :images, on: :member
post :images, on: :member
get :new_images, on: :member
delete "images/:attachment_id", to: "maintenance_entry_images#destroy", as: :image
end
resources :maintenance_schedules, except: :destroy do resources :maintenance_schedules, except: :destroy do
patch :deactivate, on: :member patch :deactivate, on: :member
end end
end end
resource :backup, only: :show do
get :download
get :download_with_images
post :restore
end
root "vehicles#index" root "vehicles#index"
end end
@@ -0,0 +1,57 @@
# This migration comes from active_storage (originally 20170806125915)
class CreateActiveStorageTables < ActiveRecord::Migration[7.0]
def change
# Use Active Record's configured type for primary and foreign keys
primary_key_type, foreign_key_type = primary_and_foreign_key_types
create_table :active_storage_blobs, id: primary_key_type do |t|
t.string :key, null: false
t.string :filename, null: false
t.string :content_type
t.text :metadata
t.string :service_name, null: false
t.bigint :byte_size, null: false
t.string :checksum
if connection.supports_datetime_with_precision?
t.datetime :created_at, precision: 6, null: false
else
t.datetime :created_at, null: false
end
t.index [ :key ], unique: true
end
create_table :active_storage_attachments, id: primary_key_type do |t|
t.string :name, null: false
t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type
t.references :blob, null: false, type: foreign_key_type
if connection.supports_datetime_with_precision?
t.datetime :created_at, precision: 6, null: false
else
t.datetime :created_at, null: false
end
t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
create_table :active_storage_variant_records, id: primary_key_type do |t|
t.belongs_to :blob, null: false, index: false, type: foreign_key_type
t.string :variation_digest, null: false
t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true
t.foreign_key :active_storage_blobs, column: :blob_id
end
end
private
def primary_and_foreign_key_types
config = Rails.configuration.generators
setting = config.options[config.orm][:primary_key_type]
primary_key_type = setting || :primary_key
foreign_key_type = setting || :bigint
[ primary_key_type, foreign_key_type ]
end
end
Generated
+31 -1
View File
@@ -10,7 +10,7 @@
# #
# It's strongly recommended that you check this file into your version control system. # It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2026_09_16_120000) do ActiveRecord::Schema[8.1].define(version: 2026_09_28_185232) do
create_table "access_keys", force: :cascade do |t| create_table "access_keys", force: :cascade do |t|
t.boolean "auto_rotate", default: true, null: false t.boolean "auto_rotate", default: true, null: false
t.integer "auto_rotation_frequency_days", default: 30, null: false t.integer "auto_rotation_frequency_days", default: 30, null: false
@@ -20,6 +20,34 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_16_120000) do
t.datetime "updated_at", null: false t.datetime "updated_at", null: false
end end
create_table "active_storage_attachments", force: :cascade do |t|
t.bigint "blob_id", null: false
t.datetime "created_at", null: false
t.string "name", null: false
t.bigint "record_id", null: false
t.string "record_type", null: false
t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
end
create_table "active_storage_blobs", force: :cascade do |t|
t.bigint "byte_size", null: false
t.string "checksum"
t.string "content_type"
t.datetime "created_at", null: false
t.string "filename", null: false
t.string "key", null: false
t.text "metadata"
t.string "service_name", null: false
t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true
end
create_table "active_storage_variant_records", force: :cascade do |t|
t.bigint "blob_id", null: false
t.string "variation_digest", null: false
t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true
end
create_table "fuel_entries", force: :cascade do |t| create_table "fuel_entries", force: :cascade do |t|
t.datetime "created_at", null: false t.datetime "created_at", null: false
t.date "date", null: false t.date "date", null: false
@@ -97,6 +125,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_09_16_120000) do
t.index ["vin"], name: "index_vehicles_on_vin", unique: true t.index ["vin"], name: "index_vehicles_on_vin", unique: true
end end
add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id"
add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id"
add_foreign_key "fuel_entries", "users", column: "updated_by_user_id" add_foreign_key "fuel_entries", "users", column: "updated_by_user_id"
add_foreign_key "fuel_entries", "vehicles" add_foreign_key "fuel_entries", "vehicles"
add_foreign_key "maintenance_entries", "users", column: "updated_by_user_id" add_foreign_key "maintenance_entries", "users", column: "updated_by_user_id"
+16
View File
@@ -0,0 +1,16 @@
services:
web:
build: .
restart: always
ports:
- "8090:3000"
environment:
- RAILS_ENV=production
- RAILS_SERVE_STATIC_FILES=true
- RAILS_LOG_TO_STDOUT=true
- SECRET_KEY_BASE=${SECRET_KEY_BASE}
volumes:
- sqlite_data:/app/db
volumes:
sqlite_data:
+35
View File
@@ -0,0 +1,35 @@
# Phase 008 Execution
## Scope
- Add compressed YAML backup export and restore for portable application data.
- Support merge and replace restore modes.
- Exclude authentication and runtime data from backups.
## Changes
- Added `BackupExport` to produce versioned YAML containing vehicles, users referenced by entries, maintenance schedules, fuel entries, and maintenance entries.
- Added `BackupImport` to restore versioned YAML in merge or replace mode.
- Added gzip download and upload handling without adding gem dependencies.
- Added top-level backup routes and `BackupsController` actions for show, download, and restore.
- Added a backup/restore page with download, upload, merge, and replace controls.
- Added a `Backup / Restore` action to the vehicle dashboard.
- Added request specs for authentication, dashboard visibility, gzip YAML export, merge restore, duplicate prevention, replace restore, invalid gzip uploads, and unsupported backup versions.
## Decisions
- Backup files are gzip-compressed YAML files with a `.yml.gz` filename.
- Backups include app data only and exclude access keys and user sessions.
- Replace mode clears user sessions before replacing app data so users can be deleted without foreign-key failures.
- Replace mode preserves access keys because authentication configuration is outside backup scope.
- Merge mode updates matched users, vehicles, and maintenance schedules, and creates unmatched records.
- Users are matched by normalized email.
- Vehicles are matched by VIN.
- Maintenance schedules are matched by vehicle and maintenance type.
- Fuel and maintenance entries are deduplicated with natural keys using vehicle, user, date, odometer, and entry-specific values.
- Import uses direct inserts for historical entries so UI-specific validations do not block valid restored history.
- Vehicle current odometers are recalculated after import from incoming vehicle data and all fuel/maintenance entry odometers.
- Unknown newer versions and older versions without an explicit migration path are rejected.
## Verification
- Passed: `bundle exec rspec spec/requests/backups_spec.rb`
- Passed: `bundle exec rspec`
- Passed: `bin/rubocop app/controllers/backups_controller.rb app/services/backup_export.rb app/services/backup_import.rb spec/requests/backups_spec.rb`
- Passed: `bin/ci`
+63
View File
@@ -0,0 +1,63 @@
# Phase 009 Execution
## Scope
- Add image attachments for fuel and maintenance entries.
- Keep vehicle history image loading explicit and lightweight.
- Extend backups with data-only and image-inclusive options.
## Changes
- Installed Active Storage tables.
- Added `has_many_attached :images` to fuel and maintenance entries.
- Added shared image validation for JPEG/PNG-only uploads with a 10 MB per-image limit.
- Added multi-file image upload fields to fuel and maintenance entry forms.
- Added lazy inline image endpoints for fuel and maintenance history rows.
- Added hidden inline upload forms for adding images to existing fuel and maintenance entries.
- Successful existing-entry image uploads immediately render the thumbnail/delete UI.
- Invalid existing-entry image uploads keep the inline form visible and purge the rejected files.
- Added small thumbnail rendering with links to full-size images.
- Added delete actions for individual fuel and maintenance entry images.
- Added data-only and image-inclusive backup download options.
- Bumped backup exports to version 2.
- Preserved version 1 backup import support as data-only imports.
- Added image export/import using Base64-encoded image data in gzip-compressed YAML.
- Added merge-import image deduplication by filename and checksum.
- Added replace-mode image purging before direct app-data deletion.
- Added model and request specs for upload validation, lazy loading, deletion, backup export, restore, and deduplication.
- Added request specs for loading existing-entry upload forms and attaching images to previous fuel and maintenance entries.
- Fixed existing-entry image uploads so they validate only newly uploaded images instead of rerunning all historical entry validations.
- Filtered blank file-field values from existing-entry image uploads.
- Added regression coverage for adding images to old fuel entries whose odometer is now lower than the vehicle current odometer.
- Changed inline image thumbnails to use original blob URLs instead of Active Storage variants so thumbnails do not require server-side image processing libraries.
- Added per-entry duplicate image detection by checksum for new entry creation and existing-entry image uploads.
- Added a user-facing duplicate error: `This image is already attached to this entry`.
- Preserved the ability to attach the same image to different entries.
## Decisions
- Images are stored with Active Storage.
- Fuel and maintenance entries support multiple images.
- Only JPEG and PNG uploads are accepted.
- Each image is limited to 10 MB.
- History images load inline only when requested.
- Full-size images open from thumbnail links.
- Backups keep gzip-compressed YAML and offer separate data-only and image-inclusive downloads.
## Verification
- Passed: `bundle exec rspec spec/models/fuel_entry_spec.rb spec/models/maintenance_entry_spec.rb spec/requests/vehicles_spec.rb spec/requests/backups_spec.rb`
- Passed: `bundle exec rspec`
- Passed: `bin/rubocop app/models/concerns/entry_image_validation.rb app/models/fuel_entry.rb app/models/maintenance_entry.rb app/controllers/fuel_entries_controller.rb app/controllers/maintenance_entries_controller.rb app/controllers/fuel_entry_images_controller.rb app/controllers/maintenance_entry_images_controller.rb app/controllers/backups_controller.rb app/controllers/vehicles_controller.rb app/services/backup_export.rb app/services/backup_import.rb spec/models/fuel_entry_spec.rb spec/models/maintenance_entry_spec.rb spec/requests/vehicles_spec.rb spec/requests/backups_spec.rb`
- Passed: `bin/ci`
- Passed after existing-entry upload support: `bundle exec rspec spec/requests/vehicles_spec.rb`
- Passed after existing-entry upload support: `bundle exec rspec spec/requests/vehicles_spec.rb spec/requests/backups_spec.rb spec/models/fuel_entry_spec.rb spec/models/maintenance_entry_spec.rb`
- Passed after existing-entry upload support: `bundle exec rspec`
- Passed after existing-entry upload support: `bin/rubocop app/controllers/fuel_entries_controller.rb app/controllers/maintenance_entries_controller.rb app/controllers/fuel_entry_images_controller.rb app/controllers/maintenance_entry_images_controller.rb spec/requests/vehicles_spec.rb`
- Passed after existing-entry upload support: `bin/ci`
- Passed after historical-entry upload fix: `bundle exec rspec spec/requests/vehicles_spec.rb`
- Passed after historical-entry upload fix: `bundle exec rspec spec/requests/vehicles_spec.rb spec/requests/backups_spec.rb spec/models/fuel_entry_spec.rb spec/models/maintenance_entry_spec.rb`
- Passed after historical-entry upload fix: `bundle exec rspec`
- Passed after historical-entry upload fix: `bin/rubocop app/controllers/fuel_entries_controller.rb app/controllers/maintenance_entries_controller.rb spec/requests/vehicles_spec.rb`
- Passed after historical-entry upload fix: `bin/ci`
- Passed after thumbnail and duplicate-image fix: `bundle exec rspec spec/requests/vehicles_spec.rb`
- Passed after thumbnail and duplicate-image fix: `bundle exec rspec spec/requests/vehicles_spec.rb spec/requests/backups_spec.rb spec/models/fuel_entry_spec.rb spec/models/maintenance_entry_spec.rb`
- Passed after thumbnail and duplicate-image fix: `bundle exec rspec`
- Passed after thumbnail and duplicate-image fix: `bin/rubocop app/controllers/fuel_entries_controller.rb app/controllers/maintenance_entries_controller.rb app/models/concerns/entry_image_validation.rb spec/requests/vehicles_spec.rb spec/models/fuel_entry_spec.rb spec/models/maintenance_entry_spec.rb`
- Passed after thumbnail and duplicate-image fix: `bin/ci`
+40
View File
@@ -0,0 +1,40 @@
# Phase 008: Backup And Restore
## Goal
Add backup and restore support for portable application data using compressed YAML files without adding new gem dependencies.
## Work
- Add a backup/restore page linked from the main vehicle dashboard.
- Export app data as a versioned YAML document compressed with gzip (`.yml.gz`).
- Include users, vehicles, maintenance schedules, fuel entries, and maintenance entries.
- Exclude authentication and runtime data, including access keys and user sessions.
- Restore uploaded backups in either merge mode or replace mode.
- Use portable references instead of raw database IDs so backups can be moved between installations.
- Support older backup versions only when an explicit migration path exists.
- Add request specs for export, merge restore, replace restore, invalid upload handling, and authentication.
## Decisions
- Backups use gzip-compressed YAML instead of zip archives because no extra gem dependency should be added.
- Any identified user may export or restore backups.
- Merge mode updates matched users, vehicles, and maintenance schedules, and creates unmatched records.
- Users are matched by normalized email.
- Vehicles are matched by VIN.
- Maintenance schedules are matched by vehicle and maintenance type.
- Fuel and maintenance entries use natural keys to avoid duplicate imports.
- Replace mode removes existing app data and imports the uploaded data inside one transaction.
- Restore recalculates vehicle odometers from imported/stored vehicle odometers and event histories.
## Deliverables
- Backup export/import services.
- Backup controller and routes.
- Backup/restore page and dashboard link.
- Request specs for backup and restore behavior.
- Phase execution notes.
## Acceptance Criteria
- Authenticated users can download a `.yml.gz` backup from the app.
- The backup contains app data only and excludes auth/session data.
- Authenticated users can restore by replacing all app data.
- Authenticated users can restore by merging portable records into existing app data.
- Invalid or unsupported uploads fail with a clear user-facing error.
- Backup and restore behavior is covered by request specs.
+37
View File
@@ -0,0 +1,37 @@
# Phase 009: Fuel And Maintenance Entry Images
## Goal
Allow fuel and maintenance entries to store multiple receipt/service images, display them only when requested, and optionally include them in portable backups.
## Work
- Use Active Storage for fuel and maintenance entry images.
- Support multiple images per entry.
- Accept only JPEG and PNG uploads.
- Enforce a 10 MB maximum per image.
- Add image upload fields to fuel and maintenance entry forms.
- Allow images to be added to existing fuel and maintenance entries.
- Load entry images inline on demand from the vehicle detail history tables.
- Show small thumbnails that link to full-size images.
- Allow users to delete individual attached images.
- Add separate backup download options for data-only and image-inclusive backups.
- Extend backup import/export to support images while preserving data-only restores.
- Deduplicate imported images by filename and checksum during merge restores.
## Deliverables
- Active Storage migrations and model attachment declarations.
- Attachment validation behavior for fuel and maintenance entries.
- Lazy inline image display and deletion UI.
- Lazy inline image upload UI for existing entries.
- Backup/export support for data-only and full image backups.
- Request and model specs for image behavior and backup image portability.
## Acceptance Criteria
- Users can attach multiple JPEG/PNG images to fuel and maintenance entries.
- Uploads over 10 MB or non-JPEG/PNG uploads are rejected.
- Vehicle detail pages do not load image thumbnails until a user requests them.
- Existing fuel and maintenance entries can add images from the history tables.
- Successful existing-entry uploads immediately show thumbnails inline.
- Requested images render inline as small thumbnails linked to full-size images.
- Users can delete individual entry images.
- Data-only backups exclude image content.
- Image-inclusive backups restore images and avoid duplicate images on merge.
+33
View File
@@ -1,4 +1,5 @@
require "rails_helper" require "rails_helper"
require "stringio"
RSpec.describe FuelEntry do RSpec.describe FuelEntry do
it "has a valid factory" do it "has a valid factory" do
@@ -57,4 +58,36 @@ RSpec.describe FuelEntry do
expect(entry).to be_valid expect(entry).to be_valid
end end
it "accepts multiple JPEG or PNG images" do
entry = build(:fuel_entry)
entry.images.attach(image_attachment("receipt-one.png", "image/png"))
entry.images.attach(image_attachment("receipt-two.jpg", "image/jpeg"))
expect(entry).to be_valid
end
it "rejects non-JPEG and non-PNG images" do
entry = build(:fuel_entry)
entry.images.attach(io: StringIO.new("not an image"), filename: "receipt.txt", content_type: "text/plain")
expect(entry).not_to be_valid
expect(entry.errors[:images]).to include("must be JPEG or PNG")
end
it "rejects images larger than 10 MB" do
entry = build(:fuel_entry)
entry.images.attach(io: StringIO.new("a" * (10.megabytes + 1)), filename: "large.png", content_type: "image/png")
expect(entry).not_to be_valid
expect(entry.errors[:images]).to include("must be 10 MB or smaller")
end
def image_attachment(filename, content_type)
{
io: StringIO.new("image content for #{filename}"),
filename: filename,
content_type: content_type
}
end
end end
+33
View File
@@ -1,4 +1,5 @@
require "rails_helper" require "rails_helper"
require "stringio"
RSpec.describe MaintenanceEntry do RSpec.describe MaintenanceEntry do
it "has a valid factory" do it "has a valid factory" do
@@ -50,4 +51,36 @@ RSpec.describe MaintenanceEntry do
expect(unknown_entry).not_to be_valid expect(unknown_entry).not_to be_valid
expect(unknown_entry.errors[:name]).to be_present expect(unknown_entry.errors[:name]).to be_present
end end
it "accepts multiple JPEG or PNG images" do
entry = build(:maintenance_entry)
entry.images.attach(image_attachment("service-one.png", "image/png"))
entry.images.attach(image_attachment("service-two.jpg", "image/jpeg"))
expect(entry).to be_valid
end
it "rejects non-JPEG and non-PNG images" do
entry = build(:maintenance_entry)
entry.images.attach(io: StringIO.new("not an image"), filename: "service.txt", content_type: "text/plain")
expect(entry).not_to be_valid
expect(entry.errors[:images]).to include("must be JPEG or PNG")
end
it "rejects images larger than 10 MB" do
entry = build(:maintenance_entry)
entry.images.attach(io: StringIO.new("a" * (10.megabytes + 1)), filename: "large.png", content_type: "image/png")
expect(entry).not_to be_valid
expect(entry.errors[:images]).to include("must be 10 MB or smaller")
end
def image_attachment(filename, content_type)
{
io: StringIO.new("image content for #{filename}"),
filename: filename,
content_type: content_type
}
end
end end
+316
View File
@@ -0,0 +1,316 @@
require "rails_helper"
require "base64"
require "digest/md5"
require "stringio"
require "tempfile"
require "zlib"
RSpec.describe "Backups" do
describe "unauthenticated access" do
it "redirects backup pages to identification" do
get backup_path
expect(response).to redirect_to(identify_path)
end
it "does not download backups" do
get download_backup_path
expect(response).to redirect_to(identify_path)
end
end
describe "GET /backup" do
before { identify_user }
it "renders the backup and restore page" do
get backup_path
expect(response).to have_http_status(:ok)
expect(response.body).to include("Backup / Restore")
expect(response.body).to include("Download backup")
expect(response.body).to include("Restore backup")
end
end
describe "GET /backup/download" do
before { identify_user }
it "downloads app data as gzip-compressed YAML" do
user = create(:user, name: "Driver", email: "driver@example.com")
vehicle = create(:vehicle, vin: "ABC123", licence_plate: "FLT1234")
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
fuel_entry = create(:fuel_entry, vehicle: vehicle, updated_by_user: user, odometer: 10_500)
fuel_entry.images.attach(image_attachment("receipt.png"))
create(:maintenance_entry, vehicle: vehicle, updated_by_user: user, name: "Oil Change", odometer: 10_600, ensure_matching_schedule: false)
AccessKey.current
UserSession.create_for!(user)
get download_backup_path
backup = YAML.safe_load(gunzip(response.body), aliases: false)
vehicle_data = backup.fetch("vehicles").first
expect(response).to have_http_status(:ok)
expect(response.media_type).to eq("application/gzip")
expect(response.headers.fetch("Content-Disposition")).to include(".yml.gz")
expect(backup.fetch("format")).to eq("car_tracker_backup")
expect(backup.fetch("version")).to eq(2)
expect(vehicle_data.fetch("vin")).to eq("ABC123")
expect(vehicle_data.fetch("fuel_entries").first.fetch("updated_by_user").fetch("email")).to eq("driver@example.com")
expect(gunzip(response.body)).not_to include("access_keys")
expect(gunzip(response.body)).not_to include("user_sessions")
expect(gunzip(response.body)).not_to include("data_base64")
end
end
describe "GET /backup/download_with_images" do
before { identify_user }
it "downloads app data and image content" do
user = create(:user, name: "Driver", email: "driver@example.com")
vehicle = create(:vehicle, vin: "ABC123", licence_plate: "FLT1234")
fuel_entry = create(:fuel_entry, vehicle: vehicle, updated_by_user: user, odometer: 10_500)
fuel_entry.images.attach(image_attachment("receipt.png"))
get download_with_images_backup_path
backup = YAML.safe_load(gunzip(response.body), aliases: false)
image_data = backup.fetch("vehicles").first.fetch("fuel_entries").first.fetch("images").first
expect(response).to have_http_status(:ok)
expect(response.headers.fetch("Content-Disposition")).to include("with-images")
expect(image_data.fetch("filename")).to eq("receipt.png")
expect(image_data.fetch("content_type")).to eq("image/png")
expect(Base64.strict_decode64(image_data.fetch("data_base64"))).to eq(png_bytes)
end
end
describe "dashboard link" do
before { identify_user }
it "shows backup and restore on the main dashboard" do
get vehicles_path
expect(response.body).to include("Backup / Restore")
expect(response.body).to include(backup_path)
end
end
describe "POST /backup/restore" do
before { identify_user }
it "merges backup data into existing records" do
existing_user = create(:user, name: "Old Name", email: "driver@example.com")
existing_vehicle = create(:vehicle, vin: "ABC123", licence_plate: "OLD123", make: "Old", current_odometer: 1_000)
existing_schedule = create(:maintenance_schedule, vehicle: existing_vehicle, maintenance_type: "Oil Change", mileage_interval: 3_000)
expect do
post restore_backup_path, params: {
mode: "merge",
backup_file: uploaded_backup(backup_payload)
}
end.to change(FuelEntry, :count).by(1)
.and change(MaintenanceEntry, :count).by(1)
expect(response).to redirect_to(backup_path)
expect(existing_user.reload.name).to eq("Driver")
expect(existing_vehicle.reload.make).to eq("Ford")
expect(existing_vehicle.licence_plate).to eq("FLT1234")
expect(existing_vehicle.current_odometer).to eq(10_600)
expect(existing_schedule.reload.mileage_interval).to eq(5_000)
expect(Vehicle.count).to eq(1)
expect(User.count).to eq(2)
end
it "does not duplicate matching entries during merge" do
post restore_backup_path, params: { mode: "merge", backup_file: uploaded_backup(backup_payload) }
post restore_backup_path, params: { mode: "merge", backup_file: uploaded_backup(backup_payload) }
expect(Vehicle.count).to eq(1)
expect(FuelEntry.count).to eq(1)
expect(MaintenanceEntry.count).to eq(1)
end
it "replaces existing app data" do
create(:vehicle, vin: "OLDVIN", licence_plate: "OLD999")
create(:user, email: "old@example.com")
AccessKey.current
post restore_backup_path, params: {
mode: "replace",
backup_file: uploaded_backup(backup_payload)
}
expect(response).to redirect_to(backup_path)
expect(Vehicle.pluck(:vin)).to eq([ "ABC123" ])
expect(User.pluck(:email)).to contain_exactly("driver@example.com")
expect(AccessKey.count).to eq(1)
end
it "rejects invalid gzip uploads" do
expect do
post restore_backup_path, params: {
mode: "merge",
backup_file: uploaded_file("not gzip")
}
end.not_to change(Vehicle, :count)
expect(response).to redirect_to(backup_path)
expect(flash[:alert]).to include("gzip-compressed YAML")
end
it "rejects unsupported backup versions" do
payload = backup_payload.merge("version" => 0)
post restore_backup_path, params: {
mode: "merge",
backup_file: uploaded_backup(payload)
}
expect(response).to redirect_to(backup_path)
expect(flash[:alert]).to include("does not have an available migration path")
end
it "restores image-inclusive backups" do
payload = backup_payload_with_images
expect do
post restore_backup_path, params: {
mode: "replace",
backup_file: uploaded_backup(payload)
}
end.to change(FuelEntry, :count).by(1)
expect(response).to redirect_to(backup_path)
expect(FuelEntry.last.images.count).to eq(1)
expect(FuelEntry.last.images.first.filename.to_s).to eq("receipt.png")
end
it "deduplicates imported images by filename and checksum during merge" do
post restore_backup_path, params: {
mode: "merge",
backup_file: uploaded_backup(backup_payload_with_images)
}
post restore_backup_path, params: {
mode: "merge",
backup_file: uploaded_backup(backup_payload_with_images)
}
expect(FuelEntry.count).to eq(1)
expect(FuelEntry.last.images.count).to eq(1)
end
end
def backup_payload
{
"format" => "car_tracker_backup",
"version" => 1,
"exported_at" => Time.current.iso8601,
"vehicles" => [
{
"vin" => "ABC123",
"licence_plate" => "FLT1234",
"make" => "Ford",
"model" => "F-150",
"year" => Date.current.year,
"color" => "White",
"current_odometer" => 10_000,
"fuel_tank_size" => "26.0",
"active" => true,
"maintenance_schedules" => [
{
"maintenance_type" => "Oil Change",
"mileage_interval" => 5_000,
"time_interval" => 180,
"baseline_odometer" => 10_000,
"baseline_date" => Date.current.iso8601,
"active" => true,
"last_status" => nil,
"last_status_changed_at" => nil
}
],
"fuel_entries" => [
{
"date" => Date.current.iso8601,
"odometer" => 10_500,
"gallons_pumped" => "18.25",
"price_paid" => "47.62",
"updated_by_user" => {
"name" => "Driver",
"email" => "driver@example.com"
}
}
],
"maintenance_entries" => [
{
"name" => "Oil Change",
"notes" => "Oil change performed.",
"date" => Date.current.iso8601,
"odometer" => 10_600,
"cost" => "89.95",
"updated_by_user" => {
"name" => "Driver",
"email" => "driver@example.com"
}
}
]
}
]
}
end
def uploaded_backup(payload)
uploaded_file(gzip(payload.to_yaml))
end
def uploaded_file(content)
file = Tempfile.new([ "backup", ".yml.gz" ])
file.binmode
file.write(content)
file.rewind
Rack::Test::UploadedFile.new(file.path, "application/gzip")
end
def backup_payload_with_images
payload = backup_payload.deep_dup.merge("version" => 2)
payload.fetch("vehicles").first.fetch("fuel_entries").first["images"] = [
{
"filename" => "receipt.png",
"content_type" => "image/png",
"checksum" => Digest::MD5.base64digest(png_bytes),
"byte_size" => png_bytes.bytesize,
"data_base64" => Base64.strict_encode64(png_bytes)
}
]
payload
end
def image_attachment(filename)
{
io: StringIO.new(png_bytes),
filename: filename,
content_type: "image/png"
}
end
def png_bytes
Base64.decode64("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=")
end
def gzip(content)
buffer = StringIO.new
Zlib::GzipWriter.wrap(buffer) { |gzip| gzip.write(content) }
buffer.string
end
def gunzip(content)
Zlib::GzipReader.wrap(StringIO.new(content), &:read)
end
def identify_user(user = create(:user))
@identified_user = user
access_key = AccessKey.current
post session_path, params: { name: user.name, email: user.email, key: access_key.raw_key }
end
end
+370
View File
@@ -1,4 +1,7 @@
require "rails_helper" require "rails_helper"
require "base64"
require "stringio"
require "tempfile"
RSpec.describe "Vehicles" do RSpec.describe "Vehicles" do
describe "unauthenticated access" do describe "unauthenticated access" do
@@ -242,6 +245,18 @@ RSpec.describe "Vehicles" do
expect(response.body).not_to include("Oil Change is overdue") expect(response.body).not_to include("Oil Change is overdue")
end end
it "shows image counts without loading image URLs" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
fuel_entry.images.attach(image_attachment("receipt.png"))
get vehicle_path(vehicle)
expect(response).to have_http_status(:ok)
expect(response.body).to include("Show images (1)")
expect(response.body).not_to include("/rails/active_storage")
end
it "logs overdue notifications only when schedule status changes" do it "logs overdue notifications only when schedule status changes" do
vehicle = create(:vehicle, current_odometer: 15_000) vehicle = create(:vehicle, current_odometer: 15_000)
schedule = create( schedule = create(
@@ -337,6 +352,45 @@ RSpec.describe "Vehicles" do
expect(FuelEntry.last.updated_by_user).to eq(@identified_user) expect(FuelEntry.last.updated_by_user).to eq(@identified_user)
end end
it "creates a fuel entry with multiple images" do
vehicle = create(:vehicle, current_odometer: 10_000)
expect do
post vehicle_fuel_entries_path(vehicle), params: {
fuel_entry: valid_fuel_entry_params.merge(images: [ uploaded_image("receipt-one.png"), uploaded_image("receipt-two.png") ])
}
end.to change(FuelEntry, :count).by(1)
expect(response).to redirect_to(vehicle_path(vehicle))
expect(FuelEntry.last.images.count).to eq(2)
end
it "rejects duplicate images when creating a fuel entry" do
vehicle = create(:vehicle, current_odometer: 10_000)
expect do
post vehicle_fuel_entries_path(vehicle), params: {
fuel_entry: valid_fuel_entry_params.merge(images: [ uploaded_image("receipt-one.png", png_bytes), uploaded_image("receipt-two.png", png_bytes) ])
}
end.not_to change(FuelEntry, :count)
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("This image is already attached to this entry")
end
it "rejects unsupported fuel entry images" do
vehicle = create(:vehicle, current_odometer: 10_000)
expect do
post vehicle_fuel_entries_path(vehicle), params: {
fuel_entry: valid_fuel_entry_params.merge(images: [ uploaded_file("receipt.txt", "text/plain", "not an image") ])
}
end.not_to change(FuelEntry, :count)
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("Images must be JPEG or PNG")
end
it "updates the vehicle odometer when the fuel odometer is newer" do it "updates the vehicle odometer when the fuel odometer is newer" do
vehicle = create(:vehicle, current_odometer: 10_000) vehicle = create(:vehicle, current_odometer: 10_000)
@@ -394,6 +448,34 @@ RSpec.describe "Vehicles" do
expect(MaintenanceEntry.last.updated_by_user).to eq(@identified_user) expect(MaintenanceEntry.last.updated_by_user).to eq(@identified_user)
end end
it "creates a maintenance entry with multiple images" do
vehicle = create(:vehicle, current_odometer: 10_000)
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
expect do
post vehicle_maintenance_entries_path(vehicle), params: {
maintenance_entry: valid_maintenance_entry_params.merge(images: [ uploaded_image("service-one.png"), uploaded_image("service-two.png") ])
}
end.to change(MaintenanceEntry, :count).by(1)
expect(response).to redirect_to(vehicle_path(vehicle))
expect(MaintenanceEntry.last.images.count).to eq(2)
end
it "rejects duplicate images when creating a maintenance entry" do
vehicle = create(:vehicle, current_odometer: 10_000)
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
expect do
post vehicle_maintenance_entries_path(vehicle), params: {
maintenance_entry: valid_maintenance_entry_params.merge(images: [ uploaded_image("service-one.png", png_bytes), uploaded_image("service-two.png", png_bytes) ])
}
end.not_to change(MaintenanceEntry, :count)
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("This image is already attached to this entry")
end
it "updates the vehicle odometer when the maintenance odometer is newer" do it "updates the vehicle odometer when the maintenance odometer is newer" do
vehicle = create(:vehicle, current_odometer: 10_000) vehicle = create(:vehicle, current_odometer: 10_000)
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change") create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
@@ -451,6 +533,270 @@ RSpec.describe "Vehicles" do
end end
end end
describe "GET /vehicles/:vehicle_id/fuel_entries/:id/images" do
before { identify_user }
it "loads fuel entry images inline" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
fuel_entry.images.attach(image_attachment("receipt.png"))
get images_vehicle_fuel_entry_path(vehicle, fuel_entry)
expect(response).to have_http_status(:ok)
expect(response.body).to include("receipt.png")
expect(response.body).to include("/rails/active_storage")
expect(response.body).not_to include("/rails/active_storage/representations")
end
end
describe "GET /vehicles/:vehicle_id/fuel_entries/:id/new_images" do
before { identify_user }
it "loads an inline upload form for an existing fuel entry" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
get new_images_vehicle_fuel_entry_path(vehicle, fuel_entry)
expect(response).to have_http_status(:ok)
expect(response.body).to include("Upload images")
expect(response.body).to include(images_vehicle_fuel_entry_path(vehicle, fuel_entry))
end
end
describe "POST /vehicles/:vehicle_id/fuel_entries/:id/images" do
before { identify_user }
it "adds images to an existing fuel entry and renders thumbnails immediately" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
expect do
post images_vehicle_fuel_entry_path(vehicle, fuel_entry), params: {
fuel_entry: { images: [ uploaded_image("receipt-one.png"), uploaded_image("receipt-two.png") ] }
}
end.to change { fuel_entry.reload.images.count }.from(0).to(2)
expect(response).to have_http_status(:ok)
expect(response.body).to include("receipt-one")
expect(response.body).to include("receipt-two")
expect(response.body).to include("/rails/active_storage")
end
it "adds images to an older fuel entry without rerunning odometer validation" do
vehicle = create(:vehicle, current_odometer: 10_000)
fuel_entry = create(:fuel_entry, vehicle: vehicle, odometer: 10_000)
vehicle.update!(current_odometer: 15_000)
expect do
post images_vehicle_fuel_entry_path(vehicle, fuel_entry), params: {
fuel_entry: { images: [ "", uploaded_image("receipt.png") ] }
}
end.to change { fuel_entry.reload.images.count }.from(0).to(1)
expect(response).to have_http_status(:ok)
expect(response.body).to include("receipt")
expect(response.body).to include("/rails/active_storage")
end
it "rejects an empty existing fuel entry image upload" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
expect do
post images_vehicle_fuel_entry_path(vehicle, fuel_entry), params: {
fuel_entry: { images: [ "" ] }
}
end.not_to change { fuel_entry.reload.images.count }
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("Images must be selected")
expect(response.body).to include("Upload images")
end
it "rejects unsupported images for an existing fuel entry" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
expect do
post images_vehicle_fuel_entry_path(vehicle, fuel_entry), params: {
fuel_entry: { images: [ uploaded_file("receipt.txt", "text/plain", "not an image") ] }
}
end.not_to change { fuel_entry.reload.images.count }
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("Images must be JPEG or PNG")
expect(response.body).to include("Upload images")
end
it "rejects duplicate images for an existing fuel entry" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
fuel_entry.images.attach(image_attachment("receipt.png"))
expect do
post images_vehicle_fuel_entry_path(vehicle, fuel_entry), params: {
fuel_entry: { images: [ uploaded_image("receipt-copy.png", png_bytes) ] }
}
end.not_to change { fuel_entry.reload.images.count }
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("This image is already attached to this entry")
expect(response.body).to include("Upload images")
end
it "allows the same image on a different fuel entry" do
vehicle = create(:vehicle)
first_entry = create(:fuel_entry, vehicle: vehicle)
second_entry = create(:fuel_entry, vehicle: vehicle)
first_entry.images.attach(image_attachment("receipt.png"))
expect do
post images_vehicle_fuel_entry_path(vehicle, second_entry), params: {
fuel_entry: { images: [ uploaded_image("receipt-copy.png", png_bytes) ] }
}
end.to change { second_entry.reload.images.count }.from(0).to(1)
expect(response).to have_http_status(:ok)
end
end
describe "GET /vehicles/:vehicle_id/maintenance_entries/:id/images" do
before { identify_user }
it "loads maintenance entry images inline" do
vehicle = create(:vehicle)
maintenance_entry = create(:maintenance_entry, vehicle: vehicle)
maintenance_entry.images.attach(image_attachment("service.png"))
get images_vehicle_maintenance_entry_path(vehicle, maintenance_entry)
expect(response).to have_http_status(:ok)
expect(response.body).to include("service.png")
expect(response.body).to include("/rails/active_storage")
expect(response.body).not_to include("/rails/active_storage/representations")
end
end
describe "GET /vehicles/:vehicle_id/maintenance_entries/:id/new_images" do
before { identify_user }
it "loads an inline upload form for an existing maintenance entry" do
vehicle = create(:vehicle)
maintenance_entry = create(:maintenance_entry, vehicle: vehicle)
get new_images_vehicle_maintenance_entry_path(vehicle, maintenance_entry)
expect(response).to have_http_status(:ok)
expect(response.body).to include("Upload images")
expect(response.body).to include(images_vehicle_maintenance_entry_path(vehicle, maintenance_entry))
end
end
describe "POST /vehicles/:vehicle_id/maintenance_entries/:id/images" do
before { identify_user }
it "adds images to an existing maintenance entry and renders thumbnails immediately" do
vehicle = create(:vehicle)
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
maintenance_entry = create(:maintenance_entry, vehicle: vehicle)
expect do
post images_vehicle_maintenance_entry_path(vehicle, maintenance_entry), params: {
maintenance_entry: { images: [ uploaded_image("service-one.png"), uploaded_image("service-two.png") ] }
}
end.to change { maintenance_entry.reload.images.count }.from(0).to(2)
expect(response).to have_http_status(:ok)
expect(response.body).to include("service-one")
expect(response.body).to include("service-two")
expect(response.body).to include("/rails/active_storage")
end
it "ignores blank image params for an existing maintenance entry" do
vehicle = create(:vehicle)
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
maintenance_entry = create(:maintenance_entry, vehicle: vehicle)
expect do
post images_vehicle_maintenance_entry_path(vehicle, maintenance_entry), params: {
maintenance_entry: { images: [ "", uploaded_image("service.png") ] }
}
end.to change { maintenance_entry.reload.images.count }.from(0).to(1)
expect(response).to have_http_status(:ok)
expect(response.body).to include("service")
end
it "rejects unsupported images for an existing maintenance entry" do
vehicle = create(:vehicle)
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
maintenance_entry = create(:maintenance_entry, vehicle: vehicle)
expect do
post images_vehicle_maintenance_entry_path(vehicle, maintenance_entry), params: {
maintenance_entry: { images: [ uploaded_file("service.txt", "text/plain", "not an image") ] }
}
end.not_to change { maintenance_entry.reload.images.count }
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("Images must be JPEG or PNG")
expect(response.body).to include("Upload images")
end
it "rejects duplicate images for an existing maintenance entry" do
vehicle = create(:vehicle)
create(:maintenance_schedule, vehicle: vehicle, maintenance_type: "Oil Change")
maintenance_entry = create(:maintenance_entry, vehicle: vehicle)
maintenance_entry.images.attach(image_attachment("service.png"))
expect do
post images_vehicle_maintenance_entry_path(vehicle, maintenance_entry), params: {
maintenance_entry: { images: [ uploaded_image("service-copy.png", png_bytes) ] }
}
end.not_to change { maintenance_entry.reload.images.count }
expect(response).to have_http_status(:unprocessable_content)
expect(response.body).to include("This image is already attached to this entry")
expect(response.body).to include("Upload images")
end
end
describe "DELETE /vehicles/:vehicle_id/fuel_entries/:fuel_entry_id/images/:attachment_id" do
before { identify_user }
it "deletes one fuel entry image" do
vehicle = create(:vehicle)
fuel_entry = create(:fuel_entry, vehicle: vehicle)
fuel_entry.images.attach(image_attachment("receipt.png"))
attachment = fuel_entry.images.first
expect do
delete vehicle_fuel_entry_image_path(vehicle, fuel_entry, attachment)
end.to change { fuel_entry.reload.images.count }.from(1).to(0)
expect(response).to redirect_to(images_vehicle_fuel_entry_path(vehicle, fuel_entry))
end
end
describe "DELETE /vehicles/:vehicle_id/maintenance_entries/:maintenance_entry_id/images/:attachment_id" do
before { identify_user }
it "deletes one maintenance entry image" do
vehicle = create(:vehicle)
maintenance_entry = create(:maintenance_entry, vehicle: vehicle)
maintenance_entry.images.attach(image_attachment("service.png"))
attachment = maintenance_entry.images.first
expect do
delete vehicle_maintenance_entry_image_path(vehicle, maintenance_entry, attachment)
end.to change { maintenance_entry.reload.images.count }.from(1).to(0)
expect(response).to redirect_to(images_vehicle_maintenance_entry_path(vehicle, maintenance_entry))
end
end
describe "GET /vehicles/new" do describe "GET /vehicles/new" do
before { identify_user } before { identify_user }
@@ -584,4 +930,28 @@ RSpec.describe "Vehicles" do
access_key = AccessKey.current access_key = AccessKey.current
post session_path, params: { name: user.name, email: user.email, key: access_key.raw_key } post session_path, params: { name: user.name, email: user.email, key: access_key.raw_key }
end end
def image_attachment(filename)
{
io: StringIO.new(png_bytes),
filename: filename,
content_type: "image/png"
}
end
def uploaded_image(filename, content = nil)
uploaded_file(filename, "image/png", content || "image content for #{filename}")
end
def uploaded_file(filename, content_type, content)
file = Tempfile.new([ File.basename(filename, ".*"), File.extname(filename) ])
file.binmode
file.write(content)
file.rewind
Rack::Test::UploadedFile.new(file.path, content_type)
end
def png_bytes
Base64.decode64("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=")
end
end end