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:
rickyandClaude Opus 5.5 committed 2026-11-06 06:12:51 -05:00
1 parent 6c6e7af8e6
commit d519aa9aae
24 files changed
+3456 -2

No files matched your search

+116
View File
@@ -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
+1
View File
@@ -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] ],
+38
View File
@@ -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
+1
View File
@@ -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
+1 -1
View File
@@ -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
+1
View File
@@ -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
+60
View File
@@ -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
+207
View File
@@ -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
+36
View File
@@ -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 "&lt; 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 %>
+6
View File
@@ -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 %>
+3
View File
@@ -0,0 +1,3 @@
<% content_for :title, "Edit Oil Analysis" %>
<%= render "shared/aircraft_header", aircraft: @aircraft %>
<%= render "form", aircraft: @aircraft, analysis: @analysis %>
+81
View File
@@ -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>
+8
View File
@@ -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 %>
+62
View File
@@ -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>