Import ADs from FAA DRS exports; N/A determinations and DRS links

AD import (owners, ADs tab → Import from FAA DRS):
- Upload a DRS export (.xlsx recommended, .csv works), preview, confirm.
- Per AD: track, not applicable, or skip, with suggestions and flags for
  superseded/non-current ADs, model mismatches, appliance and STC-only
  ADs, repetitive actions, and older ADs this one supersedes.
- ADs are matched by number; re-importing updates existing ADs from the
  FAA data (preview lists what will change) without touching compliance
  records, recurrence or applicability. Superseded tracked ADs are
  updated and flagged rather than skipped.
- DRS's Excel export hyperlinks each AD number to its DRS page; those
  links are kept (http(s) only). DRS ids aren't derivable from the AD
  number, so no links are guessed.

Also:
- Per-aircraft "not applicable" AD determinations (N/A badge, quick
  action, excluded from airworthiness).
- AD numbers link to their DRS document in the AD list, compliance
  history (now with description, logbook/inspection links) and share page.
- Saved DRS search link per aircraft with an "Open in DRS" button.
- Upload storage extracted to a StoredUpload concern shared with the
  flight import.
- document_url / drs_search_url added in their own guarded migration
  (they were briefly in an already-applied migration).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-05 18:35:38 -05:00
1 parent f94ccee99b
commit b75fd7cf62
31 files changed
+817 -57

No files matched your search

