From 31ac991babadb137a3e89de9ada0f1d2510d3d2c Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Wed, 11 Nov 2026 21:30:34 -0500 Subject: [PATCH] Overview shows coming due and the last flight; intervals in days, months or years - Overview: "Coming due" (next 30 days or 10 hours) and "Last flight" (the most recent day's legs, meters at the end, fuel and oil left). - Component replace / TBO / inspect intervals, inspection types and ADs take a number and a days / months / years choice (CalendarInterval). Components gain month columns (years stored as 12 months; months land on the same date); inspection types and ADs keep end-of-month. ADs now honour days. - Due list: hours already run out count as overdue; a component covered by an inspection type no longer gets its own "Inspect every" item. - Loading calculator moved to a partial; no limit warnings until a load is entered. Header buttons don't wrap on phones. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + app/controllers/aircraft_controller.rb | 3 + .../airworthiness_directives_controller.rb | 2 +- app/controllers/components_controller.rb | 3 +- .../inspection_types_controller.rb | 2 +- app/form_builders/app_form_builder.rb | 17 +++ .../controllers/wb_calculator_controller.js | 7 ++ app/models/airworthiness_directive.rb | 7 +- app/models/component.rb | 7 +- app/models/concerns/calendar_interval.rb | 77 +++++++++++++ app/models/inspection_type.rb | 5 +- app/services/aircraft_archive/exporter.rb | 3 +- app/services/aircraft_archive/importer.rb | 3 +- app/services/airworthiness.rb | 2 +- app/services/compliance.rb | 4 +- app/services/due_list.rb | 34 ++++-- app/services/maintenance_report.rb | 4 +- app/views/aircraft/_coming_due.html.erb | 22 ++++ app/views/aircraft/_last_flight.html.erb | 27 +++++ app/views/aircraft/show.html.erb | 4 + .../airworthiness_directives/_form.html.erb | 2 +- .../airworthiness_directives/index.html.erb | 2 +- app/views/components/_form.html.erb | 7 +- app/views/components/index.html.erb | 4 +- app/views/components/show.html.erb | 2 +- app/views/inspection_types/_form.html.erb | 4 +- app/views/maintenance_reports/show.html.erb | 4 +- app/views/shared/_aircraft_header.html.erb | 2 +- .../_calculator.html.erb | 34 ++++++ .../weight_balance_records/index.html.erb | 34 +----- ...10000_add_month_intervals_to_components.rb | 9 ++ db/schema.rb | 5 +- docs/guide/ads.md | 2 +- docs/guide/aircraft.md | 2 + docs/guide/components.md | 6 +- docs/guide/inspections.md | 2 +- .../overview_due_and_intervals_test.rb | 104 ++++++++++++++++++ 37 files changed, 385 insertions(+), 75 deletions(-) create mode 100644 app/models/concerns/calendar_interval.rb create mode 100644 app/views/aircraft/_coming_due.html.erb create mode 100644 app/views/aircraft/_last_flight.html.erb create mode 100644 app/views/weight_balance_records/_calculator.html.erb create mode 100644 db/migrate/20261112010000_add_month_intervals_to_components.rb create mode 100644 test/integration/overview_due_and_intervals_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 08c0ce7..cd97e07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,8 @@ The first numbered release. Highlights of what Simple Aircraft Manager does as o - Airworthiness status from ADs, inspections, squawks, components and documents, with Part 91 rules (annual as 100-hour, overruns, IFR and transponder limits). - ADs: FAA DRS import with an AD baseline per model, and a weekly search for newly published ADs covering the aircraft, engine, propeller and every installed component. - Logbook: templates, engine and propeller times, sub-components (a new entry can also record them serviced or replaced), printable entries for the paper logbook, and AI transcription of scanned pages. +- The Overview shows what's coming due in the next 30 days or 10 hours, and the last day's flying. +- Intervals are entered as a number of days, months or years: no converting months to days. - Calendar feed of everything coming due, with dates projected from recent flying for hour-based items. - Weight and balance with a loading calculator (CG envelope in inches or lb-in/1000). diff --git a/app/controllers/aircraft_controller.rb b/app/controllers/aircraft_controller.rb index 37eb664..d79be44 100644 --- a/app/controllers/aircraft_controller.rb +++ b/app/controllers/aircraft_controller.rb @@ -14,6 +14,9 @@ class AircraftController < ApplicationController @notes = @aircraft.notes.recent_first.includes(:user).limit(5) @oil = ConsumptionStats.new(@aircraft, "oil") @fuel = ConsumptionStats.new(@aircraft, "fuel") + @coming_due = DueList.new(@aircraft).soon + last = @aircraft.flight_logs.recent_first.first + @last_day = last && @aircraft.flight_logs.where(date: last.date).order(:created_at).to_a end def new diff --git a/app/controllers/airworthiness_directives_controller.rb b/app/controllers/airworthiness_directives_controller.rb index 3d6b418..beab9f2 100644 --- a/app/controllers/airworthiness_directives_controller.rb +++ b/app/controllers/airworthiness_directives_controller.rb @@ -68,7 +68,7 @@ class AirworthinessDirectivesController < ApplicationController def ad_params p = params.require(:airworthiness_directive).permit( :name, :short_description, :required_action, :compliance_type, :trigger_condition, :recurring, - :recurring_hours, :recurring_months, :recurring_days, :bulletin_type, :mandatory, :document_id, :document_url + :recurring_hours, :recurring_months, :recurring_days, :recurring_every, :recurring_unit, :bulletin_type, :mandatory, :document_id, :document_url ) p[:document_id] = scoped_id(@aircraft.documents, p[:document_id]) p diff --git a/app/controllers/components_controller.rb b/app/controllers/components_controller.rb index f41d121..4e0df80 100644 --- a/app/controllers/components_controller.rb +++ b/app/controllers/components_controller.rb @@ -77,7 +77,8 @@ class ComponentsController < ApplicationController :component_type_id, :parent_component_id, :manufacturer, :model, :serial_number, :install_location, :notes, :status, :date_in_service, :hours_in_service, :hours_since_overhaul, :overhaul_date, :overhaul_kind, :tbo_hours, :tbo_days, :inspection_hours, - :inspection_days, :replacement_hours, :replacement_days, :tbo_critical, :on_condition, + :inspection_days, :replacement_hours, :replacement_days, :replacement_every, :replacement_unit, :tbo_every, :tbo_unit, + :inspection_every, :inspection_unit, :tbo_critical, :on_condition, :inspection_critical, :replacement_critical, :expires_on ).tap do |p| # Owners can create a component type inline instead of asking an admin. diff --git a/app/controllers/inspection_types_controller.rb b/app/controllers/inspection_types_controller.rb index 47ff4f4..52cb1dc 100644 --- a/app/controllers/inspection_types_controller.rb +++ b/app/controllers/inspection_types_controller.rb @@ -68,7 +68,7 @@ class InspectionTypesController < ApplicationController def type_params p = params.require(:inspection_type).permit(:name, :recurring, :effect, :hours_tolerance, :satisfies_id, - :recurring_hours, :recurring_days, :recurring_months) + :recurring_hours, :recurring_days, :recurring_months, :recurring_every, :recurring_unit) p[:satisfies_id] = scoped_id(@aircraft.applicable_inspection_types, p[:satisfies_id]) if p.key?(:satisfies_id) p end diff --git a/app/form_builders/app_form_builder.rb b/app/form_builders/app_form_builder.rb index 1a01bef..f0ec20b 100644 --- a/app/form_builders/app_form_builder.rb +++ b/app/form_builders/app_form_builder.rb @@ -39,6 +39,23 @@ class AppFormBuilder < ActionView::Helpers::FormBuilder end end + # A calendar interval: a number and a days / months / years choice + # (see CalendarInterval). + # <%= f.interval :replacement, label: "Replace every" %> + def interval(name, label:, hint: nil, wrapper: {}) + every = :"#{name}_every" + errors = object.errors[every] + @template.content_tag(:div, class: wrapper[:class]) do + label(every, label, class: "label") + + @template.content_tag(:div, class: "flex gap-2") do + number_field(every, class: "input min-w-0 flex-1", min: 1, step: 1, inputmode: "numeric") + + select(:"#{name}_unit", CalendarInterval::UNITS.invert, {}, class: "input w-auto", "aria-label": "#{label} unit") + end + + (hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) + + errors.map { |e| @template.content_tag(:p, "#{label} #{e}", class: "field-error") }.join.html_safe + end + end + def errors_summary return "".html_safe unless object&.errors&.any? @template.content_tag(:div, class: "rounded-md bg-red-50 p-3 text-sm text-red-700 ring-1 ring-red-200") do diff --git a/app/javascript/controllers/wb_calculator_controller.js b/app/javascript/controllers/wb_calculator_controller.js index eb5caa2..d05e710 100644 --- a/app/javascript/controllers/wb_calculator_controller.js +++ b/app/javascript/controllers/wb_calculator_controller.js @@ -15,8 +15,10 @@ export default class extends Controller { let moment = this.emptyMomentValue let fuelArmMoment = 0 let fuelGallons = 0 + let loaded = false this.stationTargets.forEach((input) => { const qty = parseFloat(input.value) || 0 + if (qty > 0) loaded = true const arm = parseFloat(input.dataset.arm) const fuel = input.dataset.fuel === "true" const max = parseFloat(input.dataset.max) || 0 @@ -39,6 +41,11 @@ export default class extends Controller { this.show("takeoff", takeoff) this.show("landing", landing) + if (!loaded) { + this.messagesTarget.replaceChildren(Object.assign(document.createElement("li"), { className: "text-slate-500", textContent: "Enter the loading to check weight and CG." })) + this.draw(takeoff, landing) + return + } if (this.maxGrossValue && takeoff.weight > this.maxGrossValue) { messages.push([ "bad", `Takeoff weight is ${(takeoff.weight - this.maxGrossValue).toFixed(1)} lb over the maximum of ${this.maxGrossValue} lb.` ]) } diff --git a/app/models/airworthiness_directive.rb b/app/models/airworthiness_directive.rb index 205883b..be8444e 100644 --- a/app/models/airworthiness_directive.rb +++ b/app/models/airworthiness_directive.rb @@ -6,6 +6,9 @@ class AirworthinessDirective < ApplicationRecord }.freeze BULLETIN_LABELS = { "ad" => "AD", "saib" => "SAIB", "sb" => "SB", "alert" => "Alert", "other" => "Bulletin" }.freeze + include CalendarInterval + calendar_interval :recurring, days: :recurring_days, months: :recurring_months, blank: 0 + belongs_to :document, optional: true include SharedRecordHistory # has_and_belongs_to_many :aircraft and :components, with history has_many :ad_compliances, dependent: :destroy @@ -45,9 +48,9 @@ class AirworthinessDirective < ApplicationRecord def conditional? = compliance_type == "conditional" def bulletin_label = BULLETIN_LABELS[bulletin_type] - # Recurrence rule for next-due math (AD status uses hours and months). + # Recurrence rule for next-due math. def due_rule - { hours: recurring_hours.to_f, months: recurring_months, days: 0 } if recurring? + { hours: recurring_hours.to_f, months: recurring_months, days: recurring_days } if recurring? end def latest_compliance_for(aircraft) diff --git a/app/models/component.rb b/app/models/component.rb index e6c2c3b..60be0e8 100644 --- a/app/models/component.rb +++ b/app/models/component.rb @@ -1,10 +1,15 @@ class Component < ApplicationRecord include Versioned + include CalendarInterval STATUSES = { "SPARE" => "Spare Part", "IN-USE" => "In Service", "DISPOSED" => "Disposed" }.freeze # What "since overhaul" counts from, and how logbooks abbreviate it. OVERHAUL_KINDS = { "major" => "Major overhaul", "factory_overhaul" => "Factory overhaul", "factory_new" => "Factory new or rebuilt (zero time)" }.freeze OVERHAUL_ABBREVIATIONS = { "major" => "SMOH", "factory_overhaul" => "SFOH", "factory_new" => "SNEW" }.freeze + calendar_interval :replacement, days: :replacement_days, months: :replacement_months + calendar_interval :tbo, days: :tbo_days, months: :tbo_months + calendar_interval :inspection, days: :inspection_days, months: :inspection_months + belongs_to :aircraft, optional: true belongs_to :parent_component, class_name: "Component", optional: true belongs_to :component_type @@ -66,7 +71,7 @@ class Component < ApplicationRecord def expired?(today = Date.current) = expires_on.present? && today > expires_on def next_replacement_date - overhaul_date + replacement_days.days if replacement_days && overhaul_date + replacement_after(overhaul_date) end # :overdue / :due_soon / :ok / nil (not tracked) for display on the components tab. diff --git a/app/models/concerns/calendar_interval.rb b/app/models/concerns/calendar_interval.rb new file mode 100644 index 0000000..d541bcc --- /dev/null +++ b/app/models/concerns/calendar_interval.rb @@ -0,0 +1,77 @@ +# A calendar interval entered as a number and a unit (days, months or years) +# and stored in a days column and a months column (years as 12 months); one +# of the two is used. +# +# calendar_interval :replacement, days: :replacement_days, months: :replacement_months +# +# gives replacement_every / replacement_unit (for the form), and +# replacement_interval_label ("1 year", "6 months", "90 days"). +module CalendarInterval + extend ActiveSupport::Concern + + UNITS = { "days" => "days", "months" => "months", "years" => "years" }.freeze + + # [count, unit] for display, from the stored columns. + def self.split(days, months) + months = months.to_i + days = days.to_i + if months.positive? then months % 12 == 0 ? [ months / 12, "years" ] : [ months, "months" ] + elsif days.positive? then [ days, "days" ] + end + end + + def self.label(days, months) + count, unit = split(days, months) + count && "#{count} #{count == 1 ? unit.singularize : unit}" + end + + class_methods do + # blank: what an empty interval is stored as (nil, or 0 for NOT NULL columns). + def calendar_interval(name, days:, months:, blank: nil) + every_ivar = :"@#{name}_every" + unit_ivar = :"@#{name}_unit" + + define_method(:"#{name}_every") do + instance_variable_defined?(every_ivar) ? instance_variable_get(every_ivar) : CalendarInterval.split(self[days], self[months])&.first + end + define_method(:"#{name}_unit") do + (instance_variable_get(unit_ivar) if instance_variable_defined?(unit_ivar)) || + CalendarInterval.split(self[days], self[months])&.last || "months" + end + define_method(:"#{name}_every=") { |v| instance_variable_set(every_ivar, v) } + define_method(:"#{name}_unit=") { |v| instance_variable_set(unit_ivar, v) } + define_method(:"#{name}_interval_label") { CalendarInterval.label(self[days], self[months]) } + define_method(:"#{name}_calendar?") { self[months].to_i.positive? || self[days].to_i.positive? } + # The date one interval after `date`: months to the same day (or the + # month's last day), days added. + define_method(:"#{name}_after") do |date| + if date.nil? then nil + elsif self[months].to_i.positive? then date >> self[months].to_i + elsif self[days].to_i.positive? then date + self[days].to_i + end + end + + # Store the entered interval; a bad number leaves the columns alone and + # is reported by the validation below. + before_validation do + next unless instance_variable_defined?(every_ivar) + raw = instance_variable_get(every_ivar).to_s.strip + count = Integer(raw, 10, exception: false) + unit = public_send(:"#{name}_unit") + if raw.empty? + self[days] = blank + self[months] = blank + elsif count&.positive? && UNITS.key?(unit) + self[days] = unit == "days" ? count : blank + self[months] = { "months" => count, "years" => count * 12 }.fetch(unit, blank) + end + end + validate do + next unless instance_variable_defined?(every_ivar) + raw = instance_variable_get(every_ivar).to_s.strip + next if raw.empty? || Integer(raw, 10, exception: false)&.positive? + errors.add(:"#{name}_every", "must be a whole number more than 0") + end + end + end +end diff --git a/app/models/inspection_type.rb b/app/models/inspection_type.rb index 99c6df2..da16dee 100644 --- a/app/models/inspection_type.rb +++ b/app/models/inspection_type.rb @@ -12,6 +12,8 @@ class InspectionType < ApplicationRecord # Short form for the airworthiness status ("VFR only"). LIMITATIONS = { "no_ifr" => "VFR only", "no_transponder" => "No transponder" }.freeze + include CalendarInterval + calendar_interval :recurring, days: :recurring_days, months: :recurring_months, blank: 0 include SharedRecordHistory # has_and_belongs_to_many :aircraft and :components, with history has_many :inspection_records, dependent: :destroy belongs_to :satisfies, class_name: "InspectionType", optional: true @@ -54,7 +56,8 @@ class InspectionType < ApplicationRecord return "One-time" unless recurring? parts = [] parts << "#{recurring_hours.to_s.sub(/\.0\z/, '')} hrs" if recurring_hours.to_f > 0 - parts << "#{recurring_months} months" if recurring_months > 0 + parts << recurring_interval_label if recurring_months > 0 && recurring_days.zero? + parts << "#{recurring_months} months" if recurring_months > 0 && recurring_days > 0 parts << "#{recurring_days} days" if recurring_days > 0 parts.any? ? "Every #{parts.join(' / ')}" : "Recurring" end diff --git a/app/services/aircraft_archive/exporter.rb b/app/services/aircraft_archive/exporter.rb index 38e1a5a..aab5b60 100644 --- a/app/services/aircraft_archive/exporter.rb +++ b/app/services/aircraft_archive/exporter.rb @@ -146,7 +146,8 @@ module AircraftArchive expires_on: c.expires_on&.iso8601, notes: c.notes, status: c.status, date_in_service: c.date_in_service&.iso8601, hours_in_service: dec(c.hours_in_service), hours_since_overhaul: dec(c.hours_since_overhaul), overhaul_date: c.overhaul_date&.iso8601, tbo_hours: c.tbo_hours, tbo_days: c.tbo_days, inspection_hours: c.inspection_hours, inspection_days: c.inspection_days, - replacement_hours: c.replacement_hours, replacement_days: c.replacement_days, tbo_critical: c.tbo_critical, + replacement_hours: c.replacement_hours, replacement_days: c.replacement_days, + replacement_months: c.replacement_months, tbo_months: c.tbo_months, inspection_months: c.inspection_months, tbo_critical: c.tbo_critical, on_condition: c.on_condition, inspection_critical: c.inspection_critical, replacement_critical: c.replacement_critical } end diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index 7ca6a9c..3649cff 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -215,7 +215,8 @@ module AircraftArchive status: Component::STATUSES.key?(data["status"]) ? data["status"] : "SPARE", date_in_service: date(data["date_in_service"]) || Date.new(1900, 1, 1), hours_in_service: num(data["hours_in_service"]) || 0, hours_since_overhaul: num(data["hours_since_overhaul"]) || 0, overhaul_date: date(data["overhaul_date"]), - **data.slice(*%w[tbo_hours tbo_days inspection_hours inspection_days replacement_hours replacement_days]).symbolize_keys, + **data.slice(*%w[tbo_hours tbo_days inspection_hours inspection_days replacement_hours replacement_days + tbo_months inspection_months replacement_months]).symbolize_keys, **data.slice(*%w[tbo_critical on_condition inspection_critical replacement_critical]).transform_values { _1 == true }.symbolize_keys ) c.save!(validate: false) diff --git a/app/services/airworthiness.rb b/app/services/airworthiness.rb index 46d8f1b..5e96903 100644 --- a/app/services/airworthiness.rb +++ b/app/services/airworthiness.rb @@ -158,7 +158,7 @@ class Airworthiness if c.replacement_critical? && (due = c.next_replacement_date) if @today >= due overdue = true - desc = "Replace every #{c.replacement_days} days. Last serviced #{c.overhaul_date}." + desc = "Replace every #{c.replacement_interval_label}. Last serviced #{c.overhaul_date}." elsif @today + DAYS_WARNING >= due approaching = true desc = "Replace in #{(due - @today).to_i} days." diff --git a/app/services/compliance.rb b/app/services/compliance.rb index 70928c4..c49f193 100644 --- a/app/services/compliance.rb +++ b/app/services/compliance.rb @@ -51,8 +51,8 @@ module Compliance end end - if ad.recurring? && ad.recurring_months.positive? - due = end_of_month_after(compliance.date_complied, ad.recurring_months) + if ad.recurring? && ad.recurring_calendar? + due = next_due(ad.due_rule, date: compliance.date_complied, hours: nil)[:date] result.next_due_date = due if today > due rank = OVERDUE diff --git a/app/services/due_list.rb b/app/services/due_list.rb index a45eade..2a5cec4 100644 --- a/app/services/due_list.rb +++ b/app/services/due_list.rb @@ -3,11 +3,16 @@ # Items due by hours get a projected date from the aircraft's flying over # the past year. Used by the calendar feed. class DueList - Item = Data.define(:key, :title, :date, :projected, :due_hours, :kind, :path) do - def overdue?(today = Date.current) = date < today + # past_hours: the hours have already run out (the date is then today). + Item = Data.define(:key, :title, :date, :projected, :due_hours, :kind, :path, :past_hours) do + def overdue?(today = Date.current) = past_hours || date < today end # Hours flown per day over the past year (nil when it hasn't flown). + # What counts as coming up soon (Overview). + SOON_DAYS = 30 + SOON_HOURS = 10 + def self.daily_rate(aircraft, today: Date.current) hours = aircraft.flight_logs.where(date: (today - 365)..today).sum(:tach_time).to_f hours.positive? ? hours / 365.0 : nil @@ -25,6 +30,13 @@ class DueList (inspections + ads + components + documents).compact.sort_by { [ _1.date, _1.title ] } end + # Due in the next SOON_DAYS days or SOON_HOURS hours (or overdue). + def soon + horizon = @today + SOON_DAYS + hours_limit = @now_hours + SOON_HOURS + items.select { |i| i.date <= horizon || (i.due_hours && i.due_hours <= hours_limit) } + end + private # The date it's due: the calendar date, or when the hours run out at the @@ -35,7 +47,8 @@ class DueList use = [ date, projected ].compact.min return unless use Item.new(key: key, title: title, date: use, projected: use == projected && projected != date, kind: kind, path: path, - due_hours: hours_left ? (@now_hours + hours_left.to_d).round(1) : nil) + due_hours: hours_left ? (@now_hours + hours_left.to_d).round(1) : nil, + past_hours: !hours_left.nil? && hours_left.negative? && use == projected) end def hours_left(due_hours) = due_hours ? due_hours.to_d - @now_hours : nil @@ -55,20 +68,23 @@ class DueList end end + # A component's own "Inspect every" counts from its last service; when an + # inspection type covers the component, that inspection (tracked from its + # records, under inspections) governs instead. def components - @aircraft.components.in_use.includes(:component_type).flat_map do |c| + @aircraft.components.in_use.includes(:component_type, :inspection_types).flat_map do |c| label = "#{c} #{c.model}".strip path = @urls.aircraft_component_path(@aircraft, c) since_service = c.hours_since_overhaul.to_d [ (item("replace-#{c.id}", "Replace #{label}", "component", path, date: c.next_replacement_date, - hours_left: c.replacement_hours && c.replacement_hours - since_service) if c.replacement_hours || c.replacement_days), + hours_left: c.replacement_hours && c.replacement_hours - since_service) if c.replacement_hours || c.replacement_calendar?), (item("tbo-#{c.id}", "#{label} reaches TBO", "component", path, - date: c.tbo_days && c.overhaul_date ? c.overhaul_date + c.tbo_days : nil, - hours_left: c.tbo_hours && c.tbo_hours - since_service) if (c.tbo_hours || c.tbo_days) && !c.on_condition?), + date: c.tbo_after(c.overhaul_date), + hours_left: c.tbo_hours && c.tbo_hours - since_service) if (c.tbo_hours || c.tbo_calendar?) && !c.on_condition?), (item("inspect-#{c.id}", "Inspect #{label}", "component", path, - date: c.inspection_days && c.overhaul_date ? c.overhaul_date + c.inspection_days : nil, - hours_left: c.inspection_hours && c.inspection_hours - since_service) if c.inspection_hours || c.inspection_days), + date: c.inspection_after(c.overhaul_date), + hours_left: c.inspection_hours && c.inspection_hours - since_service) if (c.inspection_hours || c.inspection_calendar?) && c.inspection_types.empty?), (item("expires-#{c.id}", "#{label} expires", "component", path, date: c.expires_on) if c.expires_on) ] end diff --git a/app/services/maintenance_report.rb b/app/services/maintenance_report.rb index 8969f55..99be90f 100644 --- a/app/services/maintenance_report.rb +++ b/app/services/maintenance_report.rb @@ -17,12 +17,12 @@ class MaintenanceReport # Parts with a mandatory replacement time (life limits). def life_limited - in_use.select { |c| (c.replacement_critical? && (c.replacement_hours || c.replacement_days)) || c.expires_on } + in_use.select { |c| (c.replacement_critical? && (c.replacement_hours || c.replacement_calendar?)) || c.expires_on } end # Items overhauled on a time basis. def overhaul_items - in_use.select { |c| c.tbo_hours || c.tbo_days } + in_use.select { |c| c.tbo_hours || c.tbo_calendar? } end def inspections = @inspections ||= Compliance.inspection_rows(aircraft) diff --git a/app/views/aircraft/_coming_due.html.erb b/app/views/aircraft/_coming_due.html.erb new file mode 100644 index 0000000..ee34192 --- /dev/null +++ b/app/views/aircraft/_coming_due.html.erb @@ -0,0 +1,22 @@ +<%# What's due in the next few weeks or hours (Overview). %> +
+
+

