Record history for ADs and inspection types (applicability links and changes), with restore

Shared records keep applicability in join tables, so linking to the
airframe or a component, unlinking, edits to the shared record and a
component's deletion are now appended to each affected aircraft's hash
chain. Owners can restore a removed link from Activity -> Record history.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-11 20:54:35 -05:00
1 parent d5d06d4169
commit ba0455b149
10 files changed
+164 -7

No files matched your search

@@ -1,6 +1,9 @@
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2). # Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
class RecordVersionsController < ApplicationController class RecordVersionsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner!, only: :restore
SHARED = %w[AirworthinessDirective InspectionType].freeze
def index def index
@type = params[:type].presence_in(RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type)) @type = params[:type].presence_in(RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type))
@@ -9,4 +12,34 @@ class RecordVersionsController < ApplicationController
@versions = scope.limit(500) @versions = scope.limit(500)
@types = RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type).sort @types = RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type).sort
end end
# Puts back an AD or inspection type link that was removed (the removal
# stays in the history, and the restore is recorded as a new link).
def restore
version = RecordVersion.where(aircraft_id: @aircraft.id, event: "unlink", item_type: SHARED).find(params[:id])
record = version.item_type.constantize.find_by(id: version.item_id)
return redirect_to(aircraft_record_versions_path(@aircraft), alert: "That record no longer exists.") unless record
c = version.changes_hash
if c["applies_to"] == "component"
component = @aircraft.components.find_by(id: c["component_id"])
return redirect_to(aircraft_record_versions_path(@aircraft), alert: "That component no longer exists; edit the record's applicability instead.") unless component
record.components << component unless record.components.include?(component)
else
record.aircraft << @aircraft unless record.aircraft.include?(@aircraft)
end
log_event(version.item_type == "AirworthinessDirective" ? "ad" : "inspection", "Restored: #{record} applies again")
redirect_to aircraft_record_versions_path(@aircraft), notice: "#{record} applies to #{@aircraft.tail_number} again."
end
# Whether an unlink can still be undone (the record exists and isn't linked that way now).
def self.restorable?(version, aircraft)
return false unless version.event == "unlink" && SHARED.include?(version.item_type)
record = version.item_type.constantize.find_by(id: version.item_id) or return false
c = version.changes_hash
if c["applies_to"] == "component"
record.component_ids.exclude?(c["component_id"]) && aircraft.components.exists?(id: c["component_id"])
else
record.aircraft_ids.exclude?(aircraft.id)
end
end
end end
+1 -2
View File
@@ -7,8 +7,7 @@ class AirworthinessDirective < ApplicationRecord
BULLETIN_LABELS = { "ad" => "AD", "saib" => "SAIB", "sb" => "SB", "alert" => "Alert", "other" => "Bulletin" }.freeze BULLETIN_LABELS = { "ad" => "AD", "saib" => "SAIB", "sb" => "SB", "alert" => "Alert", "other" => "Bulletin" }.freeze
belongs_to :document, optional: true belongs_to :document, optional: true
has_and_belongs_to_many :aircraft include SharedRecordHistory # has_and_belongs_to_many :aircraft and :components, with history
has_and_belongs_to_many :components
has_many :ad_compliances, dependent: :destroy has_many :ad_compliances, dependent: :destroy
validates :name, :short_description, presence: true validates :name, :short_description, presence: true
+2
View File
@@ -19,6 +19,8 @@ class Component < ApplicationRecord
has_many :logbook_entry_parts, dependent: :destroy has_many :logbook_entry_parts, dependent: :destroy
has_and_belongs_to_many :inspection_types has_and_belongs_to_many :inspection_types
has_and_belongs_to_many :airworthiness_directives has_and_belongs_to_many :airworthiness_directives
# Its AD and inspection links go with it; keep that in the record history.
before_destroy(prepend: true) { (airworthiness_directives.to_a + inspection_types.to_a).each { _1.history_component_deleted(self) } }
validates :manufacturer, :model, :date_in_service, presence: true validates :manufacturer, :model, :date_in_service, presence: true
validates :status, inclusion: { in: STATUSES.keys } validates :status, inclusion: { in: STATUSES.keys }
@@ -0,0 +1,43 @@
# Record history for records shared between aircraft (ADs and inspection
# types). Their applicability lives in plain join tables, so linking one to
# an aircraft or a component, unlinking it, and changes to the shared record
# are written to each affected aircraft's history chain here (AC 120-78B 3.2.2;
# for ADs, the AD status kept under 14 CFR 91.417(a)(2)(v)).
module SharedRecordHistory
extend ActiveSupport::Concern
IGNORED = %w[created_at updated_at].freeze
included do
has_and_belongs_to_many :aircraft, after_add: :history_link_aircraft, after_remove: :history_unlink_aircraft
has_and_belongs_to_many :components, after_add: :history_link_component, after_remove: :history_unlink_component
after_update { (c = saved_changes.except(*IGNORED)).any? && linked_aircraft_ids.each { |id| history!(id, "update", c) } }
before_destroy { linked_aircraft_ids.each { |id| history!(id, "destroy", attributes.except(*IGNORED)) } }
end
# Aircraft this record applies to, directly or through a component.
def linked_aircraft_ids = (aircraft_ids + components.map(&:aircraft_id)).compact.uniq
# Logs that a component it applied to is being deleted (the join row goes
# with the component, without the callbacks above).
def history_component_deleted(component) = history_link(component.aircraft_id, "unlink", component, reason: "component deleted")
private
def history_link_aircraft(aircraft) = history_link(aircraft.id, "link", nil)
def history_unlink_aircraft(aircraft) = history_link(aircraft.id, "unlink", nil)
def history_link_component(component) = history_link(component.aircraft_id, "link", component)
def history_unlink_component(component) = history_link(component.aircraft_id, "unlink", component)
def history_link(aircraft_id, event, component, reason: nil)
return unless persisted? && aircraft_id
changes = { "record" => to_s, "applies_to" => component ? "component" : "airframe" }
changes.merge!("component_id" => component.id, "component" => "#{component} #{component.model}".strip) if component
changes["reason"] = reason if reason
history!(aircraft_id, event, changes)
end
def history!(aircraft_id, event, changes)
RecordVersion.append!(item: self, aircraft_id: aircraft_id, event: event, changes: changes.as_json)
end
end
+1 -2
View File
@@ -12,8 +12,7 @@ class InspectionType < ApplicationRecord
# Short form for the airworthiness status ("VFR only"). # Short form for the airworthiness status ("VFR only").
LIMITATIONS = { "no_ifr" => "VFR only", "no_transponder" => "No transponder" }.freeze LIMITATIONS = { "no_ifr" => "VFR only", "no_transponder" => "No transponder" }.freeze
has_and_belongs_to_many :aircraft include SharedRecordHistory # has_and_belongs_to_many :aircraft and :components, with history
has_and_belongs_to_many :components
has_many :inspection_records, dependent: :destroy has_many :inspection_records, dependent: :destroy
belongs_to :satisfies, class_name: "InspectionType", optional: true belongs_to :satisfies, class_name: "InspectionType", optional: true
has_many :satisfied_by, class_name: "InspectionType", foreign_key: :satisfies_id, inverse_of: :satisfies, dependent: :nullify has_many :satisfied_by, class_name: "InspectionType", foreign_key: :satisfies_id, inverse_of: :satisfies, dependent: :nullify
+10 -1
View File
@@ -4,9 +4,18 @@
<li class="px-4 py-2"> <li class="px-4 py-2">
<div class="flex flex-wrap items-baseline justify-between gap-2"> <div class="flex flex-wrap items-baseline justify-between gap-2">
<span><span class="font-medium"><%= v.item_type.underscore.humanize %> #<%= v.item_id %></span> <span><span class="font-medium"><%= v.item_type.underscore.humanize %> #<%= v.item_id %></span>
<span class="<%= { 'create' => 'badge-green', 'update' => 'badge-blue', 'destroy' => 'badge-red' }[v.event] %> ml-1"><%= { "create" => "created", "update" => "changed", "destroy" => "deleted" }[v.event] %></span></span> <span class="<%= { 'create' => 'badge-green', 'update' => 'badge-blue', 'destroy' => 'badge-red', 'link' => 'badge-green', 'unlink' => 'badge-orange' }[v.event] %> ml-1"><%= { "create" => "created", "update" => "changed", "destroy" => "deleted", "link" => "applied", "unlink" => "removed" }[v.event] %></span></span>
<span class="text-xs text-slate-500"><%= v.created_at.utc.strftime("%Y-%m-%d %H:%M:%S UTC") %> · <%= v.user&.display_name || "system" %><%= " · #{v.ip_address}" if v.ip_address %></span> <span class="text-xs text-slate-500"><%= v.created_at.utc.strftime("%Y-%m-%d %H:%M:%S UTC") %> · <%= v.user&.display_name || "system" %><%= " · #{v.ip_address}" if v.ip_address %></span>
</div> </div>
<% if v.event.in?(%w[link unlink]) %>
<% c = v.changes_hash %>
<p class="mt-1 text-xs text-slate-600">
<%= c["record"] %> <%= v.event == "link" ? "applies to" : "no longer applies to" %> <%= c["applies_to"] == "component" ? c["component"] : "the airframe" %><%= " (#{c['reason']})" if c["reason"] %>.
<% if v.event == "unlink" && local_assigns[:aircraft] && local_assigns[:can_restore] && RecordVersionsController.restorable?(v, aircraft) %>
<%= button_to "Restore", restore_aircraft_record_version_path(aircraft, v), method: :post, class: "btn-secondary btn-sm ml-2", form: { class: "inline" } %>
<% end %>
</p>
<% end %>
<% if v.event == "update" %> <% if v.event == "update" %>
<dl class="mt-1 grid gap-x-3 text-xs text-slate-600 sm:grid-cols-[10rem_1fr]"> <dl class="mt-1 grid gap-x-3 text-xs text-slate-600 sm:grid-cols-[10rem_1fr]">
<% v.changes_hash.each do |field, (before, after)| %> <% v.changes_hash.each do |field, (before, after)| %>
+1 -1
View File
@@ -10,5 +10,5 @@
<%= select_tag :type, options_for_select([ [ "All records", "" ] ] + @types.map { [ _1.underscore.humanize, _1 ] }, @type), class: "input w-48", data: { submit_on_change: true } %> <%= select_tag :type, options_for_select([ [ "All records", "" ] ] + @types.map { [ _1.underscore.humanize, _1 ] }, @type), class: "input w-48", data: { submit_on_change: true } %>
<% end %> <% end %>
</div> </div>
<% if @versions.any? %><%= render "record_versions/list", versions: @versions %><% else %><%= empty_state "No changes recorded yet." %><% end %> <% if @versions.any? %><%= render "record_versions/list", versions: @versions, aircraft: @aircraft, can_restore: owner? %><% else %><%= empty_state "No changes recorded yet." %><% end %>
</section> </section>
+3 -1
View File
@@ -109,7 +109,9 @@ Rails.application.routes.draw do
resource :export, controller: "aircraft_exports", only: :show resource :export, controller: "aircraft_exports", only: :show
resource :report, controller: "maintenance_reports", only: :show resource :report, controller: "maintenance_reports", only: :show
resource :records_package, path: "records", only: :show resource :records_package, path: "records", only: :show
resources :record_versions, path: "history", only: :index resources :record_versions, path: "history", only: :index do
member { post :restore }
end
resources :events, only: :index resources :events, only: :index
end end
+2
View File
@@ -16,4 +16,6 @@ The app searches the Federal Register weekly for new ADs mentioning the aircraft
**Comply** records the date, aircraft hours, the component, the logbook entry, the method (inspection, terminating action, AMOC) and the AD revision complied with, with details of what was done. **N/A** records that an AD doesn't apply, and why (for example, serial number outside the affected range). Recurring ADs then show when they're next due. **Comply** records the date, aircraft hours, the component, the logbook entry, the method (inspection, terminating action, AMOC) and the AD revision complied with, with details of what was done. **N/A** records that an AD doesn't apply, and why (for example, serial number outside the affected range). Recurring ADs then show when they're next due.
Applying an AD to the aircraft or a component, removing it, and changes to it are kept in **Activity → Record history**, with who and when. An owner can **Restore** an AD that was removed by mistake from there.
Make the logbook entry for the work as well; the status report lists each AD with its method and revision (91.417(a)(2)(v)). Make the logbook entry for the work as well; the status report lists each AD with its method and revision (91.417(a)(2)(v)).
+68
View File
@@ -0,0 +1,68 @@
require "test_helper"
# ADs and inspection types are shared between aircraft; linking, unlinking
# and changing them is kept in each aircraft's record history.
class AdHistoryTest < ActionDispatch::IntegrationTest
setup do
@owner = create_user("owner@example.com")
@a = create_aircraft(owner: @owner, tail_number: "N12345")
@engine = create_component(@a, component_type: component_type("Engine"), model: "O-200A")
sign_in @owner
end
def history(event = nil)
scope = RecordVersion.where(aircraft_id: @a.id, item_type: "AirworthinessDirective")
event ? scope.where(event: event) : scope
end
test "applying, changing, removing and restoring an AD are all in the history, with who did it" do
post aircraft_airworthiness_directives_path(@a), params: { applies_to_airframe: "1",
airworthiness_directive: { name: "2000-06-01", bulletin_type: "ad", compliance_type: "standard", short_description: "Fuel strainer" } }
ad = AirworthinessDirective.find_by!(name: "2000-06-01")
assert_equal [ "airframe" ], history("link").map { _1.changes_hash["applies_to"] }
assert_equal @owner, history("link").last.user
patch aircraft_airworthiness_directive_path(@a, ad), params: { applies_to_airframe: "0", component_ids: [ @engine.id ],
airworthiness_directive: { short_description: "Fuel strainer assembly" } }
assert_equal [ "Fuel strainer", "Fuel strainer assembly" ], history("update").last.changes_hash["short_description"]
assert_equal "component", history("link").last.changes_hash["applies_to"]
assert_equal "airframe", history("unlink").last.changes_hash["applies_to"]
delete aircraft_airworthiness_directive_path(@a, ad) # removed from this aircraft (no compliance: the AD record goes too)
assert_equal "component", history("unlink").last.changes_hash["applies_to"]
ad2 = AirworthinessDirective.create!(name: "71-22-02", short_description: "Nose gear fork")
ad2.aircraft << @a
ad2.ad_compliances.create!(aircraft: @a, date_complied: Date.current, compliance_method: "inspection", compliance_notes: "Inspected, no cracks")
delete aircraft_airworthiness_directive_path(@a, ad2)
refute_includes @a.reload.applicable_ads, ad2
unlink = history("unlink").where(item_id: ad2.id).last
get aircraft_record_versions_path(@a)
assert_select "button", text: "Restore"
assert_includes response.body, "71-22-02 no longer applies to the airframe"
post restore_aircraft_record_version_path(@a, unlink)
assert_includes @a.reload.applicable_ads, ad2
assert_equal 2, history("link").where(item_id: ad2.id).count # the restore is a new link
assert RecordsIntegrity.check!.ok # the chain still verifies
end
test "deleting a component records that its ADs no longer apply; DRS-style links are recorded too" do
ad = AirworthinessDirective.create!(name: "96-12-22", short_description: "Oil adapter")
ad.components << @engine
assert_equal "O-200A", history("link").last.changes_hash["component"].split.last
delete aircraft_component_path(@a, @engine)
assert_equal "component deleted", history("unlink").last.changes_hash["reason"]
end
test "pilots can't restore" do
pilot = create_user("pilot@example.com")
@a.roles.create!(user: pilot, role: "pilot")
ad = AirworthinessDirective.create!(name: "68-17-04", short_description: "Stall warning")
ad.aircraft << @a
ad.aircraft.delete(@a)
sign_in pilot
post restore_aircraft_record_version_path(@a, history("unlink").last)
refute_includes @a.reload.applicable_ads, ad
end
end