Blackstone oil analysis, .sam.zip export/import, AI logbook transcription

- Oil analysis: Blackstone PDF import (20 elements, oil properties, universal
  averages), results stored per element, oil type, "leave out of trends",
  the original app's statuses; AvLab fixes (multi-line comments, unrelated
  labels no longer steal values). Existing records migrate.
- Aircraft archives in the original app's .sam.zip format (schema v2): export
  from Access & Sharing, background import from the Fleet page, rake tasks.
  Archives move both ways between this app and the original.
- Scanned logbook pages (images or PDFs) upload as a document; with
  ANTHROPIC_API_KEY set, Claude transcribes them into logbook entries.
- Fix: deleting a component or aircraft failed when AD compliances or
  inspection records pointed at a component.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-06 21:05:19 -05:00
1 parent 2d068e1a63
commit 1c6c2f88c0
54 files changed
+2794 -286

No files matched your search

Binary file not shown.
Binary file not shown.
@@ -0,0 +1,93 @@
require "test_helper"
class AircraftArchiveFlowTest < ActionDispatch::IntegrationTest
include ActiveJob::TestHelper
setup do
@owner = create_user("owner@example.com")
@pilot = create_user("pilot@example.com")
@a = create_aircraft(owner: @owner, pilot: @pilot, tail_number: "N12345", make: "Cessna")
engine = create_component(@a)
@a.squawks.create!(priority: 1, issue_reported: "Cracked fairing", component: engine,
attachments: [ { io: StringIO.new("see photo"), filename: "notes.txt", content_type: "text/plain" } ])
@a.logbook_entries.create!(date: Date.new(2026, 1, 5), text: "Oil changed")
end
def download_export
get aircraft_export_path(@a)
assert_response :success
assert_equal "application/zip", response.media_type
path = File.join(Dir.mktmpdir, "export.sam.zip")
File.binwrite(path, response.body)
path
end
test "owner downloads an export; pilots and outsiders can't" do
sign_in @pilot
get aircraft_export_path(@a)
assert_redirected_to aircraft_path(@a)
sign_in create_user
get aircraft_export_path(@a)
assert_response :not_found
sign_in @owner
get aircraft_aircraft_roles_path(@a)
assert_select "a[href='#{aircraft_export_path(@a)}']", text: "Download .sam.zip"
path = download_export
assert_match(/attachment; filename="n12345-\d{4}-\d\d-\d\d\.sam\.zip"/, response.headers["Content-Disposition"])
assert_equal "N12345", Zip::File.open(path) { JSON.parse(_1.read("manifest.json")) }["aircraft"]["tail_number"]
assert_equal "Aircraft exported (.sam.zip)", @a.events.last.event_name
end
test "importing an archive: tail clash asks for a new tail, then the job builds the aircraft" do
sign_in @owner
path = download_export
archive = -> { Rack::Test::UploadedFile.new(path, "application/zip", original_filename: "n12345.sam.zip") }
sign_in @pilot
get root_path
assert_select "a[href='#{new_aircraft_import_path}']"
post aircraft_imports_path, params: { archive: archive.() }
assert_response :unprocessable_entity
assert_includes response.body, "An aircraft N12345 already exists"
assert_equal 0, AircraftImport.count
assert_enqueued_jobs 1, only: AircraftImportJob do
post aircraft_imports_path, params: { archive: archive.(), tail_number: "n54321" }
end
import = AircraftImport.last
assert_redirected_to aircraft_import_path(import)
assert_equal [ "N54321", @pilot, "queued" ], [ import.tail_number, import.user, import.status ]
follow_redirect!
assert_includes response.body, "Waiting to start"
assert_select "meta[http-equiv=refresh]"
perform_enqueued_jobs(only: AircraftImportJob)
import.reload
assert_equal "done", import.status, import.error
copy = import.aircraft
assert_equal [ "N54321", "Cessna" ], [ copy.tail_number, copy.make ]
assert_equal [ "owner" ], copy.roles.where(user: @pilot).pluck(:role) # the importer owns the copy
assert_equal "notes.txt", copy.squawks.sole.attachments.sole.filename.to_s
assert_equal 1, import.counts["logbook_entries"]
get aircraft_import_path(import)
assert_includes response.body, "Imported."
assert_select "meta[http-equiv=refresh]", 0
assert_select "a[href='#{aircraft_path(copy)}']"
perform_enqueued_jobs # purge the staged archive
refute import.reload.archive.attached?
sign_in create_user
get aircraft_import_path(import)
assert_response :not_found # only the importer (or an admin) sees it
end
test "a bad file is refused up front" do
sign_in @owner
post aircraft_imports_path, params: { archive: fixture_file_upload("flights.csv", "application/zip") }
assert_redirected_to new_aircraft_import_path
assert_match "That archive can't be imported: Not a valid .sam.zip archive", flash[:alert]
end
end
@@ -0,0 +1,152 @@
require "test_helper"
class LogbookImportFlowTest < ActionDispatch::IntegrationTest
include ActiveJob::TestHelper
# Stands in for Anthropic::Client: records each request and answers from a queue.
class FakeClaude
Message = Struct.new(:stop_reason, :content, :model)
Text = Struct.new(:type, :text)
attr_reader :requests
def initialize(*answers)
@answers = answers
@requests = []
end
def beta = self
def messages = self
def stream(**params)
@requests << params
answer = @answers.shift or raise "unexpected request"
message = answer.is_a?(Symbol) ? Message.new(answer, [], "claude-opus-5-5") : Message.new(:end_turn, [ Text.new(:text, answer.to_json) ], "claude-opus-5-5")
Struct.new(:accumulated_message).new(message)
end
end
JPEG = "\xFF\xD8\xFF\xE0fake-jpeg".b
def entry(text, page_start, page_end = page_start, **extra)
{ date: "2026-01-05", log_type: "ENG", entry_type: "MAINTENANCE", text: text, aircraft_hours: 1990.5,
signoff_person: "J. Mechanic A&P 1234567", signoff_location: "KOQU", page_start: page_start, page_end: page_end,
confidence: "high" }.merge(extra)
end
def answer(*entries, forms: []) = { entries: entries, non_logbook_pages: forms, unparseable_pages: [] }
def page(name) = Rack::Test::UploadedFile.new(StringIO.new(JPEG), "image/jpeg", original_filename: name)
setup do
@owner = create_user("owner@example.com")
@pilot = create_user("pilot@example.com")
@a = create_aircraft(owner: @owner, pilot: @pilot)
@previous_key = ENV["ANTHROPIC_API_KEY"]
ENV["ANTHROPIC_API_KEY"] = "sk-ant-test"
LogbookTranscriptionJob.batch_pages = 2
end
teardown do
ENV["ANTHROPIC_API_KEY"] = @previous_key
LogbookTranscriber.client = nil
LogbookTranscriptionJob.batch_pages = 6
end
test "pages are saved in name order and transcribed in overlapping batches" do
claude = FakeClaude.new(
# pages 1–2: A on page 1; B starts on page 2 and may continue
answer(entry("Changed oil", 0), entry("Annual inspection, found", 1, 1, entry_type: "INSPECTION")),
# pages 2–3: B completed from the carried copy, C on page 3 (no readable date, hard to read), page 3 also has a form
answer(entry("Annual inspection, found airworthy", 0, 1, entry_type: "INSPECTION"), entry("Replaced [?] gasket", 1, date: nil, confidence: "low"))
)
LogbookTranscriber.client = claude
sign_in @owner
get aircraft_logbook_entries_path(@a)
assert_select "a[href='#{new_aircraft_logbook_import_path(@a)}']", text: "Import scans"
get new_aircraft_logbook_import_path(@a)
assert_select "input[type=checkbox][name=transcribe]:not([disabled])"
post aircraft_logbook_imports_path(@a), params: { pages: [ page("page-10.jpg"), page("page-2.jpg"), page("page-1.jpg") ],
collection_id: "new", collection_name: "Engine Log #1", transcribe: "1", log_type: "" }
import = @a.logbook_imports.last
assert_redirected_to aircraft_logbook_import_path(@a, import)
document = import.document
assert_equal %w[page-1.jpg page-2.jpg page-10.jpg], document.pages.sort_by(&:id).map { _1.filename.to_s } # natural order
assert_equal "Engine Log #1", document.document_collection.name
assert_equal "LOG", document.doc_type
follow_redirect!
assert_select "meta[http-equiv=refresh]"
perform_enqueued_jobs(only: LogbookTranscriptionJob)
import.reload
assert_equal [ "done", 3, 3, 3 ], [ import.status, import.pages_total, import.pages_done, import.entries_created ], import.error
first, second = claude.requests
assert_equal "claude-opus-5-5", first[:model]
assert_equal :default, first[:fallbacks]
assert_equal [ "server-side-fallback-2026-07-01" ], first[:betas]
assert_equal :json_schema, first[:output_config][:format_][:type]
assert_equal 2, first[:messages][0][:content].count { _1[:type] == "image" }
assert_match "Entries already read from page 0", second[:messages][0][:content].map { _1[:text] }.compact.join
assert_match "Annual inspection, found", second[:messages][0][:content].map { _1[:text] }.compact.join
entries = @a.logbook_entries.order(:id)
assert_equal [ "Changed oil", "Annual inspection, found airworthy", "[date unreadable] Replaced [?] gasket" ], entries.map(&:text)
assert_equal [ 1, 2, 3 ], entries.map(&:page_number)
assert entries.all? { _1.document == document && _1.log_type == "ENG" }
assert_equal [ "MAINTENANCE", "INSPECTION", "MAINTENANCE" ], entries.map(&:entry_type)
assert_equal 1990.5, entries.first.aircraft_hours_at_entry.to_f
assert_equal Date.new(2026, 1, 5), entries.last.date # borrowed from the entry before it
assert_equal 2, import.warnings.size
assert_match "had no readable date", import.warnings.first
assert_match "hard to read", import.warnings.last
get aircraft_logbook_import_path(@a, import)
assert_includes response.body, "Done: 3 logbook entries added."
assert_select "meta[http-equiv=refresh]", 0
assert_equal "Logbook pages transcribed (3 entries)", @a.events.where(category: "logbook").last.event_name
end
test "a PDF goes up whole, the log type can be forced, and a refusal becomes a note" do
LogbookTranscriber.client = FakeClaude.new(answer(entry("Prop overhauled", 0), entry("Prop balanced", 2, log_type: "AC"), forms: [ 1 ]), :refusal)
sign_in @owner
pdf = Rack::Test::UploadedFile.new(StringIO.new("%PDF-1.4 fake"), "application/pdf", original_filename: "prop-log.pdf")
post aircraft_logbook_imports_path(@a), params: { pages: [ page("z-loose-page.jpg"), pdf ], transcribe: "1", log_type: "PROP",
collection_id: "new", document_name: "Prop log" }
perform_enqueued_jobs(only: LogbookTranscriptionJob)
import = @a.logbook_imports.last
assert_equal "done", import.status
request = LogbookTranscriber.client.requests.first
assert_equal [ "text", "document", "text" ], request[:messages][0][:content].map { _1[:type] }
assert_equal %w[PROP PROP], @a.logbook_entries.pluck(:log_type)
assert_equal [ 1, 1 ], @a.logbook_entries.pluck(:page_number) # both from the PDF, page 1 of the document
assert_match "Not logbook entries (forms, tags…), so nothing was transcribed from: prop-log.pdf page 2", import.warnings.first
assert_equal "Page 2 wasn't transcribed: Claude declined to read these pages.", import.warnings.last
end
test "without an API key, pages are only uploaded" do
ENV["ANTHROPIC_API_KEY"] = nil
LogbookTranscriber.client = FakeClaude.new # any request would raise
sign_in @owner
get new_aircraft_logbook_import_path(@a)
assert_select "input[type=checkbox][name=transcribe][disabled]"
assert_includes response.body, "ANTHROPIC_API_KEY"
post aircraft_logbook_imports_path(@a), params: { pages: [ page("p1.jpg") ], transcribe: "1", collection_id: "new" }
perform_enqueued_jobs(only: LogbookTranscriptionJob)
import = @a.logbook_imports.last
assert_equal [ "done", false, 0 ], [ import.status, import.transcribe, import.entries_created ]
assert_equal 1, import.document.pages.count
end
test "rejects files that aren't scans, and pilots can't import" do
sign_in @owner
post aircraft_logbook_imports_path(@a), params: { pages: [ fixture_file_upload("engine_data/cgr30p.csv", "application/x-msdownload") ], collection_id: "new" }
assert_response :unprocessable_entity
assert_equal 0, @a.documents.count
sign_in @pilot
get new_aircraft_logbook_import_path(@a)
assert_redirected_to aircraft_path(@a)
end
end
+54 -11
View File
@@ -8,10 +8,11 @@ class OilAnalysisFlowTest < ActionDispatch::IntegrationTest
@engine = create_component(@aircraft, hours_since_overhaul: 120.5)
end
def results(**overrides)
def results(elements: {}, **overrides)
{ sample_date: "2026-08-01", status: "normal", component_id: @engine.id, lab: "Example Lab",
engine_hours: 120.5, oil_hours: 40, iron: 30, iron_avg: 35, copper: 6, copper_avg: 9,
lead: 2500, lead_avg: 2400, silicon: 22, silicon_avg: 12 }.merge(overrides)
engine_hours: 120.5, oil_hours: 40,
elements: { iron: 30, copper: 6, lead: 2500, silicon: 22 }.merge(elements),
element_averages: { iron: 35, copper: 9, lead: 2400, silicon: 12 } }.merge(overrides)
end
test "pilot adds samples; trends, flags and comparison render" do
@@ -20,7 +21,7 @@ class OilAnalysisFlowTest < ActionDispatch::IntegrationTest
assert_response :success
assert_includes response.body, 'value="120.5"' # engine hours default from the engine
post aircraft_oil_analyses_path(@aircraft), params: { oil_analysis: results(sample_date: "2026-03-01", iron: 25, silicon: 10) }
post aircraft_oil_analyses_path(@aircraft), params: { oil_analysis: results(sample_date: "2026-03-01", elements: { iron: 25, silicon: 10 }) }
post aircraft_oil_analyses_path(@aircraft), params: { oil_analysis: results(report: fixture_file_upload("engine_data/cgr30p.csv", "application/pdf")) }
latest = @aircraft.oil_analyses.recent_first.first
assert_redirected_to aircraft_oil_analysis_path(@aircraft, latest)
@@ -42,19 +43,44 @@ class OilAnalysisFlowTest < ActionDispatch::IntegrationTest
test "only owners edit and delete" do
analysis = @aircraft.oil_analyses.create!(results.except(:component_id))
sign_in @pilot
patch aircraft_oil_analysis_path(@aircraft, analysis), params: { oil_analysis: { status: "high" } }
patch aircraft_oil_analysis_path(@aircraft, analysis), params: { oil_analysis: { status: "action_required" } }
assert_equal "normal", analysis.reload.status
sign_in @owner
get edit_aircraft_oil_analysis_path(@aircraft, analysis)
assert_response :success
patch aircraft_oil_analysis_path(@aircraft, analysis), params: { oil_analysis: { status: "elevated", iron: "" } }
assert_equal "elevated", analysis.reload.status
assert_nil analysis.iron
assert_select "input[name='oil_analysis[elements][iron]'][value='30.0']"
assert_select "input[name='oil_analysis[elements][zinc]']" # the extra elements are there too
patch aircraft_oil_analysis_path(@aircraft, analysis), params: { oil_analysis: { status: "monitor", elements: { iron: "", copper: "6", lead: "2500", silicon: "22", zinc: "4" } } }
analysis.reload
assert_equal "monitor", analysis.status
assert_nil analysis.value("iron")
assert_equal 4.0, analysis.value("zinc")
delete aircraft_oil_analysis_path(@aircraft, analysis)
assert_equal 0, @aircraft.oil_analyses.count
end
test "oil type, properties and leaving a sample out of trends" do
sign_in @owner
post aircraft_oil_analyses_path(@aircraft), params: { oil_analysis: results(sample_date: "2026-03-01", elements: { iron: 25 }) }
post aircraft_oil_analyses_path(@aircraft), params: { oil_analysis: results(sample_date: "2026-05-01", elements: { iron: 90 }, excluded_from_averages: "1") }
post aircraft_oil_analyses_path(@aircraft), params: { oil_analysis: results(oil_type: "Aeroshell W100 Plus", status: "",
oil_properties: { flashpoint_f: "445", fuel_percent: "0.5" }) }
latest = @aircraft.oil_analyses.recent_first.first
assert_nil latest.status
get aircraft_oil_analysis_path(@aircraft, latest)
assert_includes response.body, "Aeroshell W100 Plus"
assert_includes response.body, "445 °F"
assert_includes response.body, "Not rated"
get aircraft_oil_analyses_path(@aircraft)
assert_includes response.body, "left out of trends"
iron = response.body[/"name":"Iron","data":\[(.*?)\]\]/, 1]
assert_includes iron, "25.0"
refute_includes iron, "90.0" # the excluded sample isn't charted
end
test "an engine from another aircraft is ignored" do
other = create_component(create_aircraft)
sign_in @owner
@@ -85,8 +111,8 @@ class OilAnalysisImportTest < ActionDispatch::IntegrationTest
assert analyses.all? { _1.component == @engine && _1.lab == "AvLab" } # matched by engine serial
assert analyses.first.report.attached?
refute analyses.last.report.attached?
assert_equal 44.0, analyses.first.iron.to_f
assert_equal 13.7, analyses.first.silicon_avg.to_f
assert_equal 44.0, analyses.first.value("iron")
assert_equal 13.7, analyses.first.average("silicon")
assert_equal 3, @aircraft.events.where(category: "oil_analysis").count
post import_aircraft_oil_analyses_path(@aircraft), params: { report: report }
@@ -98,7 +124,7 @@ class OilAnalysisImportTest < ActionDispatch::IntegrationTest
end
test "attaches the PDF to a matching sample entered by hand" do
manual = @aircraft.oil_analyses.create!(sample_date: Date.new(2026, 8, 20), iron: 44)
manual = @aircraft.oil_analyses.create!(sample_date: Date.new(2026, 8, 20), elements: { iron: 44 })
sign_in @owner
post import_aircraft_oil_analyses_path(@aircraft), params: { report: report }
assert_equal 3, @aircraft.oil_analyses.count
@@ -116,4 +142,21 @@ class OilAnalysisImportTest < ActionDispatch::IntegrationTest
assert_match(/Couldn't import that report/, flash[:alert])
assert_equal 0, @aircraft.oil_analyses.count
end
test "imports a Blackstone report: 20 elements, properties, oil type, unrated" do
sign_in @owner
post import_aircraft_oil_analyses_path(@aircraft), params: { report: fixture_file_upload("oil_analysis/blackstone_report.pdf", "application/pdf") }
assert_equal "Imported 5 samples from the Blackstone report.", flash[:notice]
latest = @aircraft.oil_analyses.recent_first.first
assert_equal [ Date.new(2024, 1, 25), "Blackstone", "Phillips XC (A/C) 20W/50", nil, @in_service ],
[ latest.sample_date, latest.lab, latest.oil_type, latest.status, latest.component ] # no engine S/N: the engine in service
assert_equal 20, latest.elements.size
assert_equal 445.0, latest.property("flashpoint_f")
assert latest.report.attached?
follow_redirect!
assert_select "td", text: "Zinc"
assert_includes response.body, "Viscosity @ 100°C"
assert_match(/Iron, Copper, .* above average/, response.body) # 2019: iron 818 ppm vs the 35 ppm universal average
end
end
+1 -1
View File
@@ -24,7 +24,7 @@ class PagesTest < ActionDispatch::IntegrationTest
@major = @a.major_records.create!(record_type: "alteration", title: "LED lights", date_performed: Date.current)
@flight = @a.flight_logs.create!(date: Date.current, tach_time: 1.2)
@cr = @a.consumable_records.create!(record_type: "oil", date: Date.current, quantity_added: 1, flight_hours: 1000)
@oa = @a.oil_analyses.create!(sample_date: Date.current, iron: 30, iron_avg: 35)
@oa = @a.oil_analyses.create!(sample_date: Date.current, elements: { iron: 30 }, element_averages: { iron: 35 })
@token = @a.share_tokens.create!(privilege: "maintenance", label: "Mechanic")
@a.log_event!("aircraft", "Created", user: @owner)
sign_in @owner
+23
View File
@@ -0,0 +1,23 @@
require "test_helper"
class ComponentTest < ActiveSupport::TestCase
test "deleting a component, or its aircraft, works when records point at it" do
a = create_aircraft
engine = create_component(a)
ad = AirworthinessDirective.create!(name: "2020-01-01", short_description: "Check")
compliance = a.ad_compliances.create!(airworthiness_directive: ad, date_complied: Date.current, compliance_notes: "Done",
permanent: true, component: engine)
annual = InspectionType.create!(name: "Annual")
record = a.inspection_records.create!(inspection_type: annual, date: Date.current, component: engine)
engine.destroy!
assert_nil compliance.reload.component_id
assert_nil record.reload.component_id
other = create_component(a)
a.ad_compliances.create!(airworthiness_directive: ad, date_complied: Date.current, compliance_notes: "Done", permanent: true, component: other)
a.inspection_records.create!(inspection_type: annual, date: Date.current, component: other)
a.destroy!
assert_not Aircraft.exists?(a.id)
end
end
+25 -3
View File
@@ -6,7 +6,8 @@ class OilAnalysisTest < ActiveSupport::TestCase
def analysis(**attrs) = @a.oil_analyses.new({ sample_date: Date.current }.merge(attrs))
test "flags readings well above the lab average" do
a = analysis(iron: 60, iron_avg: 35, copper: 10, copper_avg: 20, silicon: 20, silicon_avg: 13.3, tin: 5)
a = analysis(elements: { iron: 60, copper: 10, silicon: 20, tin: 5 },
element_averages: { iron: 35, copper: 20, silicon: 13.3 })
assert a.flagged?("iron")
refute a.flagged?("copper")
assert a.flagged?("silicon") # exactly 1.5×
@@ -14,13 +15,34 @@ class OilAnalysisTest < ActiveSupport::TestCase
assert_equal %w[iron silicon], a.flagged_elements
end
test "validates status, non-negative results, and engine on this aircraft" do
test "results from a form: blanks dropped, numbers kept, unknown keys ignored" do
a = analysis(elements: { "iron" => "30.5", "copper" => "", "unobtainium" => "9" },
oil_properties: { "flashpoint_f" => "445", "water_percent" => "0" })
assert a.valid?
assert_equal({ "iron" => 30.5 }, a.elements)
assert_equal({ "flashpoint_f" => 445.0, "water_percent" => 0.0 }, a.oil_properties)
a.save!
assert_equal({ "iron" => 30.5 }, a.reload.elements)
end
test "validates status, non-negative numeric results, and engine on this aircraft" do
assert analysis.valid?
assert analysis(status: "").valid? # not rated
assert analysis(status: "monitor").valid?
refute analysis(status: "bad").valid?
refute analysis(iron: -1).valid?
a = analysis(elements: { iron: "-1", copper: "lots" })
refute a.valid?
assert_match "Iron and Copper", a.errors[:elements].first
refute analysis(oil_properties: { fuel_percent: "x" }).valid?
other_engine = create_component(create_aircraft)
a = analysis(component: other_engine)
refute a.valid?
assert_includes a.errors[:component], "must be on this aircraft"
end
test "elements_in lists elements any sample has, in display order" do
a = analysis(elements: { lead: 900, iron: 30 })
b = analysis(elements: { zinc: 4 })
assert_equal %w[iron lead zinc], OilAnalysis.elements_in([ a, b ])
end
end
+213
View File
@@ -0,0 +1,213 @@
require "test_helper"
class AircraftArchiveTest < ActiveSupport::TestCase
include ActiveJob::TestHelper
PNG = "\x89PNG\r\n\x1A\n".b + "rest-of-image".b
setup do
@owner = create_user("owner@example.com")
@dir = Dir.mktmpdir
end
teardown { FileUtils.rm_rf(@dir) }
def upload(name, body, type) = { io: StringIO.new(body), filename: name, content_type: type }
# An aircraft with something in every section.
def full_aircraft
a = create_aircraft(owner: @owner, tail_number: "N12345", make: "Cessna", model: "150", icao_type: "C150", tach_time: 2000)
a.picture.attach(upload("plane.png", PNG, "image/png"))
engine = create_component(a, serial_number: "900001", component_type: component_type("Engine"))
oil = create_component(a, parent_component: engine, component_type: component_type("Oil"), replacement_critical: true, replacement_hours: 50)
collection = a.document_collections.create!(name: "Logbooks", visibility: "maintenance")
doc = a.documents.create!(name: "Engine log", document_collection: collection, doc_type: "LOG")
doc.pages.attach(upload("page1.pdf", "%PDF-1.4 page one", "application/pdf"), upload("page2.png", PNG, "image/png"))
entry = a.logbook_entries.create!(date: Date.new(2026, 1, 5), text: "Oil changed", log_type: "ENG", document: doc, aircraft_hours_at_entry: 1990)
a.squawks.create!(priority: 1, issue_reported: "Cracked fairing", component: engine, reported_by: @owner,
attachments: [ upload("crack.png", PNG, "image/png"), upload("notes.txt", "see photo", "text/plain") ])
a.squawks.create!(priority: 3, issue_reported: "Old one", resolved: true, resolved_at: 1.day.ago)
annual = InspectionType.create!(name: "Annual", recurring: true, recurring_months: 12)
annual.aircraft << a
record = a.inspection_records.create!(inspection_type: annual, date: Date.new(2026, 2, 1), aircraft_hours: 1995, logbook_entry: entry)
ad = AirworthinessDirective.create!(name: "2020-01-01", short_description: "Check muffler", recurring: true, recurring_hours: 100, docket_number: "FAA-2020-1")
ad.components << engine
a.ad_compliances.create!(airworthiness_directive: ad, date_complied: Date.new(2026, 2, 1), next_due_at_time: 2095, compliance_notes: "Inspected",
component: engine, inspection_record: record)
flight = a.flight_logs.create!(date: Date.new(2025, 7, 14), tach_time: 1.2, departure_location: "KOQU", destination_location: "KBID",
user: @owner, track_log: { io: file_fixture("tracks/flight.gpx").open, filename: "flight.gpx" },
engine_data: { io: file_fixture("engine_data/cgr30p.csv").open, filename: "cgr30p.csv" })
a.consumable_records.create!(record_type: "oil", date: Date.new(2026, 1, 5), quantity_added: 1, flight_hours: 1990, flight_log: flight)
a.major_records.create!(record_type: "alteration", title: "LED lights", date_performed: Date.new(2025, 5, 1), form_337_document: doc)
a.notes.create!(text: "Hangar 4", public: true, user: @owner)
a.oil_analyses.create!(sample_date: Date.new(2026, 1, 5), lab: "Blackstone", sample_number: "S1", component: engine, oil_type: "W100",
elements: { iron: 30, zinc: 4 }, element_averages: { iron: 35 }, oil_properties: { flashpoint_f: 445 },
excluded_from_averages: true, report: upload("report.pdf", "%PDF-1.4 lab", "application/pdf"))
a
end
def export(aircraft)
path = File.join(@dir, "export.sam.zip")
AircraftArchive::Exporter.new(aircraft, source: "sam.example.com").write_to(path)
path
end
def manifest(path) = Zip::File.open(path) { JSON.parse(_1.read("manifest.json")) }
test "export writes a manifest the original app accepts, plus every file" do
path = export(full_aircraft)
data = manifest(path)
assert_equal AircraftArchive::TOP_LEVEL_KEYS.sort, data.keys.sort # the original rejects unknown or missing top-level keys
assert_equal 2, data["schema_version"]
assert_equal "N12345", data["aircraft"]["tail_number"]
assert_equal 2, data["document_images"].size
squawk = data["squawks"].find { _1["issue_reported"] == "Cracked fairing" }
assert_equal 2, squawk["attachments"].size
assert_equal squawk["attachments"].first, squawk["attachment"] # what the original reads
oil = data["oil_analysis_reports"].first
assert_equal({ "iron" => 30.0, "zinc" => 4.0 }, oil["elements_ppm"])
assert_equal "S1", oil["lab_number"]
files = Zip::File.open(path) { |zip| zip.entries.map(&:name) - [ "manifest.json" ] }
assert_equal 8, files.size # picture, 2 document pages, 2 squawk files, track log, engine data, oil report
assert files.all? { _1.start_with?("attachments/") }
assert files.any? { _1.end_with?("/crack.png") }, "original filenames are kept"
end
test "round trip: importing an export recreates the aircraft with new IDs" do
original = full_aircraft
path = export(original)
other = create_user("other@example.com")
result = AircraftArchive::Importer.new(path, owner: other, tail_number: "N54321").run
a = result[:aircraft]
assert_equal [ "N54321", "Cessna", "150", "C150", 2000 ], [ a.tail_number, a.make, a.model, a.icao_type, a.tach_time.to_i ]
refute_equal original.id, a.id
assert a.picture.attached?
assert_equal [ "owner" ], a.roles.where(user: other).pluck(:role)
assert_equal 2, a.components.count
oil = a.components.find_by(component_type: component_type("Oil"))
assert_equal a.components.find_by(serial_number: "900001"), oil.parent_component
doc = a.documents.sole
assert_equal %w[page1.pdf page2.png], doc.pages.map { _1.filename.to_s }
assert_equal "%PDF-1.4 page one", doc.pages.first.download
assert_equal doc, a.logbook_entries.sole.document
squawk = a.squawks.find_by(issue_reported: "Cracked fairing")
assert_equal %w[crack.png notes.txt], squawk.attachments.map { _1.filename.to_s }.sort
assert_equal "IN-USE", squawk.component.status
assert a.squawks.find_by(issue_reported: "Old one").resolved?
assert_includes a.inspection_types.pluck(:name), "Annual"
assert_equal 1, InspectionType.where(name: "Annual").count, "existing inspection types are reused"
compliance = a.ad_compliances.sole
assert_equal [ "2020-01-01", 2095 ], [ compliance.airworthiness_directive.name, compliance.next_due_at_time.to_i ]
assert_equal a.inspection_records.sole, compliance.inspection_record
assert_equal 1, AirworthinessDirective.where(name: "2020-01-01").count
assert_includes compliance.airworthiness_directive.components, a.components.find_by(serial_number: "900001")
flight = a.flight_logs.sole
assert flight.track_log.attached?
assert flight.engine_data.attached?
assert_equal flight, a.consumable_records.sole.flight_log
assert_equal doc, a.major_records.sole.form_337_document
assert_match "Hangar 4", a.notes.sole.text
analysis = a.oil_analyses.sole
assert_equal [ "Blackstone", "S1", "W100", true ], [ analysis.lab, analysis.sample_number, analysis.oil_type, analysis.excluded_from_averages ]
assert_equal({ "iron" => 30.0, "zinc" => 4.0 }, analysis.elements)
assert_equal({ "iron" => 35.0 }, analysis.element_averages)
assert analysis.report.attached?
assert_equal "aircraft", a.events.last.category
assert_empty result[:warnings]
end
test "imports an archive from the original app (UUIDs, its field names, links we don't keep)" do
path = File.join(@dir, "original.sam.zip")
ids = Hash.new { |h, k| h[k] = SecureRandom.uuid }
data = AircraftArchive::TOP_LEVEL_KEYS.to_h { [ _1, [] ] }.merge(
"schema_version" => 2, "exported_at" => "2026-10-01T12:00:00+00:00", "source_instance" => "sam.example.org",
"aircraft" => { "id" => ids[:a], "tail_number" => "N0000X", "make" => "Piper", "model" => "PA-28", "status" => "AVAILABLE",
"tach_time" => "1234.5", "tach_time_offset" => "0.0", "hobbs_time" => "0.0", "hobbs_time_offset" => "0.0", "picture" => nil },
"component_types" => [ { "id" => ids[:ct], "name" => "engine", "consumable" => false } ],
"components" => [ { "id" => ids[:c], "aircraft_id" => ids[:a], "parent_component_id" => nil, "component_type_id" => ids[:ct],
"manufacturer" => "Lycoming", "model" => "O-360", "status" => "IN-USE", "date_in_service" => "2020-01-01",
"hours_in_service" => "500.0", "hours_since_overhaul" => "500.0", "tbo_hours" => 2000, "tbo_critical" => true } ],
"logbook_entries" => [ { "id" => ids[:le], "aircraft_id" => ids[:a], "log_type" => "ENG", "date" => "2026-01-01", "text" => "Annual",
"components" => [ ids[:c] ], "component_hours" => { ids[:c] => 500.0 }, "entry_type" => "INSPECTION" } ],
"squawks" => [ { "id" => ids[:s], "aircraft_id" => ids[:a], "priority" => 0, "issue_reported" => "Mag drop",
"attachment" => "attachments/health/squawks/abc123.png", "resolved" => false, "logbook_entries" => [] } ],
"oil_analysis_reports" => [ { "id" => ids[:o], "aircraft_id" => ids[:a], "component_id" => ids[:c], "sample_date" => "2026-01-01",
"lab" => "AVLab", "lab_number" => "", "oil_hours" => "40.0", "elements_ppm" => { "iron" => 12.5 },
"oil_properties" => nil, "status" => "monitor", "excluded_from_averages" => false } ],
"flight_logs" => [ { "id" => ids[:f], "aircraft_id" => ids[:a], "date" => "2026-02-01", "tach_time" => "1.3",
"track_log" => "attachments/track_logs/xyz.kml" } ],
"features" => [ { "feature" => "airworthiness_enforcement", "enabled" => true }, { "feature" => "oil_analysis", "enabled" => true } ]
)
Zip::OutputStream.open(path) do |zip|
zip.put_next_entry("manifest.json")
zip.write(data.to_json)
zip.put_next_entry("attachments/health/squawks/abc123.png")
zip.write(PNG)
zip.put_next_entry("attachments/track_logs/xyz.kml")
zip.write(file_fixture("tracks/flight.kml").read)
end
engine_type = component_type("Engine")
preview = AircraftArchive::Importer.check(path)
assert_equal [ "N0000X", "sam.example.org", 1 ], [ preview.tail_number, preview.source, preview.counts["components"] ]
result = AircraftArchive::Importer.new(path, owner: @owner).run
a = result[:aircraft]
assert_equal [ "N0000X", "Piper", 1234.5 ], [ a.tail_number, a.make, a.tach_time.to_f ]
assert_equal engine_type, a.components.sole.component_type, "matched case-insensitively"
assert_equal 2000, a.components.sole.tbo_hours
assert_equal "INSPECTION", a.logbook_entries.sole.entry_type
squawk = a.squawks.sole
assert_equal [ 0, "abc123.png" ], [ squawk.priority, squawk.attachments.sole.filename.to_s ]
analysis = a.oil_analyses.sole
assert_equal [ "monitor", 12.5, nil, a.components.sole ], [ analysis.status, analysis.value("iron"), analysis.sample_number, analysis.component ]
assert a.flight_logs.sole.track_log.attached?
assert_equal [ "1 logbook entry was linked to components; those links aren't kept here." ], result[:warnings]
end
test "a file whose contents don't match its name is skipped with a note" do
path = export(full_aircraft)
data = manifest(path)
fake = data["squawks"].find { _1["attachments"].any? }["attachments"].first
Zip::File.open(path) { |zip| zip.get_output_stream(fake) { _1.write("MZ not a png") } }
result = AircraftArchive::Importer.new(path, owner: @owner, tail_number: "N777").run
assert_equal 1, result[:aircraft].squawks.find_by(issue_reported: "Cracked fairing").attachments.count
assert_match "doesn't contain what its name says (.png)", result[:warnings].sole
end
test "rejects unsafe or unrecognized archives before importing anything" do
write = lambda do |entries|
path = File.join(@dir, "#{SecureRandom.hex(4)}.zip")
Zip::OutputStream.open(path) { |zip| entries.each { |name, body| zip.put_next_entry(name); zip.write(body) } }
path
end
good = AircraftArchive::TOP_LEVEL_KEYS.to_h { [ _1, [] ] }.merge("schema_version" => 2, "aircraft" => { "tail_number" => "N1" })
{
write.({ "notes.txt" => "hi" }) => "no manifest.json",
write.({ "manifest.json" => good.merge("schema_version" => 3).to_json }) => "Unsupported archive version 3",
write.({ "manifest.json" => good.except("squawks").to_json }) => "missing squawks",
write.({ "manifest.json" => good.to_json, "../../evil.txt" => "x" }) => "unsafe path",
write.({ "manifest.json" => good.merge("aircraft" => {}).to_json }) => "no aircraft tail number",
write.({ "manifest.json" => "{not json" }) => "couldn't be read",
File.join(@dir, "missing.zip").tap { File.write(_1, "not a zip") } => "Not a valid .sam.zip"
}.each do |path, message|
error = assert_raises(AircraftArchive::Error) { AircraftArchive::Importer.check(path) }
assert_match message, error.message
end
assert_equal 0, Aircraft.where(tail_number: "N1").count
end
test "a failure part-way removes everything the import created" do
path = export(full_aircraft)
before = [ Aircraft.count, Component.count, ActiveStorage::Blob.count ]
importer = AircraftArchive::Importer.new(path, owner: @owner, tail_number: "N999")
importer.define_singleton_method(:import_notes) { raise "disk on fire" }
assert_raises(RuntimeError) { importer.run }
assert_equal before[0, 2], [ Aircraft.count, Component.count ]
assert_equal 0, Aircraft.where(tail_number: "N999").count
perform_enqueued_jobs
assert_equal before[2], ActiveStorage::Blob.count
end
end
+32
View File
@@ -0,0 +1,32 @@
require "test_helper"
class LogbookTranscriberTest < ActiveSupport::TestCase
Message = Struct.new(:stop_reason, :content, :model)
Text = Struct.new(:type, :text)
def client_returning(message)
Class.new do
define_method(:beta) { self }
define_method(:messages) { self }
define_method(:stream) { |**| Struct.new(:accumulated_message).new(message) }
end.new
end
def transcribe(message) = LogbookTranscriber.new(client: client_returning(message)).transcribe([ { data: "x", media_type: "image/png" } ])
test "reads the structured answer" do
json = { entries: [ { "text" => "Annual" } ], non_logbook_pages: [ 2 ], unparseable_pages: [] }.to_json
result = transcribe(Message.new(:end_turn, [ Text.new(:thinking, ""), Text.new(:text, json) ], "claude-opus-5-5"))
assert_equal [ { "text" => "Annual" } ], result.entries
assert_equal [ 2 ], result.non_logbook_pages
end
test "turns refusals, truncation and bad JSON into clear errors" do
{ refusal: "declined", max_tokens: "too long to finish" }.each do |reason, message|
error = assert_raises(LogbookTranscriber::Error) { transcribe(Message.new(reason, [], "m")) }
assert_match message, error.message
end
error = assert_raises(LogbookTranscriber::Error) { transcribe(Message.new(:end_turn, [ Text.new(:text, "{nope") ], "m")) }
assert_match "wasn't valid JSON", error.message
end
end
+91 -22
View File
@@ -1,43 +1,112 @@
require "test_helper"
class OilReportParserTest < ActiveSupport::TestCase
def parse(name) = OilReportParser.from_pdf(file_fixture("oil_analysis/#{name}").open)
# A real AvLab report rebuilt with glyph positions intact (including the hidden
# color-code layer that overlaps the results) and a dummy header.
def report = @report ||= OilReportParser.from_pdf(file_fixture("oil_analysis/avlab_report.pdf").open)
def avlab = @avlab ||= parse("avlab_report.pdf")
test "reads the header" do
assert_equal "AvLab", report.lab
assert_equal "N12345", report.tail_number
assert_equal "900001", report.engine_serial
assert_equal "CONT. 200", report.engine_model
# Anonymized sample reports from the original Simple Aircraft Manager project's
# test suite (public domain): an older AvLab layout and a Blackstone report.
def older_avlab = @older_avlab ||= parse("avlab_older_report.pdf")
def blackstone = @blackstone ||= parse("blackstone_report.pdf")
test "AvLab: reads the header" do
assert_equal "AvLab", avlab.lab
assert_equal "N12345", avlab.tail_number
assert_equal "900001", avlab.engine_serial
assert_equal "CONT. 200", avlab.engine_model
end
test "reads the current sample and both previous ones" do
assert_equal [ true, false, false ], report.samples.map { _1[:current] }
current = report.samples.first
test "AvLab: reads the current sample and both previous ones" do
assert_equal [ true, false, false ], avlab.samples.map { _1[:current] }
current = avlab.samples.first
assert_equal Date.new(2026, 8, 20), current[:sample_date]
assert_equal Date.new(2026, 9, 3), current[:analysis_date]
assert_equal "P26", current[:sample_number]
assert_equal [ 94.7, 43.7, 43.7, 1 ], current.values_at(:engine_hours, :oil_hours, :filter_hours, :oil_added).map(&:to_f)
assert_equal "normal", current[:status]
assert_match(/ALL OIL VALUES SEEM FINE/, current[:lab_comments])
assert_equal "ALL OIL VALUES SEEM FINE. WE WILL CONTINUE TO MONITOR THIS ENGINE WITH YOUR NEXT SAMPLE.", current[:lab_comments]
end
test "reads results and lab averages through the color-code layer" do
current, previous1, previous2 = report.samples
assert_equal({ iron: 44.0, copper: 8.1, nickel: 2.5, chromium: 3.9, aluminum: 6.7, lead: 2650.0, silicon: 25.3, tin: 1.6 },
current.slice(:iron, :copper, :nickel, :chromium, :aluminum, :lead, :silicon, :tin).transform_values(&:to_f))
assert_equal({ iron_avg: 40.5, lead_avg: 2654.0, tin_avg: 3.2 }, current.slice(:iron_avg, :lead_avg, :tin_avg).transform_values(&:to_f))
assert_nil current[:silver] # N/A
assert_nil current[:silver_avg]
assert_equal 0.3, previous1[:nickel].to_f # a real "0" hidden under a color-code "0"
assert_equal 0, previous1[:tin] # "< 0.1"
assert_equal 2024.0, previous2[:lead].to_f
assert_equal 58.7, previous2[:iron].to_f # not overwritten by "Cylinder Type: steel"
test "AvLab: reads results and lab averages through the color-code layer" do
current, previous1, previous2 = avlab.samples.map { |s| [ s[:elements].transform_values(&:to_f), s[:element_averages].transform_values(&:to_f) ] }
assert_equal({ "iron" => 44.0, "copper" => 8.1, "nickel" => 2.5, "chromium" => 3.9, "aluminum" => 6.7, "lead" => 2650.0, "silicon" => 25.3, "tin" => 1.6 },
current[0].slice("iron", "copper", "nickel", "chromium", "aluminum", "lead", "silicon", "tin"))
assert_equal({ "iron" => 40.5, "lead" => 2654.0, "tin" => 3.2 }, current[1].slice("iron", "lead", "tin"))
refute current[0].key?("silver") # N/A
refute current[1].key?("silver")
assert_equal 0.3, previous1[0]["nickel"] # a real "0" hidden under a color-code "0"
assert_equal 0, previous1[0]["tin"] # "< 0.1"
assert_equal 2024.0, previous2[0]["lead"]
assert_equal 58.7, previous2[0]["iron"] # not overwritten by "Cylinder Type: steel"
end
test "AvLab, older layout: unused labels don't steal values; comments span lines" do
current, previous = older_avlab.samples
assert_nil current[:oil_added] # the "Filter Wt. (mgs): 121" beside it isn't oil added
assert_equal "normal", current[:status]
assert_match(/\AALL METALLIC DEBRIS .* WITH YOUR NEXT SAMPLE\.\z/, current[:lab_comments])
assert_equal "monitor", previous[:status] # "** SEE LAB COMMENTS **"
assert_match "CLOSEST MATCH AMS# 6274, WITH THE LARGEST PIECE", previous[:lab_comments]
assert_equal [ 518.1, 43, 5 ], previous.values_at(:engine_hours, :oil_hours, :oil_added).map(&:to_f)
assert_equal({ "aluminum" => 6.8, "chromium" => 4.1, "copper" => 13.0, "iron" => 30.2, "lead" => 1510.0, "nickel" => 0.5, "silicon" => 3.7, "tin" => 0.0 },
previous[:elements].transform_values(&:to_f).sort.to_h)
end
test "Blackstone: header, five samples newest first, no rating" do
assert_equal "Blackstone", blackstone.lab
assert_equal "Phillips XC (A/C) 20W/50", blackstone.oil_type
assert_equal "Generic Engine", blackstone.engine_model
assert_nil blackstone.tail_number # "N0000X" isn't a real registration
assert_equal %w[2024-01-25 2022-03-31 2021-08-12 2020-06-08 2019-12-30], blackstone.samples.map { _1[:sample_date].iso8601 }
assert_equal [ true, false, false, false, false ], blackstone.samples.map { _1[:current] }
assert blackstone.samples.all? { _1[:status].nil? }
current = blackstone.samples.first
assert_equal "S000000", current[:sample_number]
assert_match(/\ALorem ipsum dolor sit amet.* id est laborum\.\z/, current[:lab_comments])
assert_nil blackstone.samples.second[:lab_comments]
end
test "Blackstone: hours, all 20 elements, universal averages and oil properties per column" do
current, second, _, fourth, oldest = blackstone.samples
assert_equal [ 43, 518, 5 ], current.values_at(:oil_hours, :engine_hours, :oil_added).map(&:to_f)
assert_equal 1903, fourth[:engine_hours].to_i # "1,903"
assert_nil blackstone.samples.third[:oil_added]
assert_equal 20, current[:elements].size
assert_equal({ "iron" => 36.0, "lead" => 1841.0, "aluminum" => 7.0, "zinc" => 4.0, "barium" => 0.0 },
current[:elements].slice("iron", "lead", "aluminum", "zinc", "barium").transform_values(&:to_f))
assert_equal 807.0, second[:elements]["lead"].to_f # skips the unit/location average column (1458)
assert_equal 818.0, oldest[:elements]["iron"].to_f
assert_equal({ "iron" => 35.0, "lead" => 2354.0, "phosphorus" => 415.0 },
current[:element_averages].slice("iron", "lead", "phosphorus").transform_values(&:to_f))
assert_equal({ "viscosity_sus_210f" => 95.3, "viscosity_cst_100c" => 19.24, "flashpoint_f" => 445.0, "fuel_percent" => 0.5, "water_percent" => 0.0, "insolubles_percent" => 0.3 },
current[:oil_properties].transform_values(&:to_f))
assert_equal 490.0, oldest[:oil_properties]["flashpoint_f"].to_f
end
test "rejects other PDFs and non-PDFs" do
assert_raises(OilReportParser::Error) { OilReportParser.from_pdf(StringIO.new("not a pdf")) }
assert_raises(OilReportParser::Error) { OilReportParser.new([]).parse }
assert_raises(OilReportParser::Error) { OilReportParser::Avlab.new([]).parse }
error = assert_raises(OilReportParser::Error) { parse_pdf_text("Just some other document") }
assert_match "AvLab and Blackstone", error.message
end
private
# A minimal one-page PDF with the given text.
def parse_pdf_text(text)
objects = [ "<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",
nil, "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>" ]
stream = "BT /F1 12 Tf 72 720 Td (#{text}) Tj ET"
objects[3] = "<< /Length #{stream.bytesize} >>\nstream\n#{stream}\nendstream"
pdf = +"%PDF-1.4\n"
offsets = objects.each_with_index.map { |body, i| pdf.bytesize.tap { pdf << "#{i + 1} 0 obj\n#{body}\nendobj\n" } }
xref = pdf.bytesize
pdf << "xref\n0 #{objects.size + 1}\n0000000000 65535 f \n" << offsets.map { format("%010d 00000 n \n", _1) }.join
pdf << "trailer\n<< /Size #{objects.size + 1} /Root 1 0 R >>\nstartxref\n#{xref}\n%%EOF\n"
OilReportParser.from_pdf(StringIO.new(pdf))
end
end