diff --git a/app/controllers/aircraft_controller.rb b/app/controllers/aircraft_controller.rb index 05f09ec..a1dd8fb 100644 --- a/app/controllers/aircraft_controller.rb +++ b/app/controllers/aircraft_controller.rb @@ -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, :drs_search_url + :airworthiness_enforcement, :picture ) end end diff --git a/app/controllers/flight_logs_controller.rb b/app/controllers/flight_logs_controller.rb index efdab3e..dfd4a3f 100644 --- a/app/controllers/flight_logs_controller.rb +++ b/app/controllers/flight_logs_controller.rb @@ -4,6 +4,7 @@ class FlightLogsController < ApplicationController def index @flight_logs = @aircraft.flight_logs.recent_first.includes(:user) + @stats = FlightStats.new(@aircraft) end def show diff --git a/app/models/aircraft.rb b/app/models/aircraft.rb index 5c4c3d3..f973053 100644 --- a/app/models/aircraft.rb +++ b/app/models/aircraft.rb @@ -28,8 +28,6 @@ class Aircraft < ApplicationRecord validates :tail_number, presence: true validates :status, inclusion: { in: STATUSES.keys } - validates :drs_search_url, format: { with: %r{\Ahttps://drs\.faa\.gov/\S*\z}, message: "must be a https://drs.faa.gov/ link" }, allow_blank: true - normalizes :drs_search_url, with: ->(url) { url.strip.sub(/#.*\z/, "").presence } validate :picture_is_image scope :ordered, -> { order(:tail_number) } diff --git a/app/services/flight_stats.rb b/app/services/flight_stats.rb new file mode 100644 index 0000000..e06062c --- /dev/null +++ b/app/services/flight_stats.rb @@ -0,0 +1,85 @@ +# Flying metrics for the Flights tab: totals, recent periods, fuel, airports +# and a monthly/yearly breakdown. +# +# "Flight time" is Hobbs time where the flight has it, otherwise tach time +# (e.g. flights logged before a Hobbs was installed). +class FlightStats + Period = Struct.new(:label, :flights, :tach, :flight, :fuel, keyword_init: true) + + attr_reader :today + + def initialize(aircraft, today: Date.current) + @aircraft = aircraft + @today = today + @flights = aircraft.flight_logs.order(:date, :created_at).to_a + @fuel = aircraft.consumable_records.where(record_type: "fuel").pluck(:date, :quantity_added) + end + + def any? = @flights.any? + def count = @flights.size + def first_date = @flights.first&.date + + def total_tach = sum(@flights) { _1.tach_time } + def total_flight = sum(@flights) { flight_hours(_1) } + def total_fuel = @fuel.sum { _2.to_f }.round(1) + + def average_flight = count.zero? ? nil : (total_flight / count).round(1) + def shortest_flight = @flights.map { flight_hours(_1) }.min&.round(1) + def longest_flight = @flights.map { flight_hours(_1) }.max&.round(1) + + # Gallons per tach hour over all fuel records. + def gph = ConsumptionStats.new(@aircraft, "fuel").lifetime + + def airports + @airports ||= @flights.flat_map { [ _1.departure_location, _1.destination_location ] } + .filter_map { _1.to_s.strip.upcase.presence } + end + + def airports_visited = airports.uniq.size + + # Most-used airports (departures + arrivals), e.g. [["KOQU", 412], ...] + def top_airports(limit = 5) = airports.tally.sort_by { [ -_2, _1 ] }.first(limit) + + def periods + [ + period("Past 30 days", today - 29..today), + period("Past 12 months", (today << 12) + 1..today), + period("This year (#{today.year})", Date.new(today.year)..today), + period("Last year (#{today.year - 1})", Date.new(today.year - 1)..Date.new(today.year - 1, 12, 31)), + period("Since purchase", (first_date || today)..today) + ] + end + + def monthly_average_past_year + (period("", (today << 12) + 1..today).flight / 12.0).round(1) + end + + # { "Nov 2024" => 12.3, ... } for the last `months` months, including empty ones. + def flight_hours_by_month(months = 24) + start = (today << (months - 1)).beginning_of_month + totals = @flights.select { _1.date >= start }.group_by { _1.date.beginning_of_month } + .transform_values { |fs| sum(fs) { flight_hours(_1) } } + (0...months).to_h do |i| + month = start >> i + [ month.strftime("%b %Y"), totals.fetch(month, 0.0) ] + end + end + + def by_year + years = (@flights.map { _1.date.year } + @fuel.map { _1[0].year }).uniq.sort.reverse + years.map { |y| period(y.to_s, Date.new(y)..Date.new(y, 12, 31)) } + end + + private + + def flight_hours(f) = (f.hobbs_time || f.tach_time).to_f + + def sum(items, &block) = items.sum { block.(_1).to_f }.round(1) + + def period(label, range) + flights = @flights.select { range.cover?(_1.date) } + Period.new(label: label, flights: flights.size, + tach: sum(flights) { _1.tach_time }, flight: sum(flights) { flight_hours(_1) }, + fuel: @fuel.select { range.cover?(_1[0]) }.sum { _2.to_f }.round(1)) + end +end diff --git a/app/views/ad_imports/new.html.erb b/app/views/ad_imports/new.html.erb index cab9177..b32ba3b 100644 --- a/app/views/ad_imports/new.html.erb +++ b/app/views/ad_imports/new.html.erb @@ -14,11 +14,10 @@

Getting the file

    -
  1. On " class="link" target="_blank" rel="noopener noreferrer"><%= @aircraft.drs_search_url.present? ? "your saved DRS search" : "drs.faa.gov" %>, search Airworthiness Directives for this aircraft's make and model (add the engine and propeller too).
  2. +
  3. On drs.faa.gov, search Airworthiness Directives for this aircraft's make and model (add the engine and propeller too).
  4. Save the results as Excel. The Excel file links each AD number to its DRS page; the CSV doesn't, so a CSV import won't have links.
  5. Upload it here.
- <% unless @aircraft.drs_search_url.present? %>

Tip: save the DRS search link on the aircraft (Edit aircraft) for a one-click “Open in DRS” button.

<% end %>

ADs already tracked are matched by number, so importing the Excel file after a CSV import just adds the links.

diff --git a/app/views/aircraft/_form.html.erb b/app/views/aircraft/_form.html.erb index 34e6392..46f7a27 100644 --- a/app/views/aircraft/_form.html.erb +++ b/app/views/aircraft/_form.html.erb @@ -20,8 +20,6 @@ <% unless aircraft.new_record? %>

To change hours use “Update Hours” on the overview, so component times stay in sync.

<% end %> - <%= f.field :drs_search_url, label: "FAA DRS AD search link", placeholder: "https://drs.faa.gov/browse/ADFRAWD/doctypeDetails?…", - hint: "Run the AD search for this aircraft on drs.faa.gov and paste the page link. The ADs tab then gets a one-click “Open in DRS” button." %> <%= f.field :picture, as: :file, accept: "image/*" %> <%= f.field :airworthiness_enforcement, as: :checkbox, label: "Enforce airworthiness", hint: "Block flight logs and hours updates while the aircraft is red." %> diff --git a/app/views/airworthiness_directives/index.html.erb b/app/views/airworthiness_directives/index.html.erb index daf66d9..6409c4b 100644 --- a/app/views/airworthiness_directives/index.html.erb +++ b/app/views/airworthiness_directives/index.html.erb @@ -11,7 +11,6 @@ <%= f.submit "Link existing", class: "btn-secondary" %> <% end %> <% end %> - <% if @aircraft.drs_search_url.present? %><%= link_to "Open in DRS ↗", @aircraft.drs_search_url, class: "btn-secondary", target: "_blank", rel: "noopener noreferrer" %><% end %> <%= link_to "Import from FAA DRS", new_aircraft_ad_import_path(@aircraft), class: "btn-secondary" %> <%= link_to "+ New AD", new_aircraft_airworthiness_directive_path(@aircraft), class: "btn-primary" %> diff --git a/app/views/flight_logs/_stats.html.erb b/app/views/flight_logs/_stats.html.erb new file mode 100644 index 0000000..932391b --- /dev/null +++ b/app/views/flight_logs/_stats.html.erb @@ -0,0 +1,61 @@ +<%# Flying metrics. "Flight time" = Hobbs where recorded, else tach. %> +<% periods = stats.periods %> +
+ <% [ [ "Past 30 days", periods[0] ], [ "This year", periods[2] ], [ "Past 12 months", periods[1] ], [ "Since #{fmt_date(stats.first_date)}", periods[4] ] ].each do |title, p| %> +
+
<%= title %>
+
<%= hours(p.flight) %> hrs
+
<%= pluralize(p.flights, "flight") %> · <%= hours(p.tach) %> tach · <%= number_with_delimiter(p.fuel) %> gal
+
+ <% end %> +
+ +
+
+

Flight hours by month

+ Avg <%= hours(stats.monthly_average_past_year) %> hrs/month over the past year
+
+ <%= column_chart stats.flight_hours_by_month, height: "220px", colors: [ "#0369a1" ], ytitle: "hrs", library: { plugins: { legend: { display: false } } } %> +
+
+ +
+

Totals

+
+
Flights logged
<%= number_with_delimiter(stats.count) %>
+
Flight time
<%= hours(stats.total_flight) %> hrs
+
Tach time
<%= hours(stats.total_tach) %> hrs
+
Average flight
<%= hours(stats.average_flight) %> hrs
+
Longest flight
<%= hours(stats.longest_flight) %> hrs
+
Fuel
<%= number_with_delimiter(stats.total_fuel) %> gal
+
Fuel burn
<%= stats.gph || "—" %> gal/hr
+
Airports visited
<%= stats.airports_visited %>
+
+ <% if stats.top_airports.any? %> +
+ Most visited: + <%= stats.top_airports.map { |code, n| "#{code} (#{n})" }.join(" · ") %> +
+ <% end %> +
+
+ +
+ By year + + + + <% stats.by_year.each do |y| %> + + + + + + + + + <% end %> + +
YearFlightsFlight hrsTach hrsFuel (gal)Avg flight
<%= y.label %><%= y.flights %><%= hours(y.flight) %><%= hours(y.tach) %><%= number_with_delimiter(y.fuel) %><%= y.flights.positive? ? hours(y.flight / y.flights) : "—" %>
+

Flight time is Hobbs time where recorded, otherwise tach time.

+
diff --git a/app/views/flight_logs/index.html.erb b/app/views/flight_logs/index.html.erb index 5fa7f86..a450268 100644 --- a/app/views/flight_logs/index.html.erb +++ b/app/views/flight_logs/index.html.erb @@ -1,5 +1,6 @@ <% content_for :title, "#{@aircraft.tail_number} Flights" %> <%= render "shared/aircraft_header", aircraft: @aircraft %> +<% if @stats.any? %><%= render "flight_logs/stats", stats: @stats %><% end %>

Flight Log

<% 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" %>
<% if @flight_logs.any? %> diff --git a/db/migrate/20261106120000_remove_drs_search_url_from_aircraft.rb b/db/migrate/20261106120000_remove_drs_search_url_from_aircraft.rb new file mode 100644 index 0000000..d2042bb --- /dev/null +++ b/db/migrate/20261106120000_remove_drs_search_url_from_aircraft.rb @@ -0,0 +1,7 @@ +# The per-aircraft DRS search link turned out to be unnecessary: each AD's +# DRS link comes from the Excel import. +class RemoveDrsSearchUrlFromAircraft < ActiveRecord::Migration[8.1] + def change + remove_column :aircraft, :drs_search_url, :string if column_exists?(:aircraft, :drs_search_url) + end +end diff --git a/db/schema.rb b/db/schema.rb index 6e057ab..67f95d2 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -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_05_200000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_06_120000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -75,7 +75,6 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_05_200000) do t.boolean "airworthiness_enforcement", default: false, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false - t.string "drs_search_url" end create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t| diff --git a/test/integration/ad_import_flow_test.rb b/test/integration/ad_import_flow_test.rb index 4244a74..65fca4f 100644 --- a/test/integration/ad_import_flow_test.rb +++ b/test/integration/ad_import_flow_test.rb @@ -45,18 +45,6 @@ class AdImportFlowTest < ActionDispatch::IntegrationTest assert_equal "GREEN", @aircraft.reload.airworthiness.status end - test "saved DRS search link shows an Open in DRS button; only drs.faa.gov links allowed" do - sign_in @owner - url = "https://drs.faa.gov/browse/ADFRAWD/doctypeDetails?Status=Current&Make=Cessna%20Aircraft%20Company&Model=150L#:~:text=Save-,Results" - patch aircraft_path(@aircraft), params: { aircraft: { drs_search_url: url } } - assert_equal url.sub(/#.*/, ""), @aircraft.reload.drs_search_url - get aircraft_airworthiness_directives_path(@aircraft) - assert_select "a[href='#{@aircraft.drs_search_url}']", text: "Open in DRS ↗" - - patch aircraft_path(@aircraft), params: { aircraft: { drs_search_url: "https://evil.example/drs.faa.gov" } } - assert_response :unprocessable_entity - end - test "pilots cannot import ADs" do sign_in @pilot post aircraft_ad_import_path(@aircraft), params: { file: fixture_file_upload("drs_ads.csv", "text/csv") } diff --git a/test/integration/pages_test.rb b/test/integration/pages_test.rb index 28790c6..f33e58b 100644 --- a/test/integration/pages_test.rb +++ b/test/integration/pages_test.rb @@ -82,6 +82,12 @@ class PagesTest < ActionDispatch::IntegrationTest assert_select "a[href='https://drs.faa.gov/browse/excelExternalWindow/ABC.0001']", minimum: 2 # status + history end + test "flights tab shows flying stats" do + get aircraft_flight_logs_path(@a) + assert_select "h2", text: "Flight hours by month" + assert_select "dt", text: "Airports visited" + end + test "maintenance share link renders without login and shows history" do delete session_path get shared_path(@token.token) diff --git a/test/services/ad_import_test.rb b/test/services/ad_import_test.rb index 04aa92a..0b03aa1 100644 --- a/test/services/ad_import_test.rb +++ b/test/services/ad_import_test.rb @@ -180,7 +180,6 @@ class AdImportTest < ActiveSupport::TestCase AdImport::FAA_FIELDS.each_key do |attr| assert_includes AirworthinessDirective.column_names, attr.to_s end - assert_includes Aircraft.column_names, "drs_search_url" end test "rejects files that aren't DRS exports" do diff --git a/test/services/flight_stats_test.rb b/test/services/flight_stats_test.rb new file mode 100644 index 0000000..6650252 --- /dev/null +++ b/test/services/flight_stats_test.rb @@ -0,0 +1,57 @@ +require "test_helper" + +class FlightStatsTest < ActiveSupport::TestCase + setup do + @a = create_aircraft(tach_time: 1000) + @today = Date.new(2026, 11, 5) + end + + def fly(date, tach, hobbs: nil, from: "KAAA", to: "KBBB", fuel: nil) + f = @a.flight_logs.create!(date: date, tach_time: tach, hobbs_time: hobbs, + departure_location: from, destination_location: to, fuel_added: fuel) + @a.consumable_records.create!(record_type: "fuel", date: date, quantity_added: fuel, flight_hours: 1000, flight_log: f) if fuel + f + end + + def stats = FlightStats.new(@a, today: @today) + + test "periods use Hobbs time, falling back to tach" do + fly Date.new(2024, 6, 1), 2.0, hobbs: 2.4, fuel: 10 + fly Date.new(2025, 12, 20), 1.0, hobbs: 1.2 # last year, and within past 12 months + fly Date.new(2026, 3, 1), 1.5 # no Hobbs: counts 1.5 + fly Date.new(2026, 10, 20), 0.8, hobbs: 1.0, from: "kccc ", to: "KAAA", fuel: 12.5 + + p30, p12, this_year, last_year, all = stats.periods + assert_equal [ 1, 1.0, 12.5 ], [ p30.flights, p30.flight, p30.fuel ] + assert_equal [ 3, 3.7 ], [ p12.flights, p12.flight ] + assert_equal [ 2, 2.5, 2.3 ], [ this_year.flights, this_year.flight, this_year.tach ] + assert_equal [ 1, 1.2 ], [ last_year.flights, last_year.flight ] + assert_equal [ 4, 6.1, 22.5 ], [ all.flights, all.flight, all.fuel ] + assert_equal Date.new(2024, 6, 1), stats.first_date + end + + test "totals, airports, monthly series and years" do + fly Date.new(2026, 9, 1), 1.0, hobbs: 1.2, from: "KOQU", to: "KBID" + fly Date.new(2026, 9, 1), 0.5, hobbs: 0.6, from: "KBID", to: "koqu" + fly Date.new(2025, 9, 1), 3.0, hobbs: 3.5, from: "KOQU", to: "KMFD" + s = stats + assert_equal 3, s.count + assert_equal 1.8, s.average_flight + assert_equal [ 0.6, 3.5 ], [ s.shortest_flight, s.longest_flight ] + assert_equal 3, s.airports_visited + assert_equal [ "KOQU", 3 ], s.top_airports.first + + months = s.flight_hours_by_month(24) + assert_equal 24, months.size + assert_equal 1.8, months["Sep 2026"] + assert_equal 0.0, months["Oct 2026"] + assert_equal "Nov 2026", months.keys.last + assert_equal %w[2026 2025], s.by_year.map(&:label) + assert_equal 0.2, s.monthly_average_past_year # 1.8 / 12, rounded + end + + test "no flights" do + assert_not stats.any? + assert_nil stats.average_flight + end +end