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 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-11 21:00:30 -05:00
1 parent 87e30946fe
commit 98e943cf0a
14 files changed
+266 -7

No files matched your search

@@ -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
@@ -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
@@ -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"])
+1
View File
@@ -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) }
+82
View File
@@ -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
+46
View File
@@ -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
+17
View File
@@ -46,6 +46,23 @@
<% end %>
</section>
<section class="card card-body mt-5 max-w-md" id="calendar">
<h2 class="card-title">Calendar feed</h2>
<p class="mt-1 text-sm text-slate-600">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.</p>
<% if @user.calendar_token.present? %>
<% feed = "#{Sso.app_url}#{calendar_feed_path(@user.calendar_token)}" %>
<input class="input mt-3 font-mono text-xs" value="<%= feed %>" readonly aria-label="Calendar feed address">
<div class="mt-2 flex flex-wrap gap-2">
<%= 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." } } %>
</div>
<p class="hint">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.</p>
<% else %>
<div class="mt-3"><%= button_to "Create calendar link", calendar_token_path, class: "btn-secondary btn-sm" %></div>
<% end %>
</section>
<section class="card card-body mt-5 max-w-md" id="certificates">
<h2 class="card-title">Certificates</h2>
<p class="mt-1 text-sm text-slate-600">Your FAA certificates, for signing logbook entries: “Sign as” fills in your name, the kind of certificate and its number.</p>