diff --git a/README.md b/README.md index 89d27c1..9629e9f 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ To back up or move a single aircraft with all its files, use **Access & Sharing | Documents | Collections, multi-file documents with a page viewer, per-document share visibility, bulk upload, and expiration dates (registration, insurance…). | | Electronic signatures | Logbook entries can be signed electronically along the lines of AC 120-78B chapter 2: the signer reviews the entry, picks their certificate, re-enters their password (or signs in again with SSO) and confirms a "Certified by" statement. The signature records who, which certificate, the statement, the time and a SHA-256 fingerprint of the entry, sealed by the server; the signer gets an email. Signed entries are locked: a correction is a new signed entry that supersedes the original. Owners can invite an outside mechanic to sign one entry with their own account. Disabled accounts can't sign; their past signatures stay. | | Records integrity | Every change to maintenance records is kept (who, when, field by field) in a hash chain per aircraft (Activity → Record history). Nightly: a verified SQLite backup in `storage/backups` (how many are kept: Admin → Settings), then a check of the history chains and every signature; admins are emailed on a problem (Admin → About). Software versions are recorded. A records package (Access & Sharing) bundles every entry as a PDF with signatures, a signature register, the history, the status report and the `.sam.zip` for the FAA or a buyer. Scans of paper logbooks can be marked as legacy records, with an "electronic records since" date per aircraft. | +| Recordkeeping procedures and audits | Admin → Recordkeeping Procedures generates the procedures document AC 120-78B asks for (who is responsible, who may sign, signing, corrections, backups, access, audits, transfer, legacy records) from the system setup plus a few details you fill in; adopt it as numbered, unchangeable revisions, included in the records package. Admin → Records Audits is a periodic QC checklist (app checks plus a restore test, a sample of entries against source documents and a user review); admins get the due date in the weekly reminder. Users' instructions are at `/help/records`, linked from the logbook and the signing page. | | 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. | | 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. | diff --git a/app/controllers/admin/audits_controller.rb b/app/controllers/admin/audits_controller.rb new file mode 100644 index 0000000..bd18c18 --- /dev/null +++ b/app/controllers/admin/audits_controller.rb @@ -0,0 +1,21 @@ +class Admin::AuditsController < ApplicationController + before_action :require_admin! + + def index + @audits = AuditRun.latest_first.includes(:performed_by) + end + + def new + @audit = RecordsAudit.new + end + + def create + answers = params.fetch(:answers, {}).permit(RecordsAudit::MANUAL.keys.index_with { %i[passed note] }).to_h + run = RecordsAudit.new.record!(user: current_user, answers: answers, notes: params[:notes], sample_ids: Array(params[:sample_ids]).map(&:to_i)) + redirect_to admin_audit_path(run), notice: run.passed ? "Audit recorded: everything passed." : "Audit recorded, with items that didn't pass. Note what's being done about them." + end + + def show + @audit = AuditRun.find(params[:id]) + end +end diff --git a/app/controllers/admin/procedures_controller.rb b/app/controllers/admin/procedures_controller.rb new file mode 100644 index 0000000..8f21a1e --- /dev/null +++ b/app/controllers/admin/procedures_controller.rb @@ -0,0 +1,52 @@ +# The electronic signature and recordkeeping procedures document +# (AC 120-78B 2.2.11 / 3.2.8): the owner fills in what the app can't know, +# reviews the generated draft, and adopts it as a numbered revision. +class Admin::ProceduresController < ApplicationController + before_action :require_admin! + + def show + @policy = RecordkeepingPolicy.current + @revisions = ProceduresRevision.latest_first.includes(:adopted_by) + end + + def update + @policy = RecordkeepingPolicy.current + if @policy.update(params.require(:recordkeeping_policy).permit(:operator_name, :responsible_name, :responsible_title, :hosting_description, + :offsite_backup_description, :audit_interval_months, :audit_sample_size, + :additional_procedures)) + redirect_to admin_procedures_path, notice: "Saved. Review the draft and adopt it as a new revision when it's right." + else + @revisions = ProceduresRevision.latest_first + render :show, status: :unprocessable_entity + end + end + + # The current draft, printable. + def draft + render html: draft_html.html_safe, layout: "report" + end + + def adopt + policy = RecordkeepingPolicy.current + return redirect_to(admin_procedures_path, alert: "Fill in the operator, responsible person, hosting and off-site backup first.") unless policy.complete? + number = (ProceduresRevision.maximum(:number) || 0) + 1 + revision = ProceduresRevision.create!(number: number, adopted_by: current_user, adopted_at: Time.current, + summary: params[:summary].to_s.strip.first(500).presence || "Revision #{number}", + content: draft_html(number: number, summary: params[:summary].to_s.strip.first(500))) + redirect_to admin_procedures_path, notice: "Revision #{revision.number} adopted. Print it or keep the PDF with your records." + end + + def revision + @revision = ProceduresRevision.find(params[:id]) + render html: @revision.content.html_safe, layout: "report" + end + + private + + def draft_html(number: nil, summary: nil) + render_to_string(partial: "admin/procedures/document", + locals: { policy: RecordkeepingPolicy.current, number: number || "#{(ProceduresRevision.maximum(:number) || 0) + 1} (draft)", + adopted_at: number ? Time.current : nil, adopted_by: number ? current_user : nil, + revisions: ProceduresRevision.latest_first.to_a, summary: summary }) + end +end diff --git a/app/controllers/help_controller.rb b/app/controllers/help_controller.rb new file mode 100644 index 0000000..13db097 --- /dev/null +++ b/app/controllers/help_controller.rb @@ -0,0 +1,4 @@ +# User instructions for electronic records and signatures (AC 120-78B 2.2.12, 3.2.9). +class HelpController < ApplicationController + def records; end +end diff --git a/app/mailers/reminder_mailer.rb b/app/mailers/reminder_mailer.rb index 09c600a..7d20eff 100644 --- a/app/mailers/reminder_mailer.rb +++ b/app/mailers/reminder_mailer.rb @@ -8,15 +8,18 @@ class ReminderMailer < ApplicationMailer def self.expiring_certificates_for(user) = user.certificates.expiring.to_a - def self.anything_for?(user) = items_for(user).any? || expiring_certificates_for(user).any? + def self.audit_due_for?(user) = user.admin? && AuditRun.due_soon? + + def self.anything_for?(user) = items_for(user).any? || expiring_certificates_for(user).any? || audit_due_for?(user) def weekly(user) @user = user @items = self.class.items_for(user) @certificates = self.class.expiring_certificates_for(user) + @audit_due = self.class.audit_due_for?(user) && AuditRun.next_due overdue = @items.sum { |_, issues, _| issues.count { _1.severity.in?(%w[RED LIMITED]) } } subject = overdue.positive? ? "#{overdue} #{'item'.pluralize(overdue)} overdue" : "Maintenance coming due" - subject = "Certificate expiring" if @items.empty? + subject = (@certificates.any? ? "Certificate expiring" : "Records audit due") if @items.empty? mail subject: [ subject, @items.map { _1.first.tail_number }.to_sentence.presence ].compact.join(": "), to: user.email_address end end diff --git a/app/models/audit_run.rb b/app/models/audit_run.rb new file mode 100644 index 0000000..91739e3 --- /dev/null +++ b/app/models/audit_run.rb @@ -0,0 +1,18 @@ +# A quality-control audit of the electronic records (AC 120-78B 3.2.8.5): +# a checklist, some items checked by the app, some confirmed by the auditor. +class AuditRun < ApplicationRecord + belongs_to :performed_by, class_name: "User", optional: true + + scope :latest_first, -> { order(performed_at: :desc) } + before_update { throw :abort } + before_destroy { throw :abort } + + def self.latest = latest_first.first + + def self.next_due + interval = RecordkeepingPolicy.current.audit_interval_months.months + (latest&.performed_at || Time.current - interval).to_date + interval + end + + def self.due_soon? = next_due <= 14.days.from_now.to_date +end diff --git a/app/models/procedures_revision.rb b/app/models/procedures_revision.rb new file mode 100644 index 0000000..c2f0f19 --- /dev/null +++ b/app/models/procedures_revision.rb @@ -0,0 +1,11 @@ +# An adopted revision of the procedures document, kept for good (the +# superseded ones are the archive, as AC 120-78B 4.3.8 asks of manuals). +class ProceduresRevision < ApplicationRecord + belongs_to :adopted_by, class_name: "User", optional: true + + scope :latest_first, -> { order(number: :desc) } + before_update { throw :abort } + before_destroy { throw :abort } + + def self.current = latest_first.first +end diff --git a/app/models/recordkeeping_policy.rb b/app/models/recordkeeping_policy.rb new file mode 100644 index 0000000..001d6e5 --- /dev/null +++ b/app/models/recordkeeping_policy.rb @@ -0,0 +1,11 @@ +# The facts the procedures document needs that the app can't know (who is +# responsible, where it's hosted, the off-site backup, how often to audit). +# One row for the installation. +class RecordkeepingPolicy < ApplicationRecord + validates :audit_interval_months, numericality: { only_integer: true, in: 1..24 } + validates :audit_sample_size, numericality: { only_integer: true, in: 1..50 } + + def self.current = first || create! + + def complete? = [ operator_name, responsible_name, hosting_description, offsite_backup_description ].all?(&:present?) +end diff --git a/app/services/records_audit.rb b/app/services/records_audit.rb new file mode 100644 index 0000000..0a0c001 --- /dev/null +++ b/app/services/records_audit.rb @@ -0,0 +1,70 @@ +# The QC audit checklist (AC 120-78B 3.2.8.5): items the app checks itself, +# and items the auditor confirms (restore test, comparing a sample of entries +# with their source documents, reviewing users). +class RecordsAudit + Item = Data.define(:key, :title, :auto, :passed, :detail) + + MANUAL = { + "restore_test" => "Restored the latest off-site backup somewhere separate and opened it (records readable, counts plausible)", + "sample" => "Compared the sampled entries below with their work orders, receipts or other source documents; they match", + "users" => "Reviewed the users and roles below; accounts of people who no longer need access are disabled", + "legacy" => "The paper (legacy) logbooks are kept, complete and accounted for" + }.freeze + + def initialize(since: AuditRun.latest&.performed_at) + @since = since + @policy = RecordkeepingPolicy.current + end + + def auto_items + check = IntegrityCheck.latest + backup = BackupRun.latest + revision = ProceduresRevision.current + expired = UserCertificate.joins(:user).merge(User.active).where(expires_on: ...Date.current) + [ + Item.new("integrity", "Records integrity check passed in the last 2 days", true, + check.present? && check.ok && check.created_at > 2.days.ago, + check ? "#{check.created_at.to_date}: #{check.ok ? 'no problems' : check.problems.first(3).join('; ')}" : "Never run"), + Item.new("backup", "A verified database backup was made in the last 2 days", true, + backup.present? && backup.ok && backup.created_at > 2.days.ago, + backup ? "#{backup.created_at.to_date}: #{backup.message}" : "Never run"), + Item.new("procedures", "The procedures document is adopted and its details filled in", true, + revision.present? && @policy.complete?, + revision ? "Revision #{revision.number}, adopted #{revision.adopted_at.to_date}" : "Not adopted yet"), + Item.new("signatures", "Electronic signatures since the last audit are intact", true, + check.present? && check.ok, "#{signatures_since.count} signed since #{since_label}"), + Item.new("certificates", "No active user is relying on an expired certificate", true, true, + expired.any? ? "Expired (can't sign until renewed): #{expired.map { "#{_1.user.display_name} #{_1.short_label}" }.join(', ')}" : "None expired"), + Item.new("versions", "Software versions since the last audit", true, true, + versions_since.map(&:revision).join(", ").presence || "No changes") + ] + end + + # Entries to compare with source documents: a random few since the last audit, signed ones first. + def sample + pool = LogbookEntry.where(created_at: (@since || Time.at(0))..).includes(:aircraft, :signature) + signed = pool.joins(:signature).order(Arel.sql("RANDOM()")).limit(@policy.audit_sample_size).to_a + (signed + pool.where.not(id: signed.map(&:id)).order(Arel.sql("RANDOM()")).limit(@policy.audit_sample_size - signed.size).to_a).first(@policy.audit_sample_size) + end + + def users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) + + # Saves the audit from the auditor's answers: { key => { "passed" => "1", "note" => … } }. + def record!(user:, answers:, notes:, sample_ids:) + autos = auto_items + manual = MANUAL.map do |key, title| + a = answers.fetch(key, {}) + { "key" => key, "title" => title, "auto" => false, "passed" => a["passed"] == "1", "detail" => a["note"].to_s.strip.first(1000) } + end + results = autos.map { { "key" => _1.key, "title" => _1.title, "auto" => true, "passed" => _1.passed, "detail" => _1.detail } } + manual + results << { "key" => "sample_entries", "title" => "Entries sampled", "auto" => true, "passed" => true, + "detail" => LogbookEntry.where(id: sample_ids).includes(:aircraft).map { "#{_1.aircraft.tail_number} #{_1.date}" }.join(", ") } + AuditRun.create!(performed_by: user, performed_at: Time.current, passed: results.all? { _1["passed"] }, results: results, notes: notes.to_s.strip.first(5000)) + end + + private + + def since_label = @since ? @since.to_date.to_s : "the start" + def signatures_since = EntrySignature.where(signed_at: (@since || Time.at(0))..) + def versions_since = AppRevision.where(first_seen_at: (@since || Time.at(0))..).order(:first_seen_at) +end diff --git a/app/services/records_package.rb b/app/services/records_package.rb index bd87143..7e0cb9d 100644 --- a/app/services/records_package.rb +++ b/app/services/records_package.rb @@ -22,6 +22,9 @@ class RecordsPackage add(zip, "signatures.csv", signatures_csv(entries)) add(zip, "record-history.csv", history_csv) add(zip, "status-report.html", status_report_html) + if (revision = ProceduresRevision.current) + add(zip, "recordkeeping-procedures.html", standalone_html(revision.content, "Recordkeeping procedures, revision #{revision.number}")) + end archive = Tempfile.new([ "archive", ".sam.zip" ]) AircraftArchive::Exporter.new(@aircraft, source: @source).write_to(archive.path) zip.put_next_entry("#{@aircraft.tail_number.downcase}.sam.zip") @@ -55,6 +58,7 @@ class RecordsPackage - record-history.csv Every change to the maintenance records (created, changed, deleted), with who and when. - status-report.html Maintenance status per 14 CFR 91.417(a)(2): times, life-limited parts, inspections, ADs, alterations. - #{@aircraft.tail_number.downcase}.sam.zip All records and files as data, to load into another system. + - recordkeeping-procedures.html How these electronic records and signatures are kept (AC 120-78B), current adopted revision. Signatures Each electronic signature records who signed, with which certificate, what they certified, when, and a SHA-256 @@ -91,8 +95,14 @@ class RecordsPackage # The status report as one self-contained HTML file (styles inlined). def status_report_html - html = ApplicationController.render("maintenance_reports/show", layout: "report", - assigns: { report: MaintenanceReport.new(@aircraft) }) + inline_styles(ApplicationController.render("maintenance_reports/show", layout: "report", assigns: { report: MaintenanceReport.new(@aircraft) })) + end + + def standalone_html(body, title) + inline_styles(ApplicationController.render(html: body.html_safe, layout: "report", assigns: {}).sub(%r{.*?}m, "#{ERB::Util.h(title)}")) + end + + def inline_styles(html) css = %w[tailwind.css application.css].filter_map { Rails.application.assets.load_path.find(_1)&.content }.join("\n") html.gsub(%r{]*>\s*}, "").sub("", "") .gsub(%r{]*>.*?}m, "").gsub(%r{]*>\s*}, "") diff --git a/app/views/admin/about/show.html.erb b/app/views/admin/about/show.html.erb index e608603..5443bcc 100644 --- a/app/views/admin/about/show.html.erb +++ b/app/views/admin/about/show.html.erb @@ -93,7 +93,10 @@ [ "Checked", check ? "#{number_with_delimiter(check.versions_checked)} history entries, #{number_with_delimiter(check.signatures_checked)} signatures" : nil ], [ "Last backup", backup ? "#{l(backup.created_at, format: :short)} · #{backup.ok ? number_to_human_size(backup.bytes) : 'FAILED'}" : "not run yet" ], [ "Backup check", backup&.message ], - [ "Backups kept", "#{Setting.integer('backups_kept')} (in storage/backups)" ] + [ "Backups kept", "#{Setting.integer('backups_kept')} (in storage/backups)" ], + [ "Procedures", (r = ProceduresRevision.current) ? "Revision #{r.number}, adopted #{r.adopted_at.to_date}" : tag.span("not adopted", class: "badge-orange") ], + [ "Last audit", AuditRun.latest ? "#{AuditRun.latest.performed_at.to_date} · #{AuditRun.latest.passed ? 'passed' : 'items not passed'}" : "none yet" ], + [ "Next audit due", AuditRun.due_soon? ? tag.span(AuditRun.next_due.to_s, class: "badge-orange") : AuditRun.next_due.to_s ] ] %> <% if check && !check.ok %> diff --git a/app/views/admin/audits/index.html.erb b/app/views/admin/audits/index.html.erb new file mode 100644 index 0000000..660fc6f --- /dev/null +++ b/app/views/admin/audits/index.html.erb @@ -0,0 +1,20 @@ +<% content_for :title, "Records audits" %> +
+
+

