diff --git a/README.md b/README.md index 2619f44..f39cb55 100644 --- a/README.md +++ b/README.md @@ -101,11 +101,13 @@ To back up or move a single aircraft with all its files, use **Access & Sharing | Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. Owners can create new component types inline. | | Squawks | Four priorities. "Ground Aircraft" grounds the aircraft. Inoperative items can be deferred under 91.213(d) after confirming each condition; resolving can record the fix as a logbook entry. Attachments, reopen. | | ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, per-aircraft "not applicable" determinations, and compliance history with method of compliance and the revision complied with. | +| New ADs | Weekly search of the Federal Register for newly published ADs mentioning the aircraft, engine or propeller models (or your own terms). Review each: track it as an AD or dismiss it. | | AD import | Import ADs from an FAA DRS export (`.xlsx` recommended: its AD numbers link to each AD's DRS page, which the import keeps; `.csv` works without links). ADs are matched by number, so nothing is duplicated. The preview suggests Track, Not applicable or Skip for each AD, and flags superseded or non-current ADs, model mismatches, appliance or STC-only ADs, and repetitive actions. | | Inspections | Shared inspection types with hour, month, and day recurrence, plus history. Each says what overdue means (grounded, no IFR, no transponder, advisory); an annual can also count as the 100-hour, and the 100-hour's 10-hour overrun is credited (91.409(b)). One click adds the standard Part 91 set. | -| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. | +| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Templates for pilot preventive maintenance (43.3(g), Part 43 Appendix A(c)). | | Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). | -| Major repairs and alterations | Form 337, STC, and ICA tracking. | +| Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. | +| Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. | | Status report | A printable maintenance status (91.417(a)(2)): total times, life-limited parts, time since overhaul, inspections, ADs with method and revision, major alterations, open discrepancies. Also on maintenance share links. | | Reminders | A Monday email to owners when something is overdue or coming due (needs SMTP; users can turn it off). | | Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). | diff --git a/app/controllers/ad_alerts_controller.rb b/app/controllers/ad_alerts_controller.rb new file mode 100644 index 0000000..b37a0ff --- /dev/null +++ b/app/controllers/ad_alerts_controller.rb @@ -0,0 +1,37 @@ +# Newly published ADs that may apply: check now, track or dismiss, and the +# search terms used. +class AdAlertsController < ApplicationController + include AircraftScoped + before_action :require_owner! + before_action :set_alert, only: %i[track dismiss] + rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: "Try again in a minute." } + + def check + found = AdWatch.new(@aircraft).check! + redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), + notice: found.any? ? "Found #{helpers.pluralize(found.size, 'newly published AD')} to review." : "No new ADs found for #{AdWatch.new(@aircraft).terms.to_sentence}." + rescue AdWatch::Error => e + redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: "Couldn't check for new ADs: #{e.message}." + end + + def track + ad = @alert.track! + log_event("ad", "AD tracked from the Federal Register: #{ad.name}") + redirect_to edit_aircraft_airworthiness_directive_path(@aircraft, ad), + notice: "#{ad.name} is now tracked. Set its applicability and recurrence from the AD's text, then record compliance or mark it not applicable." + end + + def dismiss + @alert.dismiss! + redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: "Dismissed." + end + + def terms + @aircraft.update!(ad_watch_terms: params[:ad_watch_terms].to_s.strip.first(500).presence) + redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: "Search terms saved." + end + + private + + def set_alert = @alert = @aircraft.ad_alerts.find(params[:id]) +end diff --git a/app/controllers/airworthiness_directives_controller.rb b/app/controllers/airworthiness_directives_controller.rb index 68024b7..3d6b418 100644 --- a/app/controllers/airworthiness_directives_controller.rb +++ b/app/controllers/airworthiness_directives_controller.rb @@ -9,6 +9,7 @@ class AirworthinessDirectivesController < ApplicationController @history = AdCompliance.for_aircraft(@aircraft).recent_first .includes(:component, :logbook_entry, airworthiness_directive: :document, inspection_record: :inspection_type) @attachable = AirworthinessDirective.where.not(id: @aircraft.applicable_ads.select(:id)).ordered if owner? + @alerts = @aircraft.ad_alerts.pending end def new diff --git a/app/controllers/inspection_types_controller.rb b/app/controllers/inspection_types_controller.rb index 3da9afe..47ff4f4 100644 --- a/app/controllers/inspection_types_controller.rb +++ b/app/controllers/inspection_types_controller.rb @@ -7,6 +7,11 @@ class InspectionTypesController < ApplicationController def new @inspection_type = InspectionType.new(required: true, recurring: true) @applies_to_airframe = true + if (@major_record = ica_record) + @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 + end end def create @@ -14,11 +19,17 @@ class InspectionTypesController < ApplicationController InspectionType.transaction do @inspection_type.save! apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) + ica_record&.update!(ica_inspection_type: @inspection_type) end log_event("inspection", "Inspection type added: #{@inspection_type.name}") - redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type added." + if (record = ica_record) + redirect_to aircraft_major_record_path(@aircraft, record), notice: "ICA inspection added. Record when it was last done to see when it's next due." + else + redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type added." + end rescue ActiveRecord::RecordInvalid @applies_to_airframe = applies_to_airframe? + @major_record = ica_record render :new, status: :unprocessable_entity end @@ -46,6 +57,11 @@ class InspectionTypesController < ApplicationController private + # Creating the inspection an STC's ICA calls for (from its major record). + def ica_record + @aircraft.major_records.find_by(id: params[:major_record_id]) if params[:major_record_id].present? + end + def set_type @inspection_type = @aircraft.applicable_inspection_types.find(params[:id]) end diff --git a/app/controllers/loading_setups_controller.rb b/app/controllers/loading_setups_controller.rb new file mode 100644 index 0000000..642816c --- /dev/null +++ b/app/controllers/loading_setups_controller.rb @@ -0,0 +1,22 @@ +# The aircraft's loading stations (arms) and CG envelope, from the POH, for +# the loading calculator. +class LoadingSetupsController < ApplicationController + include AircraftScoped + before_action :require_owner! + + def edit + @setup = @aircraft.loading_setup + end + + def update + permitted = params.fetch(:setup, {}).permit(:fuel_lb_per_gal, stations: %i[name arm max fuel], envelope: %i[weight cg]) + @setup = LoadingSetup.from_params(permitted.to_h) + if @setup.valid? + @aircraft.update!(loading_stations: @setup.stations_json, cg_envelope: @setup.envelope) + log_event("aircraft", "Loading stations and CG envelope updated") + redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Loading setup saved." + else + render :edit, status: :unprocessable_entity + end + end +end diff --git a/app/controllers/logbook_entries_controller.rb b/app/controllers/logbook_entries_controller.rb index 2b046da..2d4f28c 100644 --- a/app/controllers/logbook_entries_controller.rb +++ b/app/controllers/logbook_entries_controller.rb @@ -1,16 +1,28 @@ class LogbookEntriesController < ApplicationController include AircraftScoped before_action :require_owner!, except: %i[index show] - before_action :set_entry, only: %i[show edit update destroy] + before_action :set_entry, only: %i[show edit update destroy verify] def index @query = params[:q] @log_type = params[:log_type].presence scope = @aircraft.logbook_entries.search(@query).recent_first.includes(:document) scope = scope.where(log_type: @log_type) if @log_type + @unverified_only = params[:unverified] == "1" + scope = scope.unverified if @unverified_only + @unverified_count = @aircraft.logbook_entries.unverified.count @entries = scope.limit(500) end + # Someone has checked a transcribed entry against the scan. + def verify + @entry.update!(verified: true) + log_event("logbook", "Transcribed logbook entry verified: #{@entry.date}") + next_entry = @aircraft.logbook_entries.unverified.order(:date, :id).first + redirect_to next_entry ? aircraft_logbook_entry_path(@aircraft, next_entry) : aircraft_logbook_entries_path(@aircraft), + notice: next_entry ? "Verified. Here's the next one to check." : "Verified. All transcribed entries are checked." + end + def show; end def new @@ -51,7 +63,7 @@ class LogbookEntriesController < ApplicationController def entry_params p = params.require(:logbook_entry).permit(:log_type, :entry_type, :date, :text, :signoff_person, :signoff_location, :aircraft_hours_at_entry, :document_id, :page_number, - :signoff_certificate_type, :signoff_certificate_number, :inspection_result) + :signoff_certificate_type, :signoff_certificate_number, :inspection_result, :verified) p[:document_id] = scoped_id(@aircraft.documents, p[:document_id]) p end diff --git a/app/controllers/weight_balance_records_controller.rb b/app/controllers/weight_balance_records_controller.rb new file mode 100644 index 0000000..213c383 --- /dev/null +++ b/app/controllers/weight_balance_records_controller.rb @@ -0,0 +1,57 @@ +# Weight & balance history and the loading calculator (pilots use it; owners +# keep the records and the loading setup). +class WeightBalanceRecordsController < ApplicationController + include AircraftScoped + before_action :require_owner!, except: :index + before_action :set_record, only: %i[edit update destroy] + + def index + @records = @aircraft.weight_balance_records.recent_first.includes(:major_record, :document) + @current = @records.first + end + + def new + last = @aircraft.current_weight_balance + @record = @aircraft.weight_balance_records.new(date: Date.current, max_gross_weight: last&.max_gross_weight, + major_record_id: params[:major_record_id]) + end + + def create + @record = @aircraft.weight_balance_records.new(record_params) + if @record.save + log_event("aircraft", "Weight & balance recorded: #{@record.empty_weight} lb @ #{@record.empty_arm} in") + redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Weight & balance saved." + else + render :new, status: :unprocessable_entity + end + end + + def edit; end + + def update + if @record.update(record_params) + log_event("aircraft", "Weight & balance updated (#{@record.date})") + redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Weight & balance updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @record.destroy! + log_event("aircraft", "Weight & balance record deleted (#{@record.date})") + redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Record deleted." + end + + private + + def set_record = @record = @aircraft.weight_balance_records.find(params[:id]) + + def record_params + p = params.require(:weight_balance_record).permit(:date, :empty_weight, :empty_arm, :max_gross_weight, :reason, :notes, + :major_record_id, :document_id) + p[:major_record_id] = scoped_id(@aircraft.major_records, p[:major_record_id]) + p[:document_id] = scoped_id(@aircraft.documents, p[:document_id]) + p + end +end diff --git a/app/helpers/aircraft_helper.rb b/app/helpers/aircraft_helper.rb index b4a6ea9..36485e2 100644 --- a/app/helpers/aircraft_helper.rb +++ b/app/helpers/aircraft_helper.rb @@ -13,6 +13,7 @@ module AircraftHelper [ "ADs", aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances ad_imports] ], [ "Documents", aircraft_documents_path(aircraft), %w[documents document_collections] ], [ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ], + [ "W&B", aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ], [ "Notes", aircraft_notes_path(aircraft), %w[notes] ], [ "Activity", aircraft_events_path(aircraft), %w[events] ], ([ "Access & Sharing", aircraft_aircraft_roles_path(aircraft), %w[aircraft_roles share_tokens] ] if owner?) diff --git a/app/javascript/controllers/entry_template_controller.js b/app/javascript/controllers/entry_template_controller.js new file mode 100644 index 0000000..72d9991 --- /dev/null +++ b/app/javascript/controllers/entry_template_controller.js @@ -0,0 +1,17 @@ +import { Controller } from "@hotwired/stimulus" + +// Fills a new logbook entry from a preventive maintenance template: the +// wording, the entry type and "pilot" as the kind of certificate. +export default class extends Controller { + static targets = [ "template", "text", "entryType", "certificate" ] + + apply() { + const option = this.templateTarget.selectedOptions[0] + if (!option?.dataset.text) return + if (this.textTarget.value.trim() && !confirm("Replace the entry text with this template?")) return + this.textTarget.value = option.dataset.text + if (this.hasEntryTypeTarget) this.entryTypeTarget.value = "MAINTENANCE" + if (this.hasCertificateTarget) this.certificateTarget.value = "PILOT" + this.textTarget.focus() + } +} diff --git a/app/javascript/controllers/wb_calculator_controller.js b/app/javascript/controllers/wb_calculator_controller.js new file mode 100644 index 0000000..eb5caa2 --- /dev/null +++ b/app/javascript/controllers/wb_calculator_controller.js @@ -0,0 +1,99 @@ +import { Controller } from "@hotwired/stimulus" + +// Loading calculator: takeoff and landing weight and CG from the empty +// weight & moment plus each station's load, checked against max gross weight, +// station maximums and the CG envelope (drawn as a small chart). +export default class extends Controller { + static targets = [ "station", "burn", "takeoffWeight", "takeoffCg", "takeoffMoment", "landingWeight", "landingCg", "landingMoment", "messages", "chart" ] + static values = { emptyWeight: Number, emptyMoment: Number, maxGross: Number, fuelDensity: Number, envelope: Array } + + connect() { this.update() } + + update() { + const messages = [] + let weight = this.emptyWeightValue + let moment = this.emptyMomentValue + let fuelArmMoment = 0 + let fuelGallons = 0 + this.stationTargets.forEach((input) => { + const qty = parseFloat(input.value) || 0 + const arm = parseFloat(input.dataset.arm) + const fuel = input.dataset.fuel === "true" + const max = parseFloat(input.dataset.max) || 0 + const label = input.closest("label").querySelector(".label").firstChild.textContent.trim() + if (max && qty > max) messages.push([ "bad", `${label}: ${qty} is over its maximum of ${max} ${fuel ? "gal" : "lb"}.` ]) + const lbs = fuel ? qty * this.fuelDensityValue : qty + weight += lbs + moment += lbs * arm + if (fuel) { fuelArmMoment += qty * arm; fuelGallons += qty } + }) + + // Landing: burn fuel from the tanks at their average arm. + const burn = Math.min(this.hasBurnTarget ? parseFloat(this.burnTarget.value) || 0 : 0, fuelGallons) + const fuelArm = fuelGallons ? fuelArmMoment / fuelGallons : 0 + const landingWeight = weight - burn * this.fuelDensityValue + const landingMoment = moment - burn * this.fuelDensityValue * fuelArm + + const takeoff = { weight, moment, cg: moment / weight } + const landing = { weight: landingWeight, moment: landingMoment, cg: landingMoment / landingWeight } + this.show("takeoff", takeoff) + this.show("landing", landing) + + 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.` ]) + } + if (this.envelopeValue.length >= 3) { + for (const [ name, point ] of [ [ "Takeoff", takeoff ], [ "Landing", landing ] ]) { + if (!this.inside(point)) messages.push([ "bad", `${name} CG ${point.cg.toFixed(2)} in at ${point.weight.toFixed(0)} lb is outside the envelope.` ]) + } + } + if (!messages.length) messages.push([ "ok", "Within the limits entered here." ]) + this.messagesTarget.replaceChildren(...messages.map(([ kind, text ]) => { + const li = document.createElement("li") + li.className = kind === "ok" ? "text-emerald-700" : "text-red-700" + li.textContent = text + return li + })) + this.draw(takeoff, landing) + } + + show(prefix, p) { + this[`${prefix}WeightTarget`].textContent = `${p.weight.toFixed(1)} lb` + this[`${prefix}CgTarget`].textContent = `${p.cg.toFixed(2)} in` + this[`${prefix}MomentTarget`].textContent = Math.round(p.moment).toLocaleString() + } + + // Ray casting: is the (cg, weight) point inside the envelope polygon? + inside({ cg, weight }) { + const pts = this.envelopeValue + let inside = false + for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) { + const [ wi, ci ] = pts[i] + const [ wj, cj ] = pts[j] + if ((wi > weight) !== (wj > weight) && cg < ((cj - ci) * (weight - wi)) / (wj - wi) + ci) inside = !inside + } + return inside + } + + draw(takeoff, landing) { + const pts = this.envelopeValue + const svg = this.chartTarget + svg.replaceChildren() + if (pts.length < 3) return + const cgs = [ ...pts.map((p) => p[1]), takeoff.cg, landing.cg ] + const ws = [ ...pts.map((p) => p[0]), takeoff.weight, landing.weight ] + const [ cMin, cMax, wMin, wMax ] = [ Math.min(...cgs), Math.max(...cgs), Math.min(...ws), Math.max(...ws) ] + const x = (c) => 15 + ((c - cMin) / (cMax - cMin || 1)) * 190 + const y = (w) => 145 - ((w - wMin) / (wMax - wMin || 1)) * 130 + const ns = "http://www.w3.org/2000/svg" + const poly = document.createElementNS(ns, "polygon") + poly.setAttribute("points", pts.map(([ w, c ]) => `${x(c)},${y(w)}`).join(" ")) + poly.setAttribute("class", "fill-sky-100 stroke-sky-600") + svg.append(poly) + for (const [ p, cls ] of [ [ takeoff, "fill-slate-900" ], [ landing, "fill-slate-400" ] ]) { + const dot = document.createElementNS(ns, "circle") + dot.setAttribute("cx", x(p.cg)); dot.setAttribute("cy", y(p.weight)); dot.setAttribute("r", 4); dot.setAttribute("class", cls) + svg.append(dot) + } + } +} diff --git a/app/jobs/ad_watch_job.rb b/app/jobs/ad_watch_job.rb new file mode 100644 index 0000000..cadda3c --- /dev/null +++ b/app/jobs/ad_watch_job.rb @@ -0,0 +1,12 @@ +# Weekly: look for newly published ADs for every aircraft. +class AdWatchJob < ApplicationJob + queue_as :default + + def perform + Aircraft.find_each do |aircraft| + AdWatch.new(aircraft).check! + rescue AdWatch::Error => e + Rails.logger.warn("[ad watch] #{aircraft.tail_number}: #{e.message}") + end + end +end diff --git a/app/jobs/logbook_transcription_job.rb b/app/jobs/logbook_transcription_job.rb index 707f8a8..39eecbf 100644 --- a/app/jobs/logbook_transcription_job.rb +++ b/app/jobs/logbook_transcription_job.rb @@ -124,7 +124,8 @@ class LogbookTranscriptionJob < ApplicationJob signoff_certificate_type: LogbookEntry::CERTIFICATE_TYPES.key?(entry["signoff_certificate_type"]) ? entry["signoff_certificate_type"] : nil, signoff_certificate_number: entry["signoff_certificate_number"].to_s.strip.first(40).presence, aircraft_hours_at_entry: entry["aircraft_hours"].is_a?(Numeric) && entry["aircraft_hours"] >= 0 ? entry["aircraft_hours"] : nil, - document: @document, page_number: page_number + document: @document, page_number: page_number, + verified: false, transcription_confidence: (entry["confidence"] if %w[high medium low].include?(entry["confidence"])) ) @import.increment!(:entries_created) warn("The #{date} entry on page #{page_number} was hard to read. Please check it against the scan.") if entry["confidence"] == "low" diff --git a/app/mailers/reminder_mailer.rb b/app/mailers/reminder_mailer.rb index 50642e4..f0cde28 100644 --- a/app/mailers/reminder_mailer.rb +++ b/app/mailers/reminder_mailer.rb @@ -1,14 +1,15 @@ class ReminderMailer < ApplicationMailer - # [[aircraft, issues], …] for the aircraft the user owns that need attention. + # [[aircraft, issues, new AD alerts], …] for the aircraft the user owns + # that need attention. def self.items_for(user) Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered - .map { [ _1, _1.airworthiness.issues ] }.reject { _2.empty? } + .map { [ _1, _1.airworthiness.issues, _1.ad_alerts.pending.to_a ] }.reject { _2.empty? && _3.empty? } end def weekly(user) @user = user @items = self.class.items_for(user) - overdue = @items.sum { |_, issues| issues.count { _1.severity.in?(%w[RED LIMITED]) } } + overdue = @items.sum { |_, issues, _| issues.count { _1.severity.in?(%w[RED LIMITED]) } } subject = overdue.positive? ? "#{overdue} #{'item'.pluralize(overdue)} overdue" : "Maintenance coming due" mail subject: "#{subject}: #{@items.map { _1.first.tail_number }.to_sentence}", to: user.email_address end diff --git a/app/models/ad_alert.rb b/app/models/ad_alert.rb new file mode 100644 index 0000000..585b212 --- /dev/null +++ b/app/models/ad_alert.rb @@ -0,0 +1,36 @@ +# An AD published in the Federal Register that may apply to an aircraft, +# waiting for the owner to track it (as an AD to comply with) or dismiss it. +class AdAlert < ApplicationRecord + STATUSES = %w[new tracked dismissed].freeze + + belongs_to :aircraft + belongs_to :airworthiness_directive, optional: true + + validates :fr_document_number, presence: true, uniqueness: { scope: :aircraft_id } + validates :status, inclusion: { in: STATUSES } + + scope :pending, -> { where(status: "new").order(publication_date: :desc) } + + # Tracks it: the AD (shared across aircraft, matched by number) is linked + # to this aircraft, so it counts against airworthiness until complied with. + def track! + transaction do + ad = AirworthinessDirective.find_by(name: ad_number) if ad_number.present? + ad ||= AirworthinessDirective.create!( + name: ad_number.presence || fr_document_number, short_description: summary, effective_date: effective_on, + document_url: html_url, docket_number: amendment, required_action: abstract.to_s.truncate(2000) + ) + ad.aircraft << aircraft unless ad.aircraft.include?(aircraft) + update!(status: "tracked", airworthiness_directive: ad) + ad + end + end + + def dismiss! = update!(status: "dismissed") + + # "Requires …" from the abstract, else the title without its prefix. + def summary + requires = abstract.to_s[/This AD requires ([^.]+)\./, 1] + (requires ? "Requires #{requires}" : title.to_s.delete_prefix("Airworthiness Directives; ")).truncate(250) + end +end diff --git a/app/models/aircraft.rb b/app/models/aircraft.rb index edead76..060317c 100644 --- a/app/models/aircraft.rb +++ b/app/models/aircraft.rb @@ -25,6 +25,8 @@ class Aircraft < ApplicationRecord has_many :flight_logs, dependent: :destroy has_many :consumable_records, dependent: :destroy has_many :oil_analyses, dependent: :destroy + has_many :weight_balance_records, dependent: :destroy + has_many :ad_alerts, dependent: :destroy has_and_belongs_to_many :inspection_types has_and_belongs_to_many :airworthiness_directives @@ -52,6 +54,9 @@ class Aircraft < ApplicationRecord end def hobbs? = time_basis == "hobbs" + + def current_weight_balance = weight_balance_records.recent_first.first + def loading_setup = LoadingSetup.from_aircraft(self) def time_basis_label = TIME_BASES[time_basis] def airworthiness diff --git a/app/models/loading_setup.rb b/app/models/loading_setup.rb new file mode 100644 index 0000000..ec0c59c --- /dev/null +++ b/app/models/loading_setup.rb @@ -0,0 +1,49 @@ +# Loading stations (name, arm, maximum, fuel or not) and the CG envelope +# (weight/CG points in order around the boundary), as entered from the POH. +class LoadingSetup + include ActiveModel::Model + + Station = Data.define(:name, :arm, :max, :fuel) + + attr_accessor :stations, :envelope, :fuel_lb_per_gal + + def self.from_aircraft(aircraft) + data = aircraft.loading_stations.is_a?(Hash) ? aircraft.loading_stations : {} + new(stations: Array(data["stations"]).map { Station.new(name: _1["name"], arm: _1["arm"].to_d, max: _1["max"]&.to_d, fuel: _1["fuel"] == true) }, + envelope: Array(aircraft.cg_envelope).map { [ _1[0].to_d, _1[1].to_d ] }, + fuel_lb_per_gal: (data["fuel_lb_per_gal"] || 6).to_d) + end + + # From the edit form: blank rows are ignored. + def self.from_params(p) + rows = Array(p["stations"]&.values).reject { _1["name"].to_s.strip.empty? && _1["arm"].to_s.strip.empty? } + points = Array(p["envelope"]&.values).reject { _1["weight"].to_s.strip.empty? && _1["cg"].to_s.strip.empty? } + setup = new(fuel_lb_per_gal: p["fuel_lb_per_gal"].presence&.to_d || 6, stations: [], envelope: []) + setup.instance_variable_set(:@raw_stations, rows) + setup.instance_variable_set(:@raw_envelope, points) + setup.stations = rows.filter_map do |r| + next unless numeric?(r["arm"]) + Station.new(name: r["name"].to_s.strip.first(40), arm: r["arm"].to_d, max: numeric?(r["max"]) ? r["max"].to_d : nil, fuel: r["fuel"] == "1") + end + setup.envelope = points.filter_map { numeric?(_1["weight"]) && numeric?(_1["cg"]) ? [ _1["weight"].to_d, _1["cg"].to_d ] : nil } + setup + end + + def self.numeric?(v) = v.to_s.strip.match?(/\A-?\d+(\.\d+)?\z/) + + validate do + raw_s = @raw_stations || [] + raw_e = @raw_envelope || [] + errors.add(:base, "Every station needs a name and a numeric arm (inches)") if raw_s.size != stations.size || stations.any? { _1.name.blank? } + errors.add(:base, "Every envelope point needs a numeric weight and CG") if raw_e.size != envelope.size + errors.add(:base, "The CG envelope needs at least 3 points, or none") if envelope.size.between?(1, 2) + errors.add(:base, "Fuel weight per gallon must be between 4 and 9 lb") unless fuel_lb_per_gal.to_d.between?(4, 9) + end + + def stations_json + { "fuel_lb_per_gal" => fuel_lb_per_gal.to_f, + "stations" => stations.map { { "name" => _1.name, "arm" => _1.arm.to_f, "max" => _1.max&.to_f, "fuel" => _1.fuel } } } + end + + def configured? = stations.any? +end diff --git a/app/models/logbook_entry.rb b/app/models/logbook_entry.rb index 0a842f4..ab27f46 100644 --- a/app/models/logbook_entry.rb +++ b/app/models/logbook_entry.rb @@ -33,6 +33,7 @@ class LogbookEntry < ApplicationRecord normalizes :signoff_certificate_type, :inspection_result, :signoff_certificate_number, with: ->(v) { v.strip.presence } scope :recent_first, -> { order(date: :desc, created_at: :desc) } + scope :unverified, -> { where(verified: false) } def self.search(q) return all if q.blank? diff --git a/app/models/major_record.rb b/app/models/major_record.rb index 2702281..519208a 100644 --- a/app/models/major_record.rb +++ b/app/models/major_record.rb @@ -6,6 +6,9 @@ class MajorRecord < ApplicationRecord belongs_to :form_337_document, class_name: "Document", optional: true belongs_to :stc_document, class_name: "Document", optional: true belongs_to :logbook_entry, optional: true + # The recurring inspection this STC's Instructions for Continued + # Airworthiness call for (owners must follow ICAs: 91.403(c), 43.13(a)). + belongs_to :ica_inspection_type, class_name: "InspectionType", optional: true validates :title, :date_performed, presence: true validates :record_type, inclusion: { in: RECORD_TYPES.keys } diff --git a/app/models/preventive_maintenance.rb b/app/models/preventive_maintenance.rb new file mode 100644 index 0000000..7f5606c --- /dev/null +++ b/app/models/preventive_maintenance.rb @@ -0,0 +1,37 @@ +# Logbook wording for common preventive maintenance a pilot-owner may do +# (14 CFR 43.3(g)), keyed to Part 43 Appendix A paragraph (c). The item +# descriptions are paraphrased; the rule sets each item's limits. +module PreventiveMaintenance + Item = Data.define(:key, :paragraphs, :label, :work) + + ITEMS = [ + Item.new("oil_change", %w[(c)(6) (c)(23)], "Oil and filter change", "Drained engine oil and replaced the oil filter. Cut open and inspected the filter: no metal found. Refilled with __ qt of __. Ran engine and checked for leaks."), + Item.new("tire", %w[(c)(1)], "Tire removal, installation or repair", "Removed and replaced the __ tire and tube. Inflated to __ psi."), + Item.new("strut", %w[(c)(3)], "Servicing landing gear shock struts", "Serviced the __ shock strut with __."), + Item.new("bearings", %w[(c)(4)], "Servicing wheel bearings", "Cleaned, inspected and repacked the __ wheel bearings with __ grease."), + Item.new("safety_wire", %w[(c)(5)], "Replacing safety wire or cotter keys", "Replaced defective safety wire / cotter key at __."), + Item.new("lubrication", %w[(c)(6)], "Lubrication", "Lubricated __ per the maintenance manual."), + Item.new("hydraulic", %w[(c)(8)], "Replenishing hydraulic fluid", "Replenished the hydraulic reservoir with __."), + Item.new("upholstery", %w[(c)(11)], "Repairing upholstery", "Repaired the upholstery of __."), + Item.new("fairings", %w[(c)(12)], "Small repairs to fairings or cowlings", "Made a small repair to the __ (non-structural, contour unchanged)."), + Item.new("seat_belts", %w[(c)(14)], "Replacing safety belts", "Replaced the __ safety belt with P/N __."), + Item.new("landing_light_wiring", %w[(c)(16)], "Repairing landing light circuits", "Troubleshot and repaired a broken circuit in the landing light wiring."), + Item.new("lights", %w[(c)(17)], "Replacing light bulbs, reflectors or lenses", "Replaced the __ position/landing light bulb with P/N __. Checked operation."), + Item.new("cowling", %w[(c)(19)], "Replacing a cowling", "Removed and reinstalled the __ cowling."), + Item.new("spark_plugs", %w[(c)(20)], "Cleaning or replacing spark plugs", "Removed, cleaned, gapped and rotated the spark plugs. Reinstalled and torqued to __."), + Item.new("hoses", %w[(c)(21)], "Replacing hose connections (not hydraulic)", "Replaced the __ hose with P/N __."), + Item.new("fuel_lines", %w[(c)(22)], "Replacing prefabricated fuel lines", "Replaced the prefabricated fuel line __ with P/N __."), + Item.new("filters", %w[(c)(23)], "Cleaning or replacing fuel/oil strainers or filters", "Cleaned / replaced the __ strainer / filter element."), + Item.new("battery", %w[(c)(24)], "Replacing or servicing the battery", "Replaced the battery with P/N __ / serviced the battery."), + Item.new("fasteners", %w[(c)(26)], "Replacing non-structural fasteners", "Replaced non-structural standard fasteners at __."), + Item.new("chip_detector", %w[(c)(29)], "Checking magnetic chip detectors", "Removed, checked and reinstalled the magnetic chip detector: no particles found."), + Item.new("nav_database", %w[(c)(31)], "Updating the navigation database", "Updated the __ navigation database to cycle __."), + Item.new("nav_com", %w[(c)(32)], "Swapping a tray-mounted nav/com unit", "Removed and reinstalled the tray-mounted __ unit. Checked operation.") + ].freeze + + module_function + + def text_for(item) + "#{item.work} Preventive maintenance per 14 CFR 43.3(g), Part 43 Appendix A paragraph #{item.paragraphs.to_sentence}." + end +end diff --git a/app/models/system_info.rb b/app/models/system_info.rb index 776bec3..262acd0 100644 --- a/app/models/system_info.rb +++ b/app/models/system_info.rb @@ -19,11 +19,12 @@ class SystemInfo "unknown" end - def repository_url = REPOSITORY_URL.chomp("/") + # Only an http(s) address is linked (it comes from the environment). + def repository_url = REPOSITORY_URL.match?(%r{\Ahttps?://[^\s"'<>]+\z}) ? REPOSITORY_URL.chomp("/") : nil # The running commit on the repository host, when the revision is known. def revision_url - "#{repository_url}/commit/#{revision}" if revision.match?(/\A\h{7,40}\z/) + "#{repository_url}/commit/#{revision}" if repository_url && revision.match?(/\A\h{7,40}\z/) end def built_at diff --git a/app/models/weight_balance_record.rb b/app/models/weight_balance_record.rb new file mode 100644 index 0000000..9185ad3 --- /dev/null +++ b/app/models/weight_balance_record.rb @@ -0,0 +1,19 @@ +# One weight & balance report: the aircraft's empty weight and CG as of a +# date, usually after weighing or an equipment change (each alteration that +# changes them needs a new one; its 337 can be linked). +class WeightBalanceRecord < ApplicationRecord + belongs_to :aircraft + belongs_to :major_record, optional: true + belongs_to :document, optional: true + + validates :date, presence: true + validates :empty_weight, numericality: { greater_than: 0 } + validates :empty_arm, numericality: true + validates :max_gross_weight, numericality: { greater_than: 0 }, allow_nil: true + validate { errors.add(:max_gross_weight, "must be more than the empty weight") if max_gross_weight && empty_weight && max_gross_weight <= empty_weight } + + scope :recent_first, -> { order(date: :desc, created_at: :desc) } + + def empty_moment = empty_weight * empty_arm + def useful_load = max_gross_weight && max_gross_weight - empty_weight +end diff --git a/app/services/ad_watch.rb b/app/services/ad_watch.rb new file mode 100644 index 0000000..ce9643d --- /dev/null +++ b/app/services/ad_watch.rb @@ -0,0 +1,73 @@ +require "net/http" + +# Looks for newly published ADs that may apply to an aircraft. Every AD is +# published in the Federal Register, whose API is public; this searches its +# full text for each of the aircraft's watch terms (by default the aircraft, +# engine and propeller models). Matches are only possibly applicable: the +# owner reviews them on the ADs tab. +class AdWatch + API = "https://www.federalregister.gov/api/v1/documents.json".freeze + FIELDS = %w[document_number title publication_date effective_on html_url abstract docket_ids].freeze + FIRST_LOOKBACK = 2.years + + class Error < StandardError; end + + def initialize(aircraft) + @aircraft = aircraft + end + + # Model names to search for: the owner's list, or the aircraft, engine and + # propeller models. + def self.default_terms(aircraft) + models = [ aircraft.model ] + aircraft.components.in_use.includes(:component_type) + .select { _1.component_type&.name.to_s.match?(/engine|propell?er|\bprop\b/i) }.map(&:model) + models.compact_blank.map { _1.strip }.uniq + end + + def terms + custom = @aircraft.ad_watch_terms.to_s.split(/[,;\n]/).map(&:strip).compact_blank + custom.any? ? custom : self.class.default_terms(@aircraft) + end + + # Returns the new AdAlerts. + def check! + since = (@aircraft.ad_watch_checked_at || FIRST_LOOKBACK.ago).to_date - 7 # overlap; duplicates are skipped + known = AirworthinessDirective.pluck(:name).to_set + created = terms.flat_map { |term| search(term, since).filter_map { record(_1, term, known) } } + @aircraft.update_column(:ad_watch_checked_at, Time.current) + created + end + + private + + def record(doc, term, known) + dockets = Array(doc["docket_ids"]) + ad_number = dockets.find { _1.start_with?("AD ") }&.delete_prefix("AD ") + return if ad_number && known.include?(ad_number) && @aircraft.applicable_ads.exists?(name: ad_number) + return if @aircraft.ad_alerts.exists?(fr_document_number: doc["document_number"]) + @aircraft.ad_alerts.create!( + fr_document_number: doc["document_number"], ad_number: ad_number, + amendment: dockets.find { _1.start_with?("Amendment ") }&.delete_prefix("Amendment "), + title: doc["title"].to_s.truncate(250), abstract: doc["abstract"], html_url: doc["html_url"], + publication_date: doc["publication_date"], effective_on: doc["effective_on"], matched_term: term + ) + end + + def search(term, since) + query = [ + [ "per_page", "50" ], [ "order", "newest" ], + [ "conditions[agencies][]", "federal-aviation-administration" ], [ "conditions[type][]", "RULE" ], + [ "conditions[term]", %("airworthiness directives" "#{term.delete('"')}") ], + [ "conditions[publication_date][gte]", since.iso8601 ] + ] + FIELDS.map { [ "fields[]", _1 ] } + uri = URI(API) + uri.query = URI.encode_www_form(query) + response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) do |http| + http.get(uri.request_uri, "Accept" => "application/json", "User-Agent" => "SimpleAircraftManager") + end + raise Error, "the Federal Register returned #{response.code}" unless response.is_a?(Net::HTTPSuccess) + Array(JSON.parse(response.body)["results"]).select { _1["title"].to_s.start_with?("Airworthiness Directives") } + rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError, JSON::ParserError => e + raise Error, "couldn't reach the Federal Register (#{e.class.name.demodulize})" + end +end diff --git a/app/services/aircraft_archive.rb b/app/services/aircraft_archive.rb index e748663..b8c0bc8 100644 --- a/app/services/aircraft_archive.rb +++ b/app/services/aircraft_archive.rb @@ -16,9 +16,10 @@ module AircraftArchive TOP_LEVEL_KEYS = %w[ schema_version exported_at source_instance aircraft component_types components document_collections documents document_images logbook_entries squawks inspection_types inspection_records ads ad_compliances - consumable_records major_records notes oil_analysis_reports flight_logs features + consumable_records major_records notes oil_analysis_reports flight_logs features weight_balance_records ].freeze - OPTIONAL_KEYS = %w[features].freeze # and flight_logs before schema v2 + # Not in archives from the original app (nor flight_logs before schema v2). + OPTIONAL_KEYS = %w[features weight_balance_records].freeze MANIFEST_MAX_BYTES = 50.megabytes FILE_MAX_BYTES = 1.gigabyte # the most Admin → Settings allows for uploads diff --git a/app/services/aircraft_archive/exporter.rb b/app/services/aircraft_archive/exporter.rb index 0b40823..f555877 100644 --- a/app/services/aircraft_archive/exporter.rb +++ b/app/services/aircraft_archive/exporter.rb @@ -81,7 +81,12 @@ module AircraftArchive date_performed: r.date_performed&.iso8601, performed_by: r.performed_by, component_id: id(r.component_id), form_337_document_id: id(r.form_337_document_id), stc_number: r.stc_number, stc_holder: r.stc_holder, stc_document_id: id(r.stc_document_id), logbook_entry_id: id(r.logbook_entry_id), aircraft_hours: dec(r.aircraft_hours), - notes: r.notes, has_ica: r.has_ica, ica_notes: r.ica_notes } + notes: r.notes, has_ica: r.has_ica, ica_notes: r.ica_notes, ica_inspection_type_id: id(r.ica_inspection_type_id) } + end, + weight_balance_records: a.weight_balance_records.map do |w| + { id: id(w), date: w.date&.iso8601, empty_weight: dec(w.empty_weight), empty_arm: dec(w.empty_arm), + max_gross_weight: dec(w.max_gross_weight), reason: w.reason, notes: w.notes, + major_record_id: id(w.major_record_id), document_id: id(w.document_id) } end, notes: a.notes.includes(:user).map do |n| { id: id(n), aircraft_id: id(a), text: n.text, public: n.public, added_by_display: n.user&.display_name, @@ -120,7 +125,8 @@ module AircraftArchive def aircraft_hash(a) { id: id(a), tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number, - description: a.description, purchased: a.purchased&.iso8601, status: a.status, time_basis: a.time_basis, tach_time: dec(a.tach_time), + description: a.description, purchased: a.purchased&.iso8601, status: a.status, time_basis: a.time_basis, + loading_stations: a.loading_stations, cg_envelope: a.cg_envelope, ad_watch_terms: a.ad_watch_terms, tach_time: dec(a.tach_time), tach_time_offset: dec(a.tach_time_offset), hobbs_time: dec(a.hobbs_time), hobbs_time_offset: dec(a.hobbs_time_offset), picture: file(a.picture, "aircraft_pictures"), icao_type: a.icao_type } end @@ -139,7 +145,8 @@ module AircraftArchive { id: id(e), aircraft_id: id(e.aircraft_id), log_type: e.log_type, date: e.date&.iso8601, text: e.text, signoff_person: e.signoff_person, signoff_location: e.signoff_location, signoff_certificate_type: e.signoff_certificate_type, signoff_certificate_number: e.signoff_certificate_number, - inspection_result: e.inspection_result, log_image_id: id(e.document_id), + inspection_result: e.inspection_result, verified: e.verified, transcription_confidence: e.transcription_confidence, + log_image_id: id(e.document_id), aircraft_hours_at_entry: dec(e.aircraft_hours_at_entry), component_hours: {}, entry_type: e.entry_type, page_number: e.page_number, components: [], related_documents: [] } end diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index 9365c10..8ed74f1 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -140,6 +140,8 @@ module AircraftArchive make: a["make"].to_s, model: a["model"].to_s, serial_number: a["serial_number"].to_s, description: a["description"].to_s, purchased: date(a["purchased"]), status: Aircraft::STATUSES.key?(a["status"]) ? a["status"] : "AVAILABLE", time_basis: Aircraft::TIME_BASES.key?(a["time_basis"]) ? a["time_basis"] : "tach", + loading_stations: a["loading_stations"].is_a?(Hash) ? a["loading_stations"] : nil, + cg_envelope: a["cg_envelope"].is_a?(Array) ? a["cg_envelope"] : nil, ad_watch_terms: a["ad_watch_terms"].to_s.first(500).presence, tach_time: num(a["tach_time"] || a["flight_time"]) || 0, tach_time_offset: num(a["tach_time_offset"]) || 0, hobbs_time: num(a["hobbs_time"]) || 0, hobbs_time_offset: num(a["hobbs_time_offset"]) || 0, icao_type: a["icao_type"].to_s.upcase.presence&.then { _1.match?(/\A[A-Z0-9]{1,4}\z/) ? _1 : nil } @@ -227,6 +229,8 @@ module AircraftArchive signoff_certificate_type: LogbookEntry::CERTIFICATE_TYPES.key?(data["signoff_certificate_type"]) ? data["signoff_certificate_type"] : nil, signoff_certificate_number: data["signoff_certificate_number"].to_s.presence, inspection_result: LogbookEntry::INSPECTION_RESULTS.key?(data["inspection_result"]) ? data["inspection_result"] : nil, + verified: data["verified"] != false, + transcription_confidence: %w[high medium low].include?(data["transcription_confidence"]) ? data["transcription_confidence"] : nil, aircraft_hours_at_entry: num(data["aircraft_hours_at_entry"]), page_number: data["page_number"], document_id: @map[:document][data["log_image_id"].to_s] ) @@ -359,11 +363,26 @@ module AircraftArchive form_337_document_id: @map[:document][data["form_337_document_id"].to_s], stc_number: data["stc_number"].to_s, stc_holder: data["stc_holder"].to_s, stc_document_id: @map[:document][data["stc_document_id"].to_s], logbook_entry_id: @map[:logbook][data["logbook_entry_id"].to_s], aircraft_hours: num(data["aircraft_hours"]), - notes: data["notes"].to_s, has_ica: data["has_ica"] == true, ica_notes: data["ica_notes"] + notes: data["notes"].to_s, has_ica: data["has_ica"] == true, ica_notes: data["ica_notes"], + ica_inspection_type_id: @map[:inspection_type][data["ica_inspection_type_id"].to_s] ) r.save!(validate: false) + (@map[:major_record] ||= {})[data["id"].to_s] = r.id tick("major_records") end + import_weight_balance + end + + def import_weight_balance + m("weight_balance_records").each do |data| + w = @aircraft.weight_balance_records.new( + date: date(data["date"]) || Date.new(1900, 1, 1), empty_weight: num(data["empty_weight"]) || 0, empty_arm: num(data["empty_arm"]) || 0, + max_gross_weight: num(data["max_gross_weight"]), reason: data["reason"].to_s.presence, notes: data["notes"].to_s.presence, + major_record_id: (@map[:major_record] || {})[data["major_record_id"].to_s], document_id: @map[:document][data["document_id"].to_s] + ) + w.save!(validate: false) + tick("weight_balance_records") + end end def import_notes diff --git a/app/views/admin/about/show.html.erb b/app/views/admin/about/show.html.erb index 9311432..e1bf5bd 100644 --- a/app/views/admin/about/show.html.erb +++ b/app/views/admin/about/show.html.erb @@ -11,7 +11,7 @@
<%= info.revision_url ? link_to(info.revision, info.revision_url, class: "link", target: "_blank", rel: "noopener", title: "This commit on GitHub") : info.revision %>
-<%= link_to "Source code", info.repository_url, class: "link", target: "_blank", rel: "noopener" %>
+ <% if info.repository_url %><%= link_to "Source code", info.repository_url, class: "link", target: "_blank", rel: "noopener" %>
<% end %>Searched weekly in the Federal Register for <%= AdWatch.new(@aircraft).terms.to_sentence.presence || "the aircraft, engine and propeller models" %><%= " · last checked #{time_ago_in_words(@aircraft.ad_watch_checked_at)} ago" if @aircraft.ad_watch_checked_at %>.
+<%= alert.abstract.to_s.truncate(400) %>
+ <%= link_to "Read it in the Federal Register", alert.html_url, class: "link text-xs", target: "_blank", rel: "noopener" %> +Comma-separated model names. Left blank, the aircraft, engine and propeller models are used. Matches are only possibly applicable: check each AD's applicability (and serial number ranges) before tracking it.
+ <% end %> + <% end %> +For the Instructions for Continued Airworthiness of <%= @major_record.title %><%= " (STC #{@major_record.stc_number})" if @major_record.stc_number.present? %>. Set the interval the ICA gives.<%= " ICA notes: #{@major_record.ica_notes}" if @major_record.ica_notes.present? %>
+ <% end %> <%= f.field :name, required: true, placeholder: "Annual Inspection" %> <%= f.field :effect, as: :select, label: "When overdue", collection: InspectionType::EFFECTS.invert, hint: "An overdue pitot-static check (91.411) only rules out IFR, and an overdue transponder check (91.413) only rules out using the transponder. Neither grounds the aircraft." %> diff --git a/app/views/loading_setups/edit.html.erb b/app/views/loading_setups/edit.html.erb new file mode 100644 index 0000000..46d92e0 --- /dev/null +++ b/app/views/loading_setups/edit.html.erb @@ -0,0 +1,43 @@ +<% content_for :title, "#{@aircraft.tail_number} Loading setup" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<% stations = @setup.stations + Array.new([ 8 - @setup.stations.size, 2 ].max) { nil } %> +<% points = @setup.envelope + Array.new([ 10 - @setup.envelope.size, 2 ].max) { nil } %> +<%= form_with url: aircraft_loading_setup_path(@aircraft), method: :patch, class: "card card-body max-w-3xl space-y-5" do %> +From the POH's weight and balance section. Arms are inches aft of the datum.
+6 for avgas, 6.7 for Jet-A.
+For a pilot doing preventive maintenance on an aircraft they own or operate (14 CFR 43.3(g)). Fill in the blanks (__) and add your name and pilot certificate number. The item list is paraphrased from Part 43 Appendix A(c); the rule sets each item's limits.
+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).
Check the new entries against the scans: handwriting isn't always read perfectly.
+The new entries are marked unverified until someone checks them against the scans, since handwriting isn't always read perfectly. + <%= link_to "Check them now", aircraft_logbook_entries_path(@aircraft, unverified: 1), class: "link" %>
<% end %> <% else %>The import stopped: <%= @import.error %>
diff --git a/app/views/maintenance_reports/show.html.erb b/app/views/maintenance_reports/show.html.erb index 23f75d6..2652dcd 100644 --- a/app/views/maintenance_reports/show.html.erb +++ b/app/views/maintenance_reports/show.html.erb @@ -136,6 +136,13 @@ <% else %>None recorded.
<% end %> +Empty weight <%= number_with_precision(wb.empty_weight, precision: 1, delimiter: ",") %> lb, CG <%= number_with_precision(wb.empty_arm, precision: 2) %> in<%= ", useful load #{number_with_precision(wb.useful_load, precision: 1, delimiter: ',')} lb" if wb.useful_load %>, as of <%= wb.date %><%= " (#{wb.reason})" if wb.reason.present? %>.
+ <% else %>None recorded.
<% end %> +Here's what needs attention on your aircraft.
-<% @items.each do |aircraft, issues| %> +<% @items.each do |aircraft, issues, alerts| %><%= alerts.size %> newly published <%= "AD".pluralize(alerts.size) %> may apply: + <%= alerts.map { _1.ad_number || _1.fr_document_number }.to_sentence %>. <%= link_to "Review them", aircraft_airworthiness_directives_url(aircraft, anchor: "new-ads") %>.
+ <% end %> <% end %>Based on the records in Simple Aircraft Manager. Turn these emails off on your <%= link_to "profile", edit_profile_url %>. diff --git a/app/views/reminder_mailer/weekly.text.erb b/app/views/reminder_mailer/weekly.text.erb index a62af5c..e23a2e7 100644 --- a/app/views/reminder_mailer/weekly.text.erb +++ b/app/views/reminder_mailer/weekly.text.erb @@ -1,10 +1,13 @@ Here's what needs attention on your aircraft. -<% @items.each do |aircraft, issues| %> +<% @items.each do |aircraft, issues, alerts| %> <%= aircraft.tail_number %> (<%= aircraft.airworthiness.label %>): <%= aircraft_url(aircraft) %> <% issues.each do |issue| %> - <%= { "RED" => "Overdue", "LIMITED" => "Overdue", "ORANGE" => "Due soon", "INFO" => "Deferred" }[issue.severity] %>: <%= issue.title %>. <%= issue.description %> <% end %> +<% if alerts.any? %> +- New ADs that may apply: <%= alerts.map { _1.ad_number || _1.fr_document_number }.to_sentence %>. Review: <%= aircraft_airworthiness_directives_url(aircraft, anchor: "new-ads") %> +<% end %> <% end %> Based on the records in Simple Aircraft Manager. Turn these emails off on your profile: <%= edit_profile_url %> diff --git a/app/views/weight_balance_records/_form.html.erb b/app/views/weight_balance_records/_form.html.erb new file mode 100644 index 0000000..b178498 --- /dev/null +++ b/app/views/weight_balance_records/_form.html.erb @@ -0,0 +1,18 @@ +<%= form_with model: [aircraft, record], url: record.new_record? ? aircraft_weight_balance_records_path(aircraft) : aircraft_weight_balance_record_path(aircraft, record), + class: "card card-body space-y-4 max-w-2xl" do |f| %> + <%= f.errors_summary %> +
The figures from the weight & balance report: after weighing, or after an alteration or equipment change that changes the empty weight or CG.
+| Weight | CG | Moment | |
|---|---|---|---|
| Takeoff | — | — | — |
| Landing | — | — | — |
A planning aid from the figures entered here. Check against the POH and the aircraft's current W&B report.
+| Date | Empty weight | CG | Useful load | Reason | |
|---|---|---|---|---|---|
| <%= r.date %> | +<%= number_with_precision(r.empty_weight, precision: 1, delimiter: ",") %> lb | +<%= number_with_precision(r.empty_arm, precision: 2) %> in | +<%= r.useful_load ? "#{number_with_precision(r.useful_load, precision: 1, delimiter: ',')} lb" : "—" %> | +<%= r.reason %>
+ <% if r.major_record %> <%= link_to r.major_record.title, aircraft_major_record_path(@aircraft, r.major_record), class: "link" %> <% end %>
+ <% if r.document %><%= link_to "📄 #{r.document.name}", aircraft_document_path(@aircraft, r.document), class: "link" %> <% end %> |
+ <% if owner? %><%= link_to "Edit", edit_aircraft_weight_balance_record_path(@aircraft, r), class: "btn-secondary btn-sm" %><% end %> | +