mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 15: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
+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