Records audits

+

Quality-control audits of the electronic records (AC 120-78B 3.2.8.5), every <%= RecordkeepingPolicy.current.audit_interval_months %> months. Next due <%= AuditRun.next_due %>.

+
+ <%= link_to "Start an audit", new_admin_audit_path, class: "btn-primary" %> +
+
+ <% if @audits.any? %> + + <% else %><%= empty_state "No audits yet." %><% end %> +
diff --git a/app/views/admin/audits/new.html.erb b/app/views/admin/audits/new.html.erb new file mode 100644 index 0000000..5257e17 --- /dev/null +++ b/app/views/admin/audits/new.html.erb @@ -0,0 +1,39 @@ +<% content_for :title, "Records audit" %> +

Records audit

+

Work through each item; the app has checked the first ones itself.

+<%= form_with url: admin_audits_path, class: "space-y-5" do %> +
+

Checked by the app

+ +
+ + <% sample = @audit.sample %> +
+

Confirmed by you

+
+ <% RecordsAudit::MANUAL.each do |key, title| %> +
+ + <% if key == "sample" %> +
    + <% sample.each do |e| %>
  • <%= hidden_field_tag "sample_ids[]", e.id, id: nil %><%= link_to "#{e.aircraft.tail_number} · #{e.date} · #{e.text.truncate(80)}", aircraft_logbook_entry_path(e.aircraft, e), class: "link", target: "_blank" %><%= " (signed)" if e.signature %>
  • <% end %> + <% if sample.empty? %>
  • No entries since the last audit.
  • <% end %> +
