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") %> +
<%= button_to "Send me this week's reminder", admin_test_reminder_path, class: "btn-secondary btn-sm", disabled: !MailSettings.configured? %>
diff --git a/app/views/components/_form.html.erb b/app/views/components/_form.html.erb index 345d724..d749717 100644 --- a/app/views/components/_form.html.erb +++ b/app/views/components/_form.html.erb @@ -27,7 +27,9 @@ Limits <%= f.field :replacement_hours, as: :number, label: "Replace every (hrs)" %> <%= f.field :replacement_days, as: :number, label: "Replace every (days)" %> - <%= f.field :replacement_critical, as: :checkbox, label: "Replacement critical", hint: "Overdue replacement grounds the aircraft (oil, filters, ELT battery…)." %> + <%= f.field :replacement_critical, as: :checkbox, label: "Replacement critical", hint: "Overdue replacement or expiry grounds the aircraft (oil, filters, ELT battery…)." %> + <%= f.field :expires_on, as: :date, label: "Expires on", + hint: "The date marked on the part, e.g. an ELT battery's replacement date (14 CFR 91.207(c): also replace it after 1 hour of cumulative use)." %> <%= f.field :tbo_hours, as: :number, label: "TBO (hrs)" %> <%= f.field :tbo_days, as: :number, label: "TBO (days)" %>
diff --git a/app/views/components/index.html.erb b/app/views/components/index.html.erb index 48dd016..72329df 100644 --- a/app/views/components/index.html.erb +++ b/app/views/components/index.html.erb @@ -34,7 +34,8 @@ <% if c.replacement_critical? && (c.replacement_hours || c.replacement_days) %> Replace: <%= [c.replacement_hours && "#{c.replacement_hours} h", c.replacement_days && "#{c.replacement_days} d"].compact.join(" / ") %>
<% end %> - <% if c.tbo_critical? && c.tbo_hours %>TBO: <%= c.tbo_hours %> h<%= " (on condition)" if c.on_condition? %><% end %> + <% if c.tbo_critical? && c.tbo_hours %>TBO: <%= c.tbo_hours %> h<%= " (on condition)" if c.on_condition? %>
<% end %> + <% if c.expires_on %>Expires: <%= c.expires_on %><% end %> <%= life_badge(c.life_status) %> diff --git a/app/views/documents/_doc_row.html.erb b/app/views/documents/_doc_row.html.erb index 6a5c1af..9616d3e 100644 --- a/app/views/documents/_doc_row.html.erb +++ b/app/views/documents/_doc_row.html.erb @@ -2,6 +2,7 @@
<%= link_to doc.name, aircraft_document_path(aircraft, doc), class: "link font-medium" %> <%= doc.type_label %> · <%= pluralize(doc.pages.size, "file") %> + <% if doc.expires_on %><%= doc.expired? ? "Expired" : "Expires" %> <%= doc.expires_on %><% end %> <% if doc.description.present? %>
<%= doc.description.truncate(120) %>
<% end %>
diff --git a/app/views/documents/_form.html.erb b/app/views/documents/_form.html.erb index 7ad9fd0..e3a8000 100644 --- a/app/views/documents/_form.html.erb +++ b/app/views/documents/_form.html.erb @@ -8,6 +8,8 @@ <%= f.field :visibility, as: :select, label: "Share-link visibility", collection: [["Inherit from collection", nil]] + DocumentCollection::VISIBILITIES.invert.to_a %>
+ <%= f.field :expires_on, as: :date, label: "Expires on", wrapper: { class: "max-w-xs" }, + hint: "Optional. Registration (good for 7 years, 14 CFR 47.40), insurance, radio license… You'll be reminded before it expires; an expired registration shows the aircraft grounded." %> <%= f.field :description, as: :textarea, rows: 2 %> <%= f.field :pages, as: :file, multiple: true, label: document.persisted? ? "Add files" : "Files", hint: "Images, PDFs or text, up to #{Setting.max_upload_mb} MB each. Each file is a page in the viewer, in upload order." %> diff --git a/app/views/inspections/index.html.erb b/app/views/inspections/index.html.erb index 10cb6c0..e8505ab 100644 --- a/app/views/inspections/index.html.erb +++ b/app/views/inspections/index.html.erb @@ -2,7 +2,7 @@ <%= render "shared/aircraft_header", aircraft: @aircraft %>

