From 6cab81332e589d1b1b2c5dddc523b3ecef1aa769 Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Sat, 7 Nov 2026 10:49:29 -0500 Subject: [PATCH] Unverified transcriptions, PM templates, ICA inspections, W&B, AD watch - Entries transcribed by Claude are unverified (with Claude's confidence) until an owner checks them against the scan: badge, filter, "mark verified" stepping through the rest - Preventive maintenance templates on new logbook entries, keyed to Part 43 Appendix A(c), setting the entry type and pilot certificate (43.3(g)) - An STC's ICA can become a tracked recurring inspection, linked from its major record - Weight & balance: history of empty weight/CG (linked to the 337 that changed them), loading stations and CG envelope from the POH, and a live calculator for takeoff and landing weight/CG; shown on the status report - New ADs: weekly Federal Register search per aircraft (aircraft, engine and propeller models, or custom terms); track or dismiss each; included in the weekly reminder - Archives carry the new records; brakeman: explicit params, reviewed About-page links Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- app/controllers/ad_alerts_controller.rb | 37 ++++ .../airworthiness_directives_controller.rb | 1 + .../inspection_types_controller.rb | 18 +- app/controllers/loading_setups_controller.rb | 22 +++ app/controllers/logbook_entries_controller.rb | 16 +- .../weight_balance_records_controller.rb | 57 ++++++ app/helpers/aircraft_helper.rb | 1 + .../controllers/entry_template_controller.js | 17 ++ .../controllers/wb_calculator_controller.js | 99 ++++++++++ app/jobs/ad_watch_job.rb | 12 ++ app/jobs/logbook_transcription_job.rb | 3 +- app/mailers/reminder_mailer.rb | 7 +- app/models/ad_alert.rb | 36 ++++ app/models/aircraft.rb | 5 + app/models/loading_setup.rb | 49 +++++ app/models/logbook_entry.rb | 1 + app/models/major_record.rb | 3 + app/models/preventive_maintenance.rb | 37 ++++ app/models/system_info.rb | 5 +- app/models/weight_balance_record.rb | 19 ++ app/services/ad_watch.rb | 73 +++++++ app/services/aircraft_archive.rb | 5 +- app/services/aircraft_archive/exporter.rb | 13 +- app/services/aircraft_archive/importer.rb | 21 +- app/views/admin/about/show.html.erb | 2 +- .../airworthiness_directives/index.html.erb | 42 ++++ app/views/inspection_types/_form.html.erb | 4 + app/views/loading_setups/edit.html.erb | 43 ++++ app/views/logbook_entries/_form.html.erb | 23 ++- app/views/logbook_entries/index.html.erb | 6 +- app/views/logbook_entries/show.html.erb | 6 + app/views/logbook_imports/show.html.erb | 3 +- app/views/maintenance_reports/show.html.erb | 7 + app/views/major_records/show.html.erb | 19 +- app/views/reminder_mailer/weekly.html.erb | 6 +- app/views/reminder_mailer/weekly.text.erb | 5 +- .../weight_balance_records/_form.html.erb | 18 ++ .../weight_balance_records/edit.html.erb | 3 + .../weight_balance_records/index.html.erb | 94 +++++++++ app/views/weight_balance_records/new.html.erb | 3 + config/brakeman.ignore | 73 ++++++- config/recurring.yml | 3 + config/routes.rb | 16 +- .../20261107220000_add_group_four_records.rb | 49 +++++ db/schema.rb | 53 ++++- test/integration/group_four_test.rb | 187 ++++++++++++++++++ test/integration/logbook_import_flow_test.rb | 2 + test/integration/phone_layout_test.rb | 2 +- 49 files changed, 1197 insertions(+), 35 deletions(-) create mode 100644 app/controllers/ad_alerts_controller.rb create mode 100644 app/controllers/loading_setups_controller.rb create mode 100644 app/controllers/weight_balance_records_controller.rb create mode 100644 app/javascript/controllers/entry_template_controller.js create mode 100644 app/javascript/controllers/wb_calculator_controller.js create mode 100644 app/jobs/ad_watch_job.rb create mode 100644 app/models/ad_alert.rb create mode 100644 app/models/loading_setup.rb create mode 100644 app/models/preventive_maintenance.rb create mode 100644 app/models/weight_balance_record.rb create mode 100644 app/services/ad_watch.rb create mode 100644 app/views/loading_setups/edit.html.erb create mode 100644 app/views/weight_balance_records/_form.html.erb create mode 100644 app/views/weight_balance_records/edit.html.erb create mode 100644 app/views/weight_balance_records/index.html.erb create mode 100644 app/views/weight_balance_records/new.html.erb create mode 100644 db/migrate/20261107220000_add_group_four_records.rb create mode 100644 test/integration/group_four_test.rb 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 %>
Built
<%= info.built_at ? l(info.built_at.in_time_zone, format: :short) : "—" %>
diff --git a/app/views/airworthiness_directives/index.html.erb b/app/views/airworthiness_directives/index.html.erb index c3023a1..e59f40a 100644 --- a/app/views/airworthiness_directives/index.html.erb +++ b/app/views/airworthiness_directives/index.html.erb @@ -51,6 +51,48 @@ <% end %> +
+
+
+

Newly published ADs that may apply

+

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 %>.

+
+ <% if owner? %><%= button_to "Check now", check_aircraft_ad_alerts_path(@aircraft), class: "btn-secondary btn-sm", data: { turbo_submits_with: "Checking…" } %><% end %> +
+ <% if @alerts.any? %> +
    + <% @alerts.each do |alert| %> +
  • +
    +
    <%= alert.ad_number ? "AD #{alert.ad_number}" : alert.fr_document_number %> · <%= alert.title.to_s.delete_prefix("Airworthiness Directives; ") %>
    +
    <%= [ (alert.effective_on && "Effective #{alert.effective_on}"), "published #{alert.publication_date}", "matched “#{alert.matched_term}”" ].compact.join(" · ") %>
    +

    <%= 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" %> +
    + <% if owner? %> +
    + <%= button_to "Track", track_aircraft_ad_alert_path(@aircraft, alert), class: "btn-primary btn-sm", title: "Add it to this aircraft's ADs" %> + <%= button_to "Dismiss", dismiss_aircraft_ad_alert_path(@aircraft, alert), class: "btn-secondary btn-sm", title: "Doesn't apply" %> +
    + <% end %> +
  • + <% end %> +
+ <% else %> + <%= empty_state "Nothing new to review." %> + <% end %> + <% if owner? %> + <%= form_with url: terms_aircraft_ad_alerts_path(@aircraft), method: :patch, class: "flex flex-wrap items-end gap-2 border-t border-slate-100 px-4 py-3" do %> +
+ <%= label_tag :ad_watch_terms, "Search terms", class: "label" %> + <%= text_field_tag :ad_watch_terms, @aircraft.ad_watch_terms, class: "input", placeholder: AdWatch.default_terms(@aircraft).join(", ").presence || "e.g. 172N, O-320, 1C160" %> +
+ <%= submit_tag "Save", class: "btn-secondary" %> +

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 %> +
+

Compliance History

<% if @history.any? %> diff --git a/app/views/inspection_types/_form.html.erb b/app/views/inspection_types/_form.html.erb index 31afeb8..d4f092a 100644 --- a/app/views/inspection_types/_form.html.erb +++ b/app/views/inspection_types/_form.html.erb @@ -1,5 +1,9 @@ <%= form_with model: inspection_type, url: inspection_type.new_record? ? aircraft_inspection_types_path(aircraft) : aircraft_inspection_type_path(aircraft, inspection_type), class: "card card-body space-y-4 max-w-2xl" do |f| %> <%= f.errors_summary %> + <% if @major_record %> + <%= hidden_field_tag :major_record_id, @major_record.id %> +

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 %> +
+

Loading setup

+

From the POH's weight and balance section. Arms are inches aft of the datum.

+
+ <% if @setup.errors.any? %> + + <% end %> +
+ Stations +
NameArm (in)MaxFuel (gal)
+ <% stations.each_with_index do |st, i| %> +
+ <%= text_field_tag "setup[stations][#{i}][name]", st&.name, class: "input", placeholder: ("Front seats" if i.zero?), "aria-label": "Station #{i + 1} name" %> + <%= text_field_tag "setup[stations][#{i}][arm]", st&.arm&.to_s&.sub(/\.0\z/, ""), class: "input", inputmode: "decimal", "aria-label": "Station #{i + 1} arm" %> + <%= text_field_tag "setup[stations][#{i}][max]", st&.max&.to_s&.sub(/\.0\z/, ""), class: "input", inputmode: "decimal", "aria-label": "Station #{i + 1} maximum" %> + <%= check_box_tag "setup[stations][#{i}][fuel]", "1", st&.fuel, class: "mx-auto h-4 w-4", "aria-label": "Station #{i + 1} is fuel" %> +
+ <% end %> +

Tick "Fuel" for fuel tanks: their quantity is entered in gallons and the max is the usable capacity. Other maximums are in pounds.

+
+
+ <%= label_tag "setup[fuel_lb_per_gal]", "Fuel weight (lb per gallon)", class: "label" %> + <%= text_field_tag "setup[fuel_lb_per_gal]", @setup.fuel_lb_per_gal.to_s.sub(/\.0\z/, ""), class: "input", inputmode: "decimal" %> +

6 for avgas, 6.7 for Jet-A.

+
+
+ CG envelope +

The corners of the normal-category envelope, in order around it (e.g. forward limit at low weight, forward limit at gross, aft limit at gross, aft limit at low weight).

+
Weight (lb)CG (in)
+ <% points.each_with_index do |pt, i| %> +
+ <%= text_field_tag "setup[envelope][#{i}][weight]", pt&.first&.to_s&.sub(/\.0\z/, ""), class: "input", inputmode: "decimal", "aria-label": "Envelope point #{i + 1} weight" %> + <%= text_field_tag "setup[envelope][#{i}][cg]", pt&.last&.to_s&.sub(/\.0\z/, ""), class: "input", inputmode: "decimal", "aria-label": "Envelope point #{i + 1} CG" %> +
+ <% end %> +
+
<%= submit_tag "Save", class: "btn-primary" %><%= link_to "Cancel", aircraft_weight_balance_records_path(@aircraft), class: "btn-secondary" %>
+<% end %> diff --git a/app/views/logbook_entries/_form.html.erb b/app/views/logbook_entries/_form.html.erb index b5b2658..249750e 100644 --- a/app/views/logbook_entries/_form.html.erb +++ b/app/views/logbook_entries/_form.html.erb @@ -1,17 +1,29 @@ -<%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl" do |f| %> +<%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl", data: { controller: "entry-template" } do |f| %> <%= f.errors_summary %> + <% if entry.new_record? %> +
+ <%= label_tag :template, "Preventive maintenance template", class: "label" %> + +

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.

+
+ <% end %>
<%= f.field :date, as: :date %> <%= f.field :log_type, as: :select, label: "Logbook", collection: LogbookEntry::LOG_TYPES.invert %> - <%= f.field :entry_type, as: :select, label: "Entry type", collection: LogbookEntry::ENTRY_TYPES.invert %> + <%= f.field :entry_type, as: :select, label: "Entry type", collection: LogbookEntry::ENTRY_TYPES.invert, data: { entry_template_target: "entryType" } %> <%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: "Aircraft hours" %>
- <%= f.field :text, as: :textarea, label: "Entry text", rows: 8 %> + <%= 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).

