From 7caa213e7a7543bebd4547ca1a5c41b797a49aa1 Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Sat, 7 Nov 2026 12:54:49 -0500 Subject: [PATCH] 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 --- README.md | 2 +- app/controllers/logbook_entries_controller.rb | 10 ++- app/controllers/logbook_prints_controller.rb | 2 +- app/controllers/squawks_controller.rb | 1 + .../controllers/component_times_controller.js | 50 ++++++++++++-- app/models/component.rb | 16 ++++- app/models/logbook_entry.rb | 15 +++++ app/models/logbook_entry_part.rb | 9 +++ app/services/aircraft_archive/exporter.rb | 10 +-- app/services/aircraft_archive/importer.rb | 14 ++-- app/services/logbook_entry_pdf.rb | 11 +++- .../_component_fields.html.erb | 30 +++++++++ app/views/logbook_entries/show.html.erb | 5 ++ ...261108000000_create_logbook_entry_parts.rb | 14 ++++ db/schema.rb | 16 ++++- test/integration/logbook_entry_parts_test.rb | 66 +++++++++++++++++++ 16 files changed, 249 insertions(+), 22 deletions(-) create mode 100644 app/models/logbook_entry_part.rb create mode 100644 db/migrate/20261108000000_create_logbook_entry_parts.rb create mode 100644 test/integration/logbook_entry_parts_test.rb diff --git a/README.md b/README.md index 846a48c..62194a1 100644 --- a/README.md +++ b/README.md @@ -104,7 +104,7 @@ To back up or move a single aircraft with all its files, use **Access & Sharing | New ADs | Weekly search of the Federal Register for newly published ADs mentioning the aircraft, engine or propeller models (or your own terms). Review each: track it as an AD or dismiss it. | | AD import | Import ADs from an FAA DRS export (`.xlsx` recommended: its AD numbers link to each AD's DRS page, which the import keeps; `.csv` works without links). ADs are matched by number, so nothing is duplicated. The preview suggests Track, Not applicable or Skip for each AD, and flags superseded or non-current ADs, model mismatches, appliance or STC-only ADs, and repetitive actions. | | Inspections | Shared inspection types with hour, month, and day recurrence, plus history. Each says what overdue means (grounded, no IFR, no transponder, advisory); an annual can also count as the 100-hour, and the 100-hour's 10-hour overrun is credited (91.409(b)). One click adds the standard Part 91 set. | -| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Entry templates (built-in pilot preventive maintenance per 43.3(g) and Part 43 Appendix A(c); admins add and edit their own under Admin → Logbook templates). Engine and propeller entries link the component and record its total time and time since overhaul (SMOH/SFOH/SNEW) at the entry, worked out from the entry's airframe total time. Print entries as a PDF on Avery 5163/5164 labels or half-letter/letter pages (boxed) to sign and put in the paper logbook. | +| Logbook | Maintenance entries with search and a link to a scanned document page. Records the signer's certificate kind and number and an inspection's result, and flags what 43.9 / 43.11 needs that's missing. Entries transcribed by Claude stay "unverified" until someone checks them against the scan. Entry templates (built-in pilot preventive maintenance per 43.3(g) and Part 43 Appendix A(c); admins add and edit their own under Admin → Logbook templates). Engine and propeller entries link the component and record its total time and time since overhaul (SMOH/SFOH/SNEW) at the entry, worked out from the entry's airframe total time; sub-components (an oil filter on the engine…) can be included with their own times. Print entries as a PDF on Avery 5163/5164 labels or half-letter/letter pages (boxed) to sign and put in the paper logbook. | | Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). | | Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. | | Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. | diff --git a/app/controllers/logbook_entries_controller.rb b/app/controllers/logbook_entries_controller.rb index a3a9ac3..7626d0c 100644 --- a/app/controllers/logbook_entries_controller.rb +++ b/app/controllers/logbook_entries_controller.rb @@ -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 diff --git a/app/controllers/logbook_prints_controller.rb b/app/controllers/logbook_prints_controller.rb index 0dcce51..ee5316b 100644 --- a/app/controllers/logbook_prints_controller.rb +++ b/app/controllers/logbook_prints_controller.rb @@ -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 diff --git a/app/controllers/squawks_controller.rb b/app/controllers/squawks_controller.rb index 4cca17e..6b3ec89 100644 --- a/app/controllers/squawks_controller.rb +++ b/app/controllers/squawks_controller.rb @@ -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 diff --git a/app/javascript/controllers/component_times_controller.js b/app/javascript/controllers/component_times_controller.js index 7060b06..90b7a56 100644 --- a/app/javascript/controllers/component_times_controller.js +++ b/app/javascript/controllers/component_times_controller.js @@ -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) : "" diff --git a/app/models/component.rb b/app/models/component.rb index a8be19f..b0787d4 100644 --- a/app/models/component.rb +++ b/app/models/component.rb @@ -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) diff --git a/app/models/logbook_entry.rb b/app/models/logbook_entry.rb index 5acb1cf..8321448 100644 --- a/app/models/logbook_entry.rb +++ b/app/models/logbook_entry.rb @@ -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] diff --git a/app/models/logbook_entry_part.rb b/app/models/logbook_entry_part.rb new file mode 100644 index 0000000..f5b1396 --- /dev/null +++ b/app/models/logbook_entry_part.rb @@ -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 diff --git a/app/services/aircraft_archive/exporter.rb b/app/services/aircraft_archive/exporter.rb index 138767d..11bbe67 100644 --- a/app/services/aircraft_archive/exporter.rb +++ b/app/services/aircraft_archive/exporter.rb @@ -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 diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index d157050..0fcf8d0 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -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 diff --git a/app/services/logbook_entry_pdf.rb b/app/services/logbook_entry_pdf.rb index 2b5266b..04f251d 100644 --- a/app/services/logbook_entry_pdf.rb +++ b/app/services/logbook_entry_pdf.rb @@ -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 diff --git a/app/views/logbook_entries/_component_fields.html.erb b/app/views/logbook_entries/_component_fields.html.erb index d0aeb90..645f760 100644 --- a/app/views/logbook_entries/_component_fields.html.erb +++ b/app/views/logbook_entries/_component_fields.html.erb @@ -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." %> +<%# 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 %> +
> + Sub-components + <% children.each do |c| %> + <% part = parts[c.id] %> + <% ancestors = c.ancestor_ids %> + <% field = "#{f.object_name}[parts][#{c.id}]" %> +
> + +
+ <%= 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" } %>
+
+ <%= 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" } %>
+
+ <% end %> +

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").

+
+<% end %> diff --git a/app/views/logbook_entries/show.html.erb b/app/views/logbook_entries/show.html.erb index b0e0941..0dbd2af 100644 --- a/app/views/logbook_entries/show.html.erb +++ b/app/views/logbook_entries/show.html.erb @@ -21,6 +21,11 @@ <%= 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 %> <% end %> + <% @entry.parts.each do |part| %> + <% pc = part.component %> + <%= 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 %> + <% end %>
<%= @entry.text %>
diff --git a/db/migrate/20261108000000_create_logbook_entry_parts.rb b/db/migrate/20261108000000_create_logbook_entry_parts.rb new file mode 100644 index 0000000..489b34c --- /dev/null +++ b/db/migrate/20261108000000_create_logbook_entry_parts.rb @@ -0,0 +1,14 @@ +# Sub-components a logbook entry also covers (e.g. the oil filter on the +# engine), with their times at the entry. +class CreateLogbookEntryParts < ActiveRecord::Migration[8.1] + def change + create_table :logbook_entry_parts do |t| + t.references :logbook_entry, null: false, foreign_key: { on_delete: :cascade } + t.references :component, null: false, foreign_key: { on_delete: :cascade } + t.decimal :hours_at_entry, precision: 8, scale: 1 + t.decimal :since_overhaul_at_entry, precision: 8, scale: 1 + t.timestamps + end + add_index :logbook_entry_parts, %i[logbook_entry_id component_id], unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index e2fcfc8..560135e 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -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_07_250000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_08_000000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -458,6 +458,18 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_250000) do t.index ["document_id"], name: "index_logbook_entries_on_document_id" end + create_table "logbook_entry_parts", force: :cascade do |t| + t.integer "logbook_entry_id", null: false + t.integer "component_id", null: false + t.decimal "hours_at_entry", precision: 8, scale: 1 + t.decimal "since_overhaul_at_entry", precision: 8, scale: 1 + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["component_id"], name: "index_logbook_entry_parts_on_component_id" + t.index ["logbook_entry_id", "component_id"], name: "index_logbook_entry_parts_on_logbook_entry_id_and_component_id", unique: true + t.index ["logbook_entry_id"], name: "index_logbook_entry_parts_on_logbook_entry_id" + end + create_table "logbook_imports", force: :cascade do |t| t.integer "aircraft_id", null: false t.integer "user_id" @@ -682,6 +694,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_250000) do add_foreign_key "logbook_entries", "aircraft" add_foreign_key "logbook_entries", "components", on_delete: :nullify add_foreign_key "logbook_entries", "documents", on_delete: :nullify + add_foreign_key "logbook_entry_parts", "components", on_delete: :cascade + add_foreign_key "logbook_entry_parts", "logbook_entries", on_delete: :cascade add_foreign_key "logbook_imports", "aircraft" add_foreign_key "logbook_imports", "documents", on_delete: :nullify add_foreign_key "logbook_imports", "users", on_delete: :nullify diff --git a/test/integration/logbook_entry_parts_test.rb b/test/integration/logbook_entry_parts_test.rb new file mode 100644 index 0000000..9b8490a --- /dev/null +++ b/test/integration/logbook_entry_parts_test.rb @@ -0,0 +1,66 @@ +require "test_helper" +require "pdf-reader" + +# Sub-components on a logbook entry: the oil filter on the engine, with its +# times at the entry. +class LogbookEntryPartsTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user("owner@example.com") + @a = create_aircraft(owner: @owner, tail_number: "N12345", tach_time: 4210.3) + @engine = create_component(@a, component_type: component_type("Engine"), manufacturer: "Continental", model: "O-470-R", + serial_number: "100001-R", hours_in_service: 2655.9, hours_since_overhaul: 94.7, overhaul_kind: "major") + @filter = create_component(@a, component_type: component_type("Oil filter"), manufacturer: "Challenger", model: "CP48108C", + serial_number: "10000000", parent_component: @engine, hours_in_service: 120.5, hours_since_overhaul: 20.5) + @prop = create_component(@a, component_type: component_type("Propeller"), manufacturer: "McCauley", model: "2A34C203") + @elsewhere = create_component(create_aircraft, component_type: component_type("Oil filter")) + sign_in @owner + end + + def entry_params(**extra) + { date: "2026-08-20", log_type: "ENG", entry_type: "MAINTENANCE", text: "Changed oil; cleaned the filter.", aircraft_hours_at_entry: 4200.3, + component_id: @engine.id, component_hours_at_entry: 2645.9, component_since_overhaul_at_entry: 84.7 }.merge(extra) + end + + test "the engine's sub-components are offered and saved with their times" do + get new_aircraft_logbook_entry_path(@a) + assert_select "[data-component-times-target=part][data-ancestors='#{@engine.id}'][data-total='120.5'][data-since='20.5'][hidden]" do + assert_select "input[name='logbook_entry[parts][#{@filter.id}][include]']" + assert_select "label", text: "Since service" + end + + post aircraft_logbook_entries_path(@a), params: { logbook_entry: entry_params(parts: { + @filter.id => { include: "1", hours: "110.5", since: "10.5" }, + @prop.id => { include: "1", hours: "1" }, # not under the engine: ignored + @elsewhere.id => { include: "1", hours: "1" } }) } # another aircraft's: ignored + entry = @a.logbook_entries.sole + assert_equal [ [ @filter, 110.5, 10.5 ] ], entry.parts.map { [ _1.component, _1.hours_at_entry.to_f, _1.since_overhaul_at_entry.to_f ] } + + get aircraft_logbook_entry_path(@a, entry) + assert_includes response.body, "110.5 total, 10.5 since service" + get edit_aircraft_logbook_entry_path(@a, entry) + assert_select "input[name='logbook_entry[parts][#{@filter.id}][include]'][checked]" + assert_select "[data-component-times-target=part][data-ancestors='#{@engine.id}']:not([hidden])" + + patch aircraft_logbook_entry_path(@a, entry), params: { logbook_entry: { parts: { @filter.id => { include: "1", hours: "111", since: "11" } } } } + assert_equal [ 111, 11 ], entry.parts.reload.sole.then { [ _1.hours_at_entry.to_i, _1.since_overhaul_at_entry.to_i ] } + patch aircraft_logbook_entry_path(@a, entry), params: { logbook_entry: { text: "Changed oil.", parts: { @filter.id => { include: "0" } } } } + assert_empty entry.parts.reload + end + + test "printouts add a line per sub-component; archives carry them" do + entry = @a.logbook_entries.create!(entry_params.merge(component: @engine)) + entry.parts.create!(component: @filter, hours_at_entry: 110.5, since_overhaul_at_entry: 10.5) + get aircraft_logbook_print_path(@a, format: :pdf), params: { ids: [ entry.id ], layout: "letter" } + text = PDF::Reader.new(StringIO.new(response.body)).pages.map(&:text).join(" ").gsub(/\s+/, " ") + assert_includes text, "Engine: Continental O-470-R S/N 100001-R Engine total time: 2,645.9 SMOH: 84.7" + assert_includes text, "Oil filter: Challenger CP48108C S/N 10000000 Total time: 110.5 Since service: 10.5" + + path = File.join(Dir.mktmpdir, "a.sam.zip") + AircraftArchive::Exporter.new(@a, source: "sam.example.com").write_to(path) + copy = AircraftArchive::Importer.new(path, owner: @owner, tail_number: "N54321").run[:aircraft] + copied = copy.logbook_entries.sole + assert_equal [ "Engine", 2645.9 ], [ copied.component.component_type.name, copied.component_hours_at_entry.to_f ] + assert_equal [ [ "Oil filter", 110.5, 10.5 ] ], copied.parts.map { [ _1.component.component_type.name, _1.hours_at_entry.to_f, _1.since_overhaul_at_entry.to_f ] } + assert_equal copied.component, copied.parts.sole.component.parent_component + end +end