Coming due

+ next <%= DueList::SOON_DAYS %> days or <%= DueList::SOON_HOURS %> hrs +
+ <% if due.any? %> +
    + <% due.each do |item| %> +
  • + <%= link_to item.title, item.path, class: [ "hover:underline", ("font-medium text-red-700" if item.overdue?) ] %> + + <% if item.overdue? %>overdue<% else %><%= "~" if item.projected %><%= fmt_date(item.date) %><% end %><%= " · at #{hours(item.due_hours)} hrs" if item.due_hours %> + +
  • + <% end %> +
+ <% if due.any?(&:projected) %>

"~" dates are estimated from the last year's flying.

<% end %> + <% else %> + <%= empty_state "Nothing coming due soon." %> + <% end %> +
diff --git a/app/views/aircraft/_last_flight.html.erb b/app/views/aircraft/_last_flight.html.erb new file mode 100644 index 0000000..c54c840 --- /dev/null +++ b/app/views/aircraft/_last_flight.html.erb @@ -0,0 +1,27 @@ +<%# The most recent day's flying (Overview). %> +
+
+

Last flight

+ <%= link_to "Flights →", aircraft_flight_logs_path(aircraft), class: "link text-sm" %> +
+ <% if last_day %> + <% route = last_day.flat_map { [ _1.departure_location, _1.destination_location ] }.compact_blank.chunk_while { _1 == _2 }.map(&:first) %> + <% last_leg = last_day.last %> + <% fuel_after = last_day.reverse.find(&:fuel_level_after)&.fuel_level_after %> + <% oil_after = last_day.reverse.find(&:oil_level_after)&.oil_level_after %> +
+
Date
+
<%= fmt_date(last_leg.date) %><%= " · #{pluralize(last_day.size, 'leg')}" if last_day.size > 1 %>
+ <% if route.any? %>
Route
<%= route.join(" → ") %>
<% end %> +
Flown
<%= hours(last_day.sum { _1.tach_time.to_d }) %> hrs tach
+ <% if last_leg.tach_in %>
Ended at
Tach <%= hours(last_leg.tach_in) %><%= " · Hobbs #{hours(last_leg.hobbs_in)}" if last_leg.hobbs_in %>
<% end %> + <% if fuel_after %>
Fuel after
<%= number_with_precision(fuel_after, precision: 1, strip_insignificant_zeros: true) %> gal
<% end %> + <% if oil_after %>
Oil after
<%= number_with_precision(oil_after, precision: 1, strip_insignificant_zeros: true) %> qt
<% end %> + <% if (notes = last_day.filter_map { _1.notes.presence }).any? %> +
Notes
<%= notes.join("\n") %>
+ <% end %> +
+ <% else %> + <%= empty_state "No flights logged yet." %> + <% end %> +
diff --git a/app/views/aircraft/show.html.erb b/app/views/aircraft/show.html.erb index ad4fcc5..c2a0fde 100644 --- a/app/views/aircraft/show.html.erb +++ b/app/views/aircraft/show.html.erb @@ -46,6 +46,8 @@ <% end %> + <%= render "aircraft/coming_due", aircraft: @aircraft, due: @coming_due %> +