<%= f.field :signoff_person, label: "Signed off by", placeholder: "Name" %> <%= f.field :signoff_certificate_type, as: :select, label: "Kind of certificate", include_blank: "—", - collection: LogbookEntry::CERTIFICATE_TYPES.invert %> + collection: LogbookEntry::CERTIFICATE_TYPES.invert, data: { entry_template_target: "certificate" } %> <%= f.field :signoff_certificate_number, label: "Certificate number", placeholder: "e.g. 1234567" %>
@@ -21,6 +33,9 @@ <%= f.field :document_id, as: :select, label: "Scanned page document", collection: document_options(aircraft) %> <%= f.field :page_number, as: :number, label: "Page # in document" %>
+ <% if entry.persisted? && !entry.verified_was %> + <%= f.field :verified, as: :checkbox, label: "I've checked this against the scan", hint: "Transcribed by Claude; it stays marked unverified until someone checks it." %> + <% end %>
<%= f.submit "Save Entry" %><%= link_to "Cancel", aircraft_logbook_entries_path(aircraft), class: "btn-secondary" %>
<% end %> <% if entry.persisted? %>
<%= delete_button "Delete entry", aircraft_logbook_entry_path(aircraft, entry) %>
<% end %> diff --git a/app/views/logbook_entries/index.html.erb b/app/views/logbook_entries/index.html.erb index 83fe422..101e466 100644 --- a/app/views/logbook_entries/index.html.erb +++ b/app/views/logbook_entries/index.html.erb @@ -7,6 +7,9 @@ <%= form_with url: aircraft_logbook_entries_path(@aircraft), method: :get, class: "flex w-full flex-wrap gap-2 sm:w-auto" do |f| %> <%= f.search_field :q, value: @query, placeholder: "Search entries…", class: "input min-w-0 flex-1 sm:w-48 sm:flex-none" %> <%= f.select :log_type, LogbookEntry::LOG_TYPES.invert, { include_blank: "All logs", selected: @log_type }, class: "input w-32" %> + <% if @unverified_count.positive? || @unverified_only %> + + <% end %> <%= f.submit "Filter", class: "btn-secondary" %> <% end %> <% if owner? %><%= link_to "Import scans", new_aircraft_logbook_import_path(@aircraft), class: "btn-secondary" %><%= link_to "+ New Entry", new_aircraft_logbook_entry_path(@aircraft), class: "btn-primary" %><% end %> @@ -23,7 +26,8 @@ <%= LogbookEntry::LOG_TYPES[e.log_type] %> <%= LogbookEntry::ENTRY_TYPES[e.entry_type] %> <%= hours(e.aircraft_hours_at_entry) %> - <%= e.text.truncate(220) %> <%= "📄" if e.document %> + <%= e.text.truncate(220) %> <%= "📄" if e.document %> + <% unless e.verified? %>; check it against the scan">Unverified<% end %> <%= e.signoff_person %><%= " ##{e.signoff_certificate_number}" if e.signoff_certificate_number %><% if e.signoff_location.present? %>
<%= e.signoff_location %><% end %> <% if (missing = e.missing_record_items).any? %>
Incomplete<% end %> diff --git a/app/views/logbook_entries/show.html.erb b/app/views/logbook_entries/show.html.erb index 79019f2..79b5e98 100644 --- a/app/views/logbook_entries/show.html.erb +++ b/app/views/logbook_entries/show.html.erb @@ -5,6 +5,12 @@ <% if owner? %><%= link_to "Edit", edit_aircraft_logbook_entry_path(@aircraft, @entry), class: "btn-secondary btn-sm" %><% end %>
+ <% unless @entry.verified? %> +
+ Transcribed by Claude<%= " (#{@entry.transcription_confidence} confidence)" if @entry.transcription_confidence %> and not yet checked. Compare it with the scan<%= @entry.document ? "" : " or the paper logbook" %> before relying on it. + <% if owner? %><%= button_to "Matches the scan: mark verified", verify_aircraft_logbook_entry_path(@aircraft, @entry), method: :patch, class: "btn-secondary btn-sm" %><% end %> +
+ <% end %>
Type: <%= LogbookEntry::ENTRY_TYPES[@entry.entry_type] %> Aircraft hours: <%= hours(@entry.aircraft_hours_at_entry) %> diff --git a/app/views/logbook_imports/show.html.erb b/app/views/logbook_imports/show.html.erb index 6b45c9e..da3ec70 100644 --- a/app/views/logbook_imports/show.html.erb +++ b/app/views/logbook_imports/show.html.erb @@ -23,7 +23,8 @@ <%= @import.transcribe ? "Done: #{pluralize(@import.entries_created, 'logbook entry')} added." : "Pages saved." %>

