diff --git a/CHANGELOG.md b/CHANGELOG.md index c6062c8..15a722b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ Each release has a **version** (year.month.release, e.g. 2026.11.0) and a **build** (the exact source commit, shown on Admin → About). The newest release is first. +## 2026.11.1 + +### Fixes + +- Logging a flight offline works: the Log Flight form is kept on the device however you open it, the offline page shows its links and icon, and a flight saved while the app's server is unreachable (502/503/504) is queued and sent later instead of failing. +- Marking a sub-component Serviced on a logbook entry restarts its time since service from the airframe time on the entry, so new oil typed in at 0 hours no longer keeps its old hours. + +### Changes + +- New logbook entries have **Inspections completed**: tick the inspections the work completes (an oil change) and they're recorded on the Inspections tab at the entry's date and airframe time, linked to the entry. +- Components have **Replacement counts from**: last service (as before) or installation, for a life-limited part that's cleaned and reused, such as a reusable oil filter. Only a replacement restarts an installation-based limit. +- A component's own "Inspect every" and "Inspection critical" settings are gone; inspections of a part are inspection types applied to it. A component's page lists its inspections with last done and next due, and **+ Inspection** adds one for that part. Existing settings are converted when upgrading. + ## 2026.11.0 The first numbered release. Highlights of what Simple Aircraft Manager does as of this version: diff --git a/VERSION b/VERSION index d6484a6..92848b9 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2026.11.0 +2026.11.1 diff --git a/app/controllers/components_controller.rb b/app/controllers/components_controller.rb index 4e0df80..db8baa5 100644 --- a/app/controllers/components_controller.rb +++ b/app/controllers/components_controller.rb @@ -23,6 +23,8 @@ class ComponentsController < ApplicationController def show @squawks = @component.squawks.by_priority.with_attached_attachments + ids = @component.inspection_type_ids + @inspection_rows = Compliance.inspection_rows(@aircraft).select { ids.include?(_1.type.id) } end def new @@ -76,10 +78,8 @@ class ComponentsController < ApplicationController params.require(:component).permit( :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, :replacement_every, :replacement_unit, :tbo_every, :tbo_unit, - :inspection_every, :inspection_unit, :tbo_critical, :on_condition, - :inspection_critical, :replacement_critical, :expires_on + :hours_since_overhaul, :overhaul_date, :overhaul_kind, :tbo_hours, :tbo_days, :replacement_hours, :replacement_days, :replacement_every, :replacement_unit, :tbo_every, :tbo_unit, + :tbo_critical, :on_condition, :replacement_critical, :replacement_from_install, :expires_on ).tap do |p| # Owners can create a component type inline instead of asking an admin. if (name = params[:new_component_type].to_s.strip).present? diff --git a/app/controllers/inspection_types_controller.rb b/app/controllers/inspection_types_controller.rb index 52cb1dc..3ddce2c 100644 --- a/app/controllers/inspection_types_controller.rb +++ b/app/controllers/inspection_types_controller.rb @@ -11,6 +11,11 @@ class InspectionTypesController < ApplicationController @inspection_type.name = "ICA: #{@major_record.title}".first(120) @applies_to_airframe = @major_record.component.nil? @inspection_type.components = [ @major_record.component ] if @major_record.component + elsif (component = @aircraft.components.find_by(id: params[:component_id])) + # From a component's page: applies to that part, e.g. "Magneto 500-hour inspection". + @inspection_type.name = "#{component} inspection" + @inspection_type.components = [ component ] + @applies_to_airframe = false end end diff --git a/app/controllers/logbook_entries_controller.rb b/app/controllers/logbook_entries_controller.rb index 65cf1e0..4f743e2 100644 --- a/app/controllers/logbook_entries_controller.rb +++ b/app/controllers/logbook_entries_controller.rb @@ -38,6 +38,7 @@ class LogbookEntriesController < ApplicationController if @entry.save log_event("logbook", "Logbook entry #{@entry.supersedes ? 'correction ' : ''}added (#{@entry.date})") record_parts_service + record_inspections redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: @entry.supersedes ? "Correction saved. Sign it to supersede the original entry." : "Logbook entry added." else @@ -92,15 +93,27 @@ class LogbookEntriesController < ApplicationController # Sub-components marked "Serviced" or "Replaced" on a new entry: recorded on # the Components tab too, dated to the entry. def record_parts_service + flown = (@aircraft.current_hours - @entry.aircraft_hours_at_entry if @entry.aircraft_hours_at_entry) parts_params.each do |id, p| next unless p["include"] == "1" && %w[serviced replaced].include?(p["service"]) part = @entry.parts.find { _1.component_id == id.to_i } or next component = part.component - component.service_from_entry!(date: @entry.date, hours_at_entry: part.hours_at_entry, replaced: p["service"] == "replaced") + component.service_from_entry!(date: @entry.date, hours_at_entry: part.hours_at_entry, flown_since: flown, replaced: p["service"] == "replaced") log_event("component", "#{p['service'] == 'replaced' ? 'Replaced' : 'Serviced'}: #{component} (logbook entry #{@entry.date})") end end + # Inspections ticked on a new entry (e.g. Oil Change): done at the entry's + # date and airframe time, linked to it. + def record_inspections + ids = Array(params.dig(:logbook_entry, :inspection_type_ids)).compact_blank + @aircraft.applicable_inspection_types.where(id: ids).find_each do |type| + @aircraft.inspection_records.create!(inspection_type: type, logbook_entry: @entry, date: @entry.date, + aircraft_hours: @entry.aircraft_hours_at_entry) + log_event("inspection", "Inspection completed: #{type.name} (logbook entry #{@entry.date})") + end + end + # Sub-components ticked on the form: { component_id => { include, hours, since, service } }. def parts_params params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {} diff --git a/app/javascript/controllers/offline_flight_controller.js b/app/javascript/controllers/offline_flight_controller.js index 3aa8cea..a10b047 100644 --- a/app/javascript/controllers/offline_flight_controller.js +++ b/app/javascript/controllers/offline_flight_controller.js @@ -35,6 +35,14 @@ export default class extends Controller { if (this.pending) await this.save(this.pending) } + // A proxy answered because the app is unreachable (502/503/504): keep the + // flight instead of showing the proxy's error page. + async gatewayFailed(event) { + if (![ 502, 503, 504 ].includes(event.detail.fetchResponse.statusCode) || !this.pending) return + event.preventDefault() + await this.save(this.pending) + } + async save(fields) { const item = { id: this.keyTarget.value, url: this.element.action, tail: this.tailValue, savedAt: new Date().toISOString(), fields } try { diff --git a/app/javascript/controllers/offline_sync_controller.js b/app/javascript/controllers/offline_sync_controller.js index 8b7eb57..080ae83 100644 --- a/app/javascript/controllers/offline_sync_controller.js +++ b/app/javascript/controllers/offline_sync_controller.js @@ -46,6 +46,7 @@ export default class extends Controller { try { response = await fetch(item.url, { method: "POST", body, credentials: "same-origin", headers: { Accept: "text/html" } }) } catch (_) { return "offline" } + if ([ 502, 503, 504 ].includes(response.status)) return "offline" if (response.url.includes("/session/new")) return "signin" if (response.ok) return "sent" const html = await response.text() diff --git a/app/models/component.rb b/app/models/component.rb index 60be0e8..bc4f965 100644 --- a/app/models/component.rb +++ b/app/models/component.rb @@ -8,7 +8,6 @@ class Component < ApplicationRecord 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 @@ -63,15 +62,21 @@ class Component < ApplicationRecord tbo_hours - hours_since_overhaul if tbo_hours end + # The hours the replacement limit counts: since installed for a life-limited + # part that's serviced and reused, else since its last service. + def replacement_hours_used = replacement_from_install? ? hours_in_service : hours_since_overhaul + + def replacement_counted_from = replacement_from_install? ? date_in_service : overhaul_date + def hours_to_replacement - replacement_hours - hours_since_overhaul if replacement_hours + replacement_hours - replacement_hours_used if replacement_hours end # Past the date marked on the part (it may be used through that date). def expired?(today = Date.current) = expires_on.present? && today > expires_on def next_replacement_date - replacement_after(overhaul_date) + replacement_after(replacement_counted_from) end # :overdue / :due_soon / :ok / nil (not tracked) for display on the components tab. @@ -96,10 +101,18 @@ class Component < ApplicationRecord # Service reset: always zeroes time since overhaul; optionally the whole # in-service clock when the part was physically replaced. # Serviced (or replaced) as recorded in a logbook entry: dated to the entry, - # with the hours it has run since then (its total time now less its total - # time at the entry) as the new time since service. - def service_from_entry!(date:, hours_at_entry:, replaced: false) - since = hours_at_entry ? [ hours_in_service.to_d - hours_at_entry.to_d, 0 ].max : 0 + # with the hours it has run since then as the new time since service. That's + # the airframe time flown since the entry when known (the part's own total + # at the entry is often typed as 0 for new oil, which would keep the old + # hours), else its total time now less its total time at the entry. + def service_from_entry!(date:, hours_at_entry:, flown_since: nil, replaced: false) + since = + if flown_since then flown_since.to_d + elsif hours_at_entry then hours_in_service.to_d - hours_at_entry.to_d + else 0 + end + since = [ since, 0 ].max + since = [ since, hours_in_service.to_d ].min unless replaced # can't have run longer since service than in total attrs = { hours_since_overhaul: since, overhaul_date: date } attrs.merge!(hours_in_service: since, date_in_service: date) if replaced update!(attrs) diff --git a/app/services/aircraft_archive/exporter.rb b/app/services/aircraft_archive/exporter.rb index aab5b60..e5bed72 100644 --- a/app/services/aircraft_archive/exporter.rb +++ b/app/services/aircraft_archive/exporter.rb @@ -145,10 +145,11 @@ module AircraftArchive manufacturer: c.manufacturer, model: c.model, serial_number: c.serial_number, install_location: c.install_location, 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, + tbo_days: c.tbo_days, 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 } + replacement_months: c.replacement_months, tbo_months: c.tbo_months, tbo_critical: c.tbo_critical, + on_condition: c.on_condition, replacement_critical: c.replacement_critical, + replacement_from_install: c.replacement_from_install } end def logbook_hash(e) diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index 3649cff..2d852de 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -215,9 +215,9 @@ 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 - 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 + **data.slice(*%w[tbo_hours tbo_days replacement_hours replacement_days + tbo_months replacement_months]).symbolize_keys, + **data.slice(*%w[tbo_critical on_condition replacement_critical replacement_from_install]).transform_values { _1 == true }.symbolize_keys ) c.save!(validate: false) @map[:component][data["id"].to_s] = c.id diff --git a/app/services/airworthiness.rb b/app/services/airworthiness.rb index 5e96903..01f77d0 100644 --- a/app/services/airworthiness.rb +++ b/app/services/airworthiness.rb @@ -146,19 +146,20 @@ class Airworthiness desc = "" if c.replacement_critical? && c.replacement_hours - if c.hours_since_overhaul >= c.replacement_hours + used = c.replacement_hours_used + if used >= c.replacement_hours overdue = true - desc = "Replace every #{c.replacement_hours} hrs. Current: #{c.hours_since_overhaul} hrs." - elsif c.hours_since_overhaul + HOURS_WARNING >= c.replacement_hours + desc = "Replace every #{c.replacement_hours} hrs. Current: #{used} hrs#{' since installed' if c.replacement_from_install?}." + elsif used + HOURS_WARNING >= c.replacement_hours approaching = true - desc = "Replace in #{c.replacement_hours - c.hours_since_overhaul} hrs." + desc = "Replace in #{c.replacement_hours - used} hrs." end end if c.replacement_critical? && (due = c.next_replacement_date) if @today >= due overdue = true - desc = "Replace every #{c.replacement_interval_label}. Last serviced #{c.overhaul_date}." + desc = "Replace every #{c.replacement_interval_label}. #{c.replacement_from_install? ? 'Installed' : 'Last serviced'} #{c.replacement_counted_from}." elsif @today + DAYS_WARNING >= due approaching = true desc = "Replace in #{(due - @today).to_i} days." diff --git a/app/services/due_list.rb b/app/services/due_list.rb index 6a3b8db..7c130f1 100644 --- a/app/services/due_list.rb +++ b/app/services/due_list.rb @@ -57,23 +57,17 @@ 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, :inspection_types).flat_map do |c| + @aircraft.components.in_use.includes(:component_type).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_calendar?), + hours_left: c.hours_to_replacement) if c.replacement_hours || c.replacement_calendar?), (item("tbo-#{c.id}", "#{label} reaches TBO", "component", path, 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_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/views/components/_form.html.erb b/app/views/components/_form.html.erb index a4acb32..a6017ff 100644 --- a/app/views/components/_form.html.erb +++ b/app/views/components/_form.html.erb @@ -29,6 +29,9 @@ Limits <%= f.field :replacement_hours, as: :number, label: "Replace every (hrs)" %> <%= f.interval :replacement, label: "Replace every" %> + <%= f.field :replacement_from_install, as: :select, label: "Replacement counts from", + collection: [ [ "Last service", false ], [ "Installation (life limit)", true ] ], + hint: "Installation: for a part that's cleaned and reused but has a life limit (e.g. a reusable oil filter); only Replaced restarts it." %> <%= 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)." %> @@ -40,10 +43,7 @@ <%= f.field :on_condition, as: :checkbox, label: "On condition (Part 91)", 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.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" %> +

