Initial commit: Rails port of Simple Aircraft Manager

Rails 8.1 + SQLite rewrite of marbindrakon/simple-aircraft-manager,
designed to self-host as a single container (Solid Queue/Cache/Cable,
Active Storage on disk, Hotwire + importmap, Tailwind).

- Airworthiness engine ported from health/services.py (ADs, grounding
  squawks, inspection recurrency, component replacement)
- Hours updates and flight logs cascading to in-service components,
  optional airworthiness enforcement
- Components, squawks, ADs, inspections, logbook, documents, major
  records, oil/fuel consumption stats and charts, activity log
- Admin/owner/pilot RBAC and public share links (status/maintenance)
- Docker Compose and Kamal deployment, env-driven production config
- Service and integration tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-04 17:59:08 -05:00
commit 38df19c331
264 files changed
+8365

No files matched your search

View File
Whitespace-only changes.
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
/*
* This is a manifest file that'll be compiled into application.css.
*
* With Propshaft, assets are served efficiently without preprocessing steps. You can still include
* application-wide styles in this file, but keep in mind that CSS precedence will follow the standard
* cascading order, meaning styles declared later in the document or manifest will override earlier ones,
* depending on specificity.
*
* Consider organizing styles into separate files for maintainability.
*/
+36
View File
@@ -0,0 +1,36 @@
@import "tailwindcss";
@utility btn { @apply inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm font-medium shadow-sm transition cursor-pointer disabled:opacity-50; }
@utility btn-primary { @apply btn bg-sky-700 text-white hover:bg-sky-800; }
@utility btn-secondary { @apply btn bg-white text-slate-700 ring-1 ring-slate-300 ring-inset hover:bg-slate-50; }
@utility btn-danger { @apply btn bg-white text-red-700 ring-1 ring-red-300 ring-inset hover:bg-red-50; }
@utility btn-sm { @apply px-2 py-1 text-xs; }
@utility link { @apply text-sky-700 hover:underline; }
@utility card { @apply rounded-lg bg-white shadow-sm ring-1 ring-slate-200; }
@utility card-header { @apply flex flex-wrap items-center justify-between gap-3 border-b border-slate-200 px-4 py-3; }
@utility card-title { @apply text-base font-semibold text-slate-900; }
@utility card-body { @apply p-4; }
@utility label { @apply block text-sm font-medium text-slate-700 mb-1; }
@utility input { @apply block w-full rounded-md border-0 px-2.5 py-1.5 text-sm text-slate-900 shadow-sm ring-1 ring-slate-300 ring-inset placeholder:text-slate-400 focus:ring-2 focus:ring-sky-600 focus:outline-none bg-white; }
@utility hint { @apply mt-1 text-xs text-slate-500; }
@utility field-error { @apply mt-1 text-xs text-red-600; }
@utility table {
@apply min-w-full text-sm;
& th { @apply px-3 py-2 text-left text-xs font-semibold uppercase tracking-wide text-slate-500 bg-slate-50; }
& td { @apply px-3 py-2 align-top text-slate-700; }
& tbody tr { @apply border-t border-slate-100; }
& tbody tr:hover { @apply bg-slate-50; }
}
@utility badge { @apply inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium ring-1 ring-inset whitespace-nowrap; }
@utility badge-red { @apply badge bg-red-50 text-red-700 ring-red-600/20; }
@utility badge-orange { @apply badge bg-amber-50 text-amber-800 ring-amber-600/30; }
@utility badge-green { @apply badge bg-emerald-50 text-emerald-700 ring-emerald-600/20; }
@utility badge-blue { @apply badge bg-sky-50 text-sky-700 ring-sky-600/20; }
@utility badge-gray { @apply badge bg-slate-100 text-slate-600 ring-slate-500/20; }
@utility tab { @apply whitespace-nowrap border-b-2 border-transparent px-3 py-2 text-sm font-medium text-slate-500 hover:border-slate-300 hover:text-slate-700; }
@utility tab-active { @apply border-sky-700 text-sky-700; }
@@ -0,0 +1,16 @@
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
set_current_user || reject_unauthorized_connection
end
private
def set_current_user
if session = Session.find_by(id: cookies.signed[:session_id])
self.current_user = session.user
end
end
end
end
@@ -0,0 +1,57 @@
class AdCompliancesController < ApplicationController
include AircraftScoped
before_action :require_owner!
before_action :set_compliance, only: %i[edit update destroy]
def new
ad = @aircraft.applicable_ads.find_by(id: params[:ad_id])
@compliance = AdCompliance.new(aircraft: @aircraft, airworthiness_directive: ad, date_complied: Date.current,
aircraft_hours_at_compliance: @aircraft.tach_time)
if ad&.recurring? && ad.recurring_hours.to_d > 0
@compliance.next_due_at_time = @aircraft.current_hours + ad.recurring_hours
end
end
def create
@compliance = AdCompliance.new(compliance_params.merge(aircraft: @aircraft))
if @compliance.save
log_event("ad", "Compliance recorded: #{@compliance.airworthiness_directive.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance recorded."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @compliance.update(compliance_params)
log_event("ad", "Compliance updated: #{@compliance.airworthiness_directive.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@compliance.destroy!
log_event("ad", "Compliance deleted: #{@compliance.airworthiness_directive.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance record deleted."
end
private
def set_compliance = @compliance = AdCompliance.for_aircraft(@aircraft).find(params[:id])
def compliance_params
p = params.require(:ad_compliance).permit(
:airworthiness_directive_id, :date_complied, :compliance_notes, :permanent, :next_due_at_time,
:aircraft_hours_at_compliance, :logbook_entry_id, :inspection_record_id, :component_id
)
p[:airworthiness_directive_id] = scoped_id(@aircraft.applicable_ads, p[:airworthiness_directive_id])
p[:logbook_entry_id] = scoped_id(@aircraft.logbook_entries, p[:logbook_entry_id])
p[:inspection_record_id] = scoped_id(InspectionRecord.for_aircraft(@aircraft), p[:inspection_record_id])
p[:component_id] = scoped_id(@aircraft.components, p[:component_id])
p
end
end
@@ -0,0 +1,44 @@
class Admin::ComponentTypesController < ApplicationController
before_action :require_admin!
before_action :set_type, only: %i[edit update destroy]
def index
@component_types = ComponentType.ordered
end
def new
@component_type = ComponentType.new
end
def create
@component_type = ComponentType.new(type_params)
if @component_type.save
redirect_to admin_component_types_path, notice: "Component type created."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @component_type.update(type_params)
redirect_to admin_component_types_path, notice: "Component type updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
if @component_type.destroy
redirect_to admin_component_types_path, notice: "Component type deleted."
else
redirect_to admin_component_types_path, alert: @component_type.errors.full_messages.to_sentence
end
end
private
def set_type = @component_type = ComponentType.find(params[:id])
def type_params = params.require(:component_type).permit(:name, :consumable)
end
+50
View File
@@ -0,0 +1,50 @@
class Admin::UsersController < ApplicationController
before_action :require_admin!
before_action :set_user, only: %i[edit update destroy]
def index
@users = User.order(:email_address).includes(aircraft_roles: :aircraft)
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
@user.admin = admin_flag
if @user.save
redirect_to admin_users_path, notice: "User #{@user.email_address} created."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
attrs = user_params
attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank?
if @user == current_user && !admin_flag
return redirect_to admin_users_path, alert: "You can't remove your own admin rights."
end
@user.admin = admin_flag
if @user.update(attrs)
redirect_to admin_users_path, notice: "User updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
return redirect_to admin_users_path, alert: "You can't delete yourself." if @user == current_user
@user.destroy!
redirect_to admin_users_path, notice: "User deleted."
end
private
def set_user = @user = User.find(params[:id])
def user_params = params.require(:user).permit(:name, :email_address, :password, :password_confirmation)
def admin_flag = params.dig(:user, :admin) == "1"
end
+74
View File
@@ -0,0 +1,74 @@
class AircraftController < ApplicationController
include AircraftScoped
skip_before_action :set_aircraft, only: %i[index new create]
before_action :require_owner!, only: %i[edit update destroy]
def index
@aircraft_list = current_user.accessible_aircraft.ordered.with_attached_picture
end
def show
@airworthiness = @aircraft.airworthiness
@active_squawks = @aircraft.squawks.active.by_priority.includes(:component, :reported_by)
@recent_events = @aircraft.events.includes(:user).limit(8)
@notes = @aircraft.notes.recent_first.includes(:user).limit(5)
@oil = ConsumptionStats.new(@aircraft, "oil")
@fuel = ConsumptionStats.new(@aircraft, "fuel")
end
def new
@aircraft = Aircraft.new
end
def create
@aircraft = Aircraft.new(aircraft_params)
Aircraft.transaction do
@aircraft.save!
@aircraft.roles.create!(user: current_user, role: "owner")
@aircraft.log_event!("aircraft", "Aircraft created")
end
redirect_to @aircraft, notice: "#{@aircraft.tail_number} added."
rescue ActiveRecord::RecordInvalid
render :new, status: :unprocessable_entity
end
def edit; end
def update
if @aircraft.update(aircraft_params)
log_event("aircraft", "Aircraft details updated")
redirect_to @aircraft, notice: "Aircraft updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@aircraft.destroy!
redirect_to root_path, notice: "#{@aircraft.tail_number} deleted."
end
# Pilots and above: set absolute tach/hobbs readings.
def update_hours
delta = HoursService.new(@aircraft).update_hours!(
tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time]
)
redirect_to @aircraft, notice: "Hours updated (#{delta >= 0 ? '+' : ''}#{delta})."
rescue AircraftGroundedError => e
redirect_to @aircraft, alert: e.message
rescue ArgumentError
redirect_to @aircraft, alert: "Enter a valid tach reading."
end
private
def aircraft_param = params[:id]
def aircraft_params
params.require(:aircraft).permit(
:tail_number, :make, :model, :serial_number, :description, :purchased, :status,
:tach_time, :tach_time_offset, :hobbs_time, :hobbs_time_offset,
:airworthiness_enforcement, :picture
)
end
end
@@ -0,0 +1,54 @@
# Owner-only: manage who can access the aircraft, and its public share links.
class AircraftRolesController < ApplicationController
include AircraftScoped
before_action :require_owner!
def index
@roles = @aircraft.roles.includes(:user).order(:role, :created_at)
@share_tokens = @aircraft.share_tokens.order(created_at: :desc).includes(:created_by)
end
def create
user = User.find_by(email_address: params[:email_address].to_s.strip.downcase)
unless user
return redirect_to aircraft_aircraft_roles_path(@aircraft),
alert: "No user with that email. Ask an administrator to create their account first."
end
role = @aircraft.roles.new(user: user, role: params[:role])
if role.save
log_event("role", "#{user.display_name} added as #{role.role}")
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "#{user.display_name} added."
else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence
end
end
def update
role = @aircraft.roles.find(params[:id])
if demoting_last_owner?(role, params[:role])
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner."
end
role.update!(role: params[:role])
log_event("role", "#{role.user.display_name} changed to #{role.role}")
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Role updated."
end
def destroy
role = @aircraft.roles.find(params[:id])
if role.user == current_user
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "You can't remove yourself."
end
if demoting_last_owner?(role, nil)
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner."
end
role.destroy!
log_event("role", "#{role.user.display_name} removed")
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Access removed."
end
private
def demoting_last_owner?(role, new_role)
role.role == "owner" && new_role != "owner" && @aircraft.roles.owners.count <= 1
end
end
@@ -0,0 +1,74 @@
class AirworthinessDirectivesController < ApplicationController
include AircraftScoped
include Applicability
before_action :require_owner!, except: :index
before_action :set_ad, only: %i[edit update destroy]
def index
@rows = Compliance.ad_rows(@aircraft)
@history = AdCompliance.for_aircraft(@aircraft).recent_first.includes(:airworthiness_directive, :component)
@attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner?
end
def new
@ad = AirworthinessDirective.new
@applies_to_airframe = true
end
def create
@ad = AirworthinessDirective.new(ad_params)
AirworthinessDirective.transaction do
@ad.save!
apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end
log_event("ad", "#{@ad.bulletin_label} added: #{@ad.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} added."
rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe?
render :new, status: :unprocessable_entity
end
# Link an AD that already exists (e.g. tracked on another aircraft).
def attach
ad = AirworthinessDirective.find(params[:airworthiness_directive_id])
ad.aircraft << @aircraft unless ad.aircraft.include?(@aircraft)
log_event("ad", "#{ad.bulletin_label} linked: #{ad.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{ad.name} linked."
end
def edit
@applies_to_airframe = @ad.aircraft.include?(@aircraft)
end
def update
AirworthinessDirective.transaction do
@ad.update!(ad_params)
apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end
log_event("ad", "#{@ad.bulletin_label} updated: #{@ad.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} updated."
rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe?
render :edit, status: :unprocessable_entity
end
# Removes the AD from this aircraft (the shared AD record survives if other aircraft use it).
def destroy
detach_from_aircraft(@ad)
log_event("ad", "#{@ad.bulletin_label} removed: #{@ad.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.name} removed from #{@aircraft.tail_number}."
end
private
def set_ad = @ad = @aircraft.applicable_ads.find(params[:id])
def ad_params
p = params.require(:airworthiness_directive).permit(
:name, :short_description, :required_action, :compliance_type, :trigger_condition, :recurring,
:recurring_hours, :recurring_months, :recurring_days, :bulletin_type, :mandatory, :document_id
)
p[:document_id] = scoped_id(@aircraft.documents, p[:document_id])
p
end
end
+28
View File
@@ -0,0 +1,28 @@
class ApplicationController < ActionController::Base
default_form_builder AppFormBuilder
include Authentication
allow_browser versions: :modern
prepend_before_action :redirect_to_setup
helper_method :current_user
rescue_from ActiveRecord::RecordNotFound do
respond_to do |format|
format.html { render "errors/not_found", status: :not_found, layout: (authenticated? ? "application" : "public") }
format.any { head :not_found }
end
end
private
def current_user = Current.user
# First run: no users yet → create the initial admin.
def redirect_to_setup
redirect_to new_setup_path if !User.exists? && !is_a?(SetupController)
end
def require_admin!
redirect_to root_path, alert: "Admins only." unless current_user&.admin?
end
end
+90
View File
@@ -0,0 +1,90 @@
class ComponentsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
before_action :set_component, only: %i[show edit update destroy reset_service]
def index
all = @aircraft.components.includes(:component_type, :parent_component).order(:install_location)
@show_disposed = params[:disposed].present?
all = all.where.not(status: "DISPOSED") unless @show_disposed
# Depth-first tree order: parents followed by their children.
by_parent = all.group_by(&:parent_component_id)
@rows = []
walk = ->(parent_id, depth) do
(by_parent[parent_id] || []).sort_by { [ _1.component_type.name, _1.install_location.to_s ] }.each do |c|
@rows << [ c, depth ]
walk.(c.id, depth + 1)
end
end
walk.(nil, 0)
orphans = all.to_a - @rows.map(&:first) # children whose parent is filtered out
orphans.each { @rows << [ _1, 0 ] }
end
def show
@squawks = @component.squawks.by_priority
end
def new
@component = @aircraft.components.new(date_in_service: Date.current, status: "IN-USE",
parent_component_id: params[:parent_id])
end
def create
@component = @aircraft.components.new(component_params)
if @component.save
log_event("component", "Component added: #{@component}")
redirect_to aircraft_components_path(@aircraft), notice: "Component added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @component.update(component_params)
log_event("component", "Component updated: #{@component}")
redirect_to aircraft_components_path(@aircraft), notice: "Component updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@component.destroy!
log_event("component", "Component deleted: #{@component}")
redirect_to aircraft_components_path(@aircraft), notice: "Component deleted."
end
# Always zeroes hours since overhaul; reset_in_service=1 also zeroes the
# in-service clock (use when the part was physically replaced).
def reset_service
replaced = params[:reset_in_service] == "1"
@component.reset_service!(reset_in_service: replaced)
log_event("component", "#{replaced ? 'Replaced' : 'Serviced'}: #{@component}")
redirect_to aircraft_components_path(@aircraft), notice: "#{@component} #{replaced ? 'replaced' : 'serviced'}."
end
private
def set_component
@component = @aircraft.components.find(params[:id])
end
def component_params
params.require(:component).permit(
:component_type_id, :parent_component_id, :manufacturer, :model, :serial_number,
:install_location, :notes, :status, :date_in_service, :hours_in_service,
:hours_since_overhaul, :overhaul_date, :tbo_hours, :tbo_days, :inspection_hours,
:inspection_days, :replacement_hours, :replacement_days, :tbo_critical, :on_condition,
:inspection_critical, :replacement_critical
).tap do |p|
# Owners can create a component type inline instead of asking an admin.
if (name = params[:new_component_type].to_s.strip).present?
type = ComponentType.where("lower(name) = ?", name.downcase).first || ComponentType.create!(name: name)
p[:component_type_id] = type.id
end
end
end
end
View File
Whitespace-only changes.
@@ -0,0 +1,46 @@
# Scopes a controller to one aircraft the current user can access and exposes
# role helpers. Unknown and inaccessible aircraft both 404 (enumeration-safe).
#
# Access matrix (mirrors the original):
# admin – everything
# owner – everything on their aircraft
# pilot – view all; update hours; create squawks, notes, oil/fuel, flight logs
module AircraftScoped
extend ActiveSupport::Concern
included do
before_action :set_aircraft
helper_method :current_role, :owner?, :can_write?
end
private
def aircraft_param = params[:aircraft_id]
def set_aircraft
@aircraft = current_user.accessible_aircraft.find(aircraft_param)
end
def current_role
@current_role ||= current_user.role_for(@aircraft)
end
# Owner-level write access (admins included).
def owner? = current_role.in?(%w[admin owner])
alias_method :can_write?, :owner?
def require_owner!
return if owner?
redirect_back fallback_location: aircraft_path(@aircraft),
alert: "Only owners can do that."
end
# Returns id only if it belongs to the given (aircraft-scoped) relation; else nil.
def scoped_id(scope, id)
id.present? && scope.where(id: id).exists? ? id : nil
end
def log_event(category, name, notes: nil)
@aircraft.log_event!(category, name, notes: notes)
end
end
+38
View File
@@ -0,0 +1,38 @@
# ADs and inspection types are shared reference data that can apply to many
# aircraft. From an aircraft's page we only ever touch *this* aircraft's links:
# the airframe itself and/or some of its components.
module Applicability
extend ActiveSupport::Concern
private
def apply_applicability(record, to_airframe:, component_ids:)
mine = @aircraft.components.where(id: Array(component_ids).compact_blank).to_a
others = record.components.where.not(aircraft_id: @aircraft.id).to_a
record.components = others + mine
if to_airframe
record.aircraft << @aircraft unless record.aircraft.include?(@aircraft)
else
record.aircraft.delete(@aircraft)
end
# Never let a record silently drop off this aircraft entirely.
record.aircraft << @aircraft if mine.empty? && !to_airframe
end
def detach_from_aircraft(record)
record.aircraft.delete(@aircraft)
record.components.delete(*record.components.where(aircraft_id: @aircraft.id))
record.destroy if record.aircraft.empty? && record.components.empty? && orphan_deletable?(record)
end
def orphan_deletable?(record)
case record
when AirworthinessDirective then record.ad_compliances.none?
when InspectionType then record.inspection_records.none?
else false
end
end
def applies_to_airframe? = params[:applies_to_airframe] == "1"
def applicable_component_ids = params[:component_ids]
end
@@ -0,0 +1,52 @@
module Authentication
extend ActiveSupport::Concern
included do
before_action :require_authentication
helper_method :authenticated?
end
class_methods do
def allow_unauthenticated_access(**options)
skip_before_action :require_authentication, **options
end
end
private
def authenticated?
resume_session
end
def require_authentication
resume_session || request_authentication
end
def resume_session
Current.session ||= find_session_by_cookie
end
def find_session_by_cookie
Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id]
end
def request_authentication
session[:return_to_after_authenticating] = request.url
redirect_to new_session_path
end
def after_authentication_url
session.delete(:return_to_after_authenticating) || root_url
end
def start_new_session_for(user)
user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip).tap do |session|
Current.session = session
cookies.signed.permanent[:session_id] = { value: session.id, httponly: true, same_site: :lax }
end
end
def terminate_session
Current.session.destroy
cookies.delete(:session_id)
end
end
@@ -0,0 +1,53 @@
class ConsumableRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
before_action :set_record, only: %i[edit update destroy]
def index
@oil = ConsumptionStats.new(@aircraft, "oil")
@fuel = ConsumptionStats.new(@aircraft, "fuel")
@records = @aircraft.consumable_records.recent_first.limit(200)
end
def new
type = params[:type].in?(ConsumableRecord::TYPES.keys) ? params[:type] : "oil"
@record = @aircraft.consumable_records.new(record_type: type, date: Date.current,
flight_hours: @aircraft.tach_time)
end
def create
@record = @aircraft.consumable_records.new(record_params)
if @record.save
log_event(@record.record_type, "#{@record.record_type.capitalize} added: #{@record.quantity_added} #{@record.unit}")
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @record.update(record_params)
log_event(@record.record_type, "#{@record.record_type.capitalize} record updated")
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@record.destroy!
log_event(@record.record_type, "#{@record.record_type.capitalize} record deleted")
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record deleted."
end
private
def set_record = @record = @aircraft.consumable_records.find(params[:id])
def record_params
params.require(:consumable_record).permit(:record_type, :date, :quantity_added, :level_after,
:consumable_type, :flight_hours, :notes, :excluded_from_averages)
end
end
@@ -0,0 +1,41 @@
class DocumentCollectionsController < ApplicationController
include AircraftScoped
before_action :require_owner!
before_action :set_collection, only: %i[edit update destroy]
def new
@collection = @aircraft.document_collections.new
end
def create
@collection = @aircraft.document_collections.new(collection_params)
if @collection.save
log_event("document", "Collection created: #{@collection.name}")
redirect_to aircraft_documents_path(@aircraft), notice: "Collection created."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @collection.update(collection_params)
log_event("document", "Collection updated: #{@collection.name}")
redirect_to aircraft_documents_path(@aircraft), notice: "Collection updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@collection.destroy!
log_event("document", "Collection deleted: #{@collection.name}")
redirect_to aircraft_documents_path(@aircraft), notice: "Collection and its documents deleted."
end
private
def set_collection = @collection = @aircraft.document_collections.find(params[:id])
def collection_params = params.require(:document_collection).permit(:name, :description, :visibility, :starred)
end
+62
View File
@@ -0,0 +1,62 @@
class DocumentsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
before_action :set_document, only: %i[show edit update destroy]
def index
@collections = @aircraft.document_collections.ordered.includes(documents: { pages_attachments: :blob })
@uncollected = @aircraft.documents.where(document_collection_id: nil).ordered.includes(pages_attachments: :blob)
end
def show
@page = (params[:page] || 1).to_i.clamp(1, [ @document.pages.size, 1 ].max)
end
def new
@document = @aircraft.documents.new(document_collection_id: params[:collection_id])
end
def create
@document = @aircraft.documents.new(document_params)
if @document.save
log_event("document", "Document added: #{@document.name}")
redirect_to aircraft_document_path(@aircraft, @document), notice: "Document added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
attrs = document_params
new_pages = attrs.delete(:pages)
@document.assign_attributes(attrs)
@document.pages.attach(new_pages) if new_pages.present?
Array(params[:remove_page_ids]).each { |id| @document.pages.find_by(id: id)&.purge_later }
if @document.save
log_event("document", "Document updated: #{@document.name}")
redirect_to aircraft_document_path(@aircraft, @document), notice: "Document updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@document.destroy!
log_event("document", "Document deleted: #{@document.name}")
redirect_to aircraft_documents_path(@aircraft), notice: "Document deleted."
end
private
def set_document = @document = @aircraft.documents.find(params[:id])
def document_params
p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, pages: [])
p[:pages]&.compact_blank!
p.delete(:pages) if p[:pages].blank?
p[:document_collection_id] = scoped_id(@aircraft.document_collections, p[:document_collection_id])
p
end
end
+10
View File
@@ -0,0 +1,10 @@
class EventsController < ApplicationController
include AircraftScoped
def index
@category = params[:category].presence_in(AircraftEvent::CATEGORIES.keys)
scope = @aircraft.events.includes(:user)
scope = scope.where(category: @category) if @category
@events = scope.limit(200)
end
end
+47
View File
@@ -0,0 +1,47 @@
class FlightLogsController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: :destroy
def index
@flight_logs = @aircraft.flight_logs.recent_first.includes(:user)
end
def show
@flight_log = @aircraft.flight_logs.find(params[:id])
end
def new
@flight_log = @aircraft.flight_logs.new(date: Date.current, tach_out: @aircraft.tach_time,
hobbs_out: @aircraft.hobbs_time)
end
def create
@flight_log = @aircraft.flight_logs.new(flight_log_params)
if @flight_log.valid?
HoursService.new(@aircraft).log_flight!(@flight_log)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight logged (#{@flight_log.tach_time} hrs)."
else
render :new, status: :unprocessable_entity
end
rescue AircraftGroundedError => e
flash.now[:alert] = e.message
render :new, status: :conflict
end
# Deleting a flight does not roll back hours; correct those with an hours update.
def destroy
@aircraft.flight_logs.find(params[:id]).destroy!
log_event("flight", "Flight log deleted")
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight log deleted. Aircraft hours were not changed."
end
private
def flight_log_params
params.require(:flight_log).permit(
:date, :tach_time, :tach_out, :tach_in, :hobbs_time, :hobbs_out, :hobbs_in,
:departure_location, :destination_location, :route, :oil_added, :oil_added_type,
:oil_level_after, :fuel_added, :fuel_added_type, :fuel_level_after, :notes, :track_log
)
end
end
@@ -0,0 +1,51 @@
class InspectionRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!
before_action :set_record, only: %i[edit update destroy]
def new
@record = InspectionRecord.new(aircraft: @aircraft, date: Date.current,
aircraft_hours: @aircraft.tach_time,
inspection_type_id: params[:inspection_type_id])
end
def create
@record = InspectionRecord.new(record_params.merge(aircraft: @aircraft))
if @record.save
log_event("inspection", "Inspection completed: #{@record.inspection_type.name}")
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection recorded."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @record.update(record_params)
log_event("inspection", "Inspection record updated: #{@record.inspection_type.name}")
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@record.destroy!
log_event("inspection", "Inspection record deleted: #{@record.inspection_type.name}")
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record deleted."
end
private
def set_record = @record = InspectionRecord.for_aircraft(@aircraft).find(params[:id])
def record_params
p = params.require(:inspection_record).permit(:inspection_type_id, :date, :aircraft_hours, :notes,
:logbook_entry_id, :component_id)
p[:inspection_type_id] = scoped_id(@aircraft.applicable_inspection_types, p[:inspection_type_id])
p[:logbook_entry_id] = scoped_id(@aircraft.logbook_entries, p[:logbook_entry_id])
p[:component_id] = scoped_id(@aircraft.components, p[:component_id])
p
end
end
@@ -0,0 +1,56 @@
class InspectionTypesController < ApplicationController
include AircraftScoped
include Applicability
before_action :require_owner!
before_action :set_type, only: %i[edit update destroy]
def new
@inspection_type = InspectionType.new(required: true, recurring: true)
@applies_to_airframe = true
end
def create
@inspection_type = InspectionType.new(type_params)
InspectionType.transaction do
@inspection_type.save!
apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end
log_event("inspection", "Inspection type added: #{@inspection_type.name}")
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type added."
rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe?
render :new, status: :unprocessable_entity
end
def edit
@applies_to_airframe = @inspection_type.aircraft.include?(@aircraft)
end
def update
InspectionType.transaction do
@inspection_type.update!(type_params)
apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end
log_event("inspection", "Inspection type updated: #{@inspection_type.name}")
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type updated."
rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe?
render :edit, status: :unprocessable_entity
end
def destroy
detach_from_aircraft(@inspection_type)
log_event("inspection", "Inspection type removed: #{@inspection_type.name}")
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection removed from #{@aircraft.tail_number}."
end
private
def set_type
@inspection_type = @aircraft.applicable_inspection_types.find(params[:id])
end
def type_params
params.require(:inspection_type).permit(:name, :recurring, :required, :recurring_hours, :recurring_days, :recurring_months)
end
end
@@ -0,0 +1,8 @@
class InspectionsController < ApplicationController
include AircraftScoped
def index
@rows = Compliance.inspection_rows(@aircraft)
@history = InspectionRecord.for_aircraft(@aircraft).recent_first.includes(:inspection_type, :component, :logbook_entry)
end
end
@@ -0,0 +1,57 @@
class LogbookEntriesController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
before_action :set_entry, only: %i[show edit update destroy]
def index
@query = params[:q]
@log_type = params[:log_type].presence
scope = @aircraft.logbook_entries.search(@query).recent_first.includes(:document)
scope = scope.where(log_type: @log_type) if @log_type
@entries = scope.limit(500)
end
def show; end
def new
@entry = @aircraft.logbook_entries.new(date: Date.current, aircraft_hours_at_entry: @aircraft.tach_time)
end
def create
@entry = @aircraft.logbook_entries.new(entry_params)
if @entry.save
log_event("logbook", "Logbook entry added (#{@entry.date})")
redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @entry.update(entry_params)
log_event("logbook", "Logbook entry updated (#{@entry.date})")
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Logbook entry updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@entry.destroy!
log_event("logbook", "Logbook entry deleted (#{@entry.date})")
redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry deleted."
end
private
def set_entry = @entry = @aircraft.logbook_entries.find(params[:id])
def entry_params
p = params.require(:logbook_entry).permit(:log_type, :entry_type, :date, :text, :signoff_person,
:signoff_location, :aircraft_hours_at_entry, :document_id, :page_number)
p[:document_id] = scoped_id(@aircraft.documents, p[:document_id])
p
end
end
@@ -0,0 +1,59 @@
class MajorRecordsController < ApplicationController
include AircraftScoped
before_action :require_owner!, except: %i[index show]
before_action :set_record, only: %i[show edit update destroy]
def index
@records = @aircraft.major_records.recent_first.includes(:component)
end
def show; end
def new
@record = @aircraft.major_records.new(record_type: params[:type] || "repair", date_performed: Date.current,
aircraft_hours: @aircraft.tach_time)
end
def create
@record = @aircraft.major_records.new(record_params)
if @record.save
log_event("major_record", "#{@record.type_label} added: #{@record.title}")
redirect_to aircraft_major_records_path(@aircraft), notice: "Record added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @record.update(record_params)
log_event("major_record", "#{@record.type_label} updated: #{@record.title}")
redirect_to aircraft_major_record_path(@aircraft, @record), notice: "Record updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@record.destroy!
log_event("major_record", "#{@record.type_label} deleted: #{@record.title}")
redirect_to aircraft_major_records_path(@aircraft), notice: "Record deleted."
end
private
def set_record = @record = @aircraft.major_records.find(params[:id])
def record_params
p = params.require(:major_record).permit(
:record_type, :title, :description, :date_performed, :performed_by, :component_id,
:form_337_document_id, :stc_number, :stc_holder, :stc_document_id, :logbook_entry_id,
:aircraft_hours, :has_ica, :ica_notes, :notes
)
p[:component_id] = scoped_id(@aircraft.components, p[:component_id])
p[:logbook_entry_id] = scoped_id(@aircraft.logbook_entries, p[:logbook_entry_id])
%i[form_337_document_id stc_document_id].each { |k| p[k] = scoped_id(@aircraft.documents, p[k]) }
p
end
end
+45
View File
@@ -0,0 +1,45 @@
class NotesController < ApplicationController
include AircraftScoped
before_action :require_owner!, only: %i[edit update destroy]
before_action :set_note, only: %i[edit update destroy]
def index
@notes = @aircraft.notes.recent_first.includes(:user)
end
def new
@note = @aircraft.notes.new
end
def create
@note = @aircraft.notes.new(note_params.merge(user: current_user))
if @note.save
log_event("note", "Note added")
redirect_to aircraft_notes_path(@aircraft), notice: "Note added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @note.update(note_params.merge(edited_at: Time.current))
log_event("note", "Note updated")
redirect_to aircraft_notes_path(@aircraft), notice: "Note updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@note.destroy!
log_event("note", "Note deleted")
redirect_to aircraft_notes_path(@aircraft), notice: "Note deleted."
end
private
def set_note = @note = @aircraft.notes.find(params[:id])
def note_params = params.require(:aircraft_note).permit(:text, :public)
end
+33
View File
@@ -0,0 +1,33 @@
class PasswordsController < ApplicationController
allow_unauthenticated_access
before_action :set_user_by_token, only: %i[ edit update ]
def new
end
def create
if user = User.find_by(email_address: params[:email_address])
PasswordsMailer.reset(user).deliver_later
end
redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)."
end
def edit
end
def update
if @user.update(params.permit(:password, :password_confirmation))
redirect_to new_session_path, notice: "Password has been reset."
else
redirect_to edit_password_path(params[:token]), alert: "Passwords did not match."
end
end
private
def set_user_by_token
@user = User.find_by_password_reset_token!(params[:token])
rescue ActiveSupport::MessageVerifier::InvalidSignature
redirect_to new_password_path, alert: "Password reset link is invalid or has expired."
end
end
+16
View File
@@ -0,0 +1,16 @@
class ProfilesController < ApplicationController
def edit
@user = current_user
end
def update
@user = current_user
attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation)
attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank?
if @user.update(attrs)
redirect_to root_path, notice: "Profile updated."
else
render :edit, status: :unprocessable_entity
end
end
end
+21
View File
@@ -0,0 +1,21 @@
class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[ new create ]
rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_url, alert: "Try again later." }
def new
end
def create
if user = User.authenticate_by(params.permit(:email_address, :password))
start_new_session_for user
redirect_to after_authentication_url
else
redirect_to new_session_path, alert: "Try another email address or password."
end
end
def destroy
terminate_session
redirect_to new_session_path
end
end
+20
View File
@@ -0,0 +1,20 @@
class SetupController < ApplicationController
allow_unauthenticated_access
before_action { redirect_to root_path if User.exists? }
layout "public"
def new
@user = User.new
end
def create
@user = User.new(params.require(:user).permit(:name, :email_address, :password, :password_confirmation))
@user.admin = true
if @user.save
start_new_session_for @user
redirect_to root_path, notice: "Welcome! You're the administrator. Add your first aircraft."
else
render :new, status: :unprocessable_entity
end
end
end
@@ -0,0 +1,22 @@
class ShareTokensController < ApplicationController
include AircraftScoped
before_action :require_owner!
def create
token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at))
token.created_by = current_user
if token.save
log_event("aircraft", "Share link created (#{token.privilege})", notes: token.label)
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link created."
else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: token.errors.full_messages.to_sentence
end
end
def destroy
token = @aircraft.share_tokens.find(params[:id])
token.destroy!
log_event("aircraft", "Share link revoked", notes: token.label)
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link revoked."
end
end
+30
View File
@@ -0,0 +1,30 @@
# Read-only public view of an aircraft via a share link — no login required.
# 'status' links see current state; 'maintenance' links also see full history.
class SharedController < ApplicationController
allow_unauthenticated_access
skip_before_action :redirect_to_setup
layout "public"
def show
@share = ShareToken.find_active(params[:token]) or raise ActiveRecord::RecordNotFound
@aircraft = @share.aircraft
@airworthiness = @aircraft.airworthiness
@components = @aircraft.components.where.not(status: "DISPOSED").includes(:component_type).order(:install_location)
@active_squawks = @aircraft.squawks.active.by_priority
@notes = @aircraft.notes.visible_publicly.recent_first
@ad_rows = Compliance.ad_rows(@aircraft)
@inspection_rows = Compliance.inspection_rows(@aircraft)
@oil = ConsumptionStats.new(@aircraft, "oil")
@fuel = ConsumptionStats.new(@aircraft, "fuel")
@documents = @aircraft.documents.includes(:document_collection, pages_attachments: :blob)
.select { |d| d.visible_to_share?(@share) }
if @share.maintenance?
@logbook = @aircraft.logbook_entries.recent_first
@resolved_squawks = @aircraft.squawks.resolved.order(resolved_at: :desc)
@major_records = @aircraft.major_records.recent_first
@inspection_history = InspectionRecord.for_aircraft(@aircraft).recent_first.includes(:inspection_type)
@ad_history = AdCompliance.for_aircraft(@aircraft).recent_first.includes(:airworthiness_directive)
end
end
end
+62
View File
@@ -0,0 +1,62 @@
class SquawksController < ApplicationController
include AircraftScoped
# Pilots may create squawks; editing/resolving needs an owner.
before_action :require_owner!, except: %i[index new create]
before_action :set_squawk, only: %i[edit update destroy resolve reopen]
def index
@active = @aircraft.squawks.active.by_priority.includes(:component, :reported_by)
@resolved = @aircraft.squawks.resolved.order(resolved_at: :desc).includes(:component).limit(100)
end
def new
@squawk = @aircraft.squawks.new(priority: 1)
end
def create
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
if @squawk.save
log_event("squawk", "Squawk reported: #{@squawk.priority_label}", notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reported."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @squawk.update(squawk_params)
log_event("squawk", "Squawk updated")
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk updated."
else
render :edit, status: :unprocessable_entity
end
end
def resolve
@squawk.resolve!(notes: params[:resolution_notes])
log_event("squawk", "Squawk resolved", notes: @squawk.issue_reported.truncate(200))
redirect_back fallback_location: aircraft_squawks_path(@aircraft), notice: "Squawk resolved."
end
def reopen
@squawk.update!(resolved: false, resolved_at: nil)
log_event("squawk", "Squawk reopened")
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reopened."
end
def destroy
@squawk.destroy!
log_event("squawk", "Squawk deleted")
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk deleted."
end
private
def set_squawk = @squawk = @aircraft.squawks.find(params[:id])
def squawk_params
params.require(:squawk).permit(:priority, :issue_reported, :component_id, :notes, :attachment)
end
end
+54
View File
@@ -0,0 +1,54 @@
# Wraps fields with a label, hint, and inline errors using the app's Tailwind classes.
# <%= f.field :tail_number %>
# <%= f.field :tach_time, as: :number, step: 0.1 %>
# <%= f.field :status, as: :select, collection: Aircraft::STATUSES.invert %>
# <%= f.field :public, as: :checkbox, label: "Show on share links" %>
class AppFormBuilder < ActionView::Helpers::FormBuilder
def field(method, as: :text, label: nil, hint: nil, collection: nil, include_blank: false, wrapper: {}, **opts)
label_text = label || method.to_s.humanize
errors = object.respond_to?(:errors) ? object.errors[method] : []
if as == :checkbox
return @template.content_tag(:div, class: [ "flex items-start gap-2", wrapper[:class] ]) do
check_box(method, { class: "mt-0.5 h-4 w-4 rounded border-slate-300 text-sky-700" }.merge(opts)) +
@template.content_tag(:div) do
label(method, label_text, class: "text-sm text-slate-700") +
(hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe)
end
end
end
input_opts = { class: "input" }.merge(opts)
input =
case as
when :textarea then text_area(method, { rows: 4 }.merge(input_opts))
when :number then number_field(method, input_opts)
when :date then date_field(method, input_opts)
when :datetime then datetime_field(method, input_opts)
when :email then email_field(method, input_opts)
when :password then password_field(method, input_opts)
when :file then file_field(method, opts.merge(class: "block text-sm text-slate-600 file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-1.5 file:text-sm file:font-medium hover:file:bg-slate-200"))
when :select then select(method, collection, { include_blank: include_blank }, input_opts)
else text_field(method, input_opts)
end
@template.content_tag(:div, class: wrapper[:class]) do
label(method, label_text, class: "label") + input +
(hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) +
errors.map { |e| @template.content_tag(:p, "#{label_text} #{e}", class: "field-error") }.join.html_safe
end
end
def errors_summary
return "".html_safe unless object&.errors&.any?
@template.content_tag(:div, class: "rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200") do
@template.content_tag(:ul, class: "list-disc pl-5") do
object.errors.full_messages.map { |m| @template.content_tag(:li, m) }.join.html_safe
end
end
end
def submit(value = nil, **opts)
super(value, { class: "btn-primary" }.merge(opts))
end
end
+33
View File
@@ -0,0 +1,33 @@
module AircraftHelper
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
def aircraft_tabs(aircraft)
[
[ "Overview", aircraft_path(aircraft), %w[aircraft] ],
[ "Components", aircraft_components_path(aircraft), %w[components] ],
[ "Squawks", aircraft_squawks_path(aircraft), %w[squawks] ],
[ "Flights", aircraft_flight_logs_path(aircraft), %w[flight_logs] ],
[ "Oil & Fuel", aircraft_consumable_records_path(aircraft), %w[consumable_records] ],
[ "Logbook", aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ],
[ "Inspections", aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ],
[ "ADs", aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances] ],
[ "Documents", aircraft_documents_path(aircraft), %w[documents document_collections] ],
[ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ],
[ "Notes", aircraft_notes_path(aircraft), %w[notes] ],
[ "Activity", aircraft_events_path(aircraft), %w[events] ],
([ "Access & Sharing", aircraft_aircraft_roles_path(aircraft), %w[aircraft_roles share_tokens] ] if owner?)
].compact
end
def component_options(aircraft, include_blank: true)
opts = aircraft.components.where.not(status: "DISPOSED").includes(:component_type).map { [ _1.to_s, _1.id ] }
include_blank ? [ [ "— None —", nil ] ] + opts : opts
end
def document_options(aircraft)
[ [ "— None —", nil ] ] + aircraft.documents.ordered.map { [ _1.name, _1.id ] }
end
def logbook_options(aircraft)
[ [ "— None —", nil ] ] + aircraft.logbook_entries.recent_first.limit(300).map { [ "#{_1.date} – #{_1.text.truncate(60)}", _1.id ] }
end
end
+64
View File
@@ -0,0 +1,64 @@
module ApplicationHelper
def hours(value)
return "—" if value.nil?
number_with_precision(value, precision: 1, delimiter: ",")
end
def fmt_date(value)
value ? l(value.to_date, format: :long) : "—"
end
def airworthiness_badge(status, large: false)
color = { "RED" => "red", "ORANGE" => "orange", "GREEN" => "green" }[status.status]
tag.span(status.label, class: [ "badge-#{color}", ("text-sm px-3 py-1" if large) ])
end
def airworthiness_dot(status)
color = { "RED" => "bg-red-500", "ORANGE" => "bg-amber-400", "GREEN" => "bg-emerald-500" }[status.status]
tag.span(class: "inline-block h-3 w-3 rounded-full #{color}", title: status.label)
end
COMPLIANCE_BADGES = {
"compliant" => [ "green", "Compliant" ], "due_soon" => [ "orange", "Due Soon" ],
"overdue" => [ "red", "Overdue" ], "no_compliance" => [ "red", "No Record" ],
"never_completed" => [ "red", "Never Completed" ], "conditional" => [ "gray", "Conditional" ]
}.freeze
def compliance_badge(status)
color, text = COMPLIANCE_BADGES.fetch(status, [ "gray", status.to_s.humanize ])
tag.span(text, class: "badge-#{color}")
end
def life_badge(status)
return "" unless status
color, text = { overdue: [ "red", "Overdue" ], due_soon: [ "orange", "Due Soon" ], ok: [ "green", "OK" ] }[status]
tag.span(text, class: "badge-#{color}")
end
def squawk_priority_badge(squawk)
tag.span(squawk.priority_label, class: "badge-#{squawk.priority_color}")
end
def aircraft_status_badge(aircraft)
color = { "AVAILABLE" => "green", "MX" => "orange", "GROUND" => "red", "UNAVAILABLE" => "gray" }[aircraft.status]
tag.span(aircraft.status_label, class: "badge-#{color}")
end
def visibility_badge(visibility)
color = { "private" => "gray", "status" => "green", "maintenance" => "blue" }[visibility]
tag.span(DocumentCollection::VISIBILITIES[visibility], class: "badge-#{color}")
end
def delete_button(label, path, confirm: "Are you sure?", **opts)
button_to label, path, method: :delete, form: { data: { turbo_confirm: confirm }, class: "inline" },
class: opts[:class] || "btn-danger btn-sm"
end
def empty_state(text)
tag.p(text, class: "py-6 text-center text-sm text-slate-500")
end
def nav_tab(label, path, active)
link_to label, path, class: [ "tab", ("tab-active" if active) ]
end
end
+5
View File
@@ -0,0 +1,5 @@
// Configure your import map in config/importmap.rb.
import "@hotwired/turbo-rails"
import "controllers"
import "chartkick"
import "Chart.bundle"
@@ -0,0 +1,9 @@
import { Application } from "@hotwired/stimulus"
const application = Application.start()
// Configure Stimulus development experience
application.debug = false
window.Stimulus = application
export { application }
@@ -0,0 +1,7 @@
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
this.element.textContent = "Hello World!"
}
}
+4
View File
@@ -0,0 +1,4 @@
// Import and register all your controllers from the importmap via controllers/**/*_controller
import { application } from "controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
+7
View File
@@ -0,0 +1,7 @@
class ApplicationJob < ActiveJob::Base
# Automatically retry jobs that encountered a deadlock
# retry_on ActiveRecord::Deadlocked
# Most jobs are safe to ignore if the underlying records are no longer available
# discard_on ActiveJob::DeserializationError
end
+4
View File
@@ -0,0 +1,4 @@
class ApplicationMailer < ActionMailer::Base
default from: ENV.fetch("MAIL_FROM", "aircraft-manager@localhost")
layout "mailer"
end
+6
View File
@@ -0,0 +1,6 @@
class PasswordsMailer < ApplicationMailer
def reset(user)
@user = user
mail subject: "Reset your password", to: user.email_address
end
end
+16
View File
@@ -0,0 +1,16 @@
class AdCompliance < ApplicationRecord
belongs_to :airworthiness_directive
belongs_to :aircraft, optional: true
belongs_to :component, optional: true
belongs_to :logbook_entry, optional: true
belongs_to :inspection_record, optional: true
validates :date_complied, :compliance_notes, presence: true
validate { errors.add(:base, "Must belong to an aircraft or component") unless aircraft_id || component_id }
scope :recent_first, -> { order(date_complied: :desc, created_at: :desc) }
def self.for_aircraft(aircraft)
where(aircraft_id: aircraft.id).or(where(component_id: aircraft.components.select(:id)))
end
end
+73
View File
@@ -0,0 +1,73 @@
class Aircraft < ApplicationRecord
STATUSES = {
"AVAILABLE" => "Available",
"MX" => "In Maintenance",
"GROUND" => "Grounded",
"UNAVAILABLE" => "Unavailable"
}.freeze
has_one_attached :picture
has_many :roles, class_name: "AircraftRole", dependent: :destroy
has_many :users, through: :roles
has_many :notes, class_name: "AircraftNote", dependent: :destroy
has_many :events, class_name: "AircraftEvent", dependent: :delete_all
has_many :share_tokens, dependent: :destroy
has_many :components, dependent: :destroy
has_many :squawks, dependent: :destroy
has_many :logbook_entries, dependent: :destroy
has_many :document_collections, dependent: :destroy
has_many :documents, dependent: :destroy
has_many :inspection_records, dependent: :destroy
has_many :ad_compliances, dependent: :destroy
has_many :major_records, dependent: :destroy
has_many :flight_logs, dependent: :destroy
has_many :consumable_records, dependent: :destroy
has_and_belongs_to_many :inspection_types
has_and_belongs_to_many :airworthiness_directives
validates :tail_number, presence: true
validates :status, inclusion: { in: STATUSES.keys }
validate :picture_is_image
scope :ordered, -> { order(:tail_number) }
def to_s = tail_number
def status_label = STATUSES[status]
# Hours used for compliance calculations (tach minus offset, as in the original).
def current_hours
tach_time - tach_time_offset
end
def airworthiness
@airworthiness ||= Airworthiness.new(self).call
end
def reload(*)
@airworthiness = nil
super
end
# ADs that apply directly or via any installed component.
def applicable_ads
AirworthinessDirective.applicable_to(self)
end
def applicable_inspection_types
InspectionType.applicable_to(self)
end
def log_event!(category, event_name, user: Current.user, notes: nil)
events.create!(category: category, event_name: event_name, user: user, notes: notes)
end
private
def picture_is_image
if picture.attached? && !picture.content_type.to_s.start_with?("image/")
errors.add(:picture, "must be an image")
end
end
end
+15
View File
@@ -0,0 +1,15 @@
class AircraftEvent < ApplicationRecord
CATEGORIES = {
"hours" => "Hours Update", "flight" => "Flight", "component" => "Component",
"squawk" => "Squawk", "note" => "Note", "oil" => "Oil", "fuel" => "Fuel",
"logbook" => "Logbook", "ad" => "Airworthiness Directive", "inspection" => "Inspection",
"document" => "Document", "aircraft" => "Aircraft", "role" => "Role",
"major_record" => "Major Repair/Alteration"
}.freeze
belongs_to :aircraft
belongs_to :user, optional: true
validates :category, inclusion: { in: CATEGORIES.keys }
default_scope { order(created_at: :desc) }
end
+8
View File
@@ -0,0 +1,8 @@
class AircraftNote < ApplicationRecord
belongs_to :aircraft
belongs_to :user, optional: true
validates :text, presence: true
scope :visible_publicly, -> { where(public: true) }
scope :recent_first, -> { order(created_at: :desc) }
end
+11
View File
@@ -0,0 +1,11 @@
class AircraftRole < ApplicationRecord
ROLES = { "owner" => "Owner", "pilot" => "Pilot" }.freeze
belongs_to :aircraft
belongs_to :user
validates :role, inclusion: { in: ROLES.keys }
validates :user_id, uniqueness: { scope: :aircraft_id, message: "already has a role on this aircraft" }
scope :owners, -> { where(role: "owner") }
end
+33
View File
@@ -0,0 +1,33 @@
class AirworthinessDirective < ApplicationRecord
COMPLIANCE_TYPES = { "standard" => "Standard", "conditional" => "Conditional" }.freeze
BULLETIN_TYPES = {
"ad" => "Airworthiness Directive", "saib" => "Special Airworthiness Information Bulletin",
"sb" => "Service Bulletin", "alert" => "Airworthiness Alert", "other" => "Other"
}.freeze
BULLETIN_LABELS = { "ad" => "AD", "saib" => "SAIB", "sb" => "SB", "alert" => "Alert", "other" => "Bulletin" }.freeze
belongs_to :document, optional: true
has_and_belongs_to_many :aircraft
has_and_belongs_to_many :components
has_many :ad_compliances, dependent: :destroy
validates :name, :short_description, presence: true
validates :compliance_type, inclusion: { in: COMPLIANCE_TYPES.keys }
validates :bulletin_type, inclusion: { in: BULLETIN_TYPES.keys }
scope :ordered, -> { order(:name) }
def self.applicable_to(aircraft)
direct = joins(:aircraft).where(aircraft: { id: aircraft.id }).select(:id)
via_component = joins(:components).where(components: { aircraft_id: aircraft.id }).select(:id)
where(id: direct).or(where(id: via_component))
end
def to_s = name
def conditional? = compliance_type == "conditional"
def bulletin_label = BULLETIN_LABELS[bulletin_type]
def latest_compliance_for(aircraft)
ad_compliances.for_aircraft(aircraft).order(date_complied: :desc, created_at: :desc).first
end
end
+3
View File
@@ -0,0 +1,3 @@
class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
end
+73
View File
@@ -0,0 +1,73 @@
class Component < ApplicationRecord
STATUSES = { "SPARE" => "Spare Part", "IN-USE" => "In Service", "DISPOSED" => "Disposed" }.freeze
belongs_to :aircraft, optional: true
belongs_to :parent_component, class_name: "Component", optional: true
belongs_to :component_type
has_many :child_components, class_name: "Component", foreign_key: :parent_component_id, dependent: :destroy
has_many :squawks, dependent: :nullify
has_and_belongs_to_many :inspection_types
has_and_belongs_to_many :airworthiness_directives
validates :manufacturer, :model, :date_in_service, presence: true
validates :status, inclusion: { in: STATUSES.keys }
validate :parent_on_same_aircraft
scope :in_use, -> { where(status: "IN-USE") }
def to_s
[ component_type&.name, install_location.presence && "(#{install_location})" ].compact.join(" ")
end
def status_label = STATUSES[status]
def hours_to_tbo
tbo_hours - hours_since_overhaul if tbo_hours
end
def hours_to_replacement
replacement_hours - hours_since_overhaul if replacement_hours
end
def next_replacement_date
overhaul_date + replacement_days.days if replacement_days && overhaul_date
end
# :overdue / :due_soon / :ok / nil (not tracked) for display on the components tab.
def life_status
statuses = []
if replacement_critical?
if replacement_hours
statuses << rank(hours_to_replacement <= 0, hours_to_replacement <= Airworthiness::HOURS_WARNING)
end
if (d = next_replacement_date)
statuses << rank(Date.current >= d, Date.current + Airworthiness::DAYS_WARNING >= d)
end
end
if tbo_critical? && tbo_hours && !on_condition?
statuses << rank(hours_to_tbo <= 0, hours_to_tbo <= Airworthiness::HOURS_WARNING * 5)
end
return nil if statuses.empty?
%i[overdue due_soon ok].find { |s| statuses.include?(s) }
end
# Service reset: always zeroes time since overhaul; optionally the whole
# in-service clock when the part was physically replaced.
def reset_service!(reset_in_service: false)
attrs = { hours_since_overhaul: 0, overhaul_date: Date.current }
attrs.merge!(hours_in_service: 0, date_in_service: Date.current) if reset_in_service
update!(attrs)
end
private
def rank(overdue, soon)
overdue ? :overdue : (soon ? :due_soon : :ok)
end
def parent_on_same_aircraft
return unless parent_component
errors.add(:parent_component, "can't be itself") if parent_component_id == id && id
errors.add(:parent_component, "must be on the same aircraft") if parent_component.aircraft_id != aircraft_id
end
end
+6
View File
@@ -0,0 +1,6 @@
class ComponentType < ApplicationRecord
has_many :components, dependent: :restrict_with_error
validates :name, presence: true, uniqueness: { case_sensitive: false }
scope :ordered, -> { order(:name) }
def to_s = name
end
View File
Whitespace-only changes.
+27
View File
@@ -0,0 +1,27 @@
# Mirrors the original's ALLOWED_UPLOAD_EXTENSIONS / content-type checks.
module UploadValidation
extend ActiveSupport::Concern
ALLOWED_CONTENT_TYPES = %w[
image/jpeg image/png image/gif image/webp image/bmp image/tiff
application/pdf text/plain application/gpx+xml application/xml text/xml
text/csv application/vnd.google-earth.kml+xml application/octet-stream
].freeze
MAX_SIZE = 50.megabytes
class_methods do
def validates_uploads(*names)
validate do
names.each do |name|
Array(public_send(name).attachments).each do |att|
next unless att.blob
unless ALLOWED_CONTENT_TYPES.include?(att.blob.content_type)
errors.add(name, "#{att.filename} is not an allowed file type")
end
errors.add(name, "#{att.filename} is too large") if att.blob.byte_size > MAX_SIZE
end
end
end
end
end
end
+17
View File
@@ -0,0 +1,17 @@
class ConsumableRecord < ApplicationRecord
TYPES = { "oil" => "Oil", "fuel" => "Fuel" }.freeze
UNITS = { "oil" => "qt", "fuel" => "gal" }.freeze
belongs_to :aircraft
belongs_to :flight_log, optional: true
validates :record_type, inclusion: { in: TYPES.keys }
validates :date, :flight_hours, presence: true
validates :quantity_added, presence: true, numericality: { greater_than_or_equal_to: 0 }
scope :oil, -> { where(record_type: "oil") }
scope :fuel, -> { where(record_type: "fuel") }
scope :recent_first, -> { order(date: :desc, created_at: :desc) }
def unit = UNITS[record_type]
end
+4
View File
@@ -0,0 +1,4 @@
class Current < ActiveSupport::CurrentAttributes
attribute :session
delegate :user, to: :session, allow_nil: true
end
+38
View File
@@ -0,0 +1,38 @@
class Document < ApplicationRecord
include UploadValidation
TYPES = {
"LOG" => "Logbook", "ALTER" => "Alteration Record", "REPORT" => "Report",
"ESTIMATE" => "Estimate", "DISC" => "Discrepancy List", "INVOICE" => "Receipt / Invoice",
"AIRCRAFT" => "Aircraft Record", "OTHER" => "Other"
}.freeze
belongs_to :aircraft
belongs_to :document_collection, optional: true
has_many_attached :pages
has_many :logbook_entries, dependent: :nullify
validates :name, presence: true
validates :doc_type, inclusion: { in: TYPES.keys }
validates :visibility, inclusion: { in: DocumentCollection::VISIBILITIES.keys }, allow_nil: true
validates_uploads :pages
normalizes :visibility, with: ->(v) { v.presence }
scope :ordered, -> { order(:name) }
def to_s = name
def type_label = TYPES[doc_type]
# nil visibility inherits from the collection; uncollected docs default to private.
def effective_visibility
visibility || document_collection&.visibility || "private"
end
def visible_to_share?(share)
case effective_visibility
when "status" then true
when "maintenance" then share.maintenance?
else false
end
end
end
+12
View File
@@ -0,0 +1,12 @@
class DocumentCollection < ApplicationRecord
VISIBILITIES = { "private" => "Private", "status" => "All share links", "maintenance" => "Maintenance only" }.freeze
belongs_to :aircraft
has_many :documents, dependent: :destroy
validates :name, presence: true
validates :visibility, inclusion: { in: VISIBILITIES.keys }
scope :ordered, -> { order(starred: :desc, name: :asc) }
def to_s = name
end
+28
View File
@@ -0,0 +1,28 @@
class FlightLog < ApplicationRecord
include UploadValidation
belongs_to :aircraft
belongs_to :user, optional: true
has_many :consumable_records, dependent: :nullify
has_one_attached :track_log
validates :date, presence: true
validates :tach_time, presence: true, numericality: { greater_than: 0 }
validates :hobbs_time, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
validates_uploads :track_log
before_validation :derive_times
scope :recent_first, -> { order(date: :desc, created_at: :desc) }
def route_summary
[ departure_location, destination_location ].compact_blank.join(" → ")
end
private
# Let the pilot enter out/in readings instead of the delta.
def derive_times
self.tach_time = tach_in - tach_out if tach_time.blank? && tach_in && tach_out
self.hobbs_time = hobbs_in - hobbs_out if hobbs_time.blank? && hobbs_in && hobbs_out
end
end
+22
View File
@@ -0,0 +1,22 @@
class InspectionRecord < ApplicationRecord
belongs_to :inspection_type
belongs_to :aircraft, optional: true
belongs_to :component, optional: true
belongs_to :logbook_entry, optional: true
has_many :ad_compliances, dependent: :nullify
validates :date, presence: true
validate { errors.add(:base, "Must belong to an aircraft or component") unless aircraft_id || component_id }
scope :recent_first, -> { order(date: :desc, created_at: :desc) }
# Records belonging to the aircraft, or to any of its components.
def self.for_aircraft(aircraft)
where(aircraft_id: aircraft.id).or(where(component_id: aircraft.components.select(:id)))
end
# Hours at inspection, falling back to the linked logbook entry.
def hours_at_inspection
aircraft_hours || logbook_entry&.aircraft_hours_at_entry
end
end
+27
View File
@@ -0,0 +1,27 @@
class InspectionType < ApplicationRecord
has_and_belongs_to_many :aircraft
has_and_belongs_to_many :components
has_many :inspection_records, dependent: :destroy
validates :name, presence: true
scope :ordered, -> { order(:name) }
# Applies to the aircraft directly, or to one of its components.
def self.applicable_to(aircraft)
direct = joins(:aircraft).where(aircraft: { id: aircraft.id }).select(:id)
via_component = joins(:components).where(components: { aircraft_id: aircraft.id }).select(:id)
where(id: direct).or(where(id: via_component))
end
def to_s = name
def interval_description
return "One-time" unless recurring?
parts = []
parts << "#{recurring_hours.to_s.sub(/\.0\z/, '')} hrs" if recurring_hours.to_f > 0
parts << "#{recurring_months} months" if recurring_months > 0
parts << "#{recurring_days} days" if recurring_days > 0
parts.any? ? "Every #{parts.join(' / ')}" : "Recurring"
end
end
+26
View File
@@ -0,0 +1,26 @@
class LogbookEntry < ApplicationRecord
LOG_TYPES = { "AC" => "Aircraft", "ENG" => "Engine", "PROP" => "Propeller", "OTHER" => "Other" }.freeze
ENTRY_TYPES = {
"MAINTENANCE" => "Maintenance", "INSPECTION" => "Inspection", "FLIGHT" => "Flight",
"HOURS_UPDATE" => "Hours Update", "OTHER" => "Other"
}.freeze
belongs_to :aircraft
belongs_to :document, optional: true
has_many :inspection_records, dependent: :nullify
has_many :ad_compliances, dependent: :nullify
validates :date, :text, presence: true
validates :log_type, inclusion: { in: LOG_TYPES.keys }
validates :entry_type, inclusion: { in: ENTRY_TYPES.keys }
scope :recent_first, -> { order(date: :desc, created_at: :desc) }
def self.search(q)
return all if q.blank?
term = "%#{sanitize_sql_like(q)}%"
where("text LIKE :t OR signoff_person LIKE :t OR signoff_location LIKE :t", t: term)
end
def to_s = "#{date} — #{LOG_TYPES[log_type]}"
end
+16
View File
@@ -0,0 +1,16 @@
class MajorRecord < ApplicationRecord
RECORD_TYPES = { "repair" => "Major Repair", "alteration" => "Major Alteration" }.freeze
belongs_to :aircraft
belongs_to :component, optional: true
belongs_to :form_337_document, class_name: "Document", optional: true
belongs_to :stc_document, class_name: "Document", optional: true
belongs_to :logbook_entry, optional: true
validates :title, :date_performed, presence: true
validates :record_type, inclusion: { in: RECORD_TYPES.keys }
scope :recent_first, -> { order(date_performed: :desc, created_at: :desc) }
def type_label = RECORD_TYPES[record_type]
end
+3
View File
@@ -0,0 +1,3 @@
class Session < ApplicationRecord
belongs_to :user
end
+28
View File
@@ -0,0 +1,28 @@
class ShareToken < ApplicationRecord
PRIVILEGES = { "status" => "Current Status", "maintenance" => "Maintenance Detail" }.freeze
MAX_PER_AIRCRAFT = 10
belongs_to :aircraft
belongs_to :created_by, class_name: "User", optional: true
has_secure_token :token, length: 32
validates :privilege, inclusion: { in: PRIVILEGES.keys }
validate :within_limit, on: :create
scope :active, -> { where(expires_at: nil).or(where(expires_at: Time.current..)) }
def self.find_active(token)
active.find_by(token: token.to_s)
end
def maintenance? = privilege == "maintenance"
def expired? = expires_at.present? && expires_at < Time.current
private
def within_limit
if aircraft && aircraft.share_tokens.count >= MAX_PER_AIRCRAFT
errors.add(:base, "An aircraft can have at most #{MAX_PER_AIRCRAFT} share links")
end
end
end
+27
View File
@@ -0,0 +1,27 @@
class Squawk < ApplicationRecord
include UploadValidation
PRIORITIES = { 0 => "Ground Aircraft", 1 => "Fix Soon", 2 => "Fix at Next Inspection", 3 => "Fix Eventually" }.freeze
PRIORITY_COLORS = { 0 => "red", 1 => "orange", 2 => "blue", 3 => "gray" }.freeze
belongs_to :aircraft
belongs_to :component, optional: true
belongs_to :reported_by, class_name: "User", optional: true
has_one_attached :attachment
validates :priority, inclusion: { in: PRIORITIES.keys }
validates :issue_reported, presence: true
validates_uploads :attachment
scope :active, -> { where(resolved: false) }
scope :resolved, -> { where(resolved: true) }
scope :by_priority, -> { order(:priority, created_at: :desc) }
def priority_label = PRIORITIES[priority]
def priority_color = PRIORITY_COLORS[priority]
def grounding? = priority.zero? && !resolved?
def resolve!(notes: nil)
update!(resolved: true, resolved_at: Time.current, notes: [ self.notes, notes ].compact_blank.join("\n\n"))
end
end
+27
View File
@@ -0,0 +1,27 @@
class User < ApplicationRecord
has_secure_password
has_many :sessions, dependent: :destroy
has_many :aircraft_roles, dependent: :destroy
has_many :aircraft, through: :aircraft_roles
normalizes :email_address, with: ->(e) { e.strip.downcase }
validates :email_address, presence: true, uniqueness: true,
format: { with: URI::MailTo::EMAIL_REGEXP }
validates :password, length: { minimum: 8 }, allow_nil: true
# Aircraft visible to this user: admins see the whole fleet.
def accessible_aircraft
admin? ? Aircraft.all : aircraft
end
# 'admin' | 'owner' | 'pilot' | nil
def role_for(aircraft)
return "admin" if admin?
aircraft_roles.find_by(aircraft: aircraft)&.role
end
def display_name
name.presence || email_address
end
end
+11
View File
@@ -0,0 +1,11 @@
# Raised when a flight-activity write is attempted on a RED aircraft whose
# airworthiness enforcement is enabled.
class AircraftGroundedError < StandardError
attr_reader :airworthiness
def initialize(airworthiness)
@airworthiness = airworthiness
reasons = airworthiness.red_issues.map(&:title).join("; ")
super([ "Aircraft is grounded and airworthiness enforcement is enabled", reasons.presence ].compact.join(": "))
end
end
+120
View File
@@ -0,0 +1,120 @@
# Computes RED / ORANGE / GREEN airworthiness for an aircraft. Checks (in order):
# AD compliance, grounding squawks, inspection recurrency, component replacement.
class Airworthiness
HOURS_WARNING = BigDecimal("10")
DAYS_WARNING = 30
RED = "RED"
ORANGE = "ORANGE"
GREEN = "GREEN"
Issue = Struct.new(:category, :severity, :title, :description, :item, keyword_init: true)
Status = Struct.new(:status, :issues, keyword_init: true) do
def red? = status == RED
def orange? = status == ORANGE
def green? = status == GREEN
def can_fly? = green?
def red_issues = issues.select { |i| i.severity == RED }
def label = { RED => "Not Airworthy", ORANGE => "Attention Needed", GREEN => "Airworthy" }[status]
end
def initialize(aircraft, today: Date.current)
@aircraft = aircraft
@today = today
@hours = aircraft.current_hours
@issues = []
end
def call
check_ads
check_grounding_squawks
check_inspections
check_components
status =
if @issues.any? { _1.severity == RED } then RED
elsif @issues.any? { _1.severity == ORANGE } then ORANGE
else GREEN
end
Status.new(status: status, issues: @issues)
end
private
def add(category, severity, title, description, item)
@issues << Issue.new(category:, severity:, title:, description:, item:)
end
def check_ads
@aircraft.applicable_ads.where(mandatory: true, compliance_type: "standard").find_each do |ad|
compliance = ad.latest_compliance_for(@aircraft)
res = Compliance.ad_status(ad, compliance, @hours, @today)
label = ad.bulletin_label
case res.rank
when Compliance::OVERDUE
desc = compliance ? "#{ad.short_description}. Compliance overdue." : "#{ad.short_description}. No compliance record found."
add("AD", RED, "#{label} #{ad.name} - Overdue", desc, ad)
when Compliance::DUE_SOON
add("AD", ORANGE, "#{label} #{ad.name} - Due Soon", "#{ad.short_description}. Compliance due soon.", ad)
end
end
end
def check_grounding_squawks
@aircraft.squawks.active.where(priority: 0).find_each do |squawk|
add("SQUAWK", RED, "Grounding Squawk", squawk.issue_reported.to_s.truncate(100).presence || "No description", squawk)
end
end
def check_inspections
@aircraft.applicable_inspection_types.where(required: true).find_each do |type|
last = type.inspection_records.for_aircraft(@aircraft).recent_first.first
res = Compliance.inspection_status(type, last, @hours, @today)
case res.rank
when Compliance::OVERDUE
if last
add("INSPECTION", RED, "#{type.name} - Overdue", "Inspection overdue.", type)
else
add("INSPECTION", RED, "#{type.name} - Never Completed", "Required inspection has no completion record.", type)
end
when Compliance::DUE_SOON
add("INSPECTION", ORANGE, "#{type.name} - Due Soon", "Inspection due soon.", type)
end
end
end
def check_components
@aircraft.components.in_use.where(replacement_critical: true).includes(:component_type).find_each do |c|
overdue = false
approaching = false
desc = ""
if c.replacement_hours
if c.hours_since_overhaul >= c.replacement_hours
overdue = true
desc = "Replace every #{c.replacement_hours} hrs. Current: #{c.hours_since_overhaul} hrs."
elsif c.hours_since_overhaul + HOURS_WARNING >= c.replacement_hours
approaching = true
desc = "Replace in #{c.replacement_hours - c.hours_since_overhaul} hrs."
end
end
if (due = c.next_replacement_date)
if @today >= due
overdue = true
desc = "Replace every #{c.replacement_days} days. Last serviced #{c.overhaul_date}."
elsif @today + DAYS_WARNING >= due
approaching = true
desc = "Replace in #{(due - @today).to_i} days."
end
end
if overdue
add("COMPONENT", RED, "#{c} - Replacement Overdue", desc, c)
elsif approaching
add("COMPONENT", ORANGE, "#{c} - Replacement Due Soon", desc, c)
end
end
end
end
+119
View File
@@ -0,0 +1,119 @@
# Shared AD / inspection due-status math (port of ad_compliance_status /
# inspection_compliance_status from the original health/services.py).
module Compliance
COMPLIANT = 0
DUE_SOON = 1
OVERDUE = 2
LABELS = %w[compliant due_soon overdue].freeze
Result = Struct.new(:rank, :next_due_date, :next_due_hours, keyword_init: true) do
def label = LABELS[rank]
end
module_function
# Last day of the month `months` after `date` (FAA "end of month" convention).
def end_of_month_after(date, months)
(date >> months).end_of_month
end
def ad_status(ad, compliance, current_hours, today = Date.current)
return Result.new(rank: COMPLIANT) if ad.conditional?
return Result.new(rank: OVERDUE) unless compliance
return Result.new(rank: COMPLIANT) if compliance.permanent?
rank = COMPLIANT
result = Result.new
due_hours = compliance.next_due_at_time.to_d
if due_hours > 0
result.next_due_hours = due_hours
if current_hours >= due_hours
rank = OVERDUE
elsif current_hours + Airworthiness::HOURS_WARNING >= due_hours
rank = [ rank, DUE_SOON ].max
end
end
if ad.recurring? && ad.recurring_months.positive?
due = end_of_month_after(compliance.date_complied, ad.recurring_months)
result.next_due_date = due
if today > due
rank = OVERDUE
elsif today + Airworthiness::DAYS_WARNING >= due
rank = [ rank, DUE_SOON ].max
end
end
result.rank = rank
result
end
def inspection_status(type, last_record, current_hours, today = Date.current)
return Result.new(rank: OVERDUE) unless last_record
return Result.new(rank: COMPLIANT) unless type.recurring?
rank = COMPLIANT
result = Result.new
if type.recurring_months.positive? || type.recurring_days.positive?
due = last_record.date
due = end_of_month_after(due, type.recurring_months) if type.recurring_months.positive?
due += type.recurring_days.days if type.recurring_days.positive?
result.next_due_date = due
if today > due
rank = OVERDUE
elsif today + Airworthiness::DAYS_WARNING >= due
rank = [ rank, DUE_SOON ].max
end
end
interval = type.recurring_hours.to_d
if interval > 0 && (hours_at = last_record.hours_at_inspection)
since = current_hours - hours_at
result.next_due_hours = hours_at + interval
if since >= interval
rank = OVERDUE
elsif since + Airworthiness::HOURS_WARNING >= interval
rank = [ rank, DUE_SOON ].max
end
end
result.rank = rank
result
end
# Rows for the ADs tab: every applicable AD with its latest compliance and status.
AdRow = Struct.new(:ad, :latest, :status, :next_due_date, :next_due_hours, keyword_init: true)
def ad_rows(aircraft)
hours = aircraft.current_hours
aircraft.applicable_ads.ordered.map do |ad|
latest = ad.latest_compliance_for(aircraft)
status =
if ad.conditional? then latest ? "compliant" : "conditional"
elsif latest.nil? then "no_compliance"
elsif latest.permanent? then "compliant"
end
res = ad_status(ad, latest, hours) unless status
AdRow.new(ad: ad, latest: latest, status: status || res.label,
next_due_date: res&.next_due_date, next_due_hours: res&.next_due_hours)
end
end
InspectionRow = Struct.new(:type, :latest, :status, :next_due_date, :next_due_hours, keyword_init: true)
def inspection_rows(aircraft)
hours = aircraft.current_hours
aircraft.applicable_inspection_types.ordered.map do |type|
latest = type.inspection_records.for_aircraft(aircraft).recent_first.first
if latest.nil?
InspectionRow.new(type: type, latest: nil, status: "never_completed")
else
res = inspection_status(type, latest, hours)
InspectionRow.new(type: type, latest: latest, status: res.label,
next_due_date: res.next_due_date, next_due_hours: res.next_due_hours)
end
end
end
end
+58
View File
@@ -0,0 +1,58 @@
# Oil/fuel consumption: per-interval datapoints between consecutive records
# (sorted by flight hours), averaged over the last 20 with IQR outliers and
# excluded records left out. Oil → hours per quart; fuel → gallons per hour.
class ConsumptionStats
WINDOW = 20
Point = Struct.new(:record, :hours, :value, :excluded, :outlier, keyword_init: true)
attr_reader :record_type, :records
def initialize(aircraft, record_type)
@record_type = record_type
@records = aircraft.consumable_records.where(record_type: record_type).order(:flight_hours, :date).to_a
end
def oil? = record_type == "oil"
def metric_label = oil? ? "hrs/qt" : "gal/hr"
def points
@points ||= begin
pts = @records.each_cons(2).filter_map do |prev, cur|
dh = (cur.flight_hours - prev.flight_hours).to_f
qty = cur.quantity_added.to_f
next unless qty > 0 && dh > 0
Point.new(record: cur, hours: cur.flight_hours.to_f, value: oil? ? dh / qty : qty / dh,
excluded: cur.excluded_from_averages?)
end
bounds = iqr_bounds(pts.map(&:value))
pts.each { |p| p.outlier = bounds && !(bounds[0]..bounds[1]).cover?(p.value) }
end
end
def average
window = points.last(WINDOW)
return nil if window.empty?
included = window.reject { |p| p.excluded || p.outlier }
source = included.presence || window
(source.sum(&:value) / source.size).round(1)
end
def latest = points.last&.value&.round(1)
def chart_data
points.map { |p| [ p.hours.round(1), p.value.round(2) ] }
end
private
def iqr_bounds(values)
return nil if values.size < 5
nums = values.sort
n = nums.size
q1 = nums[n / 4]
q3 = nums[(3 * n) / 4]
iqr = q3 - q1
return nil if iqr.zero?
[ q1 - 1.5 * iqr, q3 + 1.5 * iqr ]
end
end
+75
View File
@@ -0,0 +1,75 @@
# Flight-activity writes: absolute hours updates and flight logs. Both cascade
# the tach delta to every IN-USE component.
class HoursService
def initialize(aircraft, user: Current.user)
@aircraft = aircraft
@user = user
end
def enforce_airworthiness!
return unless @aircraft.airworthiness_enforcement?
status = Airworthiness.new(@aircraft).call
raise AircraftGroundedError, status if status.red?
end
# Set absolute tach (and optional hobbs); component hours are clamped at 0
# so downward corrections can't go negative.
def update_hours!(tach_time:, hobbs_time: nil)
enforce_airworthiness!
tach = BigDecimal(tach_time.to_s)
delta = tach - @aircraft.tach_time
old = @aircraft.tach_time
Aircraft.transaction do
@aircraft.tach_time = tach
@aircraft.hobbs_time = BigDecimal(hobbs_time.to_s) if hobbs_time.present?
@aircraft.save!
cascade_to_components(delta, clamp: true)
@aircraft.log_event!("hours",
"Hours #{delta >= 0 ? 'updated' : 'corrected'} to #{tach}",
user: @user, notes: "Previous: #{old}, delta: #{delta >= 0 ? '+' : ''}#{delta}")
end
delta
end
# Persist a flight log and apply its side effects atomically.
def log_flight!(flight)
enforce_airworthiness!
Aircraft.transaction do
flight.aircraft = @aircraft
flight.user ||= @user
flight.save!
@aircraft.tach_time += flight.tach_time
@aircraft.hobbs_time += flight.hobbs_time if flight.hobbs_time
@aircraft.save!
cascade_to_components(flight.tach_time)
{ "oil" => [ flight.oil_added, flight.oil_level_after, flight.oil_added_type ],
"fuel" => [ flight.fuel_added, flight.fuel_level_after, flight.fuel_added_type ] }.each do |type, (qty, level, kind)|
next unless qty.to_f > 0
@aircraft.consumable_records.create!(
record_type: type, flight_log: flight, date: flight.date, quantity_added: qty,
level_after: level, consumable_type: kind, flight_hours: @aircraft.tach_time,
notes: "Auto-created from flight log")
@aircraft.log_event!(type, "#{type.capitalize} added: #{qty} #{ConsumableRecord::UNITS[type]}",
user: @user, notes: "From flight log")
end
route = flight.route_summary.presence
@aircraft.log_event!("flight", "Flight logged: #{flight.tach_time} hrs#{" (#{route})" if route}", user: @user)
end
flight
end
private
def cascade_to_components(delta, clamp: false)
@aircraft.components.in_use.find_each do |c|
his = c.hours_in_service + delta
hso = c.hours_since_overhaul + delta
his, hso = [ his, 0 ].max, [ hso, 0 ].max if clamp
c.update_columns(hours_in_service: his, hours_since_overhaul: hso, updated_at: Time.current)
end
end
end
+15
View File
@@ -0,0 +1,15 @@
<%= form_with model: compliance, url: compliance.new_record? ? aircraft_ad_compliances_path(aircraft) : aircraft_ad_compliance_path(aircraft, compliance), class: "card card-body space-y-4 max-w-2xl" do |f| %>
<%= f.errors_summary %>
<%= f.field :airworthiness_directive_id, as: :select, label: "AD", collection: aircraft.applicable_ads.ordered.map { ["#{_1.name} – #{_1.short_description.truncate(50)}", _1.id] } %>
<div class="grid gap-4 sm:grid-cols-2">
<%= f.field :date_complied, as: :date %>
<%= f.field :aircraft_hours_at_compliance, as: :number, step: 0.1, label: "Aircraft hours (tach)" %>
<%= f.field :next_due_at_time, as: :number, step: 0.1, label: "Next due at (tach hours)", hint: "0 = no hour-based recurrence." %>
<%= f.field :component_id, as: :select, label: "Component", collection: component_options(aircraft) %>
<%= f.field :logbook_entry_id, as: :select, label: "Logbook entry", collection: logbook_options(aircraft) %>
</div>
<%= f.field :permanent, as: :checkbox, label: "Permanently complied (terminating action)" %>
<%= f.field :compliance_notes, as: :textarea, label: "Method of compliance", rows: 3, required: true %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %></div>
<% end %>
<% if compliance.persisted? %><div class="mt-4"><%= delete_button "Delete record", aircraft_ad_compliance_path(aircraft, compliance) %></div><% end %>
+2
View File
@@ -0,0 +1,2 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft, compliance: @compliance %>
+2
View File
@@ -0,0 +1,2 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft, compliance: @compliance %>
@@ -0,0 +1,7 @@
<%= form_with model: [:admin, component_type], class: "card card-body space-y-4 max-w-md" do |f| %>
<%= f.errors_summary %>
<%= f.field :name, required: true %>
<%= f.field :consumable, as: :checkbox, label: "Consumable (oil filter, spark plugs…)" %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", admin_component_types_path, class: "btn-secondary" %></div>
<% end %>
<% if component_type.persisted? %><div class="mt-4"><%= delete_button "Delete type", admin_component_type_path(component_type) %></div><% end %>
@@ -0,0 +1,2 @@
<h1 class="mb-4 text-2xl font-bold">Edit Component Type</h1>
<%= render "form", component_type: @component_type %>
@@ -0,0 +1,7 @@
<% content_for :title, "Component Types" %>
<div class="mb-4 flex items-center justify-between"><h1 class="text-2xl font-bold">Component Types</h1><%= link_to "+ New Type", new_admin_component_type_path, class: "btn-primary" %></div>
<section class="card"><table class="table">
<thead><tr><th>Name</th><th>Consumable</th><th></th></tr></thead>
<tbody><% @component_types.each do |t| %><tr><td><%= t.name %></td><td><%= "Yes" if t.consumable? %></td>
<td class="text-right"><%= link_to "Edit", edit_admin_component_type_path(t), class: "btn-secondary btn-sm" %></td></tr><% end %></tbody>
</table></section>
@@ -0,0 +1,2 @@
<h1 class="mb-4 text-2xl font-bold">New Component Type</h1>
<%= render "form", component_type: @component_type %>
+10
View File
@@ -0,0 +1,10 @@
<%= form_with model: [:admin, user], class: "card card-body space-y-4 max-w-md" do |f| %>
<%= f.errors_summary %>
<%= f.field :name %>
<%= f.field :email_address, as: :email, label: "Email", required: true %>
<%= f.field :password, as: :password, hint: (user.persisted? ? "Leave blank to keep current password." : "At least 8 characters."), autocomplete: "new-password" %>
<%= f.field :password_confirmation, as: :password %>
<%= f.field :admin, as: :checkbox, label: "Administrator", hint: "Admins can see and edit every aircraft and manage users." %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", admin_users_path, class: "btn-secondary" %></div>
<% end %>
<% if user.persisted? && user != current_user %><div class="mt-4"><%= delete_button "Delete user", admin_user_path(user) %></div><% end %>
+2
View File
@@ -0,0 +1,2 @@
<h1 class="mb-4 text-2xl font-bold">Edit User</h1>
<%= render "form", user: @user %>
+12
View File
@@ -0,0 +1,12 @@
<% content_for :title, "Users" %>
<div class="mb-4 flex items-center justify-between"><h1 class="text-2xl font-bold">Users</h1><%= link_to "+ New User", new_admin_user_path, class: "btn-primary" %></div>
<section class="card"><table class="table">
<thead><tr><th>Name</th><th>Email</th><th>Aircraft</th><th></th></tr></thead>
<tbody><% @users.each do |u| %><tr>
<td><%= u.name %> <% if u.admin? %><span class="badge-blue">Admin</span><% end %></td>
<td><%= u.email_address %></td>
<td class="text-xs"><%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %></td>
<td class="text-right"><%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %></td>
</tr><% end %></tbody>
</table></section>
<p class="hint mt-3">After creating an account, an aircraft owner can grant access from the aircraft's “Access & Sharing” tab.</p>
+2
View File
@@ -0,0 +1,2 @@
<h1 class="mb-4 text-2xl font-bold">New User</h1>
<%= render "form", user: @user %>
+30
View File
@@ -0,0 +1,30 @@
<%= form_with model: aircraft, class: "card card-body space-y-4 max-w-3xl" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-3">
<%= f.field :tail_number, required: true, autofocus: true %>
<%= f.field :make %>
<%= f.field :model %>
<%= f.field :serial_number %>
<%= f.field :purchased, as: :date %>
<%= f.field :status, as: :select, collection: Aircraft::STATUSES.invert %>
</div>
<%= f.field :description, as: :textarea, rows: 3 %>
<div class="grid gap-4 sm:grid-cols-4">
<% if aircraft.new_record? %>
<%= f.field :tach_time, as: :number, step: 0.1, label: "Current tach" %>
<%= f.field :hobbs_time, as: :number, step: 0.1, label: "Current hobbs" %>
<% end %>
<%= f.field :tach_time_offset, as: :number, step: 0.1, hint: "Subtracted from tach for compliance math (e.g. after a tach replacement)." %>
<%= f.field :hobbs_time_offset, as: :number, step: 0.1 %>
</div>
<% unless aircraft.new_record? %>
<p class="hint">To change hours use “Update Hours” on the overview, so component times stay in sync.</p>
<% end %>
<%= f.field :picture, as: :file, accept: "image/*" %>
<%= f.field :airworthiness_enforcement, as: :checkbox, label: "Enforce airworthiness",
hint: "Block flight logs and hours updates while the aircraft is red." %>
<div class="flex gap-2">
<%= f.submit aircraft.new_record? ? "Add Aircraft" : "Save" %>
<%= link_to "Cancel", aircraft.new_record? ? root_path : aircraft_path(aircraft), class: "btn-secondary" %>
</div>
<% end %>
+9
View File
@@ -0,0 +1,9 @@
<% content_for :title, "Edit #{@aircraft.tail_number}" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft %>
<div class="mt-6 max-w-3xl card card-body border-red-200">
<h2 class="font-semibold text-red-700">Danger zone</h2>
<p class="text-sm text-slate-600 mb-3">Deleting an aircraft removes all of its records, documents and history.</p>
<%= delete_button "Delete #{@aircraft.tail_number}", aircraft_path(@aircraft),
confirm: "Delete #{@aircraft.tail_number} and ALL its records? This cannot be undone.", class: "btn-danger" %>
</div>
+48
View File
@@ -0,0 +1,48 @@
<% content_for :title, "Fleet" %>
<div class="mb-5 flex items-center justify-between">
<h1 class="text-2xl font-bold tracking-tight">Fleet</h1>
<%= link_to "+ Add Aircraft", new_aircraft_path, class: "btn-primary" %>
</div>
<% if @aircraft_list.empty? %>
<div class="card card-body text-center">
<p class="text-slate-600">No aircraft yet.</p>
<p class="mt-3"><%= link_to "Add your first aircraft", new_aircraft_path, class: "btn-primary" %></p>
</div>
<% else %>
<div class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<% @aircraft_list.each do |aircraft| %>
<% aw = aircraft.airworthiness %>
<%= link_to aircraft_path(aircraft), class: "card block overflow-hidden transition hover:shadow-md" do %>
<div class="flex h-36 items-center justify-center bg-slate-200">
<% if aircraft.picture.attached? %>
<%= image_tag aircraft.picture, class: "h-full w-full object-cover" %>
<% else %>
<span class="text-5xl text-slate-400">✈</span>
<% end %>
</div>
<div class="card-body">
<div class="flex items-start justify-between gap-2">
<div>
<div class="text-lg font-bold"><%= aircraft.tail_number %></div>
<div class="text-sm text-slate-500"><%= [aircraft.make, aircraft.model].compact_blank.join(" ").presence || "—" %></div>
</div>
<%= airworthiness_badge(aw) %>
</div>
<div class="mt-3 flex items-center justify-between text-sm text-slate-600">
<span>Tach <strong><%= hours(aircraft.tach_time) %></strong></span>
<%= aircraft_status_badge(aircraft) %>
</div>
<% if aw.issues.any? %>
<ul class="mt-3 space-y-1 text-xs">
<% aw.issues.first(3).each do |issue| %>
<li class="<%= issue.severity == 'RED' ? 'text-red-700' : 'text-amber-700' %>">• <%= issue.title %></li>
<% end %>
<% if aw.issues.size > 3 %><li class="text-slate-500">+ <%= aw.issues.size - 3 %> more</li><% end %>
</ul>
<% end %>
</div>
<% end %>
<% end %>
</div>
<% end %>
+3
View File
@@ -0,0 +1,3 @@
<% content_for :title, "Add Aircraft" %>
<h1 class="mb-4 text-2xl font-bold">Add Aircraft</h1>
<%= render "form", aircraft: @aircraft %>
+109
View File
@@ -0,0 +1,109 @@
<% content_for :title, @aircraft.tail_number %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<div class="grid gap-5 lg:grid-cols-3">
<div class="space-y-5 lg:col-span-2">
<section class="card">
<div class="card-header">
<h2 class="card-title">Airworthiness</h2>
<%= airworthiness_badge(@airworthiness, large: true) %>
</div>
<div class="card-body">
<% if @airworthiness.issues.empty? %>
<p class="text-sm text-emerald-700">No open issues. All tracked ADs, inspections, components and squawks are current.</p>
<% else %>
<ul class="divide-y divide-slate-100">
<% @airworthiness.issues.each do |issue| %>
<li class="flex items-start gap-3 py-2">
<span class="<%= issue.severity == 'RED' ? 'badge-red' : 'badge-orange' %> mt-0.5"><%= issue.category %></span>
<div>
<div class="text-sm font-medium"><%= issue.title %></div>
<div class="text-xs text-slate-500"><%= issue.description %></div>
</div>
</li>
<% end %>
</ul>
<% end %>
<% if @aircraft.airworthiness_enforcement? %>
<p class="hint mt-3">Airworthiness enforcement is on: flights and hours updates are blocked while the status is red.</p>
<% end %>
</div>
</section>
<section class="card">
<div class="card-header">
<h2 class="card-title">Active Squawks</h2>
<%= link_to "All squawks →", aircraft_squawks_path(@aircraft), class: "link text-sm" %>
</div>
<% if @active_squawks.any? %>
<%= render "squawks/table", squawks: @active_squawks, aircraft: @aircraft %>
<% else %>
<%= empty_state "No open squawks." %>
<% end %>
</section>
<section class="card">
<div class="card-header"><h2 class="card-title">Consumption</h2>
<%= link_to "Oil & fuel →", aircraft_consumable_records_path(@aircraft), class: "link text-sm" %></div>
<div class="card-body grid grid-cols-2 gap-4 text-center">
<div><div class="text-2xl font-semibold"><%= @oil.average || "—" %></div><div class="text-xs text-slate-500">Avg oil, hrs/qt</div></div>
<div><div class="text-2xl font-semibold"><%= @fuel.average || "—" %></div><div class="text-xs text-slate-500">Avg fuel burn, gal/hr</div></div>
</div>
</section>
</div>
<div class="space-y-5">
<section class="card">
<div class="card-header"><h2 class="card-title">Update Hours</h2></div>
<%= form_with url: hours_aircraft_path(@aircraft), method: :patch, class: "card-body space-y-3" do |f| %>
<div class="grid grid-cols-2 gap-3">
<div><%= f.label :tach_time, "Tach", class: "label" %>
<%= f.number_field :tach_time, value: @aircraft.tach_time, step: 0.1, class: "input", required: true %></div>
<div><%= f.label :hobbs_time, "Hobbs", class: "label" %>
<%= f.number_field :hobbs_time, value: @aircraft.hobbs_time, step: 0.1, class: "input" %></div>
</div>
<p class="hint">Enter the current meter readings. The difference is applied to every in-service component. For a single flight, use <%= link_to "Log Flight", new_aircraft_flight_log_path(@aircraft), class: "link" %>.</p>
<%= f.submit "Update Hours", class: "btn-primary" %>
<% end %>
</section>
<section class="card">
<div class="card-header">
<h2 class="card-title">Details</h2>
<% if owner? %><%= link_to "Edit", edit_aircraft_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
</div>
<dl class="card-body grid grid-cols-2 gap-x-3 gap-y-2 text-sm">
<dt class="text-slate-500">Serial</dt><dd><%= @aircraft.serial_number.presence || "—" %></dd>
<dt class="text-slate-500">Purchased</dt><dd><%= fmt_date(@aircraft.purchased) %></dd>
<dt class="text-slate-500">Tach offset</dt><dd><%= hours(@aircraft.tach_time_offset) %></dd>
<dt class="text-slate-500">Hobbs offset</dt><dd><%= hours(@aircraft.hobbs_time_offset) %></dd>
</dl>
<% if @aircraft.description.present? %>
<p class="border-t border-slate-100 px-4 py-3 text-sm text-slate-600"><%= simple_format @aircraft.description %></p>
<% end %>
</section>
<section class="card">
<div class="card-header"><h2 class="card-title">Notes</h2>
<%= link_to "+ Add", new_aircraft_note_path(@aircraft), class: "btn-secondary btn-sm" %></div>
<% if @notes.any? %>
<ul class="divide-y divide-slate-100">
<% @notes.each do |note| %>
<li class="px-4 py-2 text-sm">
<div><%= note.text.truncate(200) %></div>
<div class="text-xs text-slate-500"><%= note.user&.display_name %> · <%= time_ago_in_words(note.created_at) %> ago <%= "· public" if note.public? %></div>
</li>
<% end %>
</ul>
<% else %>
<%= empty_state "No notes." %>
<% end %>
</section>
<section class="card">
<div class="card-header"><h2 class="card-title">Recent Activity</h2>
<%= link_to "All →", aircraft_events_path(@aircraft), class: "link text-sm" %></div>
<%= render "events/list", events: @recent_events %>
</section>
</div>
</div>
+61
View File
@@ -0,0 +1,61 @@
<% content_for :title, "#{@aircraft.tail_number} Access" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<div class="grid gap-5 lg:grid-cols-2">
<section class="card">
<div class="card-header"><h2 class="card-title">People</h2></div>
<table class="table">
<tbody>
<% @roles.each do |r| %>
<tr>
<td><%= r.user.display_name %><div class="text-xs text-slate-500"><%= r.user.email_address %></div></td>
<td>
<%= form_with url: aircraft_aircraft_role_path(@aircraft, r), method: :patch do |f| %>
<%= f.select :role, AircraftRole::ROLES.invert, { selected: r.role }, class: "input w-28", onchange: "this.form.requestSubmit()" %>
<% end %>
</td>
<td class="text-right"><% unless r.user == current_user %><%= delete_button "Remove", aircraft_aircraft_role_path(@aircraft, r), confirm: "Remove #{r.user.display_name}'s access?" %><% end %></td>
</tr>
<% end %>
</tbody>
</table>
<%= form_with url: aircraft_aircraft_roles_path(@aircraft), class: "flex flex-wrap items-end gap-2 border-t border-slate-100 p-4" do |f| %>
<div class="flex-1"><%= f.label :email_address, "Add by email", class: "label" %><%= f.email_field :email_address, class: "input", required: true %></div>
<%= f.select :role, AircraftRole::ROLES.invert, { selected: "pilot" }, class: "input w-28" %>
<%= f.submit "Add", class: "btn-primary" %>
<% end %>
<p class="px-4 pb-4 hint"><strong>Owners</strong> can edit everything. <strong>Pilots</strong> can view all records, log flights, update hours, and add squawks, notes and oil/fuel.</p>
</section>
<section class="card">
<div class="card-header"><h2 class="card-title">Share Links</h2></div>
<% if @share_tokens.any? %>
<ul class="divide-y divide-slate-100">
<% @share_tokens.each do |t| %>
<li class="px-4 py-3">
<div class="flex items-center justify-between gap-2">
<div>
<span class="font-medium"><%= t.label.presence || "Untitled link" %></span>
<%= tag.span ShareToken::PRIVILEGES[t.privilege], class: t.maintenance? ? "badge-blue" : "badge-green" %>
<% if t.expired? %><span class="badge-red">Expired</span><% end %>
</div>
<%= delete_button "Revoke", aircraft_share_token_path(@aircraft, t), confirm: "Revoke this link? Anyone using it will lose access." %>
</div>
<input type="text" readonly value="<%= shared_url(t.token) %>" class="input mt-2 font-mono text-xs" onclick="this.select()">
<div class="mt-1 text-xs text-slate-500">Created <%= t.created_at.to_date %><%= " by #{t.created_by.display_name}" if t.created_by %> · <%= t.expires_at ? "expires #{l t.expires_at, format: :short}" : "never expires" %></div>
</li>
<% end %>
</ul>
<% else %>
<%= empty_state "No share links." %>
<% end %>
<%= form_with model: ShareToken.new, url: aircraft_share_tokens_path(@aircraft), class: "space-y-3 border-t border-slate-100 p-4" do |f| %>
<div class="grid gap-3 sm:grid-cols-3">
<%= f.field :label, placeholder: "Mechanic, buyer…" %>
<%= f.field :privilege, as: :select, label: "Shows", collection: ShareToken::PRIVILEGES.invert %>
<%= f.field :expires_at, as: :datetime, label: "Expires (optional)" %>
</div>
<p class="hint"><strong>Current Status</strong>: overview, airworthiness, components, open squawks, AD/inspection status, oil & fuel, public notes and documents shared with all links. <strong>Maintenance Detail</strong> adds the full logbook, history, resolved squawks and major records.</p>
<%= f.submit "Create Share Link" %>
<% end %>
</section>
</div>
@@ -0,0 +1,27 @@
<%= form_with model: ad, url: ad.new_record? ? aircraft_airworthiness_directives_path(aircraft) : aircraft_airworthiness_directive_path(aircraft, ad), class: "card card-body space-y-4 max-w-3xl" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-3">
<%= f.field :name, label: "Number", required: true, placeholder: "2011-10-09" %>
<%= f.field :bulletin_type, as: :select, label: "Type", collection: AirworthinessDirective::BULLETIN_TYPES.invert %>
<%= f.field :compliance_type, as: :select, label: "Compliance", collection: AirworthinessDirective::COMPLIANCE_TYPES.invert,
hint: "Conditional ADs only apply when a trigger occurs and don't affect airworthiness." %>
</div>
<%= f.field :short_description, required: true %>
<%= f.field :required_action, as: :textarea, rows: 3 %>
<%= f.field :trigger_condition, as: :textarea, rows: 2, hint: "For conditional ADs (e.g. “on prop strike”)." %>
<div class="flex gap-6">
<%= f.field :mandatory, as: :checkbox, label: "Mandatory" %>
<%= f.field :recurring, as: :checkbox, label: "Recurring" %>
</div>
<div class="grid gap-4 sm:grid-cols-3">
<%= f.field :recurring_hours, as: :number, step: 0.1, label: "Every (hours)" %>
<%= f.field :recurring_months, as: :number, label: "Every (months)" %>
<%= f.field :document_id, as: :select, label: "Reference document", collection: document_options(aircraft) %>
</div>
<%= render "shared/applicability_fields", aircraft: aircraft, record: ad, applies_to_airframe: @applies_to_airframe %>
<% if ad.persisted? && (ad.aircraft.count + ad.components.where.not(aircraft_id: aircraft.id).count) > 1 %>
<p class="rounded bg-amber-50 p-2 text-xs text-amber-800">This AD is shared with other aircraft; edits affect them too.</p>
<% end %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %></div>
<% end %>
<% if ad.persisted? %><div class="mt-4"><%= delete_button "Remove from #{aircraft.tail_number}", aircraft_airworthiness_directive_path(aircraft, ad) %></div><% end %>
@@ -0,0 +1,2 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft, ad: @ad %>
@@ -0,0 +1,70 @@
<% content_for :title, "#{@aircraft.tail_number} ADs" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<section class="card">
<div class="card-header">
<h2 class="card-title">Airworthiness Directives & Bulletins</h2>
<% if owner? %>
<div class="flex flex-wrap items-center gap-2">
<% if @attachable.any? %>
<%= form_with url: attach_aircraft_airworthiness_directives_path(@aircraft), class: "flex gap-2" do |f| %>
<%= f.select :airworthiness_directive_id, @attachable.map { ["#{_1.name} – #{_1.short_description.truncate(40)}", _1.id] }, {}, class: "input w-64" %>
<%= f.submit "Link existing", class: "btn-secondary" %>
<% end %>
<% end %>
<%= link_to "+ New AD", new_aircraft_airworthiness_directive_path(@aircraft), class: "btn-primary" %>
</div>
<% end %>
</div>
<% if @rows.any? %>
<div class="overflow-x-auto">
<table class="table">
<thead><tr><th>AD / Bulletin</th><th>Description</th><th>Recurrence</th><th>Last complied</th><th>Next due</th><th>Status</th><th></th></tr></thead>
<tbody>
<% @rows.each do |row| ad = row.ad %>
<tr>
<td class="whitespace-nowrap font-medium"><span class="badge-gray mr-1"><%= ad.bulletin_label %></span><%= ad.name %>
<% unless ad.mandatory? %><div class="text-xs text-slate-400">not mandatory</div><% end %></td>
<td class="max-w-sm text-xs"><%= ad.short_description %>
<% if ad.conditional? && ad.trigger_condition.present? %><div class="text-slate-500">Trigger: <%= ad.trigger_condition %></div><% end %></td>
<td class="text-xs"><%= ad.recurring? ? [ad.recurring_hours.to_f > 0 && "#{hours(ad.recurring_hours)} h", ad.recurring_months > 0 && "#{ad.recurring_months} mo"].select(&:itself).join(" / ") : "One-time" %></td>
<td class="text-xs"><%= row.latest ? "#{row.latest.date_complied}#{' (permanent)' if row.latest.permanent?}" : "—" %></td>
<td class="text-xs"><%= [row.next_due_date&.strftime("%b %Y"), row.next_due_hours && "#{hours(row.next_due_hours)} h"].compact.join(" / ").presence || "—" %></td>
<td><%= compliance_badge(row.status) %></td>
<td class="whitespace-nowrap text-right">
<% if owner? %>
<%= link_to "Comply", new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id), class: "btn-secondary btn-sm" %>
<%= link_to "Edit", edit_aircraft_airworthiness_directive_path(@aircraft, ad), class: "btn-secondary btn-sm" %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% else %>
<%= empty_state "No ADs tracked for this aircraft." %>
<% end %>
</section>
<section class="card mt-5">
<div class="card-header"><h2 class="card-title">Compliance History</h2></div>
<% if @history.any? %>
<table class="table">
<thead><tr><th>Date</th><th>AD</th><th class="text-right">Hours</th><th>Next due (hrs)</th><th>Notes</th><th></th></tr></thead>
<tbody>
<% @history.each do |c| %>
<tr>
<td class="whitespace-nowrap"><%= c.date_complied %></td>
<td><%= c.airworthiness_directive.name %><%= " (#{c.component})" if c.component %></td>
<td class="text-right"><%= hours(c.aircraft_hours_at_compliance) %></td>
<td><%= c.permanent? ? "Permanent" : (c.next_due_at_time.to_f > 0 ? hours(c.next_due_at_time) : "—") %></td>
<td class="max-w-md text-xs"><%= c.compliance_notes %></td>
<td class="text-right"><% if owner? %><%= link_to "Edit", edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %></td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<%= empty_state "No compliance records." %>
<% end %>
</section>
@@ -0,0 +1,2 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft, ad: @ad %>
+50
View File
@@ -0,0 +1,50 @@
<%= form_with model: [aircraft, component], class: "card card-body space-y-5 max-w-4xl" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-3">
<div>
<%= f.field :component_type_id, as: :select, label: "Type",
collection: ComponentType.ordered.map { [_1.name, _1.id] }, include_blank: "— Select —" %>
<%= text_field_tag :new_component_type, params[:new_component_type], class: "input mt-2", placeholder: "…or type a new one" %>
</div>
<%= f.field :manufacturer, required: true %>
<%= f.field :model, required: true %>
<%= f.field :serial_number %>
<%= f.field :install_location, hint: "e.g. Left mag, #3 cylinder" %>
<%= f.field :status, as: :select, collection: Component::STATUSES.invert %>
<%= f.field :parent_component_id, as: :select, label: "Parent component",
collection: [["— None —", nil]] + aircraft.components.where.not(id: component.id).includes(:component_type).map { [_1.to_s, _1.id] } %>
</div>
<fieldset class="grid gap-4 sm:grid-cols-4">
<legend class="mb-2 text-sm font-semibold text-slate-900">Time</legend>
<%= f.field :date_in_service, as: :date, required: true %>
<%= f.field :hours_in_service, as: :number, step: 0.1 %>
<%= f.field :overhaul_date, as: :date, label: "Last overhaul / service" %>
<%= f.field :hours_since_overhaul, as: :number, step: 0.1, label: "Hours since OH / service" %>
</fieldset>
<fieldset class="grid gap-4 sm:grid-cols-3">
<legend class="mb-2 text-sm font-semibold text-slate-900">Limits</legend>
<%= f.field :replacement_hours, as: :number, label: "Replace every (hrs)" %>
<%= f.field :replacement_days, as: :number, label: "Replace every (days)" %>
<%= f.field :replacement_critical, as: :checkbox, label: "Replacement critical", hint: "Overdue replacement grounds the aircraft (oil, filters, ELT battery…)." %>
<%= f.field :tbo_hours, as: :number, label: "TBO (hrs)" %>
<%= f.field :tbo_days, as: :number, label: "TBO (days)" %>
<div class="space-y-2">
<%= f.field :tbo_critical, as: :checkbox, label: "TBO critical" %>
<%= f.field :on_condition, as: :checkbox, label: "On condition (Part 91)" %>
</div>
<%= f.field :inspection_hours, as: :number, label: "Inspect every (hrs)" %>
<%= f.field :inspection_days, as: :number, label: "Inspect every (days)" %>
<%= f.field :inspection_critical, as: :checkbox, label: "Inspection critical" %>
</fieldset>
<%= f.field :notes, as: :textarea, rows: 3 %>
<div class="flex gap-2">
<%= f.submit component.new_record? ? "Add Component" : "Save" %>
<%= link_to "Cancel", aircraft_components_path(aircraft), class: "btn-secondary" %>
</div>
<% end %>
<% if component.persisted? %>
<div class="mt-4"><%= delete_button "Delete component", aircraft_component_path(aircraft, component), confirm: "Delete #{component} and its sub-components?" %></div>
<% end %>
+3
View File
@@ -0,0 +1,3 @@
<% content_for :title, "Edit Component" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft, component: @component %>
+52
View File
@@ -0,0 +1,52 @@
<% content_for :title, "#{@aircraft.tail_number} Components" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<section class="card">
<div class="card-header">
<h2 class="card-title">Components</h2>
<div class="flex items-center gap-3">
<%= link_to (@show_disposed ? "Hide disposed" : "Show disposed"),
aircraft_components_path(@aircraft, disposed: (@show_disposed ? nil : 1)), class: "link text-sm" %>
<% if owner? %><%= link_to "+ Add Component", new_aircraft_component_path(@aircraft), class: "btn-primary" %><% end %>
</div>
</div>
<% if @rows.empty? %>
<%= empty_state "No components yet. Add the engine, propeller, oil filter, ELT battery, etc." %>
<% else %>
<div class="overflow-x-auto">
<table class="table">
<thead><tr>
<th>Component</th><th>Make / Model</th><th>Status</th>
<th class="text-right">In service</th><th class="text-right">Since OH/svc</th>
<th>Limit</th><th>Life</th><th></th>
</tr></thead>
<tbody>
<% @rows.each do |c, depth| %>
<tr>
<td style="padding-left: <%= 0.75 + depth * 1.25 %>rem">
<%= "↳ " if depth > 0 %><%= link_to c.component_type.name, aircraft_component_path(@aircraft, c), class: "link font-medium" %>
<% if c.install_location.present? %><div class="text-xs text-slate-500"><%= c.install_location %></div><% end %>
</td>
<td><%= c.manufacturer %> <%= c.model %><% if c.serial_number.present? %><div class="text-xs text-slate-500">S/N <%= c.serial_number %></div><% end %></td>
<td><%= tag.span c.status_label, class: { "IN-USE" => "badge-green", "SPARE" => "badge-gray", "DISPOSED" => "badge-gray" }[c.status] %></td>
<td class="text-right tabular-nums"><%= hours(c.hours_in_service) %></td>
<td class="text-right tabular-nums"><%= hours(c.hours_since_overhaul) %></td>
<td class="text-xs text-slate-600">
<% if c.replacement_critical? && (c.replacement_hours || c.replacement_days) %>
Replace: <%= [c.replacement_hours && "#{c.replacement_hours} h", c.replacement_days && "#{c.replacement_days} d"].compact.join(" / ") %><br>
<% end %>
<% if c.tbo_critical? && c.tbo_hours %>TBO: <%= c.tbo_hours %> h<%= " (on condition)" if c.on_condition? %><% end %>
</td>
<td><%= life_badge(c.life_status) %></td>
<td class="whitespace-nowrap text-right">
<% if owner? %>
<%= link_to "Edit", edit_aircraft_component_path(@aircraft, c), class: "btn-secondary btn-sm" %>
<%= link_to "Service", aircraft_component_path(@aircraft, c, anchor: "service"), class: "btn-secondary btn-sm" %>
<% end %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
<% end %>
</section>
+3
View File
@@ -0,0 +1,3 @@
<% content_for :title, "Add Component" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft, component: @component %>
+61
View File
@@ -0,0 +1,61 @@
<% content_for :title, @component.to_s %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<div class="grid gap-5 lg:grid-cols-3">
<section class="card lg:col-span-2">
<div class="card-header">
<h2 class="card-title"><%= @component %> <%= life_badge(@component.life_status) %></h2>
<% if owner? %>
<div class="flex gap-2">
<%= link_to "+ Sub-component", new_aircraft_component_path(@aircraft, parent_id: @component.id), class: "btn-secondary btn-sm" %>
<%= link_to "Edit", edit_aircraft_component_path(@aircraft, @component), class: "btn-secondary btn-sm" %>
</div>
<% end %>
</div>
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm sm:grid-cols-4">
<dt class="text-slate-500">Manufacturer</dt><dd><%= @component.manufacturer %></dd>
<dt class="text-slate-500">Model</dt><dd><%= @component.model %></dd>
<dt class="text-slate-500">Serial</dt><dd><%= @component.serial_number.presence || "—" %></dd>
<dt class="text-slate-500">Status</dt><dd><%= @component.status_label %></dd>
<dt class="text-slate-500">Parent</dt><dd><%= @component.parent_component ? link_to(@component.parent_component, aircraft_component_path(@aircraft, @component.parent_component), class: "link") : "—" %></dd>
<dt class="text-slate-500">Location</dt><dd><%= @component.install_location.presence || "—" %></dd>
<dt class="text-slate-500">In service since</dt><dd><%= fmt_date(@component.date_in_service) %></dd>
<dt class="text-slate-500">Last OH / service</dt><dd><%= fmt_date(@component.overhaul_date) %></dd>
<dt class="text-slate-500">Hours in service</dt><dd><%= hours(@component.hours_in_service) %></dd>
<dt class="text-slate-500">Since OH / service</dt><dd><%= hours(@component.hours_since_overhaul) %></dd>
<dt class="text-slate-500">TBO</dt><dd><%= @component.tbo_hours ? "#{@component.tbo_hours} h (#{hours(@component.hours_to_tbo)} remaining)" : "—" %></dd>
<dt class="text-slate-500">Replacement</dt><dd>
<%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_days && "#{@component.replacement_days} d"].compact.join(" / ").presence || "—" %>
<% if (d = @component.next_replacement_date) %><div class="text-xs text-slate-500">Next by <%= fmt_date(d) %></div><% end %>
</dd>
<dt class="text-slate-500">Flags</dt>
<dd class="col-span-3 flex flex-wrap gap-1">
<% { tbo_critical: "TBO critical", replacement_critical: "Replacement critical", inspection_critical: "Inspection critical", on_condition: "On condition" }.each do |flag, label| %>
<% if @component.public_send("#{flag}?") %><span class="badge-blue"><%= label %></span><% end %>
<% end %>
</dd>
</dl>
<% if @component.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @component.notes %></div><% end %>
</section>
<% if owner? %>
<section class="card" id="service">
<div class="card-header"><h2 class="card-title">Service / Replace</h2></div>
<%= form_with url: reset_service_aircraft_component_path(@aircraft, @component), method: :post, class: "card-body space-y-3",
data: { turbo_confirm: "Reset hours for #{@component}?" } do |f| %>
<p class="text-sm text-slate-600">Resets <strong>hours since overhaul</strong> to 0 and sets the service date to today.</p>
<label class="flex items-start gap-2 text-sm">
<%= f.check_box :reset_in_service, class: "mt-0.5 h-4 w-4" %>
<span>Part was physically <strong>replaced</strong> — also reset hours in service and in-service date.</span>
</label>
<%= f.submit "Record Service", class: "btn-primary" %>
<% end %>
</section>
<% end %>
</div>
<% if @squawks.any? %>
<section class="card mt-5">
<div class="card-header"><h2 class="card-title">Squawks on this component</h2></div>
<%= render "squawks/table", squawks: @squawks, aircraft: @aircraft %>
</section>
<% end %>
Loaded 100 of 264 files, more files were not shown because too many files have changed in this diff. Show more