diff --git a/README.md b/README.md index 141da35..abfdbcd 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,8 @@ Alternatively, stop the container and copy the volume. | Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is RED. | | 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" makes the aircraft RED. Supports attachments, resolve, and 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, and compliance history. | +| 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. | +| 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. | | Logbook | Maintenance entries with search and a link to a scanned document page. | | Documents | Collections, multi-file documents with a page viewer, and per-document share visibility. | diff --git a/app/controllers/ad_compliances_controller.rb b/app/controllers/ad_compliances_controller.rb index 63831ca..d786e08 100644 --- a/app/controllers/ad_compliances_controller.rb +++ b/app/controllers/ad_compliances_controller.rb @@ -6,14 +6,16 @@ class AdCompliancesController < ApplicationController def new ad = @aircraft.applicable_ads.find_by(id: params[:ad_id]) @compliance = AdCompliance.new(aircraft: @aircraft, airworthiness_directive: ad, date_complied: Date.current, - aircraft_hours_at_compliance: @aircraft.tach_time) + aircraft_hours_at_compliance: @aircraft.tach_time, + not_applicable: params[:not_applicable] == "1") + @compliance.compliance_notes = "Not applicable: " if @compliance.not_applicable? @compliance.fill_next_due end def create @compliance = AdCompliance.new(compliance_params.merge(aircraft: @aircraft)) if @compliance.save - log_event("ad", "Compliance recorded: #{@compliance.airworthiness_directive.name}") + log_event("ad", "#{@compliance.not_applicable? ? "Marked N/A" : "Compliance recorded"}: #{@compliance.airworthiness_directive.name}") redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance recorded." else render :new, status: :unprocessable_entity @@ -44,7 +46,7 @@ class AdCompliancesController < ApplicationController def compliance_params p = params.require(:ad_compliance).permit( :airworthiness_directive_id, :date_complied, :compliance_notes, :permanent, :next_due_at_time, - :aircraft_hours_at_compliance, :logbook_entry_id, :inspection_record_id, :component_id + :aircraft_hours_at_compliance, :logbook_entry_id, :inspection_record_id, :component_id, :not_applicable ) p[:airworthiness_directive_id] = scoped_id(@aircraft.applicable_ads, p[:airworthiness_directive_id]) p[:logbook_entry_id] = scoped_id(@aircraft.logbook_entries, p[:logbook_entry_id]) diff --git a/app/controllers/ad_imports_controller.rb b/app/controllers/ad_imports_controller.rb new file mode 100644 index 0000000..e92e79c --- /dev/null +++ b/app/controllers/ad_imports_controller.rb @@ -0,0 +1,45 @@ +# Owner-only import of ADs from an FAA DRS export: upload → preview → confirm. +class AdImportsController < ApplicationController + include AircraftScoped + include StoredUpload + before_action :require_owner! + + def new; end + + def create + token, error = store_upload(params[:file]) + return redirect_to_upload(error) if error + redirect_to aircraft_ad_import_path(@aircraft, token: token, filename: params[:file].original_filename) + end + + def show + @token = params[:token].to_s + return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(@token) + @filename = params[:filename].to_s + @import = AdImport.new(@aircraft, path: stored_path(@token), filename: @filename) + @import.rows + rescue AdImport::Error => e + redirect_to_upload(e.message) + end + + def confirm + token = params[:token].to_s + return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(token) + import = AdImport.new(@aircraft, path: stored_path(token), filename: params[:filename]) + # Only AD numbers present in the uploaded file; values are checked against AdImport::ACTIONS. + decisions = params.fetch(:decisions, {}).permit(*import.rows.map(&:number)).to_h + result = import.import!(decisions: decisions, user: current_user) + discard_upload(token) + redirect_to aircraft_airworthiness_directives_path(@aircraft), + notice: "Imported #{result[:tracked]} ADs to track and #{result[:not_applicable]} marked N/A; " \ + "#{result[:updated]} existing ADs updated, #{result[:skipped]} skipped." + rescue AdImport::Error => e + redirect_to_upload(e.message) + end + + private + + def redirect_to_upload(message) + redirect_to new_aircraft_ad_import_path(@aircraft), alert: message + end +end diff --git a/app/controllers/aircraft_controller.rb b/app/controllers/aircraft_controller.rb index a1dd8fb..05f09ec 100644 --- a/app/controllers/aircraft_controller.rb +++ b/app/controllers/aircraft_controller.rb @@ -68,7 +68,7 @@ class AircraftController < ApplicationController params.require(:aircraft).permit( :tail_number, :make, :model, :serial_number, :description, :purchased, :status, :tach_time, :tach_time_offset, :hobbs_time, :hobbs_time_offset, - :airworthiness_enforcement, :picture + :airworthiness_enforcement, :picture, :drs_search_url ) end end diff --git a/app/controllers/airworthiness_directives_controller.rb b/app/controllers/airworthiness_directives_controller.rb index 8ad1d91..68024b7 100644 --- a/app/controllers/airworthiness_directives_controller.rb +++ b/app/controllers/airworthiness_directives_controller.rb @@ -6,7 +6,8 @@ class AirworthinessDirectivesController < ApplicationController def index @rows = Compliance.ad_rows(@aircraft) - @history = AdCompliance.for_aircraft(@aircraft).recent_first.includes(:airworthiness_directive, :component) + @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? end @@ -66,7 +67,7 @@ class AirworthinessDirectivesController < ApplicationController def ad_params p = params.require(:airworthiness_directive).permit( :name, :short_description, :required_action, :compliance_type, :trigger_condition, :recurring, - :recurring_hours, :recurring_months, :recurring_days, :bulletin_type, :mandatory, :document_id + :recurring_hours, :recurring_months, :recurring_days, :bulletin_type, :mandatory, :document_id, :document_url ) p[:document_id] = scoped_id(@aircraft.documents, p[:document_id]) p diff --git a/app/controllers/concerns/stored_upload.rb b/app/controllers/concerns/stored_upload.rb new file mode 100644 index 0000000..de049cc --- /dev/null +++ b/app/controllers/concerns/stored_upload.rb @@ -0,0 +1,40 @@ +# Keeps an uploaded spreadsheet in tmp/imports between the upload and confirm +# steps of an import. Tokens are server-generated "." and files are +# namespaced by aircraft, so a token can't be replayed elsewhere or used to +# reach other paths. +module StoredUpload + extend ActiveSupport::Concern + + UPLOAD_DIR = Rails.root.join("tmp/imports") + UPLOAD_MAX_SIZE = 10.megabytes + UPLOAD_EXTENSIONS = %w[xlsx csv].freeze + TOKEN_FORMAT = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\.(xlsx|csv)\z/ + + private + + # Returns [token, nil] on success or [nil, error message]. + def store_upload(file) + return [ nil, "Choose a file to upload." ] unless file.respond_to?(:path) + return [ nil, "File is too large." ] if file.size > UPLOAD_MAX_SIZE + ext = File.extname(file.original_filename.to_s).delete(".").downcase + return [ nil, "Upload an .xlsx or .csv file." ] unless ext.in?(UPLOAD_EXTENSIONS) + + FileUtils.mkdir_p(UPLOAD_DIR) + Dir.glob(UPLOAD_DIR.join("*")).each { |f| File.delete(f) if File.mtime(f) < 1.day.ago } + token = "#{SecureRandom.uuid}.#{ext}" + FileUtils.cp(file.path, stored_path(token)) + [ token, nil ] + end + + def stored_file?(token) + TOKEN_FORMAT.match?(token.to_s) && File.exist?(stored_path(token)) + end + + def stored_path(token) + UPLOAD_DIR.join("#{@aircraft.id}-#{File.basename(token.to_s)}") + end + + def discard_upload(token) + File.delete(stored_path(token)) if stored_file?(token) + end +end diff --git a/app/controllers/flight_imports_controller.rb b/app/controllers/flight_imports_controller.rb index eff1167..2d73761 100644 --- a/app/controllers/flight_imports_controller.rb +++ b/app/controllers/flight_imports_controller.rb @@ -1,32 +1,16 @@ # Owner-only bulk import of historical flights: upload → preview → confirm. -# The uploaded file is kept in tmp/imports between the two steps. class FlightImportsController < ApplicationController include AircraftScoped + include StoredUpload before_action :require_owner! - MAX_SIZE = 10.megabytes - DIR = Rails.root.join("tmp/imports") - # Server-generated "."; anything else is rejected before touching the filesystem. - TOKEN_FORMAT = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\.(xlsx|csv)\z/ - def new; end # Store the upload, then redirect to the preview (Turbo requires a redirect after a form POST). def create - file = params[:file] - return redirect_to(new_aircraft_flight_import_path(@aircraft), alert: "Choose a file to upload.") unless file.respond_to?(:path) - return redirect_to(new_aircraft_flight_import_path(@aircraft), alert: "File is too large.") if file.size > MAX_SIZE - - ext = File.extname(file.original_filename).delete(".").downcase - unless ext.in?(FlightImport::EXTENSIONS) - return redirect_to new_aircraft_flight_import_path(@aircraft), alert: "Upload an .xlsx or .csv file." - end - - cleanup_old_files - FileUtils.mkdir_p(DIR) - token = "#{SecureRandom.uuid}.#{ext}" - FileUtils.cp(file.path, stored_path(token)) - redirect_to aircraft_flight_import_path(@aircraft, token: token, filename: file.original_filename, + token, error = store_upload(params[:file]) + return redirect_to_upload(error) if error + redirect_to aircraft_flight_import_path(@aircraft, token: token, filename: params[:file].original_filename, starting_tach: params[:starting_tach].presence, starting_hobbs: params[:starting_hobbs].presence) end @@ -48,11 +32,10 @@ class FlightImportsController < ApplicationController def confirm token = params[:token].to_s return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(token) - path = stored_path(token) import = build_import(token, params[:filename], starting_tach: params[:starting_tach], starting_hobbs: params[:starting_hobbs]) count = import.import!(user: current_user, update_aircraft_hours: params[:update_aircraft_hours] == "1") - File.delete(path) + discard_upload(token) redirect_to aircraft_flight_logs_path(@aircraft), notice: "Imported #{count} flights." rescue FlightImport::Error => e redirect_to new_aircraft_flight_import_path(@aircraft), alert: e.message @@ -63,10 +46,6 @@ class FlightImportsController < ApplicationController private - def stored_file?(token) - TOKEN_FORMAT.match?(token) && File.exist?(stored_path(token)) - end - def redirect_to_upload(message) redirect_to new_aircraft_flight_import_path(@aircraft), alert: message end @@ -75,13 +54,4 @@ class FlightImportsController < ApplicationController FlightImport.new(@aircraft, path: stored_path(token), filename: filename, starting_tach: starting_tach, starting_hobbs: starting_hobbs) end - - # Files are namespaced by aircraft so a token can't be replayed on another aircraft. - def stored_path(token) - DIR.join("#{@aircraft.id}-#{File.basename(token)}") - end - - def cleanup_old_files - Dir.glob(DIR.join("*")).each { |f| File.delete(f) if File.mtime(f) < 1.day.ago } - end end diff --git a/app/helpers/aircraft_helper.rb b/app/helpers/aircraft_helper.rb index a971a58..bc43d6e 100644 --- a/app/helpers/aircraft_helper.rb +++ b/app/helpers/aircraft_helper.rb @@ -9,7 +9,7 @@ module AircraftHelper [ "Oil & Fuel", aircraft_consumable_records_path(aircraft), %w[consumable_records] ], [ "Logbook", aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ], [ "Inspections", aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ], - [ "ADs", aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances] ], + [ "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] ], [ "Notes", aircraft_notes_path(aircraft), %w[notes] ], diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 5ef17df..7226d7f 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -21,7 +21,8 @@ module ApplicationHelper COMPLIANCE_BADGES = { "compliant" => [ "green", "Compliant" ], "due_soon" => [ "orange", "Due Soon" ], "overdue" => [ "red", "Overdue" ], "no_compliance" => [ "red", "No Record" ], - "never_completed" => [ "red", "Never Completed" ], "conditional" => [ "gray", "Conditional" ] + "never_completed" => [ "red", "Never Completed" ], "conditional" => [ "gray", "Conditional" ], + "not_applicable" => [ "gray", "N/A" ] }.freeze def compliance_badge(status) @@ -49,6 +50,13 @@ module ApplicationHelper tag.span(DocumentCollection::VISIBILITIES[visibility], class: "badge-#{color}") end + # AD number, linked to its document (opens in a new tab) when we have a link. + def ad_link(ad) + link = ad.reference_link + return ad.name unless link + link_to ad.name, link[0], class: "link", target: "_blank", rel: "noopener noreferrer", title: link[1] + end + def delete_button(label, path, confirm: "Are you sure?", **opts) button_to label, path, method: :delete, form: { data: { turbo_confirm: confirm }, class: "inline" }, class: opts[:class] || "btn-danger btn-sm" diff --git a/app/javascript/controllers/next_due_controller.js b/app/javascript/controllers/next_due_controller.js index b941f3b..fc2f0f8 100644 --- a/app/javascript/controllers/next_due_controller.js +++ b/app/javascript/controllers/next_due_controller.js @@ -40,7 +40,7 @@ export default class extends Controller { if (!this.hasPreviewTarget) return const rule = this.currentRule let text - if (this.isPermanent) text = "Permanent compliance: never due again." + if (this.isPermanent) text = "Permanent compliance or not applicable: never due again." else if (!this.ruleTarget.value) text = "" else if (!rule) text = "One-time: no recurring due date." else { @@ -60,6 +60,6 @@ export default class extends Controller { } get isPermanent() { - return this.hasPermanentTarget && this.permanentTarget.checked + return this.permanentTargets.some((el) => el.checked) } } diff --git a/app/models/ad_compliance.rb b/app/models/ad_compliance.rb index bbdd454..cb572c2 100644 --- a/app/models/ad_compliance.rb +++ b/app/models/ad_compliance.rb @@ -15,12 +15,15 @@ class AdCompliance < ApplicationRecord # Prefill next_due_at_time from the AD's hour recurrence (hours at compliance # + interval). Only fills a blank/zero value, so a typed-in reading wins. def fill_next_due - return if permanent? || airworthiness_directive.nil? + return if closed? || airworthiness_directive.nil? base = aircraft_hours_at_compliance || aircraft&.tach_time due = Compliance.next_due(airworthiness_directive.due_rule, date: date_complied, hours: base) self.next_due_at_time = due[:hours] if due[:hours] end + # Permanent compliance or a not-applicable determination: never due again. + def closed? = permanent? || not_applicable? + def self.for_aircraft(aircraft) where(aircraft_id: aircraft.id).or(where(component_id: aircraft.components.select(:id))) end @@ -31,7 +34,7 @@ class AdCompliance < ApplicationRecord # easy mistake of entering "100" for "every 100 hours". def next_due_is_a_future_reading due = next_due_at_time.to_d - return if permanent? || due <= 0 + return if closed? || due <= 0 base = aircraft_hours_at_compliance || aircraft&.tach_time return unless base && due <= base errors.add(:next_due_at_time, "must be a tach reading after the compliance hours (#{base}). " \ diff --git a/app/models/aircraft.rb b/app/models/aircraft.rb index f973053..5c4c3d3 100644 --- a/app/models/aircraft.rb +++ b/app/models/aircraft.rb @@ -28,6 +28,8 @@ class Aircraft < ApplicationRecord validates :tail_number, presence: true validates :status, inclusion: { in: STATUSES.keys } + validates :drs_search_url, format: { with: %r{\Ahttps://drs\.faa\.gov/\S*\z}, message: "must be a https://drs.faa.gov/ link" }, allow_blank: true + normalizes :drs_search_url, with: ->(url) { url.strip.sub(/#.*\z/, "").presence } validate :picture_is_image scope :ordered, -> { order(:tail_number) } diff --git a/app/models/airworthiness_directive.rb b/app/models/airworthiness_directive.rb index 989c1d0..d95017a 100644 --- a/app/models/airworthiness_directive.rb +++ b/app/models/airworthiness_directive.rb @@ -14,9 +14,20 @@ class AirworthinessDirective < ApplicationRecord validates :name, :short_description, presence: true validates :compliance_type, inclusion: { in: COMPLIANCE_TYPES.keys } validates :bulletin_type, inclusion: { in: BULLETIN_TYPES.keys } + validates :document_url, format: { with: %r{\Ahttps?://\S+\z}i, message: "must be an http(s) link" }, allow_blank: true + normalizes :document_url, with: ->(url) { url.strip.presence } scope :ordered, -> { order(:name) } + # "2009-10-09 r2" → "2009-10-09 R2" + def self.normalize_number(number) + number.to_s.strip.upcase.gsub(/\s+/, " ") + end + + def self.find_by_number(number) + find_by("upper(replace(name, ' ', '')) = ?", normalize_number(number).delete(" ")) + end + def self.applicable_to(aircraft) direct = joins(:aircraft).where(aircraft: { id: aircraft.id }).select(:id) via_component = joins(:components).where(components: { aircraft_id: aircraft.id }).select(:id) @@ -24,6 +35,14 @@ class AirworthinessDirective < ApplicationRecord end def to_s = name + + # [url, label] for this AD's document, when we have its link (DRS Excel + # exports carry one per AD; it can also be pasted in). DRS links use an + # internal document id, so they can't be derived from the AD number. + def reference_link + [ document_url, "View AD" ] if document_url.present? + end + def conditional? = compliance_type == "conditional" def bulletin_label = BULLETIN_LABELS[bulletin_type] diff --git a/app/services/ad_import.rb b/app/services/ad_import.rb new file mode 100644 index 0000000..dde7960 --- /dev/null +++ b/app/services/ad_import.rb @@ -0,0 +1,233 @@ +require "roo" + +# Imports Airworthiness Directives from an FAA DRS (drs.faa.gov) export +# (.csv or .xlsx) for one aircraft. Each row becomes a shared +# AirworthinessDirective linked to the aircraft (matched by AD number, so +# re-imports and ADs entered by hand aren't duplicated). +# +# Per AD the owner chooses: track (needs a compliance record), not applicable +# (records an N/A determination), or skip. The preview suggests a choice and +# flags things worth checking: non-current/superseded ADs, a model that isn't +# listed, appliance or STC-only ADs, repetitive actions, and older ADs this +# one supersedes that the aircraft still tracks. +class AdImport + class Error < StandardError; end + + ACTIONS = { "track" => "Track", "na" => "Not applicable", "skip" => "Skip" }.freeze + NA_NOTE = "Not applicable (marked during FAA DRS import)".freeze + + # DRS export headers, normalized (lowercase letters only). + HEADERS = { + number: "adnumber", heading: "subjectheading", subject: "subject", status: "status", + effective_date: "effectivedate", docket: "docketnumber", models: "model", + product_type: "producttype", supersedes: "supersededad", superseded_by: "supersededby", + summary: "summary" + }.freeze + + # AD attributes that come from the FAA and are refreshed on every import: + # attribute => [label shown in the preview, value from the row]. + FAA_FIELDS = { + short_description: [ "Subject", ->(r) { r.subject.to_s.truncate(254).presence } ], + required_action: [ "Summary", ->(r) { r.summary } ], + effective_date: [ "Effective date", ->(r) { r.effective_date } ], + docket_number: [ "Docket", ->(r) { r.docket } ], + supersedes: [ "Supersedes", ->(r) { r.supersedes.join(", ").presence } ], + superseded_by: [ "Superseded by", ->(r) { r.superseded_by.join(", ").presence } ], + applicable_models: [ "Models", ->(r) { r.models.join(", ").presence } ], + product_type: [ "Product type", ->(r) { r.product_type } ], + document_url: [ "DRS link", ->(r) { r.url } ] + }.freeze + + Row = Struct.new(:line, :number, :subject, :status, :effective_date, :docket, :models, :product_type, + :supersedes, :superseded_by, :summary, :url, :existing, :tracked, :suggested, :notes, :changes, + keyword_init: true) do + def note(msg) = notes << msg + end + + def initialize(aircraft, path:, filename:) + @aircraft = aircraft + @path = path.to_s + @filename = filename.to_s + end + + def rows + @rows ||= build_rows + end + + def count(action) = rows.count { _1.suggested == action } + + # decisions: { "AD number" => "track" | "na" | "skip" }; missing → suggested. + # "track" on an AD that's already tracked means "update it from the file". + # Returns { tracked:, not_applicable:, skipped:, updated: }. + def import!(decisions:, user:) + result = { tracked: 0, not_applicable: 0, skipped: 0, updated: 0 } + AirworthinessDirective.transaction do + rows.each do |row| + action = decisions.fetch(row.number, row.suggested).to_s + action = "skip" unless ACTIONS.key?(action) + if action == "skip" + result[:skipped] += 1 + next + end + + ad = upsert_ad(row) + result[:updated] += 1 if row.existing && row.changes.any? + ad.aircraft << @aircraft unless ad.aircraft.include?(@aircraft) + if action == "na" + unless ad.latest_compliance_for(@aircraft)&.not_applicable? + ad.ad_compliances.create!(aircraft: @aircraft, date_complied: Date.current, + not_applicable: true, compliance_notes: NA_NOTE) + end + result[:not_applicable] += 1 + else + result[:tracked] += 1 + end + end + imported = result[:tracked] + result[:not_applicable] + raise Error, "Nothing selected to import." if imported.zero? + @aircraft.log_event!("ad", "Imported #{imported} ADs from FAA DRS", user: user, + notes: "#{@filename}: #{result[:tracked]} tracked, #{result[:not_applicable]} N/A, #{result[:skipped]} skipped") + end + result + end + + private + + def build_rows + sheet, header_index, cols = locate_header + tracked_numbers = @aircraft.applicable_ads.pluck(:name).map { AirworthinessDirective.normalize_number(_1) }.to_set + # Accept "150L" or "Cessna 150L" as the aircraft's model. + model = AirworthinessDirective.normalize_number(@aircraft.model) + model_names = [ model, model.split.last ].compact_blank.uniq + + ((header_index + 1)..sheet.last_row).filter_map do |i| + raw = sheet.row(i) + number = AirworthinessDirective.normalize_number(raw[cols[:number]]) + next if number.empty? + + cell = ->(key) { (idx = cols[key]) ? raw[idx] : nil } + row = Row.new( + line: i, number: number, + subject: text(cell.(:subject)).presence || text(cell.(:heading)), + status: text(cell.(:status)), + effective_date: parse_date(cell.(:effective_date)), + docket: text(cell.(:docket)).then { _1 == "Unknown" ? nil : _1.presence }, + models: list(cell.(:models)), + product_type: text(cell.(:product_type)).presence, + supersedes: list(cell.(:supersedes)), + superseded_by: list(cell.(:superseded_by)), + summary: clean_summary(cell.(:summary)), + url: row_link(sheet, i, raw, cols), + notes: [] + ) + row.existing = AirworthinessDirective.find_by_number(number) + row.tracked = tracked_numbers.include?(number) + row.changes = row.existing ? changed_fields(row.existing, row) : [] + row.suggested = "track" + + if row.existing + prefix = row.tracked ? "Already tracked" : "Matches an AD already in the system; it will be linked" + row.note(row.changes.any? ? "#{prefix}. Will update: #{row.changes.join(', ')}" : "#{prefix}. Up to date") + end + + # Reasons not to add a NEW AD. An AD that's already tracked is still + # updated (so supersession and links reach it), just flagged for review. + skip_reasons = [] + skip_reasons << "FAA status: #{row.status}" if row.status.present? && !row.status.casecmp?("current") + skip_reasons << "Superseded by #{row.superseded_by.join(', ')}" if row.superseded_by.any? + if model_names.any? && row.models.any? && (row.models.map { AirworthinessDirective.normalize_number(_1) } & model_names).empty? + skip_reasons << "Your model (#{@aircraft.model}) isn't in this AD's model list" + end + skip_reasons.each { row.note(row.tracked ? "#{_1}: review whether it still applies" : _1) } + row.suggested = "skip" if skip_reasons.any? && !row.tracked + if row.product_type&.casecmp?("appliance") + row.note("Appliance AD: applies only if that equipment is installed") + end + if row.summary =~ /Supplemental Type Certificate|\bSTC\b/i + row.note("Mentions an STC: may apply only if that modification is installed") + end + if row.summary =~ /repetitive|recurring|reinspect/i + row.note("Mentions repetitive actions: set the recurrence after import") + end + (row.supersedes & tracked_numbers.to_a).each do |old| + row.note("Supersedes #{old}, which this aircraft still tracks; consider removing it") + end + row + end + end + + # FAA data is authoritative: every FAA field present in the file replaces + # what's stored. Fields the file leaves blank are kept. Compliance records, + # recurrence and applicability are never touched by an import. + def upsert_ad(row) + ad = row.existing || AirworthinessDirective.new(name: row.number, bulletin_type: "ad", mandatory: true) + ad.assign_attributes(faa_attributes(row)) + ad.short_description = row.number if ad.short_description.blank? + ad.save! + ad + end + + def faa_attributes(row) + FAA_FIELDS.transform_values { |(_, value)| value.(row) }.compact + end + + def changed_fields(ad, row) + faa_attributes(row).filter_map { |attr, value| FAA_FIELDS[attr][0] if ad.public_send(attr) != value } + end + + def locate_header + book = open_spreadsheet + book.sheets.each do |name| + sheet = book.sheet(name) + next unless sheet.first_row + (sheet.first_row..[ sheet.first_row + 10, sheet.last_row ].min).each do |i| + normalized = sheet.row(i).map { _1.to_s.downcase.gsub(/[^a-z]/, "") } + next unless normalized.include?(HEADERS[:number]) + cols = HEADERS.transform_values { normalized.index(_1) }.compact + link_col = normalized.index { _1.include?("link") || _1.include?("url") } + cols[:url] = link_col if link_col + return [ sheet, i, cols ] + end + end + raise Error, "This doesn't look like an FAA DRS export: no “AD Number” column found." + end + + def open_spreadsheet + ext = File.extname(@filename).delete(".").downcase + raise Error, "Upload an .xlsx or .csv file." unless ext.in?(%w[xlsx csv]) + Roo::Spreadsheet.open(@path, extension: ext.to_sym) + rescue Zip::Error, ArgumentError, CSV::MalformedCSVError => e + raise Error, "Couldn't read the file (#{e.message})." + end + + # Link to the AD document: a hyperlink on any cell in the row (Excel exports), + # a link/URL column, or a bare URL in any cell. Only http(s) links are kept. + def row_link(sheet, line, raw, cols) + candidates = [] + if sheet.respond_to?(:hyperlink) + order = [ cols[:number], *raw.each_index.to_a ].compact.uniq + candidates += order.map { |c| sheet.hyperlink(line, c + 1) rescue nil } + end + candidates << raw[cols[:url]] if cols[:url] + candidates += raw.map(&:to_s) + candidates.map { _1.to_s.strip }.find { _1.match?(%r{\Ahttps?://\S+\z}i) } + end + + def text(value) = value.to_s.strip + + def list(value) + text(value).split(/\s*[|;,]\s*/).map(&:strip).reject(&:empty?) + end + + def parse_date(value) + return value.to_date if value.respond_to?(:to_date) && !value.is_a?(String) + Date.strptime(value.to_s.strip, "%m/%d/%Y") + rescue ArgumentError, TypeError + nil + end + + # Federal Register text arrives with literal "\n" sequences and page markers. + def clean_summary(value) + text(value).gsub(/\\n|\r?\n/, " ").gsub(/\(\(Page \d+\)\)/, " ").squeeze(" ").strip.presence + end +end diff --git a/app/services/compliance.rb b/app/services/compliance.rb index b992c7c..e95f08c 100644 --- a/app/services/compliance.rb +++ b/app/services/compliance.rb @@ -36,7 +36,7 @@ module Compliance def ad_status(ad, compliance, current_hours, today = Date.current) return Result.new(rank: COMPLIANT) if ad.conditional? return Result.new(rank: OVERDUE) unless compliance - return Result.new(rank: COMPLIANT) if compliance.permanent? + return Result.new(rank: COMPLIANT) if compliance.closed? rank = COMPLIANT result = Result.new @@ -109,6 +109,7 @@ module Compliance status = if ad.conditional? then latest ? "compliant" : "conditional" elsif latest.nil? then "no_compliance" + elsif latest.not_applicable? then "not_applicable" elsif latest.permanent? then "compliant" end res = ad_status(ad, latest, hours) unless status diff --git a/app/views/ad_compliances/_form.html.erb b/app/views/ad_compliances/_form.html.erb index b660c69..bb8dacc 100644 --- a/app/views/ad_compliances/_form.html.erb +++ b/app/views/ad_compliances/_form.html.erb @@ -18,7 +18,10 @@ <%= f.field :permanent, as: :checkbox, label: "Permanently complied (terminating action)", data: { next_due_target: "permanent", action: "change->next-due#changed" } %> - <%= f.field :compliance_notes, as: :textarea, label: "Method of compliance", rows: 3, required: true %> + <%= f.field :not_applicable, as: :checkbox, label: "Not applicable to this aircraft", + hint: "E.g. serial number outside the affected range, or the equipment isn't installed. Record why below.", + data: { next_due_target: "permanent", action: "change->next-due#changed" } %> + <%= f.field :compliance_notes, as: :textarea, label: "Method of compliance / reason", rows: 3, required: true %>
<%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %>
<% end %> <% if compliance.persisted? %>
<%= delete_button "Delete record", aircraft_ad_compliance_path(aircraft, compliance) %>
<% end %> diff --git a/app/views/ad_imports/new.html.erb b/app/views/ad_imports/new.html.erb new file mode 100644 index 0000000..cab9177 --- /dev/null +++ b/app/views/ad_imports/new.html.erb @@ -0,0 +1,24 @@ +<% content_for :title, "Import ADs" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +
+ <%= form_with url: aircraft_ad_import_path(@aircraft), multipart: true, class: "card card-body space-y-4 lg:col-span-2" do |f| %> +