Recurring inspections of this part (e.g. a 500-hour magneto inspection) are set up on the Inspections tab and applied to it.

<%= f.field :notes, as: :textarea, rows: 3 %> diff --git a/app/views/components/index.html.erb b/app/views/components/index.html.erb index b71f15b..cd635c8 100644 --- a/app/views/components/index.html.erb +++ b/app/views/components/index.html.erb @@ -32,7 +32,7 @@ <%= hours(c.hours_since_overhaul) %> <% if c.replacement_critical? && (c.replacement_hours || c.replacement_calendar?) %> - Replace: <%= [c.replacement_hours && "#{c.replacement_hours} h", c.replacement_interval_label].compact.join(" / ") %>
+ Replace: <%= [c.replacement_hours && "#{c.replacement_hours} h", c.replacement_interval_label].compact.join(" / ") %><%= " since installed" if c.replacement_from_install? %>
<% 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 4423e48..4d492ca 100644 --- a/app/views/components/show.html.erb +++ b/app/views/components/show.html.erb @@ -24,12 +24,12 @@
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_interval_label].compact.join(" / ").presence || "—" %> + <%= [@component.replacement_hours && "#{@component.replacement_hours} h", @component.replacement_interval_label].compact.join(" / ").presence&.then { @component.replacement_from_install? ? "#{_1} since installed" : _1 } || "—" %> <% if (d = @component.next_replacement_date) %>
Next by <%= fmt_date(d) %>
<% end %>
Flags
- <% { tbo_critical: "TBO critical", replacement_critical: "Replacement critical", inspection_critical: "Inspection critical", on_condition: "On condition" }.each do |flag, label| %> + <% { tbo_critical: "TBO critical", replacement_critical: "Replacement critical", on_condition: "On condition" }.each do |flag, label| %> <% if @component.public_send("#{flag}?") %><%= label %><% end %> <% end %>
@@ -53,6 +53,33 @@ <% end %> +<% if @inspection_rows.any? || owner? %> +
+
+