+ <% elsif key == "users" %> +
    + <% @audit.users.each do |u| %>
  • <%= u.display_name %> (<%= u.email_address %>)<%= " · admin" if u.admin? %><%= " · #{u.aircraft_roles.map { "#{_1.role} #{_1.aircraft.tail_number}" }.join(', ')}" if u.aircraft_roles.any? %> · last sign-in <%= u.last_signed_in_at ? time_ago_in_words(u.last_signed_in_at) + " ago" : "never" %><%= " · DISABLED" if u.disabled? %>
  • <% end %> +
+ <% end %> + <%= text_field_tag "answers[#{key}][note]", nil, class: "input", placeholder: "Note (what was checked, or what's being done)" %> +
+ <% end %> +
<%= label_tag :notes, "Overall notes", class: "label" %><%= text_area_tag :notes, nil, rows: 3, class: "input" %>
+ <%= submit_tag "Record audit", class: "btn-primary" %> +
+
+<% end %> diff --git a/app/views/admin/audits/show.html.erb b/app/views/admin/audits/show.html.erb new file mode 100644 index 0000000..b218242 --- /dev/null +++ b/app/views/admin/audits/show.html.erb @@ -0,0 +1,14 @@ +<% content_for :title, "Records audit" %> +

Records audit, <%= @audit.performed_at.to_date %>

