From 98e943cf0a76c2046eac3917d23d70a4141e389e Mon Sep 17 00:00:00 2001 From: Rick Barrette Date: Wed, 11 Nov 2026 21:00:30 -0500 Subject: [PATCH] Calendar feed: due items (inspections, ADs, component limits, documents) as a private iCalendar link, hour-based dates projected from the past year's flying Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + app/controllers/calendar_feeds_controller.rb | 23 ++++++ app/controllers/calendar_tokens_controller.rb | 7 ++ app/controllers/record_versions_controller.rb | 10 +-- app/models/user.rb | 1 + app/services/due_list.rb | 82 +++++++++++++++++++ app/services/ical.rb | 46 +++++++++++ app/views/profiles/edit.html.erb | 17 ++++ config/routes.rb | 5 ++ ...61111020000_add_calendar_token_to_users.rb | 7 ++ db/schema.rb | 4 +- docs/authentik.md | 4 +- docs/guide/profile.md | 6 ++ test/integration/calendar_feed_test.rb | 60 ++++++++++++++ 14 files changed, 266 insertions(+), 7 deletions(-) create mode 100644 app/controllers/calendar_feeds_controller.rb create mode 100644 app/controllers/calendar_tokens_controller.rb create mode 100644 app/services/due_list.rb create mode 100644 app/services/ical.rb create mode 100644 db/migrate/20261111020000_add_calendar_token_to_users.rb create mode 100644 test/integration/calendar_feed_test.rb diff --git a/README.md b/README.md index 7b9b769..9af8776 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ To back up or move a single aircraft with all its files, use **Access & Sharing | Major repairs and alterations | Form 337, STC, and ICA tracking; an STC's ICA can become a tracked recurring inspection. | | Weight & balance | History of empty weight and CG (linked to the alteration that changed them) and a loading calculator: takeoff and landing weight and CG against max gross and the CG envelope. The envelope can be entered as CG (inches) or as moment (lb-in/1000, as in POH moment charts and Garmin Pilot). | | 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. | +| Calendar feed | A private iCalendar link (Profile) with everything coming due on your aircraft as all-day events; hour-based items get a date projected from the past year's flying. | | Reminders | A Monday email to owners when something is overdue or coming due, and to anyone whose certificate (e.g. an IA) is about to expire; admins also get the records audit due date (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`. | diff --git a/app/controllers/calendar_feeds_controller.rb b/app/controllers/calendar_feeds_controller.rb new file mode 100644 index 0000000..8a39f44 --- /dev/null +++ b/app/controllers/calendar_feeds_controller.rb @@ -0,0 +1,23 @@ +# The calendar feed: what's coming due on every aircraft the user can see, +# as all-day events (dates for hour-based items are projected from the past +# year's flying). Calendar apps fetch it with the secret link from Profile. +class CalendarFeedsController < ApplicationController + allow_unauthenticated_access + skip_before_action :redirect_to_setup + rate_limit to: 60, within: 1.hour, with: -> { head :too_many_requests } + + def show + user = User.active.find_by(calendar_token: params[:token].to_s) or return head(:not_found) + cal = Ical.new("Aircraft maintenance") + host = Sso.app_url + user.accessible_aircraft.ordered.each do |aircraft| + DueList.new(aircraft).items.each do |i| + when_text = [ ("projected from recent flying" if i.projected), ("at #{i.due_hours} hrs" if i.due_hours) ].compact.join(", ") + cal.add(uid: "#{aircraft.id}-#{i.key}@simple-aircraft-manager", date: i.date, + summary: "#{aircraft.tail_number}: #{i.title}#{' (overdue)' if i.overdue?}", + description: [ "#{aircraft.tail_number}: #{i.title}", when_text.presence ].compact.join("\n"), url: "#{host}#{i.path}") + end + end + send_data cal.to_s, type: "text/calendar; charset=utf-8", disposition: "inline", filename: "aircraft-maintenance.ics" + end +end diff --git a/app/controllers/calendar_tokens_controller.rb b/app/controllers/calendar_tokens_controller.rb new file mode 100644 index 0000000..9a22f2f --- /dev/null +++ b/app/controllers/calendar_tokens_controller.rb @@ -0,0 +1,7 @@ +# Profile: create (or replace) the secret calendar feed link. +class CalendarTokensController < ApplicationController + def create + current_user.regenerate_calendar_token + redirect_to edit_profile_path(anchor: "calendar"), notice: "Calendar link ready. Any earlier link no longer works." + end +end diff --git a/app/controllers/record_versions_controller.rb b/app/controllers/record_versions_controller.rb index a7cbe21..26ecfaa 100644 --- a/app/controllers/record_versions_controller.rb +++ b/app/controllers/record_versions_controller.rb @@ -3,7 +3,7 @@ class RecordVersionsController < ApplicationController include AircraftScoped before_action :require_owner!, only: :restore - SHARED = %w[AirworthinessDirective InspectionType].freeze + SHARED = { "AirworthinessDirective" => AirworthinessDirective, "InspectionType" => InspectionType }.freeze def index @type = params[:type].presence_in(RecordVersion.where(aircraft_id: @aircraft.id).distinct.pluck(:item_type)) @@ -16,8 +16,8 @@ class RecordVersionsController < ApplicationController # Puts back an AD or inspection type link that was removed (the removal # stays in the history, and the restore is recorded as a new link). def restore - version = RecordVersion.where(aircraft_id: @aircraft.id, event: "unlink", item_type: SHARED).find(params[:id]) - record = version.item_type.constantize.find_by(id: version.item_id) + version = RecordVersion.where(aircraft_id: @aircraft.id, event: "unlink", item_type: SHARED.keys).find(params[:id]) + record = SHARED.fetch(version.item_type).find_by(id: version.item_id) return redirect_to(aircraft_record_versions_path(@aircraft), alert: "That record no longer exists.") unless record c = version.changes_hash if c["applies_to"] == "component" @@ -33,8 +33,8 @@ class RecordVersionsController < ApplicationController # Whether an unlink can still be undone (the record exists and isn't linked that way now). def self.restorable?(version, aircraft) - return false unless version.event == "unlink" && SHARED.include?(version.item_type) - record = version.item_type.constantize.find_by(id: version.item_id) or return false + return false unless version.event == "unlink" && SHARED.key?(version.item_type) + record = SHARED[version.item_type].find_by(id: version.item_id) or return false c = version.changes_hash if c["applies_to"] == "component" record.component_ids.exclude?(c["component_id"]) && aircraft.components.exists?(id: c["component_id"]) diff --git a/app/models/user.rb b/app/models/user.rb index 5c14f3a..c796c37 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -6,6 +6,7 @@ class User < ApplicationRecord has_one :air_trail_connection, dependent: :destroy has_many :certificates, -> { ordered }, class_name: "UserCertificate", dependent: :destroy has_many :entry_signatures, dependent: :nullify + has_secure_token :calendar_token, length: 32 scope :active, -> { where(disabled_at: nil) } diff --git a/app/services/due_list.rb b/app/services/due_list.rb new file mode 100644 index 0000000..a45eade --- /dev/null +++ b/app/services/due_list.rb @@ -0,0 +1,82 @@ +# Everything coming due on an aircraft, with a date: inspections, ADs, +# component replacement / TBO / inspection / expiry, and expiring documents. +# Items due by hours get a projected date from the aircraft's flying over +# the past year. Used by the calendar feed. +class DueList + Item = Data.define(:key, :title, :date, :projected, :due_hours, :kind, :path) do + def overdue?(today = Date.current) = date < today + end + + # Hours flown per day over the past year (nil when it hasn't flown). + def self.daily_rate(aircraft, today: Date.current) + hours = aircraft.flight_logs.where(date: (today - 365)..today).sum(:tach_time).to_f + hours.positive? ? hours / 365.0 : nil + end + + def initialize(aircraft, today: Date.current) + @aircraft = aircraft + @today = today + @rate = self.class.daily_rate(aircraft, today: today) + @now_hours = aircraft.current_hours.to_d + @urls = Rails.application.routes.url_helpers + end + + def items + (inspections + ads + components + documents).compact.sort_by { [ _1.date, _1.title ] } + end + + private + + # The date it's due: the calendar date, or when the hours run out at the + # current rate, whichever comes first. + def item(key, title, kind, path, date: nil, hours_left: nil) + projected = hours_left && @rate ? @today + (hours_left.to_f / @rate).floor : nil + projected = @today if projected && projected < @today + use = [ date, projected ].compact.min + return unless use + Item.new(key: key, title: title, date: use, projected: use == projected && projected != date, kind: kind, path: path, + due_hours: hours_left ? (@now_hours + hours_left.to_d).round(1) : nil) + end + + def hours_left(due_hours) = due_hours ? due_hours.to_d - @now_hours : nil + + def inspections + Compliance.inspection_rows(@aircraft).map do |r| + item("inspection-#{r.type.id}", "#{r.type.name} due", "inspection", @urls.aircraft_inspections_path(@aircraft), + date: r.next_due_date, hours_left: hours_left(r.next_due_hours)) + end + end + + def ads + Compliance.ad_rows(@aircraft).map do |r| + next if r.status.to_s.in?(%w[not_applicable na conditional]) + item("ad-#{r.ad.id}", "AD #{r.ad.name} due", "ad", @urls.aircraft_airworthiness_directives_path(@aircraft), + date: r.next_due_date, hours_left: hours_left(r.next_due_hours)) + end + end + + def components + @aircraft.components.in_use.includes(:component_type).flat_map do |c| + label = "#{c} #{c.model}".strip + path = @urls.aircraft_component_path(@aircraft, c) + since_service = c.hours_since_overhaul.to_d + [ + (item("replace-#{c.id}", "Replace #{label}", "component", path, date: c.next_replacement_date, + hours_left: c.replacement_hours && c.replacement_hours - since_service) if c.replacement_hours || c.replacement_days), + (item("tbo-#{c.id}", "#{label} reaches TBO", "component", path, + date: c.tbo_days && c.overhaul_date ? c.overhaul_date + c.tbo_days : nil, + hours_left: c.tbo_hours && c.tbo_hours - since_service) if (c.tbo_hours || c.tbo_days) && !c.on_condition?), + (item("inspect-#{c.id}", "Inspect #{label}", "component", path, + date: c.inspection_days && c.overhaul_date ? c.overhaul_date + c.inspection_days : nil, + hours_left: c.inspection_hours && c.inspection_hours - since_service) if c.inspection_hours || c.inspection_days), + (item("expires-#{c.id}", "#{label} expires", "component", path, date: c.expires_on) if c.expires_on) + ] + end + end + + def documents + @aircraft.documents.expiring.map do |d| + item("document-#{d.id}", "#{d.name} expires", "document", @urls.aircraft_document_path(@aircraft, d), date: d.expires_on) + end + end +end diff --git a/app/services/ical.rb b/app/services/ical.rb new file mode 100644 index 0000000..80ad9fd --- /dev/null +++ b/app/services/ical.rb @@ -0,0 +1,46 @@ +# A minimal iCalendar (RFC 5545) writer for all-day events. +class Ical + def initialize(name) + @name = name + @events = [] + end + + def add(uid:, date:, summary:, description: nil, url: nil) + @events << { uid: uid, date: date, summary: summary, description: description, url: url } + end + + def to_s + lines = [ "BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Simple Aircraft Manager//EN", "CALSCALE:GREGORIAN", + "METHOD:PUBLISH", "X-WR-CALNAME:#{escape(@name)}", "REFRESH-INTERVAL;VALUE=DURATION:PT6H", "X-PUBLISHED-TTL:PT6H" ] + stamp = Time.current.utc.strftime("%Y%m%dT%H%M%SZ") + @events.each do |e| + lines += [ "BEGIN:VEVENT", "UID:#{e[:uid]}", "DTSTAMP:#{stamp}", "DTSTART;VALUE=DATE:#{e[:date].strftime('%Y%m%d')}", + "DTEND;VALUE=DATE:#{(e[:date] + 1).strftime('%Y%m%d')}", "SUMMARY:#{escape(e[:summary])}", "TRANSP:TRANSPARENT" ] + lines << "DESCRIPTION:#{escape(e[:description])}" if e[:description].present? + lines << "URL:#{e[:url]}" if e[:url].present? + lines << "END:VEVENT" + end + lines << "END:VCALENDAR" + lines.map { fold(_1) }.join("\r\n") + "\r\n" + end + + private + + def escape(text) = text.to_s.gsub("\\", "\\\\\\\\").gsub(";", "\;").gsub(",", "\\,").gsub(/\r?\n/, "\\n") + + # Lines over 75 octets continue on the next line after a space. + def fold(line) + return line if line.bytesize <= 75 + parts = [] + current = +"" + line.each_char do |ch| + if (current + ch).bytesize > (parts.empty? ? 75 : 74) + parts << current + current = +"" + end + current << ch + end + parts << current + parts.first + parts.drop(1).map { "\r\n #{_1}" }.join + end +end diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb index 20f7b6b..f259636 100644 --- a/app/views/profiles/edit.html.erb +++ b/app/views/profiles/edit.html.erb @@ -46,6 +46,23 @@ <% end %> +
+