<% if @import.transcribe && @import.entries_created.positive? %> -

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 %>
+
+

Weight and balance

+ <% if (wb = a.current_weight_balance) %> +

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 %> +
+

Open discrepancies

<% if (squawks = @report.open_squawks.to_a).any? %> diff --git a/app/views/major_records/show.html.erb b/app/views/major_records/show.html.erb index a2b0c2c..fc2638d 100644 --- a/app/views/major_records/show.html.erb +++ b/app/views/major_records/show.html.erb @@ -11,7 +11,24 @@
STC
<%= [@record.stc_number, @record.stc_holder].compact_blank.join(" · ").presence || "—" %> <%= link_to("(docs)", aircraft_document_path(@aircraft, @record.stc_document), class: "link") if @record.stc_document %>
Logbook
<%= @record.logbook_entry ? link_to(@record.logbook_entry.date, aircraft_logbook_entry_path(@aircraft, @record.logbook_entry), class: "link") : "—" %>
-
ICAs
<%= @record.has_ica? ? "Yes" : "No" %>
+
Weight & balance
+
+ <% if (wb = @aircraft.weight_balance_records.where(major_record: @record).recent_first.first) %> + <%= link_to "#{wb.date}: #{number_with_precision(wb.empty_weight, precision: 1)} lb @ #{number_with_precision(wb.empty_arm, precision: 2)} in", aircraft_weight_balance_records_path(@aircraft), class: "link" %> + <% elsif owner? %> + <%= link_to "Record the new W&B", new_aircraft_weight_balance_record_path(@aircraft, major_record_id: @record.id), class: "link" %> + <% else %>—<% end %> +
+
ICAs
+
+ <%= @record.has_ica? ? "Yes" : "No" %> + <% if (ica = @record.ica_inspection_type) %> + <% row = Compliance.inspection_rows(@aircraft).find { _1.type == ica } %> + · Inspection: <%= link_to ica.name, aircraft_inspections_path(@aircraft), class: "link" %> <%= compliance_badge(row.status) if row %> + <% elsif @record.has_ica? && owner? %> + · <%= link_to "Add the ICA's recurring inspection", new_aircraft_inspection_type_path(@aircraft, major_record_id: @record.id), class: "link" %> + <% end %> +
<% [["Description", @record.description], ["ICA notes", @record.ica_notes], ["Notes", @record.notes]].each do |title, text| %> <% if text.present? %>