Inspection Status

- <% if owner? %><%= link_to "+ Inspection Type", new_aircraft_inspection_type_path(@aircraft), class: "btn-primary" %><% end %>
+ <% if owner? %>
<%= link_to "Standard inspections", new_aircraft_standard_inspections_path(@aircraft), class: "btn-secondary" %><%= link_to "+ Inspection Type", new_aircraft_inspection_type_path(@aircraft), class: "btn-primary" %>
<% end %>
<% if @rows.any? %>
diff --git a/app/views/maintenance_reports/show.html.erb b/app/views/maintenance_reports/show.html.erb index a5549cb..23f75d6 100644 --- a/app/views/maintenance_reports/show.html.erb +++ b/app/views/maintenance_reports/show.html.erb @@ -49,7 +49,7 @@ <% @report.life_limited.each do |c| %> - + diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb index cf5d723..4451c84 100644 --- a/app/views/profiles/edit.html.erb +++ b/app/views/profiles/edit.html.erb @@ -3,6 +3,8 @@ <%= f.errors_summary %> <%= f.field :name %> <%= f.field :email_address, as: :email, label: "Email" %> + <%= f.field :reminder_emails, as: :checkbox, label: "Weekly maintenance reminders", + hint: "A Monday email about overdue and upcoming inspections, ADs, parts and documents on aircraft you own. Only sent when something needs attention#{' (once email is set up)' unless MailSettings.configured?}." %> <%= f.field :password, as: :password, label: "New password", hint: "Leave blank to keep your current password.", autocomplete: "new-password" %> <%= f.field :password_confirmation, as: :password, label: "Confirm new password", autocomplete: "new-password" %>
diff --git a/app/views/reminder_mailer/weekly.html.erb b/app/views/reminder_mailer/weekly.html.erb new file mode 100644 index 0000000..3326e01 --- /dev/null +++ b/app/views/reminder_mailer/weekly.html.erb @@ -0,0 +1,13 @@ +

Here's what needs attention on your aircraft.

+<% @items.each do |aircraft, issues| %> +

<%= link_to aircraft.tail_number, aircraft_url(aircraft) %> <%= aircraft.airworthiness.label %>

+
    + <% issues.each do |issue| %> +
  • <%= { "RED" => "Overdue", "LIMITED" => "Overdue", "ORANGE" => "Due soon", "INFO" => "Deferred" }[issue.severity] %>: + <%= issue.title %> <%= issue.description %>
  • + <% end %> +
+<% end %> +

+ Based on the records in Simple Aircraft Manager. Turn these emails off on your <%= link_to "profile", edit_profile_url %>. +

diff --git a/app/views/reminder_mailer/weekly.text.erb b/app/views/reminder_mailer/weekly.text.erb new file mode 100644 index 0000000..a62af5c --- /dev/null +++ b/app/views/reminder_mailer/weekly.text.erb @@ -0,0 +1,10 @@ +Here's what needs attention on your aircraft. +<% @items.each do |aircraft, issues| %> + +<%= aircraft.tail_number %> (<%= aircraft.airworthiness.label %>): <%= aircraft_url(aircraft) %> +<% issues.each do |issue| %> +- <%= { "RED" => "Overdue", "LIMITED" => "Overdue", "ORANGE" => "Due soon", "INFO" => "Deferred" }[issue.severity] %>: <%= issue.title %>. <%= issue.description %> +<% end %> +<% end %> + +Based on the records in Simple Aircraft Manager. Turn these emails off on your profile: <%= edit_profile_url %> diff --git a/app/views/squawks/_table.html.erb b/app/views/squawks/_table.html.erb index 30c2bc2..5c4a11a 100644 --- a/app/views/squawks/_table.html.erb +++ b/app/views/squawks/_table.html.erb @@ -9,14 +9,18 @@ <%= s.issue_reported %> <%= render "squawks/attachments", squawk: s %> <% if s.notes.present? %>
<%= s.notes %>
<% end %> + <% if s.deferred? %>
<%= s.deferral_action_label %>, <%= s.deferred_at.to_date %>, determined by <%= s.deferred_by_name %> (<%= Squawk::DEFERRAL_ROLES[s.deferred_by_role]&.downcase %>)
<% 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 %> +
+

