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:
rickyandClaude Opus 5.5 committed 2026-11-05 19:40:20 -05:00
1 parent 0c4803d717
commit 5bf682502b
68 files changed
+2667 -10

No files matched your search

@@ -0,0 +1,63 @@
# Admin → Airports: OurAirports updates and custom airports.
class Admin::AirportsController < ApplicationController
before_action :require_admin!
before_action :set_airport, only: %i[edit update destroy]
def index
@total = Airport.count
@custom = Airport.custom.order(:ident)
@updates = AirportUpdate.recent_first.includes(:requested_by).limit(5)
@running = AirportUpdate.in_progress.exists?
@last_success = AirportUpdate.last_success
@query = params[:q].to_s.strip
@results = @query.present? ? Airport.search(@query, limit: 20) : []
end
# Queue a download + sync from OurAirports.
def refresh
if AirportUpdate.in_progress.exists?
redirect_to admin_airports_path, alert: "An update is already running."
else
update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL, requested_by: current_user)
AirportUpdateJob.perform_later(update.id)
redirect_to admin_airports_path, notice: "Airport update started. Refresh this page in a minute or two."
end
end
def new
@airport = Airport.new(custom: true, kind: "small_airport", ident: params[:ident])
end
def create
@airport = Airport.new(airport_params.merge(custom: true))
if @airport.save
redirect_to admin_airports_path, notice: "Custom airport #{@airport.ident} added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @airport.update(airport_params)
redirect_to admin_airports_path, notice: "#{@airport.ident} updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@airport.destroy!
redirect_to admin_airports_path, notice: "#{@airport.ident} removed."
end
private
# Only custom airports can be edited; OurAirports data comes from updates.
def set_airport = @airport = Airport.custom.find(params[:id])
def airport_params
params.require(:airport).permit(:ident, :name, :kind, :municipality, :region, :country, :latitude, :longitude, :elevation_ft, :gps_code, :local_code, :iata)
end
end
@@ -0,0 +1,94 @@
# The signed-in user's AirTrail sync settings (Profile → AirTrail).
class AirTrailConnectionsController < ApplicationController
before_action :set_connection, except: %i[show create]
def show
@connection = current_user.air_trail_connection || current_user.build_air_trail_connection
return unless @connection.persisted?
@counts = @connection.counts
@failed = @connection.syncs.failed.includes(flight_log: :aircraft).order(updated_at: :desc).limit(20)
@unresolved = @connection.unresolved_airport_codes
@flight_count = FlightLog.where(user: current_user).count
end
def create
@connection = current_user.build_air_trail_connection(connection_params)
save_and_verify
end
def update
attrs = connection_params
attrs.delete(:api_key) if attrs[:api_key].blank? # keep the stored key
url_changed = attrs[:base_url].present? && attrs[:base_url].chomp("/") != @connection.base_url
@connection.assign_attributes(attrs)
@connection.remote_user_id = nil if url_changed || attrs.key?(:api_key) # re-identify
save_and_verify
end
def test
verify
redirect_to air_trail_connection_path
end
# Link existing AirTrail flights and push everything else, in the background.
def sync
AirTrailBackfillJob.perform_later(@connection.id)
redirect_to air_trail_connection_path, notice: "Sync started. Refresh this page in a minute to see progress."
end
def map_airport
code = params[:code].to_s.strip.upcase
target = params[:airtrail_code].to_s.strip.upcase
match = target.present? && AirTrailSyncer.new(@connection).map_airport(code, target)
if match
AirTrailBackfillJob.perform_later(@connection.id) # retry flights that needed it
redirect_to air_trail_connection_path, notice: "#{code} mapped to #{match['icao']} (#{match['name']}). Retrying affected flights."
else
redirect_to air_trail_connection_path, alert: "AirTrail has no airport matching “#{target}”."
end
rescue AirTrailClient::Error => e
redirect_to air_trail_connection_path, alert: e.message
end
# Stops syncing. Flights already in AirTrail are left there.
def destroy
@connection.destroy!
redirect_to air_trail_connection_path, notice: "AirTrail disconnected. Flights already in AirTrail were left as they are."
end
private
def set_connection
@connection = current_user.air_trail_connection or redirect_to(air_trail_connection_path)
end
def connection_params
params.require(:air_trail_connection).permit(:base_url, :api_key, :enabled)
end
def save_and_verify
if @connection.save
verify
redirect_to air_trail_connection_path
else
render :show, status: :unprocessable_entity
end
end
def verify
me = @connection.client.me
scopes = Array(me.dig("credential", "scopes"))
missing = me.dig("credential", "kind") == "apiKey" ? AirTrailConnection::REQUIRED_SCOPES - scopes : []
@connection.update!(remote_user_id: me["id"], remote_username: me["username"], checked_at: Time.current,
status: missing.empty? ? "ok" : "error",
last_error: missing.empty? ? nil : "API key is missing scopes: #{missing.join(', ')}")
if missing.empty?
flash[:notice] = "Connected to AirTrail as #{me['username']}."
else
flash[:alert] = @connection.last_error
end
rescue AirTrailClient::Error => e
@connection.update!(status: "error", last_error: e.message, checked_at: Time.current)
flash[:alert] = e.message
end
end
@@ -0,0 +1,28 @@
# Download the aircraft's flights as an AirTrail import file.
class AirTrailExportsController < ApplicationController
include AircraftScoped
def new
@export = build_export
end
def create
@export = build_export
if @export.valid?
send_data @export.to_json, filename: @export.filename, type: "application/json", disposition: "attachment"
else
render :new, status: :unprocessable_entity
end
end
private
def build_export
AirTrailExport.new(@aircraft, username: params[:username].presence || default_username,
aircraft_type: params[:aircraft_type],
only_user: params[:scope] == "mine" ? current_user : nil)
end
# A reasonable guess for the AirTrail username: the part of the email before "@".
def default_username = current_user.email_address.to_s.split("@").first.to_s.gsub(/[^A-Za-z0-9._-]/, "").first(20)
end
+1 -1
View File
@@ -68,7 +68,7 @@ class AircraftController < ApplicationController
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
:airworthiness_enforcement, :picture, :icao_type
)
end
end
@@ -0,0 +1,19 @@
# Flights → Standardize airport codes (owners).
class AirportCodesController < ApplicationController
include AircraftScoped
before_action :require_owner!
def show
@standardizer = AirportCodeStandardizer.new(@aircraft)
end
def update
codes = Array(params[:codes]).map(&:to_s)
standardizer = AirportCodeStandardizer.new(@aircraft)
# Only codes that are actually unknown in this log, and only the ticked ones.
fixes = params.fetch(:fixes, {}).permit(*standardizer.unknown.map(&:code)).to_h
.select { |code, _| Array(params[:fix]).include?(code) }
updated = standardizer.apply!(codes, fixes: fixes)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Updated #{updated} airport entries across your flights."
end
end
+15
View File
@@ -0,0 +1,15 @@
class AirportsController < ApplicationController
# GET /airports/search?q=quonset → [{ code, name, place, airtrail_code, kind }]
def search
render json: Airport.search(params[:q], prefer: familiar_codes).map(&:as_suggestion)
end
private
# Airports this aircraft has flown from/to rank first.
def familiar_codes
aircraft = params[:aircraft_id].presence && current_user.accessible_aircraft.find_by(id: params[:aircraft_id])
return [] unless aircraft
aircraft.flight_logs.distinct.pluck(:departure_location, :destination_location).flatten.compact_blank.uniq
end
end
+11 -1
View File
@@ -9,11 +9,21 @@ class FlightLogsController < ApplicationController
def show
@flight_log = @aircraft.flight_logs.find(params[:id])
begin
@track = TrackParser.parse_attachment(@flight_log.track_log)
rescue TrackParser::Error => e
@track_error = "Couldn't read track: #{e.message}"
end
@air_trail_connection = @flight_log.user&.air_trail_connection
@air_trail_sync = @flight_log.air_trail_syncs.first
end
def new
# Aircraft almost always depart from where they last landed.
last = @aircraft.flight_logs.where.not(destination_location: [ nil, "" ]).recent_first.first
@flight_log = @aircraft.flight_logs.new(date: Date.current, tach_out: @aircraft.tach_time,
hobbs_out: @aircraft.hobbs_time)
hobbs_out: @aircraft.hobbs_time,
departure_location: last&.destination_location)
end
def create
+1 -1
View File
@@ -5,7 +5,7 @@ module AircraftHelper
[ "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 flight_imports] ],
[ "Flights", aircraft_flight_logs_path(aircraft), %w[flight_logs flight_imports air_trail_exports airport_codes] ],
[ "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] ],
@@ -0,0 +1,130 @@
import { Controller } from "@hotwired/stimulus"
// Airport code field with suggestions from the airport database.
// <div data-controller="airport-autocomplete" data-airport-autocomplete-url-value="/airports/search?aircraft_id=1">
// <input data-airport-autocomplete-target="input" ...>
// <ul data-airport-autocomplete-target="list" hidden></ul>
// <p data-airport-autocomplete-target="hint"></p>
// </div>
export default class extends Controller {
static targets = ["input", "list", "hint"]
static values = { url: String }
connect() {
this.results = []
this.active = -1
this.inputTarget.setAttribute("autocomplete", "off")
this.inputTarget.setAttribute("role", "combobox")
this.inputTarget.setAttribute("aria-autocomplete", "list")
this.inputTarget.setAttribute("aria-expanded", "false")
this.listTarget.id ||= `${this.inputTarget.id}-suggestions`
this.inputTarget.setAttribute("aria-controls", this.listTarget.id)
this.describe() // e.g. From pre-filled from the last flight
}
disconnect() { clearTimeout(this.timer) }
search() {
clearTimeout(this.timer)
this.timer = setTimeout(() => this.fetch(), 150)
}
async fetch() {
const q = this.inputTarget.value.trim()
if (q.length < 2) { this.close(); this.setHint(""); return }
const url = new URL(this.urlValue, window.location.origin)
url.searchParams.set("q", q)
const response = await fetch(url, { headers: { Accept: "application/json" } })
if (!response.ok || q !== this.inputTarget.value.trim()) return
this.results = await response.json()
this.active = -1
this.render()
this.updateHint()
}
render() {
this.listTarget.replaceChildren(...this.results.map((airport, i) => {
const li = document.createElement("li")
li.id = `${this.listTarget.id}-${i}`
li.setAttribute("role", "option")
li.className = "cursor-pointer px-3 py-1.5 text-sm hover:bg-sky-50"
const code = document.createElement("span")
code.className = "font-mono font-semibold"
code.textContent = airport.code
const name = document.createElement("span")
name.className = "ml-2 text-slate-700"
name.textContent = airport.name
const place = document.createElement("span")
place.className = "ml-1 text-xs text-slate-500"
place.textContent = [airport.place, airport.aka?.length ? `also ${airport.aka.join(", ")}` : null, airport.kind].filter(Boolean).join(" · ")
li.append(code, name, place)
li.addEventListener("mousedown", (event) => { event.preventDefault(); this.choose(i) })
return li
}))
const open = this.results.length > 0
this.listTarget.hidden = !open
this.inputTarget.setAttribute("aria-expanded", String(open))
}
keydown(event) {
if (this.listTarget.hidden) return
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault()
const step = event.key === "ArrowDown" ? 1 : -1
this.active = (this.active + step + this.results.length) % this.results.length
this.highlight()
} else if (event.key === "Enter" && this.active >= 0) {
event.preventDefault()
this.choose(this.active)
} else if (event.key === "Escape") {
this.close()
}
}
highlight() {
Array.from(this.listTarget.children).forEach((li, i) => {
li.classList.toggle("bg-sky-100", i === this.active)
li.setAttribute("aria-selected", String(i === this.active))
})
this.inputTarget.setAttribute("aria-activedescendant", this.active >= 0 ? `${this.listTarget.id}-${this.active}` : "")
}
choose(index) {
const airport = this.results[index]
this.inputTarget.value = airport.code
this.setHint(this.describeAirport(airport))
this.close()
}
blur() { setTimeout(() => this.close(), 100) }
close() {
this.listTarget.hidden = true
this.inputTarget.setAttribute("aria-expanded", "false")
}
// Show the airport name for a typed code, or note that it isn't in the database.
updateHint() {
const code = this.inputTarget.value.trim().toUpperCase()
const match = this.results.find((a) => a.code === code || (a.aka || []).includes(code))
if (match) this.setHint(this.describeAirport(match))
else if (code.length >= 2 && code.length <= 4 && !code.includes(" ")) this.setHint("Not in the airport database", true)
else this.setHint("")
}
async describe() {
if (!this.inputTarget.value.trim()) return
await this.fetch()
this.close()
}
describeAirport(a) {
return [a.name, a.place].filter(Boolean).join(", ")
}
setHint(text, warn = false) {
if (!this.hasHintTarget) return
this.hintTarget.textContent = text
this.hintTarget.classList.toggle("text-amber-700", warn)
}
}
@@ -0,0 +1,12 @@
import { Controller } from "@hotwired/stimulus"
// Closes a <details> dropdown when clicking elsewhere or pressing Escape.
export default class extends Controller {
closeOutside(event) {
if (!this.element.contains(event.target)) this.close()
}
close() {
this.element.removeAttribute("open")
}
}
+13
View File
@@ -0,0 +1,13 @@
# Sync all of a user's flights: link ones already in AirTrail, push the rest.
class AirTrailBackfillJob < ApplicationJob
queue_as :default
limits_concurrency to: 1, key: ->(connection_id) { "air_trail_backfill_#{connection_id}" } if respond_to?(:limits_concurrency)
retry_on AirTrailClient::NetworkError, wait: :polynomially_longer, attempts: 3
discard_on AirTrailClient::AuthError
def perform(connection_id)
connection = AirTrailConnection.find_by(id: connection_id) or return
return unless connection.enabled?
AirTrailSyncer.new(connection).backfill
end
end
+12
View File
@@ -0,0 +1,12 @@
# Remove a deleted flight from AirTrail.
class AirTrailDeleteJob < ApplicationJob
queue_as :default
retry_on AirTrailClient::NetworkError, wait: :polynomially_longer, attempts: 6
discard_on AirTrailClient::AuthError
def perform(connection_id, remote_id)
connection = AirTrailConnection.find_by(id: connection_id) or return
return unless connection.enabled?
AirTrailSyncer.new(connection).delete_remote(remote_id)
end
end
+14
View File
@@ -0,0 +1,14 @@
# Create/update one flight in its pilot's AirTrail account.
class AirTrailPushJob < ApplicationJob
queue_as :default
retry_on AirTrailClient::NetworkError, wait: :polynomially_longer, attempts: 6
discard_on AirTrailClient::AuthError # recorded on the connection; user must fix the key
def perform(flight_log_id)
flight = FlightLog.includes(:aircraft, user: :air_trail_connection).find_by(id: flight_log_id) or return
connection = flight.user&.air_trail_connection
return unless connection&.enabled?
return unless AirTrailFlightData.exportable?(flight)
AirTrailSyncer.new(connection).push(flight)
end
end
+23
View File
@@ -0,0 +1,23 @@
# Downloads OurAirports and syncs the airports table (AirportData.refresh!).
class AirportUpdateJob < ApplicationJob
queue_as :default
limits_concurrency to: 1, key: "airport_update", duration: 1.hour if respond_to?(:limits_concurrency)
def perform(update_id = nil)
update = (update_id && AirportUpdate.find_by(id: update_id)) || AirportUpdate.create!(source_url: AirportData::SOURCE_URL)
update.update!(status: "running", started_at: Time.current, error: nil)
counts = AirportData.refresh!(update.source_url.presence || AirportData::SOURCE_URL)
update.update!(status: "done", finished_at: Time.current, created_count: counts[:created],
updated_count: counts[:updated], removed_count: counts[:removed])
rescue StandardError => e
update&.update!(status: "failed", finished_at: Time.current, error: "#{e.class}: #{e.message}".truncate(1000))
Rails.logger.error("[airports] update failed: #{e.class}: #{e.message}")
end
# Called at boot: populate the table on first start, like AirTrail does.
def self.ensure_populated
return if Airport.where(custom: false).exists? || AirportUpdate.in_progress.exists?
update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL)
perform_later(update.id)
end
end
+5
View File
@@ -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
+34
View File
@@ -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
+6
View File
@@ -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
+2
View File
@@ -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) }
+64
View File
@@ -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
+17
View File
@@ -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
+18
View File
@@ -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
+1
View File
@@ -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 }
+97
View File
@@ -0,0 +1,97 @@
require "net/http"
# Minimal client for AirTrail's REST API (/api/v1, Bearer API key).
class AirTrailClient
class Error < StandardError
attr_reader :status, :code
def initialize(message, status: nil, code: nil)
super(message)
@status = status
@code = code
end
end
class NetworkError < Error; end # retryable: timeouts, connection refused, 5xx
class AuthError < Error; end # 401/403: bad key or missing scope
class NotFound < Error; end
class ValidationError < Error; end # 400/422
def initialize(base_url:, api_key:, timeout: 20)
@base = URI.parse(base_url.to_s.chomp("/"))
@api_key = api_key
@timeout = timeout
end
def me = request(:get, "/api/v1/me").fetch("data")
def search_airports(query) = request(:get, "/api/v1/airports", query: { query: query }).fetch("data")
def search_aircraft(query) = request(:get, "/api/v1/aircraft", query: { query: query }).fetch("data")
# Yields every flight the key's user owns (follows cursor pagination).
def each_flight
cursor = nil
loop do
q = { scope: "mine", limit: 100 }
q[:cursor] = cursor if cursor
page = request(:get, "/api/v1/flights", query: q)
page.fetch("data").each { yield _1 }
cursor = page.dig("page", "nextCursor")
break unless cursor
end
end
def create_flight(body) = request(:post, "/api/v1/flights", body: body).dig("data", "id")
def update_flight(id, body) = request(:put, "/api/v1/flights/#{Integer(id)}", body: body)
def delete_flight(id)
request(:delete, "/api/v1/flights/#{Integer(id)}")
rescue NotFound
nil # already gone
end
private
def request(method, path, query: nil, body: nil)
uri = @base.dup
uri.path = "#{@base.path}#{path}"
uri.query = URI.encode_www_form(query) if query
req = Net::HTTP.const_get(method.to_s.capitalize).new(uri)
req["Authorization"] = "Bearer #{@api_key}"
req["Accept"] = "application/json"
if body
req["Content-Type"] = "application/json"
req.body = JSON.generate(body)
end
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
open_timeout: @timeout, read_timeout: @timeout) { _1.request(req) }
handle(response)
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
raise NetworkError, "Can't reach AirTrail at #{@base.host}: #{e.message}"
end
def handle(response)
status = response.code.to_i
json = begin
response.body.to_s.empty? ? {} : JSON.parse(response.body)
rescue JSON::ParserError
{}
end
return json if status.between?(200, 299)
error = json["error"].is_a?(Hash) ? json["error"] : {}
message = [ error["message"] || "HTTP #{status}", details(error["details"]) ].compact.join(": ")
klass = case status
when 401, 403 then AuthError
when 404 then NotFound
when 400, 409, 422 then ValidationError
else NetworkError
end
raise klass.new("AirTrail: #{message}", status: status, code: error["code"])
end
def details(list)
return nil unless list.is_a?(Array) && list.any?
list.first(3).map { |d| [ Array(d["path"]).join("."), d["message"] ].compact_blank.join(" ") }.join("; ")
end
end
+96
View File
@@ -0,0 +1,96 @@
# Builds an AirTrail import file (Settings → Import → AirTrail in AirTrail,
# https://github.com/johanohly/AirTrail) from an aircraft's flight log.
#
# Format follows AirTrail's own backup schema (src/lib/import/airtrail.ts):
# { flights: [...], users: [...] }, with airports referenced by code
# (AirTrail asks the user to map codes it doesn't know) and the pilot as the
# single passenger in the "pilot" seat. AirTrail matches the exported user to
# a local account by username.
#
# AirTrail de-duplicates imports on date + airports + flight number +
# registration + departure/arrival times. Our flights have no times, so
# repeat legs on the same day and route get a stable leg number ("#2", "#3")
# in the flight-number field; re-exporting and re-importing is then safe.
class AirTrailExport
USERNAME_FORMAT = /\A[A-Za-z0-9._-]{3,20}\z/
TYPE_FORMAT = /\A[A-Z0-9]{1,4}\z/
EXPORT_USER_ID = "sam-pilot".freeze
attr_reader :errors
def initialize(aircraft, username:, aircraft_type: nil, only_user: nil)
@aircraft = aircraft
@username = username.to_s.strip
@aircraft_type = aircraft_type.to_s.strip.upcase.presence || aircraft.icao_type
@only_user = only_user
@errors = []
end
def valid?
@errors = []
@errors << "AirTrail username must be 3–20 letters, numbers, “.”, “_” or “-”" unless @username.match?(USERNAME_FORMAT)
@errors << "Aircraft type must be an ICAO type designator like C150 (up to 4 letters/numbers)" if @aircraft_type && !@aircraft_type.match?(TYPE_FORMAT)
@errors << "No flights to export" if exportable.empty?
@errors.empty?
end
def flights
@flights ||= begin
scope = @aircraft.flight_logs.includes(track_log_attachment: :blob).order(:date, :created_at, :id)
scope = scope.where(user: @only_user) if @only_user
scope.to_a
end
end
# Flights need both airports, as codes AirTrail can look up.
def exportable = @exportable ||= flights.select { AirTrailFlightData.exportable?(_1) }
def skipped = flights.size - exportable.size
def filename = "#{@aircraft.tail_number.parameterize}-airtrail-#{Date.current}.json"
def to_json(*) = JSON.pretty_generate(as_json)
def as_json(*)
{
flights: exportable.zip(leg_numbers).map { |f, leg| flight_json(f, leg) },
users: [ { id: EXPORT_USER_ID, username: @username, displayName: @username } ]
}
end
private
def airport(code) = AirTrailFlightData.airport_code(code)
def leg_numbers
legs = AirTrailFlightData.leg_numbers(exportable)
exportable.map { legs[_1.id] }
end
def flight_json(f, leg)
json = {
date: f.date.iso8601,
datePrecision: "day",
from: { code: airport(f.departure_location) },
to: { code: airport(f.destination_location) },
departure: nil,
arrival: nil,
duration: AirTrailFlightData.duration(f), # seconds
airline: nil,
aircraft: @aircraft_type && { name: aircraft_name, icao: @aircraft_type },
flightNumber: leg,
aircraftReg: AirTrailFlightData.registration(@aircraft),
note: AirTrailFlightData.note(f),
passengers: [
{ userId: EXPORT_USER_ID, guestName: nil, seat: "pilot", seatNumber: nil,
seatClass: nil, flightReason: nil, customFields: {} }
]
}
track = AirTrailFlightData.track(f)
json[:track] = track if track
json
end
def aircraft_name
[ @aircraft.make, @aircraft.model ].compact_blank.join(" ").presence || @aircraft_type
end
end
+61
View File
@@ -0,0 +1,61 @@
# Flight details shared by the AirTrail file export and the API sync, so a
# flight looks the same in AirTrail whichever way it got there (and the sync
# can recognize flights that came in through a file import).
module AirTrailFlightData
AIRPORT_FORMAT = /\A[A-Z0-9]{1,4}\z/
module_function
# The code AirTrail uses for a logged airport, or nil if AirTrail can't take
# it. Logged codes are translated through the airport database (the same
# OurAirports data AirTrail uses), e.g. 1B9 → K1B9, 4MB → K5M3.
def airport_code(code)
c = code.to_s.strip.upcase
return nil if c.empty?
translated = Airport.airtrail_code_for(c) || c
translated if translated.match?(AIRPORT_FORMAT)
end
def exportable?(flight)
airport_code(flight.departure_location) && airport_code(flight.destination_location)
end
# Seconds, from Hobbs time (or tach); nil for zero-time entries.
def duration(flight)
hours = (flight.hobbs_time || flight.tach_time).to_f
hours.positive? ? (hours * 3600).round : nil
end
def note(flight)
times = [ "Tach #{flight.tach_time} h", (flight.hobbs_time && "Hobbs #{flight.hobbs_time} h") ].compact.join(" · ")
[ times, flight.route.presence, flight.notes.presence ].compact.join("\n").truncate(1000)
end
def registration(aircraft) = aircraft.tail_number.to_s.upcase.first(10).presence
# AirTrail de-duplicates on date + airports + flight number (+ reg, times).
# Repeat legs on the same day and route get "#2", "#3"… in log order.
def leg_numbers(flights)
seen = Hash.new(0)
flights.to_h do |f|
key = [ f.aircraft_id, f.date, airport_code(f.departure_location), airport_code(f.destination_location) ]
seen[key] += 1
[ f.id, (seen[key] > 1 ? "##{seen[key]}" : nil) ]
end
end
def leg_number(flight)
same_route = flight.aircraft.flight_logs.where(date: flight.date).order(:created_at, :id).select do |f|
airport_code(f.departure_location) == airport_code(flight.departure_location) &&
airport_code(f.destination_location) == airport_code(flight.destination_location)
end
leg_numbers(same_route)[flight.id]
end
# AirTrail TrackInput from the flight's track log, or nil.
def track(flight)
TrackParser.parse_attachment(flight.track_log)&.as_air_trail_json
rescue TrackParser::Error, ActiveStorage::FileNotFoundError
nil
end
end
+177
View File
@@ -0,0 +1,177 @@
# Pushes a user's flights to their AirTrail account through the REST API.
#
# - push(flight): create the AirTrail flight, or replace it (PUT) if it
# changed since the last sync. Skips unchanged flights (payload digest).
# - backfill: link flights that already exist in AirTrail (e.g. from an
# earlier file import) instead of duplicating them, then push the rest.
# - Airports are looked up by code once per connection and cached; codes
# AirTrail doesn't know are recorded so the user can map them by hand.
class AirTrailSyncer
class UnresolvedAirport < StandardError; end
AIRPORT_RECHECK = 1.day
def initialize(connection, client: connection.client)
@connection = connection
@client = client
@aircraft_ids = {}
end
# Flights this connection mirrors: the ones its user logged.
def flights = FlightLog.where(user_id: @connection.user_id)
def ensure_identity!
return if @connection.remote_user_id.present?
me = @client.me
@connection.update!(remote_user_id: me["id"], remote_username: me["username"], status: "ok",
last_error: nil, checked_at: Time.current)
end
def push(flight, leg: :lookup)
ensure_identity!
sync = @connection.syncs.find_or_initialize_by(flight_log: flight)
body = payload(flight, leg: leg == :lookup ? AirTrailFlightData.leg_number(flight) : leg)
digest = Digest::SHA256.hexdigest(JSON.generate(body))
return sync if sync.remote_id && sync.status == "synced" && sync.payload_digest == digest
if sync.remote_id
begin
@client.update_flight(sync.remote_id, body)
rescue AirTrailClient::NotFound # deleted in AirTrail: recreate
sync.remote_id = @client.create_flight(body)
end
else
sync.remote_id = @client.create_flight(body)
end
sync.update!(status: "synced", payload_digest: digest, synced_at: Time.current, last_error: nil)
sync
rescue UnresolvedAirport, AirTrailClient::ValidationError => e
sync&.update!(status: "error", last_error: e.message)
sync
rescue AirTrailClient::AuthError => e
@connection.update!(status: "error", last_error: e.message, checked_at: Time.current)
sync&.update!(status: "error", last_error: e.message)
raise
end
def delete_remote(remote_id) = @client.delete_flight(remote_id)
# Returns { linked:, pushed:, failed: }.
def backfill
ensure_identity!
local = flights.includes(:aircraft).order(:date, :created_at, :id).to_a
legs = AirTrailFlightData.leg_numbers(local)
linked = link_existing(local, legs)
pushed = 0
failed = 0
local.each do |f|
next unless AirTrailFlightData.exportable?(f)
sync = push(f, leg: legs[f.id])
sync.status == "synced" ? pushed += 1 : failed += 1
end
@connection.update!(backfilled_at: Time.current, status: "ok", last_error: nil)
{ linked: linked, pushed: pushed, failed: failed }
end
def payload(flight, leg:)
from = airport_id(flight.departure_location)
to = airport_id(flight.destination_location)
body = {
date: flight.date.iso8601,
datePrecision: "day",
departure: nil,
arrival: nil,
duration: AirTrailFlightData.duration(flight),
flightNumber: leg,
aircraftReg: AirTrailFlightData.registration(flight.aircraft),
note: AirTrailFlightData.note(flight),
fromId: from,
toId: to,
aircraftId: aircraft_id(flight.aircraft.icao_type),
airlineId: nil,
passengers: [ { userId: @connection.remote_user_id, guestName: nil, seat: "pilot", seatNumber: nil,
seatClass: nil, flightReason: nil, customFields: {} } ],
customFields: {}
}
track = AirTrailFlightData.track(flight)
body[:track] = track if track
body
end
# Look an airport code up in AirTrail (cached per connection).
def airport_id(code)
normalized = AirTrailFlightData.airport_code(code)
raise UnresolvedAirport, "Airport “#{code.presence || '(blank)'}” isn't a code AirTrail can use" unless normalized
cached = @connection.airports.find_or_initialize_by(code: normalized)
fresh = cached.manual? || cached.remote_id || (cached.looked_up_at && cached.looked_up_at > AIRPORT_RECHECK.ago)
unless fresh
results = @client.search_airports(normalized)
match = results.find { _1["icao"].to_s.casecmp?(normalized) } || results.find { _1["iata"].to_s.casecmp?(normalized) }
cached.update!(remote_id: match&.dig("id"), remote_icao: match&.dig("icao"), looked_up_at: Time.current)
end
cached.remote_id or raise UnresolvedAirport, "AirTrail doesn't know airport #{normalized}. Map it on your AirTrail settings page"
end
# Map a code to an airport the user names (e.g. its ICAO/GPS code in AirTrail).
def map_airport(code, airtrail_code)
results = @client.search_airports(airtrail_code)
match = results.find { _1["icao"].to_s.casecmp?(airtrail_code) || _1["iata"].to_s.casecmp?(airtrail_code) } || results.first
return nil unless match
@connection.airports.find_or_initialize_by(code: code)
.update!(remote_id: match["id"], remote_icao: match["icao"], manual: true, looked_up_at: Time.current)
match
end
private
def aircraft_id(icao_type)
return nil if icao_type.blank?
@aircraft_ids.fetch(icao_type) do
@aircraft_ids[icao_type] = @client.search_aircraft(icao_type).find { _1["icao"].to_s.casecmp?(icao_type) }&.dig("id")
end
end
# Match local flights to AirTrail flights already there (same signature
# AirTrail de-duplicates on), falling back to date + registration + leg +
# duration when the airports were mapped differently. Learns airport ids
# from matched flights so hand-mapped airports carry over.
def link_existing(local, legs)
already = @connection.syncs.where.not(remote_id: nil).pluck(:flight_log_id).to_set
remote = []
@client.each_flight { remote << _1 }
taken = @connection.syncs.where.not(remote_id: nil).pluck(:remote_id).to_set
remote.reject! { taken.include?(_1["id"]) }
exact = remote.group_by { |r| [ r["date"], r.dig("from", "icao").to_s.upcase, r.dig("to", "icao").to_s.upcase, r["flightNumber"].to_s, r["aircraftReg"].to_s.upcase ] }
loose = remote.group_by { |r| [ r["date"], r["aircraftReg"].to_s.upcase, r["flightNumber"].to_s, r["duration"] ] }
used = Set.new
linked = 0
local.each do |f|
next if already.include?(f.id) || !AirTrailFlightData.exportable?(f)
reg = AirTrailFlightData.registration(f.aircraft).to_s
leg = legs[f.id].to_s
candidates = exact[[ f.date.iso8601, AirTrailFlightData.airport_code(f.departure_location),
AirTrailFlightData.airport_code(f.destination_location), leg, reg ]] || []
candidates += loose[[ f.date.iso8601, reg, leg, AirTrailFlightData.duration(f) ]] || []
match = candidates.find { !used.include?(_1["id"]) }
next unless match
used << match["id"]
learn_airport(f.departure_location, match["from"])
learn_airport(f.destination_location, match["to"])
@connection.syncs.find_or_initialize_by(flight_log: f).update!(remote_id: match["id"], status: "pending")
linked += 1
end
linked
end
def learn_airport(code, remote_airport)
normalized = AirTrailFlightData.airport_code(code)
return unless normalized && remote_airport.is_a?(Hash) && remote_airport["id"]
cached = @connection.airports.find_or_initialize_by(code: normalized)
return if cached.manual? || cached.remote_id
cached.update!(remote_id: remote_airport["id"], remote_icao: remote_airport["icao"], looked_up_at: Time.current)
end
end
+89
View File
@@ -0,0 +1,89 @@
# Rewrites an aircraft's logged airport codes to the airport database's
# standard code (AirTrail's ICAO-style code, e.g. 1B9 → K1B9).
#
# s = AirportCodeStandardizer.new(aircraft)
# s.changes # => [Change(from: "1B9", to: "K1B9", airport:, flights: 12, suggested: true), ...]
# s.unknown # => [Unknown(code: "0R8", flights: 2, suggestion: <08R Richmond Airport>)]
# s.apply!(%w[1B9 44N], fixes: { "0R8" => "08R" }) # returns entries updated
class AirportCodeStandardizer
Change = Struct.new(:from, :to, :airport, :flights, :suggested, :note, keyword_init: true)
# A code not in the database, with a likely intended airport (e.g. a typo).
Unknown = Struct.new(:code, :flights, :suggestion, keyword_init: true)
def initialize(aircraft)
@aircraft = aircraft
end
def changes
analyze[:changes]
end
def unknown
analyze[:unknown]
end
# codes: logged codes to standardize; fixes: { unknown code => airport code }
# for codes not in the database (resolved to that airport's standard code).
def apply!(codes, fixes: {})
chosen = changes.select { codes.include?(_1.from) }
known_unknown = unknown.map(&:code)
fixes.each do |from, target|
from = from.to_s.strip.upcase
airport = Airport.lookup(target)
next unless airport && known_unknown.include?(from)
chosen << Change.new(from: from, to: airport.code, airport: airport)
end
updated = 0
FlightLog.transaction do
chosen.each do |c|
updated += @aircraft.flight_logs.where(departure_location: c.from).update_all(departure_location: c.to, updated_at: Time.current)
updated += @aircraft.flight_logs.where(destination_location: c.from).update_all(destination_location: c.to, updated_at: Time.current)
end
if chosen.any?
@aircraft.log_event!("flight", "Standardized #{chosen.size} airport codes",
notes: chosen.map { "#{_1.from}→#{_1.to}" }.join(", "))
end
end
updated
end
private
def analyze
@analyze ||= begin
counts = Hash.new(0)
@aircraft.flight_logs.pluck(:departure_location, :destination_location).flatten.each do |code|
counts[code.to_s.strip.upcase] += 1 if code.present?
end
changes = []
unknown = []
counts.sort.each do |code, n|
airport = Airport.lookup(code)
if airport.nil?
unknown << Unknown.new(code: code, flights: n, suggestion: suggest(code, counts.keys))
elsif airport.code != code
renamed = !airport.code.end_with?(code) # e.g. 4MB → K5M3, not just a K prefix
note = if airport.kind == "closed" then "Closed airport. Check it's the right one"
elsif renamed then "Different identifier, not just a prefix. Check it's the right field"
end
changes << Change.new(from: code, to: airport.code, airport: airport, flights: n,
suggested: airport.kind != "closed", note: note)
end
end
{ changes: changes, unknown: unknown }
end
end
# Likely intended airport for an unknown code: the same characters in a
# different order (e.g. 0R8 → 08R), preferring codes this aircraft has used.
def suggest(code, logged_codes)
return nil unless code.length.between?(3, 4)
candidates = code.chars.permutation.map(&:join).uniq - [ code ]
familiar = candidates & logged_codes
(familiar + (candidates - familiar)).each do |candidate|
airport = Airport.lookup(candidate)
return airport if airport && airport.kind != "closed"
end
nil
end
end
+169
View File
@@ -0,0 +1,169 @@
require "csv"
# Parses a flight's GPS track log (GPX, KML or CSV) into AirTrail's track
# format: coordinates as [lon, lat, altitude_m] plus aligned epoch-second
# times. Mirrors AirTrail's own parser (src/lib/track/parser.ts):
# GPX: <trkpt>/<rtept> lat/lon attributes, <ele> in meters, <time>
# KML: <LineString><coordinates> "lon,lat,alt" and <gx:Track> <when>/<gx:coord>
# CSV: latitude/longitude/altitude/time columns, altitude in FEET
class TrackParser
class Error < StandardError; end
MAX_POINTS = 100_000 # AirTrail's stored-track limit
FEET_TO_M = 0.3048
LAT_HEADERS = %w[latitude lat].freeze
LON_HEADERS = %w[longitude lon lng long].freeze
ALT_HEADERS = %w[altitude alt altitude_ft altitude_feet altitudeft altitudefeet].freeze
TIME_HEADERS = %w[timestamp time date_time datetime utc_time].freeze
Track = Struct.new(:coordinates, :times, :source_format, :source_name, keyword_init: true) do
def points = coordinates.size
def max_altitude_ft = (alts = coordinates.filter_map { _1[2] }).any? ? (alts.max / FEET_TO_M).round : nil
# AirTrail TrackInput
def as_air_trail_json
{ coordinates: coordinates, sourceFormat: source_format, sourceName: source_name.to_s.first(255).presence }
.tap { |h| h[:times] = times if times }
end
end
def self.parse_attachment(attachment)
return nil unless attachment&.attached?
attachment.blob.open { |file| new(file.read, filename: attachment.filename.to_s).parse }
end
def initialize(content, filename:)
@content = content.to_s
@filename = filename.to_s
end
def parse
coords, times =
case format
when "gpx" then parse_gpx
when "kml" then parse_kml
when "csv" then parse_csv
else raise Error, "Unsupported track format"
end
raise Error, "Track has fewer than 2 points" if coords.size < 2
times = nil unless times && times.size == coords.size
coords, times = downsample(coords, times)
Track.new(coordinates: coords, times: times, source_format: format, source_name: @filename)
end
def format
@format ||= case File.extname(@filename).downcase
when ".gpx" then "gpx"
when ".kml" then "kml"
when ".csv" then "csv"
else
head = @content[0, 2000]
if head.include?("<gpx") then "gpx"
elsif head.include?("<kml") then "kml"
elsif head.match?(/lat/i) && head.include?(",") then "csv"
end
end
end
private
def xml
Nokogiri::XML(@content) { |config| config.nonet }.tap(&:remove_namespaces!)
end
def parse_gpx
coords = []
times = []
xml.xpath("//trkpt | //rtept").each do |pt|
lat = number(pt["lat"])
lon = number(pt["lon"])
next unless valid?(lat, lon)
alt = number(pt.at_xpath("ele")&.text)
coords << coordinate(lon, lat, alt)
times << epoch(pt.at_xpath("time")&.text)
end
[ coords, times.all? ? times : nil ]
end
def parse_kml
doc = xml
track_points = doc.xpath("//Track")
if track_points.any?
coords = []
times = []
track_points.each do |track|
whens = track.xpath("when").map(&:text)
track.xpath("coord").each_with_index do |c, i|
lon, lat, alt = c.text.split.map { number(_1) }
next unless valid?(lat, lon)
coords << coordinate(lon, lat, alt)
times << epoch(whens[i])
end
end
return [ coords, times.all? ? times : nil ]
end
coords = doc.xpath("//LineString/coordinates").flat_map do |node|
node.text.split.filter_map do |triple|
lon, lat, alt = triple.split(",").map { number(_1) }
coordinate(lon, lat, alt) if valid?(lat, lon)
end
end
[ coords, nil ]
end
def parse_csv
rows = CSV.parse(@content.sub(/\A/, ""), headers: true)
headers = rows.headers.compact
find = ->(names) { headers.find { |h| names.include?(h.to_s.strip.downcase.gsub(/[^a-z_]/, "")) } }
lat_h, lon_h, alt_h, time_h = find.(LAT_HEADERS), find.(LON_HEADERS), find.(ALT_HEADERS), find.(TIME_HEADERS)
raise Error, "CSV track needs latitude and longitude columns" unless lat_h && lon_h
coords = []
times = []
rows.each do |row|
lat = number(row[lat_h])
lon = number(row[lon_h])
next unless valid?(lat, lon)
alt_ft = alt_h && number(row[alt_h])
coords << coordinate(lon, lat, alt_ft && alt_ft * FEET_TO_M)
times << (time_h && epoch(row[time_h]))
end
[ coords, times.all? ? times : nil ]
rescue CSV::MalformedCSVError => e
raise Error, "Couldn't read CSV track (#{e.message})"
end
def coordinate(lon, lat, alt)
alt ? [ lon.round(6), lat.round(6), alt.round(1) ] : [ lon.round(6), lat.round(6) ]
end
def valid?(lat, lon) = lat && lon && lat.between?(-90, 90) && lon.between?(-180, 180)
def number(value)
Float(value.to_s.strip)
rescue ArgumentError, TypeError
nil
end
# ISO 8601 or epoch seconds/milliseconds → epoch seconds.
def epoch(value)
v = value.to_s.strip
return nil if v.empty?
if v.match?(/\A-?\d+(\.\d+)?\z/)
n = v.to_f
return (n > 10_000_000_000 ? n / 1000 : n).round
end
Time.iso8601(v).to_i
rescue ArgumentError
Time.parse(v).to_i rescue nil
end
def downsample(coords, times)
return [ coords, times ] if coords.size <= MAX_POINTS
step = (coords.size.to_f / MAX_POINTS).ceil
keep = (0...coords.size).step(step).to_a
keep << coords.size - 1 unless keep.last == coords.size - 1
[ keep.map { coords[_1] }, times && keep.map { times[_1] } ]
end
end
+16
View File
@@ -0,0 +1,16 @@
<%= form_with model: [:admin, airport], class: "card card-body space-y-4 max-w-2xl" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-3">
<%= f.field :ident, label: "Code", required: true, hint: "The code you log, e.g. 0R8." %>
<%= f.field :name, required: true, wrapper: { class: "sm:col-span-2" } %>
<%= f.field :kind, as: :select, label: "Type", collection: Airport::KINDS.map { [_1.humanize, _1] } %>
<%= f.field :municipality, label: "Town" %>
<%= f.field :region, placeholder: "US-RI", hint: "ISO region" %>
<%= f.field :latitude, as: :number, step: "any" %>
<%= f.field :longitude, as: :number, step: "any" %>
<%= f.field :elevation_ft, as: :number, label: "Elevation (ft)" %>
</div>
<p class="hint">Custom airports are kept when the database is updated from OurAirports. To sync flights at this airport to AirTrail, add it there too with the same code (or map it on your AirTrail sync page).</p>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", admin_airports_path, class: "btn-secondary" %></div>
<% end %>
<% if airport.persisted? %><div class="mt-4"><%= delete_button "Remove #{airport.ident}", admin_airport_path(airport) %></div><% end %>
+2
View File
@@ -0,0 +1,2 @@
<h1 class="mb-4 text-2xl font-bold">Edit <%= @airport.ident %></h1>
<%= render "form", airport: @airport %>
+87
View File
@@ -0,0 +1,87 @@
<% content_for :title, "Airports" %>
<div class="mb-4 flex items-center justify-between">
<h1 class="text-2xl font-bold">Airports</h1>
<%= link_to "+ Custom Airport", new_admin_airport_path, class: "btn-primary" %>
</div>
<div class="grid gap-5 lg:grid-cols-3">
<section class="card lg:col-span-2">
<div class="card-header">
<h2 class="card-title">Airport database</h2>
<% if @running %>
<span class="badge-blue">Updating…</span>
<% else %>
<%= button_to "Update from OurAirports", refresh_admin_airports_path, class: "btn-secondary",
form: { data: { turbo_confirm: "Download the latest airport data from OurAirports? Custom airports are kept." } } %>
<% end %>
</div>
<div class="card-body space-y-3 text-sm">
<div class="grid grid-cols-3 gap-3 text-center">
<div><div class="text-2xl font-semibold"><%= number_with_delimiter(@total) %></div><div class="text-xs text-slate-500">airports</div></div>
<div><div class="text-2xl font-semibold"><%= @custom.size %></div><div class="text-xs text-slate-500">custom</div></div>
<div><div class="text-sm font-semibold"><%= @last_success ? "#{time_ago_in_words(@last_success.finished_at)} ago" : "never" %></div><div class="text-xs text-slate-500">last updated</div></div>
</div>
<% if @total.zero? %>
<p class="rounded-md bg-amber-50 px-3 py-2 text-amber-900 ring-1 ring-amber-200">No airport data yet. It downloads automatically when the app starts. Use “Update from OurAirports” if that didn't happen.</p>
<% end %>
<p class="hint">Airport data comes from <a href="https://ourairports.com/data/" class="link" target="_blank" rel="noopener noreferrer">OurAirports</a> (public domain), the same source AirTrail uses. It's used for From/To autocomplete and to match airport codes when syncing to AirTrail. Updates add new airports, apply changes and remove closed-out entries; custom airports are never changed.</p>
<% if @updates.any? %>
<table class="table">
<thead><tr><th>Started</th><th>By</th><th>Status</th><th>Result</th></tr></thead>
<tbody>
<% @updates.each do |u| %>
<tr>
<td class="whitespace-nowrap text-xs"><%= l(u.created_at, format: :short) %></td>
<td class="text-xs"><%= u.requested_by&.display_name || "Startup" %></td>
<td><%= tag.span u.status.capitalize, class: { "done" => "badge-green", "failed" => "badge-red" }.fetch(u.status, "badge-blue") %></td>
<td class="text-xs"><%= u.done? ? u.summary : u.error %></td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
</div>
</section>
<section class="card">
<div class="card-header"><h2 class="card-title">Look up</h2></div>
<div class="card-body space-y-2">
<%= form_with url: admin_airports_path, method: :get, class: "flex gap-2" do |f| %>
<%= f.search_field :q, value: @query, class: "input", placeholder: "Code or name" %>
<%= f.submit "Search", class: "btn-secondary" %>
<% end %>
<% if @query.present? %>
<% if @results.any? %>
<ul class="divide-y divide-slate-100 text-sm">
<% @results.each do |a| %>
<li class="py-1.5"><span class="font-mono font-semibold"><%= a.code %></span> <%= a.name %>
<div class="text-xs text-slate-500"><%= [a.place, "AirTrail #{a.airtrail_code}", (a.custom? ? "custom" : nil), Airport::KIND_LABELS[a.kind]].compact_blank.join(" · ") %></div></li>
<% end %>
</ul>
<% else %>
<p class="text-sm text-slate-600">No match for “<%= @query %>”. <%= link_to "Add it as a custom airport", new_admin_airport_path(ident: @query.upcase), class: "link" %>.</p>
<% end %>
<% end %>
</div>
</section>
</div>
<section class="card mt-5">
<div class="card-header"><h2 class="card-title">Custom airports</h2></div>
<% if @custom.any? %>
<table class="table">
<thead><tr><th>Code</th><th>Name</th><th>Location</th><th>Type</th><th></th></tr></thead>
<tbody>
<% @custom.each do |a| %>
<tr>
<td class="font-mono font-semibold"><%= a.ident %></td><td><%= a.name %></td><td class="text-xs"><%= a.place %></td>
<td class="text-xs"><%= a.kind.to_s.humanize %></td>
<td class="text-right"><%= link_to "Edit", edit_admin_airport_path(a), class: "btn-secondary btn-sm" %></td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<%= empty_state "None. Add private strips or fields that aren't in OurAirports." %>
<% end %>
</section>
+2
View File
@@ -0,0 +1,2 @@
<h1 class="mb-4 text-2xl font-bold">New Custom Airport</h1>
<%= render "form", airport: @airport %>
@@ -0,0 +1,83 @@
<% content_for :title, "AirTrail sync" %>
<h1 class="mb-1 text-2xl font-bold">AirTrail sync</h1>
<p class="mb-5 text-sm text-slate-600">Push the flights you log to your <a href="https://github.com/johanohly/AirTrail" class="link" target="_blank" rel="noopener noreferrer">AirTrail</a> flight map, with GPS tracks.</p>
<div class="grid gap-5 lg:grid-cols-3">
<div class="space-y-5 lg:col-span-2">
<%= form_with model: @connection, url: air_trail_connection_path, method: (@connection.persisted? ? :patch : :post), class: "card card-body space-y-4" do |f| %>
<h2 class="card-title">Connection</h2>
<%= f.errors_summary %>
<%= f.field :base_url, label: "AirTrail URL", placeholder: "https://airtrail.example.com", required: true %>
<%= f.field :api_key, as: :password, label: "API key", autocomplete: "off",
placeholder: (@connection.persisted? ? "•••••••• (leave blank to keep)" : ""),
hint: "Create one in AirTrail under Settings → Security → API keys." %>
<%= f.field :enabled, as: :checkbox, label: "Sync automatically", hint: "Flights you log, or delete, are pushed to AirTrail in the background." %>
<div class="flex flex-wrap gap-2">
<%= f.submit(@connection.persisted? ? "Save & test" : "Connect") %>
</div>
<% end %>
<% if @connection.persisted? %>
<section class="card">
<div class="card-header">
<h2 class="card-title">Status</h2>
<% if @connection.ok? %><span class="badge-green">Connected as <%= @connection.remote_username %></span><% else %><span class="badge-red">Needs attention</span><% end %>
</div>
<div class="card-body space-y-3 text-sm">
<% if @connection.last_error.present? %><p class="rounded-md bg-red-50 px-3 py-2 text-red-800 ring-1 ring-red-200"><%= @connection.last_error %></p><% end %>
<div class="grid grid-cols-3 gap-3 text-center">
<div><div class="text-2xl font-semibold"><%= @counts["synced"] %></div><div class="text-xs text-slate-500">synced</div></div>
<div><div class="text-2xl font-semibold"><%= @counts["pending"] %></div><div class="text-xs text-slate-500">pending</div></div>
<div><div class="text-2xl font-semibold <%= 'text-red-700' if @counts['error'].positive? %>"><%= @counts["error"] %></div><div class="text-xs text-slate-500">failed</div></div>
</div>
<p class="text-xs text-slate-500">You've logged <%= pluralize(@flight_count, "flight") %>.
<%= @connection.backfilled_at ? "Last full sync #{time_ago_in_words(@connection.backfilled_at)} ago." : "Run a full sync to send your existing flights." %></p>
<div class="flex flex-wrap gap-2">
<%= button_to "Sync all my flights now", sync_air_trail_connection_path, class: "btn-primary" %>
<%= button_to "Test connection", test_air_trail_connection_path, class: "btn-secondary" %>
</div>
<p class="hint">A full sync first links flights that are already in AirTrail (e.g. from a file import), so nothing is duplicated, then sends the rest.</p>
</div>
</section>
<% if @unresolved.any? %>
<section class="card">
<div class="card-header"><h2 class="card-title">Airports AirTrail doesn't know</h2></div>
<div class="card-body space-y-2">
<p class="text-xs text-slate-600">Flights using these codes can't sync yet. Enter the code AirTrail uses for the same airport (e.g. its ICAO or GPS code).</p>
<% @unresolved.each do |code| %>
<%= form_with url: map_airport_air_trail_connection_path, class: "flex items-center gap-2" do |f| %>
<%= hidden_field_tag :code, code %>
<span class="w-16 font-mono text-sm"><%= code %></span><span class="text-slate-400">→</span>
<%= text_field_tag :airtrail_code, nil, class: "input w-32", placeholder: "AirTrail code", required: true %>
<%= f.submit "Map", class: "btn-secondary btn-sm" %>
<% end %>
<% end %>
</div>
</section>
<% end %>
<% if @failed.any? %>
<section class="card">
<div class="card-header"><h2 class="card-title">Flights that didn't sync</h2></div>
<table class="table"><tbody>
<% @failed.each do |s| f = s.flight_log %>
<tr><td class="whitespace-nowrap"><%= link_to f.date, aircraft_flight_log_path(f.aircraft, f), class: "link" %></td>
<td><%= f.route_summary %></td><td class="text-xs text-red-700"><%= s.last_error %></td></tr>
<% end %>
</tbody></table>
</section>
<% end %>
<div><%= delete_button "Disconnect AirTrail", air_trail_connection_path, confirm: "Stop syncing to AirTrail? Flights already there stay." %></div>
<% end %>
</div>
<section class="card card-body space-y-2 text-sm text-slate-700">
<h3 class="font-semibold">Setting up the API key</h3>
<p class="text-xs">In AirTrail, open <strong>Settings → Security</strong> and create an API key with these scopes:</p>
<ul class="list-disc pl-5 font-mono text-xs"><% AirTrailConnection::REQUIRED_SCOPES.each do |s| %><li><%= s %></li><% end %></ul>
<p class="text-xs">The key is stored encrypted. Flights go to the AirTrail account of the pilot who logged them, with you in the pilot seat, the tail number as registration, and the GPS track if one is attached.</p>
<p class="text-xs">Each aircraft's <strong>ICAO type</strong> (Edit aircraft) sets the aircraft type in AirTrail.</p>
</section>
</div>
+43
View File
@@ -0,0 +1,43 @@
<% content_for :title, "Export for AirTrail" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<div class="grid gap-5 lg:grid-cols-3">
<%= form_with url: aircraft_air_trail_export_path(@aircraft), class: "card card-body space-y-4 lg:col-span-2", data: { turbo: false } do |f| %>
<h2 class="card-title">Export flights for AirTrail</h2>
<% if @export.errors.any? %>
<div class="rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200"><ul class="list-disc pl-5"><% @export.errors.each do |e| %><li><%= e %></li><% end %></ul></div>
<% end %>
<div class="grid gap-4 sm:grid-cols-2">
<div>
<%= label_tag :username, "Your AirTrail username", class: "label" %>
<%= text_field_tag :username, params[:username].presence || @export.as_json[:users].first[:username], class: "input", required: true, autocomplete: "off" %>
<p class="hint">AirTrail assigns the flights to the account with this username (you can also pick the account while importing).</p>
</div>
<div>
<%= label_tag :aircraft_type, "Aircraft type (ICAO, optional)", class: "label" %>
<%= text_field_tag :aircraft_type, params[:aircraft_type].presence || @aircraft.icao_type, class: "input", placeholder: "C150", maxlength: 4 %>
<p class="hint">ICAO type designator, e.g. C150, C172, PA28.</p>
</div>
</div>
<fieldset class="space-y-1 text-sm">
<legend class="label">Flights</legend>
<label class="flex items-center gap-2"><%= radio_button_tag :scope, "all", params[:scope] != "mine" %> All <%= @aircraft.tail_number %> flights</label>
<label class="flex items-center gap-2"><%= radio_button_tag :scope, "mine", params[:scope] == "mine" %> Only flights I logged</label>
</fieldset>
<% all = AirTrailExport.new(@aircraft, username: "preview") %>
<p class="text-sm text-slate-600">
<%= pluralize(all.exportable.size, "flight") %> ready to export<% if all.skipped.positive? %>; <%= all.skipped %> skipped because the From or To airport is missing or isn't a code AirTrail can look up<% end %>.
</p>
<%= f.submit "Download AirTrail file", class: "btn-primary" %>
<% end %>
<section class="card card-body space-y-2 text-sm text-slate-700">
<h3 class="font-semibold">Importing into AirTrail</h3>
<ol class="list-decimal space-y-1 pl-4 text-xs">
<li>In AirTrail, open <strong>Settings → Import</strong> and choose <strong>AirTrail</strong> as the source.</li>
<li>Select the downloaded file.</li>
<li>Map any airports AirTrail doesn't recognize (small private fields may need this).</li>
</ol>
<p class="text-xs">Each flight is imported with you in the pilot seat, the tail number as the registration, and its tach/Hobbs time in the note. Duration comes from Hobbs time (or tach). GPS track logs (GPX, KML or CSV) are included.</p>
<p class="text-xs">Prefer automatic? <%= link_to "Set up AirTrail sync", air_trail_connection_path, class: "link" %> to push new flights as you log them.</p>
<p class="text-xs">Re-importing later is safe with AirTrail's de-duplication left on; repeat legs on the same day and route are numbered #2, #3… so they aren't merged.</p>
</section>
</div>
+1
View File
@@ -7,6 +7,7 @@
<%= f.field :serial_number %>
<%= f.field :purchased, as: :date %>
<%= f.field :status, as: :select, collection: Aircraft::STATUSES.invert %>
<%= f.field :icao_type, label: "ICAO type", placeholder: "C150", maxlength: 4, hint: "Type designator, used for AirTrail." %>
</div>
<%= f.field :description, as: :textarea, rows: 3 %>
<div class="grid gap-4 sm:grid-cols-4">
+65
View File
@@ -0,0 +1,65 @@
<% content_for :title, "Standardize airport codes" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<% changes = @standardizer.changes %>
<%= form_with url: aircraft_airport_codes_path(@aircraft), method: :patch, class: "space-y-5" do |f| %>
<section class="card">
<div class="card-header">
<h2 class="card-title">Standardize airport codes</h2>
<span class="text-xs text-slate-500"><%= pluralize(changes.size, "code") %> to update · <%= changes.sum(&:flights) %> entries</span>
</div>
<div class="card-body text-sm text-slate-600">
Rewrites the airport codes in <%= @aircraft.tail_number %>'s flight log to the airport database's standard code: the ICAO-style code AirTrail uses (e.g. 1B9 → K1B9). New flights picked from autocomplete already use these codes. Untick anything you'd rather keep as is.
</div>
<% if changes.any? %>
<table class="table">
<thead><tr><th class="w-8"><input type="checkbox" checked aria-label="Select all" onclick="this.closest('table').querySelectorAll('tbody input[type=checkbox]').forEach(c => c.checked = this.checked)"></th><th>Logged</th><th>Standard</th><th>Airport</th><th class="text-right">Entries</th></tr></thead>
<tbody>
<% changes.each do |c| %>
<tr>
<td><%= check_box_tag "codes[]", c.from, c.suggested, id: "code_#{c.from.parameterize}" %></td>
<td class="font-mono"><%= label_tag "code_#{c.from.parameterize}", c.from %></td>
<td class="font-mono font-semibold"><%= c.to %></td>
<td><%= c.airport.name %> <span class="text-xs text-slate-500"><%= c.airport.place %></span>
<% if c.note %><div class="text-xs text-amber-700"><%= c.note %></div><% end %></td>
<td class="text-right tabular-nums"><%= c.flights %></td>
</tr>
<% end %>
</tbody>
</table>
<% else %>
<%= empty_state "All logged codes already match the airport database." %>
<% end %>
</section>
<% if @standardizer.unknown.any? %>
<section class="card">
<div class="card-header"><h2 class="card-title">Not in the airport database</h2></div>
<div class="card-body space-y-3 text-sm">
<p class="text-slate-600">Often a typo. Tick “Fix” and choose the airport these entries should be. Unticked codes are left unchanged.<% if current_user.admin? %> For a private strip that isn't listed, add it as a <%= link_to "custom airport", admin_airports_path, class: "link" %>.<% end %></p>
<% @standardizer.unknown.each do |u| %>
<div class="flex flex-wrap items-start gap-3">
<label class="mt-2 flex items-center gap-2"><%= check_box_tag "fix[]", u.code, u.suggestion.present?, id: "fix_#{u.code.parameterize}" %> Fix</label>
<div class="mt-2 w-16 font-mono"><%= u.code %></div>
<div class="mt-2 text-xs text-slate-500"><%= pluralize(u.flights, "entry") %> →</div>
<div class="relative w-72" data-controller="airport-autocomplete"
data-airport-autocomplete-url-value="<%= airport_search_path(aircraft_id: @aircraft.id) %>">
<%= text_field_tag "fixes[#{u.code}]", u.suggestion&.code, class: "input font-mono uppercase placeholder:normal-case placeholder:font-sans",
placeholder: "Airport code or name", "aria-label": "Airport for #{u.code}",
data: { airport_autocomplete_target: "input",
action: "input->airport-autocomplete#search keydown->airport-autocomplete#keydown blur->airport-autocomplete#blur" } %>
<ul data-airport-autocomplete-target="list" role="listbox" hidden
class="absolute z-20 mt-1 max-h-72 w-[min(28rem,90vw)] overflow-auto rounded-md bg-white py-1 shadow-lg ring-1 ring-slate-200"></ul>
<p class="hint min-h-4" data-airport-autocomplete-target="hint"></p>
</div>
<% if u.suggestion %><div class="mt-2 text-xs text-sky-800">Suggested: <%= u.suggestion.name %>, <%= u.suggestion.place %> (letters swapped?)</div><% end %>
</div>
<% end %>
</div>
</section>
<% end %>
<div class="flex gap-2">
<% if changes.any? || @standardizer.unknown.any? %><%= f.submit "Update selected codes", class: "btn-primary", data: { turbo_confirm: "Rewrite the selected airport codes in #{@aircraft.tail_number}'s flight log?" } %><% end %>
<%= link_to "Back to flights", aircraft_flight_logs_path(@aircraft), class: "btn-secondary" %>
</div>
<% end %>
+1 -1
View File
@@ -2,7 +2,7 @@
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<% if @stats.any? %><%= render "flight_logs/stats", stats: @stats %><% end %>
<section class="card">
<div class="card-header"><h2 class="card-title">Flight Log</h2><div class="flex gap-2"><% if owner? %><%= link_to "Import from spreadsheet", new_aircraft_flight_import_path(@aircraft), class: "btn-secondary" %><% end %><%= link_to "+ Log Flight", new_aircraft_flight_log_path(@aircraft), class: "btn-primary" %></div></div>
<div class="card-header"><h2 class="card-title">Flight Log</h2><div class="flex gap-2"><%= link_to "Export for AirTrail", new_aircraft_air_trail_export_path(@aircraft), class: "btn-secondary" %><% if owner? %><%= link_to "Standardize airport codes", aircraft_airport_codes_path(@aircraft), class: "btn-secondary" %><%= link_to "Import from spreadsheet", new_aircraft_flight_import_path(@aircraft), class: "btn-secondary" %><% end %><%= link_to "+ Log Flight", new_aircraft_flight_log_path(@aircraft), class: "btn-primary" %></div></div>
<% if @flight_logs.any? %>
<div class="overflow-x-auto">
<table class="table">
+2 -2
View File
@@ -4,8 +4,8 @@
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-3">
<%= f.field :date, as: :date, required: true %>
<%= f.field :departure_location, label: "From", placeholder: "KPVD" %>
<%= f.field :destination_location, label: "To", placeholder: "KBID" %>
<%= render "shared/airport_field", f: f, attribute: :departure_location, label: "From", aircraft: @aircraft, placeholder: "KOQU" %>
<%= render "shared/airport_field", f: f, attribute: :destination_location, label: "To", aircraft: @aircraft, placeholder: "Code or name" %>
</div>
<fieldset class="grid gap-4 sm:grid-cols-3">
<legend class="mb-2 text-sm font-semibold">Tach (required)</legend>
+11 -1
View File
@@ -9,7 +9,17 @@
<dt class="text-slate-500">Oil added</dt><dd><%= @flight_log.oil_added ? "#{@flight_log.oil_added} qt #{@flight_log.oil_added_type}" : "—" %></dd>
<dt class="text-slate-500">Fuel added</dt><dd><%= @flight_log.fuel_added ? "#{@flight_log.fuel_added} gal #{@flight_log.fuel_added_type}" : "—" %></dd>
<dt class="text-slate-500">Pilot</dt><dd><%= @flight_log.user&.display_name || "—" %></dd>
<dt class="text-slate-500">Track log</dt><dd><%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %></dd>
<dt class="text-slate-500">Track log</dt><dd class="col-span-3"><%= @flight_log.track_log.attached? ? link_to(@flight_log.track_log.filename, rails_blob_path(@flight_log.track_log, disposition: :attachment), class: "link") : "—" %>
<% if @track %><span class="text-xs text-slate-500"> · <%= number_with_delimiter(@track.points) %> GPS points<%= " · max #{number_with_delimiter(@track.max_altitude_ft)} ft" if @track.max_altitude_ft %></span>
<% elsif @track_error %><span class="text-xs text-amber-700"> · <%= @track_error %></span><% end %></dd>
<% if @air_trail_sync || @air_trail_connection %>
<dt class="text-slate-500">AirTrail</dt>
<dd class="col-span-3 text-xs">
<% if @air_trail_sync&.status == "synced" %><span class="badge-green">Synced</span> <%= time_ago_in_words(@air_trail_sync.synced_at) %> ago
<% elsif @air_trail_sync&.status == "error" %><span class="badge-red">Not synced</span> <%= @air_trail_sync.last_error %>
<% else %><span class="badge-gray">Pending</span><% end %>
</dd>
<% end %>
</dl>
<% if @flight_log.notes.present? %><div class="border-t border-slate-100 px-4 py-3 text-sm"><%= simple_format @flight_log.notes %></div><% end %>
</section>
+10 -2
View File
@@ -25,8 +25,16 @@
<nav class="flex items-center gap-4 text-sm">
<%= link_to "Fleet", root_path, class: "hover:text-sky-300" %>
<% if current_user.admin? %>
<%= link_to "Users", admin_users_path, class: "hover:text-sky-300" %>
<%= link_to "Component Types", admin_component_types_path, class: "hover:text-sky-300 hidden sm:inline" %>
<details class="relative" data-controller="dropdown" data-action="click@window->dropdown#closeOutside keydown.esc@window->dropdown#close">
<summary class="flex cursor-pointer list-none items-center gap-1 hover:text-sky-300 [&::-webkit-details-marker]:hidden">
Admin <span aria-hidden="true" class="text-xs">▾</span>
</summary>
<div class="absolute right-0 z-30 mt-2 w-48 rounded-md bg-white py-1 text-slate-700 shadow-lg ring-1 ring-slate-200">
<% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ] ].each do |label, path| %>
<%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %>
<% end %>
</div>
</details>
<% end %>
<%= link_to current_user.display_name, edit_profile_path, class: "text-slate-300 hover:text-sky-300 hidden sm:inline" %>
<%= button_to "Sign out", session_path, method: :delete, class: "rounded bg-slate-700 px-2 py-1 hover:bg-slate-600" %>
+8
View File
@@ -7,3 +7,11 @@
<%= f.field :password_confirmation, as: :password, label: "Confirm new password" %>
<%= f.submit "Save" %>
<% end %>
<section class="card card-body mt-5 max-w-md">
<h2 class="card-title">Integrations</h2>
<p class="mt-1 text-sm text-slate-600">
<%= link_to "AirTrail sync", air_trail_connection_path, class: "link" %>:
<%= current_user.air_trail_connection&.enabled? ? "on" : "off" %>. Push the flights you log to your AirTrail flight map automatically.
</p>
</section>
+11
View File
@@ -0,0 +1,11 @@
<%# Airport code input with autocomplete. locals: f, attribute, label, aircraft %>
<div class="relative" data-controller="airport-autocomplete"
data-airport-autocomplete-url-value="<%= airport_search_path(aircraft_id: aircraft.id) %>">
<%= f.label attribute, label, class: "label" %>
<%= f.text_field attribute, class: "input font-mono uppercase placeholder:normal-case placeholder:font-sans", placeholder: local_assigns[:placeholder], maxlength: 10,
data: { airport_autocomplete_target: "input",
action: "input->airport-autocomplete#search keydown->airport-autocomplete#keydown blur->airport-autocomplete#blur" } %>
<ul data-airport-autocomplete-target="list" role="listbox" hidden
class="absolute z-20 mt-1 max-h-72 w-[min(28rem,90vw)] overflow-auto rounded-md bg-white py-1 shadow-lg ring-1 ring-slate-200"></ul>
<p class="hint min-h-4" data-airport-autocomplete-target="hint"></p>
</div>