<%= title %>

<%= simple_format text %>
<% end %> diff --git a/app/views/reminder_mailer/weekly.html.erb b/app/views/reminder_mailer/weekly.html.erb index 3326e01..42f5f94 100644 --- a/app/views/reminder_mailer/weekly.html.erb +++ b/app/views/reminder_mailer/weekly.html.erb @@ -1,5 +1,5 @@

Here's what needs attention on your aircraft.

-<% @items.each do |aircraft, issues| %> +<% @items.each do |aircraft, issues, alerts| %>

<%= link_to aircraft.tail_number, aircraft_url(aircraft) %> <%= aircraft.airworthiness.label %>

+ <% if alerts.any? %> +

<%= 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.

+
+ <%= f.field :date, as: :date %> + <%= f.field :reason, placeholder: "e.g. Weighed at annual; GTX 345 installed" %> + <%= f.field :empty_weight, as: :number, step: 0.1, label: "Empty weight (lb)", required: true %> + <%= f.field :empty_arm, as: :number, step: 0.01, label: "Empty CG / arm (in aft of datum)", required: true %> + <%= f.field :max_gross_weight, as: :number, step: 0.1, label: "Max gross weight (lb)" %> + <%= f.field :major_record_id, as: :select, label: "Alteration (337)", + collection: [ [ "— None —", nil ] ] + aircraft.major_records.recent_first.map { [ "#{_1.date_performed} – #{_1.title.truncate(50)}", _1.id ] } %> + <%= f.field :document_id, as: :select, label: "W&B report document", collection: document_options(aircraft) %> +
+ <%= f.field :notes, as: :textarea, rows: 2 %> +
<%= f.submit "Save" %><%= link_to "Cancel", aircraft_weight_balance_records_path(aircraft), class: "btn-secondary" %>
+<% end %> +<% if record.persisted? %>
<%= delete_button "Delete record", aircraft_weight_balance_record_path(aircraft, record) %>
<% end %> diff --git a/app/views/weight_balance_records/edit.html.erb b/app/views/weight_balance_records/edit.html.erb new file mode 100644 index 0000000..f6893cb --- /dev/null +++ b/app/views/weight_balance_records/edit.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, "#{@aircraft.tail_number} Weight & Balance" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/app/views/weight_balance_records/index.html.erb b/app/views/weight_balance_records/index.html.erb new file mode 100644 index 0000000..5502802 --- /dev/null +++ b/app/views/weight_balance_records/index.html.erb @@ -0,0 +1,94 @@ +<% content_for :title, "#{@aircraft.tail_number} Weight & Balance" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<% setup = @aircraft.loading_setup %> +
+
+
+

Current weight & balance

+ <% if owner? %><%= link_to "+ New W&B", new_aircraft_weight_balance_record_path(@aircraft), class: "btn-primary btn-sm" %><% end %> +
+ <% if @current %> +
+
As of
<%= fmt_date(@current.date) %><%= " · #{@current.reason}" if @current.reason.present? %>
+
Empty weight
<%= number_with_precision(@current.empty_weight, precision: 1, delimiter: ",") %> lb
+
Empty CG (arm)
<%= number_with_precision(@current.empty_arm, precision: 2) %> in
+
Moment
<%= number_with_precision(@current.empty_moment, precision: 0, delimiter: ",") %> lb-in
+
Max gross weight
<%= @current.max_gross_weight ? "#{number_with_precision(@current.max_gross_weight, precision: 0, delimiter: ',')} lb" : "—" %>
+
Useful load
<%= @current.useful_load ? "#{number_with_precision(@current.useful_load, precision: 1, delimiter: ',')} lb" : "—" %>
+
+ <% else %> + <%= empty_state "No weight & balance recorded yet. Add the figures from the current W&B report." %> + <% end %> +
+ +
+
+

Loading calculator