Defer as inoperative (14 CFR 91.213(d))

+

Without a Minimum Equipment List, an aircraft may fly with an inoperative instrument or piece of equipment only if all of the following are true. Deferring stops this squawk grounding the aircraft. It stays open, and shows as inoperative, until it's fixed.

+
+
Item: <%= @squawk.issue_reported %><%= " · #{@squawk.component}" if @squawk.component %>
+ <% if @squawk.errors.any? %> + + <% end %> +
+ Confirm each one + <% Squawk::DEFERRAL_CHECKS.each do |key, text| %> + + <% end %> +
+
+
+ <%= label_tag :deferral_action, "What was done", class: "label" %> + <%= select_tag :deferral_action, options_for_select(Squawk::DEFERRAL_ACTIONS.invert, params[:deferral_action] || @squawk.deferral_action), class: "input" %> +

Deactivating or removing it is maintenance, recorded under Part 43 unless the pilot may do it as preventive maintenance.

+
+
+
+ <%= label_tag :deferred_by_name, "Determined by", class: "label" %> + <%= text_field_tag :deferred_by_name, params[:deferred_by_name] || current_user.display_name, class: "input", required: true %> +
+
+ <%= label_tag :deferred_by_role, "As", class: "label" %> + <%= select_tag :deferred_by_role, options_for_select(Squawk::DEFERRAL_ROLES.invert, params[:deferred_by_role]), class: "input" %> +
+
+
+
+ <%= label_tag :deferral_notes, "Notes", class: "label" %> + <%= text_area_tag :deferral_notes, params[:deferral_notes], rows: 2, class: "input", placeholder: "e.g. breaker pulled and collared; equipment list reviewed" %> +
+
+ <%= submit_tag "Defer item", class: "btn-primary" %> + <%= link_to "Cancel", aircraft_squawks_path(@aircraft), class: "btn-secondary" %> +
+<% end %> diff --git a/app/views/squawks/index.html.erb b/app/views/squawks/index.html.erb index 84208f5..7c46050 100644 --- a/app/views/squawks/index.html.erb +++ b/app/views/squawks/index.html.erb @@ -18,7 +18,7 @@ - + diff --git a/app/views/squawks/resolution.html.erb b/app/views/squawks/resolution.html.erb new file mode 100644 index 0000000..c56e580 --- /dev/null +++ b/app/views/squawks/resolution.html.erb @@ -0,0 +1,44 @@ +<% content_for :title, "Resolve squawk" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= form_with url: resolve_aircraft_squawk_path(@aircraft, @squawk), method: :patch, class: "card card-body max-w-3xl space-y-4" do %> +
+

Resolve squawk

+

<%= @squawk.issue_reported %><%= " · #{@squawk.component}" if @squawk.component %>

+
+ <% if @entry.errors.any? %> + + <% end %> + <% choice = params[:logbook].presence || "new" %> +
+ Logbook + + + +
+ +
+

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.