+

By <%= @audit.performed_by&.display_name %> · <%= @audit.passed ? "Passed" : "Items not passed" %>

+
+ + <% if @audit.notes.present? %>
<%= @audit.notes %>
<% end %> +
+

<%= link_to "All audits", admin_audits_path, class: "link" %>

diff --git a/app/views/admin/procedures/_document.html.erb b/app/views/admin/procedures/_document.html.erb new file mode 100644 index 0000000..0e87a38 --- /dev/null +++ b/app/views/admin/procedures/_document.html.erb @@ -0,0 +1,115 @@ +<%# The procedures document (AC 120-78B 2.2.11, 3.2.8), generated from the system's setup. + Locals: policy, number, adopted_at, adopted_by, revisions, summary. %> +<% info = SystemInfo.new %> +<% aircraft = Aircraft.ordered.includes(:roles) %> +<% users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) %> +<% h2 = "mt-6 text-base font-semibold" %> +<% p_ = "mt-1 text-sm leading-relaxed" %> +
+
+

Standalone procedures document · AC 120-78B paragraphs 2.2.11 and 3.2.8

+

Electronic Signature and Recordkeeping Procedures

+

<%= policy.operator_name.presence || "[Operator]" %> · Simple Aircraft Manager

+

Revision <%= number %><%= adopted_at ? " · adopted #{adopted_at.to_date.iso8601} by #{adopted_by&.display_name}" : " · not yet adopted" %>

+
+ +

1. Purpose and scope

+

These procedures describe how <%= policy.operator_name.presence || "[Operator]" %> keeps the maintenance records required by 14 CFR 91.417 electronically in Simple Aircraft Manager, and how entries are signed electronically under 14 CFR 43.9 and 43.11. They follow FAA AC 120-78B. Under its paragraph 1.9.5, use of electronic signatures and recordkeeping under part 91 (other than subpart K) needs no FAA approval, acceptance or authorization; the FAA recommends following the AC, and these procedures do.

+ + + + <% aircraft.each do |a| %> + + + <% end %> + +
AircraftSerial numberElectronic records sinceEarlier records
<%= a.tail_number %> <%= [ a.make, a.model ].compact_blank.join(" ") %><%= a.serial_number.presence || "—" %><%= a.electronic_records_since || "not set" %>Paper logbooks<%= " (scans held as legacy records)" if a.documents.where(legacy_record: true).exists? %>
+

Records kept electronically: logbook entries (maintenance, preventive maintenance, inspections, alterations), inspection status and history, airworthiness directive compliance, component times and life limits, major repairs and alterations with their Form 337s, weight and balance, and supporting documents. Paper logbooks from before the date above remain the record for that period and are kept.

+ +

2. Regulatory compliance

+

