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

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