+ <% if owner? %><%= link_to "Loading setup", edit_aircraft_loading_setup_path(@aircraft), class: "btn-secondary btn-sm" %><% end %> +
+ <% if @current && setup.configured? %> +
+
+ <% setup.stations.each do |st| %> + + <% end %> + <% if setup.stations.any?(&:fuel) %> + + <% end %> +
+
+ + + + + + +
WeightCGMoment
Takeoff———
Landing———
+ +
+
    +

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

    +
    + <% elsif !@current %> + <%= empty_state "Record the current weight & balance first." %> + <% else %> + <%= empty_state(owner? ? "Set up the loading stations and CG envelope from the POH to use the calculator." : "An owner needs to set up the loading stations first.") %> + <% end %> +
    +
    + +
    +

    History

    + <% if @records.any? %> +
    + + + + <% @records.each do |r| %> + + + + + + + + + <% end %> + +
    DateEmpty weightCGUseful loadReason
    <%= 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 %>
    +
    + <% else %><%= empty_state "No records yet." %><% end %> +
    diff --git a/app/views/weight_balance_records/new.html.erb b/app/views/weight_balance_records/new.html.erb new file mode 100644 index 0000000..f6893cb --- /dev/null +++ b/app/views/weight_balance_records/new.html.erb @@ -0,0 +1,3 @@ +<% content_for :title, "#{@aircraft.tail_number} Weight & Balance" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= render "form", aircraft: @aircraft, record: @record %> diff --git a/config/brakeman.ignore b/config/brakeman.ignore index aa7ee02..50903ab 100644 --- a/config/brakeman.ignore +++ b/config/brakeman.ignore @@ -1,10 +1,73 @@ { "ignored_warnings": [ { - "warning_type": "File Access", - "fingerprint": "c1d23cfd1f641b61be5cc6d747c8658806ed9e5adccb66eaca8f2aac5ef449ee", - "file": "app/controllers/flight_imports_controller.rb", - "note": "Token is validated against TOKEN_FORMAT (server-generated uuid.ext) before use, and File.basename is applied; path is confined to tmp/imports." + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "43d7e4cfb5fdffe8ce34bb9676dc02e2a9e5dba55fdc47fbb480cace17bafe59", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in `link_to` href", + "file": "app/views/admin/about/show.html.erb", + "line": 14, + "link": "https://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(\"Source code\", SystemInfo.new.repository_url, :class => \"link\", :target => \"_blank\", :rel => \"noopener\")", + "render_path": [ + { + "type": "controller", + "class": "Admin::AboutController", + "method": "show", + "line": 7, + "file": "app/controllers/admin/about_controller.rb", + "rendered": { + "name": "admin/about/show", + "file": "app/views/admin/about/show.html.erb" + } + } + ], + "location": { + "type": "template", + "template": "admin/about/show" + }, + "user_input": "SystemInfo.new.repository_url", + "confidence": "Weak", + "cwe_id": [ + 79 + ], + "note": "The repository URL comes from the server environment (APP_REPOSITORY_URL) or a constant, and SystemInfo only returns http(s) URLs; admins only." + }, + { + "warning_type": "Cross-Site Scripting", + "warning_code": 4, + "fingerprint": "85f8003e1ad00eeb2308faea3dd89e55db1b7a794b9c1a8b05c16466849038ac", + "check_name": "LinkToHref", + "message": "Potentially unsafe model attribute in `link_to` href", + "file": "app/views/admin/about/show.html.erb", + "line": 12, + "link": "https://brakemanscanner.org/docs/warning_types/link_to_href", + "code": "link_to(SystemInfo.new.revision, SystemInfo.new.revision_url, :class => \"link\", :target => \"_blank\", :rel => \"noopener\", :title => \"This commit on GitHub\")", + "render_path": [ + { + "type": "controller", + "class": "Admin::AboutController", + "method": "show", + "line": 7, + "file": "app/controllers/admin/about_controller.rb", + "rendered": { + "name": "admin/about/show", + "file": "app/views/admin/about/show.html.erb" + } + } + ], + "location": { + "type": "template", + "template": "admin/about/show" + }, + "user_input": "SystemInfo.new.revision_url", + "confidence": "Weak", + "cwe_id": [ + 79 + ], + "note": "The repository URL comes from the server environment (APP_REPOSITORY_URL) or a constant, and SystemInfo only returns http(s) URLs; admins only." } - ] + ], + "brakeman_version": "8.1.0" } diff --git a/config/recurring.yml b/config/recurring.yml index 38ef55e..5ef54b9 100644 --- a/config/recurring.yml +++ b/config/recurring.yml @@ -22,3 +22,6 @@ production: weekly_reminders: class: WeeklyReminderJob schedule: every monday at 12pm + ad_watch: + class: AdWatchJob + schedule: every sunday at 10am diff --git a/config/routes.rb b/config/routes.rb index eecc4cf..740468e 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -60,7 +60,9 @@ Rails.application.routes.draw do collection { post :import } end resources :logbook_imports, path: "logbook/import", only: %i[new create show] - resources :logbook_entries + resources :logbook_entries do + member { patch :verify } + end resources :documents do collection do get :bulk, action: :bulk_new, as: :new_bulk @@ -72,6 +74,16 @@ Rails.application.routes.draw do resources :inspection_types, except: %i[index show] resource :standard_inspections, only: %i[new create] resources :inspection_records, except: %i[index show] + resources :ad_alerts, path: "ads/new_ads", only: [] do + member do + post :track + post :dismiss + end + collection do + post :check + patch :terms + end + end resources :airworthiness_directives, path: "ads", except: :show do collection { post :attach } end @@ -80,6 +92,8 @@ Rails.application.routes.draw do post :confirm end resources :major_records + resource :loading_setup, path: "weight_balance/loading", only: %i[edit update] # before the records' :id routes + resources :weight_balance_records, path: "weight_balance", except: :show resources :aircraft_roles, path: "access", only: %i[index create update destroy] resources :share_tokens, only: %i[create destroy] resource :export, controller: "aircraft_exports", only: :show diff --git a/db/migrate/20261107220000_add_group_four_records.rb b/db/migrate/20261107220000_add_group_four_records.rb new file mode 100644 index 0000000..de89ca0 --- /dev/null +++ b/db/migrate/20261107220000_add_group_four_records.rb @@ -0,0 +1,49 @@ +# - logbook_entries.verified: AI-transcribed entries start unverified until +# someone checks them against the scan +# - major_records.ica_inspection_type: the recurring inspection an STC's +# Instructions for Continued Airworthiness call for +# - weight_balance_records + aircraft loading setup: weight & balance history +# and a loading calculator +# - ad_alerts + aircraft.ad_watch_terms: newly published ADs that may apply +class AddGroupFourRecords < ActiveRecord::Migration[8.1] + def change + add_column :logbook_entries, :verified, :boolean, null: false, default: true + add_column :logbook_entries, :transcription_confidence, :string + add_reference :major_records, :ica_inspection_type, foreign_key: { to_table: :inspection_types, on_delete: :nullify } + + create_table :weight_balance_records do |t| + t.references :aircraft, null: false, foreign_key: true + t.date :date, null: false + t.decimal :empty_weight, precision: 8, scale: 1, null: false + t.decimal :empty_arm, precision: 7, scale: 2, null: false + t.decimal :max_gross_weight, precision: 8, scale: 1 + t.string :reason + t.text :notes + t.references :major_record, foreign_key: { on_delete: :nullify } + t.references :document, foreign_key: { on_delete: :nullify } + t.timestamps + end + + add_column :aircraft, :loading_stations, :json + add_column :aircraft, :cg_envelope, :json + add_column :aircraft, :ad_watch_terms, :string + add_column :aircraft, :ad_watch_checked_at, :datetime + + create_table :ad_alerts do |t| + t.references :aircraft, null: false, foreign_key: true + t.string :fr_document_number, null: false + t.string :ad_number + t.string :amendment + t.string :title + t.text :abstract + t.date :publication_date + t.date :effective_on + t.string :html_url + t.string :matched_term + t.string :status, null: false, default: "new" + t.references :airworthiness_directive, foreign_key: { on_delete: :nullify } + t.timestamps + end + add_index :ad_alerts, %i[aircraft_id fr_document_number], unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index d92fb58..42eaf5e 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_07_210000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_07_220000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -39,6 +39,26 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true end + create_table "ad_alerts", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.string "fr_document_number", null: false + t.string "ad_number" + t.string "amendment" + t.string "title" + t.text "abstract" + t.date "publication_date" + t.date "effective_on" + t.string "html_url" + t.string "matched_term" + t.string "status", default: "new", null: false + t.integer "airworthiness_directive_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id", "fr_document_number"], name: "index_ad_alerts_on_aircraft_id_and_fr_document_number", unique: true + t.index ["aircraft_id"], name: "index_ad_alerts_on_aircraft_id" + t.index ["airworthiness_directive_id"], name: "index_ad_alerts_on_airworthiness_directive_id" + end + create_table "ad_compliances", force: :cascade do |t| t.integer "airworthiness_directive_id", null: false t.integer "aircraft_id" @@ -123,6 +143,10 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do t.datetime "updated_at", null: false t.string "icao_type" t.string "time_basis", default: "tach", null: false + t.json "loading_stations" + t.json "cg_envelope" + t.string "ad_watch_terms" + t.datetime "ad_watch_checked_at" end create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t| @@ -423,6 +447,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do t.string "signoff_certificate_type" t.string "signoff_certificate_number" t.string "inspection_result" + t.boolean "verified", default: true, null: false + t.string "transcription_confidence" t.index ["aircraft_id"], name: "index_logbook_entries_on_aircraft_id" t.index ["document_id"], name: "index_logbook_entries_on_document_id" end @@ -468,9 +494,11 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do t.text "notes" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.integer "ica_inspection_type_id" t.index ["aircraft_id"], name: "index_major_records_on_aircraft_id" t.index ["component_id"], name: "index_major_records_on_component_id" t.index ["form_337_document_id"], name: "index_major_records_on_form_337_document_id" + t.index ["ica_inspection_type_id"], name: "index_major_records_on_ica_inspection_type_id" t.index ["logbook_entry_id"], name: "index_major_records_on_logbook_entry_id" t.index ["stc_document_id"], name: "index_major_records_on_stc_document_id" end @@ -569,8 +597,27 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do t.index ["sso_uid"], name: "index_users_on_sso_uid", unique: true end + create_table "weight_balance_records", force: :cascade do |t| + t.integer "aircraft_id", null: false + t.date "date", null: false + t.decimal "empty_weight", precision: 8, scale: 1, null: false + t.decimal "empty_arm", precision: 7, scale: 2, null: false + t.decimal "max_gross_weight", precision: 8, scale: 1 + t.string "reason" + t.text "notes" + t.integer "major_record_id" + t.integer "document_id" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["aircraft_id"], name: "index_weight_balance_records_on_aircraft_id" + t.index ["document_id"], name: "index_weight_balance_records_on_document_id" + t.index ["major_record_id"], name: "index_weight_balance_records_on_major_record_id" + end + add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" + add_foreign_key "ad_alerts", "aircraft" + add_foreign_key "ad_alerts", "airworthiness_directives", on_delete: :nullify add_foreign_key "ad_compliances", "aircraft" add_foreign_key "ad_compliances", "airworthiness_directives" add_foreign_key "ad_compliances", "components" @@ -614,6 +661,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do add_foreign_key "major_records", "components", on_delete: :nullify add_foreign_key "major_records", "documents", column: "form_337_document_id", on_delete: :nullify add_foreign_key "major_records", "documents", column: "stc_document_id", on_delete: :nullify + add_foreign_key "major_records", "inspection_types", column: "ica_inspection_type_id", on_delete: :nullify add_foreign_key "major_records", "logbook_entries", on_delete: :nullify add_foreign_key "oil_analyses", "aircraft" add_foreign_key "oil_analyses", "components" @@ -624,4 +672,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do add_foreign_key "squawks", "components", on_delete: :nullify add_foreign_key "squawks", "logbook_entries", on_delete: :nullify add_foreign_key "squawks", "users", column: "reported_by_id", on_delete: :nullify + add_foreign_key "weight_balance_records", "aircraft" + add_foreign_key "weight_balance_records", "documents", on_delete: :nullify + add_foreign_key "weight_balance_records", "major_records", on_delete: :nullify end diff --git a/test/integration/group_four_test.rb b/test/integration/group_four_test.rb new file mode 100644 index 0000000..b4a50e0 --- /dev/null +++ b/test/integration/group_four_test.rb @@ -0,0 +1,187 @@ +require "test_helper" + +# Unverified transcriptions, preventive maintenance templates, ICA +# inspections, weight & balance, and watching for newly published ADs. +class GroupFourTest < ActionDispatch::IntegrationTest + include ActionMailer::TestHelper + + setup do + @owner = create_user("owner@example.com") + @pilot = create_user("pilot@example.com") + @a = create_aircraft(owner: @owner, pilot: @pilot, tail_number: "N12345", make: "Cessna", model: "172N") + end + + test "transcribed entries stay unverified until an owner checks them" do + first = @a.logbook_entries.create!(date: Date.new(2020, 1, 1), text: "Oil changed", verified: false, transcription_confidence: "medium") + second = @a.logbook_entries.create!(date: Date.new(2020, 2, 1), text: "Annual", verified: false) + @a.logbook_entries.create!(date: Date.new(2020, 3, 1), text: "Typed in") + sign_in @owner + get aircraft_logbook_entries_path(@a) + assert_select ".badge-orange", text: "Unverified", count: 2 + get aircraft_logbook_entries_path(@a, unverified: 1) + assert_select "tbody tr", 2 + get aircraft_logbook_entry_path(@a, first) + assert_includes response.body, "Transcribed by Claude (medium confidence) and not yet checked" + + patch verify_aircraft_logbook_entry_path(@a, first) + assert_redirected_to aircraft_logbook_entry_path(@a, second) # on to the next one + assert first.reload.verified? + patch aircraft_logbook_entry_path(@a, second), params: { logbook_entry: { verified: "1" } } + assert second.reload.verified? + + sign_in @pilot + patch verify_aircraft_logbook_entry_path(@a, first.tap { _1.update!(verified: false) }) + refute first.reload.verified? + end + + test "preventive maintenance templates fill in the entry with the Part 43 reference" do + sign_in @owner + get new_aircraft_logbook_entry_path(@a) + assert_select "select[data-entry-template-target=template] option", PreventiveMaintenance::ITEMS.size + 1 + assert_select "option[value=spark_plugs][data-text*='Part 43 Appendix A paragraph (c)(20)']" + assert_select "option[value=oil_change][data-text*='14 CFR 43.3(g)']" + get edit_aircraft_logbook_entry_path(@a, @a.logbook_entries.create!(date: Date.current, text: "x")) + assert_select "select[data-entry-template-target=template]", 0 + end + + test "an STC's ICA becomes a tracked inspection linked from its major record" do + record = @a.major_records.create!(record_type: "alteration", title: "Engine monitor installed", date_performed: Date.current, + stc_number: "SA02000CH", has_ica: true, ica_notes: "Inspect probes every 100 hrs") + sign_in @owner + get aircraft_major_record_path(@a, record) + assert_select "a[href='#{new_aircraft_inspection_type_path(@a, major_record_id: record.id)}']", text: "Add the ICA's recurring inspection" + get new_aircraft_inspection_type_path(@a, major_record_id: record.id) + assert_select "input[name='inspection_type[name]'][value='ICA: Engine monitor installed']" + assert_includes response.body, "Inspect probes every 100 hrs" + + post aircraft_inspection_types_path(@a), params: { major_record_id: record.id, applies_to_airframe: "1", inspection_type: { + name: "ICA: Engine monitor installed", recurring: "1", recurring_hours: 100, effect: "grounds" } } + assert_redirected_to aircraft_major_record_path(@a, record) + ica = record.reload.ica_inspection_type + assert_equal [ "ICA: Engine monitor installed", 100 ], [ ica.name, ica.recurring_hours.to_i ] + assert_includes @a.reload.applicable_inspection_types, ica + get aircraft_major_record_path(@a, record) + assert_select "a", text: "ICA: Engine monitor installed" + end + + test "weight & balance history, loading setup and the calculator" do + sign_in @pilot + get aircraft_weight_balance_records_path(@a) + assert_response :success + assert_includes response.body, "No weight & balance recorded yet" + post aircraft_weight_balance_records_path(@a), params: { weight_balance_record: { date: "2026-01-01", empty_weight: 1500, empty_arm: 39 } } + assert_equal 0, @a.weight_balance_records.count # owners only + + sign_in @owner + alteration = @a.major_records.create!(record_type: "alteration", title: "Avionics upgrade", date_performed: Date.current) + post aircraft_weight_balance_records_path(@a), params: { weight_balance_record: { + date: "2026-01-01", empty_weight: 1500, empty_arm: 39.5, max_gross_weight: 1400 } } + assert_response :unprocessable_entity + assert_includes response.body, "must be more than the empty weight" + post aircraft_weight_balance_records_path(@a), params: { weight_balance_record: { + date: "2026-01-01", empty_weight: 1500, empty_arm: 39.5, max_gross_weight: 2300, reason: "Avionics upgrade", major_record_id: alteration.id } } + wb = @a.current_weight_balance + assert_equal [ 800, 59250, alteration ], [ wb.useful_load.to_i, wb.empty_moment.to_i, wb.major_record ] + + patch aircraft_loading_setup_path(@a), params: { setup: { fuel_lb_per_gal: "6", stations: { + "0" => { name: "Front seats", arm: "37", max: "" }, "1" => { name: "Fuel", arm: "48", max: "40", fuel: "1" }, "2" => { name: "", arm: "" } }, + envelope: { "0" => { weight: "1500", cg: "35" }, "1" => { weight: "1950", cg: "35" } } } } + assert_response :unprocessable_entity + assert_includes response.body, "at least 3 points" + + patch aircraft_loading_setup_path(@a), params: { setup: { fuel_lb_per_gal: "6", stations: { + "0" => { name: "Front seats", arm: "37", max: "" }, "1" => { name: "Fuel", arm: "48", max: "40", fuel: "1" } }, + envelope: { "0" => { weight: "1500", cg: "35" }, "1" => { weight: "2300", cg: "38.5" }, "2" => { weight: "2300", cg: "47.3" }, "3" => { weight: "1500", cg: "47.3" } } } } + assert_redirected_to aircraft_weight_balance_records_path(@a) + setup = @a.reload.loading_setup + assert_equal [ [ "Front seats", false ], [ "Fuel", true ] ], setup.stations.map { [ _1.name, _1.fuel ] } + assert_equal 4, setup.envelope.size + + get aircraft_weight_balance_records_path(@a) + assert_select "[data-controller=wb-calculator][data-wb-calculator-empty-weight-value='1500.0'][data-wb-calculator-max-gross-value='2300.0']" + assert_select "input[data-wb-calculator-target=station][data-fuel=true][data-arm='48.0']" + assert_select "input[data-wb-calculator-target=burn]" + get aircraft_major_record_path(@a, alteration) + assert_includes response.body, "2026-01-01: 1500.0 lb @ 39.50 in" + get aircraft_report_path(@a) + assert_includes response.body, "Empty weight 1,500.0 lb" + end + + FR_RESPONSE = { results: [ + { document_number: "2026-17584", title: "Airworthiness Directives; Lycoming Engines", publication_date: "2026-08-28", + effective_on: "2026-09-14", html_url: "https://www.federalregister.gov/d/2026-17584", + abstract: "The FAA is adopting a new AD for certain Lycoming O-320 engines. This AD requires replacement of the affected piston pin. The FAA is issuing this AD.", + docket_ids: [ "Docket No. FAA-2026-8789", "Amendment 39-23454", "AD 2026-17-10" ] }, + { document_number: "2026-11111", title: "Airworthiness Directives; Old One", publication_date: "2026-08-01", + effective_on: "2026-08-20", html_url: "https://www.federalregister.gov/d/2026-11111", abstract: "Old.", docket_ids: [ "AD 2020-01-01" ] }, + { document_number: "2026-22222", title: "Special Conditions; Something Else", publication_date: "2026-08-02", docket_ids: [] } + ] }.to_json + + test "newly published ADs are found, tracked or dismissed, and reported weekly" do + create_component(@a, component_type: component_type("Engine"), model: "O-320-H2AD") + assert_equal [ "172N", "O-320-H2AD" ], AdWatch.default_terms(@a) + known = AirworthinessDirective.create!(name: "2020-01-01", short_description: "Already tracked") + known.aircraft << @a + stub = stub_request(:get, %r{\Ahttps://www\.federalregister\.gov/api/v1/documents\.json}).to_return(status: 200, body: FR_RESPONSE) + + sign_in @owner + post check_aircraft_ad_alerts_path(@a) + assert_redirected_to aircraft_airworthiness_directives_path(@a, anchor: "new-ads") + assert_requested stub, times: 2 # one search per term + alert = @a.ad_alerts.sole # already-tracked and non-AD documents skipped + assert_equal [ "2026-17-10", "39-23454", "new" ], [ alert.ad_number, alert.amendment, alert.status ] + get aircraft_airworthiness_directives_path(@a) + assert_includes response.body, "AD 2026-17-10 · Lycoming Engines" + assert_select "a[href='https://www.federalregister.gov/d/2026-17584']" + + assert_emails 1 do + WeeklyReminderJob.perform_now + end + assert_includes ActionMailer::Base.deliveries.last.text_part.body.to_s, "New ADs that may apply: 2026-17-10" + + post check_aircraft_ad_alerts_path(@a) # checking again doesn't duplicate + assert_equal 1, @a.ad_alerts.count + + post track_aircraft_ad_alert_path(@a, alert) + ad = AirworthinessDirective.find_by!(name: "2026-17-10") + assert_redirected_to edit_aircraft_airworthiness_directive_path(@a, ad) + assert_equal [ "Requires replacement of the affected piston pin", Date.new(2026, 9, 14), "39-23454" ], + [ ad.short_description, ad.effective_date, ad.docket_number ] + assert_includes @a.reload.applicable_ads, ad + assert @a.airworthiness.red? # untracked compliance counts until recorded + + other = @a.ad_alerts.create!(fr_document_number: "X-1", title: "Airworthiness Directives; Other", status: "new") + post dismiss_aircraft_ad_alert_path(@a, other) + assert_equal "dismissed", other.reload.status + + patch terms_aircraft_ad_alerts_path(@a), params: { ad_watch_terms: "172, O-320" } + assert_equal [ "172", "O-320" ], AdWatch.new(@a.reload).terms + + stub_request(:get, %r{federalregister}).to_return(status: 503) + post check_aircraft_ad_alerts_path(@a) + assert_match "Couldn't check for new ADs: the Federal Register returned 503", flash[:alert] + assert_nothing_raised { AdWatchJob.perform_now } + + sign_in @pilot + post check_aircraft_ad_alerts_path(@a) + assert_redirected_to aircraft_path(@a) + end + + test "archives carry weight & balance, the loading setup, the ICA link and verification" do + ica = InspectionType.create!(name: "ICA: monitor", recurring: true, recurring_hours: 100).tap { _1.aircraft << @a } + record = @a.major_records.create!(record_type: "alteration", title: "Monitor", date_performed: Date.current, has_ica: true, ica_inspection_type: ica) + @a.weight_balance_records.create!(date: Date.new(2026, 1, 1), empty_weight: 1500, empty_arm: 39.5, max_gross_weight: 2300, major_record: record) + @a.update!(loading_stations: { "fuel_lb_per_gal" => 6.0, "stations" => [ { "name" => "Pilot", "arm" => 37.0, "max" => nil, "fuel" => false } ] }, + cg_envelope: [ [ 1500, 35 ], [ 2300, 38.5 ], [ 2300, 47.3 ] ]) + @a.logbook_entries.create!(date: Date.current, text: "Read by Claude", verified: false) + path = File.join(Dir.mktmpdir, "a.sam.zip") + AircraftArchive::Exporter.new(@a, source: "sam.example.com").write_to(path) + copy = AircraftArchive::Importer.new(path, owner: @owner, tail_number: "N54321").run[:aircraft] + + wb = copy.current_weight_balance + assert_equal [ 1500, "Monitor" ], [ wb.empty_weight.to_i, wb.major_record.title ] + assert_equal ica, copy.major_records.sole.ica_inspection_type + assert_equal [ "Pilot" ], copy.loading_setup.stations.map(&:name) + refute copy.logbook_entries.sole.verified? + end +end diff --git a/test/integration/logbook_import_flow_test.rb b/test/integration/logbook_import_flow_test.rb index d112b3d..388a0b1 100644 --- a/test/integration/logbook_import_flow_test.rb +++ b/test/integration/logbook_import_flow_test.rb @@ -94,6 +94,8 @@ class LogbookImportFlowTest < ActionDispatch::IntegrationTest entries = @a.logbook_entries.order(:id) assert_equal [ "Changed oil", "Annual inspection, found airworthy", "[date unreadable] Replaced [?] gasket" ], entries.map(&:text) + assert entries.none?(&:verified?) # transcriptions wait for a person to check them + assert_equal [ "high", "high", "low" ], entries.map(&:transcription_confidence) assert_equal [ "J. Mechanic", "AP", "1234567" ], entries.first.then { [ _1.signoff_person, _1.signoff_certificate_type, _1.signoff_certificate_number ] } assert_equal [ 1, 2, 3 ], entries.map(&:page_number) assert entries.all? { _1.document == document && _1.log_type == "ENG" } diff --git a/test/integration/phone_layout_test.rb b/test/integration/phone_layout_test.rb index c646b61..8ac413a 100644 --- a/test/integration/phone_layout_test.rb +++ b/test/integration/phone_layout_test.rb @@ -14,7 +14,7 @@ class PhoneLayoutTest < ActionDispatch::IntegrationTest assert_select "header nav.sm\\:hidden a[href='#{admin_users_path}']" assert_select "details.md\\:hidden summary", text: /Section\s*Components/ assert_select "details.md\\:hidden nav a[aria-current=page]", "Components" - assert_select "details.md\\:hidden nav a", count: 14 + assert_select "details.md\\:hidden nav a", count: 15 assert_select "nav.md\\:flex a.tab-active", "Components" # wider screens keep the tabs end