Move all user-facing text into config/locales/en.yml for localization

- Views use lazy t(".key") lookups; sentences with values or links stay
  whole (interpolation, _html keys); counts use one/other plurals
- Stored-value labels (statuses, types, priorities...) are LabelSets read
  from labels: in the current locale; field names and validation messages
  under activerecord:; flash and activity text under flash:
- Services, models, helpers, mailer subjects, the logbook PDF, procedures
  templates, records package README and transcription warnings localized;
  the PDF reuses LogbookEntry#certification_statement instead of a copy
- Scripts read js: strings from a JSON tag via app/javascript/i18n.js
- Dates through I18n.l (app, weekday, month_year, long formats); html lang
  follows the locale
- APP_LOCALE picks the language (falls back to English); missing
  translations raise in development and tests
- README: Translating section and APP_LOCALE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-13 22:08:20 -05:00
1 parent 3f45b557c2
commit 89ed0a76f9
313 files changed
+6387 -2653

No files matched your search

+28 -28
View File
@@ -13,8 +13,8 @@ require "roo"
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
ACTIONS = LabelSet.new("ad_import.actions", %w[track na skip])
def self.na_note = I18n.t("services.ad_import.na_note")
# DRS export headers, normalized (lowercase letters only).
HEADERS = {
@@ -27,15 +27,15 @@ class AdImport
# 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 } ]
short_description: [ :short_description, ->(r) { r.subject.to_s.truncate(254).presence } ],
required_action: [ :required_action, ->(r) { r.summary } ],
effective_date: [ :effective_date, ->(r) { r.effective_date } ],
docket_number: [ :docket_number, ->(r) { r.docket } ],
supersedes: [ :supersedes, ->(r) { r.supersedes.join(", ").presence } ],
superseded_by: [ :superseded_by, ->(r) { r.superseded_by.join(", ").presence } ],
applicable_models: [ :applicable_models, ->(r) { r.models.join(", ").presence } ],
product_type: [ :product_type, ->(r) { r.product_type } ],
document_url: [ :document_url, ->(r) { r.url } ]
}.freeze
Row = Struct.new(:line, :number, :subject, :status, :effective_date, :docket, :models, :product_type,
@@ -76,7 +76,7 @@ class AdImport
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)
not_applicable: true, compliance_notes: AdImport.na_note)
end
result[:not_applicable] += 1
else
@@ -84,9 +84,9 @@ class AdImport
end
end
imported = result[:tracked] + result[:not_applicable]
raise Error, "Nothing selected to import." if imported.zero?
raise Error, I18n.t("services.ad_import.nothing_selected") 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")
notes: I18n.t("services.ad_import.event_notes", file: @filename, tracked: result[:tracked], not_applicable: result[:not_applicable], skipped: result[:skipped]))
end
result
end
@@ -126,31 +126,31 @@ class AdImport
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")
prefix = I18n.t(row.tracked ? "services.ad_import.already_tracked" : "services.ad_import.will_link")
row.note(row.changes.any? ? I18n.t("services.ad_import.will_update", prefix: prefix, fields: row.changes.join(", ")) : I18n.t("services.ad_import.up_to_date", prefix: prefix))
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?
skip_reasons << I18n.t("services.ad_import.faa_status", status: row.status) if row.status.present? && !row.status.casecmp?("current")
skip_reasons << I18n.t("services.ad_import.superseded_by", ads: 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"
skip_reasons << I18n.t("services.ad_import.model_not_listed", model: @aircraft.model)
end
skip_reasons.each { row.note(row.tracked ? "#{_1}: review whether it still applies" : _1) }
skip_reasons.each { row.note(row.tracked ? I18n.t("services.ad_import.review", reason: _1) : _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")
row.note(I18n.t("services.ad_import.appliance"))
end
if row.summary =~ /Supplemental Type Certificate|\bSTC\b/i
row.note("Mentions an STC: may apply only if that modification is installed")
row.note(I18n.t("services.ad_import.stc"))
end
if row.summary =~ /repetitive|recurring|reinspect/i
row.note("Mentions repetitive actions: set the recurrence after import")
row.note(I18n.t("services.ad_import.repetitive"))
end
(row.supersedes & tracked_numbers.to_a).each do |old|
row.note("Supersedes #{old}, which this aircraft still tracks; consider removing it")
row.note(I18n.t("services.ad_import.supersedes_tracked", ad: old))
end
row
end
@@ -172,7 +172,7 @@ class AdImport
end
def changed_fields(ad, row)
faa_attributes(row).filter_map { |attr, value| FAA_FIELDS[attr][0] if ad.public_send(attr) != value }
faa_attributes(row).filter_map { |attr, value| I18n.t(attr, scope: "services.ad_import.fields") if ad.public_send(attr) != value }
end
def locate_header
@@ -189,15 +189,15 @@ class AdImport
return [ sheet, i, cols ]
end
end
raise Error, "This doesn't look like an FAA DRS export: no “AD Number” column found."
raise Error, I18n.t("services.ad_import.not_drs")
end
def open_spreadsheet
ext = File.extname(@filename).delete(".").downcase
raise Error, "Upload an .xlsx or .csv file." unless ext.in?(%w[xlsx csv])
raise Error, I18n.t("flash.uploads.spreadsheet_only") 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})."
raise Error, I18n.t("services.ad_import.unreadable", message: e.message)
end
# Link to the AD document: a hyperlink on any cell in the row (Excel exports),
+2 -2
View File
@@ -136,9 +136,9 @@ class AdWatch
response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 20) do |http|
http.get(uri.request_uri, "Accept" => "application/json", "User-Agent" => "SimpleAircraftManager")
end
raise Error, "the Federal Register returned #{response.code}" unless response.is_a?(Net::HTTPSuccess)
raise Error, I18n.t("services.ad_watch.the_federal_register_returned", code: response.code) unless response.is_a?(Net::HTTPSuccess)
Array(JSON.parse(response.body)["results"]).select { _1["title"].to_s.start_with?("Airworthiness Directives") }
rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError, JSON::ParserError => e
raise Error, "couldn't reach the Federal Register (#{e.class.name.demodulize})"
raise Error, I18n.t("services.ad_watch.couldn_t_reach_the_federal", error: e.class.name.demodulize)
end
end
+1 -1
View File
@@ -67,7 +67,7 @@ class AirTrailClient
open_timeout: @timeout, read_timeout: @timeout) { _1.request(req) }
handle(response)
rescue Timeout::Error, SocketError, SystemCallError, OpenSSL::SSL::SSLError, EOFError, IOError => e
raise NetworkError, "Can't reach AirTrail at #{@base.host}: #{e.message}"
raise NetworkError, I18n.t("services.air_trail.can_t_reach_airtrail_at", host: @base.host, message: e.message)
end
def handle(response)
+3 -3
View File
@@ -28,9 +28,9 @@ class AirTrailExport
def valid?
@errors = []
@errors << "AirTrail username must be 3–20 letters, numbers, “.”, “_” or “-”" unless @username.match?(USERNAME_FORMAT)
@errors << "Aircraft type must be an ICAO type designator like C150 (up to 4 letters/numbers)" if @aircraft_type && !@aircraft_type.match?(TYPE_FORMAT)
@errors << "No flights to export" if exportable.empty?
@errors << I18n.t("services.air_trail.airtrail_username_must_be_3") unless @username.match?(USERNAME_FORMAT)
@errors << I18n.t("services.air_trail.aircraft_type_must_be_an") if @aircraft_type && !@aircraft_type.match?(TYPE_FORMAT)
@errors << I18n.t("services.air_trail.no_flights_to_export") if exportable.empty?
@errors.empty?
end
+1 -1
View File
@@ -27,7 +27,7 @@ module AirTrailFlightData
end
def note(flight)
times = [ "Tach #{flight.tach_time} h", (flight.hobbs_time && "Hobbs #{flight.hobbs_time} h") ].compact.join(" · ")
times = [ I18n.t("services.air_trail.tach", hours: flight.tach_time), (flight.hobbs_time && I18n.t("services.air_trail.hobbs", hours: flight.hobbs_time)) ].compact.join(" · ")
[ times, flight.route.presence, flight.notes.presence ].compact.join("\n").truncate(1000)
end
+2 -2
View File
@@ -101,7 +101,7 @@ class AirTrailSyncer
# Look an airport code up in AirTrail (cached per connection).
def airport_id(code)
normalized = AirTrailFlightData.airport_code(code)
raise UnresolvedAirport, "Airport “#{code.presence || '(blank)'}” isn't a code AirTrail can use" unless normalized
raise UnresolvedAirport, I18n.t("services.air_trail.unusable_code", code: code.presence || I18n.t("services.air_trail.blank")) unless normalized
cached = @connection.airports.find_or_initialize_by(code: normalized)
fresh = cached.manual? || cached.remote_id || (cached.looked_up_at && cached.looked_up_at > AIRPORT_RECHECK.ago)
@@ -110,7 +110,7 @@ class AirTrailSyncer
match = results.find { _1["icao"].to_s.casecmp?(normalized) } || results.find { _1["iata"].to_s.casecmp?(normalized) }
cached.update!(remote_id: match&.dig("id"), remote_icao: match&.dig("icao"), looked_up_at: Time.current)
end
cached.remote_id or raise UnresolvedAirport, "AirTrail doesn't know airport #{normalized}. Map it on your AirTrail settings page"
cached.remote_id or raise UnresolvedAirport, I18n.t("services.air_trail.airtrail_doesn_t_know_airport", normalized: normalized)
end
# Map a code to an airport the user names (e.g. its ICAO/GPS code in AirTrail).
+20 -20
View File
@@ -35,7 +35,7 @@ module AircraftArchive
Zip::File.open(path) do |zip|
inner = nested_archive(zip)
next yield(zip) unless inner
raise Error, "The archive inside the records package is too large." if inner.size > ARCHIVE_MAX_BYTES
raise Error, I18n.t("services.aircraft_archive.the_archive_inside_the_records") if inner.size > ARCHIVE_MAX_BYTES
Tempfile.create([ "sam-inner", ".zip" ], binmode: true) do |tmp|
inner.get_input_stream { |io| IO.copy_stream(io, tmp) }
tmp.flush
@@ -43,7 +43,7 @@ module AircraftArchive
end
end
rescue Zip::Error => e
raise Error, "Not a valid .sam.zip archive (#{e.message})"
raise Error, I18n.t("services.aircraft_archive.not_a_valid_sam_zip", message: e.message)
end
# The single *.sam.zip entry of a records package (no manifest of its own).
@@ -65,32 +65,32 @@ module AircraftArchive
def self.validate_zip(zip)
uncompressed = compressed = 0
zip.each do |entry|
raise Error, "The archive contains a link (#{entry.name}), which isn't allowed." if entry.symlink?
raise Error, "The archive contains an unsafe path: #{entry.name}" unless safe_name?(entry.name)
raise Error, I18n.t("services.aircraft_archive.the_archive_contains_a_link", entry: entry.name) if entry.symlink?
raise Error, I18n.t("services.aircraft_archive.the_archive_contains_an_unsafe", entry: entry.name) unless safe_name?(entry.name)
uncompressed += entry.size
compressed += entry.compressed_size
raise Error, "The archive is too large once unpacked." if uncompressed > ARCHIVE_MAX_BYTES
raise Error, I18n.t("services.aircraft_archive.the_archive_is_too_large") if uncompressed > ARCHIVE_MAX_BYTES
end
raise Error, "The archive is compressed suspiciously well (over #{MAX_RATIO}:1)." if compressed.positive? && uncompressed / compressed > MAX_RATIO
raise Error, I18n.t("services.aircraft_archive.the_archive_is_compressed_suspiciously", _: MAX_RATIO) if compressed.positive? && uncompressed / compressed > MAX_RATIO
entry = zip.find_entry("#{root_prefix(zip)}manifest.json") or raise Error, "The archive has no manifest.json. Is it a .sam.zip export?"
raise Error, "manifest.json is too large." if entry.size > MANIFEST_MAX_BYTES
entry = zip.find_entry("#{root_prefix(zip)}manifest.json") or raise Error, I18n.t("services.aircraft_archive.the_archive_has_no_manifest")
raise Error, I18n.t("services.aircraft_archive.manifest_json_is_too_large") if entry.size > MANIFEST_MAX_BYTES
manifest = begin
JSON.parse(entry.get_input_stream.read.force_encoding("UTF-8"))
rescue JSON::ParserError => e
raise Error, "manifest.json couldn't be read (#{e.message.truncate(120)})"
raise Error, I18n.t("services.aircraft_archive.manifest_json_couldn_t_be", truncate: (e.message.truncate(120)))
end
raise Error, "manifest.json isn't a JSON object." unless manifest.is_a?(Hash)
raise Error, I18n.t("services.aircraft_archive.manifest_json_isn_t_a") unless manifest.is_a?(Hash)
version = manifest["schema_version"]
unless version.is_a?(Integer) && version.between?(1, SCHEMA_VERSION)
raise Error, "Unsupported archive version #{version.inspect} (this app reads versions 1–#{SCHEMA_VERSION})."
raise Error, I18n.t("services.aircraft_archive.unsupported_archive_version_this_app", version: version.inspect, _: SCHEMA_VERSION)
end
required = TOP_LEVEL_KEYS - OPTIONAL_KEYS - (version < 2 ? %w[flight_logs] : [])
missing = required - manifest.keys
raise Error, "manifest.json is missing #{missing.to_sentence}." if missing.any?
raise Error, I18n.t("services.aircraft_archive.manifest_json_is_missing", to_sentence: missing.to_sentence) if missing.any?
raise Error, "manifest.json has no aircraft tail number." unless manifest["aircraft"].is_a?(Hash) && manifest["aircraft"]["tail_number"].present?
RECORD_SECTIONS.each { |key| raise Error, "manifest.json #{key} must be a list." unless manifest[key].nil? || manifest[key].is_a?(Array) }
RECORD_SECTIONS.each { |key| raise Error, I18n.t("services.aircraft_archive.manifest_json_must_be_a", key: key) unless manifest[key].nil? || manifest[key].is_a?(Array) }
manifest
end
@@ -207,7 +207,7 @@ module AircraftArchive
ordered.each do |data|
type_id = @map[:component_type][data["component_type_id"].to_s]
next warn("Component #{data['manufacturer']} #{data['model']}: unknown component type, skipped.") unless type_id
next warn(I18n.t("services.aircraft_archive.component_unknown_component_type_skipped", manufacturer: (data["manufacturer"]), model: (data["model"]))) unless type_id
c = @aircraft.components.new(
component_type_id: type_id, parent_component_id: @map[:component][data["parent_component_id"].to_s],
manufacturer: data["manufacturer"].to_s, model: data["model"].to_s, serial_number: data["serial_number"].to_s,
@@ -329,7 +329,7 @@ module AircraftArchive
end
m("inspection_records").each do |data|
type_id = @map[:inspection_type][data["inspection_type_id"].to_s]
next warn("An inspection record from #{data['date']} has no inspection type and was skipped.") unless type_id
next warn(I18n.t("services.aircraft_archive.an_inspection_record_from_has", date: (data["date"]))) unless type_id
r = @aircraft.inspection_records.new(
inspection_type_id: type_id, date: date(data["date"]) || Date.new(1900, 1, 1), aircraft_hours: num(data["aircraft_hours"]),
logbook_entry_id: @map[:logbook][data["logbook_entry_id"].to_s], notes: data["notes"],
@@ -515,17 +515,17 @@ module AircraftArchive
end
def upload(archive_path)
raise Error, "unsafe file path #{archive_path}" unless self.class.safe_name?(archive_path)
entry = @zip.find_entry("#{@root}#{archive_path}") or raise Error, "file #{File.basename(archive_path)} isn't in the archive"
raise Error, "#{File.basename(archive_path)} is too large" if entry.size > FILE_MAX_BYTES
raise Error, I18n.t("services.aircraft_archive.unsafe_file_path", archive_path: archive_path) unless self.class.safe_name?(archive_path)
entry = @zip.find_entry("#{@root}#{archive_path}") or raise Error, I18n.t("services.aircraft_archive.file_isn_t_in_the", basename: (File.basename(archive_path)))
raise Error, I18n.t("services.aircraft_archive.is_too_large", basename: (File.basename(archive_path))) if entry.size > FILE_MAX_BYTES
ext = AircraftArchive.extension(archive_path)
raise Error, "#{File.basename(archive_path)} isn't an allowed file type" unless EXTENSIONS.include?(ext)
raise Error, I18n.t("services.aircraft_archive.isn_t_an_allowed_file", basename: (File.basename(archive_path))) unless EXTENSIONS.include?(ext)
Tempfile.create([ "sam-import", ".#{ext}" ], binmode: true) do |tmp|
entry.get_input_stream { |input| IO.copy_stream(input, tmp) }
tmp.rewind
head = tmp.read(16).to_s
raise Error, "#{File.basename(archive_path)} doesn't contain what its name says (.#{ext})" unless AircraftArchive.content_matches?(head, ext)
raise Error, I18n.t("services.aircraft_archive.doesn_t_contain_what_its", basename: (File.basename(archive_path)), ext: ext) unless AircraftArchive.content_matches?(head, ext)
tmp.rewind
ActiveStorage::Blob.create_and_upload!(io: tmp, filename: File.basename(archive_path)).tap { @created_blobs << _1 }
end
+1 -1
View File
@@ -6,6 +6,6 @@ class AircraftGroundedError < StandardError
def initialize(airworthiness)
@airworthiness = airworthiness
reasons = airworthiness.red_issues.map(&:title).join("; ")
super([ "Aircraft is grounded and airworthiness enforcement is enabled", reasons.presence ].compact.join(": "))
super([ I18n.t("services.aircraft_grounded_error.message"), reasons.presence ].compact.join(": "))
end
end
+1 -1
View File
@@ -64,7 +64,7 @@ class AirportCodeStandardizer
elsif airport.code != code
renamed = !airport.code.end_with?(code) # e.g. 4MB → K5M3, not just a K prefix
note = if airport.kind == "closed" then "Closed airport. Check it's the right one"
elsif renamed then "Different identifier, not just a prefix. Check it's the right field"
elsif renamed then I18n.t("services.airport_codes.different_identifier_not_just_a")
end
changes << Change.new(from: code, to: airport.code, airport: airport, flights: n,
suggested: airport.kind != "closed", note: note)
+36 -30
View File
@@ -18,9 +18,12 @@ class Airworthiness
INFO = "INFO" # listed for awareness; doesn't change the status (a deferred inoperative item)
ORANGE = "ORANGE"
GREEN = "GREEN"
DISCLAIMER = "Based on the records in this app. Before each flight the pilot in command decides whether the aircraft is airworthy (14 CFR 91.7)."
def self.disclaimer = I18n.t("services.airworthiness.disclaimer")
def self.t(key, **opts) = I18n.t(key, scope: "services.airworthiness", **opts)
Issue = Struct.new(:category, :severity, :title, :description, :item, :limitation, keyword_init: true)
Issue = Struct.new(:category, :severity, :title, :description, :item, :limitation, keyword_init: true) do
def category_label = Airworthiness.t(category, scope: "services.airworthiness.categories")
end
Status = Struct.new(:status, :issues, keyword_init: true) do
def red? = status == RED
@@ -32,10 +35,10 @@ class Airworthiness
def label
case status
when RED then "Grounded"
when RED then Airworthiness.t(:grounded)
when LIMITED then limitations.join(" · ")
when ORANGE then "Due soon"
else "Current"
when ORANGE then Airworthiness.t(:due_soon)
else Airworthiness.t(:current)
end
end
end
@@ -65,6 +68,8 @@ class Airworthiness
private
def t(key, **opts) = self.class.t(key, **opts)
def add(category, severity, title, description, item, limitation: nil)
@issues << Issue.new(category:, severity:, title:, description:, item:, limitation:)
end
@@ -76,21 +81,21 @@ class Airworthiness
label = ad.bulletin_label
case res.rank
when Compliance::OVERDUE
desc = compliance ? "#{ad.short_description}. Compliance overdue." : "#{ad.short_description}. No compliance record found."
add("AD", RED, "#{label} #{ad.name} - Overdue", desc, ad)
desc = t(compliance ? :ad_overdue : :ad_no_record, description: ad.short_description)
add("AD", RED, t(:ad_overdue_title, label: label, name: ad.name), desc, ad)
when Compliance::DUE_SOON
add("AD", ORANGE, "#{label} #{ad.name} - Due Soon", "#{ad.short_description}. Compliance due soon.", ad)
add("AD", ORANGE, t(:ad_due_soon_title, label: label, name: ad.name), t(:ad_due_soon, description: ad.short_description), ad)
end
end
end
def check_grounding_squawks
@aircraft.squawks.active.where(priority: 0, deferred_at: nil).find_each do |squawk|
add("SQUAWK", RED, "Grounding Squawk", squawk.issue_reported.to_s.truncate(100).presence || "No description", squawk)
add("SQUAWK", RED, t(:grounding_squawk), squawk.issue_reported.to_s.truncate(100).presence || t(:no_description), squawk)
end
@aircraft.squawks.deferred.find_each do |squawk|
add("DEFERRED", INFO, "Inoperative: #{squawk.issue_reported.to_s.truncate(80)}",
"Deferred under 91.213(d) on #{squawk.deferred_at.to_date} by #{squawk.deferred_by_name}. Fix at the next inspection.", squawk)
add("DEFERRED", INFO, t(:inoperative, issue: squawk.issue_reported.to_s.truncate(80)),
t(:deferred, date: squawk.deferred_at.to_date, name: squawk.deferred_by_name), squawk)
end
end
@@ -100,14 +105,14 @@ class Airworthiness
res = Compliance.inspection_status(type, records, @hours, @today)
case res.rank
when Compliance::OVERDUE
title = "#{type.name} - #{records.any? ? 'Overdue' : 'Never Completed'}"
title = t(records.any? ? :inspection_overdue_title : :inspection_never_title, name: type.name)
if (limitation = type.limitation)
add("INSPECTION", LIMITED, title, "#{limitation} until it's done.", type, limitation: limitation)
add("INSPECTION", LIMITED, title, t(:limited_until_done, limitation: limitation), type, limitation: limitation)
else
add("INSPECTION", RED, title, overdue_description(type, records, res), type)
end
when Compliance::DUE_SOON
add("INSPECTION", ORANGE, "#{type.name} - Due Soon", "Inspection due soon.", type)
add("INSPECTION", ORANGE, t(:inspection_due_soon_title, name: type.name), t(:inspection_due_soon), type)
end
end
end
@@ -115,13 +120,12 @@ class Airworthiness
# The 100-hour may be overflown by up to its tolerance only to reach a
# place where it can be done (91.409(b)); say so while that's still open.
def overdue_description(type, records, res)
return "Required inspection has no completion record." if records.empty?
return t(:no_completion_record) if records.empty?
over = res.next_due_hours && @hours - res.next_due_hours
if over && type.hours_tolerance.positive? && over <= type.hours_tolerance
"Inspection overdue. It may be flown up to #{type.hours_tolerance.to_s.sub(/\.0\z/, '')} hrs past due only to reach " \
"a place where it can be done; that time counts toward the next interval (91.409(b))."
t(:inspection_overdue_tolerance, hours: type.hours_tolerance.to_s.sub(/\.0\z/, ""))
else
"Inspection overdue."
t(:inspection_overdue)
end
end
@@ -129,10 +133,10 @@ class Airworthiness
@aircraft.documents.expiring.find_each do |doc|
grounds = Document::GROUNDING_EXPIRY_TYPES.include?(doc.doc_type)
if doc.expired?(@today)
add("DOCUMENT", grounds ? RED : ORANGE, "#{doc.name} - Expired",
"#{doc.type_label} expired #{doc.expires_on}.#{' The aircraft may not be flown without a current registration (91.203).' if grounds}", doc)
add("DOCUMENT", grounds ? RED : ORANGE, t(:expired_title, name: doc.name),
t(grounds ? :document_expired_grounds : :document_expired, type: doc.type_label, date: doc.expires_on), doc)
elsif @today + doc.expiry_warning_days >= doc.expires_on
add("DOCUMENT", ORANGE, "#{doc.name} - Expires Soon", "#{doc.type_label} expires #{doc.expires_on}.", doc)
add("DOCUMENT", ORANGE, t(:expires_soon_title, name: doc.name), t(:document_expires, type: doc.type_label, date: doc.expires_on), doc)
end
end
end
@@ -142,26 +146,27 @@ class Airworthiness
scope.includes(:component_type).find_each do |c|
overdue = false
approaching = false
expiring = false
desc = ""
if c.replacement_critical? && c.replacement_hours
used = c.replacement_hours_used
if used >= c.replacement_hours
overdue = true
desc = "Replace every #{c.replacement_hours} hrs. Current: #{used} hrs#{' since installed' if c.replacement_from_install?}."
desc = t(c.replacement_from_install? ? :replace_every_hours_installed : :replace_every_hours, hours: c.replacement_hours, used: used)
elsif used + HOURS_WARNING >= c.replacement_hours
approaching = true
desc = "Replace in #{c.replacement_hours - used} hrs."
desc = t(:replace_in_hours, hours: c.replacement_hours - used)
end
end
if c.replacement_critical? && (due = c.next_replacement_date)
if @today >= due
overdue = true
desc = "Replace every #{c.replacement_interval_label}. #{c.replacement_from_install? ? 'Installed' : 'Last serviced'} #{c.replacement_counted_from}."
desc = t(c.replacement_from_install? ? :replace_every_installed : :replace_every_serviced, interval: c.replacement_interval_label, date: c.replacement_counted_from)
elsif @today + DAYS_WARNING >= due
approaching = true
desc = "Replace in #{(due - @today).to_i} days."
desc = t(:replace_in_days, count: (due - @today).to_i)
end
end
@@ -169,19 +174,20 @@ class Airworthiness
if c.expires_on
if c.expired?(@today)
expired = true
desc = "Expired #{c.expires_on}."
desc = t(:component_expired, date: c.expires_on)
elsif @today + DAYS_WARNING >= c.expires_on
approaching = true
desc = "Expires #{c.expires_on}."
expiring = true
desc = t(:component_expires, date: c.expires_on)
end
end
if overdue || (expired && c.replacement_critical?)
add("COMPONENT", RED, "#{c} - #{expired ? 'Expired' : 'Replacement Overdue'}", desc, c)
add("COMPONENT", RED, t(expired ? :expired_title : :replacement_overdue_title, name: c), desc, c)
elsif expired
add("COMPONENT", ORANGE, "#{c} - Expired", desc, c)
add("COMPONENT", ORANGE, t(:expired_title, name: c), desc, c)
elsif approaching
add("COMPONENT", ORANGE, "#{c} - #{c.expires_on && desc.start_with?('Expires') ? 'Expires Soon' : 'Replacement Due Soon'}", desc, c)
add("COMPONENT", ORANGE, t(expiring ? :expires_soon_title : :replacement_due_soon_title, name: c), desc, c)
end
end
end
+1 -1
View File
@@ -43,7 +43,7 @@ class DatabaseBackup
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"
I18n.t("services.database_backup.verified_sqlite_integrity_check_ok", logbook_entries: (counts["logbook_entries"]), entry_signatures: (counts["entry_signatures"]))
ensure
db&.close
end
+6 -6
View File
@@ -44,7 +44,7 @@ class DueList
def inspections
Compliance.inspection_rows(@aircraft).map do |r|
item("inspection-#{r.type.id}", "#{r.type.name} due", "inspection", @urls.aircraft_inspections_path(@aircraft),
item("inspection-#{r.type.id}", I18n.t("services.due_list.due", type: r.type.name), "inspection", @urls.aircraft_inspections_path(@aircraft),
date: r.next_due_date, hours_left: hours_left(r.next_due_hours))
end
end
@@ -52,7 +52,7 @@ class DueList
def ads
Compliance.ad_rows(@aircraft).map do |r|
next if r.status.to_s.in?(%w[not_applicable na conditional])
item("ad-#{r.ad.id}", "AD #{r.ad.name} due", "ad", @urls.aircraft_airworthiness_directives_path(@aircraft),
item("ad-#{r.ad.id}", I18n.t("services.due_list.ad_due", ad: r.ad.name), "ad", @urls.aircraft_airworthiness_directives_path(@aircraft),
date: r.next_due_date, hours_left: hours_left(r.next_due_hours))
end
end
@@ -63,19 +63,19 @@ class DueList
path = @urls.aircraft_component_path(@aircraft, c)
since_service = c.hours_since_overhaul.to_d
[
(item("replace-#{c.id}", "Replace #{label}", "component", path, date: c.next_replacement_date,
(item("replace-#{c.id}", I18n.t("services.due_list.replace", label: label), "component", path, date: c.next_replacement_date,
hours_left: c.hours_to_replacement) if c.replacement_hours || c.replacement_calendar?),
(item("tbo-#{c.id}", "#{label} reaches TBO", "component", path,
(item("tbo-#{c.id}", I18n.t("services.due_list.reaches_tbo", label: label), "component", path,
date: c.tbo_after(c.overhaul_date),
hours_left: c.tbo_hours && c.tbo_hours - since_service) if (c.tbo_hours || c.tbo_calendar?) && !c.on_condition?),
(item("expires-#{c.id}", "#{label} expires", "component", path, date: c.expires_on) if c.expires_on)
(item("expires-#{c.id}", I18n.t("services.due_list.expires", label: label), "component", path, date: c.expires_on) if c.expires_on)
]
end
end
def documents
@aircraft.documents.expiring.map do |d|
item("document-#{d.id}", "#{d.name} expires", "document", @urls.aircraft_document_path(@aircraft, d), date: d.expires_on)
item("document-#{d.id}", I18n.t("services.due_list.expires_2", d: d.name), "document", @urls.aircraft_document_path(@aircraft, d), date: d.expires_on)
end
end
end
+3 -3
View File
@@ -137,7 +137,7 @@ class EngineDataParser
lines = @content.lines.map(&:chomp)
header_at = lines.index { _1.start_with?("TIME,") }
unless header_at && @content[0, 500].match?(/CGR-30|Electronics International/i)
raise Error, "Not a recognized engine monitor file (expected a CGR-30P/CGR-30C .csv recording)"
raise Error, I18n.t("services.engine_data.not_a_recognized_engine_monitor")
end
metadata = parse_metadata(lines[0...header_at])
@@ -159,7 +159,7 @@ class EngineDataParser
times << local - utc_offset
columns.each { |key, i| values[key] << number(fields[i]) }
end
raise Error, "No data rows found" if times.size < 2
raise Error, I18n.t("services.engine_data.no_data_rows_found") if times.size < 2
channels = columns.keys.to_h do |key|
label, unit = describe(key)
@@ -185,7 +185,7 @@ class EngineDataParser
def clock(meta)
local = parse_time(meta[:local_time])
zulu = parse_time(meta[:zulu_time])
raise Error, "Recording has no start date (Local Time line missing)" unless local
raise Error, I18n.t("services.engine_data.recording_has_no_start_date") unless local
offset = zulu ? ((local - zulu) / 900).round * 900 : 0 # whole quarter hours
[ local.to_date, offset ]
end
+4 -4
View File
@@ -16,10 +16,10 @@ class EntrySigner
end
def sign!
raise Error, "Your account is disabled" if @user.disabled?
raise Error, "That certificate isn't yours" unless @certificate && @certificate.user_id == @user.id
raise Error, I18n.t("services.entry_signer.your_account_is_disabled") if @user.disabled?
raise Error, I18n.t("services.entry_signer.that_certificate_isn_t_yours") unless @certificate && @certificate.user_id == @user.id
problems = @entry.signing_problems(@certificate)
raise Error, "This entry can't be signed: #{problems.to_sentence}" if problems.any?
raise Error, I18n.t("services.entry_signer.this_entry_can_t_be", to_sentence: problems.to_sentence) if problems.any?
LogbookEntry.transaction do
@entry.update!(signoff_person: @user.display_name, signoff_certificate_type: @certificate.kind,
@@ -34,7 +34,7 @@ class EntrySigner
)
@entry.supersedes&.update_column(:superseded_at, signature.signed_at)
@entry.aircraft.log_event!("logbook", "Logbook entry signed electronically (#{@entry.date})",
notes: "#{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}", user: @user)
notes: I18n.t("services.entry_signer.text", signer_name: signature.signer_name, certificate_label: signature.certificate_label, certificate_number: signature.certificate_number), user: @user)
signature
end
end
+20 -20
View File
@@ -63,7 +63,7 @@ class FlightImport
# Creates flight logs + oil/fuel records. Returns the number of flights imported.
def import!(user:, update_aircraft_hours: false)
flights = importable
raise Error, "Nothing to import." if flights.empty?
raise Error, I18n.t("services.flight_import.nothing_to_import") if flights.empty?
Aircraft.transaction do
flights.each do |r|
@@ -71,17 +71,17 @@ class FlightImport
user: user, date: r.date, departure_location: r.from, destination_location: r.to,
tach_out: r.tach_out, tach_in: r.tach_in, tach_time: r.tach_time,
hobbs_out: r.hobbs_out, hobbs_in: r.hobbs_in, hobbs_time: r.hobbs_time,
oil_added: r.oil, fuel_added: r.fuel, notes: "Imported from #{@filename}"
oil_added: r.oil, fuel_added: r.fuel, notes: I18n.t("services.flight_import.imported_from", filename: @filename)
)
{ "oil" => r.oil, "fuel" => r.fuel }.each do |type, qty|
next unless qty
@aircraft.consumable_records.create!(record_type: type, flight_log: log, date: r.date,
quantity_added: qty, flight_hours: r.tach_in,
notes: "Imported from #{@filename}")
notes: I18n.t("services.flight_import.imported_from", filename: @filename))
end
end
@aircraft.log_event!("flight", "Imported #{flights.size} flights from spreadsheet", user: user,
notes: "#{@filename}: #{flights.first.date} – #{flights.last.date}, #{total_tach_hours} tach hrs")
notes: I18n.t("services.flight_import.tach_hrs", filename: @filename, from: flights.first.date, to: flights.last.date, total_tach_hours: total_tach_hours))
end
advance_aircraft_hours!(user) if update_aircraft_hours
@@ -116,33 +116,33 @@ class FlightImport
row.to = code(cell(raw, :to))
row.tach_in = decimal(cell(raw, :tach), 1)
row.hobbs_in = decimal(cell(raw, :hobbs), 1)
row.oil = quantity(row, cell(raw, :oil), "Oil")
row.fuel = quantity(row, cell(raw, :fuel), "Fuel")
row.oil = quantity(row, cell(raw, :oil), ConsumableRecord::TYPES["oil"])
row.fuel = quantity(row, cell(raw, :fuel), ConsumableRecord::TYPES["fuel"])
flight_time = decimal(cell(raw, :flight_time), 1)
row.error("Date missing or not recognized (#{cell(raw, :date).inspect})") unless row.date
row.error("Tach reading missing") unless row.tach_in
row.error(I18n.t("services.flight_import.date_missing_or_not_recognized", date: (cell(raw, :date).inspect))) unless row.date
row.error(I18n.t("services.flight_import.tach_reading_missing")) unless row.tach_in
if row.tach_in
if prev_tach.nil?
if flight_time&.positive?
row.tach_time = flight_time
row.tach_out = row.tach_in - flight_time
row.warn("First row: duration taken from Flight Time column (enter the starting tach to be exact)")
row.warn(I18n.t("services.flight_import.first_row_duration_taken_from"))
else
row.error("Starting reading only: no previous tach to measure from. Enter the tach before the first flight to import this row")
row.error(I18n.t("services.flight_import.starting_reading_only_no_previous"))
row.baseline = true
end
elsif row.tach_in < prev_tach
row.error("Tach went backwards (#{prev_tach} → #{row.tach_in}). Likely a typo")
row.error(I18n.t("services.flight_import.tach_went_backwards_likely_a", prev_tach: prev_tach, tach_in: row.tach_in))
elsif row.tach_in == prev_tach
row.tach_out = prev_tach
row.tach_time = BigDecimal("0")
row.warn("Tach didn't change (#{row.tach_in}). Imported as 0.0 hrs; check for a typo")
row.warn(I18n.t("services.flight_import.tach_didn_t_change_imported", tach_in: row.tach_in))
else
row.tach_out = prev_tach
row.tach_time = row.tach_in - prev_tach
row.warn("Long flight: #{row.tach_time} tach hrs. Missing rows?") if row.tach_time > LONG_FLIGHT_HOURS
row.warn(I18n.t("services.flight_import.long_flight_tach_hrs_missing", tach_time: row.tach_time)) if row.tach_time > LONG_FLIGHT_HOURS
end
end
@@ -153,12 +153,12 @@ class FlightImport
row.hobbs_time = flight_time
end
if row.hobbs_in && prev_hobbs && row.hobbs_in < prev_hobbs
row.warn("Hobbs went backwards (#{prev_hobbs} → #{row.hobbs_in}). Meter replaced?")
row.warn(I18n.t("services.flight_import.hobbs_went_backwards_meter_replaced", prev_hobbs: prev_hobbs, hobbs_in: row.hobbs_in))
end
if row.status != :error && existing.include?([ row.date, row.tach_in ])
row.status = :duplicate
row.messages = [ "Already imported" ]
row.messages = [ I18n.t("services.flight_import.already_imported") ]
end
# Bad rows don't move the baseline, so the next good row absorbs the time.
@@ -185,15 +185,15 @@ class FlightImport
end
end
end
raise Error, "Couldn't find a header row with Date and Tach columns."
raise Error, I18n.t("services.flight_import.couldn_t_find_a_header")
end
def open_spreadsheet
ext = File.extname(@filename).delete(".").downcase
raise Error, "Upload an .xlsx or .csv file." unless ext.in?(EXTENSIONS)
raise Error, I18n.t("flash.uploads.spreadsheet_only") unless ext.in?(EXTENSIONS)
Roo::Spreadsheet.open(@path, extension: ext.to_sym)
rescue Zip::Error, ArgumentError, CSV::MalformedCSVError => e
raise Error, "Couldn't read the file (#{e.message})."
raise Error, I18n.t("services.flight_import.couldn_t_read_the_file", message: e.message)
end
def detect_columns(header_row)
@@ -235,12 +235,12 @@ class FlightImport
def quantity(row, value, label)
return nil if value.nil? || BLANK_VALUES.include?(value.to_s.strip.downcase)
if value.to_s.strip.casecmp?("full")
row.warn("#{label} “Full” has no quantity, so it isn't recorded")
row.warn(I18n.t("services.flight_import.full_has_no_quantity_so", label: label))
return nil
end
qty = decimal(value)
if qty.nil? || qty.negative?
row.warn("#{label} value #{value.inspect} ignored")
row.warn(I18n.t("services.flight_import.value_ignored", label: label, value: value.inspect))
return nil
end
qty
+6 -6
View File
@@ -41,11 +41,11 @@ class FlightStats
def periods
[
period("Past 30 days", today - 29..today),
period("Past 12 months", (today << 12) + 1..today),
period("This year (#{today.year})", Date.new(today.year)..today),
period("Last year (#{today.year - 1})", Date.new(today.year - 1)..Date.new(today.year - 1, 12, 31)),
period("Since purchase", (first_date || today)..today)
period(I18n.t("services.flight_stats.past_30_days"), today - 29..today),
period(I18n.t("services.flight_stats.past_12_months"), (today << 12) + 1..today),
period(I18n.t("services.flight_stats.this_year", year: today.year), Date.new(today.year)..today),
period(I18n.t("services.flight_stats.last_year", year: (today.year - 1)), Date.new(today.year - 1)..Date.new(today.year - 1, 12, 31)),
period(I18n.t("services.flight_stats.since_purchase"), (first_date || today)..today)
]
end
@@ -60,7 +60,7 @@ class FlightStats
.transform_values { |fs| sum(fs) { flight_hours(_1) } }
(0...months).to_h do |i|
month = start >> i
[ month.strftime("%b %Y"), totals.fetch(month, 0.0) ]
[ I18n.l(month, format: :month_year), totals.fetch(month, 0.0) ]
end
end
+10 -10
View File
@@ -23,12 +23,12 @@ class GoogleDriveClient
# The refresh token from the code Google sent back.
def self.exchange_code(client_id:, client_secret:, code:, redirect_uri:)
token = token_request(client_id: client_id, client_secret: client_secret, code: code, redirect_uri: redirect_uri, grant_type: "authorization_code")
token["refresh_token"].presence or raise AuthError, "Google didn't return a refresh token; remove the app's access in your Google account and connect again"
token["refresh_token"].presence or raise AuthError, I18n.t("services.google_drive.google_didn_t_return_a")
end
def self.revoke(token)
res = Net::HTTP.post_form(URI(REVOKE_URL), token: token)
raise Error, "revoke failed (#{res.code})" unless res.is_a?(Net::HTTPSuccess)
raise Error, I18n.t("services.google_drive.revoke_failed", code: res.code) unless res.is_a?(Net::HTTPSuccess)
rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout => e
raise Error, e.message
end
@@ -37,10 +37,10 @@ class GoogleDriveClient
res = Net::HTTP.post_form(URI(TOKEN_URL), form)
body = JSON.parse(res.body) rescue {}
return body if res.is_a?(Net::HTTPSuccess)
raise AuthError, "Google refused the credentials (#{body['error_description'] || body['error'] || res.code})" if res.code.to_i.in?([ 400, 401 ])
raise Error, "Google token request failed (#{res.code})"
raise AuthError, I18n.t("services.google_drive.refused_credentials", reason: body["error_description"] || body["error"] || res.code) if res.code.to_i.in?([ 400, 401 ])
raise Error, I18n.t("services.google_drive.google_token_request_failed", code: res.code)
rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout => e
raise Error, "couldn't reach Google: #{e.message}"
raise Error, I18n.t("services.google_drive.couldn_t_reach_google", message: e.message)
end
def initialize(client_id:, client_secret:, refresh_token:)
@@ -68,7 +68,7 @@ class GoogleDriveClient
session = request(:post, UPLOAD, query: { uploadType: "resumable", fields: "id" },
json: { name: name, parents: [ parent ], appProperties: properties },
headers: { "X-Upload-Content-Type" => content_type, "X-Upload-Content-Length" => size.to_s }, raw: true)
location = session["Location"] or raise Error, "Google didn't start the upload"
location = session["Location"] or raise Error, I18n.t("services.google_drive.google_didn_t_start_the")
put = Net::HTTP::Put.new(URI(location))
put["Content-Length"] = size.to_s
put["Content-Type"] = content_type
@@ -105,7 +105,7 @@ class GoogleDriveClient
to.rewind if to.respond_to?(:rewind)
to
rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout => e
raise Error, "couldn't reach Google Drive: #{e.message}"
raise Error, I18n.t("services.google_drive.couldn_t_reach_google_drive", message: e.message)
end
def delete(id) = request(:delete, "#{API}/files/#{CGI.escape(id)}")
@@ -139,12 +139,12 @@ class GoogleDriveClient
raise_for(res) unless res.is_a?(Net::HTTPSuccess)
res
rescue SocketError, SystemCallError, Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout => e
raise Error, "couldn't reach Google Drive: #{e.message}"
raise Error, I18n.t("services.google_drive.couldn_t_reach_google_drive", message: e.message)
end
def raise_for(res)
message = (JSON.parse(res.body.to_s).dig("error", "message") rescue nil) || res.message
raise AuthError, "Google Drive refused access (#{message}); connect again" if res.code.to_i == 401
raise Error, "Google Drive: #{message} (#{res.code})"
raise AuthError, I18n.t("services.google_drive.google_drive_refused_access_connect", message: message) if res.code.to_i == 401
raise Error, I18n.t("services.google_drive.google_drive", message: message, code: res.code)
end
end
+7 -6
View File
@@ -2,6 +2,7 @@
# the time-in-service delta (tach or Hobbs, per the aircraft's maintenance
# clock) to every IN-USE component.
class HoursService
H = "services.hours_service"
def initialize(aircraft, user: Current.user)
@aircraft = aircraft
@user = user
@@ -30,8 +31,8 @@ class HoursService
@aircraft.save!
cascade_to_components(delta, clamp: true)
@aircraft.log_event!("hours",
"Hours #{tach_delta >= 0 ? 'updated' : 'corrected'} to #{tach}",
user: @user, notes: "Previous: #{old}, delta: #{tach_delta >= 0 ? '+' : ''}#{tach_delta}")
I18n.t(tach_delta >= 0 ? "#{H}.hours_updated" : "#{H}.hours_corrected", tach: tach),
user: @user, notes: I18n.t("#{H}.hours_notes", old: old, delta: "#{'+' if tach_delta >= 0}#{tach_delta}"))
end
tach_delta
end
@@ -55,13 +56,13 @@ class HoursService
@aircraft.consumable_records.create!(
record_type: type, flight_log: flight, date: flight.date, quantity_added: qty,
level_after: level, consumable_type: kind, flight_hours: @aircraft.tach_time,
notes: "Auto-created from flight log")
@aircraft.log_event!(type, "#{type.capitalize} added: #{qty} #{ConsumableRecord::UNITS[type]}",
user: @user, notes: "From flight log")
notes: I18n.t("services.hours_service.auto_created_from_flight_log"))
@aircraft.log_event!(type, I18n.t("#{H}.consumable_added", type: ConsumableRecord::TYPES[type], quantity: qty, unit: ConsumableRecord::UNITS[type]),
user: @user, notes: I18n.t("services.hours_service.from_flight_log"))
end
route = flight.route_summary.presence
@aircraft.log_event!("flight", "Flight logged: #{flight.tach_time} hrs#{" (#{route})" if route}", user: @user)
@aircraft.log_event!("flight", I18n.t(route ? "#{H}.flight_logged_route" : "#{H}.flight_logged", hours: flight.tach_time, route: route), user: @user)
end
flight
end
+31 -47
View File
@@ -15,21 +15,22 @@ Prawn::Fonts::AFM.hide_m17n_warning = true # text is reduced to what the built-i
class LogbookEntryPdf
IN = 72 # points per inch
Layout = Data.define(:key, :label, :page, :cols, :rows, :width, :height, :left, :top, :col_gap, :row_gap, :padding) do
Layout = Data.define(:key, :page, :cols, :rows, :width, :height, :left, :top, :col_gap, :row_gap, :padding) do
def label = I18n.t(key, scope: "services.logbook_entry_pdf.layouts")
def per_page = cols * rows
def labels? = per_page > 1 || page != [ width, height ]
end
LAYOUTS = [
Layout.new(key: "avery_5164", label: "Labels: Avery 5164 / 8164 (3⅓ × 4 in, 6 per sheet)", page: [ 8.5 * IN, 11 * IN ],
Layout.new(key: "avery_5164", page: [ 8.5 * IN, 11 * IN ],
cols: 2, rows: 3, width: 4 * IN, height: 3.333 * IN, left: 0.156 * IN, top: 0.5 * IN,
col_gap: 0.188 * IN, row_gap: 0, padding: 0.15 * IN),
Layout.new(key: "avery_5163", label: "Labels: Avery 5163 / 8163 (2 × 4 in, 10 per sheet)", page: [ 8.5 * IN, 11 * IN ],
Layout.new(key: "avery_5163", page: [ 8.5 * IN, 11 * IN ],
cols: 2, rows: 5, width: 4 * IN, height: 2 * IN, left: 0.156 * IN, top: 0.5 * IN,
col_gap: 0.188 * IN, row_gap: 0, padding: 0.12 * IN),
Layout.new(key: "half_letter", label: "Half-letter pages (5½ × 8½ in)", page: [ 5.5 * IN, 8.5 * IN ],
Layout.new(key: "half_letter", page: [ 5.5 * IN, 8.5 * IN ],
cols: 1, rows: 1, width: 5.5 * IN, height: 8.5 * IN, left: 0, top: 0, col_gap: 0, row_gap: 0, padding: 0.4 * IN),
Layout.new(key: "letter", label: "Letter pages (8½ × 11 in, also full-sheet labels)", page: [ 8.5 * IN, 11 * IN ],
Layout.new(key: "letter", page: [ 8.5 * IN, 11 * IN ],
cols: 1, rows: 1, width: 8.5 * IN, height: 11 * IN, left: 0, top: 0, col_gap: 0, row_gap: 0, padding: 0.6 * IN)
].freeze
@@ -50,15 +51,17 @@ class LogbookEntryPdf
def filename = "#{@aircraft.tail_number.downcase}-logbook-entries.pdf"
def t(key, **opts) = I18n.t(key, scope: "services.logbook_entry_pdf", **opts)
def render
info = { Title: "#{@aircraft.tail_number} logbook entries", Creator: "Simple Aircraft Manager" }
info = { Title: t(:title, tail_number: @aircraft.tail_number), Creator: "Simple Aircraft Manager" }
if @layout.labels?
@pdf = Prawn::Document.new(page_size: @layout.page, margin: 0, info: info)
@entries.each { place_on_labels(_1) }
else
@pdf = Prawn::Document.new(page_size: @layout.page, margin: @layout.padding, info: info)
@entries.each { place_on_pages(_1) }
@pdf.number_pages clean("#{@aircraft.tail_number} · page <page> of <total>"), at: [ 0, -@layout.padding / 2 ],
@pdf.number_pages clean(t(:page_number, tail_number: @aircraft.tail_number)), at: [ 0, -@layout.padding / 2 ],
width: @pdf.bounds.width, align: :right, size: 7, color: "777777"
end
@pdf.render
@@ -132,7 +135,7 @@ class LogbookEntryPdf
leftover = nil
@pdf.bounding_box([ x, y ], width: w, height: h) do
@pdf.text_box clean(header_line), at: [ 0, h ], width: w * 0.68, height: small + 2, size: small, style: :bold, overflow: :truncate
@pdf.text_box clean("#{LogbookEntry::LOG_TYPES[entry.log_type]} log#{' (continued)' if continued}"),
@pdf.text_box clean(t(continued ? :log_continued : :log, log: LogbookEntry::LOG_TYPES[entry.log_type])),
at: [ w * 0.68, h ], width: w * 0.32, height: small + 2, size: small, align: :right, overflow: :truncate
line_y = h - small - 3
detail_lines(entry).each do |line|
@@ -153,39 +156,39 @@ class LogbookEntryPdf
def header_line
[ @aircraft.tail_number, [ @aircraft.make, @aircraft.model ].compact_blank.join(" ").presence,
(@aircraft.serial_number.present? ? "S/N #{@aircraft.serial_number}" : nil) ].compact.join(" · ")
(@aircraft.serial_number.present? ? t(:serial, serial: @aircraft.serial_number) : nil) ].compact.join(" · ")
end
# Date and airframe total time; for engine / propeller entries (or any with
# a component) the component's serial number, total time and since overhaul.
def detail_lines(entry)
airframe = entry.aircraft_hours_at_entry ? "#{hrs(entry.aircraft_hours_at_entry)} (#{@aircraft.time_basis})" : "________"
lines = [ "Date: #{entry.date&.strftime('%b %-d, %Y')} Airframe total time: #{airframe}" ]
lines = [ t(:date_line, date: entry.date && I18n.l(entry.date, format: :app), airframe: airframe) ]
component = entry.component
noun = component_noun(entry, component)
if component
model = [ component.manufacturer, component.model ].compact_blank.join(" ")
serial = component.serial_number.present? ? " S/N #{component.serial_number}" : " S/N __________"
serial = " #{t(:serial, serial: component.serial_number.presence || '__________')}"
lines << [ "#{noun}: #{model}#{serial}",
"#{noun} total time: #{blank_or_hours(entry.component_hours_at_entry)}",
t(:component_total_time, noun: noun, hours: blank_or_hours(entry.component_hours_at_entry)),
"#{component.since_overhaul_abbreviation}: #{blank_or_hours(entry.component_since_overhaul_at_entry)}" ].join(" ")
elsif noun
lines << "#{noun}: ______________ S/N __________ #{noun} total time: ________ SMOH / SFOH: ________"
lines << t(:component_blank, noun: noun)
end
entry.parts.each do |part|
c = part.component
name = c.component_type&.name || "Part"
name = c.component_type&.name || t(:part)
model = [ c.manufacturer, c.model ].compact_blank.join(" ")
lines << [ "#{name}: #{model}#{" S/N #{c.serial_number}" if c.serial_number.present?}",
"Total time: #{blank_or_hours(part.hours_at_entry)}",
lines << [ "#{name}: #{model}#{" #{t(:serial, serial: c.serial_number)}" if c.serial_number.present?}",
t(:total_time, hours: blank_or_hours(part.hours_at_entry)),
"#{c.since_overhaul_abbreviation}: #{blank_or_hours(part.since_overhaul_at_entry)}" ].join(" ")
end
lines
end
def component_noun(entry, component)
return "Engine" if component&.engine? || (component.nil? && entry.log_type == "ENG")
return "Propeller" if component&.propeller? || (component.nil? && entry.log_type == "PROP")
return t(:engine) if component&.engine? || (component.nil? && entry.log_type == "ENG")
return t(:propeller) if component&.propeller? || (component.nil? && entry.log_type == "PROP")
component&.component_type&.name
end
@@ -198,17 +201,17 @@ class LogbookEntryPdf
return electronic_signature_block(entry, w, height, small, more: more) if entry.signature
@pdf.bounding_box([ 0, height ], width: w, height: height) do
if more
@pdf.text_box "Continued on the next #{more}.", at: [ 0, height ], width: w, height: small + 2, size: small,
@pdf.text_box clean(t(:"continued_#{more}")), at: [ 0, height ], width: w, height: small + 2, size: small,
style: :italic, overflow: :truncate
end
line_y = height - (small + 3) * 1.6
@pdf.stroke_color "555555"
@pdf.line_width 0.5
@pdf.stroke_horizontal_line 0, w * 0.62, at: line_y
@pdf.text_box "Signature", at: [ 0, line_y - 1 ], width: w * 0.6, height: small, size: small - 1, overflow: :truncate
@pdf.text_box clean(t(:signature)), at: [ 0, line_y - 1 ], width: w * 0.6, height: small, size: small - 1, overflow: :truncate
@pdf.text_box clean(certificate(entry)), at: [ w * 0.64, line_y + small + 1 ], width: w * 0.36, height: small * 2 + 4,
size: small, overflow: :shrink_to_fit, min_font_size: 5
who = [ entry.signoff_person.presence || "Name: ____________________", entry.signoff_location.presence ].compact.join(" · ")
who = [ entry.signoff_person.presence || t(:name_blank), entry.signoff_location.presence ].compact.join(" · ")
@pdf.text_box clean(who), at: [ 0, line_y - small - 1 ], width: w, height: small + 2, size: small, overflow: :truncate
end
end
@@ -219,23 +222,21 @@ class LogbookEntryPdf
@pdf.bounding_box([ 0, height ], width: w, height: height) do
top = height
if more
@pdf.text_box "Continued on the next #{more}.", at: [ 0, top ], width: w, height: small + 2, size: small, style: :italic, overflow: :truncate
@pdf.text_box clean(t(:"continued_#{more}")), at: [ 0, top ], width: w, height: small + 2, size: small, style: :italic, overflow: :truncate
end
top -= small + 3
@pdf.text_box clean("#{EntrySignature::LABEL} #{sig.signer_name}, #{sig.certificate_label} #{sig.certificate_number}" \
"#{' (SUPERSEDED BY A CORRECTION)' if entry.superseded?}"),
@pdf.text_box clean("#{EntrySignature.label} #{sig.signer_name}, #{sig.certificate_label} #{sig.certificate_number}" \
"#{" #{t(:superseded)}" if entry.superseded?}"),
at: [ 0, top ], width: w, height: small + 2, size: small, style: :bold, overflow: :shrink_to_fit, min_font_size: 5
top -= small + 3
@pdf.text_box clean("Signed electronically #{sig.signed_at.utc.strftime('%Y-%m-%d %H:%M UTC')} · fingerprint #{sig.content_digest.first(16)}"),
@pdf.text_box clean(t(:signed_electronically, time: sig.signed_at.utc.strftime("%Y-%m-%d %H:%M UTC"), fingerprint: sig.content_digest.first(16))),
at: [ 0, top ], width: w, height: small + 2, size: small - 1, overflow: :shrink_to_fit, min_font_size: 5
end
end
def certificate(entry)
kind = { "AP" => "A&P", "IA" => "A&P/IA", "A" => "A", "P" => "P", "REPAIR_STATION" => "Repair station", "REPAIRMAN" => "Repairman",
"PILOT" => "Pilot", "OTHER" => "" }[entry.signoff_certificate_type].to_s
number = entry.signoff_certificate_number.presence || "__________"
"#{kind.presence || 'Cert.'} No. #{number}"
kind = (t(entry.signoff_certificate_type, scope: "services.logbook_entry_pdf.certificate_kinds", default: "") if entry.signoff_certificate_type.present?)
t(:certificate_number, kind: kind.presence || t(:certificate), number: entry.signoff_certificate_number.presence || "__________")
end
# The entry text, plus the 43.11(a)(5) statement for an inspection whose
@@ -244,24 +245,7 @@ class LogbookEntryPdf
text = entry.text.to_s.strip
return "#{text}\n\n#{entry.signature.statement}" if entry.signature
return text unless entry.entry_type == "INSPECTION" && entry.inspection_result.present? && !text.match?(/I certify/i)
type = inspection_kind(entry, text)
statement =
if entry.inspection_result == "approved"
"I certify that this aircraft has been inspected in accordance with #{type} inspection and was determined to be in airworthy condition."
else
"I certify that this aircraft has been inspected in accordance with #{type} inspection and a list of discrepancies and unairworthy items " \
"dated #{entry.date&.strftime('%b %-d, %Y')} has been provided for the aircraft owner or operator."
end
"#{text}\n\n#{statement}"
end
# "an annual" / "a 100-hour": from a linked inspection record, else the text.
def inspection_kind(entry, text)
name = entry.inspection_records.first&.inspection_type&.name.to_s.sub(/\s*\(.*\)\z/, "").sub(/\s*inspection\z/i, "").strip.downcase
name = "annual" if name.empty? && text.match?(/annual/i)
name = "100-hour" if name.empty? && text.match?(/100[- ]?h(ou)?r/i)
return "a ______________" if name.empty?
"#{name.match?(/\A[aeiou]/) ? 'an' : 'a'} #{name}"
"#{text}\n\n#{entry.certification_statement(entry.signoff_certificate_type)}"
end
# The built-in PDF fonts cover Windows-1252; anything else becomes "?".
+7 -7
View File
@@ -48,8 +48,8 @@ class LogbookTranscriber
)
message = stream.accumulated_message
case message.stop_reason
when :refusal then raise Error, "Claude declined to read these pages"
when :max_tokens then raise Error, "the transcription was too long to finish; try fewer pages per file"
when :refusal then raise Error, I18n.t("services.logbook_transcriber.claude_declined_to_read_these")
when :max_tokens then raise Error, I18n.t("services.logbook_transcriber.the_transcription_was_too_long")
end
text = message.content.select { _1.type == :text }.map(&:text).join
@@ -57,15 +57,15 @@ class LogbookTranscriber
Result.new(entries: Array(data["entries"]), non_logbook_pages: Array(data["non_logbook_pages"]),
unparseable_pages: Array(data["unparseable_pages"]), model: message.model.to_s)
rescue JSON::ParserError
raise Error, "Claude's answer wasn't valid JSON"
raise Error, I18n.t("services.logbook_transcriber.claude_s_answer_wasn_t")
rescue Anthropic::Errors::RateLimitError
raise Error, "the Anthropic API is rate limiting requests; try again in a few minutes"
raise Error, I18n.t("services.logbook_transcriber.the_anthropic_api_is_rate")
rescue Anthropic::Errors::AuthenticationError, Anthropic::Errors::PermissionDeniedError
raise Error, "the Anthropic API key was rejected"
raise Error, I18n.t("services.logbook_transcriber.the_anthropic_api_key_was")
rescue Anthropic::Errors::APIStatusError => e
raise Error, "the Anthropic API returned an error (#{e.status})"
raise Error, I18n.t("services.logbook_transcriber.the_anthropic_api_returned_an", status: e.status)
rescue Anthropic::Errors::APIConnectionError
raise Error, "couldn't reach the Anthropic API"
raise Error, I18n.t("services.logbook_transcriber.couldn_t_reach_the_anthropic")
end
private
+6 -6
View File
@@ -18,14 +18,14 @@ class OffsiteBackup
end
def run!(database_path)
raise "Google Drive isn't connected" unless @connection.connected?
raise I18n.t("services.offsite_backup.not_connected") unless @connection.connected?
drive = @connection.client
@connection.ensure_folders!(drive)
bytes = upload_database(drive, database_path)
pruned = prune(drive)
uploaded, failed = upload_files(drive)
message = "Database copy uploaded (#{ActiveSupport::NumberHelper.number_to_human_size(bytes)}); #{uploaded.size} new #{'file'.pluralize(uploaded.size)} copied"
message += "; #{failed.size} couldn't be copied: #{failed.first(3).join('; ')}" if failed.any?
message = I18n.t("services.offsite_backup.uploaded", size: ActiveSupport::NumberHelper.number_to_human_size(bytes), count: uploaded.size)
message += I18n.t("services.offsite_backup.failed", count: failed.size, files: failed.first(3).join("; ")) if failed.any?
OffsiteRun.create!(kind: "backup", ok: failed.empty?, bytes: bytes + uploaded.sum, files_uploaded: uploaded.size, message: message,
details: { "account" => @connection.account_email, "pruned" => pruned, "failed" => failed.first(20) })
rescue StandardError => e
@@ -36,13 +36,13 @@ class OffsiteBackup
# Downloads the newest database copy from Drive, opens it and checks it,
# and downloads a few random files and checks them against their checksums.
def restore_test!
raise "Google Drive isn't connected" unless @connection.connected?
raise I18n.t("services.offsite_backup.not_connected") unless @connection.connected?
drive = @connection.client
latest = drive.list(@connection.database_folder_id).select { _1["name"].end_with?(".sqlite3.gz") }.max_by { _1["name"] } or raise "no database copy in Google Drive yet"
db_result = Dir.mktmpdir("sam-restore") { |dir| check_database(drive, latest, dir) }
samples = OffsiteFile.includes(:blob).order(Arel.sql("RANDOM()")).limit(SAMPLE_FILES).to_a
bad = samples.reject { check_file(drive, _1) }
message = "#{latest['name']}: #{db_result}. #{samples.size - bad.size} of #{samples.size} sampled files match their checksums"
message = I18n.t("services.offsite_backup.restore_result", name: latest["name"], result: db_result, good: samples.size - bad.size, total: samples.size)
OffsiteRun.create!(kind: "restore_test", ok: bad.empty?, message: message,
details: { "database" => latest["name"], "files_checked" => samples.map { _1.blob.filename.to_s }, "mismatched" => bad.map { _1.blob.filename.to_s } })
rescue StandardError => e
@@ -98,7 +98,7 @@ class OffsiteBackup
result = db.get_first_value("PRAGMA integrity_check")
raise "integrity check of the downloaded copy failed: #{result}" unless result == "ok"
entries, signatures = %w[logbook_entries entry_signatures].map { db.get_first_value("SELECT COUNT(*) FROM #{_1}") }
"opened, SQLite integrity check ok, #{entries} logbook entries and #{signatures} signatures (#{LogbookEntry.count} and #{EntrySignature.count} now)"
I18n.t("services.offsite_backup.restore_db", entries: entries, signatures: signatures, entries_now: LogbookEntry.count, signatures_now: EntrySignature.count)
ensure
db&.close
end
+2 -2
View File
@@ -22,10 +22,10 @@ class OilReportParser
elsif text.match?(/OIL ANALYSIS RESULTS IN PARTS PER MILLION|AVIATION LABORATORIES|avlab\.com/i)
Avlab.from_receivers(receivers)
else
raise Error, "Not a recognized lab report (AvLab and Blackstone PDFs are supported)"
raise Error, I18n.t("services.oil_report.not_a_recognized_lab_report")
end
rescue PDF::Reader::MalformedPDFError, PDF::Reader::UnsupportedFeatureError => e
raise Error, "Couldn't read the PDF (#{e.message})"
raise Error, I18n.t("services.oil_report.couldn_t_read_the_pdf", message: e.message)
end
# "1,903" → 1903, "<0.5" → 0.5, "5 qts" → 5, ".3" → 0.3; nil for "-", "N/A"…
+2 -2
View File
@@ -48,10 +48,10 @@ class OilReportParser
def parse
unless @lines.any? { _1.text.include?("OIL ANALYSIS RESULTS IN PARTS PER MILLION") }
raise Error, "Not an AvLab oil analysis report"
raise Error, I18n.t("services.oil_report.not_an_avlab_oil_analysis")
end
samples = sample_blocks.map { parse_sample(_1) }.select { _1[:sample_date] }
raise Error, "No samples found in the report" if samples.empty?
raise Error, I18n.t("services.oil_report.no_samples_found_in_the") if samples.empty?
Report.new(lab: LAB, tail_number: after("Tail No.:"), engine_serial: after("Engine S/N:"),
engine_model: after("Engine Model:", words: 3), samples: samples)
+2 -2
View File
@@ -33,9 +33,9 @@ class OilReportParser
end
def parse
date_label = label("Sample Date") or raise Error, "No sample dates found in the Blackstone report"
date_label = label("Sample Date") or raise Error, I18n.t("services.oil_report.no_sample_dates_found_in")
dates = row(date_label).select { DATE.match?(_1.text) }.sort_by(&:x)
raise Error, "No sample dates found in the Blackstone report" if dates.empty?
raise Error, I18n.t("services.oil_report.no_sample_dates_found_in") if dates.empty?
@columns = dates.map(&:endx)
@universal_x = (@runs.find { _1.text == "UNIVERSAL" }&.x || 530) - 10
+16 -42
View File
@@ -7,63 +7,37 @@ module ProceduresTemplates
def hosting
[
"**Server.** The system runs #{docker? ? 'as a Docker container on a server' : 'on a server'} at [location, e.g. the owner's home or a hosting provider]. " \
"Its data (the database, the uploaded files and the nightly verified database copies) is on that server's storage volume. " \
"Only [the owner] has administrative access to the server.",
"**Network access.** [How the system is reached: e.g. directly from the internet at its own address, only on the home network, or over a VPN.] #{https_sentence}",
"**Sign-in.** #{sign_in_sentence} Password accounts require at least #{User::PASSWORD_MIN} characters, reject passwords found in known data breaches, " \
"lock for #{User::LOCK_FOR.inspect} after #{User::LOCK_AFTER} failed attempts in a row, and can add an authenticator app. " \
"Sessions end after #{Authentication::SESSION_IDLE_TIMEOUT.inspect} unused.",
"**Signing.** Signing an entry always requires the signer to re-enter their password (and authenticator code if enabled)#{' or to sign in again with single sign-on' if Sso.enabled?}.",
"**Updates.** Software updates are installed by [the owner] from [the project's published container images]. Each version is recorded by the system under Software versions.",
"**Secret key.** The application secret key (SECRET_KEY_BASE), needed to verify electronic signatures and to restore from backup, is kept by the owner off the server in [a password manager]."
t(:server, location: t(docker? ? :server_docker : :server_plain)),
t(:network, https: https_sentence),
t(:sign_in, sentence: sign_in_sentence, min: User::PASSWORD_MIN, minutes: User::LOCK_FOR.in_minutes.to_i,
tries: User::LOCK_AFTER, days: Authentication::SESSION_IDLE_TIMEOUT.in_days.to_i),
t(Sso.enabled? ? :signing_sso : :signing),
t(:updates),
t(:secret_key)
].join("\n\n")
end
def additional
since = Aircraft.where.not(electronic_records_since: nil).minimum(:electronic_records_since)
[
"**Who makes entries.** The owner enters maintenance records. A mechanic who performs work signs their own entry: through a signing invitation, with their own account in the system, " \
"or by signing a printed entry in ink. The owner signs only preventive maintenance they performed under 14 CFR 43.3(g), with their pilot certificate.",
"**Outside signers.** Signing invitations are sent only to the mechanic's own email address, for the specific entry they performed. Each invitation can be used once and expires after 14 days. " \
"If a mechanic forgets their password, the owner resets it or sends a new invitation; passwords are never shared or set on a mechanic's behalf. " \
"Mechanics are encouraged to add an authenticator app. Accounts of mechanics no longer working on the aircraft are disabled at the next audit; their past signatures remain valid.",
"**Account problems.** If someone may have used another person's password, or an account is locked without explanation, the owner disables or unlocks it as appropriate, " \
"has the user change their password, and reviews the record history for changes made by that account. " \
"An authenticator app is reset only after confirming the person's identity by phone or in person.",
"**Share links.** Read-only share links are created only for a specific purpose (a mechanic, buyer, insurer or the FAA), with an expiry date where practical. " \
"They are revoked when no longer needed and reviewed at each audit.",
"**Retention (14 CFR 91.417(b)).** Records of maintenance, preventive maintenance and alterations, and of 100-hour, annual and progressive inspections, are kept until the work is " \
"repeated or superseded, or for one year after it was performed. Total time in service, current status of life-limited parts, time since last overhaul, current inspection status " \
"and AD status are kept permanently and transferred with the aircraft. In practice nothing is deleted: signed entries cannot be deleted, and the record history and off-site copies are kept.",
"**Paper records.** The paper logbooks covering the period before #{since ? since.strftime('%B %-d, %Y') : '[the date electronic records began]'} are kept by the owner at [location] " \
"and transferred with the aircraft. Their scans are marked as legacy records. Entries signed in ink after that date are scanned into Documents, and the paper is kept with the logbooks.",
"**Shop visits.** When a shop prefers paper, entries are printed from the system for signature and the signed copy is scanned in. " \
"A shop or the FAA may be given a time-limited Maintenance Detail share link for read-only access.",
"**Sale of the aircraft.** The owner gives the buyer the paper logbooks and a records package from the system (the entries with their signatures, the record history, " \
"the procedures and the data archive)."
t(:who_makes_entries), t(:outside_signers), t(:account_problems), t(:share_links), t(:retention),
t(:paper_records, since: since ? I18n.l(since, format: :long) : t(:since_blank)),
t(:shop_visits), t(:sale)
].join("\n\n")
end
def https? = Rails.application.config.force_ssl
def https_sentence
if https?
"Connections use HTTPS only: the system redirects plain HTTP and marks its cookies secure."
else
"The system is set not to enforce HTTPS itself (FORCE_SSL=false): [say how connections are protected, e.g. a TLS proxy in front, or the home network only]."
end
end
def https_sentence = t(https? ? :https_on : :https_off)
def sign_in_sentence
if Sso.enabled? && !Sso.password_login?
"People sign in only with single sign-on (#{Sso.label}); password sign-in is turned off."
elsif Sso.enabled?
"People sign in with single sign-on (#{Sso.label}) or with their own email and password; there are no shared accounts."
else
"People sign in with their own email and password; there are no shared accounts."
if Sso.enabled? && !Sso.password_login? then t(:sign_in_sso_only, provider: Sso.label)
elsif Sso.enabled? then t(:sign_in_sso, provider: Sso.label)
else t(:sign_in_password)
end
end
def docker? = File.exist?("/.dockerenv")
def t(key, **opts) = I18n.t(key, scope: "services.procedures_templates", **opts)
end
+20 -24
View File
@@ -4,12 +4,7 @@
class RecordsAudit
Item = Data.define(:key, :title, :auto, :passed, :detail)
MANUAL = {
"restore_test" => "Restored the latest off-site backup somewhere separate and opened it (records readable, counts plausible)",
"sample" => "Compared the sampled entries below with their work orders, receipts or other source documents; they match",
"users" => "Reviewed the users and roles below; accounts of people who no longer need access are disabled",
"legacy" => "The paper (legacy) logbooks are kept, complete and accounted for"
}.freeze
MANUAL = LabelSet.new("records_audit.manual", %w[restore_test sample users legacy])
def initialize(since: AuditRun.latest&.performed_at)
@since = since
@@ -22,23 +17,23 @@ class RecordsAudit
revision = ProceduresRevision.current
expired = UserCertificate.joins(:user).merge(User.active).where(expires_on: ...Date.current)
[
Item.new("integrity", "Records integrity check passed in the last 2 days", true,
Item.new("integrity", t(:integrity), true,
check.present? && check.ok && check.created_at > 2.days.ago,
check ? "#{check.created_at.to_date}: #{check.ok ? 'no problems' : check.problems.first(3).join('; ')}" : "Never run"),
Item.new("backup", "A verified database backup was made in the last 2 days", true,
check ? "#{check.created_at.to_date}: #{check.ok ? t(:no_problems) : check.problems.first(3).join('; ')}" : t(:never_run)),
Item.new("backup", t(:backup), true,
backup.present? && backup.ok && backup.created_at > 2.days.ago,
backup ? "#{backup.created_at.to_date}: #{backup.message}" : "Never run"),
backup ? "#{backup.created_at.to_date}: #{backup.message}" : t(:never_run)),
*offsite_items,
drs_item,
Item.new("procedures", "The procedures document is adopted and its details filled in", true,
Item.new("procedures", t(:procedures), true,
revision.present? && @policy.complete?,
revision ? "Revision #{revision.number}, adopted #{revision.adopted_at.to_date}" : "Not adopted yet"),
Item.new("signatures", "Electronic signatures since the last audit are intact", true,
check.present? && check.ok, "#{signatures_since.count} signed since #{since_label}"),
Item.new("certificates", "No active user is relying on an expired certificate", true, true,
expired.any? ? "Expired (can't sign until renewed): #{expired.map { "#{_1.user.display_name} #{_1.short_label}" }.join(', ')}" : "None expired"),
Item.new("versions", "Software versions since the last audit", true, true,
versions_since.map { [ _1.version, "build #{_1.revision}" ].compact.join(" ") }.join(", ").presence || "No changes")
revision ? t(:revision, number: revision.number, date: revision.adopted_at.to_date) : t(:not_adopted)),
Item.new("signatures", t(:signatures), true,
check.present? && check.ok, t(:signed_since, count: signatures_since.count, since: since_label)),
Item.new("certificates", t(:certificates), true, true,
expired.any? ? t(:expired_certificates, names: expired.map { "#{_1.user.display_name} #{_1.short_label}" }.join(", ")) : t(:none_expired)),
Item.new("versions", t(:versions), true, true,
versions_since.map { [ _1.version, t(:build, revision: _1.revision) ].compact.join(" ") }.join(", ").presence || t(:no_changes))
]
end
@@ -59,7 +54,7 @@ class RecordsAudit
{ "key" => key, "title" => title, "auto" => false, "passed" => a["passed"] == "1", "detail" => a["note"].to_s.strip.first(1000) }
end
results = autos.map { { "key" => _1.key, "title" => _1.title, "auto" => true, "passed" => _1.passed, "detail" => _1.detail } } + manual
results << { "key" => "sample_entries", "title" => "Entries sampled", "auto" => true, "passed" => true,
results << { "key" => "sample_entries", "title" => t(:entries_sampled), "auto" => true, "passed" => true,
"detail" => LogbookEntry.where(id: sample_ids).includes(:aircraft).map { "#{_1.aircraft.tail_number} #{_1.date}" }.join(", ") }
AuditRun.create!(performed_by: user, performed_at: Time.current, passed: results.all? { _1["passed"] }, results: results, notes: notes.to_s.strip.first(5000))
end
@@ -71,18 +66,19 @@ class RecordsAudit
def drs_item
due = Aircraft.ordered.select { DrsImport.renewal_due?(_1) || DrsImport.missing_models(_1).any? }
Item.new("drs", "Each aircraft's AD list was refreshed from FAA DRS in the last 12 months, for all its models", true, due.empty?,
due.any? ? "Needs a DRS import: #{due.map(&:tail_number).join(', ')}" : "Up to date")
Item.new("drs", t(:drs), true, due.empty?,
due.any? ? t(:needs_drs, aircraft: due.map(&:tail_number).join(", ")) : t(:up_to_date))
end
def offsite_items
return [] unless OffsiteConnection.connected?
run = OffsiteRun.latest_backup
[ Item.new("offsite", "The backup was copied off-site (Google Drive) in the last 2 days", true, run.present? && run.ok && run.recent?,
run ? "#{run.created_at.to_date}: #{run.message}" : "Never run") ]
[ Item.new("offsite", t(:offsite), true, run.present? && run.ok && run.recent?,
run ? "#{run.created_at.to_date}: #{run.message}" : t(:never_run)) ]
end
def since_label = @since ? @since.to_date.to_s : "the start"
def since_label = @since ? @since.to_date.to_s : t(:the_start)
def t(key, **opts) = I18n.t(key, scope: "services.records_audit", **opts)
def signatures_since = EntrySignature.where(signed_at: (@since || Time.at(0))..)
def versions_since = AppRevision.where(first_seen_at: (@since || Time.at(0))..).order(:first_seen_at)
end
+5 -5
View File
@@ -11,9 +11,9 @@ class RecordsIntegrity
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)
tail = Aircraft.find_by(id: aircraft_id)&.tail_number || I18n.t("services.records_integrity.aircraft", aircraft_id: aircraft_id.inspect)
problems << I18n.t("services.records_integrity.history_entry_doesn_t_follow", tail: tail, id: v.id) if v.prev_hash != prev
problems << I18n.t("services.records_integrity.history_entry_was_altered", tail: tail, id: v.id) if v.chain_hash != RecordVersion.digest(v.prev_hash, v.payload)
prev = v.chain_hash
end
end
@@ -22,8 +22,8 @@ class RecordsIntegrity
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'}"
problems << I18n.t(sig.seal_valid? ? "services.records_integrity.entry_changed" : "services.records_integrity.signature_altered",
tail_number: entry.aircraft.tail_number, date: entry.date, signer: sig.signer_name)
end
AppRevision.touch_current!
IntegrityCheck.create!(ok: problems.empty?, versions_checked: versions, signatures_checked: signatures, problems: problems.first(200))
+12 -39
View File
@@ -49,44 +49,17 @@ class RecordsPackage
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.version_label}.
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.
- recordkeeping-procedures.html How these electronic records and signatures are kept (AC 120-78B), current adopted revision.
- viewer/docker-compose.yml Runs Simple Aircraft Manager on your own computer to browse the archive (below).
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'}.
Viewing the data in Simple Aircraft Manager
The PDF, CSV and HTML files above open on their own. To browse everything (components, logbook, ADs,
inspections, documents, flights, oil and fuel) the way the owner sees it, run the app on your own computer:
1. Install Docker Desktop (https://www.docker.com/products/docker-desktop/).
2. In a terminal, go to the "viewer" folder of this package and run: docker compose up -d
3. Open http://localhost:3000 and create the first (admin) account.
4. Choose Fleet -> Import and select #{@aircraft.tail_number.downcase}.sam.zip from this package (or this whole zip file).
The copy runs only on your computer and stays separate from the owner's system. Electronic signatures are
shown as imported: compare their fingerprints with signatures.csv and logbook-entries.pdf. To stop it:
docker compose down (add -v to delete the local copy).
#{"\nSimple Aircraft Manager is open source: #{repository}" if repository}
TXT
t = ->(key, **opts) { I18n.t(key, scope: "services.records_package", **opts) }
check_text =
if check.nil? then t.(:check_none)
else t.(check.ok ? :check_ok : :check_problems, time: check.created_at.utc.strftime("%Y-%m-%d %H:%M UTC"), count: check.problems.size)
end
t.(:readme, tail_number: @aircraft.tail_number, aircraft: [ @aircraft.make, @aircraft.model ].compact_blank.join(" "),
serial: @aircraft.serial_number.presence || t.(:not_recorded), prepared: @generated_at.utc.strftime("%Y-%m-%d %H:%M UTC"),
source: @source, version: SystemInfo.new.version_label, since: @aircraft.electronic_records_since&.iso8601 || t.(:not_stated),
legacy: (@aircraft.documents.where(legacy_record: true).exists? ? t.(:legacy_note) : ""), count: entries.size, signed: signed,
archive: "#{@aircraft.tail_number.downcase}.sam.zip", check: check_text,
repository: (repository ? "\n#{t.(:repository, url: repository)}" : "")) + "\n"
end
def repository = SystemInfo.new.repository_url
@@ -131,7 +104,7 @@ class RecordsPackage
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.certificate_number, s.signed_at.utc.iso8601, s.imported? ? I18n.t("services.records_package.imported_from", origin: s.origin) : s.status_label,
s.content_digest, s.statement, e.supersedes&.date ]
end
end
+6 -7
View File
@@ -4,8 +4,7 @@
class SiteSearch
Result = Data.define(:kind, :title, :snippet, :aircraft, :path)
LIMIT = 25
KINDS = { "logbook" => "Logbook", "squawk" => "Squawks", "note" => "Notes", "ad" => "ADs", "document" => "Documents",
"component" => "Components", "flight" => "Flights", "major" => "Major repairs & alterations" }.freeze
KINDS = LabelSet.new("site_search.kinds", %w[logbook squawk note ad document component flight major])
attr_reader :query
@@ -24,17 +23,17 @@ class SiteSearch
return {} unless searchable?
@results ||= {
"logbook" => find(LogbookEntry.where(aircraft_id: @ids).order(date: :desc), %w[text signoff_person signoff_location]) { |e, s|
[ "#{e.date} · #{LogbookEntry::LOG_TYPES[e.log_type]} log", s, @urls.aircraft_logbook_entry_path(e.aircraft_id, e) ] },
[ I18n.t("services.site_search.logbook", date: e.date, log: LogbookEntry::LOG_TYPES[e.log_type]), s, @urls.aircraft_logbook_entry_path(e.aircraft_id, e) ] },
"squawk" => find(Squawk.where(aircraft_id: @ids).order(created_at: :desc), %w[issue_reported notes deferral_notes]) { |q, s|
[ "#{q.issue_reported.truncate(80)}#{' (resolved)' if q.resolved?}", s, @urls.aircraft_squawks_path(q.aircraft_id) ] },
[ q.resolved? ? I18n.t("services.site_search.resolved", issue: q.issue_reported.truncate(80)) : q.issue_reported.truncate(80), s, @urls.aircraft_squawks_path(q.aircraft_id) ] },
"note" => find(AircraftNote.where(aircraft_id: @ids).order(created_at: :desc), %w[text]) { |n, s|
[ "Note, #{n.created_at.to_date}", s, @urls.aircraft_notes_path(n.aircraft_id) ] },
[ I18n.t("services.site_search.note", date: n.created_at.to_date), s, @urls.aircraft_notes_path(n.aircraft_id) ] },
"ad" => ads,
"document" => find(Document.where(aircraft_id: @ids).order(:name), %w[name description pages_text]) { |d, s|
[ d.name, s, @urls.aircraft_document_path(d.aircraft_id, d) ] },
"component" => components,
"flight" => find(FlightLog.where(aircraft_id: @ids).order(date: :desc), %w[departure_location destination_location route notes]) { |f, s|
[ "#{f.date} · #{f.route_summary.presence || 'Flight'}", s, @urls.aircraft_flight_log_path(f.aircraft_id, f) ] },
[ "#{f.date} · #{f.route_summary.presence || I18n.t('services.site_search.flight')}", s, @urls.aircraft_flight_log_path(f.aircraft_id, f) ] },
"major" => find(MajorRecord.where(aircraft_id: @ids).order(date_performed: :desc), %w[title description stc_number stc_holder notes]) { |m, s|
[ m.title.to_s, s, @urls.aircraft_major_record_path(m.aircraft_id, m) ] }
}.reject { _2.empty? }
@@ -72,7 +71,7 @@ class SiteSearch
cols = %w[name short_description required_action docket_number]
sql = cols.map { "airworthiness_directives.#{_1} LIKE :t ESCAPE '\\'" }.join(" OR ")
find_scope.where(sql, t: term).limit(LIMIT).map do |ad|
Result.new(kind: nil, title: "AD #{ad.name} · #{ad.short_description.to_s.truncate(70)}", snippet: snippet_for(ad, cols),
Result.new(kind: nil, title: I18n.t("services.site_search.ad", name: ad.name, description: ad.short_description.to_s.truncate(70)), snippet: snippet_for(ad, cols),
aircraft: a, path: @urls.aircraft_airworthiness_directives_path(a))
end
end.first(LIMIT)
+4 -4
View File
@@ -43,9 +43,9 @@ class TrackParser
when "gpx" then parse_gpx
when "kml" then parse_kml
when "csv" then parse_csv
else raise Error, "Unsupported track format"
else raise Error, I18n.t("services.track.unsupported_track_format")
end
raise Error, "Track has fewer than 2 points" if coords.size < 2
raise Error, I18n.t("services.track.track_has_fewer_than_2") if coords.size < 2
times = nil unless times && times.size == coords.size
coords, times = downsample(coords, times)
Track.new(coordinates: coords, times: times, source_format: format, source_name: @filename)
@@ -117,7 +117,7 @@ class TrackParser
headers = rows.headers.compact
find = ->(names) { headers.find { |h| names.include?(h.to_s.strip.downcase.gsub(/[^a-z_]/, "")) } }
lat_h, lon_h, alt_h, time_h = find.(LAT_HEADERS), find.(LON_HEADERS), find.(ALT_HEADERS), find.(TIME_HEADERS)
raise Error, "CSV track needs latitude and longitude columns" unless lat_h && lon_h
raise Error, I18n.t("services.track.csv_track_needs_latitude_and") unless lat_h && lon_h
coords = []
times = []
@@ -131,7 +131,7 @@ class TrackParser
end
[ coords, times.all? ? times : nil ]
rescue CSV::MalformedCSVError => e
raise Error, "Couldn't read CSV track (#{e.message})"
raise Error, I18n.t("services.track.couldn_t_read_csv_track", message: e.message)
end
def coordinate(lon, lat, alt)