mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 23:50:36 -05:00
AirTrail sync and export, GPS tracks, airport database with autocomplete
AirTrail (https://github.com/johanohly/AirTrail): - File export (Flights → Export for AirTrail) in AirTrail's import format, validated against its schema; same-day repeat legs get leg numbers so AirTrail's de-duplication doesn't merge them. - Automatic sync through AirTrail's REST API (Profile → AirTrail sync): per-user connection with an encrypted API key and scope check; flights are created/updated/deleted in background jobs; a full sync first links flights already in AirTrail (e.g. from a file import) instead of duplicating them; airports are resolved and cached, with manual mapping for unknown codes. - GPS tracks: GPX, KML and CSV track logs are converted to AirTrail's track format for both sync and export; the flight page shows a summary. - Aircraft ICAO type (e.g. C150) for AirTrail's aircraft type. Airport database (OurAirports, the source AirTrail uses): - Managed like AirTrail: downloaded in the background on first start, updated in place from Admin → Airports (adds, changes, removes; ids stable), with admin-managed custom airports that updates never touch. - Each airport carries AirTrail's code, so logged codes translate to AirTrail's exactly (1B9 → K1B9, 4MB → K5M3). - From/To autocomplete on new flights (airports this aircraft has used rank first); From is pre-filled with the last flight's destination; codes are normalized to uppercase. - Flights → Standardize airport codes: rewrite logged codes to the standard code, and fix codes not in the database (typos such as 0R8 → 08R are suggested). Also: admin pages grouped under an Admin dropdown menu. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0c4803d717
commit
5bf682502b
68 files changed
+2667
-10
No files matched your search
@@ -0,0 +1,5 @@
|
||||
# Cached AirTrail airport id for an airport code (remote_id nil = not found).
|
||||
class AirTrailAirport < ApplicationRecord
|
||||
belongs_to :connection, class_name: "AirTrailConnection", foreign_key: :air_trail_connection_id
|
||||
normalizes :code, with: ->(c) { c.to_s.strip.upcase }
|
||||
end
|
||||
@@ -0,0 +1,34 @@
|
||||
# A user's AirTrail account (https://github.com/johanohly/AirTrail). Flights
|
||||
# the user logs are pushed there through AirTrail's REST API.
|
||||
#
|
||||
# The API key needs these scopes: profile.read, flight.read.own,
|
||||
# flight.create.own, flight.update.own, flight.delete.own,
|
||||
# reference_data.read and tracks.write.
|
||||
class AirTrailConnection < ApplicationRecord
|
||||
REQUIRED_SCOPES = %w[profile.read flight.read.own flight.create.own flight.update.own
|
||||
flight.delete.own reference_data.read tracks.write].freeze
|
||||
|
||||
belongs_to :user
|
||||
has_many :syncs, class_name: "AirTrailSync", dependent: :delete_all
|
||||
has_many :airports, class_name: "AirTrailAirport", dependent: :delete_all
|
||||
|
||||
encrypts :api_key
|
||||
|
||||
normalizes :base_url, with: ->(url) { url.strip.chomp("/") }
|
||||
validates :base_url, presence: true, format: { with: %r{\Ahttps?://[^\s/]+(:\d+)?(/\S*)?\z}i, message: "must be a http(s) URL" }
|
||||
validates :api_key, presence: true
|
||||
|
||||
scope :active, -> { where(enabled: true) }
|
||||
|
||||
def client = AirTrailClient.new(base_url: base_url, api_key: api_key)
|
||||
|
||||
def ok? = status == "ok"
|
||||
|
||||
def unresolved_airport_codes
|
||||
airports.where(remote_id: nil).order(:code).pluck(:code)
|
||||
end
|
||||
|
||||
def counts
|
||||
syncs.group(:status).count.reverse_merge("synced" => 0, "pending" => 0, "error" => 0)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,6 @@
|
||||
class AirTrailSync < ApplicationRecord
|
||||
belongs_to :connection, class_name: "AirTrailConnection", foreign_key: :air_trail_connection_id
|
||||
belongs_to :flight_log
|
||||
|
||||
scope :failed, -> { where(status: "error") }
|
||||
end
|
||||
@@ -28,6 +28,8 @@ class Aircraft < ApplicationRecord
|
||||
|
||||
validates :tail_number, presence: true
|
||||
validates :status, inclusion: { in: STATUSES.keys }
|
||||
validates :icao_type, format: { with: /\A[A-Z0-9]{1,4}\z/, message: "must be an ICAO type designator like C150" }, allow_blank: true
|
||||
normalizes :icao_type, with: ->(t) { t.strip.upcase.presence }
|
||||
validate :picture_is_image
|
||||
|
||||
scope :ordered, -> { order(:tail_number) }
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Airport reference data from OurAirports (the source AirTrail uses).
|
||||
# Loaded by AirportData; refresh with `bin/rails airports:refresh`.
|
||||
class Airport < ApplicationRecord
|
||||
KINDS = %w[small_airport medium_airport large_airport seaplane_base heliport balloonport closed].freeze
|
||||
KIND_RANK = { "large_airport" => 0, "medium_airport" => 1, "small_airport" => 2, "seaplane_base" => 3,
|
||||
"heliport" => 4, "balloonport" => 5, "closed" => 9 }.freeze
|
||||
KIND_LABELS = { "seaplane_base" => "seaplane base", "heliport" => "heliport", "balloonport" => "balloonport", "closed" => "closed" }.freeze
|
||||
|
||||
# Custom airports (admin-added) use their identifier as the AirTrail code.
|
||||
before_validation(if: :custom?) { self.airtrail_code = ident }
|
||||
normalizes :ident, :gps_code, :local_code, :iata, with: ->(c) { c.strip.upcase.presence }
|
||||
|
||||
validates :ident, presence: true, uniqueness: true, length: { maximum: 10 }
|
||||
validates :name, presence: true
|
||||
validates :kind, inclusion: { in: KINDS }, allow_blank: true
|
||||
validates :latitude, numericality: { in: -90..90 }, allow_nil: true
|
||||
validates :longitude, numericality: { in: -180..180 }, allow_nil: true
|
||||
|
||||
scope :custom, -> { where(custom: true) }
|
||||
|
||||
# The standard code for logging: AirTrail's (ICAO-style, e.g. K1B9 for FAA
|
||||
# 1B9), so logged codes, the airport database and AirTrail all agree.
|
||||
def code = airtrail_code
|
||||
|
||||
# Other codes the airport goes by (FAA/local, GPS, IATA), e.g. ["1B9"].
|
||||
def other_codes = [ local_code, gps_code, iata ].compact.uniq - [ code ]
|
||||
|
||||
def place = [ municipality, region.to_s.split("-", 2).last.presence ].compact.join(", ")
|
||||
|
||||
def as_suggestion
|
||||
{ code: code, name: name, place: place, airtrail_code: airtrail_code, kind: KIND_LABELS[kind], aka: other_codes }
|
||||
end
|
||||
|
||||
# Best match for a code someone logged, whichever code system it's in.
|
||||
def self.lookup(code)
|
||||
c = code.to_s.strip.upcase
|
||||
return nil if c.empty?
|
||||
candidates = where(ident: c).or(where(gps_code: c)).or(where(local_code: c)).or(where(airtrail_code: c)).or(where(iata: c)).to_a
|
||||
candidates.min_by do |a|
|
||||
field = [ a.ident, a.gps_code, a.local_code, a.airtrail_code, a.iata ].index(c) || 9
|
||||
[ a.kind == "closed" ? 1 : 0, field, KIND_RANK.fetch(a.kind, 8) ]
|
||||
end
|
||||
end
|
||||
|
||||
# The code AirTrail uses for the airport someone logged, or nil if unknown.
|
||||
def self.airtrail_code_for(code) = lookup(code)&.airtrail_code
|
||||
|
||||
# Autocomplete: exact codes, then code prefixes, then name/town matches.
|
||||
# `prefer`: codes to rank first (e.g. airports this aircraft has used).
|
||||
def self.search(query, limit: 10, prefer: [])
|
||||
q = query.to_s.strip
|
||||
return [] if q.length < 2
|
||||
up = q.upcase
|
||||
like_prefix = "#{sanitize_sql_like(up)}%"
|
||||
like_any = "%#{sanitize_sql_like(q)}%"
|
||||
exact = where(ident: up).or(where(airtrail_code: up)).or(where(gps_code: up)).or(where(local_code: up)).or(where(iata: up)).to_a
|
||||
prefix = up.match?(/\A[A-Z0-9]{1,4}\z/) ? where("gps_code LIKE :p OR local_code LIKE :p OR ident LIKE :p", p: like_prefix).limit(200).to_a : []
|
||||
named = where("name LIKE :q OR municipality LIKE :q", q: like_any).limit(400).to_a
|
||||
preferred = prefer.to_set { _1.to_s.upcase }
|
||||
familiar = ->(a) { [ a.code, a.ident, a.gps_code, a.local_code ].any? { preferred.include?(_1) } ? 0 : 1 }
|
||||
rank = ->(a) { [ familiar.(a), a.kind == "closed" ? 1 : 0, KIND_RANK.fetch(a.kind, 8), a.code.length, a.code ] }
|
||||
(exact.sort_by(&rank) + prefix.sort_by(&rank) + named.sort_by(&rank)).uniq(&:id).first(limit)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,17 @@
|
||||
# One run of the OurAirports update (see AirportData / AirportUpdateJob).
|
||||
class AirportUpdate < ApplicationRecord
|
||||
belongs_to :requested_by, class_name: "User", optional: true
|
||||
|
||||
scope :recent_first, -> { order(created_at: :desc) }
|
||||
|
||||
def self.in_progress = where(status: %w[queued running]).where(created_at: 2.hours.ago..)
|
||||
def self.last_success = where(status: "done").order(finished_at: :desc).first
|
||||
|
||||
def failed? = status == "failed"
|
||||
def done? = status == "done"
|
||||
def in_progress? = status.in?(%w[queued running])
|
||||
|
||||
def summary
|
||||
"#{created_count} added, #{updated_count} updated, #{removed_count} removed"
|
||||
end
|
||||
end
|
||||
@@ -4,6 +4,9 @@ class FlightLog < ApplicationRecord
|
||||
belongs_to :aircraft
|
||||
belongs_to :user, optional: true
|
||||
has_many :consumable_records, dependent: :nullify
|
||||
# Capture AirTrail ids before the sync rows are deleted, so the remote flights can be removed too.
|
||||
before_destroy :remember_air_trail_flights, prepend: true
|
||||
has_many :air_trail_syncs, dependent: :delete_all
|
||||
has_one_attached :track_log
|
||||
|
||||
validates :date, presence: true
|
||||
@@ -11,6 +14,9 @@ class FlightLog < ApplicationRecord
|
||||
validates :hobbs_time, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
|
||||
validates_uploads :track_log
|
||||
before_validation :derive_times
|
||||
normalizes :departure_location, :destination_location, with: ->(code) { code.strip.upcase.presence }
|
||||
after_commit :push_to_air_trail, on: %i[create update]
|
||||
after_commit :delete_from_air_trail, on: :destroy
|
||||
|
||||
scope :recent_first, -> { order(date: :desc, created_at: :desc) }
|
||||
|
||||
@@ -20,6 +26,18 @@ class FlightLog < ApplicationRecord
|
||||
|
||||
private
|
||||
|
||||
def push_to_air_trail
|
||||
AirTrailPushJob.perform_later(id) if user_id && AirTrailConnection.active.exists?(user_id: user_id)
|
||||
end
|
||||
|
||||
def remember_air_trail_flights
|
||||
@air_trail_remote = air_trail_syncs.where.not(remote_id: nil).pluck(:air_trail_connection_id, :remote_id)
|
||||
end
|
||||
|
||||
def delete_from_air_trail
|
||||
Array(@air_trail_remote).each { |connection_id, remote_id| AirTrailDeleteJob.perform_later(connection_id, remote_id) }
|
||||
end
|
||||
|
||||
# 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
|
||||
|
||||
@@ -3,6 +3,7 @@ class User < ApplicationRecord
|
||||
has_many :sessions, dependent: :destroy
|
||||
has_many :aircraft_roles, dependent: :destroy
|
||||
has_many :aircraft, through: :aircraft_roles
|
||||
has_one :air_trail_connection, dependent: :destroy
|
||||
|
||||
normalizes :email_address, with: ->(e) { e.strip.downcase }
|
||||
|
||||
|
||||
Reference in new issue
Block a user