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
@@ -71,3 +71,5 @@ gem "roo", "~> 2.10"
|
||||
gem "csv", "~> 3.3"
|
||||
|
||||
gem "caxlsx", "~> 4.5", group: :test
|
||||
|
||||
gem "webmock", "~> 3.34", group: :test
|
||||
@@ -107,6 +107,9 @@ GEM
|
||||
chartkick (5.2.1)
|
||||
concurrent-ruby (1.3.8)
|
||||
connection_pool (3.0.2)
|
||||
crack (1.0.1)
|
||||
bigdecimal
|
||||
rexml
|
||||
crass (1.0.8)
|
||||
csv (3.3.7)
|
||||
date (3.6.0)
|
||||
@@ -125,6 +128,7 @@ GEM
|
||||
raabro (~> 1.4)
|
||||
globalid (1.4.0)
|
||||
activesupport (>= 6.1)
|
||||
hashdiff (1.2.1)
|
||||
htmlentities (4.4.2)
|
||||
i18n (1.15.2)
|
||||
concurrent-ruby (~> 1.0)
|
||||
@@ -377,6 +381,10 @@ GEM
|
||||
actionview (>= 8.0.0)
|
||||
bindex (>= 0.4.0)
|
||||
railties (>= 8.0.0)
|
||||
webmock (3.34.0)
|
||||
addressable (>= 2.8.0)
|
||||
crack (>= 0.3.2)
|
||||
hashdiff (>= 0.4.0, < 2.0.0)
|
||||
websocket (1.2.11)
|
||||
websocket-driver (0.8.2)
|
||||
base64
|
||||
@@ -425,6 +433,7 @@ DEPENDENCIES
|
||||
turbo-rails
|
||||
tzinfo-data
|
||||
web-console
|
||||
webmock (~> 3.34)
|
||||
|
||||
CHECKSUMS
|
||||
action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009
|
||||
@@ -456,6 +465,7 @@ CHECKSUMS
|
||||
chartkick (5.2.1) sha256=2848d7de87189f30f28d077eb0bbdebc8a1f0f6f81de1ded95008fe564369949
|
||||
concurrent-ruby (1.3.8) sha256=b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1
|
||||
connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a
|
||||
crack (1.0.1) sha256=ff4a10390cd31d66440b7524eb1841874db86201d5b70032028553130b6d4c7e
|
||||
crass (1.0.8) sha256=7a0145c7a2c59f8e7923b3a69ce819c444823a00a5127d805298fea13be24efe
|
||||
csv (3.3.7) sha256=15a3f16f6628da8664d455eb634e7f22031bcf53044923caf56975109e71b9f8
|
||||
date (3.6.0) sha256=18ac945c4e24ebd93534f8eab8c2fd8c5604b3e977105b3798d62a1e8d27b580
|
||||
@@ -468,6 +478,7 @@ CHECKSUMS
|
||||
et-orbi (1.4.2) sha256=bb555dae668419cb24caa2a293a170e58be6d4df1e017c51f5030bdc133cd20c
|
||||
fugit (1.14.0) sha256=e311a9cc85a54bb67649df45060e721282a1e2c8ebad40e41874a3a7d576f37e
|
||||
globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427
|
||||
hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1
|
||||
htmlentities (4.4.2) sha256=bbafbdf69f2eca9262be4efef7e43e6a1de54c95eb600f26984f71d2fe96c5c3
|
||||
i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5
|
||||
importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a
|
||||
@@ -573,6 +584,7 @@ CHECKSUMS
|
||||
uri (1.1.2) sha256=89292e98eabbef6248b0a0ed5e7e398e152f83f17560023a6d94a7f492b169fb
|
||||
useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844
|
||||
web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4
|
||||
webmock (3.34.0) sha256=72eed29dc8c00148d592acaedaaa6b869e2e397de57dfc8602b84aa834f46b33
|
||||
websocket (1.2.11) sha256=b7e7a74e2410b5e85c25858b26b3322f29161e300935f70a0e0d3c35e0462737
|
||||
websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146
|
||||
websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 %>
|
||||
@@ -0,0 +1,2 @@
|
||||
<h1 class="mb-4 text-2xl font-bold">Edit <%= @airport.ident %></h1>
|
||||
<%= render "form", airport: @airport %>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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">
|
||||
|
||||
@@ -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 %>
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
@@ -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" %>
|
||||
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -0,0 +1,11 @@
|
||||
# Keys for Active Record encryption (used for stored API keys), derived from
|
||||
# SECRET_KEY_BASE so no extra secrets are needed. Changing SECRET_KEY_BASE
|
||||
# makes previously stored API keys unreadable; they'd need re-entering.
|
||||
Rails.application.config.after_initialize do
|
||||
generator = Rails.application.key_generator
|
||||
ActiveRecord::Encryption.configure(
|
||||
primary_key: generator.generate_key("active_record_encryption/primary_key", 32).unpack1("H*"),
|
||||
deterministic_key: generator.generate_key("active_record_encryption/deterministic_key", 32).unpack1("H*"),
|
||||
key_derivation_salt: generator.generate_key("active_record_encryption/key_derivation_salt", 32).unpack1("H*")
|
||||
)
|
||||
end
|
||||
@@ -0,0 +1,12 @@
|
||||
# Like AirTrail: when the server starts with no airport data, download it
|
||||
# from OurAirports in the background. Admins can update it later from
|
||||
# Admin → Airports.
|
||||
Rails.application.config.after_initialize do
|
||||
next unless defined?(Rails::Server)
|
||||
|
||||
begin
|
||||
AirportUpdateJob.ensure_populated
|
||||
rescue ActiveRecord::ActiveRecordError => e
|
||||
Rails.logger.warn("[airports] couldn't check airport data at boot: #{e.message}")
|
||||
end
|
||||
end
|
||||
@@ -3,6 +3,11 @@ Rails.application.routes.draw do
|
||||
resources :passwords, param: :token
|
||||
resource :setup, only: %i[new create], controller: "setup"
|
||||
resource :profile, only: %i[edit update]
|
||||
resource :air_trail_connection, path: "profile/airtrail", only: %i[show create update destroy] do
|
||||
post :test
|
||||
post :sync
|
||||
post :map_airport
|
||||
end
|
||||
|
||||
resources :aircraft do
|
||||
member do
|
||||
@@ -20,6 +25,8 @@ Rails.application.routes.draw do
|
||||
end
|
||||
resources :notes, except: :show
|
||||
resources :flight_logs, only: %i[index new create show destroy]
|
||||
resource :air_trail_export, path: "airtrail_export", only: %i[new create]
|
||||
resource :airport_codes, only: %i[show update]
|
||||
resource :flight_import, only: %i[new create show] do
|
||||
post :confirm
|
||||
end
|
||||
@@ -43,12 +50,17 @@ Rails.application.routes.draw do
|
||||
resources :events, only: :index
|
||||
end
|
||||
|
||||
get "airports/search", to: "airports#search", as: :airport_search
|
||||
|
||||
# Public read-only share links (no login).
|
||||
get "shared/:token", to: "shared#show", as: :shared
|
||||
|
||||
namespace :admin do
|
||||
resources :users, except: :show
|
||||
resources :component_types, except: :show
|
||||
resources :airports, except: :show do
|
||||
collection { post :refresh }
|
||||
end
|
||||
end
|
||||
|
||||
get "up" => "rails/health#show", as: :rails_health_check
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
class CreateAirTrailSync < ActiveRecord::Migration[8.1]
|
||||
def change
|
||||
# ICAO type designator (e.g. C150), used for AirTrail's aircraft type.
|
||||
add_column :aircraft, :icao_type, :string
|
||||
|
||||
# One AirTrail account per user; flights sync to their pilot's account.
|
||||
create_table :air_trail_connections do |t|
|
||||
t.references :user, null: false, foreign_key: true, index: { unique: true }
|
||||
t.string :base_url, null: false
|
||||
t.text :api_key, null: false # encrypted
|
||||
t.boolean :enabled, null: false, default: true
|
||||
t.string :remote_user_id
|
||||
t.string :remote_username
|
||||
t.string :status # ok | error
|
||||
t.text :last_error
|
||||
t.datetime :checked_at
|
||||
t.datetime :backfilled_at
|
||||
t.timestamps
|
||||
end
|
||||
|
||||
# Which AirTrail flight each local flight corresponds to.
|
||||
create_table :air_trail_syncs do |t|
|
||||
t.references :air_trail_connection, null: false, foreign_key: true
|
||||
t.references :flight_log, null: false, foreign_key: true
|
||||
t.integer :remote_id
|
||||
t.string :payload_digest
|
||||
t.string :status, null: false, default: "pending" # pending | synced | error
|
||||
t.text :last_error
|
||||
t.datetime :synced_at
|
||||
t.timestamps
|
||||
end
|
||||
add_index :air_trail_syncs, [ :air_trail_connection_id, :flight_log_id ], unique: true, name: "idx_air_trail_syncs_unique"
|
||||
|
||||
# Airport code → AirTrail airport id (nil = looked up, not found).
|
||||
create_table :air_trail_airports do |t|
|
||||
t.references :air_trail_connection, null: false, foreign_key: true
|
||||
t.string :code, null: false
|
||||
t.integer :remote_id
|
||||
t.string :remote_icao
|
||||
t.boolean :manual, null: false, default: false
|
||||
t.datetime :looked_up_at
|
||||
t.timestamps
|
||||
end
|
||||
add_index :air_trail_airports, [ :air_trail_connection_id, :code ], unique: true, name: "idx_air_trail_airports_unique"
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,32 @@
|
||||
# Airport reference data (OurAirports, the source AirTrail uses) for
|
||||
# autocomplete and for translating codes to AirTrail's. The data itself is
|
||||
# downloaded on first start (AirportUpdateJob), as AirTrail does.
|
||||
class CreateAirports < ActiveRecord::Migration[8.1]
|
||||
def up
|
||||
create_table :airports do |t|
|
||||
t.string :ident, null: false
|
||||
t.string :airtrail_code, null: false
|
||||
t.string :gps_code
|
||||
t.string :local_code
|
||||
t.string :iata
|
||||
t.string :name, null: false
|
||||
t.string :kind
|
||||
t.string :municipality
|
||||
t.string :region
|
||||
t.string :country
|
||||
t.float :latitude
|
||||
t.float :longitude
|
||||
t.integer :elevation_ft
|
||||
t.timestamps
|
||||
end
|
||||
add_index :airports, :ident, unique: true
|
||||
add_index :airports, :airtrail_code
|
||||
add_index :airports, :gps_code
|
||||
add_index :airports, :local_code
|
||||
add_index :airports, :iata
|
||||
end
|
||||
|
||||
def down
|
||||
drop_table :airports
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,21 @@
|
||||
class AddCustomAirportsAndUpdates < ActiveRecord::Migration[8.1]
|
||||
def change
|
||||
# Airports added by an admin; never touched by OurAirports updates.
|
||||
add_column :airports, :custom, :boolean, null: false, default: false
|
||||
add_index :airports, :custom
|
||||
|
||||
# History of OurAirports updates (shown on the admin Airports page).
|
||||
create_table :airport_updates do |t|
|
||||
t.string :status, null: false, default: "queued" # queued | running | done | failed
|
||||
t.string :source_url
|
||||
t.integer :created_count, null: false, default: 0
|
||||
t.integer :updated_count, null: false, default: 0
|
||||
t.integer :removed_count, null: false, default: 0
|
||||
t.text :error
|
||||
t.references :requested_by, foreign_key: { to_table: :users, on_delete: :nullify }
|
||||
t.datetime :started_at
|
||||
t.datetime :finished_at
|
||||
t.timestamps
|
||||
end
|
||||
end
|
||||
end
|
||||
Generated
+91
-1
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[8.1].define(version: 2026_11_06_120000) do
|
||||
ActiveRecord::Schema[8.1].define(version: 2026_11_06_150000) do
|
||||
create_table "active_storage_attachments", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "record_type", null: false
|
||||
@@ -60,6 +60,50 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_06_120000) do
|
||||
t.index ["logbook_entry_id"], name: "index_ad_compliances_on_logbook_entry_id"
|
||||
end
|
||||
|
||||
create_table "air_trail_airports", force: :cascade do |t|
|
||||
t.integer "air_trail_connection_id", null: false
|
||||
t.string "code", null: false
|
||||
t.integer "remote_id"
|
||||
t.string "remote_icao"
|
||||
t.boolean "manual", default: false, null: false
|
||||
t.datetime "looked_up_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["air_trail_connection_id", "code"], name: "idx_air_trail_airports_unique", unique: true
|
||||
t.index ["air_trail_connection_id"], name: "index_air_trail_airports_on_air_trail_connection_id"
|
||||
end
|
||||
|
||||
create_table "air_trail_connections", force: :cascade do |t|
|
||||
t.integer "user_id", null: false
|
||||
t.string "base_url", null: false
|
||||
t.text "api_key", null: false
|
||||
t.boolean "enabled", default: true, null: false
|
||||
t.string "remote_user_id"
|
||||
t.string "remote_username"
|
||||
t.string "status"
|
||||
t.text "last_error"
|
||||
t.datetime "checked_at"
|
||||
t.datetime "backfilled_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["user_id"], name: "index_air_trail_connections_on_user_id", unique: true
|
||||
end
|
||||
|
||||
create_table "air_trail_syncs", force: :cascade do |t|
|
||||
t.integer "air_trail_connection_id", null: false
|
||||
t.integer "flight_log_id", null: false
|
||||
t.integer "remote_id"
|
||||
t.string "payload_digest"
|
||||
t.string "status", default: "pending", null: false
|
||||
t.text "last_error"
|
||||
t.datetime "synced_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["air_trail_connection_id", "flight_log_id"], name: "idx_air_trail_syncs_unique", unique: true
|
||||
t.index ["air_trail_connection_id"], name: "index_air_trail_syncs_on_air_trail_connection_id"
|
||||
t.index ["flight_log_id"], name: "index_air_trail_syncs_on_flight_log_id"
|
||||
end
|
||||
|
||||
create_table "aircraft", force: :cascade do |t|
|
||||
t.string "tail_number", null: false
|
||||
t.string "make"
|
||||
@@ -75,6 +119,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_06_120000) do
|
||||
t.boolean "airworthiness_enforcement", default: false, null: false
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.string "icao_type"
|
||||
end
|
||||
|
||||
create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t|
|
||||
@@ -124,6 +169,46 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_06_120000) do
|
||||
t.index ["user_id"], name: "index_aircraft_roles_on_user_id"
|
||||
end
|
||||
|
||||
create_table "airport_updates", force: :cascade do |t|
|
||||
t.string "status", default: "queued", null: false
|
||||
t.string "source_url"
|
||||
t.integer "created_count", default: 0, null: false
|
||||
t.integer "updated_count", default: 0, null: false
|
||||
t.integer "removed_count", default: 0, null: false
|
||||
t.text "error"
|
||||
t.integer "requested_by_id"
|
||||
t.datetime "started_at"
|
||||
t.datetime "finished_at"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["requested_by_id"], name: "index_airport_updates_on_requested_by_id"
|
||||
end
|
||||
|
||||
create_table "airports", force: :cascade do |t|
|
||||
t.string "ident", null: false
|
||||
t.string "airtrail_code", null: false
|
||||
t.string "gps_code"
|
||||
t.string "local_code"
|
||||
t.string "iata"
|
||||
t.string "name", null: false
|
||||
t.string "kind"
|
||||
t.string "municipality"
|
||||
t.string "region"
|
||||
t.string "country"
|
||||
t.float "latitude"
|
||||
t.float "longitude"
|
||||
t.integer "elevation_ft"
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.boolean "custom", default: false, null: false
|
||||
t.index ["airtrail_code"], name: "index_airports_on_airtrail_code"
|
||||
t.index ["custom"], name: "index_airports_on_custom"
|
||||
t.index ["gps_code"], name: "index_airports_on_gps_code"
|
||||
t.index ["iata"], name: "index_airports_on_iata"
|
||||
t.index ["ident"], name: "index_airports_on_ident", unique: true
|
||||
t.index ["local_code"], name: "index_airports_on_local_code"
|
||||
end
|
||||
|
||||
create_table "airworthiness_directives", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "short_description", null: false
|
||||
@@ -394,12 +479,17 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_06_120000) do
|
||||
add_foreign_key "ad_compliances", "components"
|
||||
add_foreign_key "ad_compliances", "inspection_records", on_delete: :nullify
|
||||
add_foreign_key "ad_compliances", "logbook_entries", on_delete: :nullify
|
||||
add_foreign_key "air_trail_airports", "air_trail_connections"
|
||||
add_foreign_key "air_trail_connections", "users"
|
||||
add_foreign_key "air_trail_syncs", "air_trail_connections"
|
||||
add_foreign_key "air_trail_syncs", "flight_logs"
|
||||
add_foreign_key "aircraft_events", "aircraft"
|
||||
add_foreign_key "aircraft_events", "users", on_delete: :nullify
|
||||
add_foreign_key "aircraft_notes", "aircraft"
|
||||
add_foreign_key "aircraft_notes", "users", on_delete: :nullify
|
||||
add_foreign_key "aircraft_roles", "aircraft"
|
||||
add_foreign_key "aircraft_roles", "users"
|
||||
add_foreign_key "airport_updates", "users", column: "requested_by_id", on_delete: :nullify
|
||||
add_foreign_key "airworthiness_directives", "documents", on_delete: :nullify
|
||||
add_foreign_key "components", "aircraft"
|
||||
add_foreign_key "components", "component_types"
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
require "csv"
|
||||
require "open-uri"
|
||||
|
||||
# Keeps the airports table in sync with OurAirports
|
||||
# (https://ourairports.com/data/, public domain), the source AirTrail uses,
|
||||
# the way AirTrail does (src/lib/utils/data/airports/source.ts):
|
||||
#
|
||||
# - On first start the table is empty, so it's populated by downloading the
|
||||
# data (AirportUpdateJob, queued at boot).
|
||||
# - An admin can update it later: new airports are added, changed ones
|
||||
# updated, ones no longer in OurAirports removed. Rows keep their ids.
|
||||
# - Custom airports (added by an admin) are never touched, and a source
|
||||
# airport with the same identifier as a custom one is skipped.
|
||||
#
|
||||
# Each airport gets AirTrail's code for it (createAirportCode): the
|
||||
# 4-character GPS code when it doesn't collide with another airport's
|
||||
# identifier, otherwise the OurAirports identifier.
|
||||
module AirportData
|
||||
SOURCE_URL = "https://davidmegginson.github.io/ourairports-data/airports.csv".freeze
|
||||
BATCH = 2_000
|
||||
FIELDS = %i[airtrail_code gps_code local_code iata name kind municipality region country latitude longitude elevation_ft].freeze
|
||||
|
||||
module_function
|
||||
|
||||
# Download and sync. Returns { created:, updated:, removed: }.
|
||||
def refresh!(url = SOURCE_URL)
|
||||
Tempfile.create([ "airports", ".csv" ], binmode: true) do |file|
|
||||
URI.parse(url).open(read_timeout: 300, open_timeout: 30) { |remote| IO.copy_stream(remote, file) }
|
||||
file.flush
|
||||
file.rewind
|
||||
sync!(file)
|
||||
end
|
||||
end
|
||||
|
||||
# Sync from a CSV (IO or path) in OurAirports' format.
|
||||
def sync!(source)
|
||||
rows = read(source)
|
||||
custom = Airport.where(custom: true).pluck(:ident).to_set
|
||||
source_idents = rows.to_set { _1["ident"].to_s.strip.upcase }
|
||||
now = Time.current
|
||||
|
||||
incoming = rows.filter_map do |r|
|
||||
record = build(r, source_idents)
|
||||
record unless record.nil? || custom.include?(record[:ident])
|
||||
end.index_by { _1[:ident] }
|
||||
|
||||
existing = Airport.where(custom: false).pluck(:id, :ident, *FIELDS).to_h { |id, ident, *values| [ ident, [ id, FIELDS.zip(values).to_h ] ] }
|
||||
|
||||
created = incoming.except(*existing.keys).values
|
||||
changed = incoming.slice(*existing.keys).filter_map do |ident, rec|
|
||||
id, current = existing[ident]
|
||||
rec.slice(*FIELDS).merge(id: id, ident: ident) if normalize(current) != normalize(rec.slice(*FIELDS))
|
||||
end
|
||||
stale = existing.keys - incoming.keys
|
||||
|
||||
Airport.transaction do
|
||||
created.each_slice(BATCH) { |batch| Airport.insert_all(batch.map { _1.merge(created_at: now, updated_at: now) }) }
|
||||
changed.each_slice(BATCH) { |batch| Airport.upsert_all(batch.map { _1.merge(created_at: now, updated_at: now) }, unique_by: :id, update_only: FIELDS + [ :updated_at ]) }
|
||||
stale.each_slice(BATCH) { |idents| Airport.where(custom: false, ident: idents).delete_all }
|
||||
end
|
||||
{ created: created.size, updated: changed.size, removed: stale.size }
|
||||
end
|
||||
|
||||
def build(row, source_idents)
|
||||
ident = row["ident"].to_s.strip.upcase
|
||||
return nil if ident.empty?
|
||||
gps = row["gps_code"].to_s.strip.upcase.presence
|
||||
{
|
||||
ident: ident,
|
||||
airtrail_code: gps && gps.length == 4 && (!source_idents.include?(gps) || gps == ident) ? gps : ident,
|
||||
gps_code: gps,
|
||||
local_code: row["local_code"].to_s.strip.upcase.presence,
|
||||
iata: row["iata_code"].to_s.strip.upcase.presence,
|
||||
name: row["name"].to_s.strip,
|
||||
kind: row["type"].to_s.presence,
|
||||
municipality: row["municipality"].to_s.strip.presence,
|
||||
region: row["iso_region"].to_s.presence,
|
||||
country: row["iso_country"].to_s.presence,
|
||||
latitude: row["latitude_deg"].presence&.to_f,
|
||||
longitude: row["longitude_deg"].presence&.to_f,
|
||||
elevation_ft: row["elevation_ft"].presence&.to_f&.round
|
||||
}
|
||||
end
|
||||
|
||||
# Compare like with like (database floats/ints vs freshly parsed values).
|
||||
def normalize(attrs)
|
||||
attrs.transform_values { _1.is_a?(Float) ? _1.round(6) : _1 }
|
||||
end
|
||||
|
||||
def read(source)
|
||||
stream = source.respond_to?(:read) && !source.is_a?(Pathname)
|
||||
content = stream ? source.read : File.binread(source.to_s)
|
||||
CSV.parse(content.force_encoding("UTF-8").delete_prefix(""), headers: true).map(&:to_h)
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace :airports do
|
||||
desc "Update airports from OurAirports now (same as Admin → Airports → Update)"
|
||||
task update: :environment do
|
||||
update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL)
|
||||
AirportUpdateJob.perform_now(update.id)
|
||||
update.reload
|
||||
puts update.failed? ? "Failed: #{update.error}" : "Added #{update.created_count}, updated #{update.updated_count}, removed #{update.removed_count}"
|
||||
end
|
||||
end
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
Timestamp,Latitude,Longitude,Altitude,Speed
|
||||
1793023200000,41.597139,-71.412028,17,0
|
||||
1793023800000,41.42,-71.5,2500,95
|
||||
1793024700000,41.168056,-71.577778,110,60
|
||||
|
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<gpx version="1.1" creator="ForeFlight" xmlns="http://www.topografix.com/GPX/1/1">
|
||||
<trk><name>KOQU-KBID</name><trkseg>
|
||||
<trkpt lat="41.597139" lon="-71.412028"><ele>5.2</ele><time>2026-10-24T14:00:00Z</time></trkpt>
|
||||
<trkpt lat="41.420000" lon="-71.500000"><ele>762.0</ele><time>2026-10-24T14:10:00Z</time></trkpt>
|
||||
<trkpt lat="41.168056" lon="-71.577778"><ele>33.5</ele><time>2026-10-24T14:25:00Z</time></trkpt>
|
||||
</trkseg></trk>
|
||||
</gpx>
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
|
||||
<Document><Placemark><gx:Track>
|
||||
<when>2026-10-24T14:00:00Z</when><when>2026-10-24T14:10:00Z</when>
|
||||
<gx:coord>-71.412028 41.597139 5.2</gx:coord><gx:coord>-71.5 41.42 762</gx:coord>
|
||||
</gx:Track></Placemark></Document>
|
||||
</kml>
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<kml xmlns="http://www.opengis.net/kml/2.2"><Document><Placemark><LineString>
|
||||
<coordinates>-71.412028,41.597139,5 -71.5,41.42,762 -71.577778,41.168056,33</coordinates>
|
||||
</LineString></Placemark></Document></kml>
|
||||
@@ -0,0 +1,78 @@
|
||||
require "test_helper"
|
||||
|
||||
class AdminAirportsTest < ActionDispatch::IntegrationTest
|
||||
include ActiveJob::TestHelper
|
||||
|
||||
CSV_BODY = <<~CSV.freeze
|
||||
"id","ident","type","name","latitude_deg","longitude_deg","elevation_ft","continent","iso_country","iso_region","municipality","scheduled_service","icao_code","iata_code","gps_code","local_code","home_link","wikipedia_link","keywords"
|
||||
1,"KOQU","medium_airport","Quonset State Airport",41.597,-71.412,18,"NA","US","US-RI","North Kingstown","no","KOQU","NCO","KOQU","OQU",,,
|
||||
2,"K1B9","small_airport","Mansfield Municipal Airport",42.0,-71.19,122,"NA","US","US-MA","Mansfield","no",,,"1B9","1B9",,,
|
||||
CSV
|
||||
|
||||
setup do
|
||||
@admin = create_user("admin@example.com", admin: true)
|
||||
stub_request(:get, AirportData::SOURCE_URL).to_return(status: 200, body: CSV_BODY)
|
||||
end
|
||||
|
||||
test "admin updates from OurAirports in the background and sees the result" do
|
||||
sign_in @admin
|
||||
get admin_airports_path
|
||||
assert_response :success
|
||||
assert_select "details[data-controller='dropdown'] summary", text: /Admin/
|
||||
assert_select "details a[href='#{admin_airports_path}']", text: "Airports" # in the Admin menu
|
||||
assert_select "details a[href='#{admin_users_path}']", text: "Users"
|
||||
|
||||
perform_enqueued_jobs { post refresh_admin_airports_path }
|
||||
assert_redirected_to admin_airports_path
|
||||
assert_equal 2, Airport.count
|
||||
update = AirportUpdate.last
|
||||
assert_equal [ "done", 2, @admin ], [ update.status, update.created_count, update.requested_by ]
|
||||
follow_redirect!
|
||||
assert_match "2 added, 0 updated, 0 removed", response.body
|
||||
end
|
||||
|
||||
test "failed downloads are recorded" do
|
||||
stub_request(:get, AirportData::SOURCE_URL).to_return(status: 503)
|
||||
sign_in @admin
|
||||
perform_enqueued_jobs { post refresh_admin_airports_path }
|
||||
assert_equal "failed", AirportUpdate.last.status
|
||||
follow_redirect!
|
||||
assert_match "503", response.body
|
||||
end
|
||||
|
||||
test "first start populates an empty table once" do
|
||||
assert_enqueued_jobs(1, only: AirportUpdateJob) { AirportUpdateJob.ensure_populated }
|
||||
assert_no_enqueued_jobs(only: AirportUpdateJob) { AirportUpdateJob.ensure_populated } # already queued
|
||||
perform_enqueued_jobs
|
||||
assert_equal 2, Airport.count
|
||||
assert_no_enqueued_jobs(only: AirportUpdateJob) { AirportUpdateJob.ensure_populated } # has data
|
||||
end
|
||||
|
||||
test "admin manages custom airports; only custom ones are editable" do
|
||||
sign_in @admin
|
||||
get admin_airports_path(q: "0R8")
|
||||
assert_select "a[href='#{new_admin_airport_path(ident: '0R8')}']"
|
||||
post admin_airports_path, params: { airport: { ident: "0r8", name: "Grass Strip", kind: "small_airport", region: "US-RI" } }
|
||||
strip = Airport.find_by!(ident: "0R8")
|
||||
assert strip.custom?
|
||||
assert_equal "0R8", strip.airtrail_code
|
||||
patch admin_airport_path(strip), params: { airport: { name: "Grass Strip North" } }
|
||||
assert_equal "Grass Strip North", strip.reload.name
|
||||
|
||||
AirportData.sync!(StringIO.new(CSV_BODY))
|
||||
get edit_admin_airport_path(Airport.find_by!(ident: "KOQU"))
|
||||
assert_response :not_found
|
||||
delete admin_airport_path(strip)
|
||||
assert_not Airport.exists?(strip.id)
|
||||
end
|
||||
|
||||
test "non-admins can't reach it" do
|
||||
sign_in create_user
|
||||
get root_path
|
||||
assert_select "summary", text: /Admin/, count: 0
|
||||
get admin_airports_path
|
||||
assert_redirected_to root_path
|
||||
post refresh_admin_airports_path
|
||||
assert_equal 0, AirportUpdate.count
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,31 @@
|
||||
require "test_helper"
|
||||
|
||||
class AirTrailExportFlowTest < ActionDispatch::IntegrationTest
|
||||
setup do
|
||||
@pilot = create_user("ricky@example.com")
|
||||
@a = create_aircraft(pilot: @pilot, owner: create_user, tail_number: "N12345")
|
||||
@a.flight_logs.create!(date: Date.current, departure_location: "KOQU", destination_location: "KBID", tach_time: 0.5)
|
||||
sign_in @pilot
|
||||
end
|
||||
|
||||
test "pilot downloads the AirTrail file" do
|
||||
get aircraft_flight_logs_path(@a)
|
||||
assert_select "a[href='#{new_aircraft_air_trail_export_path(@a)}']", text: "Export for AirTrail"
|
||||
get new_aircraft_air_trail_export_path(@a)
|
||||
assert_response :success
|
||||
assert_select "input[name='username'][value='ricky']"
|
||||
assert_select "form[data-turbo='false']"
|
||||
|
||||
post aircraft_air_trail_export_path(@a), params: { username: "ricky", aircraft_type: "C150", scope: "all" }
|
||||
assert_response :success
|
||||
assert_equal "application/json", response.media_type
|
||||
assert_match(/attachment; filename="n12345-airtrail-.*\.json"/, response.headers["Content-Disposition"])
|
||||
assert_equal "KBID", JSON.parse(response.body)["flights"].first["to"]["code"]
|
||||
end
|
||||
|
||||
test "invalid username re-renders the form" do
|
||||
post aircraft_air_trail_export_path(@a), params: { username: "x" }
|
||||
assert_response :unprocessable_entity
|
||||
assert_match "3–20 letters", response.body
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,70 @@
|
||||
require "test_helper"
|
||||
|
||||
class AirTrailSyncFlowTest < ActionDispatch::IntegrationTest
|
||||
include ActiveJob::TestHelper
|
||||
|
||||
setup do
|
||||
@fake = FakeAirTrail.new(self)
|
||||
@user = create_user
|
||||
@a = create_aircraft(owner: @user, tail_number: "N12345", tach_time: 100)
|
||||
sign_in @user
|
||||
end
|
||||
|
||||
def connect(key: "at_secret")
|
||||
post air_trail_connection_path, params: { air_trail_connection: { base_url: "#{FakeAirTrail::BASE}/", api_key: key, enabled: "1" } }
|
||||
end
|
||||
|
||||
test "connect, see status, and flights sync automatically when logged and deleted" do
|
||||
get air_trail_connection_path
|
||||
assert_response :success
|
||||
connect
|
||||
assert_redirected_to air_trail_connection_path
|
||||
follow_redirect!
|
||||
assert_match "Connected to AirTrail as ricky", response.body
|
||||
assert_equal "https://airtrail.test", @user.air_trail_connection.base_url
|
||||
|
||||
perform_enqueued_jobs do
|
||||
post aircraft_flight_logs_path(@a), params: { flight_log: { date: Date.current, tach_out: 100, tach_in: 101.2,
|
||||
departure_location: "KOQU", destination_location: "KBID" } }
|
||||
end
|
||||
flight = @a.flight_logs.last
|
||||
sync = flight.air_trail_syncs.first
|
||||
assert_equal "synced", sync.status
|
||||
assert @fake.flights.key?(sync.remote_id)
|
||||
|
||||
get aircraft_flight_log_path(@a, flight)
|
||||
assert_select "span.badge-green", text: "Synced"
|
||||
|
||||
perform_enqueued_jobs { delete aircraft_flight_log_path(@a, flight) }
|
||||
assert_not @fake.flights.key?(sync.remote_id)
|
||||
end
|
||||
|
||||
test "missing scopes and bad keys are reported" do
|
||||
@fake.scopes = %w[profile.read flight.create.own]
|
||||
connect
|
||||
follow_redirect!
|
||||
assert_match "missing scopes", response.body
|
||||
assert_match "tracks.write", response.body
|
||||
|
||||
@user.air_trail_connection.destroy!
|
||||
connect(key: "wrong")
|
||||
follow_redirect!
|
||||
assert_match "Invalid API key", response.body
|
||||
end
|
||||
|
||||
test "updating keeps the stored key when left blank; sync all runs a backfill; disconnect" do
|
||||
connect
|
||||
patch air_trail_connection_path, params: { air_trail_connection: { base_url: FakeAirTrail::BASE, api_key: "" } }
|
||||
assert_equal "at_secret", @user.air_trail_connection.reload.api_key
|
||||
|
||||
assert_enqueued_with(job: AirTrailBackfillJob) { post sync_air_trail_connection_path }
|
||||
delete air_trail_connection_path
|
||||
assert_nil @user.reload.air_trail_connection
|
||||
end
|
||||
|
||||
test "flights by users without a connection don't enqueue anything" do
|
||||
assert_no_enqueued_jobs(only: AirTrailPushJob) do
|
||||
@a.flight_logs.create!(date: Date.current, tach_time: 1, user: @user, departure_location: "KOQU", destination_location: "KBID")
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -82,6 +82,38 @@ class PagesTest < ActionDispatch::IntegrationTest
|
||||
assert_select "a[href='https://drs.faa.gov/browse/excelExternalWindow/ABC.0001']", minimum: 2 # status + history
|
||||
end
|
||||
|
||||
test "new flight pre-fills From with the last flight's destination and offers airport search" do
|
||||
@a.flight_logs.create!(date: Date.current - 1, tach_time: 1.0, departure_location: "KOQU", destination_location: "kbid")
|
||||
get new_aircraft_flight_log_path(@a)
|
||||
assert_select "input[name='flight_log[departure_location]'][value='KBID']"
|
||||
assert_select "div[data-controller='airport-autocomplete'][data-airport-autocomplete-url-value='#{airport_search_path(aircraft_id: @a.id)}']", count: 2
|
||||
|
||||
AirportData.sync!(StringIO.new("ident,type,name,latitude_deg,longitude_deg,elevation_ft,iso_country,iso_region,municipality,gps_code,iata_code,local_code\nKBID,small_airport,Block Island State Airport,41.1,-71.5,108,US,US-RI,Block Island,KBID,BID,BID\n88LL,small_airport,Block Airport,41.9,-89.1,800,US,US-IL,Pearl City,88LL,,88LL\n"))
|
||||
get airport_search_path(q: "block", aircraft_id: @a.id)
|
||||
assert_equal %w[KBID 88LL], response.parsed_body.map { _1["code"] } # flown-to airport first
|
||||
end
|
||||
|
||||
test "owner standardizes airport codes from the Flights tab" do
|
||||
AirportData.sync!(StringIO.new("ident,type,name,latitude_deg,longitude_deg,elevation_ft,iso_country,iso_region,municipality,gps_code,iata_code,local_code\nK1B9,small_airport,Mansfield Municipal Airport,42,-71,122,US,US-MA,Mansfield,1B9,,1B9\n"))
|
||||
@a.flight_logs.create!(date: Date.current, tach_time: 1, departure_location: "1B9", destination_location: "1B9")
|
||||
get aircraft_flight_logs_path(@a)
|
||||
assert_select "a[href='#{aircraft_airport_codes_path(@a)}']"
|
||||
get aircraft_airport_codes_path(@a)
|
||||
assert_select "input[name='codes[]'][value='1B9'][checked]"
|
||||
patch aircraft_airport_codes_path(@a), params: { codes: [ "1B9" ] }
|
||||
assert_redirected_to aircraft_flight_logs_path(@a)
|
||||
assert_equal [ "K1B9", "K1B9" ], @a.flight_logs.last.slice(:departure_location, :destination_location).values
|
||||
|
||||
# a typo'd code: suggestion pre-filled, fixed only when ticked
|
||||
@a.flight_logs.create!(date: Date.current, tach_time: 1, departure_location: "K1B9", destination_location: "1K9B")
|
||||
get aircraft_airport_codes_path(@a)
|
||||
assert_select "input[name='fixes[1K9B]']"
|
||||
patch aircraft_airport_codes_path(@a), params: { fixes: { "1K9B" => "1B9" } } # not ticked
|
||||
assert_equal "1K9B", @a.flight_logs.last.destination_location
|
||||
patch aircraft_airport_codes_path(@a), params: { fix: [ "1K9B" ], fixes: { "1K9B" => "1B9" } }
|
||||
assert_equal "K1B9", @a.flight_logs.last.destination_location
|
||||
end
|
||||
|
||||
test "flights tab shows flying stats" do
|
||||
get aircraft_flight_logs_path(@a)
|
||||
assert_select "h2", text: "Flight hours by month"
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
require "test_helper"
|
||||
|
||||
class AirportTest < ActiveSupport::TestCase
|
||||
setup do
|
||||
# Rows shaped like OurAirports data, loaded through the real loader.
|
||||
csv = <<~CSV
|
||||
ident,type,name,latitude_deg,longitude_deg,elevation_ft,iso_country,iso_region,municipality,gps_code,iata_code,local_code
|
||||
KOQU,medium_airport,Quonset State Airport,41.597,-71.412,18,US,US-RI,North Kingstown,KOQU,NCO,OQU
|
||||
K1B9,small_airport,Mansfield Municipal Airport,42.0,-71.19,122,US,US-MA,Mansfield,1B9,,1B9
|
||||
K5M3,small_airport,Moultonborough Airport,43.76,-71.38,571,US,US-NH,Moultonborough,,,4MB
|
||||
KBID,small_airport,Block Island State Airport,41.168,-71.577,108,US,US-RI,Block Island,KBID,BID,BID
|
||||
88LL,small_airport,Block Airport,41.9,-89.1,800,US,US-IL,Pearl City,88LL,,88LL
|
||||
US-1,closed,Old Quonset Strip,41.5,-71.4,10,US,US-RI,North Kingstown,,,
|
||||
XAAA,small_airport,Collision Field,0,0,0,US,US-XX,,KOQU,,
|
||||
CSV
|
||||
@result = AirportData.sync!(StringIO.new(csv))
|
||||
end
|
||||
|
||||
test "loader applies AirTrail's code rule" do
|
||||
assert_equal({ created: 7, updated: 0, removed: 0 }, @result)
|
||||
assert_equal "K1B9", Airport.find_by(ident: "K1B9").airtrail_code # 3-char GPS code → ident
|
||||
assert_equal "KBID", Airport.find_by(ident: "KBID").airtrail_code
|
||||
assert_equal "XAAA", Airport.find_by(ident: "XAAA").airtrail_code # GPS code collides with another ident
|
||||
end
|
||||
|
||||
test "translates whatever code was logged to AirTrail's" do
|
||||
assert_equal "K1B9", Airport.airtrail_code_for("1b9")
|
||||
assert_equal "K5M3", Airport.airtrail_code_for("4MB")
|
||||
assert_equal "KBID", Airport.airtrail_code_for("BID")
|
||||
assert_equal "KOQU", Airport.airtrail_code_for("KOQU") # not the colliding XAAA
|
||||
assert_nil Airport.airtrail_code_for("ZZZZ")
|
||||
assert_equal "K1B9", Airport.lookup("1B9").code # standard (AirTrail/ICAO-style) code
|
||||
assert_equal [ "1B9" ], Airport.lookup("1B9").other_codes
|
||||
end
|
||||
|
||||
test "search: exact codes first, then prefixes, then names; closed last; familiar airports first" do
|
||||
assert_equal "KOQU", Airport.search("koqu").first.code
|
||||
assert_equal "KOQU", Airport.search("quonset").first.code
|
||||
assert_equal "Old Quonset Strip", Airport.search("quonset").last.name
|
||||
assert_equal [ "88LL", "KBID" ], Airport.search("block").map(&:code)
|
||||
assert_equal [ "KBID", "88LL" ], Airport.search("block", prefer: [ "KBID" ]).map(&:code)
|
||||
assert_empty Airport.search("k")
|
||||
assert_equal({ code: "K1B9", name: "Mansfield Municipal Airport", place: "Mansfield, MA", airtrail_code: "K1B9", kind: nil, aka: [ "1B9" ] },
|
||||
Airport.lookup("1B9").as_suggestion)
|
||||
end
|
||||
|
||||
HEADER = "ident,type,name,latitude_deg,longitude_deg,elevation_ft,iso_country,iso_region,municipality,gps_code,iata_code,local_code\n".freeze
|
||||
|
||||
test "updates in place like AirTrail: adds, changes, removes; ids stay stable" do
|
||||
koqu_id = Airport.find_by(ident: "KOQU").id
|
||||
csv = HEADER + <<~CSV
|
||||
KOQU,medium_airport,Quonset State Airport (renamed),41.597,-71.412,18,US,US-RI,North Kingstown,KOQU,NCO,OQU
|
||||
K1B9,small_airport,Mansfield Municipal Airport,42.0,-71.19,122,US,US-MA,Mansfield,1B9,,1B9
|
||||
KNEW,small_airport,New Field,40,-70,5,US,US-RI,Newtown,KNEW,,NEW
|
||||
CSV
|
||||
assert_equal({ created: 1, updated: 1, removed: 5 }, AirportData.sync!(StringIO.new(csv)))
|
||||
assert_equal koqu_id, Airport.find_by(ident: "KOQU").id
|
||||
assert_equal "Quonset State Airport (renamed)", Airport.find_by(ident: "KOQU").name
|
||||
assert_equal({ created: 0, updated: 0, removed: 0 }, AirportData.sync!(StringIO.new(csv))) # idempotent
|
||||
end
|
||||
|
||||
test "custom airports survive updates and win over a source airport with the same code" do
|
||||
Airport.create!(custom: true, ident: "0r8", name: "My Strip", kind: "small_airport")
|
||||
Airport.create!(custom: true, ident: "KNEW", name: "Our name for it", kind: "small_airport")
|
||||
csv = HEADER + "KNEW,small_airport,New Field,40,-70,5,US,US-RI,Newtown,KNEW,,NEW\n"
|
||||
AirportData.sync!(StringIO.new(csv))
|
||||
assert_equal "My Strip", Airport.find_by(ident: "0R8").name
|
||||
assert_equal "0R8", Airport.lookup("0r8").airtrail_code
|
||||
assert_equal "Our name for it", Airport.find_by(ident: "KNEW").name
|
||||
assert_equal 1, Airport.where(ident: "KNEW").count
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,88 @@
|
||||
require "test_helper"
|
||||
|
||||
class AirTrailExportTest < ActiveSupport::TestCase
|
||||
setup do
|
||||
@user = create_user
|
||||
@a = create_aircraft(owner: @user, tail_number: "N12345", make: "Cessna", model: "150L")
|
||||
end
|
||||
|
||||
def fly(date, from, to, tach:, hobbs: nil, user: @user, notes: nil)
|
||||
@a.flight_logs.create!(date: date, departure_location: from, destination_location: to,
|
||||
tach_time: tach, hobbs_time: hobbs, user: user, notes: notes)
|
||||
end
|
||||
|
||||
def export(**opts) = AirTrailExport.new(@a, username: "ricky", **opts)
|
||||
|
||||
test "builds AirTrail's import format" do
|
||||
fly Date.new(2026, 10, 24), "KLHV", "44N", tach: 1.9, hobbs: 2.0, notes: "Fall colors"
|
||||
data = JSON.parse(export(aircraft_type: "c150").to_json)
|
||||
|
||||
assert_equal [ { "id" => "sam-pilot", "username" => "ricky", "displayName" => "ricky" } ], data["users"]
|
||||
f = data["flights"].first
|
||||
assert_equal "2026-10-24", f["date"]
|
||||
assert_equal "day", f["datePrecision"]
|
||||
assert_equal({ "code" => "KLHV" }, f["from"])
|
||||
assert_equal({ "code" => "44N" }, f["to"])
|
||||
assert_equal 7200, f["duration"] # Hobbs 2.0 h in seconds
|
||||
assert_nil f["departure"]
|
||||
assert_nil f["arrival"]
|
||||
assert_nil f["airline"]
|
||||
assert_equal({ "name" => "Cessna 150L", "icao" => "C150" }, f["aircraft"])
|
||||
assert_equal "N12345", f["aircraftReg"]
|
||||
assert_nil f["flightNumber"]
|
||||
assert_equal "Tach 1.9 h · Hobbs 2.0 h\nFall colors", f["note"]
|
||||
passenger = f["passengers"].first
|
||||
assert_equal({ "userId" => "sam-pilot", "guestName" => nil, "seat" => "pilot", "seatNumber" => nil,
|
||||
"seatClass" => nil, "flightReason" => nil, "customFields" => {} }, passenger)
|
||||
# every key AirTrail requires (non-optional, nullable) is present
|
||||
%w[date from to departure arrival duration airline aircraft flightNumber aircraftReg note passengers].each { assert f.key?(_1), _1 }
|
||||
end
|
||||
|
||||
test "repeat legs on the same day and route get stable leg numbers so AirTrail doesn't merge them" do
|
||||
d = Date.new(2026, 6, 14)
|
||||
fly d, "KOQU", "KBID", tach: 0.4
|
||||
fly d, "KBID", "KOQU", tach: 0.4
|
||||
fly d, "KOQU", "KBID", tach: 0.5
|
||||
fly d + 1, "KOQU", "KBID", tach: 0.5
|
||||
numbers = JSON.parse(export.to_json)["flights"].map { _1["flightNumber"] }
|
||||
assert_equal [ nil, nil, "#2", nil ], numbers
|
||||
end
|
||||
|
||||
test "falls back to tach time; zero-time entries get no duration" do
|
||||
fly Date.current, "KOQU", "KOQU", tach: 1.5
|
||||
fly Date.current, "KDXR", "KDXR", tach: 0
|
||||
durations = JSON.parse(export.to_json)["flights"].map { _1["duration"] }
|
||||
assert_equal [ 5400, nil ], durations
|
||||
end
|
||||
|
||||
test "skips flights without usable airport codes and can limit to my flights" do
|
||||
other = create_user
|
||||
fly Date.current, "KOQU", "KBID", tach: 1
|
||||
fly Date.current, "", "KBID", tach: 1
|
||||
fly Date.current, "Home strip", "KBID", tach: 1
|
||||
fly Date.current, "KBID", "KOQU", tach: 1, user: other
|
||||
assert_equal [ 2, 2 ], [ export.exportable.size, export.skipped ]
|
||||
assert_equal 1, export(only_user: @user).exportable.size
|
||||
end
|
||||
|
||||
test "includes GPS tracks and defaults the aircraft type from the aircraft" do
|
||||
@a.update!(icao_type: "C150")
|
||||
f = fly Date.current, "KOQU", "KBID", tach: 1
|
||||
f.track_log.attach(io: File.open(Rails.root.join("test/fixtures/files/tracks/flight.kml")), filename: "flight.kml")
|
||||
fly Date.current, "KBID", "KOQU", tach: 1
|
||||
flights = JSON.parse(export.to_json)["flights"]
|
||||
assert_equal "kml", flights.first.dig("track", "sourceFormat")
|
||||
assert_equal 2, flights.first.dig("track", "times").size
|
||||
assert_not flights.last.key?("track")
|
||||
assert_equal "C150", flights.first.dig("aircraft", "icao")
|
||||
end
|
||||
|
||||
test "validates username and aircraft type" do
|
||||
fly Date.current, "KOQU", "KBID", tach: 1
|
||||
assert export.valid?
|
||||
assert_not AirTrailExport.new(@a, username: "ri").valid?
|
||||
assert_not AirTrailExport.new(@a, username: "jane pilot").valid?
|
||||
assert_not export(aircraft_type: "CESSNA").valid?
|
||||
assert_not AirTrailExport.new(create_aircraft, username: "ricky").valid? # no flights
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,130 @@
|
||||
require "test_helper"
|
||||
|
||||
class AirTrailSyncerTest < ActiveSupport::TestCase
|
||||
setup do
|
||||
@fake = FakeAirTrail.new(self)
|
||||
@user = create_user
|
||||
@a = create_aircraft(owner: @user, tail_number: "N12345", icao_type: "C150")
|
||||
@connection = AirTrailConnection.create!(user: @user, base_url: FakeAirTrail::BASE, api_key: "at_secret")
|
||||
@syncer = AirTrailSyncer.new(@connection)
|
||||
end
|
||||
|
||||
def fly(date, from, to, tach: 1.0, hobbs: nil, **attrs)
|
||||
# skip callbacks' job enqueueing noise: test adapter just records them
|
||||
@a.flight_logs.create!({ date: date, departure_location: from, destination_location: to, tach_time: tach,
|
||||
hobbs_time: hobbs, user: @user }.merge(attrs))
|
||||
end
|
||||
|
||||
test "api key is stored encrypted" do
|
||||
raw = AirTrailConnection.connection.select_value("select api_key from air_trail_connections where id = #{@connection.id}")
|
||||
assert_not_includes raw, "at_secret"
|
||||
assert_equal "at_secret", @connection.reload.api_key
|
||||
end
|
||||
|
||||
test "push creates the AirTrail flight with resolved ids, pilot seat and track" do
|
||||
f = fly(Date.new(2026, 10, 24), "KOQU", "KBID", tach: 0.5, hobbs: 0.6)
|
||||
f.track_log.attach(io: File.open(Rails.root.join("test/fixtures/files/tracks/flight.gpx")), filename: "flight.gpx")
|
||||
sync = @syncer.push(f)
|
||||
|
||||
assert_equal "synced", sync.status
|
||||
body = @fake.flights.fetch(sync.remote_id)
|
||||
assert_equal [ "2026-10-24", 101, 102, 7, 2160, "N12345" ],
|
||||
body.values_at("date", "fromId", "toId", "aircraftId", "duration", "aircraftReg")
|
||||
assert_equal [ { "userId" => "u-ricky", "guestName" => nil, "seat" => "pilot", "seatNumber" => nil,
|
||||
"seatClass" => nil, "flightReason" => nil, "customFields" => {} } ], body["passengers"]
|
||||
assert_equal "gpx", body.dig("track", "sourceFormat")
|
||||
assert_equal [ -71.412028, 41.597139, 5.2 ], body.dig("track", "coordinates", 0)
|
||||
assert_equal "ricky", @connection.reload.remote_username
|
||||
end
|
||||
|
||||
test "unchanged flights aren't re-sent; changed ones are replaced; deleted-in-AirTrail ones recreated" do
|
||||
f = fly(Date.current, "KOQU", "KBID")
|
||||
first = @syncer.push(f).remote_id
|
||||
puts_before = @fake.requests.count { _1[0] == :put }
|
||||
@syncer.push(f)
|
||||
assert_equal puts_before, @fake.requests.count { _1[0] == :put }
|
||||
|
||||
f.update!(notes: "Pattern work")
|
||||
@syncer.push(f)
|
||||
assert_equal "Tach 1.0 h\nPattern work", @fake.flights[first]["note"]
|
||||
|
||||
@fake.flights.delete(first)
|
||||
f.update!(notes: "Changed again")
|
||||
assert_not_equal first, @syncer.push(f).remote_id
|
||||
end
|
||||
|
||||
test "airports are looked up once and cached" do
|
||||
fly(Date.current, "KOQU", "KBID")
|
||||
fly(Date.current + 1, "KBID", "KOQU")
|
||||
@syncer.push(FlightLog.first)
|
||||
@syncer.push(FlightLog.last)
|
||||
assert_equal 2, @fake.requests.count { _1[1] == "/api/v1/airports" }
|
||||
end
|
||||
|
||||
test "unknown airports fail the flight with a clear error, and can be mapped by hand" do
|
||||
f = fly(Date.current, "53NH", "KOQU")
|
||||
sync = @syncer.push(f)
|
||||
assert_equal "error", sync.status
|
||||
assert_match "doesn't know airport 53NH", sync.last_error
|
||||
assert_equal [ "53NH" ], @connection.unresolved_airport_codes
|
||||
|
||||
assert @syncer.map_airport("53NH", "NH53")
|
||||
assert_equal "synced", @syncer.push(f).status
|
||||
assert_equal 106, @fake.flights.values.last["fromId"]
|
||||
end
|
||||
|
||||
test "logged codes are translated to AirTrail's through the airport database" do
|
||||
AirportData.sync!(StringIO.new("ident,type,name,latitude_deg,longitude_deg,elevation_ft,iso_country,iso_region,municipality,gps_code,iata_code,local_code\nK1B9,small_airport,Mansfield Municipal Airport,42,-71,122,US,US-MA,Mansfield,1B9,,1B9\n"))
|
||||
sync = @syncer.push(fly(Date.current, "KOQU", "1B9"))
|
||||
assert_equal "synced", sync.status
|
||||
assert_includes @fake.requests, [ :get, "/api/v1/airports", nil ]
|
||||
assert_equal FakeAirTrail::AIRPORTS["K1B9"], @fake.flights[sync.remote_id]["toId"]
|
||||
end
|
||||
|
||||
test "same-day repeat legs get leg numbers" do
|
||||
d = Date.current
|
||||
a = fly(d, "KOQU", "KBID")
|
||||
b = fly(d, "KOQU", "KBID")
|
||||
@syncer.push(a)
|
||||
@syncer.push(b)
|
||||
assert_equal [ nil, "#2" ], [ a, b ].map { @fake.flights[_1.air_trail_syncs.first.remote_id]["flightNumber"] }
|
||||
end
|
||||
|
||||
test "backfill links flights already in AirTrail (from a file import) instead of duplicating" do
|
||||
d = Date.new(2026, 10, 1)
|
||||
exact = fly(d, "KOQU", "KBID", hobbs: 1.2)
|
||||
repeat = fly(d, "KOQU", "KBID", hobbs: 0.8)
|
||||
remapped = fly(d + 1, "53NH", "KPVD", hobbs: 1.3) # hand-mapped to NH53 during the file import
|
||||
brand_new = fly(d + 2, "KPVD", "KMFD")
|
||||
e1 = @fake.add_existing(date: d.iso8601, from: "KOQU", to: "KBID")
|
||||
e2 = @fake.add_existing(date: d.iso8601, from: "KOQU", to: "KBID", flight_number: "#2")
|
||||
e3 = @fake.add_existing(date: (d + 1).iso8601, from: "NH53", to: "KPVD", duration: 4680)
|
||||
@fake.add_existing(date: d.iso8601, from: "KOQU", to: "KBID", reg: "N54321") # someone else's
|
||||
|
||||
result = @syncer.backfill
|
||||
assert_equal({ linked: 3, pushed: 4, failed: 0 }, result)
|
||||
assert_equal [ e1, e2, e3 ], [ exact, repeat, remapped ].map { _1.air_trail_syncs.first.remote_id }
|
||||
assert_equal 5, @fake.flights.size # 4 existing + brand_new
|
||||
assert brand_new.air_trail_syncs.first.remote_id
|
||||
assert_equal 106, @connection.airports.find_by(code: "53NH").remote_id # learned from the linked flight
|
||||
assert @connection.reload.backfilled_at
|
||||
end
|
||||
|
||||
test "bad key marks the connection" do
|
||||
@fake.valid_key = "other"
|
||||
assert_raises(AirTrailClient::AuthError) { @syncer.push(fly(Date.current, "KOQU", "KBID")) }
|
||||
assert_equal "error", @connection.reload.status
|
||||
assert_match "Invalid API key", @connection.last_error
|
||||
end
|
||||
|
||||
test "client follows pagination and maps errors" do
|
||||
3.times { |i| @fake.add_existing(date: "2026-01-0#{i + 1}", from: "KOQU", to: "KBID") }
|
||||
client = @connection.client
|
||||
ids = []
|
||||
client.each_flight { ids << _1["id"] }
|
||||
assert_equal 3, ids.size
|
||||
err = assert_raises(AirTrailClient::ValidationError) { client.create_flight({}) }
|
||||
assert_match "fromId Required", err.message
|
||||
assert_nil client.delete_flight(999_999) # 404 on delete is fine
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,52 @@
|
||||
require "test_helper"
|
||||
|
||||
class AirportCodeStandardizerTest < ActiveSupport::TestCase
|
||||
setup do
|
||||
AirportData.sync!(StringIO.new(<<~CSV))
|
||||
ident,type,name,latitude_deg,longitude_deg,elevation_ft,iso_country,iso_region,municipality,gps_code,iata_code,local_code
|
||||
KOQU,medium_airport,Quonset State Airport,41.6,-71.4,18,US,US-RI,North Kingstown,KOQU,NCO,OQU
|
||||
K1B9,small_airport,Mansfield Municipal Airport,42,-71.2,122,US,US-MA,Mansfield,1B9,,1B9
|
||||
K5M3,small_airport,Moultonborough Airport,43.8,-71.4,571,US,US-NH,Moultonborough,,,4MB
|
||||
08R,small_airport,Richmond Airport,41.5,-71.6,90,US,US-RI,West Kingston,,,08R
|
||||
KZZZ,closed,Old Field,40,-70,0,US,US-RI,Nowhere,,,ZZZ
|
||||
CSV
|
||||
@a = create_aircraft
|
||||
other = create_aircraft
|
||||
fly = ->(ac, from, to) { ac.flight_logs.create!(date: Date.current, tach_time: 1, departure_location: from, destination_location: to) }
|
||||
fly.(@a, "KOQU", "1B9")
|
||||
fly.(@a, "1B9", "4MB")
|
||||
fly.(@a, "4MB", "0R8")
|
||||
fly.(@a, "08R", "ZZZ")
|
||||
fly.(other, "1B9", "KOQU") # another aircraft: untouched
|
||||
@s = AirportCodeStandardizer.new(@a)
|
||||
end
|
||||
|
||||
test "previews each logged code against the standard code" do
|
||||
by_code = @s.changes.index_by(&:from)
|
||||
assert_equal %w[1B9 4MB ZZZ], by_code.keys.sort # KOQU and 08R already standard
|
||||
assert_equal [ "K1B9", 2, true, nil ], by_code["1B9"].to_h.values_at(:to, :flights, :suggested, :note)
|
||||
assert_match "Different identifier", by_code["4MB"].note
|
||||
assert_equal false, by_code["ZZZ"].suggested # closed airport: not pre-selected
|
||||
assert_equal [ "0R8", 1, "08R" ], @s.unknown.first.to_h.values_at(:code, :flights).push(@s.unknown.first.suggestion&.code)
|
||||
end
|
||||
|
||||
test "applies only the chosen codes, to this aircraft only" do
|
||||
assert_equal 4, @s.apply!(%w[1B9 4MB]) # 1B9 twice, 4MB twice
|
||||
assert_equal [ %w[KOQU K1B9], %w[K1B9 K5M3], %w[K5M3 0R8], %w[08R ZZZ] ],
|
||||
@a.flight_logs.order(:id).pluck(:departure_location, :destination_location)
|
||||
assert_equal "1B9", FlightLog.where.not(aircraft: @a).first.departure_location
|
||||
assert_match "1B9→K1B9", @a.events.first.notes
|
||||
assert_equal %w[ZZZ], AirportCodeStandardizer.new(@a).changes.map(&:from)
|
||||
end
|
||||
|
||||
test "fixes unknown codes (typos) to a chosen airport's standard code" do
|
||||
assert_equal 1, @s.apply!([], fixes: { "0R8" => "08R", "KOQU" => "1B9", "XXXX" => "1B9" }) # only real unknown codes
|
||||
assert_equal %w[4MB 08R], @a.flight_logs.order(:id).third.slice(:departure_location, :destination_location).values
|
||||
assert_empty AirportCodeStandardizer.new(@a).unknown
|
||||
assert_equal "KOQU", @a.flight_logs.order(:id).first.departure_location
|
||||
end
|
||||
|
||||
test "a fix to an airport not in the database is ignored" do
|
||||
assert_equal 0, @s.apply!([], fixes: { "0R8" => "NOPE" })
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,52 @@
|
||||
require "test_helper"
|
||||
|
||||
class TrackParserTest < ActiveSupport::TestCase
|
||||
def parse(name) = TrackParser.new(file_fixture_path.join("tracks", name).read, filename: name).parse
|
||||
def file_fixture_path = Rails.root.join("test/fixtures/files")
|
||||
|
||||
test "GPX: [lon, lat, alt_m] with epoch-second times" do
|
||||
t = parse("flight.gpx")
|
||||
assert_equal "gpx", t.source_format
|
||||
assert_equal [ -71.412028, 41.597139, 5.2 ], t.coordinates.first
|
||||
assert_equal 3, t.points
|
||||
assert_equal Time.utc(2026, 10, 24, 14).to_i, t.times.first
|
||||
assert_equal 2500, t.max_altitude_ft # 762 m
|
||||
json = t.as_air_trail_json
|
||||
assert_equal %i[coordinates sourceFormat sourceName times], json.keys.sort
|
||||
assert_equal "flight.gpx", json[:sourceName]
|
||||
end
|
||||
|
||||
test "KML gx:Track and LineString" do
|
||||
t = parse("flight.kml")
|
||||
assert_equal [ [ -71.412028, 41.597139, 5.2 ], [ -71.5, 41.42, 762.0 ] ], t.coordinates
|
||||
assert_equal 2, t.times.size
|
||||
line = parse("linestring.kml")
|
||||
assert_equal 3, line.points
|
||||
assert_nil line.times
|
||||
end
|
||||
|
||||
test "CSV: altitude in feet, millisecond timestamps" do
|
||||
t = parse("flight.csv")
|
||||
assert_equal "csv", t.source_format
|
||||
assert_equal [ -71.5, 41.42, 762.0 ], t.coordinates[1] # 2500 ft
|
||||
assert_equal 1_793_023_200, t.times.first
|
||||
end
|
||||
|
||||
test "sniffs the format when the extension doesn't say" do
|
||||
gpx = Rails.root.join("test/fixtures/files/tracks/flight.gpx").read
|
||||
assert_equal "gpx", TrackParser.new(gpx, filename: "track.xml").parse.source_format
|
||||
end
|
||||
|
||||
test "downsamples huge tracks to AirTrail's limit, keeping the last point" do
|
||||
rows = (0..100_200).map { |i| "#{41 + i * 1e-6},-71,1000" }
|
||||
t = TrackParser.new("lat,lon,alt\n#{rows.join("\n")}", filename: "big.csv").parse
|
||||
assert_operator t.points, :<=, TrackParser::MAX_POINTS + 1
|
||||
assert_in_delta 41 + 100_200 * 1e-6, t.coordinates.last[1], 1e-6
|
||||
end
|
||||
|
||||
test "rejects unusable tracks" do
|
||||
assert_raises(TrackParser::Error) { TrackParser.new("hello", filename: "x.txt").parse }
|
||||
assert_raises(TrackParser::Error) { TrackParser.new("lat,lon\n41,-71\n", filename: "one.csv").parse }
|
||||
assert_raises(TrackParser::Error) { TrackParser.new("a,b\n1,2\n3,4\n", filename: "x.csv").parse }
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,79 @@
|
||||
# In-memory AirTrail API for tests (WebMock). Mirrors /api/v1 shapes from
|
||||
# AirTrail's openapi.yaml: { data: ... } envelopes, cursor pagination,
|
||||
# Bearer auth and { error: { code, message } } errors.
|
||||
class FakeAirTrail
|
||||
BASE = "https://airtrail.test".freeze
|
||||
AIRPORTS = {
|
||||
"KOQU" => 101, "KBID" => 102, "KPVD" => 103, "KMFD" => 104, "K1B9" => 105, "NH53" => 106
|
||||
}.freeze
|
||||
|
||||
attr_reader :flights, :requests
|
||||
attr_accessor :scopes, :valid_key
|
||||
|
||||
def initialize(test)
|
||||
@test = test
|
||||
@flights = {}
|
||||
@next_id = 1000
|
||||
@requests = []
|
||||
@scopes = AirTrailConnection::REQUIRED_SCOPES.dup
|
||||
@valid_key = "at_secret"
|
||||
stub!
|
||||
end
|
||||
|
||||
def add_existing(date:, from:, to:, reg: "N12345", flight_number: nil, duration: nil)
|
||||
id = (@next_id += 1)
|
||||
@flights[id] = { "id" => id, "date" => date, "from" => airport(from), "to" => airport(to),
|
||||
"flightNumber" => flight_number, "aircraftReg" => reg, "duration" => duration }
|
||||
id
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def airport(code) = { "id" => AIRPORTS.fetch(code), "icao" => code, "iata" => nil, "name" => "#{code} Airport" }
|
||||
|
||||
def stub!
|
||||
@test.stub_request(:any, /airtrail\.test/).to_return do |req|
|
||||
@requests << [ req.method, req.uri.path, req.body.to_s.empty? ? nil : JSON.parse(req.body) ]
|
||||
next json(401, error: { code: "unauthorized", message: "Invalid API key" }) unless req.headers["Authorization"] == "Bearer #{@valid_key}"
|
||||
route(req)
|
||||
end
|
||||
end
|
||||
|
||||
def route(req)
|
||||
path = req.uri.path
|
||||
query = URI.decode_www_form(req.uri.query.to_s).to_h
|
||||
case [ req.method, path ]
|
||||
in [ :get, "/api/v1/me" ]
|
||||
json(200, data: { id: "u-ricky", username: "ricky", displayName: "Ricky", role: nil, isOwner: true,
|
||||
permissions: [], credential: { kind: "apiKey", scopes: @scopes } })
|
||||
in [ :get, "/api/v1/airports" ]
|
||||
code = query["query"].to_s.upcase
|
||||
json(200, data: AIRPORTS.key?(code) ? [ airport(code) ] : [], page: { nextCursor: nil })
|
||||
in [ :get, "/api/v1/aircraft" ]
|
||||
json(200, data: query["query"] == "C150" ? [ { id: 7, icao: "C150", name: "Cessna 150" } ] : [], page: { nextCursor: nil })
|
||||
in [ :get, "/api/v1/flights" ]
|
||||
all = @flights.values.sort_by { -_1["id"] }
|
||||
offset = query["cursor"].to_i
|
||||
page = all[offset, 2] || [] # tiny pages to exercise pagination
|
||||
json(200, data: page, page: { nextCursor: offset + 2 < all.size ? (offset + 2).to_s : nil })
|
||||
in [ :post, "/api/v1/flights" ]
|
||||
body = JSON.parse(req.body)
|
||||
return json(422, error: { code: "validation_failed", message: "Validation failed", details: [ { path: [ "fromId" ], message: "Required" } ] }) unless body["fromId"]
|
||||
id = (@next_id += 1)
|
||||
@flights[id] = body.merge("id" => id)
|
||||
json(201, data: { id: id })
|
||||
in [ :put, %r{\A/api/v1/flights/(\d+)\z} ]
|
||||
id = path[/\d+\z/].to_i
|
||||
return json(404, error: { code: "not_found", message: "Flight not found" }) unless @flights.key?(id)
|
||||
@flights[id] = JSON.parse(req.body).merge("id" => id)
|
||||
json(200, data: @flights[id])
|
||||
in [ :delete, %r{\A/api/v1/flights/(\d+)\z} ]
|
||||
id = path[/\d+\z/].to_i
|
||||
@flights.delete(id) ? { status: 204, body: "" } : json(404, error: { code: "not_found", message: "Flight not found" })
|
||||
else
|
||||
json(404, error: { code: "not_found", message: "No route" })
|
||||
end
|
||||
end
|
||||
|
||||
def json(status, payload) = { status: status, body: JSON.generate(payload), headers: { "Content-Type" => "application/json" } }
|
||||
end
|
||||
@@ -1,6 +1,9 @@
|
||||
ENV["RAILS_ENV"] ||= "test"
|
||||
require_relative "../config/environment"
|
||||
require "rails/test_help"
|
||||
require "webmock/minitest"
|
||||
WebMock.disable_net_connect!(allow_localhost: true)
|
||||
Dir[File.expand_path("support/**/*.rb", __dir__)].each { require _1 }
|
||||
|
||||
module ActiveSupport
|
||||
class TestCase
|
||||
|
||||
Reference in new issue
Block a user