Sub-components on logbook entries (e.g. the oil filter on the engine)

- Once a component is chosen, its sub-components are offered on the entry
  form (and the squawk Resolve page); ticked ones are saved with their
  total time and time since service, worked out from the airframe total
  time like the component's (editable; blank before it was installed)
- Entry page and printed PDFs list each sub-component with its serial
  number and times; parts without an overhaul type read "Since service"
- Archives carry them: the original format's list of components per entry
  (first = the entry's component, the rest = sub-components)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 12:54:49 -05:00
1 parent 72e1d7760f
commit 7caa213e7a
16 files changed
+249 -22

No files matched your search

@@ -32,6 +32,7 @@ class LogbookEntriesController < ApplicationController
def create
@entry = @aircraft.logbook_entries.new(entry_params)
@entry.assign_parts(parts_params, @aircraft)
if @entry.save
log_event("logbook", "Logbook entry added (#{@entry.date})")
redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry added."
@@ -43,7 +44,9 @@ class LogbookEntriesController < ApplicationController
def edit; end
def update
if @entry.update(entry_params)
@entry.assign_attributes(entry_params)
@entry.assign_parts(parts_params, @aircraft)
if @entry.save
log_event("logbook", "Logbook entry updated (#{@entry.date})")
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Logbook entry updated."
else
@@ -59,6 +62,11 @@ class LogbookEntriesController < ApplicationController
private
# Sub-components ticked on the form: { component_id => { include, hours, since } }.
def parts_params
params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {}
end
def set_entry = @entry = @aircraft.logbook_entries.find(params[:id])
def entry_params
+1 -1
View File
@@ -18,7 +18,7 @@ class LogbookPrintsController < ApplicationController
def set_entries
ids = Array(params[:ids]).map(&:to_i).first(200)
@entries = @aircraft.logbook_entries.where(id: ids).includes(:component, inspection_records: :inspection_type).order(:date, :id).to_a
@entries = @aircraft.logbook_entries.where(id: ids).includes(:component, :parts, inspection_records: :inspection_type).order(:date, :id).to_a
redirect_to aircraft_logbook_entries_path(@aircraft), alert: "Choose the entries to print." if @entries.empty?
end
end
+1
View File
@@ -54,6 +54,7 @@ class SquawksController < ApplicationController
case params[:logbook]
when "new"
@entry = @aircraft.logbook_entries.new(resolution_entry_params.merge(entry_type: "MAINTENANCE"))
@entry.assign_parts(params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {}, @aircraft)
return render(:resolution, status: :unprocessable_entity) unless @entry.save
log_event("logbook", "Logbook entry added: #{@entry.date}")
@entry
@@ -5,9 +5,11 @@ import { Controller } from "@hotwired/stimulus"
// since overhaul are filled in for the airframe time entered: its current
// times, shifted by however far the entry's airframe time is from the
// aircraft's current time. Typing in the component times yourself stops the
// automatic updates (until another component is picked).
// automatic updates (until another component is picked). The chosen
// component's sub-components (oil filter…) can be ticked to include them,
// with their times worked out the same way.
export default class extends Controller {
static targets = [ "logType", "component", "total", "since", "airframe" ]
static targets = [ "logType", "component", "total", "since", "airframe", "partsBox", "part" ]
static values = { aircraftHours: Number }
connect() { this.manual = false }
@@ -24,11 +26,49 @@ export default class extends Controller {
componentChanged() {
this.manual = false
this.showParts()
this.recompute()
}
// Only the chosen component's sub-components are offered.
showParts() {
const id = this.componentTarget.value
let any = false
this.partTargets.forEach((row) => {
const mine = id && row.dataset.ancestors.split(" ").includes(id)
row.hidden = !mine
if (!mine) row.querySelector("input[type=checkbox]").checked = false
any ||= mine
})
if (this.hasPartsBoxTarget) this.partsBoxTarget.hidden = !any
}
partToggled(event) {
const row = event.target.closest("[data-component-times-target=part]")
if (event.target.checked) { delete row.dataset.manual; this.fillPart(row) }
}
partEdited(event) {
const row = event.target.closest("[data-component-times-target=part]")
row.dataset.manual = "true"
row.querySelector("input[type=checkbox]").checked = true
}
airframeChanged() {
if (!this.manual) this.recompute()
this.partTargets.forEach((row) => { if (!row.hidden && !row.dataset.manual) this.fillPart(row) })
}
get delta() {
const airframe = this.hasAirframeTarget ? parseFloat(this.airframeTarget.value) : NaN
return Number.isNaN(airframe) ? 0 : airframe - this.aircraftHoursValue
}
fillPart(row) {
const total = parseFloat(row.dataset.total) + this.delta
const since = parseFloat(row.dataset.since) + this.delta
row.querySelector("[data-role=hours]").value = total >= 0 ? total.toFixed(1) : ""
row.querySelector("[data-role=since]").value = since >= 0 ? since.toFixed(1) : ""
}
markManual() { this.manual = true }
@@ -36,10 +76,8 @@ export default class extends Controller {
recompute() {
const option = this.componentTarget.selectedOptions[0]
if (!option?.dataset.total) return
const airframe = this.hasAirframeTarget ? parseFloat(this.airframeTarget.value) : NaN
const delta = Number.isNaN(airframe) ? 0 : airframe - this.aircraftHoursValue
const total = parseFloat(option.dataset.total) + delta
const since = parseFloat(option.dataset.since) + delta
const total = parseFloat(option.dataset.total) + this.delta
const since = parseFloat(option.dataset.since) + this.delta
// Negative means the entry is from before the component was new or overhauled: unknown.
this.totalTarget.value = total >= 0 ? total.toFixed(1) : ""
this.sinceTarget.value = since >= 0 ? since.toFixed(1) : ""
+15 -1
View File
@@ -15,6 +15,7 @@ class Component < ApplicationRecord
has_many :inspection_records, dependent: :nullify
has_many :major_records, dependent: :nullify
has_many :logbook_entries, dependent: :nullify
has_many :logbook_entry_parts, dependent: :destroy
has_and_belongs_to_many :inspection_types
has_and_belongs_to_many :airworthiness_directives
@@ -30,7 +31,20 @@ class Component < ApplicationRecord
end
def status_label = STATUSES[status]
def since_overhaul_abbreviation = OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind, "TSO")
# SMOH / SFOH / SNEW when the overhaul type is known; engines and
# propellers otherwise "TSO", and other parts (filters…) "since service".
def since_overhaul_abbreviation
OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind) { engine? || propeller? ? "TSO" : "Since service" }
end
# Its sub-components, and theirs.
def descendant_ids
child_components.flat_map { [ _1.id, *_1.descendant_ids ] }
end
def ancestor_ids
parent_component ? [ parent_component_id, *parent_component.ancestor_ids ] : []
end
def engine? = component_type&.name.to_s.match?(/engine/i)
def propeller? = component_type&.name.to_s.match?(/propell?er|\bprop\b/i)
+15
View File
@@ -23,6 +23,9 @@ class LogbookEntry < ApplicationRecord
belongs_to :document, optional: true
# For engine / propeller logs: which one, and its times at this entry.
belongs_to :component, optional: true
# Sub-components it also covers (the oil filter on the engine…).
has_many :parts, -> { includes(component: :component_type).order(:id) }, class_name: "LogbookEntryPart",
dependent: :destroy, autosave: true
has_many :inspection_records, dependent: :nullify
has_many :ad_compliances, dependent: :nullify
has_many :squawks, dependent: :nullify
@@ -45,6 +48,18 @@ class LogbookEntry < ApplicationRecord
end
def to_s = "#{date} — #{LOG_TYPES[log_type]}"
# From the form: { component_id => { "include" => "1", "hours" => …, "since" => … } }.
# Only the aircraft's sub-components of the entry's component are kept.
def assign_parts(params, aircraft)
allowed = component ? component.descendant_ids.to_set & aircraft.component_ids.to_set : Set.new
wanted = params.to_h.select { |id, p| p["include"] == "1" && allowed.include?(id.to_i) }
parts.each { |part| part.mark_for_destruction unless wanted.key?(part.component_id.to_s) }
wanted.each do |id, p|
part = parts.find { _1.component_id == id.to_i } || parts.build(component_id: id.to_i)
part.assign_attributes(hours_at_entry: p["hours"].presence, since_overhaul_at_entry: p["since"].presence)
end
end
def certificate_label = CERTIFICATE_TYPES[signoff_certificate_type]
def inspection_result_label = INSPECTION_RESULTS[inspection_result]
+9
View File
@@ -0,0 +1,9 @@
# A sub-component a logbook entry also covers (the oil filter on the engine…)
# and its times at the entry.
class LogbookEntryPart < ApplicationRecord
belongs_to :logbook_entry
belongs_to :component
validates :component_id, uniqueness: { scope: :logbook_entry_id }
validates :hours_at_entry, :since_overhaul_at_entry, numericality: { greater_than_or_equal_to: 0 }, allow_nil: true
end
+6 -4
View File
@@ -55,7 +55,7 @@ module AircraftArchive
document_images: a.documents.includes(pages_attachments: :blob).flat_map do |d|
d.pages.map { |page| { id: id(page), document_id: id(d), notes: "", image: file(page, "health/documents") } }
end,
logbook_entries: a.logbook_entries.map { logbook_hash(_1) },
logbook_entries: a.logbook_entries.includes(:parts).map { logbook_hash(_1) },
squawks: a.squawks.includes(:reported_by, attachments_attachments: :blob).map { squawk_hash(_1) },
inspection_types: inspection_types.map { inspection_type_hash(_1, component_ids) },
inspection_records: a.inspection_records.map do |r|
@@ -148,9 +148,11 @@ module AircraftArchive
inspection_result: e.inspection_result, verified: e.verified, transcription_confidence: e.transcription_confidence,
log_image_id: id(e.document_id),
aircraft_hours_at_entry: dec(e.aircraft_hours_at_entry), entry_type: e.entry_type, page_number: e.page_number,
components: [ id(e.component_id) ].compact,
component_hours: e.component_id ? { id(e.component_id) => dec(e.component_hours_at_entry) }.compact : {},
component_since_overhaul: e.component_id ? { id(e.component_id) => dec(e.component_since_overhaul_at_entry) }.compact : {},
components: [ id(e.component_id), *e.parts.map { id(_1.component_id) } ].compact,
component_hours: { id(e.component_id) => dec(e.component_hours_at_entry) }.merge(e.parts.to_h { [ id(_1.component_id), dec(_1.hours_at_entry) ] })
.reject { |k, v| k.nil? || v.nil? },
component_since_overhaul: { id(e.component_id) => dec(e.component_since_overhaul_at_entry) }
.merge(e.parts.to_h { [ id(_1.component_id), dec(_1.since_overhaul_at_entry) ] }).reject { |k, v| k.nil? || v.nil? },
related_documents: [] }
end
+8 -6
View File
@@ -222,7 +222,6 @@ module AircraftArchive
end
def import_logbook
dropped = 0
m("logbook_entries").each do |data|
e = @aircraft.logbook_entries.new(
log_type: LogbookEntry::LOG_TYPES.key?(data["log_type"]) ? data["log_type"] : "AC",
@@ -237,19 +236,22 @@ module AircraftArchive
aircraft_hours_at_entry: num(data["aircraft_hours_at_entry"]), page_number: data["page_number"],
document_id: @map[:document][data["log_image_id"].to_s]
)
# One component per entry here (the original allows several): the first, with its times.
if (ref = Array(data["components"]).first) && (component_id = @map[:component][ref.to_s])
e.component_id = component_id
# The first component is the entry's; the rest are its sub-components, each with its times.
refs = Array(data["components"]).select { @map[:component][_1.to_s] }
if (ref = refs.first)
e.component_id = @map[:component][ref.to_s]
e.component_hours_at_entry = num(hash_value(data["component_hours"], ref))
e.component_since_overhaul_at_entry = num(hash_value(data["component_since_overhaul"], ref))
dropped += 1 if Array(data["components"]).size > 1
end
refs.drop(1).uniq.each do |r|
e.parts.build(component_id: @map[:component][r.to_s], hours_at_entry: num(hash_value(data["component_hours"], r)),
since_overhaul_at_entry: num(hash_value(data["component_since_overhaul"], r)))
end
e.save!(validate: false)
@map[:logbook][data["id"].to_s] = e.id
tick("logbook_entries")
end
warn("#{dropped} logbook #{dropped == 1 ? 'entry was' : 'entries were'} linked to several components; only the first is kept here.") if dropped.positive?
end
def import_squawks
+10 -1
View File
@@ -6,7 +6,8 @@ Prawn::Fonts::AFM.hide_m17n_warning = true # text is reduced to what the built-i
# want (aircraft, date, airframe total time, the work, the signer's name and
# certificate) and a blank line for the signature, which must be signed by
# hand. Engine and propeller entries add the component's serial number, total
# time and time since overhaul (blanks to fill in when no component is linked).
# time and time since overhaul (blanks to fill in when no component is linked),
# and a line for each sub-component the entry covers (an oil filter…).
#
# Labels: one entry per label; long entries shrink to fit, then continue on
# the next label. Pages: entries follow one another, each in a box with its
@@ -171,6 +172,14 @@ class LogbookEntryPdf
elsif noun
lines << "#{noun}: ______________ S/N __________ #{noun} total time: ________ SMOH / SFOH: ________"
end
entry.parts.each do |part|
c = part.component
name = c.component_type&.name || "Part"
model = [ c.manufacturer, c.model ].compact_blank.join(" ")
lines << [ "#{name}: #{model}#{" S/N #{c.serial_number}" if c.serial_number.present?}",
"Total time: #{blank_or_hours(part.hours_at_entry)}",
"#{c.since_overhaul_abbreviation}: #{blank_or_hours(part.since_overhaul_at_entry)}" ].join(" ")
end
lines
end
@@ -16,3 +16,33 @@
data: { component_times_target: "since", action: "input->component-times#markManual" },
hint: "Worked out from the component's current times and the airframe total time above; edit them if they differ." %>
</div>
<%# Sub-components of the chosen component (oil filter, magnetos…): tick to include them with their times. %>
<% children = comps.select(&:parent_component_id) %>
<% if children.any? %>
<% parts = f.object.parts.index_by(&:component_id) %>
<% selected = f.object.component %>
<fieldset class="space-y-2" data-component-times-target="partsBox" <%= "hidden" unless selected && (children.map(&:id) & selected.descendant_ids).any? %>>
<legend class="label">Sub-components</legend>
<% children.each do |c| %>
<% part = parts[c.id] %>
<% ancestors = c.ancestor_ids %>
<% field = "#{f.object_name}[parts][#{c.id}]" %>
<div class="grid items-end gap-2 sm:grid-cols-[1fr_9rem_9rem]" data-component-times-target="part" data-ancestors="<%= ancestors.join(' ') %>"
data-total="<%= c.hours_in_service.to_f %>" data-since="<%= c.hours_since_overhaul.to_f %>"
<%= "hidden" unless selected && ancestors.include?(selected.id) %>>
<label class="flex items-center gap-2 text-sm">
<%= check_box_tag "#{field}[include]", "1", part.present?, id: "part_#{c.id}_include", class: "h-4 w-4 shrink-0 rounded border-slate-300",
data: { action: "component-times#partToggled" } %>
<span><%= c %> · <%= c.manufacturer %> <%= c.model %><%= " · S/N #{c.serial_number}" if c.serial_number.present? %></span>
</label>
<div><label class="text-xs text-slate-500" for="part_<%= c.id %>_hours">Total time</label>
<%= number_field_tag "#{field}[hours]", part&.hours_at_entry, id: "part_#{c.id}_hours", step: 0.1, class: "input",
data: { role: "hours", action: "input->component-times#partEdited" } %></div>
<div><label class="text-xs text-slate-500" for="part_<%= c.id %>_since"><%= c.since_overhaul_abbreviation.capitalize %></label>
<%= number_field_tag "#{field}[since]", part&.since_overhaul_at_entry, id: "part_#{c.id}_since", step: 0.1, class: "input",
data: { role: "since", action: "input->component-times#partEdited" } %></div>
</div>
<% end %>
<p class="hint">Their times are worked out the same way as the component's. Sub-components are set up on the Components tab (a part's "Parent component").</p>
</fieldset>
<% end %>
+5
View File
@@ -21,6 +21,11 @@
<span><%= c %> <%= c.model %><%= " S/N #{c.serial_number}" if c.serial_number.present? %>:
<%= hours(@entry.component_hours_at_entry) %> total, <%= hours(@entry.component_since_overhaul_at_entry) %> <%= c.since_overhaul_abbreviation %></span>
<% end %>
<% @entry.parts.each do |part| %>
<% pc = part.component %>
<span><%= pc %> <%= pc.model %><%= " S/N #{pc.serial_number}" if pc.serial_number.present? %>:
<%= hours(part.hours_at_entry) %> total, <%= hours(part.since_overhaul_at_entry) %> <%= pc.since_overhaul_abbreviation.downcase %></span>
<% end %>
</div>
<div class="whitespace-pre-wrap rounded bg-slate-50 p-3 font-mono text-sm"><%= @entry.text %></div>
<div class="text-sm text-slate-600">