Records integrity: history, nightly backup and check, records package

AC 120-78B chapter 3:
- Every change to logbook entries, sub-components, signatures, inspection
  records, AD compliance, major records, W&B, components, squawks and
  documents is kept as a RecordVersion (who, IP, when, field changes),
  hash-chained per aircraft; versions can't be edited or deleted. Shown on
  each logbook entry and in Activity -> Record history
- Nightly job: SQLite online-backup copy to storage/backups, verified
  (integrity_check + record counts), pruned to the configured number; then
  an integrity check of the history chains and every signature's seal and
  fingerprint. Results on Admin -> About ("Back up and check now"); admins
  are emailed on failure
- Software versions recorded (first/last seen) on Admin -> About
- Records package (Access & Sharing): logbook entries PDF with signatures,
  signatures.csv, record-history.csv, self-contained status report HTML,
  the .sam.zip, and a README, for the FAA/NTSB or a buyer
- Legacy (paper) records: documents can be marked as legacy records;
  aircraft have an "electronic records since" date (status report, package)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 13:21:26 -05:00
1 parent d719f663bc
commit 68a1719db2
53 files changed
+750 -12

No files matched your search

+12 -1
View File
@@ -1,11 +1,22 @@
class Admin::AboutController < ApplicationController
before_action :require_admin!
rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder], with: -> { redirect_to admin_about_path, alert: "Try again in a minute." }
rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder check_records], with: -> { redirect_to admin_about_path, alert: "Try again in a minute." }
def show
@info = SystemInfo.new
end
# Back up and verify the records now (normally nightly).
def check_records
backup = DatabaseBackup.run!
check = RecordsIntegrity.check!
if backup.ok && check.ok
redirect_to admin_about_path(anchor: "records"), notice: "Backed up and checked: no problems found."
else
redirect_to admin_about_path(anchor: "records"), alert: "The records check found problems; see Records below."
end
end
# This week's reminder for the current admin, now.
def test_reminder
return redirect_to(admin_about_path, alert: "Email isn't set up yet.") unless MailSettings.configured?
+3 -3
View File
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
before_action :require_admin!
def edit
@values = { "max_upload_mb" => Setting.max_upload_mb }
@values = { "max_upload_mb" => Setting.max_upload_mb, "backups_kept" => Setting.integer("backups_kept") }
end
def update
submitted = params.fetch(:settings, {}).permit(:max_upload_mb).to_h
submitted = params.fetch(:settings, {}).permit(:max_upload_mb, :backups_kept).to_h
records = Setting.update_integers(submitted)
@errors = records.flat_map { _1.errors.full_messages }
if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: "Settings saved."
else
@values = { "max_upload_mb" => Setting.max_upload_mb }.merge(submitted)
@values = { "max_upload_mb" => Setting.max_upload_mb, "backups_kept" => Setting.integer("backups_kept") }.merge(submitted)
render :edit, status: :unprocessable_entity
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, :icao_type, :time_basis
:airworthiness_enforcement, :picture, :icao_type, :time_basis, :electronic_records_since
)
end
end
@@ -4,6 +4,7 @@ class ApplicationController < ActionController::Base
allow_browser versions: :modern
prepend_before_action :redirect_to_setup
before_action { Current.ip_address = request.remote_ip } # for record history
helper_method :current_user
rescue_from ActiveRecord::RecordNotFound do
+1 -1
View File
@@ -126,7 +126,7 @@ class DocumentsController < ApplicationController
def set_document = @document = @aircraft.documents.find(params[:id])
def document_params
p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, :expires_on, pages: [])
p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, :expires_on, :legacy_record, pages: [])
p[:pages]&.compact_blank!
p.delete(:pages) if p[:pages].blank?
p[:document_collection_id] = scoped_id(@aircraft.document_collections, p[:document_collection_id])
@@ -0,0 +1,12 @@
# Every change to the aircraft's maintenance records (AC 120-78B 3.2.2).
class RecordVersionsController < ApplicationController
include AircraftScoped
def index
@type = params[:type].presence_in(RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type))
scope = RecordVersion.where(aircraft_id: @aircraft.id).order(id: :desc).includes(:user)
scope = scope.where(item_type: @type) if @type
@versions = scope.limit(500)
@types = RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type).sort
end
end
@@ -0,0 +1,16 @@
# Download every record of an aircraft in one ZIP (owners).
class RecordsPackagesController < ApplicationController
include AircraftScoped
before_action :require_owner!
def show
package = RecordsPackage.new(@aircraft, source: request.host)
dir = Rails.root.join("tmp", "packages")
FileUtils.mkdir_p(dir)
Dir[dir.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago }
path = dir.join("#{SecureRandom.hex(12)}.zip").to_s
package.write_to(path)
log_event("aircraft", "Records package downloaded")
send_file path, filename: package.filename, type: "application/zip", disposition: "attachment"
end
end
+1 -1
View File
@@ -15,7 +15,7 @@ module AircraftHelper
[ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ],
[ "W&B", aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ],
[ "Notes", aircraft_notes_path(aircraft), %w[notes] ],
[ "Activity", aircraft_events_path(aircraft), %w[events] ],
[ "Activity", aircraft_events_path(aircraft), %w[events record_versions] ],
([ "Access & Sharing", aircraft_aircraft_roles_path(aircraft), %w[aircraft_roles share_tokens] ] if owner?)
].compact
end
+13
View File
@@ -0,0 +1,13 @@
# Nightly: back up the database, then verify the records. Admins are emailed
# if either fails.
class RecordsIntegrityJob < ApplicationJob
queue_as :default
def perform
backup = DatabaseBackup.run!
check = RecordsIntegrity.check!
return if backup.ok && check.ok
return unless MailSettings.configured?
User.active.where(admin: true).find_each { AdminMailer.records_alert(_1, backup, check).deliver_now }
end
end
+6
View File
@@ -1,4 +1,10 @@
class AdminMailer < ApplicationMailer
def records_alert(user, backup, check)
@backup = backup
@check = check
mail subject: "Records check needs attention", to: user.email_address
end
def test_email(user)
@user = user
mail subject: "Test email from Simple Aircraft Manager", to: user.email_address
+1
View File
@@ -1,4 +1,5 @@
class AdCompliance < ApplicationRecord
include Versioned
# Method of compliance, recorded per 91.417(a)(2)(v).
METHODS = {
"inspection" => "Inspection",
+18
View File
@@ -0,0 +1,18 @@
# Which software versions have run, and when (AC 120-78B 3.2.6): recorded
# when the app starts and by the nightly check.
class AppRevision < ApplicationRecord
scope :latest_first, -> { order(first_seen_at: :desc) }
def self.touch_current!
revision = SystemInfo.new.revision
return if revision.blank? || revision == "unknown"
now = Time.current
record = find_or_initialize_by(revision: revision)
record.first_seen_at ||= now
record.built_at ||= SystemInfo.new.built_at
record.last_seen_at = now
record.save!
rescue ActiveRecord::ActiveRecordError => e
Rails.logger.warn("[app revisions] #{e.class}: #{e.message}")
end
end
+5
View File
@@ -0,0 +1,5 @@
class BackupRun < ApplicationRecord
scope :latest_first, -> { order(created_at: :desc) }
def self.latest = latest_first.first
def self.last_good = where(ok: true).latest_first.first
end
+1
View File
@@ -1,4 +1,5 @@
class Component < ApplicationRecord
include Versioned
STATUSES = { "SPARE" => "Spare Part", "IN-USE" => "In Service", "DISPOSED" => "Disposed" }.freeze
# What "since overhaul" counts from, and how logbooks abbreviate it.
OVERHAUL_KINDS = { "major" => "Major overhaul", "factory_overhaul" => "Factory overhaul", "factory_new" => "Factory new or rebuilt (zero time)" }.freeze
+26
View File
@@ -0,0 +1,26 @@
# Keeps every change to the record as a RecordVersion (AC 120-78B 3.2.2):
# full values on create and destroy, [before, after] for each changed field.
module Versioned
extend ActiveSupport::Concern
IGNORED = %w[created_at updated_at].freeze
included do
has_many :versions, -> { chronological }, as: :item, class_name: "RecordVersion", inverse_of: false
after_create { record_version!("create", attributes.except(*IGNORED)) }
after_update { (c = saved_changes.except(*IGNORED)).any? && record_version!("update", c) }
after_destroy { record_version!("destroy", attributes.except(*IGNORED)) }
end
private
def record_version!(event, changes)
RecordVersion.append!(item: self, aircraft_id: versioned_aircraft_id, event: event, changes: changes.as_json)
end
def versioned_aircraft_id
return aircraft_id if has_attribute?(:aircraft_id) && aircraft_id
return component&.aircraft_id if respond_to?(:component)
logbook_entry&.aircraft_id if respond_to?(:logbook_entry)
end
end
+1 -1
View File
@@ -1,4 +1,4 @@
class Current < ActiveSupport::CurrentAttributes
attribute :session
attribute :session, :ip_address
delegate :user, to: :session, allow_nil: true
end
+1
View File
@@ -1,4 +1,5 @@
class Document < ApplicationRecord
include Versioned
include UploadValidation
TYPES = {
+1
View File
@@ -6,6 +6,7 @@
# so any later change shows; seal is an HMAC over the signature itself, keyed
# by this server, so the signature record can't be altered unnoticed either.
class EntrySignature < ApplicationRecord
include Versioned
AUTH_METHODS = { "password" => "password re-entered", "sso" => "single sign-on, signed in again" }.freeze
# "Certified by" conveys the intent to sign (2.2.2).
LABEL = "Certified by".freeze
+1
View File
@@ -1,4 +1,5 @@
class InspectionRecord < ApplicationRecord
include Versioned
belongs_to :inspection_type
belongs_to :aircraft, optional: true
belongs_to :component, optional: true
+4
View File
@@ -0,0 +1,4 @@
class IntegrityCheck < ApplicationRecord
scope :latest_first, -> { order(created_at: :desc) }
def self.latest = latest_first.first
end
+1
View File
@@ -1,4 +1,5 @@
class LogbookEntry < ApplicationRecord
include Versioned
LOG_TYPES = { "AC" => "Aircraft", "ENG" => "Engine", "PROP" => "Propeller", "OTHER" => "Other" }.freeze
ENTRY_TYPES = {
"MAINTENANCE" => "Maintenance", "INSPECTION" => "Inspection", "FLIGHT" => "Flight",
+1
View File
@@ -1,6 +1,7 @@
# A sub-component a logbook entry also covers (the oil filter on the engine…)
# and its times at the entry.
class LogbookEntryPart < ApplicationRecord
include Versioned
belongs_to :logbook_entry
belongs_to :component
+1
View File
@@ -1,4 +1,5 @@
class MajorRecord < ApplicationRecord
include Versioned
RECORD_TYPES = { "repair" => "Major Repair", "alteration" => "Major Alteration" }.freeze
belongs_to :aircraft
+30
View File
@@ -0,0 +1,30 @@
# One change to a maintenance record (create, update, destroy), kept for
# good (AC 120-78B 3.2.2). Each aircraft's versions form a hash chain:
# chain_hash = SHA-256(prev_hash + payload), so deleting, reordering or
# editing a version breaks the chain and the nightly check reports it.
class RecordVersion < ApplicationRecord
belongs_to :user, optional: true
scope :chronological, -> { order(:id) }
before_update { throw :abort }
before_destroy { throw :abort }
def self.digest(prev_hash, payload) = OpenSSL::Digest::SHA256.hexdigest("#{prev_hash}\n#{payload}")
def self.append!(item:, aircraft_id:, event:, changes:)
now = Time.current
payload = { "item_type" => item.class.name, "item_id" => item.id, "event" => event, "changes" => changes,
"user_id" => Current.user&.id, "at" => now.utc.iso8601(6) }.to_json
prev = where(aircraft_id: aircraft_id).order(:id).last&.chain_hash
create!(aircraft_id: aircraft_id, item_type: item.class.name, item_id: item.id, event: event, user_id: Current.user&.id,
ip_address: Current.ip_address, payload: payload, prev_hash: prev, chain_hash: digest(prev, payload), created_at: now)
end
def changes_hash = JSON.parse(payload)["changes"]
# Field names changed by this version (for display).
def changed_fields
event == "update" ? changes_hash.keys : []
end
end
+1
View File
@@ -7,6 +7,7 @@
class Setting < ApplicationRecord
INTEGERS = {
"max_upload_mb" => { default: 50, in: 1..1024, label: "Maximum upload size (MB)" },
"backups_kept" => { default: 14, in: 1..365, label: "Database backups kept" },
"logbook_templates_seeded" => { default: 0, in: 0..1, label: "Built-in logbook templates added" } # internal flag
}.freeze
+1
View File
@@ -1,4 +1,5 @@
class Squawk < ApplicationRecord
include Versioned
include UploadValidation
PRIORITIES = { 0 => "Ground Aircraft", 1 => "Fix Soon", 2 => "Fix at Next Inspection", 3 => "Fix Eventually" }.freeze
+1
View File
@@ -2,6 +2,7 @@
# date, usually after weighing or an equipment change (each alteration that
# changes them needs a new one; its 337 can be linked).
class WeightBalanceRecord < ApplicationRecord
include Versioned
belongs_to :aircraft
belongs_to :major_record, optional: true
belongs_to :document, optional: true
+2 -2
View File
@@ -50,7 +50,7 @@ module AircraftArchive
end,
documents: a.documents.map do |d|
{ id: id(d), aircraft_id: id(a), collection_id: id(d.document_collection_id), doc_type: d.doc_type, name: d.name,
description: d.description, visibility: d.visibility, expires_on: d.expires_on&.iso8601, components: [] }
description: d.description, visibility: d.visibility, expires_on: d.expires_on&.iso8601, legacy_record: d.legacy_record, components: [] }
end,
document_images: a.documents.includes(pages_attachments: :blob).flat_map do |d|
d.pages.map { |page| { id: id(page), document_id: id(d), notes: "", image: file(page, "health/documents") } }
@@ -125,7 +125,7 @@ module AircraftArchive
def aircraft_hash(a)
{ id: id(a), tail_number: a.tail_number, make: a.make, model: a.model, serial_number: a.serial_number,
description: a.description, purchased: a.purchased&.iso8601, status: a.status, time_basis: a.time_basis,
description: a.description, purchased: a.purchased&.iso8601, status: a.status, time_basis: a.time_basis, electronic_records_since: a.electronic_records_since&.iso8601,
loading_stations: a.loading_stations, cg_envelope: a.cg_envelope, ad_watch_terms: a.ad_watch_terms, tach_time: dec(a.tach_time),
tach_time_offset: dec(a.tach_time_offset), hobbs_time: dec(a.hobbs_time), hobbs_time_offset: dec(a.hobbs_time_offset),
picture: file(a.picture, "aircraft_pictures"), icao_type: a.icao_type }
+2 -1
View File
@@ -143,6 +143,7 @@ module AircraftArchive
make: a["make"].to_s, model: a["model"].to_s, serial_number: a["serial_number"].to_s, description: a["description"].to_s,
purchased: date(a["purchased"]), status: Aircraft::STATUSES.key?(a["status"]) ? a["status"] : "AVAILABLE",
time_basis: Aircraft::TIME_BASES.key?(a["time_basis"]) ? a["time_basis"] : "tach",
electronic_records_since: date(a["electronic_records_since"]),
loading_stations: a["loading_stations"].is_a?(Hash) ? a["loading_stations"] : nil,
cg_envelope: a["cg_envelope"].is_a?(Array) ? a["cg_envelope"] : nil, ad_watch_terms: a["ad_watch_terms"].to_s.first(500).presence,
tach_time: num(a["tach_time"] || a["flight_time"]) || 0, tach_time_offset: num(a["tach_time_offset"]) || 0,
@@ -207,7 +208,7 @@ module AircraftArchive
d = @aircraft.documents.new(name: data["name"].to_s.presence || "Untitled", description: data["description"].to_s,
doc_type: data["doc_type"].presence, visibility: visibility(data["visibility"]),
document_collection_id: @map[:collection][data["collection_id"].to_s],
expires_on: date(data["expires_on"]))
expires_on: date(data["expires_on"]), legacy_record: data["legacy_record"] == true)
d.doc_type = "OTHER" unless Document::TYPES.key?(d.doc_type)
d.save!(validate: false)
@map[:document][data["id"].to_s] = d.id
+57
View File
@@ -0,0 +1,57 @@
# Built-in backup of the main database (AC 120-78B 3.2.7): a consistent
# snapshot (SQLite's online backup API, safe while the app runs) in storage/backups,
# checked by opening it and running SQLite's integrity check, and the newest
# few kept. Uploaded files aren't copied (they're already in storage/ and,
# being deduplicated, cheap to back up with the rest of the volume).
class DatabaseBackup
DIR = Rails.root.join("storage", "backups")
def self.run! = new.run!
def run!
FileUtils.mkdir_p(DIR)
path = DIR.join("sam-#{Time.current.utc.strftime('%Y%m%d-%H%M%S')}.sqlite3")
copy(path)
message = verify(path)
bytes = File.size(path)
prune(keep_path: path)
BackupRun.create!(ok: true, path: path.to_s, bytes: bytes, message: message)
rescue StandardError => e
Rails.logger.error("[backup] #{e.class}: #{e.message}")
BackupRun.create!(ok: false, path: path&.to_s, message: "#{e.class.name.demodulize}: #{e.message}".truncate(500))
end
private
def copy(path)
source = ActiveRecord::Base.connection.raw_connection
dest = SQLite3::Database.new(path.to_s)
backup = SQLite3::Backup.new(dest, "main", source, "main")
result = backup.step(-1)
backup.finish
raise "the database was busy (SQLite code #{result}); try again" unless result == SQLite3::Constants::ErrorCode::DONE
ensure
dest&.close
end
# Opens the copy and checks it: SQLite's integrity check, and the same
# number of logbook entries and signatures as the live database.
def verify(path)
db = SQLite3::Database.new(path.to_s, readonly: true)
result = db.get_first_value("PRAGMA integrity_check")
raise "integrity check failed: #{result}" unless result == "ok"
counts = %w[logbook_entries entry_signatures].map { |t| [ t, db.get_first_value("SELECT COUNT(*) FROM #{t}") ] }.to_h
live = { "logbook_entries" => LogbookEntry.count, "entry_signatures" => EntrySignature.count }
raise "record counts differ (#{counts} vs #{live})" unless counts == live
"Verified: SQLite integrity check ok; #{counts['logbook_entries']} logbook entries, #{counts['entry_signatures']} signatures"
ensure
db&.close
end
# Keeps the newest few (by file time), always including the one just made.
def prune(keep_path:)
keep = Setting.integer("backups_kept")
older = Dir[DIR.join("sam-*.sqlite3")].reject { _1 == keep_path.to_s }.sort_by { File.mtime(_1) }.reverse
older.drop(keep - 1).each { File.delete(_1) }
end
end
+31
View File
@@ -0,0 +1,31 @@
# Verifies the records (AC 120-78B 3.2.2 / 3.2.4 / 3.2.8.5.3): each
# aircraft's history chain is unbroken, and every signature's seal and
# fingerprint still match. The result is kept as an IntegrityCheck.
class RecordsIntegrity
def self.check! = new.check!
def check!
problems = []
versions = 0
RecordVersion.distinct.pluck(:aircraft_id).each do |aircraft_id|
prev = nil
RecordVersion.where(aircraft_id: aircraft_id).chronological.find_each do |v|
versions += 1
tail = Aircraft.find_by(id: aircraft_id)&.tail_number || "aircraft #{aircraft_id.inspect}"
problems << "#{tail}: history entry #{v.id} doesn't follow the one before it (missing or reordered history)" if v.prev_hash != prev
problems << "#{tail}: history entry #{v.id} was altered" if v.chain_hash != RecordVersion.digest(v.prev_hash, v.payload)
prev = v.chain_hash
end
end
signatures = 0
EntrySignature.includes(logbook_entry: [ :aircraft, :parts ]).find_each do |sig|
signatures += 1
next if sig.imported? || sig.status != :altered
entry = sig.logbook_entry
problems << "#{entry.aircraft.tail_number}: the #{entry.date} logbook entry (signed by #{sig.signer_name}) " \
"#{sig.seal_valid? ? 'changed after it was signed' : 'has an altered signature'}"
end
AppRevision.touch_current!
IntegrityCheck.create!(ok: problems.empty?, versions_checked: versions, signatures_checked: signatures, problems: problems.first(200))
end
end
+100
View File
@@ -0,0 +1,100 @@
require "csv"
# Everything about an aircraft's records in one ZIP, for the FAA or NTSB on
# request (91.417(c), AC 120-78B 3.2.8.6) or a buyer at sale (91.419,
# 3.2.8.12): the logbook entries as a PDF with their electronic signatures,
# a signature register, the full change history, the status report, and the
# data archive (.sam.zip) to load into another system.
class RecordsPackage
def initialize(aircraft, source:)
@aircraft = aircraft
@source = source
@generated_at = Time.current
end
def filename = "#{@aircraft.tail_number.downcase}-records-#{@generated_at.to_date.iso8601}.zip"
def write_to(path)
entries = @aircraft.logbook_entries.includes(:component, :parts, :signature, inspection_records: :inspection_type).order(:date, :id).to_a
Zip::OutputStream.open(path) do |zip|
add(zip, "README.txt", readme(entries))
add(zip, "logbook-entries.pdf", LogbookEntryPdf.new(@aircraft, entries, layout: "letter").render) if entries.any?
add(zip, "signatures.csv", signatures_csv(entries))
add(zip, "record-history.csv", history_csv)
add(zip, "status-report.html", status_report_html)
archive = Tempfile.new([ "archive", ".sam.zip" ])
AircraftArchive::Exporter.new(@aircraft, source: @source).write_to(archive.path)
zip.put_next_entry("#{@aircraft.tail_number.downcase}.sam.zip")
File.open(archive.path, "rb") { IO.copy_stream(_1, zip) }
ensure
archive&.close!
end
path
end
private
def add(zip, name, content)
zip.put_next_entry(name)
zip.write(content)
end
def readme(entries)
signed = entries.count(&:signed?)
check = IntegrityCheck.latest
<<~TXT
Maintenance records for #{@aircraft.tail_number} (#{[ @aircraft.make, @aircraft.model ].compact_blank.join(' ')}, S/N #{@aircraft.serial_number.presence || 'not recorded'})
Prepared #{@generated_at.utc.strftime('%Y-%m-%d %H:%M UTC')} by Simple Aircraft Manager (#{@source}), software version #{SystemInfo.new.revision}.
Electronic records since: #{@aircraft.electronic_records_since&.iso8601 || 'not stated'}. Earlier records are the paper logbooks#{' (scans marked "legacy record" are in the archive)' if @aircraft.documents.where(legacy_record: true).exists?}.
Contents
- logbook-entries.pdf All #{entries.size} logbook entries, oldest first. #{signed} are signed electronically: each shows
"Certified by" the signer and certificate, the time (UTC) and the first 16 characters of its fingerprint.
- signatures.csv Every electronic signature: signer, certificate, statement, time, status and full fingerprint.
- record-history.csv Every change to the maintenance records (created, changed, deleted), with who and when.
- status-report.html Maintenance status per 14 CFR 91.417(a)(2): times, life-limited parts, inspections, ADs, alterations.
- #{@aircraft.tail_number.downcase}.sam.zip All records and files as data, to load into another system.
Signatures
Each electronic signature records who signed, with which certificate, what they certified, when, and a SHA-256
fingerprint of the entry's content at signing. A signed entry can't be edited; corrections are new signed entries
that supersede the original (both are included). Status "Valid" means the entry and signature are unchanged since
signing; "Superseded" means a later signed correction replaces it.
Last records integrity check: #{check ? "#{check.created_at.utc.strftime('%Y-%m-%d %H:%M UTC')}, #{check.ok ? 'no problems found' : "#{check.problems.size} problem(s) found"}" : 'not run yet'}.
TXT
end
def signatures_csv(entries)
CSV.generate do |csv|
csv << %w[entry_date log entry_type signer certificate_kind certificate_number signed_at_utc status fingerprint statement corrects_entry_dated]
entries.select(&:signed?).each do |e|
s = e.signature
csv << [ e.date, LogbookEntry::LOG_TYPES[e.log_type], LogbookEntry::ENTRY_TYPES[e.entry_type], s.signer_name, s.certificate_label,
s.certificate_number, s.signed_at.utc.iso8601, s.imported? ? "imported from #{s.origin}" : s.status_label,
s.content_digest, s.statement, e.supersedes&.date ]
end
end
end
def history_csv
users = User.pluck(:id, :email_address).to_h
CSV.generate do |csv|
csv << %w[id at_utc record record_id event by changed_fields chain_hash]
RecordVersion.where(aircraft_id: @aircraft.id).chronological.find_each do |v|
csv << [ v.id, v.created_at.utc.iso8601, v.item_type.underscore.humanize, v.item_id, v.event, users[v.user_id] || "system",
v.event == "update" ? v.changed_fields.join(" ") : "", v.chain_hash ]
end
end
end
# The status report as one self-contained HTML file (styles inlined).
def status_report_html
html = ApplicationController.render("maintenance_reports/show", layout: "report",
assigns: { report: MaintenanceReport.new(@aircraft) })
css = %w[tailwind.css application.css].filter_map { Rails.application.assets.load_path.find(_1)&.content }.join("\n")
html.gsub(%r{<link rel="stylesheet"[^>]*>\s*}, "").sub("</head>", "<style>#{css}</style></head>")
.gsub(%r{<script\b[^>]*>.*?</script>}m, "").gsub(%r{<link rel="modulepreload"[^>]*>\s*}, "")
end
end
+32
View File
@@ -78,6 +78,38 @@
</div>
</div>
<section class="card mt-5" id="records">
<div class="card-header">
<div>
<h2 class="card-title">Records integrity</h2>
<p class="text-xs text-slate-500">Nightly: a verified database backup, then a check of the record history chains and every electronic signature (AC 120-78B 3.2).</p>
</div>
<%= button_to "Back up and check now", admin_check_records_path, class: "btn-secondary btn-sm", data: { turbo_submits_with: "Checking…" } %>
</div>
<% check = IntegrityCheck.latest %>
<% backup = BackupRun.latest %>
<%= render "pairs", pairs: [
[ "Last check", check ? "#{l(check.created_at, format: :short)} · #{check.ok ? 'no problems' : pluralize(check.problems.size, 'problem')}" : "not run yet" ],
[ "Checked", check ? "#{number_with_delimiter(check.versions_checked)} history entries, #{number_with_delimiter(check.signatures_checked)} signatures" : nil ],
[ "Last backup", backup ? "#{l(backup.created_at, format: :short)} · #{backup.ok ? number_to_human_size(backup.bytes) : 'FAILED'}" : "not run yet" ],
[ "Backup check", backup&.message ],
[ "Backups kept", "#{Setting.integer('backups_kept')} (in storage/backups)" ]
] %>
<% if check && !check.ok %>
<ul class="list-disc space-y-1 px-8 pb-3 text-sm text-red-700"><% check.problems.each do |p| %><li><%= p %></li><% end %></ul>
<% end %>
</section>
<section class="card mt-5">
<div class="card-header"><h2 class="card-title">Software versions</h2></div>
<% revisions = AppRevision.latest_first.limit(20) %>
<% if revisions.any? %>
<%= render "pairs", pairs: revisions.map { |r| [ r.revision, "#{l(r.first_seen_at, format: :short)} – #{l(r.last_seen_at, format: :short)}" ] } %>
<% else %>
<%= empty_state "No versions recorded yet." %>
<% end %>
</section>
<details class="card mt-5">
<summary class="card-header cursor-pointer"><span class="card-title">All gems (<%= info.all_gems.size %>)</span></summary>
<div class="grid gap-x-6 px-4 py-3 font-mono text-xs sm:grid-cols-2 lg:grid-cols-3">
+9
View File
@@ -22,5 +22,14 @@
</p>
</div>
<h2 class="card-title pt-2">Backups</h2>
<% kept = Setting::INTEGERS["backups_kept"] %>
<div>
<%= label_tag "settings[backups_kept]", kept[:label], class: "label" %>
<%= number_field_tag "settings[backups_kept]", @values["backups_kept"], id: "settings_backups_kept", min: kept[:in].min, max: kept[:in].max,
step: 1, required: true, class: "input w-32" %>
<p class="hint">A verified copy of the database is made nightly in storage/backups; this many of the newest are kept. Back up the whole storage volume off the server too.</p>
</div>
<div class="flex gap-2"><%= f.submit "Save Settings", class: "btn-primary" %><%= link_to "Cancel", admin_about_path, class: "btn-secondary" %></div>
<% end %>
@@ -0,0 +1,5 @@
<p>Last night's records check found a problem.</p>
<p>Backup: <strong><%= @backup.ok ? "OK" : "FAILED: #{@backup.message}" %></strong><br>
Integrity check: <strong><%= @check.ok ? "OK" : "#{@check.problems.size} problem(s)" %></strong></p>
<ul><% Array(@check.problems).first(20).each do |p| %><li><%= p %></li><% end %></ul>
<p>See Admin → About for details.</p>
@@ -0,0 +1,9 @@
Last night's records check found a problem.
Backup: <%= @backup.ok ? "OK" : "FAILED: #{@backup.message}" %>
Integrity check: <%= @check.ok ? "OK" : "#{@check.problems.size} problem(s)" %>
<% Array(@check.problems).first(20).each do |p| %>
- <%= p %>
<% end %>
See Admin → About for details.
+2
View File
@@ -25,6 +25,8 @@
<p class="hint">To change hours use “Update Hours” on the overview, so component times stay in sync.</p>
<% end %>
<%= f.field :picture, as: :file, accept: "image/*" %>
<%= f.field :electronic_records_since, as: :date, label: "Electronic records since", wrapper: { class: "max-w-xs" },
hint: "The date this app became the maintenance record. Earlier records stay in the paper logbooks (mark their scans as legacy records)." %>
<%= f.field :airworthiness_enforcement, as: :checkbox, label: "Enforce airworthiness",
hint: "Block flight logs and hours updates while the aircraft shows Grounded." %>
<div class="flex gap-2">
+7
View File
@@ -67,5 +67,12 @@
</div>
<%= link_to "Download .sam.zip", aircraft_export_path(@aircraft), class: "btn-secondary", data: { turbo: false } %>
</div>
<div class="card-header border-t border-slate-100">
<div>
<h2 class="card-title">Records package</h2>
<p class="hint">For an FAA or NTSB request, or a buyer: every logbook entry as a PDF with its electronic signature, a signature register, the full change history, the status report, and the .sam.zip, in one ZIP with a README.</p>
</div>
<%= link_to "Download records package", aircraft_records_package_path(@aircraft), class: "btn-secondary", data: { turbo: false } %>
</div>
</section>
</div>
+1
View File
@@ -2,6 +2,7 @@
<div>
<%= link_to doc.name, aircraft_document_path(aircraft, doc), class: "link font-medium" %>
<span class="ml-2 text-xs text-slate-500"><%= doc.type_label %> · <%= pluralize(doc.pages.size, "file") %></span>
<% if doc.legacy_record? %><span class="ml-1 badge-gray" title="Scan of the paper (legacy) records">Legacy record</span><% end %>
<% if doc.expires_on %><span class="ml-1 <%= doc.expired? ? 'badge-red' : (Date.current + doc.expiry_warning_days >= doc.expires_on ? 'badge-orange' : 'badge-gray') %>"><%= doc.expired? ? "Expired" : "Expires" %> <%= doc.expires_on %></span><% end %>
<% if doc.description.present? %><div class="text-xs text-slate-500"><%= doc.description.truncate(120) %></div><% end %>
</div>
+2
View File
@@ -8,6 +8,8 @@
<%= f.field :visibility, as: :select, label: "Share-link visibility",
collection: [["Inherit from collection", nil]] + DocumentCollection::VISIBILITIES.invert.to_a %>
</div>
<%= f.field :legacy_record, as: :checkbox, label: "Legacy record (a scan of the paper logbooks or records)",
hint: "Records from before the electronic records began. Keep the paper originals." %>
<%= f.field :expires_on, as: :date, label: "Expires on", wrapper: { class: "max-w-xs" },
hint: "Optional. Registration (good for 7 years, 14 CFR 47.40), insurance, radio license… You'll be reminded before it expires; an expired registration shows the aircraft grounded." %>
<%= f.field :description, as: :textarea, rows: 2 %>
+3
View File
@@ -3,9 +3,12 @@
<section class="card">
<div class="card-header">
<h2 class="card-title">Activity Log</h2>
<div class="flex flex-wrap items-center gap-2">
<%= link_to "Record history", aircraft_record_versions_path(@aircraft), class: "btn-secondary btn-sm", title: "Every change to the maintenance records, field by field" %>
<%= form_with url: aircraft_events_path(@aircraft), method: :get, class: "flex gap-2" do |f| %>
<%= f.select :category, AircraftEvent::CATEGORIES.invert, { include_blank: "All categories", selected: @category }, class: "input", data: { submit_on_change: true } %>
<% end %>
</div>
</div>
<%= render "events/list", events: @events, full: true %>
</section>
+8
View File
@@ -58,3 +58,11 @@
<% end %>
</div>
</section>
<% history = (@entry.versions.to_a + @entry.parts.flat_map { _1.versions.to_a } + (@entry.signature ? @entry.signature.versions.to_a : [])).sort_by(&:id).reverse %>
<% if history.any? %>
<details class="card mt-5 max-w-4xl">
<summary class="card-header cursor-pointer"><span class="card-title">Change history (<%= history.size %>)</span></summary>
<%= render "record_versions/list", versions: history %>
</details>
<% end %>
@@ -22,6 +22,7 @@
<dt class="text-slate-500">Airframe time in service</dt><dd class="font-semibold"><%= hours(@report.time_in_service) %> hrs (<%= clock %>)</dd>
<dt class="text-slate-500">Tach / Hobbs</dt><dd><%= hours(a.tach_time) %> / <%= hours(a.hobbs_time) %></dd>
<dt class="text-slate-500">Status</dt><dd><%= airworthiness_badge(@report.airworthiness) %></dd>
<dt class="text-slate-500">Electronic records since</dt><dd><%= a.electronic_records_since || "—" %></dd>
</dl>
</header>
+19
View File
@@ -0,0 +1,19 @@
<%# Locals: versions. %>
<ul class="divide-y divide-slate-100 text-sm">
<% versions.each do |v| %>
<li class="px-4 py-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 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="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>
<% if v.event == "update" %>
<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)| %>
<dt class="text-slate-500"><%= field.humanize %></dt><dd class="break-words"><span class="line-through decoration-slate-400"><%= before.to_s.truncate(120).presence || "—" %></span> → <%= after.to_s.truncate(120).presence || "—" %></dd>
<% end %>
</dl>
<% end %>
</li>
<% end %>
</ul>
+14
View File
@@ -0,0 +1,14 @@
<% content_for :title, "#{@aircraft.tail_number} Record history" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<section class="card">
<div class="card-header">
<div>
<h2 class="card-title">Record history</h2>
<p class="text-xs text-slate-500">Every change to the maintenance records, kept for good and chained so that removing or altering history shows in the nightly check.</p>
</div>
<%= form_with url: aircraft_record_versions_path(@aircraft), method: :get, class: "flex gap-2" do %>
<%= 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 %>
</div>
<% if @versions.any? %><%= render "record_versions/list", versions: @versions %><% else %><%= empty_state "No changes recorded yet." %><% end %>
</section>