Each logbook entry carries what 14 CFR 43.9 requires (description of the work, date, the name, certificate number and kind of certificate of the person approving return to service, and their signature) and, for inspections, what 43.11 requires (type and extent of inspection, aircraft time in service, and the airworthiness statement or discrepancy list). The app flags entries missing any of these. Records include the key elements of AC 120-78B 3.1.1: the event, when (date, and the signature's time), where (location), who, the signature, and the make, model and serial of the aircraft, engine, propeller and components. The status required by 91.417(a)(2) is produced by the maintenance status report. Records are made available under 91.417(c) and transferred under 91.419 as described in sections 9 and 10.

+ +

3. System description

+ + +

4. Responsible personnel

+

<%= policy.responsible_name.presence || "[Name]" %><%= ", #{policy.responsible_title}" if policy.responsible_title.present? %>, has authority and overall responsibility for the electronic signature process and the recordkeeping system, for controlling access to it (accounts, roles, disabling accounts), and for the quality-control audits. Administrators: <%= users.select(&:admin?).reject(&:disabled?).map(&:display_name).to_sentence.presence || "none" %>.

+ +

5. Defined users and roles

+

Owners keep an aircraft's records; pilots can view them and record flights, squawks and preventive maintenance. A user may sign entries with a current certificate on their profile: mechanic certificates (A&P, IA, airframe, powerplant, repair station, repairman) for maintenance and inspection entries; a pilot certificate for preventive maintenance only. Disabled accounts can't sign in or sign.

+ + + + <% users.each do |u| %> + <% current = u.certificates.reject(&:expired?) %> + + + + + <% end %> + +
UserRolesCertificatesMay sign
<%= u.display_name %>
<%= u.email_address %>
<%= [ ("Administrator" if u.admin?), *u.aircraft_roles.map { "#{_1.role.capitalize}, #{_1.aircraft.tail_number}" } ].compact.join("; ").presence || "—" %><%= " (DISABLED)" if u.disabled? %><%= u.certificates.map { "#{_1.short_label} #{_1.number}#{" exp. #{_1.expires_on}" if _1.expires_on}" }.join("; ").presence || "—" %><%= if u.disabled? || current.empty? then "No" + elsif current.any?(&:mechanic?) then "Maintenance and inspection entries" + else "Preventive maintenance entries" end %>
+

People outside these users (e.g. a mechanic who did the work) sign through a one-time email invitation from an owner, with their own account and certificate, for that entry only; or they sign on paper (section 11).

+ +

6. Electronic signature process

+
    +
  1. The signer opens the entry and chooses Sign. The entry is shown in full exactly as it will be certified (AC 2.2.4).
  2. +
  3. They choose one of their own current certificates. The statement they will certify is shown with it, under the heading “Certified by” (2.2.2): for maintenance, “I certify that the work described in this entry was performed in accordance with 14 CFR Part 43, and I approve it for return to service with respect to that work”; for inspections, the 43.11(a)(5) statement; for preventive maintenance by a pilot, the corresponding statement.
  4. +
  5. They prove who they are again: their password, or signing in again with single sign-on within the last five minutes (2.2.6), and confirm that they are signing with intent to sign (2.1.2.4–5).
  6. +
  7. The system records the signer, the certificate (kind and number), the statement, the time (UTC), how they authenticated, their network address and browser, a SHA-256 fingerprint of the entry's content and a readable copy of it, and a server seal (HMAC) over the signature record (2.1.2.6, 2.2.5). The signer is told on screen and by email (2.2.3).
  8. +
  9. Once signed, the entry and its components can't be edited or deleted (2.1.2.7–8, 2.2.7). A correction is made as a new entry that, once signed, supersedes the original; the original and its signature are kept and marked superseded (2.2.8).
  10. +
  11. When someone no longer needs access, the responsible person disables their account: they can no longer sign in or sign, and their past signatures stay valid (2.2.6.4).
  12. +
+

Signed records are archived in the database, its nightly verified copies and the off-site backup, and can be exported with their signatures (2.2.9).

+ +

7. Recordkeeping system controls

+ + +

8. Quality control and auditing

+

Every <%= policy.audit_interval_months %> months the responsible person carries out and records an audit in the system (3.2.8.5). The app checks that the integrity check and backups are passing, the procedures are adopted, signatures are intact, and lists expired certificates and software versions since the last audit. The auditor restores the off-site backup somewhere separate and opens it, compares <%= policy.audit_sample_size %> randomly chosen entries with their work orders or source documents, reviews the users and roles (disabling accounts no longer needed), and confirms the paper logbooks are kept. Audit results are kept in the system.<%= " Last audit: #{AuditRun.latest.performed_at.to_date}." if AuditRun.latest %>

+ +

9. Making records available to the FAA and NTSB

+

On request (14 CFR 91.417(c), 49 CFR 830), the responsible person provides the records package for the aircraft: every logbook entry as a PDF with its electronic signature, a signature register, the full change history, the maintenance status report and the data archive, with a README. Printed copies are produced the same way. Direct access to the system can be offered but isn't required (3.2.8.6).

+ +

10. Transfer of records

+

At sale (91.419, 3.2.8.12): the buyer receives the records package and the data archive, which another installation of the system can import, together with the paper logbooks. To another system (3.2.8.9): records are exported as the data archive and the records package; both systems run side by side until the transfer is checked.

+ +

11. Continuity

+

Legacy records (3.2.8.10): records before the dates in section 1 are the paper logbooks, which are kept; scans are held as legacy records for reference. Maintenance providers (3.2.8.11): a provider signs electronically through an invitation, or signs a printed entry in ink; the signed paper is kept with the logbooks and scanned into the system.

+ +

12. Changes to the system and these procedures

+

These procedures are revised when the system or its use changes. Each revision is numbered, dated and adopted in the system by an administrator; earlier revisions are kept. Under AC 120-78B 1.9.5 no submission to the FAA is required for part 91 operations (3.2.8.13).

+ +

13. User instructions and training

+

Every user who keeps or signs records reads these instructions (also in the system under “How electronic records work”) before signing (2.2.12, 3.2.9).

+
<%= render "help/records_content" %>
+ + <% if policy.additional_procedures.present? %> +

14. Additional procedures

+
<%= policy.additional_procedures %>
+ <% end %> + +

Revision history

+ + + + <% revisions.each do |r| %><% end %> + + +
RevisionAdoptedBySummary
<%= r.number %><%= r.adopted_at.to_date %><%= r.adopted_by&.display_name %><%= r.summary %>
<%= number %><%= adopted_at&.to_date || "—" %><%= adopted_by&.display_name %><%= summary.presence || "This revision" %>
+
diff --git a/app/views/admin/procedures/show.html.erb b/app/views/admin/procedures/show.html.erb new file mode 100644 index 0000000..76160b7 --- /dev/null +++ b/app/views/admin/procedures/show.html.erb @@ -0,0 +1,51 @@ +<% content_for :title, "Recordkeeping procedures" %> +

Recordkeeping procedures

+

The standalone procedures document AC 120-78B asks for (paragraphs 2.2.11 and 3.2.8): how signatures and records work here, who's responsible, who may sign, backups, audits, and how records are produced and transferred. It's generated from the system's setup; fill in what the app can't know, review the draft, and adopt it as a revision. Adopt a new revision whenever users, hosting or procedures change.

+ +
+ <%= form_with model: @policy, url: admin_procedures_path, method: :patch, class: "card card-body space-y-4" do |f| %> +

Details

+ <%= f.errors_summary %> + <%= f.field :operator_name, label: "Owner / operator", placeholder: "Jane Pilot" %> +
+ <%= f.field :responsible_name, label: "Responsible person", placeholder: "Jane Pilot" %> + <%= f.field :responsible_title, label: "Their role", placeholder: "Owner" %> +
+ <%= f.field :hosting_description, as: :textarea, rows: 2, label: "Hosting and network", + placeholder: "Self-hosted on a server at the owner's home, behind a firewall and an authenticating proxy." %> + <%= f.field :offsite_backup_description, as: :textarea, rows: 2, label: "Off-site backup", + placeholder: "The storage volume is backed up nightly with restic to an encrypted off-site repository; retention 30 days." %> +
+ <%= f.field :audit_interval_months, as: :number, min: 1, max: 24, label: "Audit every (months)" %> + <%= f.field :audit_sample_size, as: :number, min: 1, max: 50, label: "Entries sampled per audit" %> +
+ <%= f.field :additional_procedures, as: :textarea, rows: 3, label: "Additional procedures (optional)" %> + <%= f.submit "Save" %> + <% end %> + +
+
+

Current revision

+ <% current = @revisions.first %> + <% if current %> +

Revision <%= current.number %>, adopted <%= current.adopted_at.to_date %> by <%= current.adopted_by&.display_name %>. <%= link_to "View / print", revision_admin_procedures_path(current), class: "link", target: "_blank" %>

+ <% else %> +

No revision adopted yet.

+ <% end %> +

<%= link_to "Preview the draft", draft_admin_procedures_path, class: "link", target: "_blank" %> (generated from the current setup).

+ <%= form_with url: adopt_admin_procedures_path, class: "flex flex-wrap items-end gap-2" do %> +
<%= label_tag :summary, "What changed", class: "label" %><%= text_field_tag :summary, nil, class: "input", placeholder: current ? "e.g. new mechanic added" : "Initial issue" %>
+ <%= submit_tag "Adopt as revision #{(current&.number || 0) + 1}", class: "btn-primary", disabled: !@policy.complete?, + title: (@policy.complete? ? nil : "Fill in the operator, responsible person, hosting and off-site backup first") %> + <% end %> +
+
+

Earlier revisions

+ <% if @revisions.size > 1 %> +
    + <% @revisions.drop(1).each do |r| %>
  • Revision <%= r.number %> · <%= r.adopted_at.to_date %> · <%= r.summary %><%= link_to "View", revision_admin_procedures_path(r), class: "link", target: "_blank" %>
  • <% end %> +
+ <% else %><%= empty_state "None." %><% end %> +
+
+
diff --git a/app/views/entry_signatures/_form.html.erb b/app/views/entry_signatures/_form.html.erb index ba01be4..e5dde04 100644 --- a/app/views/entry_signatures/_form.html.erb +++ b/app/views/entry_signatures/_form.html.erb @@ -2,7 +2,7 @@

Sign this entry

-

Review the entry: your signature will cover exactly what's shown here, and it can't be changed afterwards. A mistake is fixed with a correction entry.

+

Review the entry: your signature will cover exactly what's shown here, and it can't be changed afterwards. A mistake is fixed with a correction entry. <%= link_to "How signing works", records_help_path, class: "link", target: "_blank" %>

<%= render "logbook_entries/content", entry: entry %> <% if @signing_error %> diff --git a/app/views/help/_records_content.html.erb b/app/views/help/_records_content.html.erb new file mode 100644 index 0000000..074a0ac --- /dev/null +++ b/app/views/help/_records_content.html.erb @@ -0,0 +1,21 @@ +<%# User instructions for electronic records (also an appendix of the procedures document). %> +
+

Writing an entry

+

On the aircraft's Logbook tab, choose + New Entry. Give the date, the logbook (aircraft, engine, propeller), the airframe total time, and what was done; for an engine or propeller entry pick the component (its times fill in) and tick any sub-components. A template can start the wording. An entry isn't a signed record until it's signed.

+

Signing

+
    +
  1. Add your certificate (kind and number) once, on your profile.
  2. +
  3. Open the entry and choose Sign. Read the entry as shown: your signature covers exactly that.
  4. +
  5. Pick the certificate you're signing with. The statement you'll certify is shown with it (return to service, or the inspection statement).
  6. +
  7. Re-enter your password, or sign in again with single sign-on, tick the confirmation and choose Sign entry. You'll see a confirmation and get an email.
  8. +
+

Never share your password or let someone else sign while you're signed in: a signature is yours alone. If you think someone has, tell the administrator straight away.

+

Mistakes

+

A signed entry can't be edited or deleted. Open it and choose Correct this entry: a new entry starts from the original; fix it, save, and sign it. The original stays, marked “Superseded by a correction”.

+

Someone else did the work

+

The owner can choose Ask someone to sign on the entry: the mechanic gets a one-time email link, signs in or creates their own account, adds their certificate and signs. If they prefer paper, print the entry (Print for logbook), have it signed in ink, and keep the paper with the logbooks (scan it into Documents).

+

Checking a record

+

A signed entry shows who certified it, with which certificate, when (UTC), what they certified, and its status. Valid means nothing has changed since signing. The fingerprint (a SHA-256 of the entry) is printed on paper copies so a copy can be matched to the record. Every change to any record is kept under Activity → Record history.

+

If the system is down

+

Make the entry on paper and sign it in ink. When the system is back, add the entry and scan the signed paper into Documents; the paper itself stays with the logbooks and remains the signed record for that entry.

+
diff --git a/app/views/help/records.html.erb b/app/views/help/records.html.erb new file mode 100644 index 0000000..9ad2711 --- /dev/null +++ b/app/views/help/records.html.erb @@ -0,0 +1,6 @@ +<% content_for :title, "How electronic records work" %> +
+

How electronic records work

+

Instructions for everyone who keeps or signs maintenance records here.

+ <%= render "help/records_content" %> +
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 25b4de8..77a473d 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -37,7 +37,7 @@ <%= link_to "Profile", edit_profile_path, class: "block px-4 py-2.5 hover:bg-slate-100" %> <% if current_user.admin? %>

Admin

- <% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Logbook Templates", admin_logbook_templates_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %> + <% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Logbook Templates", admin_logbook_templates_path ], [ "Settings", edit_admin_settings_path ], [ "Recordkeeping Procedures", admin_procedures_path ], [ "Records Audits", admin_audits_path ], [ "About", admin_about_path ] ].each do |label, path| %> <%= link_to label, path, class: "block px-4 py-2.5 hover:bg-slate-100" %> <% end %> <% end %> @@ -53,7 +53,7 @@ Admin
- <% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Logbook Templates", admin_logbook_templates_path ], [ "Settings", edit_admin_settings_path ], [ "About", admin_about_path ] ].each do |label, path| %> + <% [ [ "Users", admin_users_path ], [ "Component Types", admin_component_types_path ], [ "Airports", admin_airports_path ], [ "Logbook Templates", admin_logbook_templates_path ], [ "Settings", edit_admin_settings_path ], [ "Recordkeeping Procedures", admin_procedures_path ], [ "Records Audits", admin_audits_path ], [ "About", admin_about_path ] ].each do |label, path| %> <%= link_to label, path, class: [ "block px-4 py-2 text-sm hover:bg-slate-100", ("font-semibold text-sky-700" if current_page?(path)) ] %> <% end %>
diff --git a/app/views/logbook_entries/index.html.erb b/app/views/logbook_entries/index.html.erb index 85d706b..7db7e3c 100644 --- a/app/views/logbook_entries/index.html.erb +++ b/app/views/logbook_entries/index.html.erb @@ -2,7 +2,7 @@ <%= render "shared/aircraft_header", aircraft: @aircraft %>
-