Inspections of this component

+ <% if owner? %><%= link_to "+ Inspection", new_aircraft_inspection_type_path(@aircraft, component_id: @component.id), class: "btn-secondary btn-sm" %><% end %> +
+ <% if @inspection_rows.any? %> + + + + <% @inspection_rows.each do |row| %> + + + + + + + + <% end %> + +
InspectionIntervalLast doneNext dueStatus
<%= row.type.name %><%= tag.span(" advisory", class: "text-xs text-slate-500") if row.type.advisory? %><%= row.type.interval_description %><%= row.latest ? "#{fmt_date(row.latest.date)} @ #{hours(row.latest.hours_at_inspection)} h" : "—" %><%= [row.next_due_date&.to_s, row.next_due_hours && "#{hours(row.next_due_hours)} h"].compact.join(" / ").presence || "—" %><%= compliance_badge(row.status) %>
+ <% else %> +

None. Add one for a recurring inspection of this part (e.g. a 500-hour magneto inspection); it's tracked on the Inspections tab and can be completed from a logbook entry.

+ <% end %> +
+<% end %> + <% if @squawks.any? %>

Squawks on this component

diff --git a/app/views/flight_logs/new.html.erb b/app/views/flight_logs/new.html.erb index 6e6038c..39ff2ac 100644 --- a/app/views/flight_logs/new.html.erb +++ b/app/views/flight_logs/new.html.erb @@ -2,7 +2,7 @@ <%= render "shared/aircraft_header", aircraft: @aircraft %> <%= form_with model: [@aircraft, @flight_log], class: "card card-body space-y-5 max-w-3xl", data: { controller: "offline-flight", offline_flight_tail_value: @aircraft.tail_number, - action: "submit->offline-flight#submit turbo:submit-start->offline-flight#remember turbo:fetch-request-error->offline-flight#networkFailed" } do |f| %> + action: "submit->offline-flight#submit turbo:submit-start->offline-flight#remember turbo:fetch-request-error->offline-flight#networkFailed turbo:before-fetch-response->offline-flight#gatewayFailed" } do |f| %> <%= f.hidden_field :client_key, data: { offline_flight_target: "key" } %> <%= f.errors_summary %> diff --git a/app/views/logbook_entries/_form.html.erb b/app/views/logbook_entries/_form.html.erb index 9fc1628..c7565f5 100644 --- a/app/views/logbook_entries/_form.html.erb +++ b/app/views/logbook_entries/_form.html.erb @@ -33,6 +33,23 @@ <%= f.field :text, as: :textarea, label: "Entry text", rows: 8, data: { entry_template_target: "text" } %>