Import ADs from the FAA DRS

+
+ <%= f.label :file, "DRS export (.csv or .xlsx)", class: "label" %> + <%= f.file_field :file, accept: ".xlsx,.csv", required: true, + class: "block text-sm text-slate-600 file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-1.5 file:text-sm file:font-medium hover:file:bg-slate-200" %> +
+ <%= f.submit "Upload & Preview", class: "btn-primary" %> +

Nothing is saved until you confirm on the next page.

+ <% end %> +
+

Getting the file

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

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

<% end %> +

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

+
+
diff --git a/app/views/ad_imports/show.html.erb b/app/views/ad_imports/show.html.erb new file mode 100644 index 0000000..ff57b6a --- /dev/null +++ b/app/views/ad_imports/show.html.erb @@ -0,0 +1,54 @@ +<% content_for :title, "AD Import Preview" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<% rows = @import.rows %> +<%= form_with url: confirm_aircraft_ad_import_path(@aircraft), class: "space-y-5" do |f| %> + <%= hidden_field_tag :token, @token %> + <%= hidden_field_tag :filename, @filename %> +
+
+

Preview: <%= @filename %>

+ <%= pluralize(rows.size, "AD") %> found · <%= rows.count(&:url) %> with DRS links +
+
+ <% if rows.none?(&:url) %>

