diff --git a/README.md b/README.md index 46933dc..2619f44 100644 --- a/README.md +++ b/README.md @@ -94,18 +94,20 @@ To back up or move a single aircraft with all its files, use **Access & Sharing | Area | Notes | |---|---| | Fleet dashboard | Every aircraft you can access, with airworthiness status and its top issues. | -| Airworthiness | RED/ORANGE/GREEN from AD compliance, grounding squawks, inspection recurrency, and replacement-critical components. Warnings start 10 hours or 30 days ahead. Logic: `app/services/airworthiness.rb`, `app/services/compliance.rb`. | -| Hours | Absolute tach/hobbs updates or per-flight logs. Both apply the delta to every in-service component. Downward corrections are clamped at 0. | +| Airworthiness | Grounded / limited (e.g. "VFR only" for an overdue 91.411 check) / due soon / current, from AD compliance, grounding squawks, inspections, replacement-critical and expiring parts, and expiring documents (an expired registration grounds). Warnings start 10 hours or 30 days ahead. The pilot in command still decides airworthiness (91.7). Logic: `app/services/airworthiness.rb`, `app/services/compliance.rb`. | +| Hours | Absolute tach/hobbs updates or per-flight logs. Both apply the delta to every in-service component. Downward corrections are clamped at 0. Each aircraft picks tach or Hobbs as its maintenance clock (time in service). | | Flight import | Owners can import historical flights from `.xlsx` or `.csv` (Date, From, To, Tach, Hobbs, Oil Added, Fuel Added). Each flight's time is derived from the previous row's reading. A preview flags typos such as a tach going backwards, and rows already imported are skipped. History only: component hours aren't changed unless you choose to advance the aircraft's meters. | -| Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is RED. | +| Airworthiness enforcement | Optional per aircraft. It blocks flight logs and hours updates while the aircraft is grounded (not for limitations). | | Components | Tree of parent and child parts, TBO and replacement limits, and service/replace reset. Owners can create new component types inline. | -| Squawks | Four priorities. "Ground Aircraft" makes the aircraft RED. Supports attachments, resolve, and reopen. | -| ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, per-aircraft "not applicable" determinations, and compliance history. | +| Squawks | Four priorities. "Ground Aircraft" grounds the aircraft. Inoperative items can be deferred under 91.213(d) after confirming each condition; resolving can record the fix as a logbook entry. Attachments, reopen. | +| ADs and bulletins | Shared across aircraft and applicable to the airframe or to specific components. Hour- and month-based recurrence (due at end of month), conditional and non-mandatory types, per-aircraft "not applicable" determinations, and compliance history with method of compliance and the revision complied with. | | 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. | -| Logbook | Maintenance entries with search and a link to a scanned document page. | -| Documents | Collections, multi-file documents with a page viewer, and per-document share visibility. | +| 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. | +| 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. | +| Status report | A printable maintenance status (91.417(a)(2)): total times, life-limited parts, time since overhaul, inspections, ADs with method and revision, major alterations, open discrepancies. Also on maintenance share links. | +| Reminders | A Monday email to owners when something is overdue or coming due (needs SMTP; users can turn it off). | | Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). | | Activity log | Every write is recorded as an `AircraftEvent`. | | Access | Admin, owner, and pilot roles, plus share links (Status or Maintenance privilege, optional expiry, at most 10 per aircraft). | diff --git a/app/controllers/admin/about_controller.rb b/app/controllers/admin/about_controller.rb index f7fd396..ec51dac 100644 --- a/app/controllers/admin/about_controller.rb +++ b/app/controllers/admin/about_controller.rb @@ -1,11 +1,23 @@ class Admin::AboutController < ApplicationController before_action :require_admin! - rate_limit to: 5, within: 1.minute, only: :test_email, with: -> { redirect_to admin_about_path, alert: "Try again in a minute." } + rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder], with: -> { redirect_to admin_about_path, alert: "Try again in a minute." } def show @info = SystemInfo.new end + # This week's reminder for the current admin, now. + def test_reminder + return redirect_to(admin_about_path, alert: "Email isn't set up yet.") unless MailSettings.configured? + if ReminderMailer.items_for(current_user).empty? + return redirect_to admin_about_path, notice: "Nothing needs attention on the aircraft you own, so there's no reminder to send." + end + ReminderMailer.weekly(current_user).deliver_now + redirect_to admin_about_path, notice: "Reminder sent to #{current_user.email_address}." + rescue StandardError => e + redirect_to admin_about_path, alert: "Sending failed: #{e.class.name.demodulize}: #{e.message.to_s.squish.truncate(240)}" + end + # Sends right away (not via the job queue) so problems show up here. def test_email unless MailSettings.configured? diff --git a/app/controllers/components_controller.rb b/app/controllers/components_controller.rb index cc9489a..3abbdd6 100644 --- a/app/controllers/components_controller.rb +++ b/app/controllers/components_controller.rb @@ -78,7 +78,7 @@ class ComponentsController < ApplicationController :install_location, :notes, :status, :date_in_service, :hours_in_service, :hours_since_overhaul, :overhaul_date, :tbo_hours, :tbo_days, :inspection_hours, :inspection_days, :replacement_hours, :replacement_days, :tbo_critical, :on_condition, - :inspection_critical, :replacement_critical + :inspection_critical, :replacement_critical, :expires_on ).tap do |p| # Owners can create a component type inline instead of asking an admin. if (name = params[:new_component_type].to_s.strip).present? diff --git a/app/controllers/documents_controller.rb b/app/controllers/documents_controller.rb index d943a77..c3abff0 100644 --- a/app/controllers/documents_controller.rb +++ b/app/controllers/documents_controller.rb @@ -126,7 +126,7 @@ class DocumentsController < ApplicationController def set_document = @document = @aircraft.documents.find(params[:id]) def document_params - p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, pages: []) + p = params.require(:document).permit(:name, :description, :doc_type, :visibility, :document_collection_id, :expires_on, pages: []) p[:pages]&.compact_blank! p.delete(:pages) if p[:pages].blank? p[:document_collection_id] = scoped_id(@aircraft.document_collections, p[:document_collection_id]) diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index 16a6729..0bd37e6 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -7,7 +7,7 @@ class ProfilesController < ApplicationController # left open somewhere can't be turned into a takeover of the account. def update @user = current_user - attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation) + attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation, :reminder_emails) attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? new_email = User.normalize_value_for(:email_address, attrs[:email_address].to_s) if attrs.key?(:email_address) sensitive = (new_email && new_email != @user.email_address) || attrs.key?(:password) diff --git a/app/controllers/squawks_controller.rb b/app/controllers/squawks_controller.rb index 06c7d85..2e83702 100644 --- a/app/controllers/squawks_controller.rb +++ b/app/controllers/squawks_controller.rb @@ -1,12 +1,13 @@ class SquawksController < ApplicationController include AircraftScoped - # Pilots may create squawks; editing/resolving needs an owner. - before_action :require_owner!, except: %i[index new create] - before_action :set_squawk, only: %i[edit update destroy resolve reopen] + # Pilots may create squawks and defer inoperative items (91.213(d) lets the + # pilot decide); editing and resolving need an owner. + before_action :require_owner!, except: %i[index new create deferral defer] + before_action :set_squawk, only: %i[edit update destroy resolution resolve reopen deferral defer undefer] def index @active = @aircraft.squawks.active.by_priority.includes(:component, :reported_by).with_attached_attachments - @resolved = @aircraft.squawks.resolved.order(resolved_at: :desc).includes(:component).with_attached_attachments.limit(100) + @resolved = @aircraft.squawks.resolved.order(resolved_at: :desc).includes(:component, :logbook_entry).with_attached_attachments.limit(100) end def new @@ -36,10 +37,45 @@ class SquawksController < ApplicationController end end + # Resolve form: record the fix in the logbook (who returned it to + # service, 43.9), link an existing entry, or just close the squawk. + def resolution + @entry = @aircraft.logbook_entries.new(date: Date.current, entry_type: "MAINTENANCE", log_type: "AC", + aircraft_hours_at_entry: @aircraft.current_hours, + text: "Corrected: #{@squawk.issue_reported}") + end + def resolve - @squawk.resolve!(notes: params[:resolution_notes]) + entry = + case params[:logbook] + when "new" + @entry = @aircraft.logbook_entries.new(resolution_entry_params.merge(entry_type: "MAINTENANCE")) + return render(:resolution, status: :unprocessable_entity) unless @entry.save + log_event("logbook", "Logbook entry added: #{@entry.date}") + @entry + when "existing" then @aircraft.logbook_entries.find_by(id: params[:logbook_entry_id]) + end + @squawk.resolve!(notes: params[:resolution_notes], logbook_entry: entry) log_event("squawk", "Squawk resolved", notes: @squawk.issue_reported.truncate(200)) - redirect_back fallback_location: aircraft_squawks_path(@aircraft), notice: "Squawk resolved." + redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk resolved#{' and recorded in the logbook' if entry}." + end + + def deferral; end + + def defer + if @squawk.defer(checks: params[:checks], name: params[:deferred_by_name], role: params[:deferred_by_role], + action: params[:deferral_action], notes: params[:deferral_notes]) + log_event("squawk", "Inoperative item deferred (91.213(d))", notes: @squawk.issue_reported.truncate(200)) + redirect_to aircraft_squawks_path(@aircraft), notice: "Deferred. Keep the placard in place until it's fixed." + else + render :deferral, status: :unprocessable_entity + end + end + + def undefer + @squawk.undefer! + log_event("squawk", "Deferral removed", notes: @squawk.issue_reported.truncate(200)) + redirect_to aircraft_squawks_path(@aircraft), notice: "Deferral removed." end def reopen @@ -58,6 +94,11 @@ class SquawksController < ApplicationController def set_squawk = @squawk = @aircraft.squawks.find(params[:id]) + def resolution_entry_params + params.require(:logbook_entry).permit(:date, :log_type, :text, :aircraft_hours_at_entry, :signoff_person, + :signoff_certificate_type, :signoff_certificate_number, :signoff_location) + end + # Adds uploads and drops ticked files in one change, so nothing is saved # (or purged) unless the whole update validates. def change_attachments diff --git a/app/controllers/standard_inspections_controller.rb b/app/controllers/standard_inspections_controller.rb new file mode 100644 index 0000000..0b6a1f8 --- /dev/null +++ b/app/controllers/standard_inspections_controller.rb @@ -0,0 +1,16 @@ +class StandardInspectionsController < ApplicationController + include AircraftScoped + before_action :require_owner! + + def new; end + + def create + added = StandardInspections.add!(@aircraft, params[:templates]) + if added.any? + log_event("inspection", "Standard inspections added", notes: added.map(&:name).join(", ")) + redirect_to aircraft_inspections_path(@aircraft), notice: "Added #{added.map(&:name).to_sentence}. Record when each was last done to see when it's next due." + else + redirect_to new_aircraft_standard_inspections_path(@aircraft), alert: "Nothing new was chosen." + end + end +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index c36d80f..d50f4b6 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -8,7 +8,7 @@ module ApplicationHelper value ? l(value.to_date, format: :long) : "—" end - AIRWORTHINESS_COLORS = { "RED" => "red", "LIMITED" => "blue", "ORANGE" => "orange", "GREEN" => "green" }.freeze + AIRWORTHINESS_COLORS = { "RED" => "red", "LIMITED" => "blue", "ORANGE" => "orange", "GREEN" => "green", "INFO" => "gray" }.freeze def airworthiness_badge(status, large: false) tag.span(status.label, class: [ "badge-#{AIRWORTHINESS_COLORS[status.status]}", ("text-sm px-3 py-1" if large) ], @@ -24,7 +24,7 @@ module ApplicationHelper def issue_badge_class(issue) = "badge-#{AIRWORTHINESS_COLORS[issue.severity]}" def issue_text_class(issue) - { "RED" => "text-red-700", "LIMITED" => "text-sky-700" }.fetch(issue.severity, "text-amber-700") + { "RED" => "text-red-700", "LIMITED" => "text-sky-700", "INFO" => "text-slate-600" }.fetch(issue.severity, "text-amber-700") end COMPLIANCE_BADGES = { diff --git a/app/jobs/weekly_reminder_job.rb b/app/jobs/weekly_reminder_job.rb new file mode 100644 index 0000000..b31febb --- /dev/null +++ b/app/jobs/weekly_reminder_job.rb @@ -0,0 +1,15 @@ +# Weekly email to aircraft owners listing what's overdue or coming due +# (inspections, ADs, components, expiring documents) and deferred items. +# Nothing is sent when nothing needs attention, or when email isn't set up. +class WeeklyReminderJob < ApplicationJob + queue_as :default + + def perform + return unless MailSettings.configured? + User.where(reminder_emails: true).find_each do |user| + ReminderMailer.weekly(user).deliver_now if ReminderMailer.items_for(user).any? + rescue StandardError => e + Rails.logger.warn("[reminders] #{user.id}: #{e.class}: #{e.message}") + end + end +end diff --git a/app/mailers/reminder_mailer.rb b/app/mailers/reminder_mailer.rb new file mode 100644 index 0000000..50642e4 --- /dev/null +++ b/app/mailers/reminder_mailer.rb @@ -0,0 +1,15 @@ +class ReminderMailer < ApplicationMailer + # [[aircraft, issues], …] for the aircraft the user owns that need attention. + def self.items_for(user) + Aircraft.joins(:roles).where(aircraft_roles: { user_id: user.id, role: "owner" }).ordered + .map { [ _1, _1.airworthiness.issues ] }.reject { _2.empty? } + end + + def weekly(user) + @user = user + @items = self.class.items_for(user) + overdue = @items.sum { |_, issues| issues.count { _1.severity.in?(%w[RED LIMITED]) } } + subject = overdue.positive? ? "#{overdue} #{'item'.pluralize(overdue)} overdue" : "Maintenance coming due" + mail subject: "#{subject}: #{@items.map { _1.first.tail_number }.to_sentence}", to: user.email_address + end +end diff --git a/app/models/component.rb b/app/models/component.rb index 71f1f92..ca89326 100644 --- a/app/models/component.rb +++ b/app/models/component.rb @@ -34,6 +34,9 @@ class Component < ApplicationRecord replacement_hours - hours_since_overhaul if replacement_hours end + # Past the date marked on the part (it may be used through that date). + def expired?(today = Date.current) = expires_on.present? && today > expires_on + def next_replacement_date overhaul_date + replacement_days.days if replacement_days && overhaul_date end @@ -49,6 +52,7 @@ class Component < ApplicationRecord statuses << rank(Date.current >= d, Date.current + Airworthiness::DAYS_WARNING >= d) end end + statuses << rank(expired?, Date.current + Airworthiness::DAYS_WARNING >= expires_on) if expires_on if tbo_critical? && tbo_hours && !on_condition? statuses << rank(hours_to_tbo <= 0, hours_to_tbo <= Airworthiness::HOURS_WARNING * 5) end diff --git a/app/models/document.rb b/app/models/document.rb index 92f5bba..f214c52 100644 --- a/app/models/document.rb +++ b/app/models/document.rb @@ -4,8 +4,14 @@ class Document < ApplicationRecord TYPES = { "LOG" => "Logbook", "ALTER" => "Alteration Record", "REPORT" => "Report", "ESTIMATE" => "Estimate", "DISC" => "Discrepancy List", "INVOICE" => "Receipt / Invoice", - "AIRCRAFT" => "Aircraft Record", "OTHER" => "Other" + "AIRCRAFT" => "Aircraft Record", "REGISTRATION" => "Registration Certificate", + "AIRWORTHINESS_CERT" => "Airworthiness Certificate", "INSURANCE" => "Insurance Policy", + "RADIO" => "Radio Station License", "OTHER" => "Other" }.freeze + # An expired registration means the aircraft may not be flown (14 CFR + # 91.203(a)(2)); renewal takes a while, so warn earlier. + GROUNDING_EXPIRY_TYPES = %w[REGISTRATION].freeze + EXPIRY_WARNING_DAYS = { "REGISTRATION" => 90 }.freeze belongs_to :aircraft belongs_to :document_collection, optional: true @@ -19,9 +25,12 @@ class Document < ApplicationRecord normalizes :visibility, with: ->(v) { v.presence } scope :ordered, -> { order(:name) } + scope :expiring, -> { where.not(expires_on: nil) } def to_s = name def type_label = TYPES[doc_type] + def expired?(today = Date.current) = expires_on.present? && today > expires_on + def expiry_warning_days = EXPIRY_WARNING_DAYS.fetch(doc_type, 30) # nil visibility inherits from the collection; uncollected docs default to private. def effective_visibility diff --git a/app/models/inspection_type.rb b/app/models/inspection_type.rb index cf9d19e..0f2ab7a 100644 --- a/app/models/inspection_type.rb +++ b/app/models/inspection_type.rb @@ -6,6 +6,9 @@ class InspectionType < ApplicationRecord "no_transponder" => "Transponder can't be used (91.413)", "advisory" => "Advisory only" }.freeze + # In a sentence: "Overdue: no IFR." + EFFECT_SUMMARIES = { "grounds" => "grounds the aircraft", "no_ifr" => "no IFR", "no_transponder" => "transponder can't be used", + "advisory" => "advisory only" }.freeze # Short form for the airworthiness status ("VFR only"). LIMITATIONS = { "no_ifr" => "VFR only", "no_transponder" => "No transponder" }.freeze diff --git a/app/models/logbook_entry.rb b/app/models/logbook_entry.rb index 113bb37..0a842f4 100644 --- a/app/models/logbook_entry.rb +++ b/app/models/logbook_entry.rb @@ -23,6 +23,7 @@ class LogbookEntry < ApplicationRecord belongs_to :document, optional: true has_many :inspection_records, dependent: :nullify has_many :ad_compliances, dependent: :nullify + has_many :squawks, dependent: :nullify validates :date, :text, presence: true validates :log_type, inclusion: { in: LOG_TYPES.keys } diff --git a/app/models/squawk.rb b/app/models/squawk.rb index 4a02a71..85f3bd9 100644 --- a/app/models/squawk.rb +++ b/app/models/squawk.rb @@ -7,6 +7,7 @@ class Squawk < ApplicationRecord belongs_to :aircraft belongs_to :component, optional: true belongs_to :reported_by, class_name: "User", optional: true + belongs_to :logbook_entry, optional: true has_many_attached :attachments validates :priority, inclusion: { in: PRIORITIES.keys } @@ -17,11 +18,46 @@ class Squawk < ApplicationRecord scope :resolved, -> { where(resolved: true) } scope :by_priority, -> { order(:priority, created_at: :desc) } - def priority_label = PRIORITIES[priority] - def priority_color = PRIORITY_COLORS[priority] - def grounding? = priority.zero? && !resolved? + # Deferring inoperative equipment without an MEL, 14 CFR 91.213(d): what + # was done with the item and who decided it isn't a hazard. + DEFERRAL_ACTIONS = { "deactivated" => "Deactivated and placarded \"Inoperative\"", + "removed" => "Removed, cockpit control placarded \"Inoperative\"" }.freeze + DEFERRAL_ROLES = { "pilot" => "Pilot", "mechanic" => "Certificated mechanic" }.freeze + # Each must be confirmed to defer (91.213(d)(2)(i)–(iv) and (d)(3)–(4)). + DEFERRAL_CHECKS = { + "not_required_by_type" => "Not part of the VFR-day type certification instruments and equipment, nor on the aircraft's equipment list or kinds of operations equipment list", + "not_required_by_rules" => "Not required by 91.205 or any other rule for the kind of flight planned", + "not_required_by_ad" => "Not required by an airworthiness directive", + "placarded" => "Removed or deactivated, and placarded \"Inoperative\"", + "no_hazard" => "A pilot or certificated mechanic has determined it isn't a hazard to the aircraft" + }.freeze - def resolve!(notes: nil) - update!(resolved: true, resolved_at: Time.current, notes: [ self.notes, notes ].compact_blank.join("\n\n")) + scope :deferred, -> { active.where.not(deferred_at: nil) } + + validates :deferral_action, inclusion: { in: DEFERRAL_ACTIONS.keys }, if: :deferred? + validates :deferred_by_role, inclusion: { in: DEFERRAL_ROLES.keys }, if: :deferred? + validates :deferred_by_name, presence: true, if: :deferred? + + def priority_label = deferred? ? "Deferred (91.213(d))" : PRIORITIES[priority] + def priority_color = deferred? ? "blue" : PRIORITY_COLORS[priority] + def deferred? = deferred_at.present? && !resolved? + def grounding? = priority.zero? && !resolved? && !deferred? + def deferral_action_label = DEFERRAL_ACTIONS[deferral_action] + + # Defers the item if every check is confirmed; returns false with errors otherwise. + def defer(checks:, name:, role:, action:, notes: nil) + missing = DEFERRAL_CHECKS.keys - Array(checks).map(&:to_s) + assign_attributes(deferred_at: Time.current, deferred_by_name: name.to_s.strip.presence, deferred_by_role: role, + deferral_action: action, deferral_notes: notes.to_s.strip.presence) + missing.each { errors.add(:base, "Confirm: #{DEFERRAL_CHECKS[_1]}") } + return false if missing.any? || !valid? + save + end + + def undefer! = update!(deferred_at: nil, deferred_by_name: nil, deferred_by_role: nil, deferral_action: nil, deferral_notes: nil) + + def resolve!(notes: nil, logbook_entry: nil) + update!(resolved: true, resolved_at: Time.current, logbook_entry: logbook_entry || self.logbook_entry, + notes: [ self.notes, notes ].compact_blank.join("\n\n")) end end diff --git a/app/models/standard_inspections.rb b/app/models/standard_inspections.rb new file mode 100644 index 0000000..10d1699 --- /dev/null +++ b/app/models/standard_inspections.rb @@ -0,0 +1,53 @@ +# The recurring inspections and checks Part 91 calls for, to add to an +# aircraft in one go (Inspections → Standard inspections). +module StandardInspections + Template = Data.define(:key, :name, :who, :months, :days, :hours, :tolerance, :effect, :checked, :pattern) do + def attributes + { name: name, recurring: true, recurring_months: months.to_i, recurring_days: days.to_i, + recurring_hours: hours.to_i, hours_tolerance: tolerance.to_i, effect: effect } + end + end + + TEMPLATES = [ + Template.new(key: "annual", name: "Annual inspection (91.409(a))", who: "Every aircraft", + months: 12, days: nil, hours: nil, tolerance: nil, effect: "grounds", checked: true, pattern: /annual/i), + Template.new(key: "hundred", name: "100-hour inspection (91.409(b))", who: "Carrying anyone for hire, or flight instruction for hire", + months: nil, days: nil, hours: 100, tolerance: 10, effect: "grounds", checked: false, pattern: /100[- ]?h(ou)?r/i), + Template.new(key: "transponder", name: "Transponder check (91.413)", who: "Aircraft with a transponder", + months: 24, days: nil, hours: nil, tolerance: nil, effect: "no_transponder", checked: true, pattern: /transponder|91\.413/i), + Template.new(key: "pitot_static", name: "Altimeter and static system check (91.411)", who: "Flying IFR in controlled airspace", + months: 24, days: nil, hours: nil, tolerance: nil, effect: "no_ifr", checked: false, pattern: /pitot|static|altimeter|91\.411/i), + Template.new(key: "elt", name: "ELT inspection (91.207(d))", who: "Aircraft required to carry an ELT", + months: 12, days: nil, hours: nil, tolerance: nil, effect: "grounds", checked: true, pattern: /\belt\b|91\.207/i), + Template.new(key: "vor", name: "VOR check (91.171)", who: "Flying IFR using VORs; the pilot may do and log it", + months: nil, days: 30, hours: nil, tolerance: nil, effect: "no_ifr", checked: false, pattern: /\bvor\b|91\.171/i) + ].freeze + + module_function + + def find(key) = TEMPLATES.find { _1.key == key } + + # The aircraft's existing inspection type a template matches, if any. + def existing_for(template, aircraft) + aircraft.applicable_inspection_types.find { _1.name.match?(template.pattern) } + end + + # Adds the chosen templates the aircraft doesn't already track. Returns the + # inspection types added. + def add!(aircraft, keys) + added = {} + InspectionType.transaction do + Array(keys).filter_map { find(_1.to_s) }.each do |t| + next if existing_for(t, aircraft) + type = InspectionType.find_by(name: t.name) || InspectionType.create!(t.attributes) + type.aircraft << aircraft unless type.aircraft.include?(aircraft) + added[t.key] = type + end + # An annual also counts as the 100-hour (91.409(b)). + annual = added["annual"] || (find("annual") && existing_for(find("annual"), aircraft)) + hundred = added["hundred"] || existing_for(find("hundred"), aircraft) + annual.update!(satisfies: hundred) if annual && hundred && annual.satisfies_id.nil? && (added["annual"] || added["hundred"]) + end + added.values + end +end diff --git a/app/services/aircraft_archive/exporter.rb b/app/services/aircraft_archive/exporter.rb index 5c1a521..0b40823 100644 --- a/app/services/aircraft_archive/exporter.rb +++ b/app/services/aircraft_archive/exporter.rb @@ -50,7 +50,7 @@ module AircraftArchive end, documents: a.documents.map do |d| { id: id(d), aircraft_id: id(a), collection_id: id(d.document_collection_id), doc_type: d.doc_type, name: d.name, - description: d.description, visibility: d.visibility, components: [] } + description: d.description, visibility: d.visibility, expires_on: d.expires_on&.iso8601, components: [] } end, 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") } } @@ -128,7 +128,7 @@ module AircraftArchive def component_hash(c) { id: id(c), aircraft_id: id(c.aircraft_id), parent_component_id: id(c.parent_component_id), component_type_id: id(c.component_type_id), manufacturer: c.manufacturer, model: c.model, serial_number: c.serial_number, install_location: c.install_location, - notes: c.notes, status: c.status, date_in_service: c.date_in_service&.iso8601, hours_in_service: dec(c.hours_in_service), + expires_on: c.expires_on&.iso8601, notes: c.notes, status: c.status, date_in_service: c.date_in_service&.iso8601, hours_in_service: dec(c.hours_in_service), hours_since_overhaul: dec(c.hours_since_overhaul), overhaul_date: c.overhaul_date&.iso8601, tbo_hours: c.tbo_hours, tbo_days: c.tbo_days, inspection_hours: c.inspection_hours, inspection_days: c.inspection_days, replacement_hours: c.replacement_hours, replacement_days: c.replacement_days, tbo_critical: c.tbo_critical, diff --git a/app/services/aircraft_archive/importer.rb b/app/services/aircraft_archive/importer.rb index cf7a062..9365c10 100644 --- a/app/services/aircraft_archive/importer.rb +++ b/app/services/aircraft_archive/importer.rb @@ -177,7 +177,7 @@ module AircraftArchive c = @aircraft.components.new( component_type_id: type_id, parent_component_id: @map[:component][data["parent_component_id"].to_s], manufacturer: data["manufacturer"].to_s, model: data["model"].to_s, serial_number: data["serial_number"].to_s, - install_location: data["install_location"].to_s, notes: data["notes"].to_s, + install_location: data["install_location"].to_s, notes: data["notes"].to_s, expires_on: date(data["expires_on"]), status: Component::STATUSES.key?(data["status"]) ? data["status"] : "SPARE", date_in_service: date(data["date_in_service"]) || Date.new(1900, 1, 1), hours_in_service: num(data["hours_in_service"]) || 0, hours_since_overhaul: num(data["hours_since_overhaul"]) || 0, overhaul_date: date(data["overhaul_date"]), @@ -201,7 +201,8 @@ module AircraftArchive m("documents").each do |data| d = @aircraft.documents.new(name: data["name"].to_s.presence || "Untitled", description: data["description"].to_s, doc_type: data["doc_type"].presence, visibility: visibility(data["visibility"]), - document_collection_id: @map[:collection][data["collection_id"].to_s]) + document_collection_id: @map[:collection][data["collection_id"].to_s], + expires_on: date(data["expires_on"])) d.doc_type = "OTHER" unless Document::TYPES.key?(d.doc_type) d.save!(validate: false) @map[:document][data["id"].to_s] = d.id diff --git a/app/services/airworthiness.rb b/app/services/airworthiness.rb index ca53f02..46d8f1b 100644 --- a/app/services/airworthiness.rb +++ b/app/services/airworthiness.rb @@ -15,6 +15,7 @@ class Airworthiness RED = "RED" LIMITED = "LIMITED" + INFO = "INFO" # listed for awareness; doesn't change the status (a deferred inoperative item) ORANGE = "ORANGE" GREEN = "GREEN" DISCLAIMER = "Based on the records in this app. Before each flight the pilot in command decides whether the aircraft is airworthy (14 CFR 91.7)." @@ -52,6 +53,7 @@ class Airworthiness check_grounding_squawks check_inspections check_components + check_documents status = if @issues.any? { _1.severity == RED } then RED @@ -84,9 +86,13 @@ class Airworthiness end def check_grounding_squawks - @aircraft.squawks.active.where(priority: 0).find_each do |squawk| + @aircraft.squawks.active.where(priority: 0, deferred_at: nil).find_each do |squawk| add("SQUAWK", RED, "Grounding Squawk", squawk.issue_reported.to_s.truncate(100).presence || "No description", squawk) end + @aircraft.squawks.deferred.find_each do |squawk| + add("DEFERRED", INFO, "Inoperative: #{squawk.issue_reported.to_s.truncate(80)}", + "Deferred under 91.213(d) on #{squawk.deferred_at.to_date} by #{squawk.deferred_by_name}. Fix at the next inspection.", squawk) + end end def check_inspections @@ -120,13 +126,26 @@ class Airworthiness end end + def check_documents + @aircraft.documents.expiring.find_each do |doc| + grounds = Document::GROUNDING_EXPIRY_TYPES.include?(doc.doc_type) + if doc.expired?(@today) + add("DOCUMENT", grounds ? RED : ORANGE, "#{doc.name} - Expired", + "#{doc.type_label} expired #{doc.expires_on}.#{' The aircraft may not be flown without a current registration (91.203).' if grounds}", doc) + elsif @today + doc.expiry_warning_days >= doc.expires_on + add("DOCUMENT", ORANGE, "#{doc.name} - Expires Soon", "#{doc.type_label} expires #{doc.expires_on}.", doc) + end + end + end + def check_components - @aircraft.components.in_use.where(replacement_critical: true).includes(:component_type).find_each do |c| + scope = @aircraft.components.in_use.where(replacement_critical: true).or(@aircraft.components.in_use.where.not(expires_on: nil)) + scope.includes(:component_type).find_each do |c| overdue = false approaching = false desc = "" - if c.replacement_hours + if c.replacement_critical? && c.replacement_hours if c.hours_since_overhaul >= c.replacement_hours overdue = true desc = "Replace every #{c.replacement_hours} hrs. Current: #{c.hours_since_overhaul} hrs." @@ -136,7 +155,7 @@ class Airworthiness end end - if (due = c.next_replacement_date) + if c.replacement_critical? && (due = c.next_replacement_date) if @today >= due overdue = true desc = "Replace every #{c.replacement_days} days. Last serviced #{c.overhaul_date}." @@ -146,10 +165,23 @@ class Airworthiness end end - if overdue - add("COMPONENT", RED, "#{c} - Replacement Overdue", desc, c) + expired = false + if c.expires_on + if c.expired?(@today) + expired = true + desc = "Expired #{c.expires_on}." + elsif @today + DAYS_WARNING >= c.expires_on + approaching = true + desc = "Expires #{c.expires_on}." + end + end + + if overdue || (expired && c.replacement_critical?) + add("COMPONENT", RED, "#{c} - #{expired ? 'Expired' : 'Replacement Overdue'}", desc, c) + elsif expired + add("COMPONENT", ORANGE, "#{c} - Expired", desc, c) elsif approaching - add("COMPONENT", ORANGE, "#{c} - Replacement Due Soon", desc, c) + add("COMPONENT", ORANGE, "#{c} - #{c.expires_on && desc.start_with?('Expires') ? 'Expires Soon' : 'Replacement Due Soon'}", desc, c) end end end diff --git a/app/services/maintenance_report.rb b/app/services/maintenance_report.rb index 42eaa87..8969f55 100644 --- a/app/services/maintenance_report.rb +++ b/app/services/maintenance_report.rb @@ -17,7 +17,7 @@ class MaintenanceReport # Parts with a mandatory replacement time (life limits). def life_limited - in_use.select { |c| c.replacement_critical? && (c.replacement_hours || c.replacement_days) } + in_use.select { |c| (c.replacement_critical? && (c.replacement_hours || c.replacement_days)) || c.expires_on } end # Items overhauled on a time basis. diff --git a/app/views/admin/about/show.html.erb b/app/views/admin/about/show.html.erb index 97f3878..5ccc85e 100644 --- a/app/views/admin/about/show.html.erb +++ b/app/views/admin/about/show.html.erb @@ -51,7 +51,8 @@ <%= button_to "Send test email", admin_test_email_path, class: "btn-secondary btn-sm", disabled: !MailSettings.configured?, data: { turbo_submits_with: "Sending…" }, title: "Sends to #{current_user.email_address}" %> - <%= render "pairs", pairs: MailSettings.summary %> + <%= render "pairs", pairs: MailSettings.summary.merge("Weekly reminders" => "Mondays, to owners who haven't turned them off") %> +
| <%= c %> <%= c.model %> | <%= c.serial_number.presence || "—" %> | -<%= [ (c.replacement_hours && "#{hours(c.replacement_hours)} hrs"), (c.replacement_days && "#{c.replacement_days} days") ].compact.join(" / ") %> | +<%= [ (c.replacement_hours && "#{hours(c.replacement_hours)} hrs"), (c.replacement_days && "#{c.replacement_days} days"), (c.expires_on && "expires #{c.expires_on}") ].compact.join(" / ") %> | <%= hours(c.hours_since_overhaul) %> hrs | <%= [ (c.hours_to_replacement && "#{hours(c.hours_to_replacement)} hrs"), (c.next_replacement_date && "by #{c.next_replacement_date}") ].compact.join(", ") %> | <%= life_badge(c.life_status) %> | <%= s.component&.to_s || "—" %> | <%= s.created_at.to_date %> <%= s.reported_by&.display_name %> |
- <% if owner? %> - <%= button_to "Resolve", resolve_aircraft_squawk_path(aircraft, s), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %> - <%= link_to "Edit", edit_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %> + <% if owner? %><%= link_to "Resolve", resolution_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %><% end %> + <% if s.deferred? %> + <% if owner? %><%= button_to "Undo deferral", undefer_aircraft_squawk_path(aircraft, s), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %><% end %> + <% else %> + <%= link_to "Defer", deferral_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm", title: "Defer as inoperative (91.213(d))" %> <% end %> + <% if owner? %><%= link_to "Edit", edit_aircraft_squawk_path(aircraft, s), class: "btn-secondary btn-sm" %><% end %> | <% end %> diff --git a/app/views/squawks/deferral.html.erb b/app/views/squawks/deferral.html.erb new file mode 100644 index 0000000..548cdcf --- /dev/null +++ b/app/views/squawks/deferral.html.erb @@ -0,0 +1,48 @@ +<% content_for :title, "Defer inoperative item" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= form_with url: defer_aircraft_squawk_path(@aircraft, @squawk), method: :patch, class: "card card-body max-w-2xl space-y-4" do %> +
| <%= squawk_priority_badge(s) %> | <%= s.issue_reported %><%= render "squawks/attachments", squawk: s %> | -<%= s.notes %> | +<%= s.notes %><% if s.logbook_entry %> <%= link_to "Logbook #{s.logbook_entry.date}", aircraft_logbook_entry_path(@aircraft, s.logbook_entry), class: "link" %> <% end %> |
<%= s.resolved_at&.to_date %> | <% if owner? %><%= button_to "Reopen", reopen_aircraft_squawk_path(@aircraft, s), method: :patch, class: "btn-secondary btn-sm" %><% end %> |