Calculate next-due for AD compliance and inspections from their rules

- AD compliance "next due at tach reading" is prefilled from the AD's
  hour recurrence (hours at compliance + interval), recalculates live as
  the AD/date/hours change, keeps a typed-in override, and is filled
  server-side when left blank.
- Live "Next due" preview on AD compliance and inspection record forms
  (hours and/or end-of-month date, whichever comes first), mirroring
  Compliance.next_due so preview and status agree.
- Reject an interval entered as the next-due reading (e.g. "100" for
  "every 100 hours"), which made a complied AD show as overdue.
- ADs table shows hours remaining next to the due tach reading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-05 07:24:28 -05:00
1 parent 4d3dc7150a
commit f94ccee99b
13 files changed
+237 -15

No files matched your search

+1 -3
View File
@@ -7,9 +7,7 @@ class AdCompliancesController < ApplicationController
ad = @aircraft.applicable_ads.find_by(id: params[:ad_id])
@compliance = AdCompliance.new(aircraft: @aircraft, airworthiness_directive: ad, date_complied: Date.current,
aircraft_hours_at_compliance: @aircraft.tach_time)
if ad&.recurring? && ad.recurring_hours.to_d > 0
@compliance.next_due_at_time = @aircraft.current_hours + ad.recurring_hours
end
@compliance.fill_next_due
end
def create
@@ -0,0 +1,65 @@
import { Controller } from "@hotwired/stimulus"
import { nextDue, describeDue } from "next_due"
// Live next-due preview (and prefill of an AD's next-due tach reading) from
// the selected AD/inspection type's recurrence rule.
//
// data-controller="next-due" data-next-due-rules-value='{"12": {"hours": 100, "months": 12, "days": 0}}'
// targets: rule (select), date, hours, dueHours (optional), permanent (optional), preview
export default class extends Controller {
static targets = ["rule", "date", "hours", "dueHours", "permanent", "preview"]
static values = { rules: Object }
connect() {
// Don't overwrite a reading that's already filled in (e.g. editing a record).
this.manual = this.hasDueHoursTarget && parseFloat(this.dueHoursTarget.value) > 0
this.recalc()
}
// The user typed their own next-due reading: stop overwriting it.
markManual() {
this.manual = this.dueHoursTarget.value.trim() !== "" && parseFloat(this.dueHoursTarget.value) > 0
this.renderPreview()
}
// Inputs that the rule depends on changed: recompute, unless overridden.
changed() {
this.manual = false
this.recalc()
}
recalc() {
const due = this.computeDue()
if (this.hasDueHoursTarget && !this.manual && !this.isPermanent) {
this.dueHoursTarget.value = due.hours != null ? due.hours.toFixed(1) : "0"
}
this.renderPreview(due)
}
renderPreview(due = this.computeDue()) {
if (!this.hasPreviewTarget) return
const rule = this.currentRule
let text
if (this.isPermanent) text = "Permanent compliance: never due again."
else if (!this.ruleTarget.value) text = ""
else if (!rule) text = "One-time: no recurring due date."
else {
if (this.hasDueHoursTarget && this.manual) due = { ...due, hours: parseFloat(this.dueHoursTarget.value) }
text = describeDue(due) ? `Next due: ${describeDue(due)}` : "Enter the date and hours to calculate the next due."
}
this.previewTarget.textContent = text
this.previewTarget.hidden = text === ""
}
computeDue() {
return nextDue(this.currentRule, this.dateTarget.value, this.hoursTarget.value)
}
get currentRule() {
return this.rulesValue[this.ruleTarget.value] || null
}
get isPermanent() {
return this.hasPermanentTarget && this.permanentTarget.checked
}
}
+34
View File
@@ -0,0 +1,34 @@
// Next-due math, mirroring Compliance.next_due in app/services/compliance.rb:
// months land on the END of the month, then days are added; hours are added
// to the hours at completion. Dates are "YYYY-MM-DD" strings (no timezones).
export function nextDue(rule, dateStr, hours) {
const due = {}
if (!rule) return due
const months = Number(rule.months) || 0
const days = Number(rule.days) || 0
const interval = Number(rule.hours) || 0
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateStr || "")
if (m && (months > 0 || days > 0)) {
let d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]))
if (months > 0) d = new Date(d.getFullYear(), d.getMonth() + months + 1, 0) // last day of month
if (days > 0) d.setDate(d.getDate() + days)
due.date = [d.getFullYear(), String(d.getMonth() + 1).padStart(2, "0"), String(d.getDate()).padStart(2, "0")].join("-")
}
const base = parseFloat(hours)
if (interval > 0 && !Number.isNaN(base)) due.hours = Math.round((base + interval) * 10) / 10
return due
}
export function describeDue(due) {
const parts = []
if (due.hours != null) parts.push(`${due.hours.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 })} tach`)
if (due.date) {
const [y, mo, d] = due.date.split("-").map(Number)
parts.push(new Date(y, mo - 1, d).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" }))
}
if (parts.length === 0) return ""
return parts.length > 1 ? `${parts.join(" or ")}, whichever comes first` : parts[0]
}
+24
View File
@@ -7,10 +7,34 @@ class AdCompliance < ApplicationRecord
validates :date_complied, :compliance_notes, presence: true
validate { errors.add(:base, "Must belong to an aircraft or component") unless aircraft_id || component_id }
validate :next_due_is_a_future_reading
before_validation :fill_next_due, if: -> { next_due_at_time.to_d.zero? }
scope :recent_first, -> { order(date_complied: :desc, created_at: :desc) }
# Prefill next_due_at_time from the AD's hour recurrence (hours at compliance
# + interval). Only fills a blank/zero value, so a typed-in reading wins.
def fill_next_due
return if permanent? || airworthiness_directive.nil?
base = aircraft_hours_at_compliance || aircraft&.tach_time
due = Compliance.next_due(airworthiness_directive.due_rule, date: date_complied, hours: base)
self.next_due_at_time = due[:hours] if due[:hours]
end
def self.for_aircraft(aircraft)
where(aircraft_id: aircraft.id).or(where(component_id: aircraft.components.select(:id)))
end
private
# next_due_at_time is an absolute tach reading, not an interval. Catch the
# easy mistake of entering "100" for "every 100 hours".
def next_due_is_a_future_reading
due = next_due_at_time.to_d
return if permanent? || due <= 0
base = aircraft_hours_at_compliance || aircraft&.tach_time
return unless base && due <= base
errors.add(:next_due_at_time, "must be a tach reading after the compliance hours (#{base}). " \
"For “every 100 hours” enter #{base + 100}, not 100")
end
end
+5
View File
@@ -27,6 +27,11 @@ class AirworthinessDirective < ApplicationRecord
def conditional? = compliance_type == "conditional"
def bulletin_label = BULLETIN_LABELS[bulletin_type]
# Recurrence rule for next-due math (AD status uses hours and months).
def due_rule
{ hours: recurring_hours.to_f, months: recurring_months, days: 0 } if recurring?
end
def latest_compliance_for(aircraft)
ad_compliances.for_aircraft(aircraft).order(date_complied: :desc, created_at: :desc).first
end
+4
View File
@@ -16,6 +16,10 @@ class InspectionType < ApplicationRecord
def to_s = name
def due_rule
{ hours: recurring_hours.to_f, months: recurring_months, days: recurring_days } if recurring?
end
def interval_description
return "One-time" unless recurring?
parts = []
+16
View File
@@ -17,6 +17,22 @@ module Compliance
(date >> months).end_of_month
end
# Next due date/hours from a recurrence rule ({hours:, months:, days:}),
# matching the status math below: months land on the end of the month,
# then days are added; hours are added to the hours at completion.
def next_due(rule, date:, hours:)
return {} unless rule
due = {}
if rule[:months].to_i.positive? || rule[:days].to_i.positive?
d = date
d = end_of_month_after(d, rule[:months].to_i) if rule[:months].to_i.positive?
d += rule[:days].to_i.days if rule[:days].to_i.positive?
due[:date] = d if date
end
due[:hours] = hours.to_d + rule[:hours].to_d if rule[:hours].to_d.positive? && hours
due
end
def ad_status(ad, compliance, current_hours, today = Date.current)
return Result.new(rank: COMPLIANT) if ad.conditional?
return Result.new(rank: OVERDUE) unless compliance
+15 -6
View File
@@ -1,14 +1,23 @@
<%= form_with model: compliance, url: compliance.new_record? ? aircraft_ad_compliances_path(aircraft) : aircraft_ad_compliance_path(aircraft, compliance), class: "card card-body space-y-4 max-w-2xl" do |f| %>
<% ads = aircraft.applicable_ads.ordered %>
<% rules = ads.each_with_object({}) { |ad, h| (r = ad.due_rule) && h[ad.id.to_s] = r } %>
<%= form_with model: compliance, url: compliance.new_record? ? aircraft_ad_compliances_path(aircraft) : aircraft_ad_compliance_path(aircraft, compliance),
class: "card card-body space-y-4 max-w-2xl", data: { controller: "next-due", next_due_rules_value: rules.to_json } do |f| %>
<%= f.errors_summary %>
<%= f.field :airworthiness_directive_id, as: :select, label: "AD", collection: aircraft.applicable_ads.ordered.map { ["#{_1.name} – #{_1.short_description.truncate(50)}", _1.id] } %>
<%= f.field :airworthiness_directive_id, as: :select, label: "AD", collection: ads.map { ["#{_1.name} – #{_1.short_description.truncate(50)}", _1.id] },
data: { next_due_target: "rule", action: "change->next-due#changed" } %>
<div class="grid gap-4 sm:grid-cols-2">
<%= f.field :date_complied, as: :date %>
<%= f.field :aircraft_hours_at_compliance, as: :number, step: 0.1, label: "Aircraft hours (tach)" %>
<%= f.field :next_due_at_time, as: :number, step: 0.1, label: "Next due at (tach hours)", hint: "0 = no hour-based recurrence." %>
<%= f.field :date_complied, as: :date, data: { next_due_target: "date", action: "change->next-due#changed" } %>
<%= f.field :aircraft_hours_at_compliance, as: :number, step: 0.1, label: "Aircraft hours (tach)",
data: { next_due_target: "hours", action: "input->next-due#changed" } %>
<%= f.field :next_due_at_time, as: :number, step: 0.1, label: "Next due at tach reading",
hint: "Calculated from the AD's recurrence; you can override it. Leave 0 if not hour-based.",
data: { next_due_target: "dueHours", action: "input->next-due#markManual" } %>
<%= f.field :component_id, as: :select, label: "Component", collection: component_options(aircraft) %>
<%= f.field :logbook_entry_id, as: :select, label: "Logbook entry", collection: logbook_options(aircraft) %>
</div>
<%= f.field :permanent, as: :checkbox, label: "Permanently complied (terminating action)" %>
<p class="rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-next-due-target="preview" hidden></p>
<%= f.field :permanent, as: :checkbox, label: "Permanently complied (terminating action)",
data: { next_due_target: "permanent", action: "change->next-due#changed" } %>
<%= f.field :compliance_notes, as: :textarea, label: "Method of compliance", rows: 3, required: true %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %></div>
<% end %>
@@ -28,7 +28,7 @@
<% if ad.conditional? && ad.trigger_condition.present? %><div class="text-slate-500">Trigger: <%= ad.trigger_condition %></div><% end %></td>
<td class="text-xs"><%= ad.recurring? ? [ad.recurring_hours.to_f > 0 && "#{hours(ad.recurring_hours)} h", ad.recurring_months > 0 && "#{ad.recurring_months} mo"].select(&:itself).join(" / ") : "One-time" %></td>
<td class="text-xs"><%= row.latest ? "#{row.latest.date_complied}#{' (permanent)' if row.latest.permanent?}" : "—" %></td>
<td class="text-xs"><%= [row.next_due_date&.strftime("%b %Y"), row.next_due_hours && "#{hours(row.next_due_hours)} h"].compact.join(" / ").presence || "—" %></td>
<td class="text-xs"><%= [row.next_due_date&.strftime("%b %Y"), row.next_due_hours && "#{hours(row.next_due_hours)} tach (#{hours(row.next_due_hours - @aircraft.current_hours)} h left)"].compact.join(" / ").presence || "—" %></td>
<td><%= compliance_badge(row.status) %></td>
<td class="whitespace-nowrap text-right">
<% if owner? %>
@@ -50,7 +50,7 @@
<div class="card-header"><h2 class="card-title">Compliance History</h2></div>
<% if @history.any? %>
<table class="table">
<thead><tr><th>Date</th><th>AD</th><th class="text-right">Hours</th><th>Next due (hrs)</th><th>Notes</th><th></th></tr></thead>
<thead><tr><th>Date</th><th>AD</th><th class="text-right">Hours</th><th>Next due (tach)</th><th>Notes</th><th></th></tr></thead>
<tbody>
<% @history.each do |c| %>
<tr>
+10 -4
View File
@@ -1,12 +1,18 @@
<%= form_with model: record, url: record.new_record? ? aircraft_inspection_records_path(aircraft) : aircraft_inspection_record_path(aircraft, record), class: "card card-body space-y-4 max-w-2xl" do |f| %>
<% types = aircraft.applicable_inspection_types.ordered %>
<% rules = types.each_with_object({}) { |t, h| (r = t.due_rule) && h[t.id.to_s] = r } %>
<%= form_with model: record, url: record.new_record? ? aircraft_inspection_records_path(aircraft) : aircraft_inspection_record_path(aircraft, record),
class: "card card-body space-y-4 max-w-2xl", data: { controller: "next-due", next_due_rules_value: rules.to_json } do |f| %>
<%= f.errors_summary %>
<%= f.field :inspection_type_id, as: :select, label: "Inspection", collection: aircraft.applicable_inspection_types.ordered.map { [_1.name, _1.id] } %>
<%= f.field :inspection_type_id, as: :select, label: "Inspection", collection: types.map { [_1.name, _1.id] },
data: { next_due_target: "rule", action: "change->next-due#changed" } %>
<div class="grid gap-4 sm:grid-cols-2">
<%= f.field :date, as: :date %>
<%= f.field :aircraft_hours, as: :number, step: 0.1, label: "Aircraft hours (tach)" %>
<%= f.field :date, as: :date, data: { next_due_target: "date", action: "change->next-due#changed" } %>
<%= f.field :aircraft_hours, as: :number, step: 0.1, label: "Aircraft hours (tach)",
data: { next_due_target: "hours", action: "input->next-due#changed" } %>
<%= f.field :component_id, as: :select, label: "Component (if component-level)", collection: component_options(aircraft) %>
<%= f.field :logbook_entry_id, as: :select, label: "Logbook entry", collection: logbook_options(aircraft) %>
</div>
<p class="rounded-md bg-sky-50 px-3 py-2 text-sm text-sky-900 ring-1 ring-sky-200" data-next-due-target="preview" hidden></p>
<%= f.field :notes, as: :textarea, rows: 2 %>
<div class="flex gap-2"><%= f.submit "Save" %><%= link_to "Cancel", aircraft_inspections_path(aircraft), class: "btn-secondary" %></div>
<% end %>