This file has no links to the AD documents. DRS's Excel export includes them; import that file instead (or afterwards) to get clickable AD numbers.

<% end %> +

Choose what to do with each AD. The suggestions are based on the FAA data and your aircraft's model (<%= @aircraft.model.presence || "not set" %>); you make the call.

+
    +
  • Track: adds the AD. Until you record compliance, it counts against airworthiness, so <%= @aircraft.tail_number %> will show Not Airworthy for each tracked AD without a compliance record.
  • +
  • Not applicable: adds the AD with an N/A record (e.g. the equipment isn't installed). You can edit the reason afterwards.
  • +
  • Update (ADs already tracked): refreshes the FAA details: subject, summary, dates, supersession and DRS link. Compliance records aren't touched.
  • +
  • Skip: not imported, or left exactly as is.
  • +
+
+
+ +
+
+ + + + <% rows.each do |r| %> + + + + + + + + <% end %> + +
ADSubjectEffectiveNotesAction
<%= r.number %><%= link_to " 🔗", r.url, target: "_blank", rel: "noopener noreferrer", title: "Link found in file" if r.url %> + <% if r.product_type %>
<%= r.product_type %>
<% end %>
+ <%= r.subject %> + <% if r.summary %>
Summary<%= r.summary %>
<% end %> +
<%= r.effective_date %> + <% r.notes.each do |n| %>
">• <%= n %>
<% end %> +
<% choices = r.tracked ? [ [ "Update", "track" ], [ "Not applicable", "na" ], [ "Skip (leave as is)", "skip" ] ] : AdImport::ACTIONS.invert %> + <%= select_tag "decisions[#{r.number}]", options_for_select(choices, r.suggested), class: "input" %>
+
+
+ +
+ <%= f.submit "Import ADs", class: "btn-primary", data: { turbo_confirm: "Import these ADs to #{@aircraft.tail_number}?" } %> + <%= link_to "Upload a different file", new_aircraft_ad_import_path(@aircraft), class: "btn-secondary" %> +
+<% end %> diff --git a/app/views/aircraft/_form.html.erb b/app/views/aircraft/_form.html.erb index 46f7a27..34e6392 100644 --- a/app/views/aircraft/_form.html.erb +++ b/app/views/aircraft/_form.html.erb @@ -20,6 +20,8 @@ <% unless aircraft.new_record? %>

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

<% end %> + <%= f.field :drs_search_url, label: "FAA DRS AD search link", placeholder: "https://drs.faa.gov/browse/ADFRAWD/doctypeDetails?…", + hint: "Run the AD search for this aircraft on drs.faa.gov and paste the page link. The ADs tab then gets a one-click “Open in DRS” button." %> <%= f.field :picture, as: :file, accept: "image/*" %> <%= f.field :airworthiness_enforcement, as: :checkbox, label: "Enforce airworthiness", hint: "Block flight logs and hours updates while the aircraft is red." %> diff --git a/app/views/airworthiness_directives/_form.html.erb b/app/views/airworthiness_directives/_form.html.erb index 649382f..1f58742 100644 --- a/app/views/airworthiness_directives/_form.html.erb +++ b/app/views/airworthiness_directives/_form.html.erb @@ -18,6 +18,8 @@ <%= f.field :recurring_months, as: :number, label: "Every (months)" %> <%= f.field :document_id, as: :select, label: "Reference document", collection: document_options(aircraft) %> + <%= f.field :document_url, label: "Link to AD document", placeholder: "https://…", + hint: "Filled in automatically from a DRS Excel export. In DRS, open the AD and copy its link." %> <%= render "shared/applicability_fields", aircraft: aircraft, record: ad, applies_to_airframe: @applies_to_airframe %> <% if ad.persisted? && (ad.aircraft.count + ad.components.where.not(aircraft_id: aircraft.id).count) > 1 %>

This AD is shared with other aircraft; edits affect them too.

diff --git a/app/views/airworthiness_directives/index.html.erb b/app/views/airworthiness_directives/index.html.erb index a54c8d5..daf66d9 100644 --- a/app/views/airworthiness_directives/index.html.erb +++ b/app/views/airworthiness_directives/index.html.erb @@ -11,6 +11,8 @@ <%= f.submit "Link existing", class: "btn-secondary" %> <% end %> <% end %> + <% if @aircraft.drs_search_url.present? %><%= link_to "Open in DRS ↗", @aircraft.drs_search_url, class: "btn-secondary", target: "_blank", rel: "noopener noreferrer" %><% end %> + <%= link_to "Import from FAA DRS", new_aircraft_ad_import_path(@aircraft), class: "btn-secondary" %> <%= link_to "+ New AD", new_aircraft_airworthiness_directive_path(@aircraft), class: "btn-primary" %> <% end %> @@ -22,9 +24,12 @@ <% @rows.each do |row| ad = row.ad %> - <%= ad.bulletin_label %><%= ad.name %> + <%= ad.bulletin_label %><%= ad_link(ad) %> + <% if ad.document %><%= link_to "📄", aircraft_document_path(@aircraft, ad.document), title: ad.document.name %><% end %> <% unless ad.mandatory? %>
not mandatory
<% end %> <%= ad.short_description %> + <% if ad.effective_date || ad.product_type.present? %>
<%= [(ad.effective_date && "Effective #{ad.effective_date}"), ad.product_type.presence].compact.join(" · ") %>
<% end %> + <% if ad.superseded_by.present? %>
Superseded by <%= ad.superseded_by %>
<% end %> <% if ad.conditional? && ad.trigger_condition.present? %>
Trigger: <%= ad.trigger_condition %>
<% end %> <%= ad.recurring? ? [ad.recurring_hours.to_f > 0 && "#{hours(ad.recurring_hours)} h", ad.recurring_months > 0 && "#{ad.recurring_months} mo"].select(&:itself).join(" / ") : "One-time" %> <%= row.latest ? "#{row.latest.date_complied}#{' (permanent)' if row.latest.permanent?}" : "—" %> @@ -33,6 +38,7 @@ <% if owner? %> <%= link_to "Comply", new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id), class: "btn-secondary btn-sm" %> + <% if row.status.in?(%w[no_compliance overdue due_soon conditional]) %><%= link_to "N/A", new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id, not_applicable: 1), class: "btn-secondary btn-sm", title: "Record that this AD doesn't apply to this aircraft" %><% end %> <%= link_to "Edit", edit_aircraft_airworthiness_directive_path(@aircraft, ad), class: "btn-secondary btn-sm" %> <% end %> @@ -55,10 +61,23 @@ <% @history.each do |c| %> <%= c.date_complied %> - <%= c.airworthiness_directive.name %><%= " (#{c.component})" if c.component %> + <% ad = c.airworthiness_directive %> + + <%= ad_link(ad) %> + <% if ad.document %><%= link_to "📄", aircraft_document_path(@aircraft, ad.document), title: ad.document.name %><% end %> +
<%= ad.short_description %><%= " · #{c.component}" if c.component %>
+ <%= hours(c.aircraft_hours_at_compliance) %> - <%= c.permanent? ? "Permanent" : (c.next_due_at_time.to_f > 0 ? hours(c.next_due_at_time) : "—") %> - <%= c.compliance_notes %> + <%= c.not_applicable? ? "N/A" : c.permanent? ? "Permanent" : (c.next_due_at_time.to_f > 0 ? hours(c.next_due_at_time) : "—") %> + + <%= c.compliance_notes %> + <% if c.logbook_entry || c.inspection_record %> +
+ <% if c.logbook_entry %><%= link_to "Logbook #{c.logbook_entry.date}", aircraft_logbook_entry_path(@aircraft, c.logbook_entry), class: "link" %><% end %> + <% if c.inspection_record %><%= link_to "#{c.inspection_record.inspection_type.name} #{c.inspection_record.date}", aircraft_inspections_path(@aircraft), class: "link" %><% end %> +
+ <% end %> + <% if owner? %><%= link_to "Edit", edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %> <% end %> diff --git a/app/views/shared/show.html.erb b/app/views/shared/show.html.erb index b2d31c3..da4f45c 100644 --- a/app/views/shared/show.html.erb +++ b/app/views/shared/show.html.erb @@ -59,7 +59,7 @@