+ <%= fields_for :logbook_entry, @entry do |f| %> +
+ <%= f.field :date, as: :date %> + <%= f.field :log_type, as: :select, label: "Logbook", collection: LogbookEntry::LOG_TYPES.invert %> + <%= f.field :aircraft_hours_at_entry, as: :number, step: 0.1, label: "Aircraft hours" %> +
+ <%= f.field :text, as: :textarea, label: "Work performed", rows: 3 %> +
+ <%= f.field :signoff_person, label: "Signed off by" %> + <%= f.field :signoff_certificate_type, as: :select, label: "Kind of certificate", include_blank: "—", collection: LogbookEntry::CERTIFICATE_TYPES.invert %> + <%= f.field :signoff_certificate_number, label: "Certificate number" %> +
+ <% end %> +
+ +
+ <%= label_tag :resolution_notes, "Resolution notes (optional)", class: "label" %> + <%= text_area_tag :resolution_notes, params[:resolution_notes], rows: 2, class: "input" %> +
+
<%= submit_tag "Resolve", class: "btn-primary" %><%= link_to "Cancel", aircraft_squawks_path(@aircraft), class: "btn-secondary" %>
+<% end %> diff --git a/app/views/standard_inspections/new.html.erb b/app/views/standard_inspections/new.html.erb new file mode 100644 index 0000000..987b8fa --- /dev/null +++ b/app/views/standard_inspections/new.html.erb @@ -0,0 +1,24 @@ +<% content_for :title, "#{@aircraft.tail_number} Standard inspections" %> +<%= render "shared/aircraft_header", aircraft: @aircraft %> +<%= form_with url: aircraft_standard_inspections_path(@aircraft), class: "card card-body max-w-3xl space-y-4" do %> +
+

Standard inspections

+

The recurring inspections and checks Part 91 calls for. Pick the ones that apply to how <%= @aircraft.tail_number %> is flown. Each is added with its interval and what being overdue means; you can change them afterwards.

+
+ +

With both an annual and a 100-hour, the annual also counts as the 100-hour (91.409(b)).