Calendar feed

+

What's coming due on your aircraft (inspections, ADs, part replacements and limits, expiring documents) in your calendar app. Items due by hours get a date projected from the past year's flying; it updates on its own.

+ <% if @user.calendar_token.present? %> + <% feed = "#{Sso.app_url}#{calendar_feed_path(@user.calendar_token)}" %> + +
+ <%= link_to "Subscribe", feed.sub(%r{\Ahttps?://}, "webcal://"), class: "btn-secondary btn-sm" %> + <%= button_to "Make a new link", calendar_token_path, class: "btn-secondary btn-sm", + form: { data: { turbo_confirm: "Replace the calendar link? Calendars using the old one stop updating." } } %> +
+

Anyone with this link can see the due list, so keep it private. In Google Calendar: Other calendars → From URL. On an iPhone: tap Subscribe.

+ <% else %> +
<%= button_to "Create calendar link", calendar_token_path, class: "btn-secondary btn-sm" %>
+ <% end %> +
+

Certificates

Your FAA certificates, for signing logbook entries: “Sign as” fills in your name, the kind of certificate and its number.

diff --git a/config/routes.rb b/config/routes.rb index 647597e..87024e5 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -126,6 +126,11 @@ Rails.application.routes.draw do post "sign/:token", to: "invited_signings#create" post "sign/:token/account", to: "invited_signings#account", as: :account_invited_signing + # Calendar feed of what's coming due (secret link; calendar apps can't sign in). + get "calendar/:token.ics", to: "calendar_feeds#show", as: :calendar_feed, constraints: { token: /[A-Za-z0-9]{32}/ }, + format: false, defaults: { format: "ics" } + resource :calendar_token, path: "profile/calendar", only: :create + get "shared/:token", to: "shared#show", as: :shared get "shared/:token/report", to: "shared#report", as: :shared_report diff --git a/db/migrate/20261111020000_add_calendar_token_to_users.rb b/db/migrate/20261111020000_add_calendar_token_to_users.rb new file mode 100644 index 0000000..ea412e9 --- /dev/null +++ b/db/migrate/20261111020000_add_calendar_token_to_users.rb @@ -0,0 +1,7 @@ +class AddCalendarTokenToUsers < ActiveRecord::Migration[8.1] + def change + # Secret for the user's calendar feed URL (calendar apps can't sign in). + add_column :users, :calendar_token, :string + add_index :users, :calendar_token, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 99a8643..6cfb345 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_11_010000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_11_020000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -814,6 +814,8 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_11_010000) do t.datetime "otp_enabled_at" t.integer "otp_last_used_at" t.json "otp_recovery_codes" + t.string "calendar_token" + t.index ["calendar_token"], name: "index_users_on_calendar_token", unique: true 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 diff --git a/docs/authentik.md b/docs/authentik.md index 517b85f..f5732dc 100644 --- a/docs/authentik.md +++ b/docs/authentik.md @@ -82,6 +82,7 @@ For domain-level forward auth, Authentik matches each line as a regular expressi ^https://aircraft\.example\.com/profile/certificates(\?.*)?$ ^https://aircraft\.example\.com/profile/two_factor(/new|/recovery_codes)?(\?.*)?$ ^https://aircraft\.example\.com/help/records$ +^https://aircraft\.example\.com/calendar/[A-Za-z0-9]{32}\.ics$ ``` What each group is for: @@ -97,8 +98,9 @@ What each group is for: | `/profile/certificates` | Invited mechanics adding their certificate before signing | Adding a certificate to their own account; it only returns to a `/sign/…` page | | `/profile/two_factor…` | Invited mechanics setting up an authenticator app | Their own two-factor setup | | `/help/records` | The "How signing works" link on the signing form | The signing instructions, for signed-in accounts | +| `/calendar/.ics` | Calendar apps fetching the due-items feed (Profile → Calendar feed) | The due list of that user's aircraft, only with their secret 32-character token; making a new link retires the old one | -Leave out lines for features you don't use: without share links drop `/shared` and Active Storage; if mechanics never sign through invitations drop `/sign`, `/session`, `/profile/…` and `/help/records`. +Leave out lines for features you don't use: without share links drop `/shared` and Active Storage; without calendar feeds drop `/calendar`; if mechanics never sign through invitations drop `/sign`, `/session`, `/profile/…` and `/help/records`. Everything else stays behind Authentik: the fleet, records, admin pages, the emailed sign-in links and password resets (an invited mechanic who forgets their password asks the administrator, who resets it under Admin → Users or sends a new invitation), and the Google Drive callback (`/admin/offsite_backup/callback`), which comes back to the administrator's own signed-in browser. diff --git a/docs/guide/profile.md b/docs/guide/profile.md index 631ca3c..c02c72a 100644 --- a/docs/guide/profile.md +++ b/docs/guide/profile.md @@ -20,6 +20,12 @@ To make new recovery codes or turn it off, enter a current code (or a recovery c Signing in with single sign-on doesn't ask for this code: the sign-on provider handles its own second factor. +## Calendar feed + +**Create calendar link** gives a private address for your calendar app (Google Calendar: Other calendars → From URL; iPhone: tap **Subscribe**). It shows what's coming due on your aircraft as all-day events: inspections, ADs, part replacements, TBO and inspection limits, and expiring documents. Items due by hours get a date projected from the aircraft's flying over the past year, marked "projected". Calendar apps refresh it every few hours. + +Anyone with the link can see the list, so keep it private; **Make a new link** retires the old one. + ## Certificates Add each certificate you sign maintenance records with: its kind (A&P, IA, airframe, powerplant, repairman, repair station, pilot…), its number, and for an IA, its expiry. You need one to sign a logbook entry, and the entry records which one you used. An IA expires on March 31 of each odd-numbered year unless renewed; you're reminded 60 days ahead. diff --git a/test/integration/calendar_feed_test.rb b/test/integration/calendar_feed_test.rb new file mode 100644 index 0000000..adc922f --- /dev/null +++ b/test/integration/calendar_feed_test.rb @@ -0,0 +1,60 @@ +require "test_helper" + +# Calendar feed of what's coming due, with projected dates for hour-based items. +class CalendarFeedTest < ActionDispatch::IntegrationTest + setup do + @owner = create_user("owner@example.com") + @a = create_aircraft(owner: @owner, tail_number: "N12345", tach_time: 1000) + # 36.5 hours flown in the past year: 0.1 hour a day + @a.flight_logs.create!(date: Date.current - 100, tach_time: 36.5) + @oil = create_component(@a, component_type: component_type("Oil"), manufacturer: "Phillips", model: "20W50", + replacement_hours: 50, replacement_days: 120, hours_since_overhaul: 45, overhaul_date: Date.current - 30) + @mag = create_component(@a, component_type: component_type("Magneto"), manufacturer: "Bendix", model: "S4LN-21", + inspection_hours: 500, hours_since_overhaul: 450, overhaul_date: Date.current - 400) + @a.documents.create!(name: "Registration", doc_type: "REGISTRATION", expires_on: Date.current + 200) + end + + test "the due list dates calendar items and projects hour-based ones" do + items = DueList.new(@a).items.index_by(&:key) + oil = items["replace-#{@oil.id}"] + assert_equal Date.current + 50, oil.date # 5 hrs at 0.1/day, before the 120-day limit (90 days left) + assert oil.projected + assert_equal 1005.0, oil.due_hours.to_f + assert_equal Date.current + 500, items["inspect-#{@mag.id}"].date # 50 hrs / 0.1 a day + assert_equal Date.current + 200, items["document-#{@a.documents.first.id}"].date + refute items["document-#{@a.documents.first.id}"].projected + end + + test "the profile makes a secret link; the feed is iCalendar without signing in; a new link retires the old" do + @owner.update_column(:calendar_token, nil) # an account from before calendar links + sign_in @owner + get edit_profile_path + assert_select "button", text: "Create calendar link" + post calendar_token_path + token = @owner.reload.calendar_token + assert_equal 32, token.size + get edit_profile_path + assert_select "input[value*='/calendar/#{token}.ics']" + assert_select "a[href^='webcal://']", text: "Subscribe" + + delete session_path + get calendar_feed_path(token) + assert_response :success + assert_equal "text/calendar", response.media_type + body = response.body + unfolded = body.gsub("\r\n ", "") + assert body.start_with?("BEGIN:VCALENDAR\r\n") + assert_includes body, "SUMMARY:N12345: Replace Oil 20W50" + assert_includes body, "DTSTART;VALUE=DATE:#{(Date.current + 50).strftime('%Y%m%d')}" + assert_includes unfolded, "projected from recent flying\\, at 1005.0 hrs" + assert body.lines.all? { _1.chomp.bytesize <= 75 } # folded + + sign_in @owner + post calendar_token_path + get calendar_feed_path(token) + assert_response :not_found + @owner.reload.update!(disabled_at: Time.current) + get calendar_feed_path(@owner.calendar_token) + assert_response :not_found + end +end