diff --git a/app/controllers/ad_compliances_controller.rb b/app/controllers/ad_compliances_controller.rb index 54a92a7..63831ca 100644 --- a/app/controllers/ad_compliances_controller.rb +++ b/app/controllers/ad_compliances_controller.rb @@ -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 diff --git a/app/javascript/controllers/next_due_controller.js b/app/javascript/controllers/next_due_controller.js new file mode 100644 index 0000000..b941f3b --- /dev/null +++ b/app/javascript/controllers/next_due_controller.js @@ -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 + } +} diff --git a/app/javascript/next_due.js b/app/javascript/next_due.js new file mode 100644 index 0000000..0e6dd02 --- /dev/null +++ b/app/javascript/next_due.js @@ -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] +} diff --git a/app/models/ad_compliance.rb b/app/models/ad_compliance.rb index c6a9c49..bbdd454 100644 --- a/app/models/ad_compliance.rb +++ b/app/models/ad_compliance.rb @@ -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 diff --git a/app/models/airworthiness_directive.rb b/app/models/airworthiness_directive.rb index 37c549f..989c1d0 100644 --- a/app/models/airworthiness_directive.rb +++ b/app/models/airworthiness_directive.rb @@ -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 diff --git a/app/models/inspection_type.rb b/app/models/inspection_type.rb index d78f7bb..dcec00d 100644 --- a/app/models/inspection_type.rb +++ b/app/models/inspection_type.rb @@ -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 = [] diff --git a/app/services/compliance.rb b/app/services/compliance.rb index c771d2b..b992c7c 100644 --- a/app/services/compliance.rb +++ b/app/services/compliance.rb @@ -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 diff --git a/app/views/ad_compliances/_form.html.erb b/app/views/ad_compliances/_form.html.erb index d9e462b..b660c69 100644 --- a/app/views/ad_compliances/_form.html.erb +++ b/app/views/ad_compliances/_form.html.erb @@ -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" } %>
| Date | AD | Hours | Next due (hrs) | Notes | |
|---|---|---|---|---|---|
| Date | AD | Hours | Next due (tach) | Notes | |