Maintenance Logbook

+

Maintenance Logbook <%= link_to "How records and signing work", records_help_path, class: "link ml-2 text-xs font-normal" %>

<%= form_with url: aircraft_logbook_entries_path(@aircraft), method: :get, class: "flex w-full flex-wrap gap-2 sm:w-auto" do |f| %> <%= f.search_field :q, value: @query, placeholder: "Search entries…", class: "input min-w-0 flex-1 sm:w-48 sm:flex-none" %> diff --git a/app/views/reminder_mailer/weekly.html.erb b/app/views/reminder_mailer/weekly.html.erb index 089b727..8af7a12 100644 --- a/app/views/reminder_mailer/weekly.html.erb +++ b/app/views/reminder_mailer/weekly.html.erb @@ -18,6 +18,7 @@ <% @certificates.each do |c| %>
  • <%= c.expired? ? "Expired" : "Expires" %> <%= c.expires_on %>: <%= c.kind_label %> <%= c.number %>
  • <% end %> <% end %> +<% if @audit_due %>

    Records audit due <%= @audit_due %> (AC 120-78B quality control): <%= link_to "start it", new_admin_audit_url %>.

    <% end %>

    Based on the records in Simple Aircraft Manager. Turn these emails off on your <%= link_to "profile", edit_profile_url %>.

    diff --git a/app/views/reminder_mailer/weekly.text.erb b/app/views/reminder_mailer/weekly.text.erb index 695048c..abbb1bd 100644 --- a/app/views/reminder_mailer/weekly.text.erb +++ b/app/views/reminder_mailer/weekly.text.erb @@ -16,5 +16,9 @@ Your certificates: - <%= c.expired? ? "Expired" : "Expires" %> <%= c.expires_on %>: <%= c.kind_label %> <%= c.number %> <% end %> <% end %> +<% if @audit_due %> + +Records audit due <%= @audit_due %>: <%= new_admin_audit_url %> +<% end %> Based on the records in Simple Aircraft Manager. Turn these emails off on your profile: <%= edit_profile_url %> diff --git a/config/routes.rb b/config/routes.rb index fc03655..da80ec9 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -108,6 +108,7 @@ Rails.application.routes.draw do end get "airports/search", to: "airports#search", as: :airport_search + get "help/records", to: "help#records", as: :records_help # Public read-only share links (no login). # Invited signers (outside mechanics) sign one entry. @@ -127,6 +128,12 @@ Rails.application.routes.draw do end get "about", to: "about#show" resource :settings, only: %i[edit update] + resource :procedures, only: %i[show update] do + get :draft + post :adopt + get "revisions/:id", action: :revision, as: :revision + end + resources :audits, only: %i[index new create show] resources :logbook_templates, except: :show do collection { post :restore } end diff --git a/db/migrate/20261108030000_create_recordkeeping_procedures.rb b/db/migrate/20261108030000_create_recordkeeping_procedures.rb new file mode 100644 index 0000000..cec8fa0 --- /dev/null +++ b/db/migrate/20261108030000_create_recordkeeping_procedures.rb @@ -0,0 +1,37 @@ +# AC 120-78B 2.2.11 / 3.2.8: the procedures document (generated from the +# system and a few owner-supplied facts, adopted as numbered revisions) and +# the QC audits it calls for (3.2.8.5). +class CreateRecordkeepingProcedures < ActiveRecord::Migration[8.1] + def change + create_table :recordkeeping_policies do |t| + t.string :operator_name + t.string :responsible_name + t.string :responsible_title + t.text :hosting_description + t.text :offsite_backup_description + t.integer :audit_interval_months, null: false, default: 6 + t.integer :audit_sample_size, null: false, default: 5 + t.text :additional_procedures + t.timestamps + end + + create_table :procedures_revisions do |t| + t.integer :number, null: false + t.references :adopted_by, foreign_key: { to_table: :users, on_delete: :nullify } + t.datetime :adopted_at, null: false + t.text :summary + t.text :content, null: false + t.timestamps + end + add_index :procedures_revisions, :number, unique: true + + create_table :audit_runs do |t| + t.references :performed_by, foreign_key: { to_table: :users, on_delete: :nullify } + t.datetime :performed_at, null: false + t.boolean :passed, null: false + t.json :results, null: false + t.text :notes + t.timestamps + end + end +end diff --git a/db/schema.rb b/db/schema.rb index 724bc0b..a9460af 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_08_020000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_08_030000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -294,6 +294,17 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_020000) do t.index ["revision"], name: "index_app_revisions_on_revision", unique: true end + create_table "audit_runs", force: :cascade do |t| + t.integer "performed_by_id" + t.datetime "performed_at", null: false + t.boolean "passed", null: false + t.json "results", null: false + t.text "notes" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["performed_by_id"], name: "index_audit_runs_on_performed_by_id" + end + create_table "backup_runs", force: :cascade do |t| t.boolean "ok", null: false t.string "path" @@ -612,6 +623,18 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_020000) do t.index ["component_id"], name: "index_oil_analyses_on_component_id" end + create_table "procedures_revisions", force: :cascade do |t| + t.integer "number", null: false + t.integer "adopted_by_id" + t.datetime "adopted_at", null: false + t.text "summary" + t.text "content", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["adopted_by_id"], name: "index_procedures_revisions_on_adopted_by_id" + t.index ["number"], name: "index_procedures_revisions_on_number", unique: true + end + create_table "record_versions", force: :cascade do |t| t.integer "aircraft_id" t.string "item_type", null: false @@ -627,6 +650,19 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_020000) do t.index ["item_type", "item_id"], name: "index_record_versions_on_item_type_and_item_id" end + create_table "recordkeeping_policies", force: :cascade do |t| + t.string "operator_name" + t.string "responsible_name" + t.string "responsible_title" + t.text "hosting_description" + t.text "offsite_backup_description" + t.integer "audit_interval_months", default: 6, null: false + t.integer "audit_sample_size", default: 5, null: false + t.text "additional_procedures" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + create_table "sessions", force: :cascade do |t| t.integer "user_id", null: false t.string "ip_address" @@ -763,6 +799,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_020000) do add_foreign_key "aircraft_roles", "users" add_foreign_key "airport_updates", "users", column: "requested_by_id", on_delete: :nullify add_foreign_key "airworthiness_directives", "documents", on_delete: :nullify + add_foreign_key "audit_runs", "users", column: "performed_by_id", on_delete: :nullify add_foreign_key "components", "aircraft" add_foreign_key "components", "component_types" add_foreign_key "components", "components", column: "parent_component_id" @@ -797,6 +834,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_08_020000) do add_foreign_key "major_records", "logbook_entries", on_delete: :nullify add_foreign_key "oil_analyses", "aircraft" add_foreign_key "oil_analyses", "components" + add_foreign_key "procedures_revisions", "users", column: "adopted_by_id", on_delete: :nullify add_foreign_key "sessions", "users" add_foreign_key "share_tokens", "aircraft" add_foreign_key "share_tokens", "users", column: "created_by_id", on_delete: :nullify diff --git a/test/integration/recordkeeping_procedures_test.rb b/test/integration/recordkeeping_procedures_test.rb new file mode 100644 index 0000000..94b775a --- /dev/null +++ b/test/integration/recordkeeping_procedures_test.rb @@ -0,0 +1,101 @@ +require "test_helper" + +# Recordkeeping procedures, QC audits and user instructions (AC 120-78B 2.2.11, 3.2.8). +class RecordkeepingProceduresTest < ActionDispatch::IntegrationTest + include ActionMailer::TestHelper + + setup do + @admin = create_user("admin@example.com", admin: true) + @a = create_aircraft(owner: @admin, tail_number: "N12345") + end + + def fill_policy + patch admin_procedures_path, params: { recordkeeping_policy: { + operator_name: "Jane Pilot", responsible_name: "Jane Pilot", responsible_title: "Owner", + hosting_description: "Self-hosted server behind a firewall.", offsite_backup_description: "Nightly encrypted off-site copy.", + audit_interval_months: 6, audit_sample_size: 3 } } + end + + test "admins fill in the details, preview the draft and adopt numbered, unchangeable revisions" do + sign_in @admin + get admin_procedures_path + assert_response :success + post adopt_admin_procedures_path, params: { summary: "Initial issue" } + assert_equal 0, ProceduresRevision.count # incomplete details + fill_policy + assert RecordkeepingPolicy.current.complete? + get draft_admin_procedures_path + assert_response :success + assert_includes response.body, "Jane Pilot" + assert_includes response.body, "Self-hosted server behind a firewall." + post adopt_admin_procedures_path, params: { summary: "Initial issue" } + r1 = ProceduresRevision.current + assert_equal 1, r1.number + assert_includes r1.content, "Initial issue" + post adopt_admin_procedures_path, params: { summary: "Added a mechanic" } + assert_equal 2, ProceduresRevision.current.number + get revision_admin_procedures_path(r1) + assert_includes response.body, "Jane Pilot" + assert_raises(ActiveRecord::RecordNotSaved) { r1.update!(content: "x") } + get admin_about_path + assert_includes response.body, "Revision 2" + end + + test "non-admins can't reach procedures or audits" do + sign_in create_user("pilot@example.com") + get admin_procedures_path + assert_response :redirect + get new_admin_audit_path + assert_response :redirect + end + + test "an audit combines the app's checks with the auditor's answers and sets the next due date" do + sign_in @admin + e = @a.logbook_entries.create!(date: Date.new(2026, 10, 1), entry_type: "MAINTENANCE", text: "Changed oil", aircraft_hours_at_entry: 1000) + assert AuditRun.due_soon? # never audited + get new_admin_audit_path + assert_response :success + assert_includes response.body, "Changed oil" + assert_includes response.body, "admin@example.com" + answers = RecordsAudit::MANUAL.keys.index_with { { passed: "1", note: "ok" } } + post admin_audits_path, params: { answers: answers, notes: "All good", sample_ids: [ e.id ] } + run = AuditRun.latest + assert_redirected_to admin_audit_path(run) + refute run.passed # no integrity check or backup has run yet + assert run.results.find { _1["key"] == "restore_test" }["passed"] + assert_includes run.results.find { _1["key"] == "sample_entries" }["detail"], "N12345" + assert_equal (run.performed_at + 6.months).to_date, AuditRun.next_due + refute AuditRun.due_soon? + get admin_audit_path(run) + assert_includes response.body, "All good" + assert_raises(ActiveRecord::RecordNotSaved) { run.update!(notes: "x") } + + IntegrityCheck.create!(ok: true, problems: []) + BackupRun.create!(ok: true, message: "ok", path: "x") + fill_policy + post adopt_admin_procedures_path + post admin_audits_path, params: { answers: answers, sample_ids: [] } + assert AuditRun.latest.passed + end + + test "admins get a reminder when an audit is coming due" do + assert ReminderMailer.anything_for?(@admin) + mail = ReminderMailer.weekly(@admin) + assert_includes mail.subject, "Records audit due" + assert_includes mail.text_part.body.to_s, "/admin/audits/new" + refute ReminderMailer.audit_due_for?(create_user("pilot@example.com")) + end + + test "the records package includes the adopted procedures, and users have instructions" do + sign_in @admin + fill_policy + post adopt_admin_procedures_path + path = Rails.root.join("tmp", "package-test-#{SecureRandom.hex(4)}.zip") + RecordsPackage.new(@a, source: "test").write_to(path) + names = Zip::File.open(path) { |z| z.map(&:name) } + File.delete(path) + assert_includes names, "recordkeeping-procedures.html" + get records_help_path + assert_response :success + end +end