+2 -1
View File
@@ -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. |
+5 -3
View File
@@ -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])
+45
View File
@@ -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
+1 -1
View File
@@ -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
@@ -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
+40
View File
@@ -0,0 +1,40 @@
# Keeps an uploaded spreadsheet in tmp/imports between the upload and confirm
# steps of an import. Tokens are server-generated "<uuid>.<ext>" 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
+5 -35
View File
@@ -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 "<uuid>.<ext>"; 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
+1 -1
View File
@@ -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] ],
+9 -1
View File
@@ -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"
@@ -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)
}
}
+5 -2
View File
@@ -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}). " \
+2
View File
@@ -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) }
+19
View File
@@ -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]
+233
View File
@@ -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
+2 -1
View File
@@ -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
+4 -1
View File
@@ -18,7 +18,10 @@
<p class="rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-next-due-target="preview" hidden></p>
<%= 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 %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %></div>
<% end %>
<% if compliance.persisted? %><div class="mt-4"><%= delete_button "Delete record", aircraft_ad_compliance_path(aircraft, compliance) %></div><% end %>
+24
View File
@@ -0,0 +1,24 @@
<% content_for :title, "Import ADs" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<div class="grid gap-5 lg:grid-cols-3">
<%= form_with url: aircraft_ad_import_path(@aircraft), multipart: true, class: "card card-body space-y-4 lg:col-span-2" do |f| %>
<h2 class="card-title">Import ADs from the FAA DRS</h2>
<div>
<%= 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" %>
</div>
<%= f.submit "Upload & Preview", class: "btn-primary" %>
<p class="hint">Nothing is saved until you confirm on the next page.</p>
<% end %>
<section class="card card-body space-y-2 text-sm text-slate-700">
<h3 class="font-semibold">Getting the file</h3>
<ol class="list-decimal space-y-1 pl-4 text-xs">
<li>On <a href="<%= @aircraft.drs_search_url.presence || "https://drs.faa.gov" %>" class="link" target="_blank" rel="noopener noreferrer"><%= @aircraft.drs_search_url.present? ? "your saved DRS search" : "drs.faa.gov" %></a>, search Airworthiness Directives for this aircraft's make and model (add the engine and propeller too).</li>
<li>Save the results as <strong>Excel</strong>. The Excel file links each AD number to its DRS page; the CSV doesn't, so a CSV import won't have links.</li>
<li>Upload it here.</li>
</ol>
<% unless @aircraft.drs_search_url.present? %><p class="text-xs">Tip: save the DRS search link on the aircraft (Edit aircraft) for a one-click “Open in DRS” button.</p><% end %>
<p class="text-xs">ADs already tracked are matched by number, so importing the Excel file after a CSV import just adds the links.</p>
</section>
</div>
+54
View File
@@ -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 %>
<section class="card">
<div class="card-header">
<h2 class="card-title">Preview: <%= @filename %></h2>
<span class="text-xs text-slate-500"><%= pluralize(rows.size, "AD") %> found · <%= rows.count(&:url) %> with DRS links</span>
</div>
<div class="card-body space-y-3 text-sm">
<% if rows.none?(&:url) %><p class="rounded-md bg-amber-50 px-3 py-2 text-amber-900 ring-1 ring-amber-200">This file has no links to the AD documents. DRS's <strong>Excel</strong> export includes them; import that file instead (or afterwards) to get clickable AD numbers.</p><% end %>
<p>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.</p>
<ul class="list-disc space-y-1 pl-5 text-xs text-slate-600">
<li><strong>Track</strong>: adds the AD. Until you record compliance, it counts against airworthiness, so <%= @aircraft.tail_number %> will show <span class="badge-red">Not Airworthy</span> for each tracked AD without a compliance record.</li>
<li><strong>Not applicable</strong>: adds the AD with an N/A record (e.g. the equipment isn't installed). You can edit the reason afterwards.</li>
<li><strong>Update</strong> (ADs already tracked): refreshes the FAA details: subject, summary, dates, supersession and DRS link. Compliance records aren't touched.</li>
<li><strong>Skip</strong>: not imported, or left exactly as is.</li>
</ul>
</div>
</section>
<section class="card">
<div class="overflow-x-auto">
<table class="table">
<thead><tr><th>AD</th><th>Subject</th><th>Effective</th><th>Notes</th><th class="w-44">Action</th></tr></thead>
<tbody>
<% rows.each do |r| %>
<tr>
<td class="whitespace-nowrap font-medium"><%= r.number %><%= link_to " 🔗", r.url, target: "_blank", rel: "noopener noreferrer", title: "Link found in file" if r.url %>
<% if r.product_type %><div class="text-xs font-normal text-slate-500"><%= r.product_type %></div><% end %></td>
<td class="max-w-md">
<%= r.subject %>
<% if r.summary %><details class="mt-1 text-xs text-slate-600"><summary class="cursor-pointer text-sky-700">Summary</summary><%= r.summary %></details><% end %>
</td>
<td class="whitespace-nowrap text-xs"><%= r.effective_date %></td>
<td class="text-xs">
<% r.notes.each do |n| %><div class="<%= n.start_with?("Already", "Matches") ? 'text-slate-500' : 'text-amber-800' %>">• <%= n %></div><% end %>
</td>
<td><% 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" %></td>
</tr>
<% end %>
</tbody>
</table>
</div>
</section>
<div class="flex gap-2">
<%= 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" %>
</div>
<% end %>
+2
View File
@@ -20,6 +20,8 @@
<% unless aircraft.new_record? %>
<p class="hint">To change hours use “Update Hours” on the overview, so component times stay in sync.</p>
<% 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." %>
@@ -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) %>
</div>
<%= 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 %>
<p class="rounded bg-amber-50 p-2 text-xs text-amber-800">This AD is shared with other aircraft; edits affect them too.</p>
@@ -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" %>
</div>
<% end %>
@@ -22,9 +24,12 @@
<tbody>
<% @rows.each do |row| ad = row.ad %>
<tr>
<td class="whitespace-nowrap font-medium"><span class="badge-gray mr-1"><%= ad.bulletin_label %></span><%= ad.name %>
<td class="whitespace-nowrap font-medium"><span class="badge-gray mr-1"><%= ad.bulletin_label %></span><%= ad_link(ad) %>
<% if ad.document %><%= link_to "📄", aircraft_document_path(@aircraft, ad.document), title: ad.document.name %><% end %>
<% unless ad.mandatory? %><div class="text-xs text-slate-400">not mandatory</div><% end %></td>
<td class="max-w-sm text-xs"><%= ad.short_description %>
<% if ad.effective_date || ad.product_type.present? %><div class="text-slate-500"><%= [(ad.effective_date && "Effective #{ad.effective_date}"), ad.product_type.presence].compact.join(" · ") %></div><% end %>
<% if ad.superseded_by.present? %><div class="text-amber-700">Superseded by <%= ad.superseded_by %></div><% end %>
<% if ad.conditional? && ad.trigger_condition.present? %><div class="text-slate-500">Trigger: <%= ad.trigger_condition %></div><% end %></td>
<td class="text-xs"><%= 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" %></td>
<td class="text-xs"><%= row.latest ? "#{row.latest.date_complied}#{' (permanent)' if row.latest.permanent?}" : "—" %></td>
@@ -33,6 +38,7 @@
<td class="whitespace-nowrap text-right">
<% 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 %>
</td>
@@ -55,10 +61,23 @@
<% @history.each do |c| %>
<tr>
<td class="whitespace-nowrap"><%= c.date_complied %></td>
<td><%= c.airworthiness_directive.name %><%= " (#{c.component})" if c.component %></td>
<% ad = c.airworthiness_directive %>
<td class="max-w-xs">
<span class="whitespace-nowrap font-medium"><%= ad_link(ad) %></span>
<% if ad.document %><%= link_to "📄", aircraft_document_path(@aircraft, ad.document), title: ad.document.name %><% end %>
<div class="text-xs text-slate-500"><%= ad.short_description %><%= " · #{c.component}" if c.component %></div>
</td>
<td class="text-right"><%= hours(c.aircraft_hours_at_compliance) %></td>
<td><%= c.permanent? ? "Permanent" : (c.next_due_at_time.to_f > 0 ? hours(c.next_due_at_time) : "—") %></td>
<td class="max-w-md text-xs"><%= c.compliance_notes %></td>
<td><%= c.not_applicable? ? "N/A" : c.permanent? ? "Permanent" : (c.next_due_at_time.to_f > 0 ? hours(c.next_due_at_time) : "—") %></td>
<td class="max-w-md text-xs">
<%= c.compliance_notes %>
<% if c.logbook_entry || c.inspection_record %>
<div class="mt-1 flex flex-wrap gap-x-3">
<% 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 %>
</div>
<% end %>
</td>
<td class="text-right"><% if owner? %><%= link_to "Edit", edit_aircraft_ad_compliance_path(@aircraft, c), class: "btn-secondary btn-sm" %><% end %></td>
</tr>
<% end %>
+2 -2
View File
@@ -59,7 +59,7 @@
<section class="card">
<div class="card-header"><h2 class="card-title">ADs</h2></div>
<table class="table"><tbody><% @ad_rows.each do |r| %><tr>
<td><%= r.ad.name %><div class="text-xs text-slate-500"><%= r.ad.short_description %></div></td><td class="text-xs"><%= r.latest&.date_complied || "—" %></td><td><%= compliance_badge(r.status) %></td></tr><% end %></tbody></table>
<td><%= ad_link(r.ad) %><div class="text-xs text-slate-500"><%= r.ad.short_description %></div></td><td class="text-xs"><%= r.latest&.date_complied || "—" %></td><td><%= compliance_badge(r.status) %></td></tr><% end %></tbody></table>
</section>
</div>
@@ -87,7 +87,7 @@
<section class="card"><div class="card-header"><h2 class="card-title">Inspection History</h2></div>
<table class="table"><tbody><% @inspection_history.each do |r| %><tr><td><%= r.date %></td><td><%= r.inspection_type.name %></td><td class="text-right"><%= hours(r.hours_at_inspection) %></td></tr><% end %></tbody></table></section>
<section class="card"><div class="card-header"><h2 class="card-title">AD Compliance History</h2></div>
<table class="table"><tbody><% @ad_history.each do |c| %><tr><td><%= c.date_complied %></td><td><%= c.airworthiness_directive.name %></td><td class="text-xs"><%= c.compliance_notes %></td></tr><% end %></tbody></table></section>
<table class="table"><tbody><% @ad_history.each do |c| %><tr><td class="whitespace-nowrap"><%= c.date_complied %></td><td><%= ad_link(c.airworthiness_directive) %><div class="text-xs text-slate-500"><%= c.airworthiness_directive.short_description %></div></td><td class="text-xs"><%= c.not_applicable? ? "N/A: " : "" %><%= c.compliance_notes %></td></tr><% end %></tbody></table></section>
</div>
<section class="card"><div class="card-header"><h2 class="card-title">Major Repairs & Alterations</h2></div>
+3
View File
@@ -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]
@@ -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
@@ -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
Generated
+10 -1
View File
@@ -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
+6
View File
@@ -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,,,,,
1 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
2 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.
3 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.
4 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.
5 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
6 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
+66
View File
@@ -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</strong> 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
+15
View File
@@ -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)
@@ -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
+193
View File
@@ -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