A maintenance entry needs a description of the work, the date, and the name, signature, certificate number and kind of certificate of whoever approved the return to service (14 CFR 43.9). An inspection entry also needs the type and extent of the inspection, the aircraft's time in service, and the result (43.11).

<%= render "shared/sign_as" %> + <% if entry.new_record? && (types = aircraft.applicable_inspection_types.order(:name)).any? %> + <%# Recurring items this work completes (e.g. an oil change): recorded on the Inspections tab, dated to this entry. %> + <% ticked = Array(params.dig(:logbook_entry, :inspection_type_ids)).map(&:to_s) %> +
+ Inspections completed +
+ <% types.each do |t| %> + + <% end %> +
+

Ticked ones are recorded as done on the Inspections tab, at this entry's date and airframe time, linked to this entry.

+
+ <% end %>
<%= f.field :signoff_person, label: "Signed off by", placeholder: "Name", data: { signer_target: "name" } %> <%= f.field :signoff_certificate_type, as: :select, label: "Kind of certificate", include_blank: "—", diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js index 384a29b..521021e 100644 --- a/app/views/pwa/service-worker.js +++ b/app/views/pwa/service-worker.js @@ -2,12 +2,15 @@ // static files (the offline page, icons, fingerprinted /assets/) and, so a // flight can be logged without signal, the Log Flight forms you've opened // (tail number and meter readings only). Other aircraft pages are never cached. -const VERSION = "v2" +const VERSION = "v5" const FORM_CACHE = "sam-flight-forms" const FLIGHT_FORM = /^\/aircraft\/\d+\/flight_logs\/new$/ const SHELL_CACHE = `sam-shell-${VERSION}` const ASSET_CACHE = "sam-assets" const MAX_ASSETS = 80 +// A proxy in front of the app (Traefik, Authentik) answers these when the app +// itself can't be reached: treat them like no connection. +const UNREACHABLE = [ 502, 503, 504 ] const SHELL = [ "/offline.html", "/offline.js", "/icon.svg", "/icon-192.png" ] self.addEventListener("install", (event) => { @@ -28,11 +31,20 @@ self.addEventListener("fetch", (event) => { const url = new URL(request.url) if (url.origin !== self.location.origin) return - if (request.mode === "navigate" && FLIGHT_FORM.test(url.pathname)) { + // Turbo opens pages with fetch(), not a navigation, so match those too or + // the form is never kept when reached by tapping "Log Flight". + const wantsHtml = request.mode === "navigate" || (request.headers.get("Accept") || "").includes("text/html") + if (wantsHtml && FLIGHT_FORM.test(url.pathname)) { event.respondWith(flightForm(request)) } else if (request.mode === "navigate") { // Always go to the network for pages; show the offline page if it's unreachable. - event.respondWith(fetch(request).catch(() => caches.match("/offline.html"))) + event.respondWith(fetch(request) + .then((response) => UNREACHABLE.includes(response.status) ? caches.match("/offline.html") : response) + .catch(() => caches.match("/offline.html"))) + } else if (SHELL.includes(url.pathname)) { + // The offline page's own script and icon: fresh when online, kept copy when not. + event.respondWith(fetch(request).then((r) => r.ok ? r : caches.match(url.pathname).then((hit) => hit || r)) + .catch(() => caches.match(url.pathname))) } else if (url.pathname.startsWith("/assets/")) { event.respondWith(cachedAsset(request)) } @@ -61,11 +73,22 @@ async function trim(cache) { // the kept copy when there isn't. async function flightForm(request) { const cache = await caches.open(FORM_CACHE) + const key = request.url.split("?")[0] try { const response = await fetch(request) - if (response.ok && !response.redirected) await cache.put(request.url.split("?")[0], response.clone()) + if (UNREACHABLE.includes(response.status)) { + const kept = await cache.match(key) + if (kept) return kept + return request.mode === "navigate" ? caches.match("/offline.html") : response + } + const html = (response.headers.get("Content-Type") || "").includes("text/html") + if (response.ok && !response.redirected && html) await cache.put(key, response.clone()) return response - } catch (_) { - return (await cache.match(request.url.split("?")[0])) || caches.match("/offline.html") + } catch (error) { + const kept = await cache.match(key) + if (kept) return kept + // A Turbo fetch gets the error, so Turbo falls back to a full page load. + if (request.mode !== "navigate") throw error + return caches.match("/offline.html") } } diff --git a/db/migrate/20261112020000_add_replacement_from_install_to_components.rb b/db/migrate/20261112020000_add_replacement_from_install_to_components.rb new file mode 100644 index 0000000..8f43591 --- /dev/null +++ b/db/migrate/20261112020000_add_replacement_from_install_to_components.rb @@ -0,0 +1,8 @@ +# A life-limited part that's cleaned and reused (e.g. a Challenger oil filter): +# its "replace every" limit counts from when it was installed (total time in +# service), not from its last service. +class AddReplacementFromInstallToComponents < ActiveRecord::Migration[8.1] + def change + add_column :components, :replacement_from_install, :boolean, default: false, null: false + end +end diff --git a/db/migrate/20261112030000_move_component_inspections_to_inspection_types.rb b/db/migrate/20261112030000_move_component_inspections_to_inspection_types.rb new file mode 100644 index 0000000..646eb26 --- /dev/null +++ b/db/migrate/20261112030000_move_component_inspections_to_inspection_types.rb @@ -0,0 +1,47 @@ +# A component's own "Inspect every" (hours / days / months, "Inspection +# critical") only fed the coming-due list, counted from its last service, and +# never affected airworthiness. Inspection types linked to the component do +# all of that properly (records, airworthiness, logbook entries), so each +# setting becomes one: grounding if it was critical, else advisory, with a +# first record at the component's last service so the next due stays the same. +# Components that already had an inspection type linked ignored these fields, +# so they're just dropped. +class MoveComponentInspectionsToInspectionTypes < ActiveRecord::Migration[8.1] + def up + rows = select_all(<<~SQL).to_a + SELECT c.id, c.inspection_hours, c.inspection_days, c.inspection_months, c.inspection_critical, + c.overhaul_date, c.hours_since_overhaul + FROM components c + WHERE c.status <> 'DISPOSED' + AND (COALESCE(c.inspection_hours, 0) > 0 OR COALESCE(c.inspection_days, 0) > 0 OR COALESCE(c.inspection_months, 0) > 0) + AND NOT EXISTS (SELECT 1 FROM components_inspection_types ci WHERE ci.component_id = c.id) + SQL + [ Component, InspectionType, InspectionRecord ].each(&:reset_column_information) + rows.each do |row| + component = Component.find(row["id"]) + critical = ActiveModel::Type::Boolean.new.cast(row["inspection_critical"]) + type = InspectionType.create!(name: "#{component} #{component.model} inspection".squish.first(120), recurring: true, + required: critical, effect: critical ? "grounds" : "advisory", + recurring_hours: row["inspection_hours"].to_i, recurring_days: row["inspection_days"].to_i, + recurring_months: row["inspection_months"].to_i) + type.components << component + next unless (date = row["overhaul_date"]) + aircraft = component.aircraft + hours = aircraft && [ aircraft.current_hours - row["hours_since_overhaul"].to_d, 0 ].max + InspectionRecord.create!(inspection_type: type, aircraft: aircraft, component: component, date: date, aircraft_hours: hours, + notes: "From the component's last service (its former \"Inspect every\" setting).") + end + + remove_column :components, :inspection_hours + remove_column :components, :inspection_days + remove_column :components, :inspection_months + remove_column :components, :inspection_critical + end + + def down + add_column :components, :inspection_hours, :integer + add_column :components, :inspection_days, :integer + add_column :components, :inspection_months, :integer + add_column :components, :inspection_critical, :boolean, default: true, null: false + end +end diff --git a/db/schema.rb b/db/schema.rb index c35d2b4..caf1a9d 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_12_010000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_12_030000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -341,21 +341,18 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_12_010000) do t.date "overhaul_date" t.integer "tbo_hours" t.integer "tbo_days" - t.integer "inspection_hours" - t.integer "inspection_days" t.integer "replacement_hours" t.integer "replacement_days" t.boolean "tbo_critical", default: true, null: false t.boolean "on_condition", default: false, null: false - t.boolean "inspection_critical", default: true, null: false t.boolean "replacement_critical", default: false, null: false + t.boolean "replacement_from_install", default: false, null: false t.datetime "created_at", null: false 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/components.md b/docs/guide/components.md index c24960e..eceaa39 100644 --- a/docs/guide/components.md +++ b/docs/guide/components.md @@ -12,7 +12,9 @@ The **Components** tab is a tree of the aircraft's parts: engine, propeller, mag - **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 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. + - **Replacement counts from**: *Last service* (the default), or *Installation (life limit)* for a part that's cleaned and reused but has a life limit, such as a reusable oil filter: its limit then counts from its total time and in-service date, and only a replacement restarts it. + +**Inspections** of a part (a magneto's 500-hour inspection, an oil change, the ELT check) are inspection types applied to the component: use **+ Inspection** on the component's page, or set one up on the **Inspections** tab. The component's page lists them with when they were last done and are next due; they're tracked from their records, count toward airworthiness, and can be completed from a logbook entry. Logged hours are added to every component that's in service. diff --git a/docs/guide/logbook.md b/docs/guide/logbook.md index d690145..0dd0e18 100644 --- a/docs/guide/logbook.md +++ b/docs/guide/logbook.md @@ -9,6 +9,8 @@ The **Logbook** tab holds the maintenance record entries. Owners write and edit 1. Choose a **Template** to start the wording if one fits, and fill in its blanks (`__`). The built-in ones are for a pilot doing preventive maintenance on an aircraft they own or operate (14 CFR 43.3(g)); admins can add their own. 2. Fill in the date, the **logbook** (aircraft, engine, propeller or other), the **entry type** (usually maintenance or inspection) and the **airframe total time**. 3. For an engine or propeller entry, pick the component: its total time and time since overhaul at the entry fill in from the airframe time. Tick any **sub-components** included in the work (an oil filter on the engine) to record their times as well. On a new entry, set a sub-component to **Serviced** or **Replaced** to record that on the Components tab at the same time (an oil and filter change resets their time since service), dated to the entry. + Its time since service then counts from the airframe time on the entry. + Under **Inspections completed**, tick any inspection the work completes (an Oil Change): it's recorded as done on the Inspections tab at the entry's date and airframe time, linked to the entry. 4. Write the **entry text**: what was done, with reference to the data used. 5. The sign-off fields (who, certificate kind and number, location) are filled in when the entry is signed electronically. Fill them in yourself for an entry copied from a paper logbook. 6. For an inspection, record the **inspection result** (approved for return to service, or a list of discrepancies given to the owner). diff --git a/public/offline.js b/public/offline.js index 6c9b285..d5b43ed 100644 --- a/public/offline.js +++ b/public/offline.js @@ -6,10 +6,15 @@ try { var box = document.getElementById("forms") Object.keys(forms).forEach(function (path) { if (!/^\/aircraft\/\d+\/flight_logs\/new$/.test(path)) return - var a = document.createElement("a") - a.href = path - a.textContent = "Log a flight: " + forms[path] - box.appendChild(a) - box.hidden = false + // Only offer forms the service worker actually kept; others just loop back here. + var kept = window.caches ? caches.open("sam-flight-forms").then(function (c) { return c.match(location.origin + path) }) : Promise.resolve(null) + kept.then(function (hit) { + if (!hit) return + var a = document.createElement("a") + a.href = path + a.textContent = "Log a flight: " + forms[path] + box.appendChild(a) + box.hidden = false + }).catch(function () {}) }) } catch (e) { /* storage off */ } diff --git a/test/integration/calendar_feed_test.rb b/test/integration/calendar_feed_test.rb index adc922f..42f36db 100644 --- a/test/integration/calendar_feed_test.rb +++ b/test/integration/calendar_feed_test.rb @@ -10,7 +10,7 @@ class CalendarFeedTest < ActionDispatch::IntegrationTest @oil = create_component(@a, component_type: component_type("Oil"), manufacturer: "Phillips", model: "20W50", replacement_hours: 50, replacement_days: 120, hours_since_overhaul: 45, overhaul_date: Date.current - 30) @mag = create_component(@a, component_type: component_type("Magneto"), manufacturer: "Bendix", model: "S4LN-21", - inspection_hours: 500, hours_since_overhaul: 450, overhaul_date: Date.current - 400) + tbo_hours: 500, hours_since_overhaul: 450, overhaul_date: Date.current - 400) @a.documents.create!(name: "Registration", doc_type: "REGISTRATION", expires_on: Date.current + 200) end @@ -20,7 +20,7 @@ class CalendarFeedTest < ActionDispatch::IntegrationTest assert_equal Date.current + 50, oil.date # 5 hrs at 0.1/day, before the 120-day limit (90 days left) assert oil.projected assert_equal 1005.0, oil.due_hours.to_f - assert_equal Date.current + 500, items["inspect-#{@mag.id}"].date # 50 hrs / 0.1 a day + assert_equal Date.current + 500, items["tbo-#{@mag.id}"].date # 50 hrs / 0.1 a day assert_equal Date.current + 200, items["document-#{@a.documents.first.id}"].date refute items["document-#{@a.documents.first.id}"].projected end diff --git a/test/integration/logbook_entry_parts_test.rb b/test/integration/logbook_entry_parts_test.rb index ddf31fc..3b6ce33 100644 --- a/test/integration/logbook_entry_parts_test.rb +++ b/test/integration/logbook_entry_parts_test.rb @@ -68,6 +68,28 @@ class LogbookEntryPartsTest < ActionDispatch::IntegrationTest assert_select "select[name='logbook_entry[parts][#{oil.id}][service]']", 0 end + test "servicing new oil typed in at 0 hours restarts it from the airframe time flown since the entry" do + oil = create_component(@a, component_type: component_type("Oil"), manufacturer: "Phillips", model: "20W50", + parent_component: @engine, hours_in_service: 36.0, hours_since_overhaul: 36.0) + post aircraft_logbook_entries_path(@a), params: { logbook_entry: entry_params(aircraft_hours_at_entry: 4210.3, parts: { + oil.id => { include: "1", hours: "0.0", since: "0.0", service: "serviced" } }) } + assert_equal [ 0.0, 36.0, Date.new(2026, 8, 20) ], oil.reload.then { [ _1.hours_since_overhaul.to_f, _1.hours_in_service.to_f, _1.overhaul_date ] } + end + + test "a new entry can complete inspections such as an oil change" do + oil_change = InspectionType.create!(name: "Oil Change", recurring: true, recurring_hours: 50).tap { _1.aircraft << @a } + get new_aircraft_logbook_entry_path(@a) + assert_select "input[name='logbook_entry[inspection_type_ids][]'][value='#{oil_change.id}']" + post aircraft_logbook_entries_path(@a), params: { logbook_entry: entry_params(inspection_type_ids: [ "", oil_change.id ]) } + entry = @a.logbook_entries.sole + record = @a.inspection_records.sole + assert_equal [ oil_change, entry, Date.new(2026, 8, 20), 4200.3 ], [ record.inspection_type, record.logbook_entry, record.date, record.aircraft_hours.to_f ] + assert @a.events.exists?(event_name: "Inspection completed: Oil Change (logbook entry 2026-08-20)") + + get edit_aircraft_logbook_entry_path(@a, entry) # not offered again on edit (it would record twice) + assert_select "input[name='logbook_entry[inspection_type_ids][]']", 0 + end + test "printouts add a line per sub-component; archives carry them" do entry = @a.logbook_entries.create!(entry_params.merge(component: @engine)) entry.parts.create!(component: @filter, hours_at_entry: 110.5, since_overhaul_at_entry: 10.5) diff --git a/test/integration/overview_and_intervals_test.rb b/test/integration/overview_and_intervals_test.rb index f651c53..9604fb7 100644 --- a/test/integration/overview_and_intervals_test.rb +++ b/test/integration/overview_and_intervals_test.rb @@ -36,20 +36,30 @@ class OverviewAndIntervalsTest < ActionDispatch::IntegrationTest assert_includes response.body, "No flights logged yet." end - test "hours already run out count as overdue; an inspection covering a component replaces its own interval" do + test "hours already run out count as overdue" 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) + replacement_hours: 50, hours_since_overhaul: 60, 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 + assert items["replace-#{filter.id}"].overdue? + assert_equal Date.current, items["replace-#{filter.id}"].date refute items["replace-#{@oil.id}"].overdue? + end - 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}" } + test "a component's page lists the inspections applied to it and offers to add one for it" do + sign_in @owner + mag = create_component(@a, component_type: component_type("Magneto"), manufacturer: "Slick", model: "4371", install_location: "Left") + get aircraft_component_path(@a, mag) + assert_select "#inspections", text: /None/ + get new_aircraft_inspection_type_path(@a, component_id: mag.id) + assert_select "input[name='inspection_type[name]'][value='Magneto (Left) inspection']" + assert_select "input#comp_#{mag.id}[checked]" + assert_select "input[name=applies_to_airframe]:not([checked])" + + InspectionType.create!(name: "Left magneto 500-hour", effect: "advisory", recurring: true, recurring_hours: 500).components << mag + get aircraft_component_path(@a, mag) + assert_select "#inspections td", text: /Left magneto 500-hour/ + get edit_aircraft_component_path(@a, mag) + assert_select "input[name='component[inspection_hours]']", 0 end test "a component limit in years is stored as months and lands on the same date" do diff --git a/test/services/airworthiness_test.rb b/test/services/airworthiness_test.rb index 0f293a5..74cad67 100644 --- a/test/services/airworthiness_test.rb +++ b/test/services/airworthiness_test.rb @@ -85,6 +85,17 @@ class AirworthinessTest < ActiveSupport::TestCase assert_equal "RED", Airworthiness.new(@aircraft).call.status end + test "a life limit counted from installation ignores servicing" do + filter = create_component(@aircraft, component_type: component_type("Oil filter"), replacement_critical: true, replacement_hours: 1250, + hours_in_service: 1250, hours_since_overhaul: 10, date_in_service: Date.current, overhaul_date: Date.current) + assert_equal "GREEN", Airworthiness.new(@aircraft).call.status # counted from the last cleaning: 1240 hrs left + filter.update!(replacement_from_install: true) + assert_equal [ 0, Date.current ], [ filter.hours_to_replacement, filter.replacement_counted_from ] + assert_equal "RED", Airworthiness.new(@aircraft).call.status + filter.update!(hours_in_service: 0, replacement_hours: nil, replacement_months: 60, date_in_service: 61.months.ago.to_date) + assert_equal "RED", Airworthiness.new(@aircraft).call.status # 5 years since installed, though cleaned today + end + test "spare components are ignored" do create_component(@aircraft, status: "SPARE", replacement_critical: true, replacement_hours: 10, hours_since_overhaul: 50) assert_equal "GREEN", Airworthiness.new(@aircraft).call.status