Editable logbook templates; component times follow the airframe time

- Templates move to the database (Admin -> Logbook templates: add, edit,
  delete, restore the built-in ones). The built-in preventive maintenance
  set is added once on first use; deletions stick. A template can set the
  entry type, logbook (picking the matching component) and certificate
- Template list shows "Name — Part 43 App. A (c)(6), (c)(23)" instead of
  the doubled parentheses
- Component total time and time since overhaul are worked out from the
  entry's airframe total time (current times shifted by the difference);
  blank when the entry predates the overhaul; typing them stops the
  automatic updates

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-07 11:40:23 -05:00
1 parent a51f78ebf3
commit 72e1d7760f
22 files changed
+366 -74

No files matched your search

@@ -0,0 +1,48 @@
class Admin::LogbookTemplatesController < ApplicationController
before_action :require_admin!
before_action :set_template, only: %i[edit update destroy]
def index
LogbookTemplate.ensure_defaults!
@templates = LogbookTemplate.ordered
end
def new
@template = LogbookTemplate.new(position: (LogbookTemplate.maximum(:position) || 0) + 1)
end
def create
@template = LogbookTemplate.new(template_params)
if @template.save
redirect_to admin_logbook_templates_path, notice: "Template added."
else
render :new, status: :unprocessable_entity
end
end
def edit; end
def update
if @template.update(template_params)
redirect_to admin_logbook_templates_path, notice: "Template updated."
else
render :edit, status: :unprocessable_entity
end
end
def destroy
@template.destroy!
redirect_to admin_logbook_templates_path, notice: "Template deleted."
end
def restore
added = LogbookTemplate.restore_defaults!
redirect_to admin_logbook_templates_path, notice: added.positive? ? "Restored #{helpers.pluralize(added, 'built-in template')}." : "All the built-in templates are already here."
end
private
def set_template = @template = LogbookTemplate.find(params[:id])
def template_params = params.require(:logbook_template).permit(:name, :reference, :text, :entry_type, :log_type, :certificate_type, :position)
end
+3 -3
View File
@@ -2,18 +2,18 @@ class Admin::SettingsController < ApplicationController
before_action :require_admin!
def edit
@values = Setting::INTEGERS.keys.index_with { Setting.integer(_1) }
@values = { "max_upload_mb" => Setting.max_upload_mb }
end
def update
submitted = params.fetch(:settings, {}).permit(*Setting::INTEGERS.keys).to_h
submitted = params.fetch(:settings, {}).permit(:max_upload_mb).to_h
records = Setting.update_integers(submitted)
@errors = records.flat_map { _1.errors.full_messages }
if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: "Settings saved."
else
@values = Setting::INTEGERS.keys.index_with { Setting.integer(_1) }.merge(submitted)
@values = { "max_upload_mb" => Setting.max_upload_mb }.merge(submitted)
render :edit, status: :unprocessable_entity
end
end
@@ -26,6 +26,7 @@ class LogbookEntriesController < ApplicationController
def show; end
def new
LogbookTemplate.ensure_defaults!
@entry = @aircraft.logbook_entries.new(date: Date.current, aircraft_hours_at_entry: @aircraft.current_hours)
end
@@ -1,10 +1,16 @@
import { Controller } from "@hotwired/stimulus"
// Logbook entry form: picking an engine or propeller log selects that
// component (if none is chosen yet), and picking a component fills in its
// current total time and time since overhaul.
// component (if none is chosen yet), and the component's total time and time
// 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).
export default class extends Controller {
static targets = [ "logType", "component", "total", "since" ]
static targets = [ "logType", "component", "total", "since", "airframe" ]
static values = { aircraftHours: Number }
connect() { this.manual = false }
logTypeChanged() {
if (this.componentTarget.value) return
@@ -17,9 +23,25 @@ export default class extends Controller {
}
componentChanged() {
this.manual = false
this.recompute()
}
airframeChanged() {
if (!this.manual) this.recompute()
}
markManual() { this.manual = true }
recompute() {
const option = this.componentTarget.selectedOptions[0]
if (!option?.dataset.total) return
this.totalTarget.value = option.dataset.total
this.sinceTarget.value = option.dataset.since
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
// 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) : ""
}
}
@@ -1,18 +1,23 @@
import { Controller } from "@hotwired/stimulus"
// Fills a new logbook entry from a preventive maintenance template: the
// wording, the entry type, and "pilot" as the kind of certificate unless one
// is already chosen.
// Fills a new logbook entry from a template: the wording, and when the
// template sets them, the entry type, the logbook (which also picks the
// matching component) and the kind of certificate, unless one is chosen.
export default class extends Controller {
static targets = [ "template", "text", "entryType", "certificate" ]
static targets = [ "template", "text", "entryType", "logType", "certificate" ]
apply() {
const option = this.templateTarget.selectedOptions[0]
if (!option?.dataset.text) return
if (this.textTarget.value.trim() && !confirm("Replace the entry text with this template?")) return
this.textTarget.value = option.dataset.text
if (this.hasEntryTypeTarget) this.entryTypeTarget.value = "MAINTENANCE"
if (this.hasCertificateTarget && !this.certificateTarget.value) this.certificateTarget.value = "PILOT" // keep a chosen certificate
const { text, entryType, logType, certificate } = option.dataset
this.textTarget.value = text
if (entryType && this.hasEntryTypeTarget) this.entryTypeTarget.value = entryType
if (logType && this.hasLogTypeTarget && this.logTypeTarget.value !== logType) {
this.logTypeTarget.value = logType
this.logTypeTarget.dispatchEvent(new Event("change", { bubbles: true }))
}
if (certificate && this.hasCertificateTarget && !this.certificateTarget.value) this.certificateTarget.value = certificate
this.textTarget.focus()
}
}
+37
View File
@@ -0,0 +1,37 @@
# Wording to start a logbook entry from (Admin → Logbook templates). Picking
# one on the entry form fills the text and, when set, the entry type, the
# logbook and the kind of certificate.
class LogbookTemplate < ApplicationRecord
DEFAULTS_FILE = Rails.root.join("config/logbook_templates.yml")
validates :name, :text, presence: true
validates :entry_type, inclusion: { in: LogbookEntry::ENTRY_TYPES.keys }
validates :log_type, inclusion: { in: LogbookEntry::LOG_TYPES.keys }, allow_blank: true
validates :certificate_type, inclusion: { in: LogbookEntry::CERTIFICATE_TYPES.keys }, allow_blank: true
normalizes :log_type, :certificate_type, :reference, with: ->(v) { v.strip.presence }
scope :ordered, -> { order(:position, :name) }
def label = reference.present? ? "#{name} — #{reference}" : name
def self.defaults = YAML.safe_load_file(DEFAULTS_FILE)
# Adds the built-in templates that aren't here (matched by name). Returns
# how many were added.
def self.restore_defaults!
existing = pluck(:name).to_set
next_position = (maximum(:position) || 0) + 1
added = defaults.reject { existing.include?(_1["name"]) }
added.each_with_index { |d, i| create!(d.slice("name", "reference", "text", "log_type", "certificate_type").merge("position" => next_position + i)) }
added.size
end
# The built-in set, once: after that, admins' deletions stick.
def self.ensure_defaults!
return if Setting.integer("logbook_templates_seeded") == 1
transaction do
restore_defaults!
Setting.update_integers("logbook_templates_seeded" => "1")
end
end
end
-37
View File
@@ -1,37 +0,0 @@
# Logbook wording for common preventive maintenance a pilot-owner may do
# (14 CFR 43.3(g)), keyed to Part 43 Appendix A paragraph (c). The item
# descriptions are paraphrased; the rule sets each item's limits.
module PreventiveMaintenance
Item = Data.define(:key, :paragraphs, :label, :work)
ITEMS = [
Item.new("oil_change", %w[(c)(6) (c)(23)], "Oil and filter change", "Drained engine oil and replaced the oil filter. Cut open and inspected the filter: no metal found. Refilled with __ qt of __. Ran engine and checked for leaks."),
Item.new("tire", %w[(c)(1)], "Tire removal, installation or repair", "Removed and replaced the __ tire and tube. Inflated to __ psi."),
Item.new("strut", %w[(c)(3)], "Servicing landing gear shock struts", "Serviced the __ shock strut with __."),
Item.new("bearings", %w[(c)(4)], "Servicing wheel bearings", "Cleaned, inspected and repacked the __ wheel bearings with __ grease."),
Item.new("safety_wire", %w[(c)(5)], "Replacing safety wire or cotter keys", "Replaced defective safety wire / cotter key at __."),
Item.new("lubrication", %w[(c)(6)], "Lubrication", "Lubricated __ per the maintenance manual."),
Item.new("hydraulic", %w[(c)(8)], "Replenishing hydraulic fluid", "Replenished the hydraulic reservoir with __."),
Item.new("upholstery", %w[(c)(11)], "Repairing upholstery", "Repaired the upholstery of __."),
Item.new("fairings", %w[(c)(12)], "Small repairs to fairings or cowlings", "Made a small repair to the __ (non-structural, contour unchanged)."),
Item.new("seat_belts", %w[(c)(14)], "Replacing safety belts", "Replaced the __ safety belt with P/N __."),
Item.new("landing_light_wiring", %w[(c)(16)], "Repairing landing light circuits", "Troubleshot and repaired a broken circuit in the landing light wiring."),
Item.new("lights", %w[(c)(17)], "Replacing light bulbs, reflectors or lenses", "Replaced the __ position/landing light bulb with P/N __. Checked operation."),
Item.new("cowling", %w[(c)(19)], "Replacing a cowling", "Removed and reinstalled the __ cowling."),
Item.new("spark_plugs", %w[(c)(20)], "Cleaning or replacing spark plugs", "Removed, cleaned, gapped and rotated the spark plugs. Reinstalled and torqued to __."),
Item.new("hoses", %w[(c)(21)], "Replacing hose connections (not hydraulic)", "Replaced the __ hose with P/N __."),
Item.new("fuel_lines", %w[(c)(22)], "Replacing prefabricated fuel lines", "Replaced the prefabricated fuel line __ with P/N __."),
Item.new("filters", %w[(c)(23)], "Cleaning or replacing fuel/oil strainers or filters", "Cleaned / replaced the __ strainer / filter element."),
Item.new("battery", %w[(c)(24)], "Replacing or servicing the battery", "Replaced the battery with P/N __ / serviced the battery."),
Item.new("fasteners", %w[(c)(26)], "Replacing non-structural fasteners", "Replaced non-structural standard fasteners at __."),
Item.new("chip_detector", %w[(c)(29)], "Checking magnetic chip detectors", "Removed, checked and reinstalled the magnetic chip detector: no particles found."),
Item.new("nav_database", %w[(c)(31)], "Updating the navigation database", "Updated the __ navigation database to cycle __."),
Item.new("nav_com", %w[(c)(32)], "Swapping a tray-mounted nav/com unit", "Removed and reinstalled the tray-mounted __ unit. Checked operation.")
].freeze
module_function
def text_for(item)
"#{item.work} Preventive maintenance per 14 CFR 43.3(g), Part 43 Appendix A paragraph #{item.paragraphs.to_sentence}."
end
end
+2 -1
View File
@@ -6,7 +6,8 @@
# Setting.max_upload_bytes # => 52428800
class Setting < ApplicationRecord
INTEGERS = {
"max_upload_mb" => { default: 50, in: 1..1024, label: "Maximum upload size (MB)" }
"max_upload_mb" => { default: 50, in: 1..1024, label: "Maximum upload size (MB)" },
"logbook_templates_seeded" => { default: 0, in: 0..1, label: "Built-in logbook templates added" } # internal flag
}.freeze
validates :key, presence: true, uniqueness: true, inclusion: { in: INTEGERS.keys }
@@ -0,0 +1,17 @@
<%= form_with model: [ :admin, template ], class: "card card-body max-w-3xl space-y-4" do |f| %>
<%= f.errors_summary %>
<div class="grid gap-4 sm:grid-cols-2">
<%= f.field :name, required: true, placeholder: "Oil and filter change" %>
<%= f.field :reference, placeholder: "Part 43 App. A (c)(6)", hint: "Shown next to the name, e.g. the regulation or manual paragraph." %>
</div>
<%= f.field :text, as: :textarea, rows: 5, required: true, hint: "The entry text. Use __ for blanks to fill in (quantities, part numbers…)." %>
<div class="grid gap-4 sm:grid-cols-4">
<%= f.field :entry_type, as: :select, label: "Entry type", collection: LogbookEntry::ENTRY_TYPES.invert %>
<%= f.field :log_type, as: :select, label: "Logbook", include_blank: "— Leave as is —", collection: LogbookEntry::LOG_TYPES.invert %>
<%= f.field :certificate_type, as: :select, label: "Kind of certificate", include_blank: "— Leave as is —", collection: LogbookEntry::CERTIFICATE_TYPES.invert,
hint: "Only filled in when none is chosen yet." %>
<%= f.field :position, as: :number, label: "Order" %>
</div>
<div class="flex gap-2"><%= f.submit "Save Template" %><%= link_to "Cancel", admin_logbook_templates_path, class: "btn-secondary" %></div>
<% end %>
<% if template.persisted? %><div class="mt-4"><%= delete_button "Delete template", admin_logbook_template_path(template) %></div><% end %>
@@ -0,0 +1,3 @@
<% content_for :title, "Logbook template" %>
<h1 class="mb-4 text-2xl font-bold">Logbook template</h1>
<%= render "form", template: @template %>
@@ -0,0 +1,27 @@
<% content_for :title, "Logbook templates" %>
<div class="mb-4 flex flex-wrap items-center justify-between gap-2">
<h1 class="text-2xl font-bold">Logbook templates</h1>
<div class="flex gap-2">
<%= button_to "Restore built-in templates", restore_admin_logbook_templates_path, class: "btn-secondary", title: "Add back any of the built-in preventive maintenance templates that were deleted" %>
<%= link_to "+ New Template", new_admin_logbook_template_path, class: "btn-primary" %>
</div>
</div>
<p class="mb-4 text-sm text-slate-600">Wording to start a logbook entry from: the "Template" list on a new entry. Use __ for blanks to fill in.</p>
<section class="card">
<% if @templates.any? %>
<ul class="divide-y divide-slate-100">
<% @templates.each do |t| %>
<li class="flex flex-wrap items-start justify-between gap-3 px-4 py-3">
<div class="min-w-0 flex-1 text-sm">
<div class="font-medium"><%= t.name %><% if t.reference.present? %> <span class="font-normal text-slate-500">— <%= t.reference %></span><% end %></div>
<div class="text-xs text-slate-500"><%= [ LogbookEntry::ENTRY_TYPES[t.entry_type], (t.log_type && "#{LogbookEntry::LOG_TYPES[t.log_type]} log"), (t.certificate_type && LogbookEntry::CERTIFICATE_TYPES[t.certificate_type]) ].compact.join(" · ") %></div>
<p class="mt-1 text-xs text-slate-600"><%= t.text.truncate(220) %></p>
</div>
<%= link_to "Edit", edit_admin_logbook_template_path(t), class: "btn-secondary btn-sm" %>
</li>
<% end %>
</ul>
<% else %>
<%= empty_state "No templates." %>
<% end %>
</section>
@@ -0,0 +1,3 @@
<% content_for :title, "Logbook template" %>
<h1 class="mb-4 text-2xl font-bold">Logbook template</h1>
<%= render "form", template: @template %>
+2 -2
View File
@@ -37,7 +37,7 @@
<%= link_to "Profile", edit_profile_path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
<% if current_user.admin? %>
<p class="border-t border-slate-100 px-4 pt-2 pb-1 text-xs font-semibold text-slate-500">Admin</p>
<% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %>
<% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Logbook Templates", admin_logbook_templates_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %>
<%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %>
<% end %>
<% end %>
@@ -53,7 +53,7 @@
Admin <span aria-hidden="true" class="text-xs">▾</span>
</summary>
<div class="absolute right-0 z-30 mt-2 w-48 rounded-md bg-surface py-1 text-slate-700 shadow-lg ring-1 ring-slate-200">
<% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %>
<% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Logbook Templates", admin_logbook_templates_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %>
<%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %>
<% end %>
</div>
@@ -10,7 +10,9 @@
{}, class: "input", data: { component_times_target: "component", action: "component-times#componentChanged" } %>
<p class="hint">For engine and propeller logs: printed with its serial number and times.</p>
</div>
<%= f.field :component_hours_at_entry, as: :number, step: 0.1, label: "Component total time", data: { component_times_target: "total" } %>
<%= f.field :component_since_overhaul_at_entry, as: :number, step: 0.1, label: "Since overhaul", data: { component_times_target: "since" },
hint: "Filled in from the component; correct them for an older entry." %>
<%= f.field :component_hours_at_entry, as: :number, step: 0.1, label: "Component total time",
data: { component_times_target: "total", action: "input->component-times#markManual" } %>
<%= f.field :component_since_overhaul_at_entry, as: :number, step: 0.1, label: "Since overhaul",
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>
+11 -8
View File
@@ -1,23 +1,26 @@
<%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl", data: { controller: "entry-template signer component-times" } do |f| %>
<%= form_with model: [aircraft, entry], class: "card card-body space-y-4 max-w-3xl", data: { controller: "entry-template signer component-times", component_times_aircraft_hours_value: aircraft.current_hours.to_f } do |f| %>
<%= f.errors_summary %>
<% if entry.new_record? %>
<% templates = entry.new_record? ? LogbookTemplate.ordered.to_a : [] %>
<% if templates.any? %>
<div>
<%= label_tag :template, "Preventive maintenance template", class: "label" %>
<%= label_tag :template, "Template", class: "label" %>
<select id="template" class="input" data-entry-template-target="template" data-action="entry-template#apply">
<option value="">— Write it yourself —</option>
<% PreventiveMaintenance::ITEMS.each do |item| %>
<option value="<%= item.key %>" data-text="<%= PreventiveMaintenance.text_for(item) %>"><%= item.label %> (<%= item.paragraphs.join(", ") %>)</option>
<% templates.each do |t| %>
<option value="<%= t.id %>" data-text="<%= t.text %>" data-entry-type="<%= t.entry_type %>" data-log-type="<%= t.log_type %>"
data-certificate="<%= t.certificate_type %>"><%= t.label %></option>
<% end %>
</select>
<p class="hint">For a pilot doing preventive maintenance on an aircraft they own or operate (14 CFR 43.3(g)). Fill in the blanks (__) and add your name and pilot certificate number. The item list is paraphrased from Part 43 Appendix A(c); the rule sets each item's limits.</p>
<p class="hint">Fill in the blanks (__). The built-in ones are for a pilot doing preventive maintenance on an aircraft they own or operate (14 CFR 43.3(g)); their wording is paraphrased from Part 43 Appendix A(c), which sets each item's limits.<% if current_user.admin? %> <%= link_to "Edit templates", admin_logbook_templates_path, class: "link" %><% end %></p>
</div>
<% end %>
<div class="grid gap-4 sm:grid-cols-4">
<%= f.field :date, as: :date %>
<%= f.field :log_type, as: :select, label: "Logbook", collection: LogbookEntry::LOG_TYPES.invert,
data: { component_times_target: "logType", action: "component-times#logTypeChanged" } %>
data: { component_times_target: "logType", entry_template_target: "logType", action: "component-times#logTypeChanged" } %>
<%= f.field :entry_type, as: :select, label: "Entry type", collection: LogbookEntry::ENTRY_TYPES.invert, data: { entry_template_target: "entryType" } %>
<%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: "Airframe total time" %>
<%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: "Airframe total time",
data: { component_times_target: "airframe", action: "input->component-times#airframeChanged" } %>
</div>
<%= render "logbook_entries/component_fields", f: f, aircraft: aircraft %>
<%= f.field :text, as: :textarea, label: "Entry text", rows: 8, data: { entry_template_target: "text" } %>
+4 -2
View File
@@ -19,7 +19,8 @@
<label class="flex items-center gap-2"><%= radio_button_tag :logbook, "none", choice == "none" %> No logbook entry (e.g. it wasn't a defect)</label>
</fieldset>
<div class="space-y-4 rounded-md border border-slate-200 p-3" data-controller="signer component-times">
<div class="space-y-4 rounded-md border border-slate-200 p-3" data-controller="signer component-times"
data-component-times-aircraft-hours-value="<%= @aircraft.current_hours.to_f %>">
<p class="text-xs text-slate-500">For a new entry. 14 CFR 43.9: what was done, the date, and the name, certificate number and kind of certificate of whoever approved the return to service.</p>
<%= render "shared/sign_as" %>
<%= fields_for :logbook_entry, @entry do |f| %>
@@ -27,7 +28,8 @@
<%= f.field :date, as: :date %>
<%= f.field :log_type, as: :select, label: "Logbook", collection: LogbookEntry::LOG_TYPES.invert,
data: { component_times_target: "logType", action: "component-times#logTypeChanged" } %>
<%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: "Airframe total time" %>
<%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: "Airframe total time",
data: { component_times_target: "airframe", action: "input->component-times#airframeChanged" } %>
</div>
<%= render "logbook_entries/component_fields", f: f, aircraft: @aircraft %>
<%= f.field :text, as: :textarea, label: "Work performed", rows: 3 %>