+
<%= submit_tag "Add selected", class: "btn-primary" %><%= link_to "Cancel", aircraft_inspections_path(@aircraft), class: "btn-secondary" %>
+<% end %> diff --git a/config/recurring.yml b/config/recurring.yml index 3fb1828..38ef55e 100644 --- a/config/recurring.yml +++ b/config/recurring.yml @@ -19,3 +19,6 @@ production: dedupe_storage: command: "ActiveStorage::Blob.service.try(:sweep)" schedule: every day at 4:30am + weekly_reminders: + class: WeeklyReminderJob + schedule: every monday at 12pm diff --git a/config/routes.rb b/config/routes.rb index 8b71f0d..eecc4cf 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -32,8 +32,12 @@ Rails.application.routes.draw do end resources :squawks, except: :show do member do + get :resolution patch :resolve patch :reopen + get :deferral + patch :defer + patch :undefer end end resources :notes, except: :show do @@ -66,6 +70,7 @@ Rails.application.routes.draw do resources :document_collections, except: %i[index show] resources :inspections, only: :index resources :inspection_types, except: %i[index show] + resource :standard_inspections, only: %i[new create] resources :inspection_records, except: %i[index show] resources :airworthiness_directives, path: "ads", except: :show do collection { post :attach } @@ -92,6 +97,7 @@ Rails.application.routes.draw do get "about", to: "about#show" resource :settings, only: %i[edit update] post "about/test_email", to: "about#test_email", as: :test_email + post "about/test_reminder", to: "about#test_reminder", as: :test_reminder resources :users, except: :show resources :component_types, except: :show resources :airports, except: :show do diff --git a/db/migrate/20261107210000_add_deferrals_expirations_reminders.rb b/db/migrate/20261107210000_add_deferrals_expirations_reminders.rb new file mode 100644 index 0000000..7b95950 --- /dev/null +++ b/db/migrate/20261107210000_add_deferrals_expirations_reminders.rb @@ -0,0 +1,20 @@ +# - squawks: deferring inoperative equipment under 14 CFR 91.213(d), and the +# logbook entry that recorded the fix +# - components / documents: an expiration date (ELT battery per 91.207(c), +# registration per 47.40, insurance…) +# - users: opt out of the weekly reminder email +class AddDeferralsExpirationsReminders < ActiveRecord::Migration[8.1] + def change + change_table :squawks do |t| + t.datetime :deferred_at + t.string :deferred_by_name + t.string :deferred_by_role + t.string :deferral_action + t.text :deferral_notes + t.references :logbook_entry, foreign_key: { on_delete: :nullify } + end + add_column :components, :expires_on, :date + add_column :documents, :expires_on, :date + add_column :users, :reminder_emails, :boolean, null: false, default: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 3240da9..d92fb58 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_200000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_07_210000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -295,6 +295,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_200000) do t.boolean "replacement_critical", default: false, null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.date "expires_on" t.index ["aircraft_id"], name: "index_components_on_aircraft_id" t.index ["component_type_id"], name: "index_components_on_component_type_id" t.index ["parent_component_id"], name: "index_components_on_parent_component_id" @@ -344,6 +345,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_200000) do t.string "visibility" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.date "expires_on" t.index ["aircraft_id"], name: "index_documents_on_aircraft_id" t.index ["document_collection_id"], name: "index_documents_on_document_collection_id" end @@ -541,8 +543,15 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_200000) do t.datetime "resolved_at" t.datetime "created_at", null: false t.datetime "updated_at", null: false + t.datetime "deferred_at" + t.string "deferred_by_name" + t.string "deferred_by_role" + t.string "deferral_action" + t.text "deferral_notes" + t.integer "logbook_entry_id" t.index ["aircraft_id"], name: "index_squawks_on_aircraft_id" t.index ["component_id"], name: "index_squawks_on_component_id" + t.index ["logbook_entry_id"], name: "index_squawks_on_logbook_entry_id" t.index ["reported_by_id"], name: "index_squawks_on_reported_by_id" end @@ -555,6 +564,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_200000) do t.boolean "admin", default: false, null: false t.string "sso_uid" t.datetime "last_signed_in_at" + t.boolean "reminder_emails", default: true, null: false t.index ["email_address"], name: "index_users_on_email_address", unique: true t.index ["sso_uid"], name: "index_users_on_sso_uid", unique: true end @@ -612,5 +622,6 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_07_200000) do add_foreign_key "share_tokens", "users", column: "created_by_id", on_delete: :nullify add_foreign_key "squawks", "aircraft" add_foreign_key "squawks", "components", on_delete: :nullify + add_foreign_key "squawks", "logbook_entries", on_delete: :nullify add_foreign_key "squawks", "users", column: "reported_by_id", on_delete: :nullify end diff --git a/test/integration/maintenance_tracking_test.rb b/test/integration/maintenance_tracking_test.rb new file mode 100644 index 0000000..2c732a2 --- /dev/null +++ b/test/integration/maintenance_tracking_test.rb @@ -0,0 +1,97 @@ +require "test_helper" + +# Expiring parts and documents, the standard inspection set, and the weekly +# reminder email. +class MaintenanceTrackingTest < ActionDispatch::IntegrationTest + include ActionMailer::TestHelper + + setup do + @owner = create_user("owner@example.com") + @a = create_aircraft(owner: @owner, tail_number: "N12345") + end + + test "an expired ELT battery grounds; other expiring parts and documents warn; an expired registration grounds" do + battery = create_component(@a, component_type: component_type("ELT Battery"), replacement_critical: true, expires_on: 10.days.from_now.to_date) + assert_equal [ "ORANGE", "ELT Battery - Expires Soon" ], [ @a.reload.airworthiness.status, @a.airworthiness.issues.sole.title ] + battery.update!(expires_on: 1.day.ago.to_date) + assert_equal "ELT Battery - Expired", @a.reload.airworthiness.issues.sole.title + assert @a.airworthiness.red? + battery.update!(expires_on: Date.current) # usable through the marked date + refute @a.reload.airworthiness.red? + battery.update!(expires_on: 5.years.from_now.to_date) + + insurance = @a.documents.create!(name: "Insurance", doc_type: "INSURANCE", expires_on: 1.day.ago.to_date) + aw = @a.reload.airworthiness + assert_equal [ "ORANGE", "Insurance - Expired" ], [ aw.status, aw.issues.sole.title ] + insurance.destroy! + registration = @a.documents.create!(name: "Registration", doc_type: "REGISTRATION", expires_on: 60.days.from_now.to_date) + assert_equal "Registration - Expires Soon", @a.reload.airworthiness.issues.sole.title # 90-day warning + registration.update!(expires_on: 1.day.ago.to_date) + assert @a.reload.airworthiness.red? + assert_match "91.203", @a.airworthiness.issues.sole.description + + sign_in @owner + get aircraft_documents_path(@a) + assert_select ".badge-red", text: /Expired/ + patch aircraft_component_path(@a, battery), params: { component: { expires_on: "2030-06-30" } } + assert_equal Date.new(2030, 6, 30), battery.reload.expires_on + end + + test "standard inspections add the right rules once, linking the annual to the 100-hour" do + InspectionType.create!(name: "Transponder & encoder", recurring: true, recurring_months: 24).aircraft << @a + sign_in @owner + get new_aircraft_standard_inspections_path(@a) + assert_select "input[type=checkbox][value=transponder][disabled]" + assert_includes response.body, "Already tracked as “Transponder & encoder”" + + post aircraft_standard_inspections_path(@a), params: { templates: %w[annual hundred transponder pitot_static elt vor] } + assert_redirected_to aircraft_inspections_path(@a) + types = @a.reload.inspection_types.index_by(&:name) + assert_equal 6, types.size # five added, the existing transponder kept + hundred = types["100-hour inspection (91.409(b))"] + assert_equal [ 100, 10 ], [ hundred.recurring_hours.to_i, hundred.hours_tolerance.to_i ] + assert_equal hundred, types["Annual inspection (91.409(a))"].satisfies + assert_equal [ "no_ifr", 24 ], types["Altimeter and static system check (91.411)"].then { [ _1.effect, _1.recurring_months ] } + assert_equal [ "no_ifr", 30 ], types["VOR check (91.171)"].then { [ _1.effect, _1.recurring_days ] } + + other = create_aircraft(owner: @owner) + StandardInspections.add!(other, %w[annual]) + assert_equal types["Annual inspection (91.409(a))"], other.inspection_types.sole # shared, not duplicated + post aircraft_standard_inspections_path(@a), params: { templates: %w[annual] } + assert_redirected_to new_aircraft_standard_inspections_path(@a) + end + + test "weekly reminders go to owners with something due, not to those who opted out" do + annual = InspectionType.create!(name: "Annual", recurring: true, recurring_months: 12).tap { _1.aircraft << @a } + @a.inspection_records.create!(inspection_type: annual, date: 13.months.ago.to_date) + @a.squawks.create!(priority: 2, issue_reported: "Nav light inop", deferred_at: Time.current, deferred_by_name: "J", + deferred_by_role: "pilot", deferral_action: "deactivated") + quiet = create_user("quiet@example.com") + create_aircraft(owner: quiet) # nothing due + opted_out = create_user("optout@example.com") + opted_out.update!(reminder_emails: false) + @a.roles.create!(user: opted_out, role: "owner") + + assert_emails 1 do + WeeklyReminderJob.perform_now + end + mail = ActionMailer::Base.deliveries.last + assert_equal [ [ "owner@example.com" ], "1 item overdue: N12345" ], [ mail.to, mail.subject ] + body = mail.text_part.body.to_s + assert_includes body, "Overdue: Annual - Overdue" + assert_includes body, "Deferred: Inoperative: Nav light inop" + + sign_in @owner + patch profile_path, params: { user: { reminder_emails: "0" } } + refute @owner.reload.reminder_emails? + assert_no_emails { WeeklyReminderJob.perform_now } + + admin = create_user("admin@example.com", admin: true) + @a.roles.create!(user: admin, role: "owner") + sign_in admin + assert_emails 1 do + post admin_test_reminder_path + end + assert_equal "Reminder sent to admin@example.com.", flash[:notice] + end +end diff --git a/test/integration/squawk_workflow_test.rb b/test/integration/squawk_workflow_test.rb new file mode 100644 index 0000000..7d64cf0 --- /dev/null +++ b/test/integration/squawk_workflow_test.rb @@ -0,0 +1,72 @@ +require "test_helper" + +# Deferring inoperative equipment (91.213(d)) and recording a squawk's fix +# in the logbook (43.9). +class SquawkWorkflowTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user("owner@example.com") + @pilot = create_user("pilot@example.com") + @a = create_aircraft(owner: @owner, pilot: @pilot) + @squawk = @a.squawks.create!(priority: 0, issue_reported: "Left landing light inop", reported_by: @pilot) + end + + test "a pilot defers an inoperative item once every 91.213(d) condition is confirmed" do + assert @a.reload.airworthiness.red? + sign_in @pilot + get aircraft_squawks_path(@a) + assert_select "a[href='#{deferral_aircraft_squawk_path(@a, @squawk)}']", text: "Defer" + get deferral_aircraft_squawk_path(@a, @squawk) + assert_select "input[name='checks[]']", Squawk::DEFERRAL_CHECKS.size + + patch defer_aircraft_squawk_path(@a, @squawk), params: { checks: Squawk::DEFERRAL_CHECKS.keys.first(3), + deferral_action: "deactivated", deferred_by_name: "Jane Pilot", deferred_by_role: "pilot" } + assert_response :unprocessable_entity + assert_includes response.body, "Confirm: A pilot or certificated mechanic has determined" + refute @squawk.reload.deferred? + + patch defer_aircraft_squawk_path(@a, @squawk), params: { checks: Squawk::DEFERRAL_CHECKS.keys, + deferral_action: "deactivated", deferred_by_name: "Jane Pilot", deferred_by_role: "pilot", deferral_notes: "Breaker collared" } + assert_redirected_to aircraft_squawks_path(@a) + @squawk.reload + assert [ @squawk.deferred?, !@squawk.grounding? ].all? + assert_equal "Deferred (91.213(d))", @squawk.priority_label + aw = @a.reload.airworthiness + assert_equal "GREEN", aw.status # listed, but no longer grounding + assert_equal [ "INFO", "Inoperative: Left landing light inop" ], [ aw.issues.sole.severity, aw.issues.sole.title ] + + patch undefer_aircraft_squawk_path(@a, @squawk) # only owners undo + assert @squawk.reload.deferred? + sign_in @owner + patch undefer_aircraft_squawk_path(@a, @squawk) + refute @squawk.reload.deferred? + assert @a.reload.airworthiness.red? + end + + test "resolving records the fix as a logbook entry, links an existing one, or neither" do + sign_in @owner + get resolution_aircraft_squawk_path(@a, @squawk) + assert_select "textarea[name='logbook_entry[text]']", text: /Corrected: Left landing light inop/ + + patch resolve_aircraft_squawk_path(@a, @squawk), params: { logbook: "new", logbook_entry: { + date: "2026-11-01", log_type: "AC", text: "Replaced left landing light lamp P/N 4509", aircraft_hours_at_entry: 1000, + signoff_person: "Sam Mechanic", signoff_certificate_type: "AP", signoff_certificate_number: "7654321" } } + assert_redirected_to aircraft_squawks_path(@a) + entry = @squawk.reload.logbook_entry + assert @squawk.resolved? + assert_equal [ "MAINTENANCE", "AP", "7654321", [] ], [ entry.entry_type, entry.signoff_certificate_type, entry.signoff_certificate_number, entry.missing_record_items ] + get aircraft_squawks_path(@a) + assert_select "a[href='#{aircraft_logbook_entry_path(@a, entry)}']", text: "Logbook 2026-11-01" + + other = @a.squawks.create!(priority: 2, issue_reported: "Chipped paint") + patch resolve_aircraft_squawk_path(@a, other), params: { logbook: "existing", logbook_entry_id: entry.id } + assert_equal entry, other.reload.logbook_entry + third = @a.squawks.create!(priority: 3, issue_reported: "Not a defect") + patch resolve_aircraft_squawk_path(@a, third), params: { logbook: "none", resolution_notes: "Normal for type" } + assert [ third.reload.resolved?, third.logbook_entry.nil? ].all? + + bad = @a.squawks.create!(priority: 1, issue_reported: "Bad") + patch resolve_aircraft_squawk_path(@a, bad), params: { logbook: "new", logbook_entry: { date: "", text: "" } } + assert_response :unprocessable_entity + refute bad.reload.resolved? + end +end
<%= 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 %>
<%= 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 %>