Consumption

<%= link_to "Oil & fuel →", aircraft_consumable_records_path(@aircraft), class: "link text-sm" %>
@@ -71,6 +73,8 @@ <% end %>
+ <%= render "aircraft/last_flight", aircraft: @aircraft, last_day: @last_day %> +

Details

diff --git a/app/views/airworthiness_directives/_form.html.erb b/app/views/airworthiness_directives/_form.html.erb index 1f58742..397aa6d 100644 --- a/app/views/airworthiness_directives/_form.html.erb +++ b/app/views/airworthiness_directives/_form.html.erb @@ -15,7 +15,7 @@
<%= f.field :recurring_hours, as: :number, step: 0.1, label: "Every (hours)" %> - <%= f.field :recurring_months, as: :number, label: "Every (months)" %> + <%= f.interval :recurring, label: "Every", hint: "Months and years are due at the end of the month." %> <%= f.field :document_id, as: :select, label: "Reference document", collection: document_options(aircraft) %>
<%= f.field :document_url, label: "Link to AD document", placeholder: "https://…", diff --git a/app/views/airworthiness_directives/index.html.erb b/app/views/airworthiness_directives/index.html.erb index c25fa7c..97069dc 100644 --- a/app/views/airworthiness_directives/index.html.erb +++ b/app/views/airworthiness_directives/index.html.erb @@ -30,7 +30,7 @@ <% if ad.effective_date || ad.product_type.present? %>
<%= [(ad.effective_date && "Effective #{fmt_date(ad.effective_date)}"), ad.product_type.presence].compact.join(" · ") %>
<% end %> <% if ad.superseded_by.present? %>
Superseded by <%= ad.superseded_by %>
<% end %> <% if ad.conditional? && ad.trigger_condition.present? %>
Trigger: <%= ad.trigger_condition %>
<% end %> - <%= ad.recurring? ? [ad.recurring_hours.to_f > 0 && "#{hours(ad.recurring_hours)} h", ad.recurring_months > 0 && "#{ad.recurring_months} mo"].select(&:itself).join(" / ") : "One-time" %> + <%= ad.recurring? ? [ad.recurring_hours.to_f > 0 && "#{hours(ad.recurring_hours)} h", ad.recurring_interval_label].select(&:itself).join(" / ") : "One-time" %> <%= row.latest ? "#{row.latest.date_complied}#{' (permanent)' if row.latest.permanent?}" : "—" %> <%= [row.next_due_date&.strftime("%b %Y"), row.next_due_hours && "#{hours(row.next_due_hours)} #{@aircraft.time_basis} (#{hours(row.next_due_hours - @aircraft.current_hours)} h left)"].compact.join(" / ").presence || "—" %> <%= compliance_badge(row.status) %> diff --git a/app/views/components/_form.html.erb b/app/views/components/_form.html.erb index d77b29b..a4acb32 100644 --- a/app/views/components/_form.html.erb +++ b/app/views/components/_form.html.erb @@ -28,12 +28,12 @@
Limits <%= f.field :replacement_hours, as: :number, label: "Replace every (hrs)" %> - <%= f.field :replacement_days, as: :number, label: "Replace every (days)" %> + <%= f.interval :replacement, label: "Replace every" %> <%= f.field :replacement_critical, as: :checkbox, label: "Replacement critical", hint: "Overdue replacement or expiry grounds the aircraft (oil, filters, ELT battery…)." %> <%= f.field :expires_on, as: :date, label: "Expires on", hint: "The date marked on the part, e.g. an ELT battery's replacement date (14 CFR 91.207(c): also replace it after 1 hour of cumulative use)." %> <%= f.field :tbo_hours, as: :number, label: "TBO (hrs)" %> - <%= f.field :tbo_days, as: :number, label: "TBO (days)" %> + <%= f.interval :tbo, label: "TBO (calendar)" %>
<%= f.field :tbo_critical, as: :checkbox, label: "Treat TBO as a hard limit", hint: "Under Part 91, TBO is usually the manufacturer's recommendation, unless an AD or the Airworthiness Limitations make it mandatory." %> @@ -41,7 +41,8 @@ hint: "Run past TBO based on condition: TBO is shown for reference, never as a limit (this overrides the hard limit)." %>
<%= f.field :inspection_hours, as: :number, label: "Inspect every (hrs)" %> - <%= f.field :inspection_days, as: :number, label: "Inspect every (days)" %> + <%= f.interval :inspection, label: "Inspect every", + hint: "Counted from the component's last service. If an inspection (Inspections tab) applies to this component, that inspection and its records govern and these are ignored." %> <%= f.field :inspection_critical, as: :checkbox, label: "Inspection critical" %>
diff --git a/app/views/components/index.html.erb b/app/views/components/index.html.erb index 196b0a8..b71f15b 100644 --- a/app/views/components/index.html.erb +++ b/app/views/components/index.html.erb @@ -31,8 +31,8 @@ <%= hours(c.hours_in_service) %> <%= hours(c.hours_since_overhaul) %> - <% if c.replacement_critical? && (c.replacement_hours || c.replacement_days) %> - Replace: <%= [c.replacement_hours && "#{c.replacement_hours} h", c.replacement_days && "#{c.replacement_days} d"].compact.join(" / ") %>
+ <% if c.replacement_critical? && (c.replacement_hours || c.replacement_calendar?) %> + Replace: <%= [c.replacement_hours && "#{c.replacement_hours} h", c.replacement_interval_label].compact.join(" / ") %>
<% end %> <% if c.tbo_critical? && c.tbo_hours %>TBO: <%= c.tbo_hours %> h<%= " (on condition)" if c.on_condition? %>
<% end %> <% if c.expires_on %>Expires: <%= fmt_date(c.expires_on) %><% end %> diff --git a/app/views/components/show.html.erb b/app/views/components/show.html.erb index c169a15..4423e48 100644 --- a/app/views/components/show.html.erb +++ b/app/views/components/show.html.erb @@ -24,7 +24,7 @@
Since OH / service
<%= hours(@component.hours_since_overhaul) %>
TBO
<%= @component.tbo_hours ? "#{@component.tbo_hours} h (#{hours(@component.hours_to_tbo)} remaining)" : "—" %>
Replacement
- <%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_days && "#{@component.replacement_days} d"].compact.join(" / ").presence || "—" %> + <%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_interval_label].compact.join(" / ").presence || "—" %> <% if (d = @component.next_replacement_date) %>
Next by <%= fmt_date(d) %>
<% end %>
Flags
diff --git a/app/views/inspection_types/_form.html.erb b/app/views/inspection_types/_form.html.erb index d4f092a..624df94 100644 --- a/app/views/inspection_types/_form.html.erb +++ b/app/views/inspection_types/_form.html.erb @@ -10,8 +10,8 @@ <%= f.field :recurring, as: :checkbox, label: "Recurring" %>
<%= f.field :recurring_hours, as: :number, step: 0.1, label: "Every (hours)" %> - <%= f.field :recurring_months, as: :number, label: "Every (calendar months)", hint: "Due end of month." %> - <%= f.field :recurring_days, as: :number, label: "Every (days)" %> + <%= f.interval :recurring, label: "Every", wrapper: { class: "sm:col-span-2" }, + hint: "Months and years are calendar months: due at the end of the month (an annual done March 10 is due by the end of next March)." %>
<%= f.field :hours_tolerance, as: :number, step: 0.1, min: 0, label: "Overrun allowance (hours)", diff --git a/app/views/maintenance_reports/show.html.erb b/app/views/maintenance_reports/show.html.erb index baa8e45..352cc6e 100644 --- a/app/views/maintenance_reports/show.html.erb +++ b/app/views/maintenance_reports/show.html.erb @@ -52,7 +52,7 @@ <% @report.life_limited.each do |c| %> <%= c %> <%= c.model %><%= c.serial_number.presence || "—" %> - <%= [ (c.replacement_hours && "#{hours(c.replacement_hours)} hrs"), (c.replacement_days && "#{c.replacement_days} days"), (c.expires_on && "expires #{fmt_date(c.expires_on)}") ].compact.join(" / ") %> + <%= [ (c.replacement_hours && "#{hours(c.replacement_hours)} hrs"), c.replacement_interval_label, (c.expires_on && "expires #{fmt_date(c.expires_on)}") ].compact.join(" / ") %> <%= hours(c.hours_since_overhaul) %> hrs <%= [ (c.hours_to_replacement && "#{hours(c.hours_to_replacement)} hrs"), (c.next_replacement_date && "by #{fmt_date(c.next_replacement_date)}") ].compact.join(", ") %> <%= life_badge(c.life_status) %> @@ -70,7 +70,7 @@ <% @report.overhaul_items.each do |c| %> <%= c %> <%= c.model %><%= c.serial_number.presence || "—" %> - <%= [ (c.tbo_hours && "#{hours(c.tbo_hours)} hrs"), (c.tbo_days && "#{c.tbo_days} days") ].compact.join(" / ") %> + <%= [ (c.tbo_hours && "#{hours(c.tbo_hours)} hrs"), c.tbo_interval_label ].compact.join(" / ") %> <%= hours(c.hours_since_overhaul) %> hrs <%= c.hours_to_tbo ? "#{hours(c.hours_to_tbo)} hrs" : "—" %> <%= c.on_condition? ? "On condition (Part 91)" : (c.tbo_critical? ? "Hard limit" : "Recommended") %> diff --git a/app/views/shared/_aircraft_header.html.erb b/app/views/shared/_aircraft_header.html.erb index 4dacd25..43c3462 100644 --- a/app/views/shared/_aircraft_header.html.erb +++ b/app/views/shared/_aircraft_header.html.erb @@ -18,7 +18,7 @@
-
+
<%= link_to "Log Flight", new_aircraft_flight_log_path(aircraft), class: "btn-primary" %> <%= link_to "Report Squawk", new_aircraft_squawk_path(aircraft), class: "btn-secondary" %>
diff --git a/app/views/weight_balance_records/_calculator.html.erb b/app/views/weight_balance_records/_calculator.html.erb new file mode 100644 index 0000000..6048e26 --- /dev/null +++ b/app/views/weight_balance_records/_calculator.html.erb @@ -0,0 +1,34 @@ +<%# The loading calculator (W&B tab). %> +
+
+ <% setup.stations.each do |st| %> + + <% end %> + <% if setup.stations.any?(&:fuel) %> + + <% end %> +
+
+ + + + + + +
WeightCGMoment
Takeoff———
Landing———
+ +
+
    +

    A planning aid from the figures entered here. Check against the POH and the aircraft's current W&B report.

    +
    diff --git a/app/views/weight_balance_records/index.html.erb b/app/views/weight_balance_records/index.html.erb index 6c368b2..d1ef670 100644 --- a/app/views/weight_balance_records/index.html.erb +++ b/app/views/weight_balance_records/index.html.erb @@ -27,39 +27,7 @@ <% if owner? %><%= link_to "Loading setup", edit_aircraft_loading_setup_path(@aircraft), class: "btn-secondary btn-sm" %><% end %>
    <% if @current && setup.configured? %> -
    -
    - <% setup.stations.each do |st| %> - - <% end %> - <% if setup.stations.any?(&:fuel) %> - - <% end %> -
    -
    - - - - - - -
    WeightCGMoment
    Takeoff———
    Landing———
    - -
    -
      -

      A planning aid from the figures entered here. Check against the POH and the aircraft's current W&B report.

      -
      + <%= render "weight_balance_records/calculator", record: @current, setup: setup %> <% elsif !@current %> <%= empty_state "Record the current weight & balance first." %> <% else %> diff --git a/db/migrate/20261112010000_add_month_intervals_to_components.rb b/db/migrate/20261112010000_add_month_intervals_to_components.rb new file mode 100644 index 0000000..0a96b0c --- /dev/null +++ b/db/migrate/20261112010000_add_month_intervals_to_components.rb @@ -0,0 +1,9 @@ +# Component limits can be set in months or years (stored as months), not +# only days: "replace every 12 months" lands on the same date next year. +class AddMonthIntervalsToComponents < ActiveRecord::Migration[8.1] + def change + add_column :components, :replacement_months, :integer + add_column :components, :tbo_months, :integer + add_column :components, :inspection_months, :integer + end +end diff --git a/db/schema.rb b/db/schema.rb index 6363f10..c35d2b4 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_11_050000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_12_010000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -353,6 +353,9 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_050000) do t.datetime "updated_at", null: false t.date "expires_on" t.string "overhaul_kind" + t.integer "replacement_months" + t.integer "tbo_months" + t.integer "inspection_months" t.index ["aircraft_id"], name: "index_components_on_aircraft_id" t.index ["component_type_id"], name: "index_components_on_component_type_id" t.index ["parent_component_id"], name: "index_components_on_parent_component_id" diff --git a/docs/guide/ads.md b/docs/guide/ads.md index b15216c..a22baee 100644 --- a/docs/guide/ads.md +++ b/docs/guide/ads.md @@ -4,7 +4,7 @@ The **ADs** tab lists the ADs and bulletins that apply to the aircraft or its co ## Adding ADs -- **+ New AD**: the number, type (AD, SAIB, SB, alert, other), standard or conditional, what it requires, whether it recurs (every so many hours and/or months; due at the end of the month) and a link to the AD. A conditional AD only applies when its trigger happens (“on prop strike”) and doesn't affect airworthiness. Non-mandatory bulletins can be tracked too. +- **+ New AD**: the number, type (AD, SAIB, SB, alert, other), standard or conditional, what it requires, whether it recurs (every so many hours and/or days, months or years; months and years are due at the end of the month) and a link to the AD. A conditional AD only applies when its trigger happens (“on prop strike”) and doesn't affect airworthiness. Non-mandatory bulletins can be tracked too. - **Link existing**: ADs are shared between aircraft; link one already entered for another aircraft. - **Import from FAA DRS**: export the ADs for the aircraft, engine and propeller from the FAA's Dynamic Regulatory System, preferably as `.xlsx` so each AD keeps its DRS link, and upload it. The preview suggests **Track**, **Not applicable** or **Skip** for each AD and flags superseded ADs, model mismatches, appliance and STC-only ADs, and recurring actions. Nothing is duplicated. diff --git a/docs/guide/aircraft.md b/docs/guide/aircraft.md index 9bfe9f8..52b858b 100644 --- a/docs/guide/aircraft.md +++ b/docs/guide/aircraft.md @@ -10,6 +10,8 @@ The **Overview** tab shows: - **Airworthiness**: the overall status and each reason for it. - **Active squawks**, **Consumption** (oil and fuel rates), **Notes** and **Recent activity**. +- **Coming due**: anything due in the next 30 days or 10 hours. Dates marked "~" are estimated from the last year's flying. +- **Last flight**: the most recent day's legs as one route, the meters at the end, and the fuel and oil left. - **Update Hours**: enter the current meter readings (see [Flights and hours](flights.md)). - **Details** and the **Status report** link. diff --git a/docs/guide/components.md b/docs/guide/components.md index d5e5ba2..c24960e 100644 --- a/docs/guide/components.md +++ b/docs/guide/components.md @@ -9,10 +9,10 @@ The **Components** tab is a tree of the aircraft's parts: engine, propeller, mag - **Type** (pick one, or type a new one), manufacturer, model, serial number, install location and status. - **Time**: date in service, total time, last overhaul or service, hours since, and for engines and propellers the overhaul kind (printed in logbook entries as SMOH, SFOH or SNEW). - **Limits**: - - **Replace every** hours and/or days; **Replacement critical** makes overdue replacement ground the aircraft (oil, filters, ELT battery…). + - **Replace every** hours and/or a calendar interval in days, months or years (whichever comes first); **Replacement critical** makes overdue replacement ground the aircraft (oil, filters, ELT battery…). - **Expires on**: a date marked on the part, such as an ELT battery's. - - **TBO** hours and/or days. Under Part 91 TBO is usually a recommendation; tick **Treat TBO as a hard limit** only when an AD or the airworthiness limitations make it one, or **On condition** to show it without warnings. - - **Inspect every** hours and/or days, optionally critical. + - **TBO** hours and/or a calendar interval. Under Part 91 TBO is usually a recommendation; tick **Treat TBO as a hard limit** only when an AD or the airworthiness limitations make it one, or **On condition** to show it without warnings. + - **Inspect every** hours and/or a calendar interval, counted from the component's last service. For an inspection with its own records (an oil change, a magneto inspection, the ELT check), set it up on the **Inspections** tab and apply it to the component instead: the inspection then governs and the component's own interval is ignored. Logged hours are added to every component that's in service. diff --git a/docs/guide/inspections.md b/docs/guide/inspections.md index dcef636..2580d08 100644 --- a/docs/guide/inspections.md +++ b/docs/guide/inspections.md @@ -8,7 +8,7 @@ The **Inspections** tab shows each required inspection, when it was last done an **+ Inspection Type** adds your own, for example a recurring inspection from an STC's instructions for continued airworthiness. Each type has: -- **Recurring** every so many hours, calendar months (due at the end of the month) and/or days. +- **Recurring** every so many hours and/or days, months or years (months and years are calendar months, due at the end of the month). - What overdue means: **grounds the aircraft**, **no IFR flight** (91.411), **transponder can't be used** (91.413), or **advisory only**. - **Overrun allowance**: for the 100-hour, 10 hours. Done late within it, the next one counts from when it was due (91.409(b)). - **Also counts as**: an annual also counts as the 100-hour. diff --git a/test/integration/overview_due_and_intervals_test.rb b/test/integration/overview_due_and_intervals_test.rb new file mode 100644 index 0000000..0611520 --- /dev/null +++ b/test/integration/overview_due_and_intervals_test.rb @@ -0,0 +1,104 @@ +require "test_helper" + +# The Overview's Last flight and Coming due cards, and intervals entered as +# days, months or years. +class OverviewDueAndIntervalsTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user("owner@example.com") + @pilot = create_user("pilot@example.com") + @a = create_aircraft(owner: @owner, pilot: @pilot, tail_number: "N12345", tach_time: 1000) + @a.flight_logs.create!(date: Date.current - 20, tach_time: 1.0, departure_location: "KAAA", destination_location: "KAAA") + @a.flight_logs.create!(date: Date.current - 3, tach_time: 1.2, departure_location: "KAAA", destination_location: "KBBB") + @a.flight_logs.create!(date: Date.current - 3, tach_time: 0.9, departure_location: "KBBB", destination_location: "KAAA", + tach_in: 1000, fuel_level_after: 18, oil_level_after: 5) + @oil = create_component(@a, component_type: component_type("Oil"), manufacturer: "Phillips", model: "20W50", + replacement_hours: 50, hours_since_overhaul: 46, overhaul_date: Date.current - 30) + create_component(@a, component_type: component_type("Magneto"), manufacturer: "Bendix", model: "S4LN-21", + replacement_hours: 500, hours_since_overhaul: 100, overhaul_date: Date.current - 30) + end + + test "the overview shows the last day's flying and what's coming due" do + sign_in @pilot + get aircraft_path(@a) + assert_response :success + body = response.body + assert_includes body, "KAAA → KBBB → KAAA" + assert_includes body, "2 legs" + assert_includes body, "18 gal" + assert_includes body, "5 qt" + assert_includes body, "Replace Oil" # 4 hrs left + assert_not_includes body, "Replace Magneto" # 400 hrs left + end + + test "the overview copes with nothing logged" do + bare = create_aircraft(owner: @owner, tail_number: "N54321") + sign_in @owner + get aircraft_path(bare) + assert_response :success + assert_includes response.body, "No flights logged yet." + assert_includes response.body, "Nothing coming due soon." + end + + test "hours already run out count as overdue; an inspection covering a component replaces its own interval" do + filter = create_component(@a, component_type: component_type("Oil Filter"), manufacturer: "Champion", model: "CH48110", + inspection_hours: 50, hours_since_overhaul: 60, overhaul_date: Date.current - 300) + mag = create_component(@a, component_type: component_type("Magneto"), manufacturer: "Slick", model: "4371", + inspection_hours: 500, hours_since_overhaul: 120, overhaul_date: Date.current - 300) + items = DueList.new(@a).items.index_by(&:key) + assert items["inspect-#{filter.id}"].overdue? + assert_equal Date.current, items["inspect-#{filter.id}"].date + refute items["replace-#{@oil.id}"].overdue? + + type = InspectionType.create!(name: "Oil change", effect: "advisory", recurring: true, recurring_hours: 50) + type.components << filter + assert_nil DueList.new(@a).items.find { _1.key == "inspect-#{filter.id}" } + assert DueList.new(@a).items.find { _1.key == "inspect-#{mag.id}" } + end + + test "a component limit in years is stored as months and lands on the same date" do + sign_in @owner + get edit_aircraft_component_path(@a, @oil) + assert_select "select[name='component[replacement_unit]'] option", text: "years" + + patch aircraft_component_path(@a, @oil), params: { component: { replacement_every: "2", replacement_unit: "years", + overhaul_date: "2026-03-10" } } + @oil.reload + assert_equal [ nil, 24 ], [ @oil.replacement_days, @oil.replacement_months ] + assert_equal Date.new(2028, 3, 10), @oil.next_replacement_date + assert_equal "2 years", @oil.replacement_interval_label + + get edit_aircraft_component_path(@a, @oil) + assert_select "input[name='component[replacement_every]'][value='2']" + assert_select "select[name='component[replacement_unit]'] option[selected]", text: "years" + + patch aircraft_component_path(@a, @oil), params: { component: { replacement_every: "90", replacement_unit: "days" } } + assert_equal [ 90, nil ], @oil.reload.then { [ _1.replacement_days, _1.replacement_months ] } + + patch aircraft_component_path(@a, @oil), params: { component: { replacement_every: "", replacement_unit: "days" } } + assert_equal [ nil, nil ], @oil.reload.then { [ _1.replacement_days, _1.replacement_months ] } + + patch aircraft_component_path(@a, @oil), params: { component: { replacement_every: "1.5", replacement_unit: "months" } } + assert_response :unprocessable_entity + assert_includes response.body, "must be a whole number more than 0" + end + + test "inspection types and ADs take months or years, still due at the end of the month" do + sign_in @owner + post aircraft_inspection_types_path(@a), params: { inspection_type: { name: "ELT check", effect: "grounds", recurring: "1", + recurring_hours: "0", recurring_every: "1", recurring_unit: "years" }, + applies_to_airframe: "1" } + type = InspectionType.find_by!(name: "ELT check") + assert_equal [ 12, 0 ], [ type.recurring_months, type.recurring_days ] + assert_equal "Every 1 year", type.interval_description + + ad = AirworthinessDirective.new(name: "2020-01-01", short_description: "Seat rails", recurring: true, recurring_every: "100", recurring_unit: "days") + ad.valid? + assert_equal [ 100, 0 ], [ ad.recurring_days, ad.recurring_months ] + assert_equal({ hours: 0.0, months: 0, days: 100 }, ad.due_rule) + ad.recurring_every = "2" + ad.recurring_unit = "years" + ad.valid? + assert_equal [ 0, 24 ], [ ad.recurring_days, ad.recurring_months ] + assert_equal "2 years", ad.recurring_interval_label + end +end