ADs

<% @ad_rows.each do |r| %> - <% end %>
<%= r.ad.name %>
<%= r.ad.short_description %>
<%= r.latest&.date_complied || "—" %><%= compliance_badge(r.status) %>
+ <%= ad_link(r.ad) %>
<%= r.ad.short_description %>
<%= r.latest&.date_complied || "—" %><%= compliance_badge(r.status) %><% end %>
@@ -87,7 +87,7 @@

Inspection History

<% @inspection_history.each do |r| %><% end %>
<%= r.date %><%= r.inspection_type.name %><%= hours(r.hours_at_inspection) %>

AD Compliance History

- <% @ad_history.each do |c| %><% end %>
<%= c.date_complied %><%= c.airworthiness_directive.name %><%= c.compliance_notes %>
+ <% @ad_history.each do |c| %><% end %>
<%= c.date_complied %><%= ad_link(c.airworthiness_directive) %>
<%= c.airworthiness_directive.short_description %>
<%= c.not_applicable? ? "N/A: " : "" %><%= c.compliance_notes %>

Major Repairs & Alterations

diff --git a/config/routes.rb b/config/routes.rb index 78fec7b..851dec3 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -34,6 +34,9 @@ Rails.application.routes.draw do collection { post :attach } end resources :ad_compliances, except: %i[index show] + resource :ad_import, only: %i[new create show] do + post :confirm + end resources :major_records resources :aircraft_roles, path: "access", only: %i[index create update destroy] resources :share_tokens, only: %i[create destroy] diff --git a/db/migrate/20261105120000_add_faa_fields_to_ads.rb b/db/migrate/20261105120000_add_faa_fields_to_ads.rb new file mode 100644 index 0000000..5d3d4cb --- /dev/null +++ b/db/migrate/20261105120000_add_faa_fields_to_ads.rb @@ -0,0 +1,13 @@ +class AddFaaFieldsToAds < ActiveRecord::Migration[8.1] + def change + add_column :airworthiness_directives, :effective_date, :date + add_column :airworthiness_directives, :supersedes, :string + add_column :airworthiness_directives, :superseded_by, :string + add_column :airworthiness_directives, :docket_number, :string + add_column :airworthiness_directives, :applicable_models, :text + add_column :airworthiness_directives, :product_type, :string + + # Per-aircraft "this AD does not apply" determination (e.g. equipment not installed). + add_column :ad_compliances, :not_applicable, :boolean, null: false, default: false + end +end diff --git a/db/migrate/20261105200000_add_drs_links.rb b/db/migrate/20261105200000_add_drs_links.rb new file mode 100644 index 0000000..727c906 --- /dev/null +++ b/db/migrate/20261105200000_add_drs_links.rb @@ -0,0 +1,8 @@ +# Links to FAA DRS: per-AD document link and the owner's saved DRS search. +# Guarded because these columns were briefly part of an earlier migration. +class AddDrsLinks < ActiveRecord::Migration[8.1] + def change + add_column :airworthiness_directives, :document_url, :string unless column_exists?(:airworthiness_directives, :document_url) + add_column :aircraft, :drs_search_url, :string unless column_exists?(:aircraft, :drs_search_url) + end +end diff --git a/db/schema.rb b/db/schema.rb index a5ff998..6e057ab 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.0].define(version: 2026_11_04_222400) do +ActiveRecord::Schema[8.1].define(version: 2026_11_05_200000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -52,6 +52,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_04_222400) do t.decimal "aircraft_hours_at_compliance", precision: 8, scale: 1 t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.boolean "not_applicable", default: false, null: false t.index ["aircraft_id"], name: "index_ad_compliances_on_aircraft_id" t.index ["airworthiness_directive_id"], name: "index_ad_compliances_on_airworthiness_directive_id" t.index ["component_id"], name: "index_ad_compliances_on_component_id" @@ -74,6 +75,7 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_04_222400) do t.boolean "airworthiness_enforcement", default: false, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.string "drs_search_url" end create_table "aircraft_airworthiness_directives", id: false, force: :cascade do |t| @@ -138,6 +140,13 @@ ActiveRecord::Schema[8.0].define(version: 2026_11_04_222400) do t.integer "document_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.date "effective_date" + t.string "supersedes" + t.string "superseded_by" + t.string "docket_number" + t.text "applicable_models" + t.string "product_type" + t.string "document_url" t.index ["document_id"], name: "index_airworthiness_directives_on_document_id" end diff --git a/test/fixtures/files/drs_ads.csv b/test/fixtures/files/drs_ads.csv new file mode 100644 index 0000000..38e09fc --- /dev/null +++ b/test/fixtures/files/drs_ads.csv @@ -0,0 +1,6 @@ +AD Number,Subject Heading,Subject,Status,CFR Part Reference,Effective Date,Service/Office,Office of Primary Responsibility,Docket Number,Citation,Citation Publish Date,Make,Model,Product Type,Product Subtype,Affected AD,Superseded AD,Affected By,Superseded By,AC Reference,AIR Policy Reference,Additional Reference,Summary,Comments +2011-10-09,"Airworthiness Directives; Cessna Aircraft Company Models 150, 152 Airplanes",Seat Rails and Roller Housing Inspections,Current,Part 39,06/17/2011,,,FAA-2010-1101,"(Federal Register Volume 76, Number 93 (Friday, May 13, 2011))",05/13/2011,Cessna Aircraft Company,150L | 150M | 152,Aircraft,Small Airplane,,87-20-03 R2,,,,,,"We are superseding an existing airworthiness directive (AD). That AD currently requires repetitive inspections and replacement of parts, if necessary, \n\n((Page 27866)) \n\nof the seat rail and seat rail holes.", +2008-22-18,Airworthiness Directives; Cessna Aircraft Company 150 Series Airplanes,"Ballistic Recovery Systems, Inc. (BRS)",Current,Part 39,12/09/2008,,,FAA-2008-0790,"Federal Register: November 4, 2008",11/04/2008,Cessna Aircraft Company,150L | 150M | 152,Aircraft,Small Airplane,,,,,,,,"This AD applies to airplanes with the BRS-150 Parachute System installed via Supplemental Type Certificate (STC) SA64CH.", +96-12-22,Airworthiness Directives; Cessna Aircraft Company Engine Oil Filter Adapter Assemblies Installed on Aircraft,Full Flow Engine Oil Adapter,Current,Part 39,07/31/1996,AIR-700,AIR-720,93-CE-54-AD,"(Federal Register: June 17, 1996)",06/17/1996,Cessna Aircraft Company | Continental Motors,150L | 150M | O-200-A,Appliance,,,,,,,,,"This action requires inspecting the oil filter adapter and repetitively inspecting the torque putty.", +75-15-08,"Airworthiness Directives; BEECH AND CESSNA Models 35, 150",Engine Lubrication,Current,Part 39,09/10/1975,,,Unknown,This information is not available.,,Cessna Aircraft Company,150K | 150L | A150L,Aircraft,Small Airplane,,,,,,,,, +87-20-03 R2,Airworthiness Directives; Cessna Aircraft Company Airplanes,Seat Rails,Historical,Part 39,11/02/1987,,,Unknown,This information is not available.,,Cessna Aircraft Company,150L | 150M,Aircraft,Small Airplane,,,,2011-10-09,,,,, diff --git a/test/integration/ad_import_flow_test.rb b/test/integration/ad_import_flow_test.rb new file mode 100644 index 0000000..4244a74 --- /dev/null +++ b/test/integration/ad_import_flow_test.rb @@ -0,0 +1,66 @@ +require "test_helper" + +class AdImportFlowTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user + @pilot = create_user + @aircraft = create_aircraft(owner: @owner, pilot: @pilot, model: "150L") + end + + test "owner uploads, reviews, and imports" do + sign_in @owner + get aircraft_airworthiness_directives_path(@aircraft) + assert_select "a[href='#{new_aircraft_ad_import_path(@aircraft)}']" + + post aircraft_ad_import_path(@aircraft), params: { file: fixture_file_upload("drs_ads.csv", "text/csv") } + assert_response :redirect + follow_redirect! + assert_response :success + assert_select "select[name='decisions[2011-10-09]'] option[selected][value='track']" + assert_select "select[name='decisions[87-20-03 R2]'] option[selected][value='skip']" + assert_match "Excel export includes them", response.body + token = response.body[/name="token"[^>]*value="([^"]+)"/, 1] + + post confirm_aircraft_ad_import_path(@aircraft), params: { + token: token, filename: "AD Final Rules.csv", + decisions: { "2011-10-09" => "track", "2008-22-18" => "na", "96-12-22" => "skip", "75-15-08" => "skip", "87-20-03 R2" => "skip" } + } + assert_redirected_to aircraft_airworthiness_directives_path(@aircraft) + assert_equal %w[2008-22-18 2011-10-09], @aircraft.applicable_ads.order(:name).pluck(:name) + follow_redirect! + assert_select "span", text: "N/A" + # CSV exports carry no links, so the AD number isn't a link + assert_select "a", text: "2011-10-09", count: 0 + end + + test "N/A quick action records a not-applicable determination" do + ad = AirworthinessDirective.create!(name: "2008-22-18", short_description: "BRS") + ad.aircraft << @aircraft + sign_in @owner + get new_aircraft_ad_compliance_path(@aircraft, ad_id: ad.id, not_applicable: 1) + assert_select "input[name='ad_compliance[not_applicable]'][checked]" + post aircraft_ad_compliances_path(@aircraft), params: { ad_compliance: { + airworthiness_directive_id: ad.id, date_complied: Date.current, not_applicable: "1", + compliance_notes: "Not applicable: no BRS parachute installed" } } + assert_equal "GREEN", @aircraft.reload.airworthiness.status + end + + test "saved DRS search link shows an Open in DRS button; only drs.faa.gov links allowed" do + sign_in @owner + url = "https://drs.faa.gov/browse/ADFRAWD/doctypeDetails?Status=Current&Make=Cessna%20Aircraft%20Company&Model=150L#:~:text=Save-,Results" + patch aircraft_path(@aircraft), params: { aircraft: { drs_search_url: url } } + assert_equal url.sub(/#.*/, ""), @aircraft.reload.drs_search_url + get aircraft_airworthiness_directives_path(@aircraft) + assert_select "a[href='#{@aircraft.drs_search_url}']", text: "Open in DRS ↗" + + patch aircraft_path(@aircraft), params: { aircraft: { drs_search_url: "https://evil.example/drs.faa.gov" } } + assert_response :unprocessable_entity + end + + test "pilots cannot import ADs" do + sign_in @pilot + post aircraft_ad_import_path(@aircraft), params: { file: fixture_file_upload("drs_ads.csv", "text/csv") } + assert_response :redirect + assert_equal 0, @aircraft.applicable_ads.count + end +end diff --git a/test/integration/pages_test.rb b/test/integration/pages_test.rb index ab53e39..28790c6 100644 --- a/test/integration/pages_test.rb +++ b/test/integration/pages_test.rb @@ -67,6 +67,21 @@ class PagesTest < ActionDispatch::IntegrationTest assert_select "form[data-controller='next-due'][data-next-due-rules-value*='\"months\":12']" end + test "compliance history shows the AD's description and links" do + @ad.update!(document_url: "https://drs.faa.gov/browse/excelExternalWindow/ABC.0001") + @adc.update!(logbook_entry: @entry) + get aircraft_airworthiness_directives_path(@a) + assert_select "section", text: /Compliance History/ do + assert_select "a[href='https://drs.faa.gov/browse/excelExternalWindow/ABC.0001'][target='_blank']", text: "2020-01-01" + assert_select "div", text: "Check" + assert_select "a[href='#{aircraft_logbook_entry_path(@a, @entry)}']" + end + + delete session_path + get shared_path(@token.token) + assert_select "a[href='https://drs.faa.gov/browse/excelExternalWindow/ABC.0001']", minimum: 2 # status + history + end + test "maintenance share link renders without login and shows history" do delete session_path get shared_path(@token.token) diff --git a/test/models/airworthiness_directive_test.rb b/test/models/airworthiness_directive_test.rb new file mode 100644 index 0000000..bc4c052 --- /dev/null +++ b/test/models/airworthiness_directive_test.rb @@ -0,0 +1,18 @@ +require "test_helper" + +class AirworthinessDirectiveTest < ActiveSupport::TestCase + def ad(**attrs) = AirworthinessDirective.new({ name: "2011-10-09", short_description: "x" }.merge(attrs)) + + test "stored link wins" do + assert_equal [ "https://drs.faa.gov/x", "View AD" ], ad(document_url: "https://drs.faa.gov/x", docket_number: "FAA-2010-1101").reference_link + end + + test "no guessed links: DRS document ids can't be derived from the AD number" do + assert_nil ad(docket_number: "FAA-2010-1101").reference_link + end + + test "only http(s) links are accepted" do + assert_not ad(document_url: "javascript:alert(1)").valid? + assert ad(document_url: " https://drs.faa.gov/x ").tap(&:valid?).document_url == "https://drs.faa.gov/x" + end +end diff --git a/test/services/ad_import_test.rb b/test/services/ad_import_test.rb new file mode 100644 index 0000000..04aa92a --- /dev/null +++ b/test/services/ad_import_test.rb @@ -0,0 +1,193 @@ +require "test_helper" + +class AdImportTest < ActiveSupport::TestCase + FILE = Rails.root.join("test/fixtures/files/drs_ads.csv") + + setup do + @user = create_user + @aircraft = create_aircraft(owner: @user, make: "Cessna", model: "150L", tach_time: 7290.3) + end + + def import = AdImport.new(@aircraft, path: FILE, filename: "AD Final Rules.csv") + def row(number) = import.rows.find { _1.number == number } + + test "parses the DRS export and cleans the Federal Register text" do + rows = import.rows + assert_equal [ "2011-10-09", "2008-22-18", "96-12-22", "75-15-08", "87-20-03 R2" ], rows.map(&:number) + seat = rows.first + assert_equal "Seat Rails and Roller Housing Inspections", seat.subject + assert_equal Date.new(2011, 6, 17), seat.effective_date + assert_equal "FAA-2010-1101", seat.docket + assert_equal [ "87-20-03 R2" ], seat.supersedes + assert_not_includes seat.summary, "((Page" + assert_not_includes seat.summary, "\\n" + assert_nil rows[3].docket # "Unknown" + end + + test "suggests an action and flags things to check" do + assert_equal "track", row("2011-10-09").suggested + assert_match "repetitive", row("2011-10-09").notes.join + + assert_match "STC", row("2008-22-18").notes.join + assert_match "Appliance", row("96-12-22").notes.join + + old = row("87-20-03 R2") + assert_equal "skip", old.suggested + assert_match "Historical", old.notes.join + assert_match "Superseded by 2011-10-09", old.notes.join + end + + test "skips ADs whose model list doesn't include the aircraft" do + @aircraft.update!(model: "150M") + assert_equal "skip", row("75-15-08").suggested + assert_match "150M", row("75-15-08").notes.join + end + + test "model written with the make still matches" do + @aircraft.update!(model: "Cessna 150L") + assert_equal "track", row("75-15-08").suggested + end + + test "imports with per-AD decisions; tracked ADs need compliance, N/A ones don't" do + result = import.import!(decisions: { "2008-22-18" => "na", "96-12-22" => "skip" }, user: @user) + assert_equal({ tracked: 2, not_applicable: 1, skipped: 2, updated: 0 }, result) + assert_equal %w[2008-22-18 2011-10-09 75-15-08], @aircraft.applicable_ads.order(:name).pluck(:name) + + rows = Compliance.ad_rows(@aircraft).index_by { _1.ad.name } + assert_equal "not_applicable", rows["2008-22-18"].status + assert_equal "no_compliance", rows["2011-10-09"].status + + issues = Airworthiness.new(@aircraft).call.issues.map(&:title) + assert_includes issues, "AD 2011-10-09 - Overdue" + assert_not issues.any? { _1.include?("2008-22-18") } + + ad = AirworthinessDirective.find_by(name: "2011-10-09") + assert_equal "87-20-03 R2", ad.supersedes + assert_includes ad.applicable_models, "150L" + end + + test "re-import updates existing ADs from the FAA data and says what changes" do + mine = AirworthinessDirective.create!(name: "2011-10-09", short_description: "My seat rail notes", recurring: true, recurring_hours: 100) + mine.aircraft << @aircraft + mine.ad_compliances.create!(aircraft: @aircraft, date_complied: Date.current, compliance_notes: "Done", next_due_at_time: 7390.3) + r = row("2011-10-09") + assert_equal "track", r.suggested + assert_match "Already tracked. Will update: Subject, Summary, Effective date, Docket, Supersedes, Models, Product type", r.notes.first + + result = import.import!(decisions: {}, user: @user) + assert_equal 1, result[:updated] + assert_equal 1, AirworthinessDirective.where(name: "2011-10-09").count + mine.reload + assert_equal "Seat Rails and Roller Housing Inspections", mine.short_description + assert_equal Date.new(2011, 6, 17), mine.effective_date + # owner-managed settings and compliance untouched + assert mine.recurring? + assert_equal 100, mine.recurring_hours + assert_equal BigDecimal("7390.3"), mine.ad_compliances.first.next_due_at_time + + assert_match "Up to date", row("2011-10-09").notes.first + end + + test "a tracked AD that's now superseded is updated and flagged, not skipped" do + old = AirworthinessDirective.create!(name: "87-20-03 R2", short_description: "Old seat rail AD") + old.aircraft << @aircraft + r = row("87-20-03 R2") + assert_equal "track", r.suggested + assert_match "Superseded by 2011-10-09: review whether it still applies", r.notes.join + + import.import!(decisions: { "87-20-03 R2" => "track" }, user: @user) + assert_equal "2011-10-09", old.reload.superseded_by + end + + test "skip leaves an existing AD exactly as it is" do + mine = AirworthinessDirective.create!(name: "2011-10-09", short_description: "Mine") + mine.aircraft << @aircraft + import.import!(decisions: { "2011-10-09" => "skip" }, user: @user) + assert_equal "Mine", mine.reload.short_description + assert_nil mine.effective_date + end + + test "a later Excel import adds DRS links to ADs imported from CSV" do + import.import!(decisions: {}, user: @user) + assert_nil AirworthinessDirective.find_by(name: "2011-10-09").document_url + path = Rails.root.join("tmp/drs-#{SecureRandom.hex(4)}.xlsx") + pkg = Axlsx::Package.new + pkg.workbook.add_worksheet(name: "ADs") do |ws| + ws.add_row [ "AD Number", "Subject", "Status", "Model" ] + ws.add_row [ "2011-10-09", "Seat Rails and Roller Housing Inspections", "Current", "150L" ] + ws.add_hyperlink(location: "https://drs.faa.gov/browse/excelExternalWindow/XYZ.0001", ref: "A2") + end + pkg.serialize(path.to_s) + xlsx = AdImport.new(@aircraft, path: path, filename: "ads.xlsx") + assert_match "DRS link", xlsx.rows.first.notes.first + xlsx.import!(decisions: {}, user: @user) + ad = AirworthinessDirective.find_by(name: "2011-10-09") + assert_equal "https://drs.faa.gov/browse/excelExternalWindow/XYZ.0001", ad.document_url + assert_equal Date.new(2011, 6, 17), ad.effective_date # not blanked by the sparser file + ensure + FileUtils.rm_f(path) if path + end + + test "warns when a new AD supersedes one the aircraft still tracks" do + AirworthinessDirective.create!(name: "87-20-03 R2", short_description: "Old seat rail AD").aircraft << @aircraft + assert_match "Supersedes 87-20-03 R2", row("2011-10-09").notes.join + end + + test "re-import is idempotent and N/A isn't recorded twice" do + 2.times { import.import!(decisions: { "2008-22-18" => "na" }, user: @user) } + assert_equal 1, AdCompliance.where(not_applicable: true).count + assert_equal 4, @aircraft.applicable_ads.count + end + + test "keeps hyperlinks from an Excel export" do + path = Rails.root.join("tmp/drs-#{SecureRandom.hex(4)}.xlsx") + pkg = Axlsx::Package.new + pkg.workbook.add_worksheet(name: "ADs") do |ws| + ws.add_row [ "AD Number", "Subject", "Status", "Effective Date", "Model" ] + ws.add_row [ "2011-10-09", "Seat Rails", "Current", "06/17/2011", "150L" ] + ws.add_row [ "67-03-01", "Exhaust Gas Heat Exchangers", "Current", "01/14/1967", "150L" ] + ws.add_hyperlink(location: "https://drs.faa.gov/browse/excelExternalWindow/ABC123.0001", ref: "A2") + end + pkg.serialize(path.to_s) + + imp = AdImport.new(@aircraft, path: path, filename: "ads.xlsx") + assert_equal "https://drs.faa.gov/browse/excelExternalWindow/ABC123.0001", imp.rows.first.url + assert_nil imp.rows.last.url + imp.import!(decisions: {}, user: @user) + assert_equal [ "https://drs.faa.gov/browse/excelExternalWindow/ABC123.0001", "View AD" ], + AirworthinessDirective.find_by(name: "2011-10-09").reference_link + ensure + FileUtils.rm_f(path) + end + + test "keeps a link column from a CSV, but never non-http links" do + path = Rails.root.join("tmp/drs-#{SecureRandom.hex(4)}.csv") + File.write(path, <<~CSV) + AD Number,Subject,Status,Model,Link + 2011-10-09,Seat Rails,Current,150L,https://example.gov/ad/2011-10-09.pdf + 2008-22-18,BRS,Current,150L,javascript:alert(1) + CSV + rows = AdImport.new(@aircraft, path: path, filename: "x.csv").rows + assert_equal "https://example.gov/ad/2011-10-09.pdf", rows.first.url + assert_nil rows.last.url + ensure + FileUtils.rm_f(path) + end + + # Guards against a field only existing in memory (e.g. via `normalizes`) + # and silently not being saved. + test "every FAA field the import writes is a real database column" do + AdImport::FAA_FIELDS.each_key do |attr| + assert_includes AirworthinessDirective.column_names, attr.to_s + end + assert_includes Aircraft.column_names, "drs_search_url" + end + + test "rejects files that aren't DRS exports" do + path = Rails.root.join("tmp/not-drs-#{SecureRandom.hex(4)}.csv") + File.write(path, "Name,Value\na,1\n") + assert_raises(AdImport::Error) { AdImport.new(@aircraft, path: path, filename: "x.csv").rows } + ensure + FileUtils.rm_f(path) + end +end