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" } %>
- <%= 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) %>
- <%= f.field :permanent, as: :checkbox, label: "Permanently complied (terminating action)" %> + + <%= 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 %>
<%= f.submit "Save" %><%= link_to "Cancel", aircraft_airworthiness_directives_path(aircraft), class: "btn-secondary" %>
<% end %> diff --git a/app/views/airworthiness_directives/index.html.erb b/app/views/airworthiness_directives/index.html.erb index 661bb40..a54c8d5 100644 --- a/app/views/airworthiness_directives/index.html.erb +++ b/app/views/airworthiness_directives/index.html.erb @@ -28,7 +28,7 @@ <% if ad.conditional? && ad.trigger_condition.present? %>
Trigger: <%= ad.trigger_condition %>
<% end %> <%= 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" %> <%= row.latest ? "#{row.latest.date_complied}#{' (permanent)' if row.latest.permanent?}" : "—" %> - <%= [row.next_due_date&.strftime("%b %Y"), row.next_due_hours && "#{hours(row.next_due_hours)} h"].compact.join(" / ").presence || "—" %> + <%= [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 || "—" %> <%= compliance_badge(row.status) %> <% if owner? %> @@ -50,7 +50,7 @@

Compliance History

<% if @history.any? %> - + <% @history.each do |c| %> diff --git a/app/views/inspection_records/_form.html.erb b/app/views/inspection_records/_form.html.erb index 7b26e23..ca605e5 100644 --- a/app/views/inspection_records/_form.html.erb +++ b/app/views/inspection_records/_form.html.erb @@ -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" } %>
- <%= 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) %>
+ <%= f.field :notes, as: :textarea, rows: 2 %>
<%= f.submit "Save" %><%= link_to "Cancel", aircraft_inspections_path(aircraft), class: "btn-secondary" %>
<% end %> diff --git a/config/importmap.rb b/config/importmap.rb index 6fa0453..70cf5fa 100644 --- a/config/importmap.rb +++ b/config/importmap.rb @@ -7,3 +7,4 @@ pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" pin_all_from "app/javascript/controllers", under: "controllers" pin "chartkick", to: "chartkick.js" pin "Chart.bundle", to: "Chart.bundle.js" +pin "next_due" diff --git a/test/integration/pages_test.rb b/test/integration/pages_test.rb index 8b7ff7e..ab53e39 100644 --- a/test/integration/pages_test.rb +++ b/test/integration/pages_test.rb @@ -59,6 +59,14 @@ class PagesTest < ActionDispatch::IntegrationTest end end + test "AD compliance form is prefilled from the AD's recurrence" do + get new_aircraft_ad_compliance_path(@a, ad_id: @ad.id) + assert_select "input[name='ad_compliance[next_due_at_time]'][value='1100.0']" + assert_select "form[data-controller='next-due'][data-next-due-rules-value*='\"#{@ad.id}\"']" + get new_aircraft_inspection_record_path(@a, inspection_type_id: @itype.id) + assert_select "form[data-controller='next-due'][data-next-due-rules-value*='\"months\":12']" + end + test "maintenance share link renders without login and shows history" do delete session_path get shared_path(@token.token) diff --git a/test/models/ad_compliance_test.rb b/test/models/ad_compliance_test.rb new file mode 100644 index 0000000..4c1524f --- /dev/null +++ b/test/models/ad_compliance_test.rb @@ -0,0 +1,52 @@ +require "test_helper" + +class AdComplianceTest < ActiveSupport::TestCase + setup do + @aircraft = create_aircraft(tach_time: 7290.3) + @ad = AirworthinessDirective.create!(name: "2011-10-09", short_description: "Seat rails") + @ad.aircraft << @aircraft + end + + def comply(**attrs) + @ad.ad_compliances.new({ aircraft: @aircraft, date_complied: Date.current, compliance_notes: "Done" }.merge(attrs)) + end + + test "rejects an interval entered as the next-due reading" do + c = comply(aircraft_hours_at_compliance: 7243.4, next_due_at_time: 100) + assert_not c.valid? + assert_match "enter 7343.4, not 100", c.errors[:next_due_at_time].first + end + + test "falls back to current tach when compliance hours are blank" do + assert_not comply(next_due_at_time: 100).valid? + assert comply(next_due_at_time: 7390.3).valid? + end + + test "accepts a future reading, zero, or permanent" do + assert comply(aircraft_hours_at_compliance: 7243.4, next_due_at_time: 7343.4).valid? + assert comply(aircraft_hours_at_compliance: 7243.4, next_due_at_time: 0).valid? + assert comply(aircraft_hours_at_compliance: 7243.4, next_due_at_time: 100, permanent: true).valid? + end + + test "a correct reading makes the aircraft airworthy again" do + comply(aircraft_hours_at_compliance: 7243.4, next_due_at_time: 7343.4).save! + assert_equal "GREEN", Airworthiness.new(@aircraft).call.status + end + + test "next due is calculated from the AD's hour recurrence when left blank" do + @ad.update!(recurring: true, recurring_hours: 100) + c = comply(aircraft_hours_at_compliance: 7243.4) + c.save! + assert_equal BigDecimal("7343.4"), c.next_due_at_time + end + + test "a typed-in reading wins over the calculation, permanent never gets one" do + @ad.update!(recurring: true, recurring_hours: 100) + assert_equal BigDecimal("7300"), comply(aircraft_hours_at_compliance: 7243.4, next_due_at_time: 7300).tap(&:save!).next_due_at_time + assert_equal 0, comply(aircraft_hours_at_compliance: 7243.4, permanent: true).tap(&:save!).next_due_at_time + end + + test "one-time AD gets no hour-based next due" do + assert_equal 0, comply(aircraft_hours_at_compliance: 7243.4).tap(&:save!).next_due_at_time + end +end
DateADHoursNext due (hrs)Notes
DateADHoursNext due (tach)Notes