mirror of
https://github.com/rickbarrette/simple-aircraft-manager-rails.git
synced 2026-11-17 15:50:36 -05:00
Track oil analysis reports; import AvLab PDFs
New Oil Analysis tab: one record per oil sample with dates, hours, the lab's verdict and comments, ppm results for 12 wear metals with the lab's averages, and the report PDF. Shows wear-metal trends, a side-by-side history table, and flags readings 1.5x or more above the lab average. AvLab report PDFs can be imported: every sample on the report (current and previous) is added unless already recorded, the engine is matched by serial number, and reports for another tail number are refused. The parser reads positioned text and drops the hidden color-code layer that overlaps results. Adds the pdf-reader gem. Test fixture is a rebuilt report with a dummy header. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6c6e7af8e6
commit
d519aa9aae
24 files changed
+3456
-2
No files matched your search
@@ -73,3 +73,5 @@ gem "csv", "~> 3.3"
|
||||
gem "caxlsx", "~> 4.5", group: :test
|
||||
|
||||
gem "webmock", "~> 3.34", group: :test
|
||||
|
||||
gem "pdf-reader", "~> 2.16"
|
||||
@@ -1,6 +1,7 @@
|
||||
GEM
|
||||
remote: https://rubygems.org/
|
||||
specs:
|
||||
Ascii85 (2.0.1)
|
||||
action_text-trix (2.1.19)
|
||||
railties
|
||||
actioncable (8.1.4.1)
|
||||
@@ -77,6 +78,7 @@ GEM
|
||||
uri (>= 0.13.1)
|
||||
addressable (2.9.2)
|
||||
public_suffix (>= 2.0.2, < 8.0)
|
||||
afm (1.0.1)
|
||||
ast (2.4.3)
|
||||
base64 (0.3.0)
|
||||
bcrypt (3.1.22)
|
||||
@@ -129,6 +131,7 @@ GEM
|
||||
globalid (1.4.0)
|
||||
activesupport (>= 6.1)
|
||||
hashdiff (1.2.1)
|
||||
hashery (2.1.2)
|
||||
htmlentities (4.4.2)
|
||||
i18n (1.15.2)
|
||||
concurrent-ruby (~> 1.0)
|
||||
@@ -210,6 +213,11 @@ GEM
|
||||
parser (3.3.13.0)
|
||||
ast (~> 2.4.1)
|
||||
racc
|
||||
pdf-reader (2.16.0)
|
||||
Ascii85 (>= 1.0, < 3.0, != 2.0.0)
|
||||
afm (>= 0.2.1, < 2)
|
||||
hashery (~> 2.0)
|
||||
ttfunk
|
||||
pp (0.6.4)
|
||||
prettyprint
|
||||
prettyprint (0.2.1)
|
||||
@@ -367,6 +375,7 @@ GEM
|
||||
thruster (0.1.27-x86_64-linux)
|
||||
timeout (0.6.1)
|
||||
tsort (0.2.0)
|
||||
ttfunk (1.7.0)
|
||||
turbo-rails (2.0.23)
|
||||
actionpack (>= 7.1.0)
|
||||
railties (>= 7.1.0)
|
||||
@@ -417,6 +426,7 @@ DEPENDENCIES
|
||||
importmap-rails
|
||||
json (~> 2.10)
|
||||
kamal
|
||||
pdf-reader (~> 2.16)
|
||||
propshaft
|
||||
puma (>= 5.0)
|
||||
rails (~> 8.1.0)
|
||||
@@ -436,6 +446,7 @@ DEPENDENCIES
|
||||
webmock (~> 3.34)
|
||||
|
||||
CHECKSUMS
|
||||
Ascii85 (2.0.1) sha256=15cb5d941808543cbb9e7e6aea3c8ec3877f154c3461e8b3673e97f7ecedbe5a
|
||||
action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009
|
||||
actioncable (8.1.4.1) sha256=007670f7297973e94809e9f32a56624a7aa60b6e9d6696cd078064ce86d1c7fc
|
||||
actionmailbox (8.1.4.1) sha256=18b43dd842bf3a3e31b8e38b7917c21e48c128fc8b263c893481cc66ee1a8f78
|
||||
@@ -449,6 +460,7 @@ CHECKSUMS
|
||||
activestorage (8.1.4.1) sha256=0f4e2f114f3584723a80a2c089aacc6170e765a0b2c385c9782e26ed78f05c66
|
||||
activesupport (8.1.4.1) sha256=16ac4f341ca65c85a1fcdb8ac73f68891aae9e3c4a6f9c3a27daed8b00017ed7
|
||||
addressable (2.9.2) sha256=9117c7e7d6ee07230e75ce41fb9401ae55354dc654fcd0e862ba41d539e9a610
|
||||
afm (1.0.1) sha256=4fc98c6ea9cad60c25ae12bad517513b0d6fdbedc099e25be88bf47977b7d879
|
||||
ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383
|
||||
base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
|
||||
bcrypt (3.1.22) sha256=1f0072e88c2d705d94aff7f2c5cb02eb3f1ec4b8368671e19112527489f29032
|
||||
@@ -479,6 +491,7 @@ CHECKSUMS
|
||||
fugit (1.14.0) sha256=e311a9cc85a54bb67649df45060e721282a1e2c8ebad40e41874a3a7d576f37e
|
||||
globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427
|
||||
hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1
|
||||
hashery (2.1.2) sha256=d239cc2310401903f6b79d458c2bbef5bf74c46f3f974ae9c1061fb74a404862
|
||||
htmlentities (4.4.2) sha256=bbafbdf69f2eca9262be4efef7e43e6a1de54c95eb600f26984f71d2fe96c5c3
|
||||
i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5
|
||||
importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a
|
||||
@@ -515,6 +528,7 @@ CHECKSUMS
|
||||
ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912
|
||||
parallel (1.28.0) sha256=33e6de1484baf2524792d178b0913fc8eb94c628d6cfe45599ad4458c638c970
|
||||
parser (3.3.13.0) sha256=e02f9b63c2fe05b0c68f692ba4df89b3cb113b663964f75d988fbebfd6c3deca
|
||||
pdf-reader (2.16.0) sha256=bf1b5564c085264d8279bde3cf1467778b75841494d20c0fe7da3dad475f3732
|
||||
pp (0.6.4) sha256=dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570
|
||||
prettyprint (0.2.1) sha256=d555d57ea6d7cf001d4774b693546a6bd88bec1e778ddffb5c60b68ceec4b7d4
|
||||
prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85
|
||||
@@ -577,6 +591,7 @@ CHECKSUMS
|
||||
thruster (0.1.27-x86_64-linux) sha256=7e0e6381011401810b047ff25506e0e38755b2430499ff5586f1a110086981c6
|
||||
timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb
|
||||
tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f
|
||||
ttfunk (1.7.0) sha256=2370ba484b1891c70bdcafd3448cfd82a32dd794802d81d720a64c15d3ef2a96
|
||||
turbo-rails (2.0.23) sha256=ee0d90733aafff056cf51ff11e803d65e43cae258cc55f6492020ec1f9f9315f
|
||||
tzinfo (2.0.6) sha256=8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829b
|
||||
unicode-display_width (3.3.0) sha256=4b7aa66a4b11db50f6f7e98411215cd0dd10eaecb665d36eec5bcacb3fa0b613
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
class OilAnalysesController < ApplicationController
|
||||
include AircraftScoped
|
||||
before_action :require_owner!, only: %i[edit update destroy]
|
||||
before_action :set_analysis, only: %i[show edit update destroy]
|
||||
|
||||
COMPARE_SAMPLES = 6 # columns in the trend table, like the lab report's history
|
||||
|
||||
def index
|
||||
@analyses = @aircraft.oil_analyses.recent_first.includes(:component).with_attached_report
|
||||
end
|
||||
|
||||
def show
|
||||
@previous = @aircraft.oil_analyses.where(component_id: @analysis.component_id)
|
||||
.where("sample_date < ?", @analysis.sample_date).recent_first.first
|
||||
end
|
||||
|
||||
def new
|
||||
engine = default_engine
|
||||
@analysis = @aircraft.oil_analyses.new(sample_date: Date.current, component: engine,
|
||||
engine_hours: engine&.hours_since_overhaul,
|
||||
lab: @aircraft.oil_analyses.recent_first.pick(:lab))
|
||||
end
|
||||
|
||||
def create
|
||||
@analysis = @aircraft.oil_analyses.new(analysis_params)
|
||||
if @analysis.save
|
||||
log_event("oil_analysis", "Oil analysis added (sampled #{@analysis.sample_date})")
|
||||
redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: "Oil analysis saved."
|
||||
else
|
||||
render :new, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
# Create records from a lab report PDF. AvLab reports include the two previous
|
||||
# samples too, so samples already on file are skipped rather than duplicated.
|
||||
def import
|
||||
file = params[:report]
|
||||
return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: "Choose a lab report PDF.") if file.blank?
|
||||
|
||||
report = OilReportParser.from_pdf(file.tempfile)
|
||||
file.rewind
|
||||
if report.tail_number.present? && normalize_tail(report.tail_number) != normalize_tail(@aircraft.tail_number)
|
||||
return redirect_to(new_aircraft_oil_analysis_path(@aircraft),
|
||||
alert: "That report is for #{report.tail_number}, not #{@aircraft.tail_number}.")
|
||||
end
|
||||
|
||||
engine = engine_for(report)
|
||||
created = []
|
||||
current_record = nil
|
||||
OilAnalysis.transaction do
|
||||
report.samples.each do |sample|
|
||||
record = existing_sample(sample) ||
|
||||
@aircraft.oil_analyses.create!(sample.except(:current).merge(lab: report.lab, component: engine)).tap { created << _1 }
|
||||
current_record = record if sample[:current]
|
||||
end
|
||||
end
|
||||
current_record.report.attach(file) if current_record && !current_record.report.attached?
|
||||
|
||||
skipped = report.samples.size - created.size
|
||||
created.each { log_event("oil_analysis", "Oil analysis imported (sampled #{_1.sample_date})") }
|
||||
notice = "Imported #{helpers.pluralize(created.size, 'sample')} from the #{report.lab} report."
|
||||
notice += " #{helpers.pluralize(skipped, 'sample was', plural: 'samples were')} already recorded." if skipped.positive?
|
||||
redirect_to aircraft_oil_analyses_path(@aircraft), notice: notice
|
||||
rescue OilReportParser::Error => e
|
||||
redirect_to new_aircraft_oil_analysis_path(@aircraft), alert: "Couldn't import that report: #{e.message}"
|
||||
end
|
||||
|
||||
def edit; end
|
||||
|
||||
def update
|
||||
if @analysis.update(analysis_params)
|
||||
log_event("oil_analysis", "Oil analysis updated (sampled #{@analysis.sample_date})")
|
||||
redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: "Oil analysis updated."
|
||||
else
|
||||
render :edit, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
|
||||
def destroy
|
||||
@analysis.destroy!
|
||||
log_event("oil_analysis", "Oil analysis deleted (sampled #{@analysis.sample_date})")
|
||||
redirect_to aircraft_oil_analyses_path(@aircraft), notice: "Oil analysis deleted."
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def set_analysis = @analysis = @aircraft.oil_analyses.find(params[:id])
|
||||
|
||||
def normalize_tail(tail) = tail.to_s.upcase.delete("^A-Z0-9")
|
||||
|
||||
# Same sample date, and the same lab sample number unless one side has none.
|
||||
def existing_sample(sample)
|
||||
scope = @aircraft.oil_analyses.where(sample_date: sample[:sample_date])
|
||||
scope = scope.where(sample_number: [ sample[:sample_number], nil ]) if sample[:sample_number]
|
||||
scope.first
|
||||
end
|
||||
|
||||
# The engine whose serial number is on the report, else the one in service.
|
||||
def engine_for(report)
|
||||
serial = report.engine_serial.to_s.strip.upcase
|
||||
match = @aircraft.components.where.not(serial_number: [ nil, "" ]).find { _1.serial_number.strip.upcase == serial } if serial.present?
|
||||
match || default_engine
|
||||
end
|
||||
|
||||
def default_engine
|
||||
@aircraft.components.joins(:component_type).where(status: "IN-USE", component_types: { name: "Engine" }).first
|
||||
end
|
||||
|
||||
def analysis_params
|
||||
params.require(:oil_analysis).permit(
|
||||
:component_id, :sample_date, :analysis_date, :lab, :sample_number, :engine_hours, :oil_hours,
|
||||
:filter_hours, :oil_added, :status, :lab_comments, :notes, :report,
|
||||
*OilAnalysis::ELEMENTS.keys.flat_map { [ _1, :"#{_1}_avg" ] }
|
||||
).tap { |p| p[:component_id] = scoped_id(@aircraft.components, p[:component_id]) if p.key?(:component_id) }
|
||||
end
|
||||
end
|
||||
@@ -7,6 +7,7 @@ module AircraftHelper
|
||||
[ "Squawks", aircraft_squawks_path(aircraft), %w[squawks] ],
|
||||
[ "Flights", aircraft_flight_logs_path(aircraft), %w[flight_logs flight_imports air_trail_exports airport_codes] ],
|
||||
[ "Oil & Fuel", aircraft_consumable_records_path(aircraft), %w[consumable_records] ],
|
||||
[ "Oil Analysis", aircraft_oil_analyses_path(aircraft), %w[oil_analyses] ],
|
||||
[ "Logbook", aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ],
|
||||
[ "Inspections", aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ],
|
||||
[ "ADs", aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances ad_imports] ],
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
module OilAnalysesHelper
|
||||
STATUS_BADGES = { "normal" => "badge-green", "elevated" => "badge-orange", "high" => "badge-red" }.freeze
|
||||
TREND_COLORS = %w[#0ea5e9 #f97316 #22c55e #a855f7 #eab308 #ec4899 #64748b].freeze
|
||||
|
||||
def oil_status_badge(analysis)
|
||||
tag.span OilAnalysis::STATUSES[analysis.status], class: STATUS_BADGES[analysis.status]
|
||||
end
|
||||
|
||||
def ppm(value)
|
||||
value.nil? ? "—" : number_with_precision(value, precision: 1, strip_insignificant_zeros: true)
|
||||
end
|
||||
|
||||
# One cell: reading, lab average beneath, highlighted when well above the average.
|
||||
def ppm_cell(analysis, element)
|
||||
value = analysis.value(element)
|
||||
flagged = analysis.flagged?(element)
|
||||
content = tag.span(ppm(value), class: [ "tabular-nums", ("font-semibold text-red-700" if flagged) ],
|
||||
title: ("Over #{OilAnalysis::FLAG_RATIO}× the lab average" if flagged))
|
||||
avg = analysis.average(element)
|
||||
avg ? safe_join([ content, tag.div("(#{ppm(avg)})", class: "text-xs text-slate-500 tabular-nums") ]) : content
|
||||
end
|
||||
|
||||
# Change in ppm from the previous sample ("+3.2"), blank without one.
|
||||
def ppm_change(analysis, previous, element)
|
||||
return "" unless previous && (now = analysis.value(element)) && (before = previous.value(element))
|
||||
delta = now - before
|
||||
sign = delta.positive? ? "+" : ""
|
||||
"#{sign}#{ppm(delta)}"
|
||||
end
|
||||
|
||||
def oil_trend_series(analyses)
|
||||
chronological = analyses.sort_by(&:sample_date)
|
||||
OilAnalysis::TREND_ELEMENTS.filter_map do |el|
|
||||
data = chronological.filter_map { |a| [ a.sample_date, a.value(el).to_f ] if a.value(el) }
|
||||
{ name: OilAnalysis.element_label(el), data: data } if data.size >= 2
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -23,6 +23,7 @@ class Aircraft < ApplicationRecord
|
||||
has_many :major_records, dependent: :destroy
|
||||
has_many :flight_logs, dependent: :destroy
|
||||
has_many :consumable_records, dependent: :destroy
|
||||
has_many :oil_analyses, dependent: :destroy
|
||||
has_and_belongs_to_many :inspection_types
|
||||
has_and_belongs_to_many :airworthiness_directives
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ class AircraftEvent < ApplicationRecord
|
||||
"squawk" => "Squawk", "note" => "Note", "oil" => "Oil", "fuel" => "Fuel",
|
||||
"logbook" => "Logbook", "ad" => "Airworthiness Directive", "inspection" => "Inspection",
|
||||
"document" => "Document", "aircraft" => "Aircraft", "role" => "Role",
|
||||
"major_record" => "Major Repair/Alteration"
|
||||
"major_record" => "Major Repair/Alteration", "oil_analysis" => "Oil Analysis"
|
||||
}.freeze
|
||||
|
||||
belongs_to :aircraft
|
||||
|
||||
@@ -6,6 +6,7 @@ class Component < ApplicationRecord
|
||||
belongs_to :component_type
|
||||
has_many :child_components, class_name: "Component", foreign_key: :parent_component_id, dependent: :destroy
|
||||
has_many :squawks, dependent: :nullify
|
||||
has_many :oil_analyses, dependent: :nullify
|
||||
has_and_belongs_to_many :inspection_types
|
||||
has_and_belongs_to_many :airworthiness_directives
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# A spectrographic oil analysis lab report for one oil sample.
|
||||
class OilAnalysis < ApplicationRecord
|
||||
include UploadValidation
|
||||
|
||||
# Element → [label, what it usually indicates].
|
||||
ELEMENTS = {
|
||||
"iron" => [ "Iron", "Cylinders, cam, lifters, gears" ],
|
||||
"copper" => [ "Copper", "Bearings, bushings, oil cooler" ],
|
||||
"nickel" => [ "Nickel", "Valve guides, cylinder plating" ],
|
||||
"chromium" => [ "Chromium", "Rings, chromed cylinders" ],
|
||||
"silver" => [ "Silver", "Bearing plating" ],
|
||||
"magnesium" => [ "Magnesium", "Accessory case, additive" ],
|
||||
"aluminum" => [ "Aluminum", "Pistons, case" ],
|
||||
"lead" => [ "Lead", "Fuel (100LL) blow-by" ],
|
||||
"silicon" => [ "Silicon", "Dirt (air filter), sealant" ],
|
||||
"titanium" => [ "Titanium", "Hardened parts" ],
|
||||
"tin" => [ "Tin", "Bearings, piston pin bushings" ],
|
||||
"molybdenum" => [ "Moly", "Rings, additive" ]
|
||||
}.freeze
|
||||
STATUSES = { "normal" => "Normal", "elevated" => "Elevated", "high" => "High" }.freeze
|
||||
# A reading this far above the lab's average for similar engines gets flagged.
|
||||
FLAG_RATIO = 1.5
|
||||
# Wear metals worth charting together (lead is on its own scale: it comes from fuel).
|
||||
TREND_ELEMENTS = %w[iron copper nickel chromium aluminum silicon tin].freeze
|
||||
|
||||
belongs_to :aircraft
|
||||
belongs_to :component, optional: true
|
||||
has_one_attached :report
|
||||
|
||||
validates :sample_date, presence: true
|
||||
validates :status, inclusion: { in: STATUSES.keys }
|
||||
validates(*ELEMENTS.keys.flat_map { [ _1, :"#{_1}_avg" ] }, :engine_hours, :oil_hours, :filter_hours, :oil_added,
|
||||
numericality: { greater_than_or_equal_to: 0 }, allow_nil: true)
|
||||
validate :component_belongs_to_aircraft
|
||||
validates_uploads :report
|
||||
|
||||
normalizes :lab, :sample_number, with: ->(v) { v.strip.presence }
|
||||
|
||||
scope :recent_first, -> { order(sample_date: :desc, created_at: :desc) }
|
||||
|
||||
def self.element_label(el) = ELEMENTS.fetch(el)[0]
|
||||
|
||||
def value(el) = self[el]
|
||||
def average(el) = self[:"#{el}_avg"]
|
||||
|
||||
# Above the lab average by FLAG_RATIO (needs an average to compare against).
|
||||
def flagged?(el)
|
||||
v, avg = value(el), average(el)
|
||||
v && avg&.positive? && v >= avg * FLAG_RATIO
|
||||
end
|
||||
|
||||
def flagged_elements = ELEMENTS.keys.select { flagged?(_1) }
|
||||
def any_results? = ELEMENTS.keys.any? { value(_1) }
|
||||
|
||||
private
|
||||
|
||||
def component_belongs_to_aircraft
|
||||
errors.add(:component, "must be on this aircraft") if component && component.aircraft_id != aircraft_id
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,207 @@
|
||||
require "pdf-reader"
|
||||
|
||||
# Reads an AvLab (Aviation Laboratories) oil analysis report PDF. A report
|
||||
# holds the current sample plus up to two previous ones, each with its dates,
|
||||
# hours, lab verdict, comments and a ppm table (value, lab average beneath).
|
||||
#
|
||||
# The PDF's text layer is messy: it hides the cell color codes ("#00CC00") as
|
||||
# larger text on top of the results. So this works from positioned characters,
|
||||
# drops the color-code layer by font size, rebuilds words and lines, and maps
|
||||
# each result to its element column by x position.
|
||||
class OilReportParser
|
||||
class Error < StandardError; end
|
||||
|
||||
LAB = "AvLab".freeze
|
||||
COLOR_CODE_FONT_SIZE = 8.5 # the hidden color codes are 9pt; real text is 7–8pt
|
||||
COLUMNS = {
|
||||
"Iron" => "iron", "Copper" => "copper", "Nickel" => "nickel", "Chromium" => "chromium",
|
||||
"Silver" => "silver", "Magnesium" => "magnesium", "Aluminum" => "aluminum", "Lead" => "lead",
|
||||
"Silicon" => "silicon", "Titanium" => "titanium", "Tin" => "tin", "Moly." => "molybdenum"
|
||||
}.freeze
|
||||
LABELS = {
|
||||
"Sample Date:" => :sample_date, "Analysis Date:" => :analysis_date, "Sample Number:" => :sample_number,
|
||||
"TSN/TSO:" => :engine_hours, "Oil Hours:" => :oil_hours, "Filter Hours:" => :filter_hours,
|
||||
"Oil Added:" => :oil_added
|
||||
}.freeze
|
||||
LABEL_MAX_X = 108 # left-hand labels end before here…
|
||||
VALUE_X = 105..160 # …and their values sit in this column
|
||||
|
||||
Char = Struct.new(:text, :x, :endx, :y, :page)
|
||||
Word = Struct.new(:text, :x, :endx, :y, :page) do
|
||||
def center = (x + endx) / 2.0
|
||||
end
|
||||
Line = Struct.new(:y, :page, :words) do
|
||||
def text = words.map(&:text).join(" ")
|
||||
end
|
||||
Report = Struct.new(:lab, :tail_number, :engine_serial, :engine_model, :samples, keyword_init: true)
|
||||
|
||||
def self.from_pdf(io)
|
||||
reader = PDF::Reader.new(io)
|
||||
chars = reader.pages.each_with_index.flat_map do |page, index|
|
||||
receiver = PDF::Reader::PageTextReceiver.new
|
||||
page.walk(receiver)
|
||||
# Keep overlapping glyphs: a real "0" under a hidden one would otherwise be dropped.
|
||||
receiver.runs(merge: false, skip_overlapping: false).filter_map do |run|
|
||||
next if run.font_size >= COLOR_CODE_FONT_SIZE || run.text.strip.empty?
|
||||
Char.new(run.text, run.x, run.endx, run.y, index)
|
||||
end
|
||||
end
|
||||
new(chars).parse
|
||||
rescue PDF::Reader::MalformedPDFError, PDF::Reader::UnsupportedFeatureError => e
|
||||
raise Error, "Couldn't read the PDF (#{e.message})"
|
||||
end
|
||||
|
||||
def initialize(chars)
|
||||
@lines = build_lines(chars)
|
||||
end
|
||||
|
||||
def parse
|
||||
unless @lines.any? { _1.text.include?("OIL ANALYSIS RESULTS IN PARTS PER MILLION") }
|
||||
raise Error, "Not an AvLab oil analysis report"
|
||||
end
|
||||
samples = sample_blocks.map { parse_sample(_1) }.select { _1[:sample_date] }
|
||||
raise Error, "No samples found in the report" 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)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
# Characters → lines (same baseline ±1pt) → words (glyphs closer than a space).
|
||||
def build_lines(chars)
|
||||
lines = []
|
||||
chars.sort_by { [ _1.page, -_1.y ] }.each do |c|
|
||||
line = lines.reverse_each.find { _1.page == c.page && (_1.y - c.y).abs <= 1.0 }
|
||||
line ? line.words << c : lines << Line.new(c.y, c.page, [ c ])
|
||||
end
|
||||
lines.each do |line|
|
||||
line.words = line.words.sort_by(&:x).each_with_object([]) do |c, words|
|
||||
last = words.last
|
||||
if last && c.x - last.endx <= 1.6
|
||||
last.text += c.text
|
||||
last.endx = c.endx
|
||||
else
|
||||
words << Word.new(c.text.dup, c.x, c.endx, c.y, c.page)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def header_lines
|
||||
first = @lines.find { _1.words.first&.text.in?(%w[CURRENT PREVIOUS]) }
|
||||
first ? @lines.take_while { _1 != first } : @lines
|
||||
end
|
||||
|
||||
# The word(s) following a label on the same line, e.g. "Tail No.:" → "N12345".
|
||||
def after(label, words: 1)
|
||||
parts = label.split
|
||||
header_lines.each do |line|
|
||||
texts = line.words.map(&:text)
|
||||
texts.each_cons(parts.size).with_index do |window, i|
|
||||
next unless window == parts
|
||||
found = texts[i + parts.size, words]&.take_while { !_1.end_with?(":") }
|
||||
return found.join(" ").presence if found&.any?
|
||||
end
|
||||
end
|
||||
nil
|
||||
end
|
||||
|
||||
# Lines from each "CURRENT SAMPLE" / "PREVIOUS SAMPLE n" heading to the next.
|
||||
def sample_blocks
|
||||
starts = @lines.each_index.select { |i| @lines[i].words.first&.text.in?(%w[CURRENT PREVIOUS]) && @lines[i].words[1]&.text == "SAMPLE" }
|
||||
starts.each_with_index.map { |s, n| @lines[s...(starts[n + 1] || @lines.size)] }
|
||||
end
|
||||
|
||||
def parse_sample(block)
|
||||
heading = block.first
|
||||
verdict = heading.words.select { _1.x > 140 && _1.x < 470 }.map(&:text).join(" ")
|
||||
fields = labeled_values(block)
|
||||
comments = block.find { _1.words.first&.text == "Comments:" }&.words&.drop(1)&.map(&:text)&.join(" ")
|
||||
|
||||
{
|
||||
current: heading.words.first.text == "CURRENT",
|
||||
sample_date: date(fields[:sample_date]),
|
||||
analysis_date: date(fields[:analysis_date]),
|
||||
sample_number: fields[:sample_number],
|
||||
engine_hours: number(fields[:engine_hours]),
|
||||
oil_hours: number(fields[:oil_hours]),
|
||||
filter_hours: number(fields[:filter_hours]),
|
||||
oil_added: number(fields[:oil_added]),
|
||||
status: status(verdict),
|
||||
lab_comments: [ (verdict unless status(verdict) == "normal"), comments ].compact_blank.join("\n").presence
|
||||
}.merge(results(block))
|
||||
end
|
||||
|
||||
# Left-hand "Label:" lines and the values beside them. A value isn't always on
|
||||
# the label's baseline, so each value goes to the nearest label above or below.
|
||||
def labeled_values(block)
|
||||
labels = block.filter_map do |line|
|
||||
text = line.words.select { _1.x < LABEL_MAX_X - 20 || (_1.x < LABEL_MAX_X && _1.text.end_with?(":")) }.map(&:text).join(" ")
|
||||
[ LABELS[text], line.y ] if LABELS[text]
|
||||
end
|
||||
values = block.drop(1).flat_map { |line| line.words.select { VALUE_X.cover?(_1.x) } } # skip the heading
|
||||
values.each_with_object({}) do |word, found|
|
||||
key, = labels.min_by { (_2 - word.y).abs }
|
||||
found[key] ||= word.text if key
|
||||
end
|
||||
end
|
||||
|
||||
# The ppm row under the element headings, and the (average) row under that.
|
||||
def results(block)
|
||||
header = block.find { |line| COLUMNS.keys.count { line.words.map(&:text).include?(_1) } >= 6 } or return {}
|
||||
columns = header.words.filter_map { |w| [ COLUMNS[w.text], w.center ] if COLUMNS[w.text] }
|
||||
below = block.select { _1.y < header.y && _1.y > header.y - 25 }
|
||||
|
||||
below.each_with_object({}) do |line, out|
|
||||
# Results start right of the label column ("Cylinder Type: steel" shares these lines).
|
||||
merge_less_than(line.words.select { _1.x >= VALUE_X.end }).each do |word|
|
||||
element, = columns.min_by { (_2 - word.center).abs }
|
||||
if word.text.start_with?("(")
|
||||
out[:"#{element}_avg"] = ppm(word.text.delete("()"))
|
||||
else
|
||||
out[element.to_sym] = ppm(word.text)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# "<" and "0.1" are drawn as separate words.
|
||||
def merge_less_than(words)
|
||||
words.each_with_object([]) do |w, out|
|
||||
if out.last&.text == "<"
|
||||
out.last.text = "< #{w.text}"
|
||||
out.last.endx = w.endx
|
||||
else
|
||||
out << w.dup
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# "N/A" → nil; "< 0.1" (below detection) → 0; ".3" → 0.3
|
||||
def ppm(text)
|
||||
return nil if text.blank? || text == "N/A"
|
||||
return 0 if text.start_with?("<")
|
||||
number(text)
|
||||
end
|
||||
|
||||
def number(text)
|
||||
BigDecimal(text.to_s.strip.sub(/\A\./, "0."))
|
||||
rescue ArgumentError, TypeError
|
||||
nil
|
||||
end
|
||||
|
||||
def date(text)
|
||||
Date.strptime(text, "%m/%d/%Y") if text
|
||||
rescue Date::Error
|
||||
nil
|
||||
end
|
||||
|
||||
def status(verdict)
|
||||
case verdict.upcase
|
||||
when /ABNORMAL|HIGH|CRITICAL|SEVERE|PROBLEM/ then "high"
|
||||
when /APPEARS NORMAL/ then "normal"
|
||||
else "elevated"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,36 @@
|
||||
<%= form_with model: [aircraft, analysis], class: "card card-body space-y-5 max-w-4xl" do |f| %>
|
||||
<%= f.errors_summary %>
|
||||
<div class="grid gap-4 sm:grid-cols-3">
|
||||
<%= f.field :sample_date, as: :date, required: true %>
|
||||
<%= f.field :analysis_date, as: :date %>
|
||||
<%= f.field :status, as: :select, label: "Lab's verdict", collection: OilAnalysis::STATUSES.invert %>
|
||||
<%= f.field :component_id, as: :select, label: "Engine", collection: component_options(aircraft) %>
|
||||
<%= f.field :lab, placeholder: "AvLab, Blackstone…" %>
|
||||
<%= f.field :sample_number, label: "Sample #" %>
|
||||
</div>
|
||||
<fieldset class="grid gap-4 sm:grid-cols-4">
|
||||
<legend class="mb-2 text-sm font-semibold">Hours</legend>
|
||||
<%= f.field :engine_hours, as: :number, step: 0.1, label: "Engine (TSN/TSO)" %>
|
||||
<%= f.field :oil_hours, as: :number, step: 0.1, label: "On oil" %>
|
||||
<%= f.field :filter_hours, as: :number, step: 0.1, label: "On filter" %>
|
||||
<%= f.field :oil_added, as: :number, step: 0.25, label: "Oil added (qt)" %>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend class="mb-2 text-sm font-semibold">Results (ppm)</legend>
|
||||
<p class="hint mb-3">Leave blank what the lab didn't test (N/A). Enter "< 0.1" as 0. The average is the lab's figure for similar engines, usually in (parentheses) under the result.</p>
|
||||
<div class="grid gap-x-4 gap-y-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<% OilAnalysis::ELEMENTS.each do |el, (label, _)| %>
|
||||
<div class="grid grid-cols-[6rem_1fr_1fr] items-center gap-2">
|
||||
<%= f.label el, label, class: "text-sm font-medium text-slate-700" %>
|
||||
<%= f.number_field el, step: 0.1, min: 0, class: "input", placeholder: "Result" %>
|
||||
<%= f.number_field :"#{el}_avg", step: 0.1, min: 0, class: "input", placeholder: "Avg", "aria-label": "#{label} lab average" %>
|
||||
</div>
|
||||
<% end %>
|
||||
</div>
|
||||
</fieldset>
|
||||
<%= f.field :lab_comments, as: :textarea, rows: 2 %>
|
||||
<%= f.field :notes, as: :textarea, rows: 2 %>
|
||||
<%= f.field :report, as: :file, label: "Lab report (PDF)", accept: ".pdf,application/pdf,image/*" %>
|
||||
<% if analysis.report.attached? %><p class="hint">Current: <%= analysis.report.filename %>. Choosing a file replaces it.</p><% end %>
|
||||
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", analysis.persisted? ? aircraft_oil_analysis_path(aircraft, analysis) : aircraft_oil_analyses_path(aircraft), class: "btn-secondary" %></div>
|
||||
<% end %>
|
||||
@@ -0,0 +1,6 @@
|
||||
<%# Upload a lab report PDF to create the sample records. Locals: aircraft %>
|
||||
<%= form_with url: import_aircraft_oil_analyses_path(aircraft), multipart: true, class: "flex flex-wrap items-center gap-2" do |f| %>
|
||||
<%= f.file_field :report, accept: ".pdf,application/pdf", required: true, "aria-label": "Lab report PDF",
|
||||
class: "block text-sm text-slate-600 file:mr-3 file:rounded-md file:border-0 file:bg-slate-100 file:px-3 file:py-1.5 file:text-sm file:font-medium hover:file:bg-slate-200" %>
|
||||
<%= f.submit "Import report", class: "btn-secondary btn-sm" %>
|
||||
<% end %>
|
||||
@@ -0,0 +1,3 @@
|
||||
<% content_for :title, "Edit Oil Analysis" %>
|
||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||
<%= render "form", aircraft: @aircraft, analysis: @analysis %>
|
||||
@@ -0,0 +1,81 @@
|
||||
<% content_for :title, "#{@aircraft.tail_number} Oil Analysis" %>
|
||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||
<% recent = @analyses.first(OilAnalysesController::COMPARE_SAMPLES) %>
|
||||
<div class="space-y-5">
|
||||
<section class="card">
|
||||
<div class="card-header">
|
||||
<div>
|
||||
<h2 class="card-title">Import a lab report</h2>
|
||||
<p class="hint">AvLab PDF reports: each sample on the report (including previous ones) is added unless it's already here.</p>
|
||||
</div>
|
||||
<%= render "import", aircraft: @aircraft %>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title">Wear metal trends</h2>
|
||||
<%= link_to "+ Add Oil Analysis", new_aircraft_oil_analysis_path(@aircraft), class: "btn-secondary btn-sm" %>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<% series = oil_trend_series(@analyses) %>
|
||||
<% if series.any? %>
|
||||
<%= line_chart series, ytitle: "ppm", height: "260px", curve: false, colors: OilAnalysesHelper::TREND_COLORS, legend: "bottom" %>
|
||||
<p class="hint">Lead is left out of the chart: it comes from 100LL fuel and reads in the thousands. Look for a steady trend rather than a single reading.</p>
|
||||
<% else %>
|
||||
<%= empty_state @analyses.any? ? "Add another sample to see trends." : "No oil analyses yet. Add one from your lab report." %>
|
||||
<% end %>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<% if recent.any?(&:any_results?) %>
|
||||
<section class="card">
|
||||
<div class="card-header"><h2 class="card-title">Results (ppm)</h2>
|
||||
<span class="text-xs text-slate-500">Lab average for similar engines in (parentheses); <span class="font-semibold text-red-700">red</span> is <%= OilAnalysis::FLAG_RATIO %>× or more above it.</span></div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead>
|
||||
<tr><th>Element</th>
|
||||
<% recent.each do |a| %><th class="text-right whitespace-nowrap"><%= link_to fmt_date(a.sample_date), aircraft_oil_analysis_path(@aircraft, a), class: "link" %></th><% end %></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr class="text-xs text-slate-500"><td>Engine / oil hrs</td>
|
||||
<% recent.each do |a| %><td class="text-right tabular-nums"><%= a.engine_hours ? hours(a.engine_hours) : "—" %> / <%= a.oil_hours ? hours(a.oil_hours) : "—" %></td><% end %></tr>
|
||||
<% OilAnalysis::ELEMENTS.each do |el, (label, source)| %>
|
||||
<% next if recent.none? { _1.value(el) } %>
|
||||
<tr><td><span title="<%= source %>"><%= label %></span></td>
|
||||
<% recent.each do |a| %><td class="text-right align-top"><%= ppm_cell(a, el) %></td><% end %></tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
<% end %>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-header"><h2 class="card-title">Samples</h2></div>
|
||||
<% if @analyses.any? %>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Sampled</th><th>Result</th><th>Engine</th><th class="text-right">Engine hrs</th><th class="text-right">Oil hrs</th><th>Lab</th><th>Report</th></tr></thead>
|
||||
<tbody>
|
||||
<% @analyses.each do |a| %>
|
||||
<tr>
|
||||
<td class="whitespace-nowrap"><%= link_to fmt_date(a.sample_date), aircraft_oil_analysis_path(@aircraft, a), class: "link" %></td>
|
||||
<td class="whitespace-nowrap"><%= oil_status_badge(a) %>
|
||||
<% if (flags = a.flagged_elements).any? %><span class="ml-1 text-xs text-red-700"><%= flags.map { OilAnalysis.element_label(_1) }.to_sentence %> above average</span><% end %></td>
|
||||
<td><%= a.component&.to_s || "—" %></td>
|
||||
<td class="text-right tabular-nums"><%= a.engine_hours ? hours(a.engine_hours) : "—" %></td>
|
||||
<td class="text-right tabular-nums"><%= a.oil_hours ? hours(a.oil_hours) : "—" %></td>
|
||||
<td><%= [ a.lab, a.sample_number ].compact.join(" · ").presence || "—" %></td>
|
||||
<td><%= a.report.attached? ? link_to("PDF", rails_blob_path(a.report, disposition: :inline), class: "link", target: "_blank", rel: "noopener") : "—" %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= empty_state "No samples recorded." %>
|
||||
<% end %>
|
||||
</section>
|
||||
</div>
|
||||
@@ -0,0 +1,8 @@
|
||||
<% content_for :title, "Add Oil Analysis" %>
|
||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||
<section class="card card-body mb-5 max-w-4xl">
|
||||
<h2 class="mb-1 text-sm font-semibold">Have an AvLab PDF? Import it instead</h2>
|
||||
<p class="hint mb-3">Every sample on the report is filled in for you, and the PDF is attached to the newest one.</p>
|
||||
<%= render "import", aircraft: @aircraft %>
|
||||
</section>
|
||||
<%= render "form", aircraft: @aircraft, analysis: @analysis %>
|
||||
@@ -0,0 +1,62 @@
|
||||
<% content_for :title, "Oil Analysis #{fmt_date(@analysis.sample_date)}" %>
|
||||
<%= render "shared/aircraft_header", aircraft: @aircraft %>
|
||||
<div class="grid gap-5 lg:grid-cols-3">
|
||||
<section class="card lg:col-span-1">
|
||||
<div class="card-header">
|
||||
<h2 class="card-title">Sample <%= fmt_date(@analysis.sample_date) %></h2>
|
||||
<%= oil_status_badge(@analysis) %>
|
||||
</div>
|
||||
<dl class="card-body grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
|
||||
<dt class="text-slate-500">Engine</dt><dd><%= @analysis.component ? link_to(@analysis.component, aircraft_component_path(@aircraft, @analysis.component), class: "link") : "—" %></dd>
|
||||
<dt class="text-slate-500">Engine hrs (TSN/TSO)</dt><dd><%= @analysis.engine_hours ? hours(@analysis.engine_hours) : "—" %></dd>
|
||||
<dt class="text-slate-500">Oil hrs</dt><dd><%= @analysis.oil_hours ? hours(@analysis.oil_hours) : "—" %></dd>
|
||||
<dt class="text-slate-500">Filter hrs</dt><dd><%= @analysis.filter_hours ? hours(@analysis.filter_hours) : "—" %></dd>
|
||||
<dt class="text-slate-500">Oil added</dt><dd><%= @analysis.oil_added ? "#{number_with_precision(@analysis.oil_added, precision: 2, strip_insignificant_zeros: true)} qt" : "—" %></dd>
|
||||
<dt class="text-slate-500">Lab</dt><dd><%= @analysis.lab || "—" %></dd>
|
||||
<dt class="text-slate-500">Sample #</dt><dd><%= @analysis.sample_number || "—" %></dd>
|
||||
<dt class="text-slate-500">Analyzed</dt><dd><%= @analysis.analysis_date ? fmt_date(@analysis.analysis_date) : "—" %></dd>
|
||||
<dt class="text-slate-500">Report</dt><dd><%= @analysis.report.attached? ? link_to(@analysis.report.filename, rails_blob_path(@analysis.report, disposition: :inline), class: "link", target: "_blank", rel: "noopener") : "—" %></dd>
|
||||
</dl>
|
||||
<% if @analysis.lab_comments.present? %>
|
||||
<div class="border-t border-slate-100 px-4 py-3 text-sm"><div class="mb-1 text-xs font-semibold text-slate-500">Lab comments</div><%= simple_format @analysis.lab_comments %></div>
|
||||
<% end %>
|
||||
<% if @analysis.notes.present? %>
|
||||
<div class="border-t border-slate-100 px-4 py-3 text-sm"><div class="mb-1 text-xs font-semibold text-slate-500">Notes</div><%= simple_format @analysis.notes %></div>
|
||||
<% end %>
|
||||
<% if owner? %>
|
||||
<div class="flex gap-2 border-t border-slate-100 px-4 py-3">
|
||||
<%= link_to "Edit", edit_aircraft_oil_analysis_path(@aircraft, @analysis), class: "btn-secondary btn-sm" %>
|
||||
<%= delete_button "Delete", aircraft_oil_analysis_path(@aircraft, @analysis), confirm: "Delete this oil analysis?" %>
|
||||
</div>
|
||||
<% end %>
|
||||
</section>
|
||||
|
||||
<section class="card lg:col-span-2">
|
||||
<div class="card-header"><h2 class="card-title">Results (ppm)</h2>
|
||||
<span class="text-xs text-slate-500"><%= @previous ? "Compared with #{fmt_date(@previous.sample_date)}" : "First sample for this engine" %></span></div>
|
||||
<% if @analysis.any_results? %>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="table">
|
||||
<thead><tr><th>Element</th><th class="text-right">This sample</th><th class="text-right">Lab average</th><% if @previous %><th class="text-right">Previous</th><th class="text-right">Change</th><% end %><th>Usual source</th></tr></thead>
|
||||
<tbody>
|
||||
<% OilAnalysis::ELEMENTS.each do |el, (label, source)| %>
|
||||
<% next unless @analysis.value(el) || @analysis.average(el) %>
|
||||
<tr class="<%= "bg-red-50" if @analysis.flagged?(el) %>">
|
||||
<td><%= label %></td>
|
||||
<td class="text-right tabular-nums <%= "font-semibold text-red-700" if @analysis.flagged?(el) %>"><%= ppm(@analysis.value(el)) %></td>
|
||||
<td class="text-right tabular-nums text-slate-500"><%= ppm(@analysis.average(el)) %></td>
|
||||
<% if @previous %>
|
||||
<td class="text-right tabular-nums"><%= ppm(@previous.value(el)) %></td>
|
||||
<td class="text-right tabular-nums"><%= ppm_change(@analysis, @previous, el) %></td>
|
||||
<% end %>
|
||||
<td class="text-xs text-slate-500"><%= source %></td>
|
||||
</tr>
|
||||
<% end %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<% else %>
|
||||
<%= empty_state "No results entered." %>
|
||||
<% end %>
|
||||
</section>
|
||||
</div>
|
||||
@@ -36,6 +36,9 @@ Rails.application.routes.draw do
|
||||
post :confirm
|
||||
end
|
||||
resources :consumable_records, path: "consumables", except: :show
|
||||
resources :oil_analyses, path: "oil_analysis" do
|
||||
collection { post :import }
|
||||
end
|
||||
resources :logbook_entries
|
||||
resources :documents
|
||||
resources :document_collections, except: %i[index show]
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
class CreateOilAnalyses < ActiveRecord::Migration[8.1]
|
||||
ELEMENTS = %i[iron copper nickel chromium silver magnesium aluminum lead silicon titanium tin molybdenum].freeze
|
||||
|
||||
def change
|
||||
# One lab report (spectrographic oil analysis) per oil sample.
|
||||
create_table :oil_analyses do |t|
|
||||
t.references :aircraft, null: false, foreign_key: true
|
||||
t.references :component, foreign_key: true # the engine sampled
|
||||
t.date :sample_date, null: false
|
||||
t.date :analysis_date
|
||||
t.string :lab
|
||||
t.string :sample_number
|
||||
t.decimal :engine_hours, precision: 8, scale: 1 # TSN/TSO at sampling
|
||||
t.decimal :oil_hours, precision: 6, scale: 1
|
||||
t.decimal :filter_hours, precision: 6, scale: 1
|
||||
t.decimal :oil_added, precision: 6, scale: 2 # quarts added since last change
|
||||
t.string :status, null: false, default: "normal"
|
||||
t.text :lab_comments
|
||||
t.text :notes
|
||||
# Wear metals and contaminants, ppm; *_avg is the lab's average for similar engines.
|
||||
ELEMENTS.each do |el|
|
||||
t.decimal el, precision: 8, scale: 1
|
||||
t.decimal :"#{el}_avg", precision: 8, scale: 1
|
||||
end
|
||||
t.timestamps
|
||||
end
|
||||
add_index :oil_analyses, %i[aircraft_id sample_date]
|
||||
end
|
||||
end
|
||||
Generated
+48
-1
@@ -10,7 +10,7 @@
|
||||
#
|
||||
# It's strongly recommended that you check this file into your version control system.
|
||||
|
||||
ActiveRecord::Schema[8.1].define(version: 2026_11_06_150000) do
|
||||
ActiveRecord::Schema[8.1].define(version: 2026_11_06_160000) do
|
||||
create_table "active_storage_attachments", force: :cascade do |t|
|
||||
t.string "name", null: false
|
||||
t.string "record_type", null: false
|
||||
@@ -423,6 +423,51 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_06_150000) do
|
||||
t.index ["stc_document_id"], name: "index_major_records_on_stc_document_id"
|
||||
end
|
||||
|
||||
create_table "oil_analyses", force: :cascade do |t|
|
||||
t.integer "aircraft_id", null: false
|
||||
t.integer "component_id"
|
||||
t.date "sample_date", null: false
|
||||
t.date "analysis_date"
|
||||
t.string "lab"
|
||||
t.string "sample_number"
|
||||
t.decimal "engine_hours", precision: 8, scale: 1
|
||||
t.decimal "oil_hours", precision: 6, scale: 1
|
||||
t.decimal "filter_hours", precision: 6, scale: 1
|
||||
t.decimal "oil_added", precision: 6, scale: 2
|
||||
t.string "status", default: "normal", null: false
|
||||
t.text "lab_comments"
|
||||
t.text "notes"
|
||||
t.decimal "iron", precision: 8, scale: 1
|
||||
t.decimal "iron_avg", precision: 8, scale: 1
|
||||
t.decimal "copper", precision: 8, scale: 1
|
||||
t.decimal "copper_avg", precision: 8, scale: 1
|
||||
t.decimal "nickel", precision: 8, scale: 1
|
||||
t.decimal "nickel_avg", precision: 8, scale: 1
|
||||
t.decimal "chromium", precision: 8, scale: 1
|
||||
t.decimal "chromium_avg", precision: 8, scale: 1
|
||||
t.decimal "silver", precision: 8, scale: 1
|
||||
t.decimal "silver_avg", precision: 8, scale: 1
|
||||
t.decimal "magnesium", precision: 8, scale: 1
|
||||
t.decimal "magnesium_avg", precision: 8, scale: 1
|
||||
t.decimal "aluminum", precision: 8, scale: 1
|
||||
t.decimal "aluminum_avg", precision: 8, scale: 1
|
||||
t.decimal "lead", precision: 8, scale: 1
|
||||
t.decimal "lead_avg", precision: 8, scale: 1
|
||||
t.decimal "silicon", precision: 8, scale: 1
|
||||
t.decimal "silicon_avg", precision: 8, scale: 1
|
||||
t.decimal "titanium", precision: 8, scale: 1
|
||||
t.decimal "titanium_avg", precision: 8, scale: 1
|
||||
t.decimal "tin", precision: 8, scale: 1
|
||||
t.decimal "tin_avg", precision: 8, scale: 1
|
||||
t.decimal "molybdenum", precision: 8, scale: 1
|
||||
t.decimal "molybdenum_avg", precision: 8, scale: 1
|
||||
t.datetime "created_at", null: false
|
||||
t.datetime "updated_at", null: false
|
||||
t.index ["aircraft_id", "sample_date"], name: "index_oil_analyses_on_aircraft_id_and_sample_date"
|
||||
t.index ["aircraft_id"], name: "index_oil_analyses_on_aircraft_id"
|
||||
t.index ["component_id"], name: "index_oil_analyses_on_component_id"
|
||||
end
|
||||
|
||||
create_table "sessions", force: :cascade do |t|
|
||||
t.integer "user_id", null: false
|
||||
t.string "ip_address"
|
||||
@@ -512,6 +557,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_06_150000) do
|
||||
add_foreign_key "major_records", "documents", column: "form_337_document_id", on_delete: :nullify
|
||||
add_foreign_key "major_records", "documents", column: "stc_document_id", on_delete: :nullify
|
||||
add_foreign_key "major_records", "logbook_entries", on_delete: :nullify
|
||||
add_foreign_key "oil_analyses", "aircraft"
|
||||
add_foreign_key "oil_analyses", "components"
|
||||
add_foreign_key "sessions", "users"
|
||||
add_foreign_key "share_tokens", "aircraft"
|
||||
add_foreign_key "share_tokens", "users", column: "created_by_id", on_delete: :nullify
|
||||
|
||||
+2548
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,119 @@
|
||||
require "test_helper"
|
||||
|
||||
class OilAnalysisFlowTest < ActionDispatch::IntegrationTest
|
||||
setup do
|
||||
@owner = create_user
|
||||
@pilot = create_user
|
||||
@aircraft = create_aircraft(owner: @owner, pilot: @pilot)
|
||||
@engine = create_component(@aircraft, hours_since_overhaul: 120.5)
|
||||
end
|
||||
|
||||
def results(**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)
|
||||
end
|
||||
|
||||
test "pilot adds samples; trends, flags and comparison render" do
|
||||
sign_in @pilot
|
||||
get new_aircraft_oil_analysis_path(@aircraft)
|
||||
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(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)
|
||||
assert latest.report.attached?
|
||||
assert_equal [ "Oil analysis added (sampled 2026-08-01)" ], @aircraft.events.where(category: "oil_analysis").limit(1).pluck(:event_name)
|
||||
|
||||
get aircraft_oil_analyses_path(@aircraft)
|
||||
assert_response :success
|
||||
assert_includes response.body, "Silicon above average"
|
||||
assert_includes response.body, "Chartkick"
|
||||
|
||||
get aircraft_oil_analysis_path(@aircraft, latest)
|
||||
assert_response :success
|
||||
assert_includes response.body, "Compared with"
|
||||
assert_includes response.body, "+5" # iron 25 → 30
|
||||
refute_includes response.body, ">Edit<" # pilots can't edit
|
||||
end
|
||||
|
||||
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" } }
|
||||
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
|
||||
delete aircraft_oil_analysis_path(@aircraft, analysis)
|
||||
assert_equal 0, @aircraft.oil_analyses.count
|
||||
end
|
||||
|
||||
test "an engine from another aircraft is ignored" do
|
||||
other = create_component(create_aircraft)
|
||||
sign_in @owner
|
||||
post aircraft_oil_analyses_path(@aircraft), params: { oil_analysis: results(component_id: other.id) }
|
||||
assert_nil @aircraft.oil_analyses.last.component_id
|
||||
end
|
||||
end
|
||||
|
||||
class OilAnalysisImportTest < ActionDispatch::IntegrationTest
|
||||
setup do
|
||||
@owner = create_user
|
||||
@pilot = create_user
|
||||
@aircraft = create_aircraft(owner: @owner, pilot: @pilot, tail_number: "N12345")
|
||||
@in_service = create_component(@aircraft)
|
||||
@engine = create_component(@aircraft, serial_number: "900001", status: "SPARE")
|
||||
end
|
||||
|
||||
def report = fixture_file_upload("oil_analysis/avlab_report.pdf", "application/pdf")
|
||||
|
||||
test "pilot imports every sample on the report; reimporting adds nothing" do
|
||||
sign_in @pilot
|
||||
post import_aircraft_oil_analyses_path(@aircraft), params: { report: report }
|
||||
assert_redirected_to aircraft_oil_analyses_path(@aircraft)
|
||||
assert_equal "Imported 3 samples from the AvLab report.", flash[:notice]
|
||||
|
||||
analyses = @aircraft.oil_analyses.recent_first.to_a
|
||||
assert_equal %w[P26 P47 P69], analyses.map(&:sample_number)
|
||||
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 3, @aircraft.events.where(category: "oil_analysis").count
|
||||
|
||||
post import_aircraft_oil_analyses_path(@aircraft), params: { report: report }
|
||||
assert_equal "Imported 0 samples from the AvLab report. 3 samples were already recorded.", flash[:notice]
|
||||
assert_equal 3, @aircraft.oil_analyses.count
|
||||
|
||||
follow_redirect!
|
||||
assert_includes response.body, "Silicon above average"
|
||||
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)
|
||||
sign_in @owner
|
||||
post import_aircraft_oil_analyses_path(@aircraft), params: { report: report }
|
||||
assert_equal 3, @aircraft.oil_analyses.count
|
||||
assert manual.reload.report.attached?
|
||||
end
|
||||
|
||||
test "refuses a report for another aircraft, or a file that isn't one" do
|
||||
@aircraft.update!(tail_number: "N54321")
|
||||
sign_in @owner
|
||||
post import_aircraft_oil_analyses_path(@aircraft), params: { report: report }
|
||||
assert_redirected_to new_aircraft_oil_analysis_path(@aircraft)
|
||||
assert_equal "That report is for N12345, not N54321.", flash[:alert]
|
||||
|
||||
post import_aircraft_oil_analyses_path(@aircraft), params: { report: fixture_file_upload("flights.csv", "application/pdf") }
|
||||
assert_match(/Couldn't import that report/, flash[:alert])
|
||||
assert_equal 0, @aircraft.oil_analyses.count
|
||||
end
|
||||
end
|
||||
@@ -24,6 +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)
|
||||
@token = @a.share_tokens.create!(privilege: "maintenance", label: "Mechanic")
|
||||
@a.log_event!("aircraft", "Created", user: @owner)
|
||||
sign_in @owner
|
||||
@@ -39,6 +40,7 @@ class PagesTest < ActionDispatch::IntegrationTest
|
||||
aircraft_notes_path(a), new_aircraft_note_path(a), edit_aircraft_note_path(a, @note),
|
||||
aircraft_flight_logs_path(a), new_aircraft_flight_log_path(a), aircraft_flight_log_path(a, @flight),
|
||||
aircraft_consumable_records_path(a), new_aircraft_consumable_record_path(a, type: "fuel"), edit_aircraft_consumable_record_path(a, @cr),
|
||||
aircraft_oil_analyses_path(a), new_aircraft_oil_analysis_path(a), aircraft_oil_analysis_path(a, @oa), edit_aircraft_oil_analysis_path(a, @oa),
|
||||
aircraft_logbook_entries_path(a), aircraft_logbook_entries_path(a, q: "oil", log_type: "AC"),
|
||||
new_aircraft_logbook_entry_path(a), aircraft_logbook_entry_path(a, @entry), edit_aircraft_logbook_entry_path(a, @entry),
|
||||
aircraft_documents_path(a), new_aircraft_document_path(a), aircraft_document_path(a, @doc), edit_aircraft_document_path(a, @doc),
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
require "test_helper"
|
||||
|
||||
class OilAnalysisTest < ActiveSupport::TestCase
|
||||
setup { @a = create_aircraft }
|
||||
|
||||
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)
|
||||
assert a.flagged?("iron")
|
||||
refute a.flagged?("copper")
|
||||
assert a.flagged?("silicon") # exactly 1.5×
|
||||
refute a.flagged?("tin") # no average to compare
|
||||
assert_equal %w[iron silicon], a.flagged_elements
|
||||
end
|
||||
|
||||
test "validates status, non-negative results, and engine on this aircraft" do
|
||||
assert analysis.valid?
|
||||
refute analysis(status: "bad").valid?
|
||||
refute analysis(iron: -1).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
|
||||
end
|
||||
@@ -0,0 +1,43 @@
|
||||
require "test_helper"
|
||||
|
||||
class OilReportParserTest < ActiveSupport::TestCase
|
||||
# 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)
|
||||
|
||||
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
|
||||
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
|
||||
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])
|
||||
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"
|
||||
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 }
|
||||
end
|
||||
end
|
||||
Reference in new issue
Block a user