Move all user-facing text into config/locales/en.yml for localization

- Views use lazy t(".key") lookups; sentences with values or links stay
  whole (interpolation, _html keys); counts use one/other plurals
- Stored-value labels (statuses, types, priorities...) are LabelSets read
  from labels: in the current locale; field names and validation messages
  under activerecord:; flash and activity text under flash:
- Services, models, helpers, mailer subjects, the logbook PDF, procedures
  templates, records package README and transcription warnings localized;
  the PDF reuses LogbookEntry#certification_statement instead of a copy
- Scripts read js: strings from a JSON tag via app/javascript/i18n.js
- Dates through I18n.l (app, weekday, month_year, long formats); html lang
  follows the locale
- APP_LOCALE picks the language (falls back to English); missing
  translations raise in development and tests
- README: Translating section and APP_LOCALE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
rickyandClaude Opus 5.5 committed 2026-11-13 22:08:20 -05:00
1 parent 3f45b557c2
commit 89ed0a76f9
313 files changed
+6387 -2653

No files matched your search

+13
View File
@@ -74,6 +74,7 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai
| `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). | | `APP_HOST` | Host name the app is reached at, used in email links (password resets, sign-in links, signing invitations, reminders). |
| `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable email: password resets and **Email me a sign-in link**. Without them an admin resets passwords from **Users**. Check the setup with **Admin → About → Send test email**. | | `SMTP_ADDRESS`, `SMTP_PORT`, `SMTP_USERNAME`, `SMTP_PASSWORD`, `MAIL_FROM` | Optional. They enable email: password resets and **Email me a sign-in link**. Without them an admin resets passwords from **Users**. Check the setup with **Admin → About → Send test email**. |
| `SMTP_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. | | `SMTP_TLS` | `true` for servers that use TLS from the start. That's the default on port 465; other ports upgrade with STARTTLS. |
| `APP_LOCALE` | Optional. The app's language, e.g. `es` for `config/locales/es.yml` (see [Translating](#translating)). Default `en`. |
| `ANTHROPIC_API_KEY` | Optional. Lets Claude transcribe scanned logbook pages into entries (**Logbook → Import scans**). Without it, scans are only uploaded. | | `ANTHROPIC_API_KEY` | Optional. Lets Claude transcribe scanned logbook pages into entries (**Logbook → Import scans**). Without it, scans are only uploaded. |
| `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). | | `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). |
| `APP_URL` | Optional public base URL, e.g. `https://aircraft.example.com` (default `https://APP_HOST`). Used for the SSO and Google Drive redirect URIs. | | `APP_URL` | Optional public base URL, e.g. `https://aircraft.example.com` (default `https://APP_HOST`). Used for the SSO and Google Drive redirect URIs. |
@@ -198,6 +199,18 @@ The MCP server for AI agents, invitation codes, per-aircraft feature switches, t
AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable PWA. AirTrail sync and export, an airport database, FAA DRS AD import, spreadsheet flight import, engine monitor data (CGR-30P/C) with interactive charts, AvLab and Blackstone oil analysis import with trends, multiple squawk attachments with a photo viewer, AI logbook transcription with Claude (images and PDFs), printable logbook entries, electronic signatures and recordkeeping along the lines of AC 120-78B (record history, nightly integrity checks, records package, procedures and audits), off-site backup to Google Drive, a user guide, and an installable PWA.
## Translating
Every piece of text the app shows (pages, emails, messages, labels, printed logbook entries, the procedures and records-package text, and the scripts' messages) is in [`config/locales/en.yml`](config/locales/en.yml). To translate the app:
1. Copy `en.yml` to `<locale>.yml` (for example `es.yml`), change the top key from `en:` to `es:`, and translate the values. Keep the `%{name}` placeholders and any HTML tags in keys ending in `_html`. Keys with `one:` / `other:` are counted forms.
2. For month and day names in dates, also add that language's standard Rails translations (for example from the [rails-i18n](https://github.com/svenfuchs/rails-i18n) project).
3. Set `APP_LOCALE=es` and restart. Anything not yet translated shows in English.
Where the text lives in `en.yml`: `labels:` are the names of stored values (statuses, types, priorities); `activerecord:` holds field names and validation messages; `flash:` holds the messages shown after an action; `services:`, `models:` and `helpers:` hold text built in Ruby; `js:` holds the scripts' text; the rest are keyed by page (`<controller>.<view>.<key>`). The user guide under Help is Markdown in `docs/guide` and is translated separately.
In development and tests a missing translation raises an error, so a page that uses a key not in `en.yml` fails its test.
## Disclaimer ## Disclaimer
Simple Aircraft Manager is provided **as is**, without warranty of any kind, express or implied. It is not approved, certified or endorsed by the FAA or any other aviation authority. Simple Aircraft Manager is provided **as is**, without warranty of any kind, express or implied. It is not approved, certified or endorsed by the FAA or any other aviation authority.
+7 -7
View File
@@ -4,31 +4,31 @@ class AdAlertsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! before_action :require_owner!
before_action :set_alert, only: %i[track dismiss] before_action :set_alert, only: %i[track dismiss]
rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: "Try again in a minute." } rate_limit to: 5, within: 1.minute, only: :check, with: -> { redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.try_again_in_a") }
def check def check
found = AdWatch.new(@aircraft).check! found = AdWatch.new(@aircraft).check!
redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"),
notice: found.any? ? "Found #{helpers.pluralize(found.size, 'newly published AD')} to review." : "No new ADs found for #{AdWatch.new(@aircraft).terms.map(&:label).uniq.to_sentence}." notice: found.any? ? t("flash.ad_alerts.found", count: found.size) : t("flash.ad_alerts.none_found", terms: AdWatch.new(@aircraft).terms.map(&:label).uniq.to_sentence)
rescue AdWatch::Error => e rescue AdWatch::Error => e
redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: "Couldn't check for new ADs: #{e.message}." redirect_to aircraft_airworthiness_directives_path(@aircraft), alert: t("flash.ad_alerts.couldn_t_check_for", message: e.message)
end end
def track def track
ad = @alert.track! ad = @alert.track!
log_event("ad", "AD tracked from the Federal Register: #{ad.name}") log_event("ad", t("flash.ad_alerts.ad_tracked_from_the", name: ad.name))
redirect_to edit_aircraft_airworthiness_directive_path(@aircraft, ad), redirect_to edit_aircraft_airworthiness_directive_path(@aircraft, ad),
notice: "#{ad.name} is now tracked. Set its applicability and recurrence from the AD's text, then record compliance or mark it not applicable." notice: t("flash.ad_alerts.is_now_tracked_set", name: ad.name)
end end
def dismiss def dismiss
@alert.dismiss! @alert.dismiss!
redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: "Dismissed." redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: t("flash.ad_alerts.dismissed")
end end
def terms def terms
@aircraft.update!(ad_watch_terms: params[:ad_watch_terms].to_s.strip.first(500).presence) @aircraft.update!(ad_watch_terms: params[:ad_watch_terms].to_s.strip.first(500).presence)
redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: "Search terms saved." redirect_to aircraft_airworthiness_directives_path(@aircraft, anchor: "new-ads"), notice: t("flash.ad_alerts.search_terms_saved")
end end
private private
+6 -6
View File
@@ -9,7 +9,7 @@ class AdCompliancesController < ApplicationController
aircraft_hours_at_compliance: @aircraft.current_hours, aircraft_hours_at_compliance: @aircraft.current_hours,
compliance_method: params[:not_applicable] == "1" ? "not_applicable" : "inspection") compliance_method: params[:not_applicable] == "1" ? "not_applicable" : "inspection")
@compliance.apply_method @compliance.apply_method
@compliance.compliance_notes = "Not applicable: " if @compliance.not_applicable? @compliance.compliance_notes = t("flash.ad_compliances.not_applicable_prefix") if @compliance.not_applicable?
@compliance.fill_next_due @compliance.fill_next_due
end end
@@ -17,7 +17,7 @@ class AdCompliancesController < ApplicationController
@compliance = AdCompliance.new(compliance_params.merge(aircraft: @aircraft)) @compliance = AdCompliance.new(compliance_params.merge(aircraft: @aircraft))
if @compliance.save if @compliance.save
log_event("ad", "#{@compliance.not_applicable? ? "Marked N/A" : "Compliance recorded"}: #{@compliance.airworthiness_directive.name}") log_event("ad", "#{@compliance.not_applicable? ? "Marked N/A" : "Compliance recorded"}: #{@compliance.airworthiness_directive.name}")
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance recorded." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.ad_compliances.compliance_recorded")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -27,8 +27,8 @@ class AdCompliancesController < ApplicationController
def update def update
if @compliance.update(compliance_params) if @compliance.update(compliance_params)
log_event("ad", "Compliance updated: #{@compliance.airworthiness_directive.name}") log_event("ad", t("flash.ad_compliances.compliance_updated_2", name: @compliance.airworthiness_directive.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance updated." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.ad_compliances.compliance_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -36,8 +36,8 @@ class AdCompliancesController < ApplicationController
def destroy def destroy
@compliance.destroy! @compliance.destroy!
log_event("ad", "Compliance deleted: #{@compliance.airworthiness_directive.name}") log_event("ad", t("flash.ad_compliances.compliance_deleted", name: @compliance.airworthiness_directive.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "Compliance record deleted." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.ad_compliances.compliance_record_deleted")
end end
private private
+4 -4
View File
@@ -14,7 +14,7 @@ class AdImportsController < ApplicationController
def show def show
@token = params[:token].to_s @token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(@token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(@token)
@filename = params[:filename].to_s @filename = params[:filename].to_s
@import = AdImport.new(@aircraft, path: stored_path(@token), filename: @filename) @import = AdImport.new(@aircraft, path: stored_path(@token), filename: @filename)
@import.rows @import.rows
@@ -24,7 +24,7 @@ class AdImportsController < ApplicationController
def confirm def confirm
token = params[:token].to_s token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(token)
import = AdImport.new(@aircraft, path: stored_path(token), filename: params[:filename]) import = AdImport.new(@aircraft, path: stored_path(token), filename: params[:filename])
# Only AD numbers present in the uploaded file; values are checked against AdImport::ACTIONS. # Only AD numbers present in the uploaded file; values are checked against AdImport::ACTIONS.
decisions = params.fetch(:decisions, {}).permit(*import.rows.map(&:number)).to_h decisions = params.fetch(:decisions, {}).permit(*import.rows.map(&:number)).to_h
@@ -34,8 +34,8 @@ class AdImportsController < ApplicationController
models_covered: DrsImport.covered(@aircraft, import.rows.flat_map(&:models))) models_covered: DrsImport.covered(@aircraft, import.rows.flat_map(&:models)))
discard_upload(token) discard_upload(token)
redirect_to aircraft_airworthiness_directives_path(@aircraft), redirect_to aircraft_airworthiness_directives_path(@aircraft),
notice: "Imported #{result[:tracked]} ADs to track and #{result[:not_applicable]} marked N/A; " \ notice: t("flash.ad_imports.imported_ads_to_track", tracked: result[:tracked], not_applicable: result[:not_applicable],
"#{result[:updated]} existing ADs updated, #{result[:skipped]} skipped." updated: result[:updated], skipped: result[:skipped])
rescue AdImport::Error => e rescue AdImport::Error => e
redirect_to_upload(e.message) redirect_to_upload(e.message)
end end
+10 -10
View File
@@ -1,6 +1,6 @@
class Admin::AboutController < ApplicationController class Admin::AboutController < ApplicationController
before_action :require_admin! before_action :require_admin!
rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder check_records], with: -> { redirect_to admin_about_path, alert: "Try again in a minute." } rate_limit to: 5, within: 1.minute, only: %i[test_email test_reminder check_records], with: -> { redirect_to admin_about_path, alert: t("flash.admin_about.try_again_in_a") }
def show def show
@info = SystemInfo.new @info = SystemInfo.new
@@ -11,33 +11,33 @@ class Admin::AboutController < ApplicationController
backup = DatabaseBackup.run! backup = DatabaseBackup.run!
check = RecordsIntegrity.check! check = RecordsIntegrity.check!
if backup.ok && check.ok if backup.ok && check.ok
redirect_to admin_about_path(anchor: "records"), notice: "Backed up and checked: no problems found." redirect_to admin_about_path(anchor: "records"), notice: t("flash.admin_about.backed_up_and_checked")
else else
redirect_to admin_about_path(anchor: "records"), alert: "The records check found problems; see Records below." redirect_to admin_about_path(anchor: "records"), alert: t("flash.admin_about.the_records_check_found")
end end
end end
# This week's reminder for the current admin, now. # This week's reminder for the current admin, now.
def test_reminder def test_reminder
return redirect_to(admin_about_path, alert: "Email isn't set up yet.") unless MailSettings.configured? return redirect_to(admin_about_path, alert: t("flash.admin_about.email_isn_t_set")) unless MailSettings.configured?
unless ReminderMailer.anything_for?(current_user) unless ReminderMailer.anything_for?(current_user)
return redirect_to admin_about_path, notice: "Nothing needs attention on the aircraft you own or your certificates, so there's no reminder to send." return redirect_to admin_about_path, notice: t("flash.admin_about.nothing_needs_attention_on")
end end
ReminderMailer.weekly(current_user).deliver_now ReminderMailer.weekly(current_user).deliver_now
redirect_to admin_about_path, notice: "Reminder sent to #{current_user.email_address}." redirect_to admin_about_path, notice: t("flash.admin_about.reminder_sent_to", email_address: current_user.email_address)
rescue StandardError => e rescue StandardError => e
redirect_to admin_about_path, alert: "Sending failed: #{e.class.name.demodulize}: #{e.message.to_s.squish.truncate(240)}" redirect_to admin_about_path, alert: t("flash.admin_about.sending_failed", error: e.class.name.demodulize, message: e.message.to_s.squish.truncate(240))
end end
# Sends right away (not via the job queue) so problems show up here. # Sends right away (not via the job queue) so problems show up here.
def test_email def test_email
unless MailSettings.configured? unless MailSettings.configured?
return redirect_to admin_about_path, alert: "Email isn't set up yet: set SMTP_ADDRESS (and SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD, MAIL_FROM)." return redirect_to admin_about_path, alert: t("flash.admin_about.email_isn_t_set_2")
end end
AdminMailer.test_email(current_user).deliver_now AdminMailer.test_email(current_user).deliver_now
redirect_to admin_about_path, notice: "Test email sent to #{current_user.email_address}. If it doesn't arrive, check the spam folder." redirect_to admin_about_path, notice: t("flash.admin_about.test_email_sent_to", email_address: current_user.email_address)
rescue StandardError => e # SMTP, DNS, TLS and timeout errors alike rescue StandardError => e # SMTP, DNS, TLS and timeout errors alike
Rails.logger.warn("[test email] #{e.class}: #{e.message}") Rails.logger.warn("[test email] #{e.class}: #{e.message}")
redirect_to admin_about_path, alert: "Sending failed: #{e.class.name.demodulize}: #{e.message.to_s.squish.truncate(240)}" redirect_to admin_about_path, alert: t("flash.admin_about.sending_failed_2", error: e.class.name.demodulize, message: e.message.to_s.squish.truncate(240))
end end
end end
+5 -5
View File
@@ -16,11 +16,11 @@ class Admin::AirportsController < ApplicationController
# Queue a download + sync from OurAirports. # Queue a download + sync from OurAirports.
def refresh def refresh
if AirportUpdate.in_progress.exists? if AirportUpdate.in_progress.exists?
redirect_to admin_airports_path, alert: "An update is already running." redirect_to admin_airports_path, alert: t("flash.admin_airports.an_update_is_already")
else else
update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL, requested_by: current_user) update = AirportUpdate.create!(source_url: AirportData::SOURCE_URL, requested_by: current_user)
AirportUpdateJob.perform_later(update.id) AirportUpdateJob.perform_later(update.id)
redirect_to admin_airports_path, notice: "Airport update started. Refresh this page in a minute or two." redirect_to admin_airports_path, notice: t("flash.admin_airports.airport_update_started_refresh")
end end
end end
@@ -31,7 +31,7 @@ class Admin::AirportsController < ApplicationController
def create def create
@airport = Airport.new(airport_params.merge(custom: true)) @airport = Airport.new(airport_params.merge(custom: true))
if @airport.save if @airport.save
redirect_to admin_airports_path, notice: "Custom airport #{@airport.ident} added." redirect_to admin_airports_path, notice: t("flash.admin_airports.custom_airport_added", ident: @airport.ident)
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -41,7 +41,7 @@ class Admin::AirportsController < ApplicationController
def update def update
if @airport.update(airport_params) if @airport.update(airport_params)
redirect_to admin_airports_path, notice: "#{@airport.ident} updated." redirect_to admin_airports_path, notice: t("flash.admin_airports.updated", ident: @airport.ident)
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -49,7 +49,7 @@ class Admin::AirportsController < ApplicationController
def destroy def destroy
@airport.destroy! @airport.destroy!
redirect_to admin_airports_path, notice: "#{@airport.ident} removed." redirect_to admin_airports_path, notice: t("flash.admin_airports.removed", ident: @airport.ident)
end end
private private
+1 -1
View File
@@ -12,7 +12,7 @@ class Admin::AuditsController < ApplicationController
def create def create
answers = params.fetch(:answers, {}).permit(RecordsAudit::MANUAL.keys.index_with { %i[passed note] }).to_h 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)) 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." redirect_to admin_audit_path(run), notice: run.passed ? t("flash.admin_audits.passed") : t("flash.admin_audits.not_passed")
end end
def show def show
@@ -13,7 +13,7 @@ class Admin::ComponentTypesController < ApplicationController
def create def create
@component_type = ComponentType.new(type_params) @component_type = ComponentType.new(type_params)
if @component_type.save if @component_type.save
redirect_to admin_component_types_path, notice: "Component type created." redirect_to admin_component_types_path, notice: t("flash.admin_component_types.component_type_created")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -23,7 +23,7 @@ class Admin::ComponentTypesController < ApplicationController
def update def update
if @component_type.update(type_params) if @component_type.update(type_params)
redirect_to admin_component_types_path, notice: "Component type updated." redirect_to admin_component_types_path, notice: t("flash.admin_component_types.component_type_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -31,7 +31,7 @@ class Admin::ComponentTypesController < ApplicationController
def destroy def destroy
if @component_type.destroy if @component_type.destroy
redirect_to admin_component_types_path, notice: "Component type deleted." redirect_to admin_component_types_path, notice: t("flash.admin_component_types.component_type_deleted")
else else
redirect_to admin_component_types_path, alert: @component_type.errors.full_messages.to_sentence redirect_to admin_component_types_path, alert: @component_type.errors.full_messages.to_sentence
end end
@@ -14,7 +14,7 @@ class Admin::LogbookTemplatesController < ApplicationController
def create def create
@template = LogbookTemplate.new(template_params) @template = LogbookTemplate.new(template_params)
if @template.save if @template.save
redirect_to admin_logbook_templates_path, notice: "Template added." redirect_to admin_logbook_templates_path, notice: t("flash.admin_logbook_templates.template_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -24,7 +24,7 @@ class Admin::LogbookTemplatesController < ApplicationController
def update def update
if @template.update(template_params) if @template.update(template_params)
redirect_to admin_logbook_templates_path, notice: "Template updated." redirect_to admin_logbook_templates_path, notice: t("flash.admin_logbook_templates.template_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -32,12 +32,12 @@ class Admin::LogbookTemplatesController < ApplicationController
def destroy def destroy
@template.destroy! @template.destroy!
redirect_to admin_logbook_templates_path, notice: "Template deleted." redirect_to admin_logbook_templates_path, notice: t("flash.admin_logbook_templates.template_deleted")
end end
def restore def restore
added = LogbookTemplate.restore_defaults! added = LogbookTemplate.restore_defaults!
redirect_to admin_logbook_templates_path, notice: added.positive? ? "Restored #{helpers.pluralize(added, 'built-in template')}." : "All the built-in templates are already here." redirect_to admin_logbook_templates_path, notice: added.positive? ? t("flash.admin_logbook_templates.restored", count: added) : t("flash.admin_logbook_templates.all_present")
end end
private private
@@ -16,12 +16,12 @@ class Admin::OffsiteBackupsController < ApplicationController
changed_client = attrs[:client_id].present? && attrs[:client_id].strip != @connection.client_id changed_client = attrs[:client_id].present? && attrs[:client_id].strip != @connection.client_id
@connection.disconnect! if changed_client && @connection.connected? @connection.disconnect! if changed_client && @connection.connected?
@connection.update!(attrs.transform_values(&:strip)) @connection.update!(attrs.transform_values(&:strip))
redirect_to admin_offsite_backup_path, notice: "Saved. Now connect your Google account." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.saved_now_connect_your")
end end
# Off to Google to grant access (a link, so no form-action CSP entry is needed). # Off to Google to grant access (a link, so no form-action CSP entry is needed).
def connect def connect
return redirect_to(admin_offsite_backup_path, alert: "Enter the Google OAuth client ID and secret first.") unless @connection.configured? return redirect_to(admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.enter_the_google_oauth")) unless @connection.configured?
session[:offsite_oauth_state] = state = SecureRandom.urlsafe_base64(24) session[:offsite_oauth_state] = state = SecureRandom.urlsafe_base64(24)
redirect_to GoogleDriveClient.authorize_url(client_id: @connection.client_id, redirect_uri: @connection.redirect_uri, state: state), redirect_to GoogleDriveClient.authorize_url(client_id: @connection.client_id, redirect_uri: @connection.redirect_uri, state: state),
allow_other_host: true allow_other_host: true
@@ -30,9 +30,9 @@ class Admin::OffsiteBackupsController < ApplicationController
def callback def callback
expected = session.delete(:offsite_oauth_state) expected = session.delete(:offsite_oauth_state)
unless expected.present? && params[:state].present? && ActiveSupport::SecurityUtils.secure_compare(expected, params[:state].to_s) unless expected.present? && params[:state].present? && ActiveSupport::SecurityUtils.secure_compare(expected, params[:state].to_s)
return redirect_to(admin_offsite_backup_path, alert: "That Google sign-in didn't match a request from here. Try connecting again.") return redirect_to(admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.that_google_sign_in"))
end end
return redirect_to(admin_offsite_backup_path, alert: "Google Drive wasn't connected (#{params[:error]}).") if params[:error].present? || params[:code].blank? return redirect_to(admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.google_drive_wasn_t", error: params[:error])) if params[:error].present? || params[:code].blank?
token = GoogleDriveClient.exchange_code(client_id: @connection.client_id, client_secret: @connection.client_secret, token = GoogleDriveClient.exchange_code(client_id: @connection.client_id, client_secret: @connection.client_secret,
code: params[:code].to_s, redirect_uri: @connection.redirect_uri) code: params[:code].to_s, redirect_uri: @connection.redirect_uri)
@@ -42,25 +42,25 @@ class Admin::OffsiteBackupsController < ApplicationController
@connection.ensure_folders!(drive) @connection.ensure_folders!(drive)
Rails.logger.info("[offsite] #{current_user.email_address} connected Google Drive #{@connection.account_email}") Rails.logger.info("[offsite] #{current_user.email_address} connected Google Drive #{@connection.account_email}")
OffsiteBackupJob.perform_later OffsiteBackupJob.perform_later
redirect_to admin_offsite_backup_path, notice: "Google Drive connected (#{@connection.account_email}). The first off-site backup has started; it copies every uploaded file, so it can take a while." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.google_drive_connected_the", account_email: @connection.account_email)
rescue GoogleDriveClient::Error => e rescue GoogleDriveClient::Error => e
redirect_to admin_offsite_backup_path, alert: "Couldn't connect Google Drive: #{e.message}" redirect_to admin_offsite_backup_path, alert: t("flash.admin_offsite_backups.couldn_t_connect_google", message: e.message)
end end
def destroy def destroy
@connection.disconnect! @connection.disconnect!
Rails.logger.info("[offsite] #{current_user.email_address} disconnected Google Drive") Rails.logger.info("[offsite] #{current_user.email_address} disconnected Google Drive")
redirect_to admin_offsite_backup_path, notice: "Google Drive disconnected. The copies already there stay in your Drive." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.google_drive_disconnected_the")
end end
def backup_now def backup_now
OffsiteBackupJob.perform_later OffsiteBackupJob.perform_later
redirect_to admin_offsite_backup_path, notice: "Off-site backup started. Refresh in a minute to see the result." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.off_site_backup_started")
end end
def restore_test def restore_test
OffsiteBackupJob.perform_later("restore_test") OffsiteBackupJob.perform_later("restore_test")
redirect_to admin_offsite_backup_path, notice: "Restore test started. Refresh in a minute to see the result." redirect_to admin_offsite_backup_path, notice: t("flash.admin_offsite_backups.restore_test_started_refresh")
end end
private private
@@ -14,7 +14,7 @@ class Admin::ProceduresController < ApplicationController
if @policy.update(params.require(:recordkeeping_policy).permit(:operator_name, :responsible_name, :responsible_title, :hosting_description, 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, :offsite_backup_description, :audit_interval_months, :audit_sample_size,
:additional_procedures)) :additional_procedures))
redirect_to admin_procedures_path, notice: "Saved. Review the draft and adopt it as a new revision when it's right." redirect_to admin_procedures_path, notice: t("flash.admin_procedures.saved_review_the_draft")
else else
@revisions = ProceduresRevision.latest_first @revisions = ProceduresRevision.latest_first
render :show, status: :unprocessable_entity render :show, status: :unprocessable_entity
@@ -29,14 +29,14 @@ class Admin::ProceduresController < ApplicationController
def adopt def adopt
policy = RecordkeepingPolicy.current policy = RecordkeepingPolicy.current
if policy.unfilled_fields.any? if policy.unfilled_fields.any?
return redirect_to(admin_procedures_path, alert: "Fill in the [bracketed] blanks first: #{policy.unfilled_fields.to_sentence}.") return redirect_to(admin_procedures_path, alert: t("flash.admin_procedures.fill_in_the_bracketed", items: policy.unfilled_fields.to_sentence))
end end
return redirect_to(admin_procedures_path, alert: "Fill in the operator, responsible person, hosting and off-site backup (or connect Google Drive) first.") unless policy.complete? return redirect_to(admin_procedures_path, alert: t("flash.admin_procedures.fill_in_the_operator")) unless policy.complete?
number = (ProceduresRevision.maximum(:number) || 0) + 1 number = (ProceduresRevision.maximum(:number) || 0) + 1
revision = ProceduresRevision.create!(number: number, adopted_by: current_user, adopted_at: Time.current, revision = ProceduresRevision.create!(number: number, adopted_by: current_user, adopted_at: Time.current,
summary: params[:summary].to_s.strip.first(500).presence || "Revision #{number}", summary: params[:summary].to_s.strip.first(500).presence || "Revision #{number}",
content: draft_html(number: number, summary: params[:summary].to_s.strip.first(500))) 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." redirect_to admin_procedures_path, notice: t("flash.admin_procedures.revision_adopted_print_it", number: revision.number)
end end
def revision def revision
@@ -48,7 +48,7 @@ class Admin::ProceduresController < ApplicationController
def draft_html(number: nil, summary: nil) def draft_html(number: nil, summary: nil)
render_to_string(partial: "admin/procedures/document", render_to_string(partial: "admin/procedures/document",
locals: { policy: RecordkeepingPolicy.current, number: number || "#{(ProceduresRevision.maximum(:number) || 0) + 1} (draft)", locals: { policy: RecordkeepingPolicy.current, number: number || t("flash.admin_procedures.draft_number", number: (ProceduresRevision.maximum(:number) || 0) + 1),
adopted_at: number ? Time.current : nil, adopted_by: number ? current_user : nil, adopted_at: number ? Time.current : nil, adopted_by: number ? current_user : nil,
revisions: ProceduresRevision.latest_first.to_a, summary: summary }) revisions: ProceduresRevision.latest_first.to_a, summary: summary })
end end
+1 -1
View File
@@ -11,7 +11,7 @@ class Admin::SettingsController < ApplicationController
@errors = records.flat_map { _1.errors.full_messages } @errors = records.flat_map { _1.errors.full_messages }
if @errors.empty? if @errors.empty?
Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}") Rails.logger.info("[settings] #{current_user.email_address} changed #{submitted.inspect}")
redirect_to edit_admin_settings_path, notice: "Settings saved." redirect_to edit_admin_settings_path, notice: t("flash.admin_settings.settings_saved")
else else
@values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }.merge(submitted) @values = %w[max_upload_mb backups_kept offsite_backups_kept documents_claude_text].index_with { Setting.integer(_1) }.merge(submitted)
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
+11 -11
View File
@@ -14,7 +14,7 @@ class Admin::UsersController < ApplicationController
@user = User.new(user_params) @user = User.new(user_params)
@user.admin = admin_flag @user.admin = admin_flag
if @user.save if @user.save
redirect_to admin_users_path, notice: "User #{@user.email_address} created." redirect_to admin_users_path, notice: t("flash.admin_users.user_created", email_address: @user.email_address)
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -26,12 +26,12 @@ class Admin::UsersController < ApplicationController
attrs = user_params attrs = user_params
attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank?
if @user == current_user && !admin_flag if @user == current_user && !admin_flag
return redirect_to admin_users_path, alert: "You can't remove your own admin rights." return redirect_to admin_users_path, alert: t("flash.admin_users.you_can_t_remove")
end end
@user.admin = admin_flag @user.admin = admin_flag
if @user.update(attrs) if @user.update(attrs)
@user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) # new password signs them out @user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) # new password signs them out
redirect_to admin_users_path, notice: "User updated." redirect_to admin_users_path, notice: t("flash.admin_users.user_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -41,7 +41,7 @@ class Admin::UsersController < ApplicationController
# keeping their account, so the signatures they made stay attributed. # keeping their account, so the signatures they made stay attributed.
def unlock def unlock
@user.unlock! @user.unlock!
redirect_to admin_users_path, notice: "#{@user.email_address} unlocked." redirect_to admin_users_path, notice: t("flash.admin_users.unlocked", email_address: @user.email_address)
end end
# For a user who lost their authenticator: they sign in with their password # For a user who lost their authenticator: they sign in with their password
@@ -49,28 +49,28 @@ class Admin::UsersController < ApplicationController
def reset_two_factor def reset_two_factor
@user.disable_otp! @user.disable_otp!
Rails.logger.info("[auth] #{current_user.email_address} turned off two-factor for #{@user.email_address}") Rails.logger.info("[auth] #{current_user.email_address} turned off two-factor for #{@user.email_address}")
redirect_to admin_users_path, notice: "Two-factor turned off for #{@user.email_address}. Ask them to set it up again from their profile." redirect_to admin_users_path, notice: t("flash.admin_users.two_factor_turned_off", email_address: @user.email_address)
end end
def disable def disable
return redirect_to admin_users_path, alert: "You can't disable yourself." if @user == current_user return redirect_to admin_users_path, alert: t("flash.admin_users.you_can_t_disable") if @user == current_user
@user.update!(disabled_at: Time.current) @user.update!(disabled_at: Time.current)
@user.sessions.destroy_all @user.sessions.destroy_all
redirect_to admin_users_path, notice: "#{@user.email_address} disabled: signed out, can't sign in or sign entries. Their past signatures are kept." redirect_to admin_users_path, notice: t("flash.admin_users.disabled_signed_out_can", email_address: @user.email_address)
end end
def enable def enable
@user.update!(disabled_at: nil) @user.update!(disabled_at: nil)
redirect_to admin_users_path, notice: "#{@user.email_address} enabled." redirect_to admin_users_path, notice: t("flash.admin_users.enabled", email_address: @user.email_address)
end end
def destroy def destroy
return redirect_to admin_users_path, alert: "You can't delete yourself." if @user == current_user return redirect_to admin_users_path, alert: t("flash.admin_users.you_can_t_delete") if @user == current_user
if @user.entry_signatures.exists? if @user.entry_signatures.exists?
return redirect_to admin_users_path, alert: "#{@user.email_address} has signed logbook entries; disable the account instead of deleting it." return redirect_to admin_users_path, alert: t("flash.admin_users.has_signed_logbook_entries", email_address: @user.email_address)
end end
@user.destroy! @user.destroy!
redirect_to admin_users_path, notice: "User deleted." redirect_to admin_users_path, notice: t("flash.admin_users.user_deleted")
end end
private private
@@ -33,7 +33,7 @@ class AirTrailConnectionsController < ApplicationController
# Link existing AirTrail flights and push everything else, in the background. # Link existing AirTrail flights and push everything else, in the background.
def sync def sync
AirTrailBackfillJob.perform_later(@connection.id) AirTrailBackfillJob.perform_later(@connection.id)
redirect_to air_trail_connection_path, notice: "Sync started. Refresh this page in a minute to see progress." redirect_to air_trail_connection_path, notice: t("flash.air_trail_connections.sync_started_refresh_this")
end end
def map_airport def map_airport
@@ -42,9 +42,9 @@ class AirTrailConnectionsController < ApplicationController
match = target.present? && AirTrailSyncer.new(@connection).map_airport(code, target) match = target.present? && AirTrailSyncer.new(@connection).map_airport(code, target)
if match if match
AirTrailBackfillJob.perform_later(@connection.id) # retry flights that needed it AirTrailBackfillJob.perform_later(@connection.id) # retry flights that needed it
redirect_to air_trail_connection_path, notice: "#{code} mapped to #{match['icao']} (#{match['name']}). Retrying affected flights." redirect_to air_trail_connection_path, notice: t("flash.air_trail_connections.mapped_to_retrying_affected", code: code, icao: match["icao"], name: match["name"])
else else
redirect_to air_trail_connection_path, alert: "AirTrail has no airport matching “#{target}”." redirect_to air_trail_connection_path, alert: t("flash.air_trail_connections.airtrail_has_no_airport", target: target)
end end
rescue AirTrailClient::Error => e rescue AirTrailClient::Error => e
redirect_to air_trail_connection_path, alert: e.message redirect_to air_trail_connection_path, alert: e.message
@@ -53,7 +53,7 @@ class AirTrailConnectionsController < ApplicationController
# Stops syncing. Flights already in AirTrail are left there. # Stops syncing. Flights already in AirTrail are left there.
def destroy def destroy
@connection.destroy! @connection.destroy!
redirect_to air_trail_connection_path, notice: "AirTrail disconnected. Flights already in AirTrail were left as they are." redirect_to air_trail_connection_path, notice: t("flash.air_trail_connections.airtrail_disconnected_flights_already")
end end
private private
@@ -81,9 +81,9 @@ class AirTrailConnectionsController < ApplicationController
missing = me.dig("credential", "kind") == "apiKey" ? AirTrailConnection::REQUIRED_SCOPES - scopes : [] missing = me.dig("credential", "kind") == "apiKey" ? AirTrailConnection::REQUIRED_SCOPES - scopes : []
@connection.update!(remote_user_id: me["id"], remote_username: me["username"], checked_at: Time.current, @connection.update!(remote_user_id: me["id"], remote_username: me["username"], checked_at: Time.current,
status: missing.empty? ? "ok" : "error", status: missing.empty? ? "ok" : "error",
last_error: missing.empty? ? nil : "API key is missing scopes: #{missing.join(', ')}") last_error: missing.empty? ? nil : t("flash.air_trail_connections.missing_scopes", scopes: missing.join(", ")))
if missing.empty? if missing.empty?
flash[:notice] = "Connected to AirTrail as #{me['username']}." flash[:notice] = t("flash.air_trail_connections.connected_to_airtrail_as", username: me["username"])
else else
flash[:alert] = @connection.last_error flash[:alert] = @connection.last_error
end end
+6 -6
View File
@@ -29,7 +29,7 @@ class AircraftController < ApplicationController
@aircraft.roles.create!(user: current_user, role: "owner") @aircraft.roles.create!(user: current_user, role: "owner")
@aircraft.log_event!("aircraft", "Aircraft created") @aircraft.log_event!("aircraft", "Aircraft created")
end end
redirect_to @aircraft, notice: "#{@aircraft.tail_number} added." redirect_to @aircraft, notice: t("flash.aircraft.added", tail_number: @aircraft.tail_number)
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -38,8 +38,8 @@ class AircraftController < ApplicationController
def update def update
if @aircraft.update(aircraft_params) if @aircraft.update(aircraft_params)
log_event("aircraft", "Aircraft details updated") log_event("aircraft", t("flash.aircraft.aircraft_details_updated"))
redirect_to @aircraft, notice: "Aircraft updated." redirect_to @aircraft, notice: t("flash.aircraft.aircraft_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -47,7 +47,7 @@ class AircraftController < ApplicationController
def destroy def destroy
@aircraft.destroy! @aircraft.destroy!
redirect_to root_path, notice: "#{@aircraft.tail_number} deleted." redirect_to root_path, notice: t("flash.aircraft.deleted", tail_number: @aircraft.tail_number)
end end
# Pilots and above: set absolute tach/hobbs readings. # Pilots and above: set absolute tach/hobbs readings.
@@ -55,11 +55,11 @@ class AircraftController < ApplicationController
delta = HoursService.new(@aircraft).update_hours!( delta = HoursService.new(@aircraft).update_hours!(
tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time] tach_time: params.require(:tach_time), hobbs_time: params[:hobbs_time]
) )
redirect_to @aircraft, notice: "Hours updated (#{delta >= 0 ? '+' : ''}#{delta})." redirect_to @aircraft, notice: t("flash.aircraft.hours_updated", delta: "#{'+' if delta >= 0}#{delta}")
rescue AircraftGroundedError => e rescue AircraftGroundedError => e
redirect_to @aircraft, alert: e.message redirect_to @aircraft, alert: e.message
rescue ArgumentError rescue ArgumentError
redirect_to @aircraft, alert: "Enter a valid tach reading." redirect_to @aircraft, alert: t("flash.aircraft.enter_a_valid_tach")
end end
private private
@@ -13,7 +13,7 @@ class AircraftExportsController < ApplicationController
Dir[EXPORT_DIR.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago } Dir[EXPORT_DIR.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago }
path = EXPORT_DIR.join("#{SecureRandom.hex(12)}.zip").to_s path = EXPORT_DIR.join("#{SecureRandom.hex(12)}.zip").to_s
exporter.write_to(path) exporter.write_to(path)
log_event("aircraft", "Aircraft exported (.sam.zip)") log_event("aircraft", t("flash.aircraft_exports.aircraft_exported_sam_zip"))
# Generic binary, not application/zip: Safari unzips zip downloads into a # Generic binary, not application/zip: Safari unzips zip downloads into a
# folder ("Open safe files"), and the archive must stay one file to import. # folder ("Open safe files"), and the archive must stay one file to import.
send_file path, filename: exporter.filename, type: "application/octet-stream", disposition: "attachment" send_file path, filename: exporter.filename, type: "application/octet-stream", disposition: "attachment"
@@ -8,14 +8,14 @@ class AircraftImportsController < ApplicationController
def create def create
file = params[:archive] file = params[:archive]
return redirect_to(new_aircraft_import_path, alert: "Choose a .sam.zip file.") if file.blank? return redirect_to(new_aircraft_import_path, alert: t("flash.aircraft_imports.choose_a_sam_zip")) if file.blank?
preview = AircraftArchive::Importer.check(file.tempfile.path) preview = AircraftArchive::Importer.check(file.tempfile.path)
tail = params[:tail_number].to_s.strip.upcase.presence || preview.tail_number.to_s.upcase tail = params[:tail_number].to_s.strip.upcase.presence || preview.tail_number.to_s.upcase
if Aircraft.where("UPPER(tail_number) = ?", tail).exists? if Aircraft.where("UPPER(tail_number) = ?", tail).exists?
@preview = preview @preview = preview
@conflict = tail @conflict = tail
flash.now[:alert] = "An aircraft #{tail} already exists. Choose another tail number for the imported one." flash.now[:alert] = t("flash.aircraft_imports.an_aircraft_already_exists", tail: tail)
return render :new, status: :unprocessable_entity return render :new, status: :unprocessable_entity
end end
@@ -24,7 +24,7 @@ class AircraftImportsController < ApplicationController
AircraftImportJob.perform_later(import.id) AircraftImportJob.perform_later(import.id)
redirect_to aircraft_import_path(import) redirect_to aircraft_import_path(import)
rescue AircraftArchive::Error => e rescue AircraftArchive::Error => e
redirect_to new_aircraft_import_path, alert: "That archive can't be imported: #{e.message}" redirect_to new_aircraft_import_path, alert: t("flash.aircraft_imports.that_archive_can_t", message: e.message)
end end
def show; end def show; end
+10 -10
View File
@@ -12,12 +12,12 @@ class AircraftRolesController < ApplicationController
user = User.find_by(email_address: params[:email_address].to_s.strip.downcase) user = User.find_by(email_address: params[:email_address].to_s.strip.downcase)
unless user unless user
return redirect_to aircraft_aircraft_roles_path(@aircraft), return redirect_to aircraft_aircraft_roles_path(@aircraft),
alert: "No user with that email. Ask an administrator to create their account first." alert: t("flash.aircraft_roles.no_user_with_that")
end end
role = @aircraft.roles.new(user: user, role: params[:role]) role = @aircraft.roles.new(user: user, role: params[:role])
if role.save if role.save
log_event("role", "#{user.display_name} added as #{role.role}") log_event("role", t("flash.aircraft_roles.added_as", display_name: user.display_name, role: role.role))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "#{user.display_name} added." redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.added", display_name: user.display_name)
else else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence redirect_to aircraft_aircraft_roles_path(@aircraft), alert: role.errors.full_messages.to_sentence
end end
@@ -26,24 +26,24 @@ class AircraftRolesController < ApplicationController
def update def update
role = @aircraft.roles.find(params[:id]) role = @aircraft.roles.find(params[:id])
if demoting_last_owner?(role, params[:role]) if demoting_last_owner?(role, params[:role])
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner." return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep")
end end
role.update!(role: params[:role]) role.update!(role: params[:role])
log_event("role", "#{role.user.display_name} changed to #{role.role}") log_event("role", t("flash.aircraft_roles.changed_to", display_name: role.user.display_name, role: role.role))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Role updated." redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.role_updated")
end end
def destroy def destroy
role = @aircraft.roles.find(params[:id]) role = @aircraft.roles.find(params[:id])
if role.user == current_user if role.user == current_user
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "You can't remove yourself." return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.you_can_t_remove")
end end
if demoting_last_owner?(role, nil) if demoting_last_owner?(role, nil)
return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: "An aircraft must keep at least one owner." return redirect_to aircraft_aircraft_roles_path(@aircraft), alert: t("flash.aircraft_roles.an_aircraft_must_keep_2")
end end
role.destroy! role.destroy!
log_event("role", "#{role.user.display_name} removed") log_event("role", t("flash.aircraft_roles.removed", display_name: role.user.display_name))
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Access removed." redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.aircraft_roles.access_removed")
end end
private private
+1 -1
View File
@@ -14,6 +14,6 @@ class AirportCodesController < ApplicationController
fixes = params.fetch(:fixes, {}).permit(*standardizer.unknown.map(&:code)).to_h fixes = params.fetch(:fixes, {}).permit(*standardizer.unknown.map(&:code)).to_h
.select { |code, _| Array(params[:fix]).include?(code) } .select { |code, _| Array(params[:fix]).include?(code) }
updated = standardizer.apply!(codes, fixes: fixes) updated = standardizer.apply!(codes, fixes: fixes)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Updated #{updated} airport entries across your flights." redirect_to aircraft_flight_logs_path(@aircraft), notice: t("flash.airport_codes.updated_airport_entries_across", count: updated)
end end
end end
@@ -23,8 +23,8 @@ class AirworthinessDirectivesController < ApplicationController
@ad.save! @ad.save!
apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end end
log_event("ad", "#{@ad.bulletin_label} added: #{@ad.name}") log_event("ad", t("flash.airworthiness_directives.added_2", bulletin_label: @ad.bulletin_label, name: @ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} added." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.added", bulletin_label: @ad.bulletin_label)
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
@@ -34,8 +34,8 @@ class AirworthinessDirectivesController < ApplicationController
def attach def attach
ad = AirworthinessDirective.find(params[:airworthiness_directive_id]) ad = AirworthinessDirective.find(params[:airworthiness_directive_id])
ad.aircraft << @aircraft unless ad.aircraft.include?(@aircraft) ad.aircraft << @aircraft unless ad.aircraft.include?(@aircraft)
log_event("ad", "#{ad.bulletin_label} linked: #{ad.name}") log_event("ad", t("flash.airworthiness_directives.linked_2", bulletin_label: ad.bulletin_label, name: ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{ad.name} linked." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.linked", name: ad.name)
end end
def edit def edit
@@ -47,8 +47,8 @@ class AirworthinessDirectivesController < ApplicationController
@ad.update!(ad_params) @ad.update!(ad_params)
apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@ad, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end end
log_event("ad", "#{@ad.bulletin_label} updated: #{@ad.name}") log_event("ad", t("flash.airworthiness_directives.updated_2", bulletin_label: @ad.bulletin_label, name: @ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.bulletin_label} updated." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.updated", bulletin_label: @ad.bulletin_label)
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
@@ -57,8 +57,8 @@ class AirworthinessDirectivesController < ApplicationController
# Removes the AD from this aircraft (the shared AD record survives if other aircraft use it). # Removes the AD from this aircraft (the shared AD record survives if other aircraft use it).
def destroy def destroy
detach_from_aircraft(@ad) detach_from_aircraft(@ad)
log_event("ad", "#{@ad.bulletin_label} removed: #{@ad.name}") log_event("ad", t("flash.airworthiness_directives.removed", bulletin_label: @ad.bulletin_label, name: @ad.name))
redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: "#{@ad.name} removed from #{@aircraft.tail_number}." redirect_to aircraft_airworthiness_directives_path(@aircraft), notice: t("flash.airworthiness_directives.removed_from", name: @ad.name, tail_number: @aircraft.tail_number)
end end
private private
+1 -1
View File
@@ -24,6 +24,6 @@ class ApplicationController < ActionController::Base
end end
def require_admin! def require_admin!
redirect_to root_path, alert: "Admins only." unless current_user&.admin? redirect_to root_path, alert: t("flash.application.admins_only") unless current_user&.admin?
end end
end end
+4 -4
View File
@@ -8,14 +8,14 @@ class CalendarFeedsController < ApplicationController
def show def show
user = User.active.find_by(calendar_token: params[:token].to_s) or return head(:not_found) user = User.active.find_by(calendar_token: params[:token].to_s) or return head(:not_found)
cal = Ical.new("Aircraft maintenance") cal = Ical.new(t("flash.calendar_feeds.name"))
host = Sso.app_url host = Sso.app_url
user.accessible_aircraft.ordered.each do |aircraft| user.accessible_aircraft.ordered.each do |aircraft|
DueList.new(aircraft).items.each do |i| DueList.new(aircraft).items.each do |i|
when_text = [ ("projected from recent flying" if i.projected), ("at #{i.due_hours} hrs" if i.due_hours) ].compact.join(", ") when_text = [ (t("flash.calendar_feeds.projected") if i.projected), (t("flash.calendar_feeds.at_hours", hours: i.due_hours) if i.due_hours) ].compact.join(", ")
cal.add(uid: "#{aircraft.id}-#{i.key}@simple-aircraft-manager", date: i.date, cal.add(uid: "#{aircraft.id}-#{i.key}@simple-aircraft-manager", date: i.date,
summary: "#{aircraft.tail_number}: #{i.title}#{' (overdue)' if i.overdue?}", summary: t(i.overdue? ? "flash.calendar_feeds.summary_overdue" : "flash.calendar_feeds.summary", tail_number: aircraft.tail_number, title: i.title),
description: [ "#{aircraft.tail_number}: #{i.title}", when_text.presence ].compact.join("\n"), url: "#{host}#{i.path}") description: [ t("flash.calendar_feeds.summary", tail_number: aircraft.tail_number, title: i.title), when_text.presence ].compact.join("\n"), url: "#{host}#{i.path}")
end end
end end
send_data cal.to_s, type: "text/calendar; charset=utf-8", disposition: "inline", filename: "aircraft-maintenance.ics" send_data cal.to_s, type: "text/calendar; charset=utf-8", disposition: "inline", filename: "aircraft-maintenance.ics"
@@ -2,6 +2,6 @@
class CalendarTokensController < ApplicationController class CalendarTokensController < ApplicationController
def create def create
current_user.regenerate_calendar_token current_user.regenerate_calendar_token
redirect_to edit_profile_path(anchor: "calendar"), notice: "Calendar link ready. Any earlier link no longer works." redirect_to edit_profile_path(anchor: "calendar"), notice: t("flash.calendar_tokens.calendar_link_ready_any")
end end
end end
+8 -8
View File
@@ -35,8 +35,8 @@ class ComponentsController < ApplicationController
def create def create
@component = @aircraft.components.new(component_params) @component = @aircraft.components.new(component_params)
if @component.save if @component.save
log_event("component", "Component added: #{@component}") log_event("component", t("flash.components.component_added_2", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "Component added." redirect_to aircraft_components_path(@aircraft), notice: t("flash.components.component_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -46,8 +46,8 @@ class ComponentsController < ApplicationController
def update def update
if @component.update(component_params) if @component.update(component_params)
log_event("component", "Component updated: #{@component}") log_event("component", t("flash.components.component_updated_2", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "Component updated." redirect_to aircraft_components_path(@aircraft), notice: t("flash.components.component_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -55,8 +55,8 @@ class ComponentsController < ApplicationController
def destroy def destroy
@component.destroy! @component.destroy!
log_event("component", "Component deleted: #{@component}") log_event("component", t("flash.components.component_deleted_2", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "Component deleted." redirect_to aircraft_components_path(@aircraft), notice: t("flash.components.component_deleted")
end end
# Always zeroes hours since overhaul; reset_in_service=1 also zeroes the # Always zeroes hours since overhaul; reset_in_service=1 also zeroes the
@@ -64,8 +64,8 @@ class ComponentsController < ApplicationController
def reset_service def reset_service
replaced = params[:reset_in_service] == "1" replaced = params[:reset_in_service] == "1"
@component.reset_service!(reset_in_service: replaced) @component.reset_service!(reset_in_service: replaced)
log_event("component", "#{replaced ? 'Replaced' : 'Serviced'}: #{@component}") log_event("component", t(replaced ? "flash.components.replaced_event" : "flash.components.serviced_event", component: @component))
redirect_to aircraft_components_path(@aircraft), notice: "#{@component} #{replaced ? 'replaced' : 'serviced'}." redirect_to aircraft_components_path(@aircraft), notice: t(replaced ? "flash.components.replaced" : "flash.components.serviced", component: @component)
end end
private private
+1 -1
View File
@@ -32,7 +32,7 @@ module AircraftScoped
def require_owner! def require_owner!
return if owner? return if owner?
redirect_back fallback_location: aircraft_path(@aircraft), redirect_back fallback_location: aircraft_path(@aircraft),
alert: "Only owners can do that." alert: t("flash.common.only_owners_can_do")
end end
# Returns id only if it belongs to the given (aircraft-scoped) relation; else nil. # Returns id only if it belongs to the given (aircraft-scoped) relation; else nil.
+3 -3
View File
@@ -35,11 +35,11 @@ module EntrySigning
certificate = current_user.certificates.find_by(id: params[:certificate_id]) certificate = current_user.certificates.find_by(id: params[:certificate_id])
method = reauthenticated_method method = reauthenticated_method
unless params[:confirm] == "1" unless params[:confirm] == "1"
return signing_failed(entry, "Tick the box to confirm you're signing this entry.") return signing_failed(entry, t("flash.signing.confirm_box"))
end end
unless method unless method
return signing_failed(entry, "This account is locked for a few minutes after too many failed tries.") if current_user.reload.locked? return signing_failed(entry, t("flash.signing.locked")) if current_user.reload.locked?
return signing_failed(entry, "Re-enter your password#{' and a current authenticator code' if current_user.otp_enabled?} (or sign in again with #{Sso.label}) to sign.") return signing_failed(entry, t(current_user.otp_enabled? ? "flash.signing.reauth_otp" : "flash.signing.reauth", provider: Sso.label))
end end
current_user.clear_failed_sign_ins! current_user.clear_failed_sign_ins!
+3 -3
View File
@@ -14,10 +14,10 @@ module StoredUpload
# Returns [token, nil] on success or [nil, error message]. # Returns [token, nil] on success or [nil, error message].
def store_upload(file) def store_upload(file)
return [ nil, "Choose a file to upload." ] unless file.respond_to?(:path) return [ nil, I18n.t("flash.uploads.choose_file") ] unless file.respond_to?(:path)
return [ nil, "File is too large." ] if file.size > UPLOAD_MAX_SIZE return [ nil, I18n.t("flash.uploads.too_large") ] if file.size > UPLOAD_MAX_SIZE
ext = File.extname(file.original_filename.to_s).delete(".").downcase ext = File.extname(file.original_filename.to_s).delete(".").downcase
return [ nil, "Upload an .xlsx or .csv file." ] unless ext.in?(UPLOAD_EXTENSIONS) return [ nil, I18n.t("flash.uploads.spreadsheet_only") ] unless ext.in?(UPLOAD_EXTENSIONS)
FileUtils.mkdir_p(UPLOAD_DIR) FileUtils.mkdir_p(UPLOAD_DIR)
Dir.glob(UPLOAD_DIR.join("*")).each { |f| File.delete(f) if File.mtime(f) < 1.day.ago } Dir.glob(UPLOAD_DIR.join("*")).each { |f| File.delete(f) if File.mtime(f) < 1.day.ago }
@@ -27,8 +27,8 @@ class ConsumableRecordsController < ApplicationController
def create def create
@record = @aircraft.consumable_records.new(record_params) @record = @aircraft.consumable_records.new(record_params)
if @record.save if @record.save
log_event(@record.record_type, "#{@record.record_type.capitalize} added: #{@record.quantity_added} #{@record.unit}") log_event(@record.record_type, t("flash.consumable_records.added_event", type: ConsumableRecord::TYPES[@record.record_type], quantity: @record.quantity_added, unit: @record.unit))
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record added." redirect_to aircraft_consumable_records_path(@aircraft), notice: t("flash.consumable_records.record_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -38,8 +38,8 @@ class ConsumableRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event(@record.record_type, "#{@record.record_type.capitalize} record updated") log_event(@record.record_type, t("flash.consumable_records.updated_event", type: ConsumableRecord::TYPES[@record.record_type]))
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record updated." redirect_to aircraft_consumable_records_path(@aircraft), notice: t("flash.consumable_records.record_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -47,8 +47,8 @@ class ConsumableRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event(@record.record_type, "#{@record.record_type.capitalize} record deleted") log_event(@record.record_type, t("flash.consumable_records.deleted_event", type: ConsumableRecord::TYPES[@record.record_type]))
redirect_to aircraft_consumable_records_path(@aircraft), notice: "Record deleted." redirect_to aircraft_consumable_records_path(@aircraft), notice: t("flash.consumable_records.record_deleted")
end end
private private
+2 -2
View File
@@ -16,9 +16,9 @@ class DirectUploadsController < ActiveStorage::DirectUploadsController
def check_upload def check_upload
error = error =
if !UploadValidation::ALLOWED_CONTENT_TYPES.include?(blob_args[:content_type]) if !UploadValidation::ALLOWED_CONTENT_TYPES.include?(blob_args[:content_type])
"#{blob_args[:filename]} isn't an allowed file type" t("errors.messages.file_type", file: blob_args[:filename])
elsif blob_args[:byte_size].to_i > UploadValidation.max_size elsif blob_args[:byte_size].to_i > UploadValidation.max_size
"#{blob_args[:filename]} is over the #{UploadValidation.max_size / 1.megabyte} MB upload limit" t("errors.messages.file_size", file: blob_args[:filename], limit: UploadValidation.max_size / 1.megabyte)
end end
render json: { error: error }, status: :unprocessable_entity if error render json: { error: error }, status: :unprocessable_entity if error
end end
@@ -10,8 +10,8 @@ class DocumentCollectionsController < ApplicationController
def create def create
@collection = @aircraft.document_collections.new(collection_params) @collection = @aircraft.document_collections.new(collection_params)
if @collection.save if @collection.save
log_event("document", "Collection created: #{@collection.name}") log_event("document", t("flash.document_collections.collection_created_2", name: @collection.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Collection created." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.document_collections.collection_created")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -21,8 +21,8 @@ class DocumentCollectionsController < ApplicationController
def update def update
if @collection.update(collection_params) if @collection.update(collection_params)
log_event("document", "Collection updated: #{@collection.name}") log_event("document", t("flash.document_collections.collection_updated_2", name: @collection.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Collection updated." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.document_collections.collection_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -30,8 +30,8 @@ class DocumentCollectionsController < ApplicationController
def destroy def destroy
@collection.destroy! @collection.destroy!
log_event("document", "Collection deleted: #{@collection.name}") log_event("document", t("flash.document_collections.collection_deleted", name: @collection.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Collection and its documents deleted." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.document_collections.collection_and_its_documents")
end end
private private
+15 -15
View File
@@ -19,8 +19,8 @@ class DocumentsController < ApplicationController
def create def create
@document = @aircraft.documents.new(document_params) @document = @aircraft.documents.new(document_params)
if @document.save if @document.save
log_event("document", "Document added: #{@document.name}") log_event("document", t("flash.documents.document_added_2", name: @document.name))
redirect_to aircraft_document_path(@aircraft, @document), notice: "Document added." redirect_to aircraft_document_path(@aircraft, @document), notice: t("flash.documents.document_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -36,15 +36,15 @@ class DocumentsController < ApplicationController
def bulk_create def bulk_create
@bulk = bulk_defaults.merge(params.slice(:doc_type, :visibility, :document_collection_id, :new_collection).permit!.to_h.symbolize_keys) @bulk = bulk_defaults.merge(params.slice(:doc_type, :visibility, :document_collection_id, :new_collection).permit!.to_h.symbolize_keys)
files = Array(params[:files]).compact_blank files = Array(params[:files]).compact_blank
return bulk_error("Choose some files to upload.") if files.empty? return bulk_error(t("flash.documents.choose_files")) if files.empty?
return bulk_error("Upload at most #{MAX_BULK_FILES} files at a time.") if files.size > MAX_BULK_FILES return bulk_error(t("flash.documents.too_many_files", max: MAX_BULK_FILES)) if files.size > MAX_BULK_FILES
names = Array(params[:names]) names = Array(params[:names])
rejected = [] rejected = []
groups = {} groups = {}
files.each_with_index do |file, i| files.each_with_index do |file, i|
upload = file.is_a?(String) ? unattached_blob(file) : file upload = file.is_a?(String) ? unattached_blob(file) : file
next rejected << "file #{i + 1} (upload expired, try again)" unless upload next rejected << t("flash.documents.upload_expired", number: i + 1) unless upload
name = names[i].to_s.squish.presence || File.basename(upload_filename(upload), ".*").tr("_", " ").squish.presence || "Untitled" name = names[i].to_s.squish.presence || File.basename(upload_filename(upload), ".*").tr("_", " ").squish.presence || "Untitled"
(groups[name.first(255)] ||= []) << upload (groups[name.first(255)] ||= []) << upload
end end
@@ -58,18 +58,18 @@ class DocumentsController < ApplicationController
if doc.save if doc.save
created << doc created << doc
else else
rejected << "#{name} (#{doc.errors.full_messages.to_sentence})" rejected << t("flash.documents.rejected_file", name: name, errors: doc.errors.full_messages.to_sentence)
pages.each { _1.purge_later if _1.is_a?(ActiveStorage::Blob) } pages.each { _1.purge_later if _1.is_a?(ActiveStorage::Blob) }
end end
end end
if created.empty? if created.empty?
@aircraft.document_collections.find_by(id: collection_id)&.destroy if @bulk[:new_collection].present? @aircraft.document_collections.find_by(id: collection_id)&.destroy if @bulk[:new_collection].present?
return bulk_error("Nothing was uploaded: #{rejected.to_sentence}.") return bulk_error(t("flash.documents.nothing_uploaded", items: rejected.to_sentence))
end end
log_event("document", "#{helpers.pluralize(created.size, 'document')} uploaded", notes: created.map(&:name).join(", ").truncate(1000)) log_event("document", t("flash.documents.bulk_uploaded_event", count: created.size), notes: created.map(&:name).join(", ").truncate(1000))
flash[:alert] = "Not uploaded: #{rejected.to_sentence}." if rejected.any? flash[:alert] = t("flash.documents.not_uploaded", items: rejected.to_sentence) if rejected.any?
redirect_to aircraft_documents_path(@aircraft), notice: "#{helpers.pluralize(created.size, 'document')} uploaded.", status: :see_other redirect_to aircraft_documents_path(@aircraft), notice: t("flash.documents.bulk_uploaded", count: created.size), status: :see_other
end end
def edit; end def edit; end
@@ -81,8 +81,8 @@ class DocumentsController < ApplicationController
@document.pages.attach(new_pages) if new_pages.present? @document.pages.attach(new_pages) if new_pages.present?
Array(params[:remove_page_ids]).each { |id| @document.pages.find_by(id: id)&.purge_later } Array(params[:remove_page_ids]).each { |id| @document.pages.find_by(id: id)&.purge_later }
if @document.save if @document.save
log_event("document", "Document updated: #{@document.name}") log_event("document", t("flash.documents.document_updated_2", name: @document.name))
redirect_to aircraft_document_path(@aircraft, @document), notice: "Document updated." redirect_to aircraft_document_path(@aircraft, @document), notice: t("flash.documents.document_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -90,8 +90,8 @@ class DocumentsController < ApplicationController
def destroy def destroy
@document.destroy! @document.destroy!
log_event("document", "Document deleted: #{@document.name}") log_event("document", t("flash.documents.document_deleted_2", name: @document.name))
redirect_to aircraft_documents_path(@aircraft), notice: "Document deleted." redirect_to aircraft_documents_path(@aircraft), notice: t("flash.documents.document_deleted")
end end
private private
@@ -120,7 +120,7 @@ class DocumentsController < ApplicationController
def bulk_collection def bulk_collection
return [ scoped_id(@aircraft.document_collections, @bulk[:document_collection_id]), nil ] if @bulk[:new_collection].blank? return [ scoped_id(@aircraft.document_collections, @bulk[:document_collection_id]), nil ] if @bulk[:new_collection].blank?
col = @aircraft.document_collections.create(name: @bulk[:new_collection].squish, visibility: @bulk[:visibility].presence || "private") col = @aircraft.document_collections.create(name: @bulk[:new_collection].squish, visibility: @bulk[:visibility].presence || "private")
col.persisted? ? [ col.id, nil ] : [ nil, "Couldn't create the collection: #{col.errors.full_messages.to_sentence}." ] col.persisted? ? [ col.id, nil ] : [ nil, t("flash.documents.collection_failed", errors: col.errors.full_messages.to_sentence) ]
end end
def set_document = @document = @aircraft.documents.find(params[:id]) def set_document = @document = @aircraft.documents.find(params[:id])
@@ -12,7 +12,7 @@ class EntrySignaturesController < ApplicationController
def create def create
sign_entry(@entry) do |signature| sign_entry(@entry) do |signature|
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Signed. #{EntrySignature::LABEL} #{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}." redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.entry_signatures.signed", label: EntrySignature.label, signer_name: signature.signer_name, certificate_label: signature.certificate_label, certificate_number: signature.certificate_number)
end end
end end
+4 -4
View File
@@ -18,7 +18,7 @@ class FlightImportsController < ApplicationController
# Preview. # Preview.
def show def show
@token = params[:token].to_s @token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(@token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(@token)
@filename = params[:filename].to_s @filename = params[:filename].to_s
@starting_tach = params[:starting_tach].presence @starting_tach = params[:starting_tach].presence
@@ -31,17 +31,17 @@ class FlightImportsController < ApplicationController
def confirm def confirm
token = params[:token].to_s token = params[:token].to_s
return redirect_to_upload("Upload expired. Please upload the file again.") unless stored_file?(token) return redirect_to_upload(t("flash.uploads.expired")) unless stored_file?(token)
import = build_import(token, params[:filename], starting_tach: params[:starting_tach], starting_hobbs: params[:starting_hobbs]) import = build_import(token, params[:filename], starting_tach: params[:starting_tach], starting_hobbs: params[:starting_hobbs])
count = import.import!(user: current_user, update_aircraft_hours: params[:update_aircraft_hours] == "1") count = import.import!(user: current_user, update_aircraft_hours: params[:update_aircraft_hours] == "1")
discard_upload(token) discard_upload(token)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Imported #{count} flights." redirect_to aircraft_flight_logs_path(@aircraft), notice: t("flash.flight_imports.imported_flights", count: count)
rescue FlightImport::Error => e rescue FlightImport::Error => e
redirect_to new_aircraft_flight_import_path(@aircraft), alert: e.message redirect_to new_aircraft_flight_import_path(@aircraft), alert: e.message
rescue AircraftGroundedError rescue AircraftGroundedError
redirect_to aircraft_flight_logs_path(@aircraft), redirect_to aircraft_flight_logs_path(@aircraft),
alert: "Flights imported, but aircraft hours weren't updated: the aircraft is grounded and enforcement is on." alert: t("flash.flight_imports.flights_imported_but_aircraft")
end end
private private
+10 -10
View File
@@ -26,12 +26,12 @@ class FlightLogsController < ApplicationController
begin begin
@track = TrackParser.parse_attachment(@flight_log.track_log) @track = TrackParser.parse_attachment(@flight_log.track_log)
rescue TrackParser::Error => e rescue TrackParser::Error => e
@track_error = "Couldn't read track: #{e.message}" @track_error = t("flash.flight_logs.track_unreadable", message: e.message)
end end
begin begin
@engine_data = EngineDataParser.parse_attachment(@flight_log.engine_data) @engine_data = EngineDataParser.parse_attachment(@flight_log.engine_data)
rescue EngineDataParser::Error, ActiveStorage::FileNotFoundError => e rescue EngineDataParser::Error, ActiveStorage::FileNotFoundError => e
@engine_data_error = "Couldn't read engine data: #{e.message}" @engine_data_error = t("flash.flight_logs.engine_data_unreadable", message: e.message)
end end
@air_trail_connection = @flight_log.user&.air_trail_connection @air_trail_connection = @flight_log.user&.air_trail_connection
@air_trail_sync = @flight_log.air_trail_syncs.first @air_trail_sync = @flight_log.air_trail_syncs.first
@@ -57,12 +57,12 @@ class FlightLogsController < ApplicationController
def create def create
# Already received (sent again from the offline queue): don't log it twice. # Already received (sent again from the offline queue): don't log it twice.
if (key = params.dig(:flight_log, :client_key).to_s.presence) && @aircraft.flight_logs.exists?(client_key: key.first(64)) if (key = params.dig(:flight_log, :client_key).to_s.presence) && @aircraft.flight_logs.exists?(client_key: key.first(64))
return redirect_to(aircraft_flight_logs_path(@aircraft), notice: "Flight already logged.") return redirect_to(aircraft_flight_logs_path(@aircraft), notice: t("flash.flight_logs.flight_already_logged"))
end end
@flight_log = @aircraft.flight_logs.new(flight_log_params) @flight_log = @aircraft.flight_logs.new(flight_log_params)
if @flight_log.valid? if @flight_log.valid?
HoursService.new(@aircraft).log_flight!(@flight_log) HoursService.new(@aircraft).log_flight!(@flight_log)
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight logged (#{@flight_log.tach_time} hrs)." redirect_to aircraft_flight_logs_path(@aircraft), notice: t("flash.flight_logs.flight_logged_hrs", tach_time: @flight_log.tach_time)
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -73,11 +73,11 @@ class FlightLogsController < ApplicationController
def attach_engine_data def attach_engine_data
file = params.dig(:flight_log, :engine_data) file = params.dig(:flight_log, :engine_data)
return redirect_to(aircraft_flight_log_path(@aircraft, @flight_log), alert: "Choose an engine data file.") if file.blank? return redirect_to(aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.choose_an_engine_data")) if file.blank?
@flight_log.engine_data = file @flight_log.engine_data = file
if @flight_log.save if @flight_log.save
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: "Engine data attached." redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.engine_data_attached")
else else
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: @flight_log.errors.full_messages.to_sentence redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: @flight_log.errors.full_messages.to_sentence
end end
@@ -85,14 +85,14 @@ class FlightLogsController < ApplicationController
def remove_engine_data def remove_engine_data
@flight_log.engine_data.purge_later @flight_log.engine_data.purge_later
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: "Engine data removed." redirect_to aircraft_flight_log_path(@aircraft, @flight_log), notice: t("flash.flight_logs.engine_data_removed")
end end
# Deleting a flight does not roll back hours; correct those with an hours update. # Deleting a flight does not roll back hours; correct those with an hours update.
def destroy def destroy
@aircraft.flight_logs.find(params[:id]).destroy! @aircraft.flight_logs.find(params[:id]).destroy!
log_event("flight", "Flight log deleted") log_event("flight", t("flash.flight_logs.flight_log_deleted"))
redirect_to aircraft_flight_logs_path(@aircraft), notice: "Flight log deleted. Aircraft hours were not changed." redirect_to aircraft_flight_logs_path(@aircraft), notice: t("flash.flight_logs.flight_log_deleted_aircraft")
end end
private private
@@ -108,7 +108,7 @@ class FlightLogsController < ApplicationController
def require_engine_data_access! def require_engine_data_access!
return if manage_engine_data? return if manage_engine_data?
redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: "Only owners or the flight's pilot can do that." redirect_to aircraft_flight_log_path(@aircraft, @flight_log), alert: t("flash.flight_logs.only_owners_or_the")
end end
def flight_log_params def flight_log_params
@@ -12,8 +12,8 @@ class InspectionRecordsController < ApplicationController
def create def create
@record = InspectionRecord.new(record_params.merge(aircraft: @aircraft)) @record = InspectionRecord.new(record_params.merge(aircraft: @aircraft))
if @record.save if @record.save
log_event("inspection", "Inspection completed: #{@record.inspection_type.name}") log_event("inspection", t("flash.inspection_records.inspection_completed", name: @record.inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection recorded." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_records.inspection_recorded")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -23,8 +23,8 @@ class InspectionRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event("inspection", "Inspection record updated: #{@record.inspection_type.name}") log_event("inspection", t("flash.inspection_records.inspection_record_updated_2", name: @record.inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record updated." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_records.inspection_record_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -32,8 +32,8 @@ class InspectionRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event("inspection", "Inspection record deleted: #{@record.inspection_type.name}") log_event("inspection", t("flash.inspection_records.inspection_record_deleted_2", name: @record.inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection record deleted." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_records.inspection_record_deleted")
end end
private private
@@ -8,12 +8,12 @@ class InspectionTypesController < ApplicationController
@inspection_type = InspectionType.new(required: true, recurring: true) @inspection_type = InspectionType.new(required: true, recurring: true)
@applies_to_airframe = true @applies_to_airframe = true
if (@major_record = ica_record) if (@major_record = ica_record)
@inspection_type.name = "ICA: #{@major_record.title}".first(120) @inspection_type.name = t("flash.inspection_types.ica_name", title: @major_record.title).first(120)
@applies_to_airframe = @major_record.component.nil? @applies_to_airframe = @major_record.component.nil?
@inspection_type.components = [ @major_record.component ] if @major_record.component @inspection_type.components = [ @major_record.component ] if @major_record.component
elsif (component = @aircraft.components.find_by(id: params[:component_id])) elsif (component = @aircraft.components.find_by(id: params[:component_id]))
# From a component's page: applies to that part, e.g. "Magneto 500-hour inspection". # From a component's page: applies to that part, e.g. "Magneto 500-hour inspection".
@inspection_type.name = "#{component} inspection" @inspection_type.name = t("flash.inspection_types.component_name", component: component)
@inspection_type.components = [ component ] @inspection_type.components = [ component ]
@applies_to_airframe = false @applies_to_airframe = false
end end
@@ -26,11 +26,11 @@ class InspectionTypesController < ApplicationController
apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
ica_record&.update!(ica_inspection_type: @inspection_type) ica_record&.update!(ica_inspection_type: @inspection_type)
end end
log_event("inspection", "Inspection type added: #{@inspection_type.name}") log_event("inspection", t("flash.inspection_types.inspection_type_added_2", name: @inspection_type.name))
if (record = ica_record) if (record = ica_record)
redirect_to aircraft_major_record_path(@aircraft, record), notice: "ICA inspection added. Record when it was last done to see when it's next due." redirect_to aircraft_major_record_path(@aircraft, record), notice: t("flash.inspection_types.ica_inspection_added_record")
else else
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type added." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_types.inspection_type_added")
end end
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
@@ -47,8 +47,8 @@ class InspectionTypesController < ApplicationController
@inspection_type.update!(type_params) @inspection_type.update!(type_params)
apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids) apply_applicability(@inspection_type, to_airframe: applies_to_airframe?, component_ids: applicable_component_ids)
end end
log_event("inspection", "Inspection type updated: #{@inspection_type.name}") log_event("inspection", t("flash.inspection_types.inspection_type_updated_2", name: @inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection type updated." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_types.inspection_type_updated")
rescue ActiveRecord::RecordInvalid rescue ActiveRecord::RecordInvalid
@applies_to_airframe = applies_to_airframe? @applies_to_airframe = applies_to_airframe?
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
@@ -56,8 +56,8 @@ class InspectionTypesController < ApplicationController
def destroy def destroy
detach_from_aircraft(@inspection_type) detach_from_aircraft(@inspection_type)
log_event("inspection", "Inspection type removed: #{@inspection_type.name}") log_event("inspection", t("flash.inspection_types.inspection_type_removed", name: @inspection_type.name))
redirect_to aircraft_inspections_path(@aircraft), notice: "Inspection removed from #{@aircraft.tail_number}." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.inspection_types.inspection_removed_from", tail_number: @aircraft.tail_number)
end end
private private
@@ -5,7 +5,7 @@ class InvitedSigningsController < ApplicationController
include EntrySigning include EntrySigning
allow_unauthenticated_access only: %i[show account] allow_unauthenticated_access only: %i[show account]
before_action :set_invitation before_action :set_invitation
rate_limit to: 10, within: 15.minutes, only: :account, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 10, within: 15.minutes, only: :account, with: -> { redirect_to new_session_path, alert: t("flash.invited_signings.try_again_later") }
def show def show
@entry = @invitation.logbook_entry @entry = @invitation.logbook_entry
@@ -24,13 +24,13 @@ class InvitedSigningsController < ApplicationController
def account def account
return redirect_to(invited_signing_path(params[:token])) if authenticated? return redirect_to(invited_signing_path(params[:token])) if authenticated?
if User.exists?(email_address: @invitation.email) || !Sso.password_login? if User.exists?(email_address: @invitation.email) || !Sso.password_login?
return redirect_to invited_signing_path(params[:token]), alert: "Sign in to continue." return redirect_to invited_signing_path(params[:token]), alert: t("flash.invited_signings.sign_in_to_continue")
end end
user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email)) user = User.new(params.permit(:name, :password, :password_confirmation).merge(email_address: @invitation.email))
if user.save if user.save
reset_session reset_session
start_new_session_for user start_new_session_for user
redirect_to invited_signing_path(params[:token]), notice: "Account created. Add your certificate, then sign." redirect_to invited_signing_path(params[:token]), notice: t("flash.invited_signings.account_created_add_your")
else else
@entry = @invitation.logbook_entry @entry = @invitation.logbook_entry
@account_errors = user.errors.full_messages @account_errors = user.errors.full_messages
@@ -44,7 +44,7 @@ class InvitedSigningsController < ApplicationController
return render(:wrong_account) unless current_user.email_address == @invitation.email return render(:wrong_account) unless current_user.email_address == @invitation.email
sign_entry(@entry) do |signature| sign_entry(@entry) do |signature|
@invitation.update!(used_at: Time.current, user: current_user) @invitation.update!(used_at: Time.current, user: current_user)
redirect_to invited_signing_path(params[:token]), notice: "Signed. #{EntrySignature::LABEL} #{signature.signer_name}, #{signature.certificate_label} #{signature.certificate_number}." redirect_to invited_signing_path(params[:token]), notice: t("flash.invited_signings.signed", label: EntrySignature.label, signer_name: signature.signer_name, certificate_label: signature.certificate_label, certificate_number: signature.certificate_number)
end end
end end
+2 -2
View File
@@ -13,8 +13,8 @@ class LoadingSetupsController < ApplicationController
@setup = LoadingSetup.from_params(permitted.to_h) @setup = LoadingSetup.from_params(permitted.to_h)
if @setup.valid? if @setup.valid?
@aircraft.update!(loading_stations: @setup.stations_json, cg_envelope: @setup.envelope.map { |w, cg| [ w.to_f, cg.to_f ] }) @aircraft.update!(loading_stations: @setup.stations_json, cg_envelope: @setup.envelope.map { |w, cg| [ w.to_f, cg.to_f ] })
log_event("aircraft", "Loading stations and CG envelope updated") log_event("aircraft", t("flash.loading_setups.loading_stations_and_cg"))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Loading setup saved." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.loading_setups.loading_setup_saved")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
+11 -11
View File
@@ -18,10 +18,10 @@ class LogbookEntriesController < ApplicationController
# Someone has checked a transcribed entry against the scan. # Someone has checked a transcribed entry against the scan.
def verify def verify
@entry.update!(verified: true) @entry.update!(verified: true)
log_event("logbook", "Transcribed logbook entry verified: #{@entry.date}") log_event("logbook", t("flash.logbook_entries.transcribed_logbook_entry_verified", date: @entry.date))
next_entry = @aircraft.logbook_entries.unverified.order(:date, :id).first next_entry = @aircraft.logbook_entries.unverified.order(:date, :id).first
redirect_to next_entry ? aircraft_logbook_entry_path(@aircraft, next_entry) : aircraft_logbook_entries_path(@aircraft), redirect_to next_entry ? aircraft_logbook_entry_path(@aircraft, next_entry) : aircraft_logbook_entries_path(@aircraft),
notice: next_entry ? "Verified. Here's the next one to check." : "Verified. All transcribed entries are checked." notice: next_entry ? t("flash.logbook_entries.verified_next") : t("flash.logbook_entries.verified_all")
end end
def show; end def show; end
@@ -36,11 +36,11 @@ class LogbookEntriesController < ApplicationController
@entry.supersedes = correctable(params.dig(:logbook_entry, :supersedes_id)) @entry.supersedes = correctable(params.dig(:logbook_entry, :supersedes_id))
@entry.assign_parts(parts_params, @aircraft) @entry.assign_parts(parts_params, @aircraft)
if @entry.save if @entry.save
log_event("logbook", "Logbook entry #{@entry.supersedes ? 'correction ' : ''}added (#{@entry.date})") log_event("logbook", t(@entry.supersedes ? "flash.logbook_entries.correction_added_event" : "flash.logbook_entries.logbook_entry_added", date: @entry.date))
record_parts_service record_parts_service
record_inspections record_inspections
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), redirect_to aircraft_logbook_entry_path(@aircraft, @entry),
notice: @entry.supersedes ? "Correction saved. Sign it to supersede the original entry." : "Logbook entry added." notice: @entry.supersedes ? t("flash.logbook_entries.correction_saved") : t("flash.logbook_entries.added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -52,8 +52,8 @@ class LogbookEntriesController < ApplicationController
@entry.assign_attributes(entry_params) @entry.assign_attributes(entry_params)
@entry.assign_parts(parts_params, @aircraft) @entry.assign_parts(parts_params, @aircraft)
if @entry.save if @entry.save
log_event("logbook", "Logbook entry updated (#{@entry.date})") log_event("logbook", t("flash.logbook_entries.logbook_entry_updated_2", date: @entry.date))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Logbook entry updated." redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.logbook_entries.logbook_entry_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -61,8 +61,8 @@ class LogbookEntriesController < ApplicationController
def destroy def destroy
@entry.destroy! @entry.destroy!
log_event("logbook", "Logbook entry deleted (#{@entry.date})") log_event("logbook", t("flash.logbook_entries.logbook_entry_deleted_2", date: @entry.date))
redirect_to aircraft_logbook_entries_path(@aircraft), notice: "Logbook entry deleted." redirect_to aircraft_logbook_entries_path(@aircraft), notice: t("flash.logbook_entries.logbook_entry_deleted")
end end
private private
@@ -70,7 +70,7 @@ class LogbookEntriesController < ApplicationController
# Signed entries are locked (AC 120-78B 2.1.2.8): changes go in a correction. # Signed entries are locked (AC 120-78B 2.1.2.8): changes go in a correction.
def require_unsigned def require_unsigned
return unless @entry.signed? return unless @entry.signed?
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: "This entry is signed, so it can't be changed or deleted. Make a correction entry instead." redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: t("flash.logbook_entries.this_entry_is_signed")
end end
# A signed, not yet superseded entry of this aircraft. # A signed, not yet superseded entry of this aircraft.
@@ -99,7 +99,7 @@ class LogbookEntriesController < ApplicationController
part = @entry.parts.find { _1.component_id == id.to_i } or next part = @entry.parts.find { _1.component_id == id.to_i } or next
component = part.component component = part.component
component.service_from_entry!(date: @entry.date, hours_at_entry: part.hours_at_entry, flown_since: flown, replaced: p["service"] == "replaced") component.service_from_entry!(date: @entry.date, hours_at_entry: part.hours_at_entry, flown_since: flown, replaced: p["service"] == "replaced")
log_event("component", "#{p['service'] == 'replaced' ? 'Replaced' : 'Serviced'}: #{component} (logbook entry #{@entry.date})") log_event("component", t(p["service"] == "replaced" ? "flash.logbook_entries.replaced_event" : "flash.logbook_entries.serviced_event", component: component, date: @entry.date))
end end
end end
@@ -110,7 +110,7 @@ class LogbookEntriesController < ApplicationController
@aircraft.applicable_inspection_types.where(id: ids).find_each do |type| @aircraft.applicable_inspection_types.where(id: ids).find_each do |type|
@aircraft.inspection_records.create!(inspection_type: type, logbook_entry: @entry, date: @entry.date, @aircraft.inspection_records.create!(inspection_type: type, logbook_entry: @entry, date: @entry.date,
aircraft_hours: @entry.aircraft_hours_at_entry) aircraft_hours: @entry.aircraft_hours_at_entry)
log_event("inspection", "Inspection completed: #{type.name} (logbook entry #{@entry.date})") log_event("inspection", t("flash.logbook_entries.inspection_completed_logbook_entry", name: type.name, date: @entry.date))
end end
end end
@@ -11,7 +11,7 @@ class LogbookImportsController < ApplicationController
def create def create
files = Array(params[:pages]).compact_blank files = Array(params[:pages]).compact_blank
return redirect_to(new_aircraft_logbook_import_path(@aircraft), alert: "Choose the scanned pages to upload.") if files.empty? return redirect_to(new_aircraft_logbook_import_path(@aircraft), alert: t("flash.logbook_imports.choose_the_scanned_pages")) if files.empty?
# Page order follows the file names ("page-002" before "page-010"). # Page order follows the file names ("page-002" before "page-010").
files = files.sort_by { |f| f.original_filename.to_s.downcase.scan(/\d+|\D+/).map { _1.match?(/\d/) ? [ 0, _1.to_i ] : [ 1, _1 ] } } files = files.sort_by { |f| f.original_filename.to_s.downcase.scan(/\d+|\D+/).map { _1.match?(/\d/) ? [ 0, _1.to_i ] : [ 1, _1 ] } }
@@ -32,7 +32,7 @@ class LogbookImportsController < ApplicationController
import = @aircraft.logbook_imports.create!(user: current_user, document: document, log_type: params[:log_type], import = @aircraft.logbook_imports.create!(user: current_user, document: document, log_type: params[:log_type],
transcribe: params[:transcribe] == "1" && LogbookImport.ai_available?) transcribe: params[:transcribe] == "1" && LogbookImport.ai_available?)
end end
log_event("document", "Logbook pages uploaded: #{document.name} (#{files.size} #{'page'.pluralize(files.size)})") log_event("document", t("flash.logbook_imports.pages_uploaded", name: document.name, count: files.size))
LogbookTranscriptionJob.perform_later(import.id) LogbookTranscriptionJob.perform_later(import.id)
redirect_to aircraft_logbook_import_path(@aircraft, import) redirect_to aircraft_logbook_import_path(@aircraft, import)
end end
+2 -2
View File
@@ -10,7 +10,7 @@ class LogbookPrintsController < ApplicationController
def show def show
pdf = LogbookEntryPdf.new(@aircraft, @entries, layout: params[:layout], start_at: params[:start_at]) pdf = LogbookEntryPdf.new(@aircraft, @entries, layout: params[:layout], start_at: params[:start_at])
log_event("logbook", "Logbook entries printed (#{@entries.size})") log_event("logbook", t("flash.logbook_prints.logbook_entries_printed", count: @entries.size))
send_data pdf.render, filename: pdf.filename, type: "application/pdf", disposition: "inline" send_data pdf.render, filename: pdf.filename, type: "application/pdf", disposition: "inline"
end end
@@ -19,6 +19,6 @@ class LogbookPrintsController < ApplicationController
def set_entries def set_entries
ids = Array(params[:ids]).map(&:to_i).first(200) ids = Array(params[:ids]).map(&:to_i).first(200)
@entries = @aircraft.logbook_entries.where(id: ids).includes(:component, :parts, :signature, inspection_records: :inspection_type).order(:date, :id).to_a @entries = @aircraft.logbook_entries.where(id: ids).includes(:component, :parts, :signature, inspection_records: :inspection_type).order(:date, :id).to_a
redirect_to aircraft_logbook_entries_path(@aircraft), alert: "Choose the entries to print." if @entries.empty? redirect_to aircraft_logbook_entries_path(@aircraft), alert: t("flash.logbook_prints.choose_the_entries_to") if @entries.empty?
end end
end end
@@ -4,7 +4,7 @@ class MaintenanceReportsController < ApplicationController
def show def show
@report = MaintenanceReport.new(@aircraft) @report = MaintenanceReport.new(@aircraft)
log_event("aircraft", "Maintenance status report viewed") if params[:print] log_event("aircraft", t("flash.maintenance_reports.maintenance_status_report_viewed")) if params[:print]
render layout: "report" render layout: "report"
end end
end end
+6 -6
View File
@@ -17,8 +17,8 @@ class MajorRecordsController < ApplicationController
def create def create
@record = @aircraft.major_records.new(record_params) @record = @aircraft.major_records.new(record_params)
if @record.save if @record.save
log_event("major_record", "#{@record.type_label} added: #{@record.title}") log_event("major_record", t("flash.major_records.added", type_label: @record.type_label, title: @record.title))
redirect_to aircraft_major_records_path(@aircraft), notice: "Record added." redirect_to aircraft_major_records_path(@aircraft), notice: t("flash.major_records.record_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -28,8 +28,8 @@ class MajorRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event("major_record", "#{@record.type_label} updated: #{@record.title}") log_event("major_record", t("flash.major_records.updated", type_label: @record.type_label, title: @record.title))
redirect_to aircraft_major_record_path(@aircraft, @record), notice: "Record updated." redirect_to aircraft_major_record_path(@aircraft, @record), notice: t("flash.major_records.record_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -37,8 +37,8 @@ class MajorRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event("major_record", "#{@record.type_label} deleted: #{@record.title}") log_event("major_record", t("flash.major_records.deleted", type_label: @record.type_label, title: @record.title))
redirect_to aircraft_major_records_path(@aircraft), notice: "Record deleted." redirect_to aircraft_major_records_path(@aircraft), notice: t("flash.major_records.record_deleted")
end end
private private
+6 -6
View File
@@ -19,8 +19,8 @@ class NotesController < ApplicationController
def create def create
@note = @aircraft.notes.new(note_params.merge(user: current_user)) @note = @aircraft.notes.new(note_params.merge(user: current_user))
if @note.save if @note.save
log_event("note", "Note added") log_event("note", t("flash.notes.note_added_2"))
redirect_to aircraft_notes_path(@aircraft), notice: "Note added." redirect_to aircraft_notes_path(@aircraft), notice: t("flash.notes.note_added")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -30,8 +30,8 @@ class NotesController < ApplicationController
def update def update
if @note.update(note_params.merge(edited_at: Time.current)) if @note.update(note_params.merge(edited_at: Time.current))
log_event("note", "Note updated") log_event("note", t("flash.notes.note_updated_2"))
redirect_to aircraft_notes_path(@aircraft), notice: "Note updated." redirect_to aircraft_notes_path(@aircraft), notice: t("flash.notes.note_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -39,8 +39,8 @@ class NotesController < ApplicationController
def destroy def destroy
@note.destroy! @note.destroy!
log_event("note", "Note deleted") log_event("note", t("flash.notes.note_deleted_2"))
redirect_to aircraft_notes_path(@aircraft), notice: "Note deleted." redirect_to aircraft_notes_path(@aircraft), notice: t("flash.notes.note_deleted")
end end
private private
+12 -12
View File
@@ -24,8 +24,8 @@ class OilAnalysesController < ApplicationController
def create def create
@analysis = @aircraft.oil_analyses.new(analysis_params) @analysis = @aircraft.oil_analyses.new(analysis_params)
if @analysis.save if @analysis.save
log_event("oil_analysis", "Oil analysis added (sampled #{@analysis.sample_date})") log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_added_sampled", sample_date: @analysis.sample_date))
redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: "Oil analysis saved." redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: t("flash.oil_analyses.oil_analysis_saved")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -35,13 +35,13 @@ class OilAnalysesController < ApplicationController
# earlier samples, so samples already on file are skipped rather than duplicated. # earlier samples, so samples already on file are skipped rather than duplicated.
def import def import
file = params[:report] file = params[:report]
return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: "Choose a lab report PDF.") if file.blank? return redirect_to(new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.choose_a_lab_report")) if file.blank?
report = OilReportParser.from_pdf(file.tempfile) report = OilReportParser.from_pdf(file.tempfile)
file.rewind file.rewind
if report.tail_number.present? && normalize_tail(report.tail_number) != normalize_tail(@aircraft.tail_number) if report.tail_number.present? && normalize_tail(report.tail_number) != normalize_tail(@aircraft.tail_number)
return redirect_to(new_aircraft_oil_analysis_path(@aircraft), return redirect_to(new_aircraft_oil_analysis_path(@aircraft),
alert: "That report is for #{report.tail_number}, not #{@aircraft.tail_number}.") alert: t("flash.oil_analyses.that_report_is_for", report_tail: report.tail_number, tail_number: @aircraft.tail_number))
end end
engine = engine_for(report) engine = engine_for(report)
@@ -57,20 +57,20 @@ class OilAnalysesController < ApplicationController
current_record.report.attach(file) if current_record && !current_record.report.attached? current_record.report.attach(file) if current_record && !current_record.report.attached?
skipped = report.samples.size - created.size skipped = report.samples.size - created.size
created.each { log_event("oil_analysis", "Oil analysis imported (sampled #{_1.sample_date})") } created.each { log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_imported_sampled", sample_date: _1.sample_date)) }
notice = "Imported #{helpers.pluralize(created.size, 'sample')} from the #{report.lab} report." notice = t("flash.oil_analyses.imported", count: created.size, lab: report.lab)
notice += " #{helpers.pluralize(skipped, 'sample was', plural: 'samples were')} already recorded." if skipped.positive? notice += " #{t('flash.oil_analyses.already_recorded', count: skipped)}" if skipped.positive?
redirect_to aircraft_oil_analyses_path(@aircraft), notice: notice redirect_to aircraft_oil_analyses_path(@aircraft), notice: notice
rescue OilReportParser::Error => e rescue OilReportParser::Error => e
redirect_to new_aircraft_oil_analysis_path(@aircraft), alert: "Couldn't import that report: #{e.message}" redirect_to new_aircraft_oil_analysis_path(@aircraft), alert: t("flash.oil_analyses.couldn_t_import_that", message: e.message)
end end
def edit; end def edit; end
def update def update
if @analysis.update(analysis_params) if @analysis.update(analysis_params)
log_event("oil_analysis", "Oil analysis updated (sampled #{@analysis.sample_date})") log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_updated_sampled", sample_date: @analysis.sample_date))
redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: "Oil analysis updated." redirect_to aircraft_oil_analysis_path(@aircraft, @analysis), notice: t("flash.oil_analyses.oil_analysis_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -78,8 +78,8 @@ class OilAnalysesController < ApplicationController
def destroy def destroy
@analysis.destroy! @analysis.destroy!
log_event("oil_analysis", "Oil analysis deleted (sampled #{@analysis.sample_date})") log_event("oil_analysis", t("flash.oil_analyses.oil_analysis_deleted_sampled", sample_date: @analysis.sample_date))
redirect_to aircraft_oil_analyses_path(@aircraft), notice: "Oil analysis deleted." redirect_to aircraft_oil_analyses_path(@aircraft), notice: t("flash.oil_analyses.oil_analysis_deleted")
end end
private private
+6 -6
View File
@@ -2,8 +2,8 @@ class PasswordsController < ApplicationController
allow_unauthenticated_access allow_unauthenticated_access
before_action :require_password_login before_action :require_password_login
before_action :set_user_by_token, only: %i[ edit update ] before_action :set_user_by_token, only: %i[ edit update ]
rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_session_path, alert: t("flash.passwords.try_again_later") }
rate_limit to: 10, within: 15.minutes, only: :update, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 10, within: 15.minutes, only: :update, with: -> { redirect_to new_session_path, alert: t("flash.passwords.try_again_later_2") }
def new def new
end end
@@ -13,7 +13,7 @@ class PasswordsController < ApplicationController
PasswordsMailer.reset(user).deliver_later PasswordsMailer.reset(user).deliver_later
end end
redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)." redirect_to new_session_path, notice: t("flash.passwords.password_reset_instructions_sent")
end end
def edit def edit
@@ -22,7 +22,7 @@ class PasswordsController < ApplicationController
def update def update
if params[:password].present? && @user.update(params.permit(:password, :password_confirmation)) if params[:password].present? && @user.update(params.permit(:password, :password_confirmation))
@user.sessions.destroy_all # a reset signs out every device @user.sessions.destroy_all # a reset signs out every device
redirect_to new_session_path, notice: "Password has been reset." redirect_to new_session_path, notice: t("flash.passwords.password_has_been_reset")
else else
redirect_to edit_password_path(params[:token]), alert: @user.errors.full_messages.to_sentence.presence || "Enter a new password." redirect_to edit_password_path(params[:token]), alert: @user.errors.full_messages.to_sentence.presence || "Enter a new password."
end end
@@ -30,12 +30,12 @@ class PasswordsController < ApplicationController
private private
def require_password_login def require_password_login
redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? redirect_to new_session_path, alert: t("flash.passwords.sign_in_with", label: Sso.label) unless Sso.password_login?
end end
def set_user_by_token def set_user_by_token
@user = User.find_by_password_reset_token!(params[:token]) @user = User.find_by_password_reset_token!(params[:token])
rescue ActiveSupport::MessageVerifier::InvalidSignature rescue ActiveSupport::MessageVerifier::InvalidSignature
redirect_to new_password_path, alert: "Password reset link is invalid or has expired." redirect_to new_password_path, alert: t("flash.passwords.password_reset_link_is")
end end
end end
+3 -3
View File
@@ -14,13 +14,13 @@ class ProfilesController < ApplicationController
# Checked before assigning: setting a new password replaces the digest at once. # Checked before assigning: setting a new password replaces the digest at once.
if sensitive && !@user.authenticate_password(params.dig(:user, :current_password).to_s) if sensitive && !@user.authenticate_password(params.dig(:user, :current_password).to_s)
@user.assign_attributes(attrs.except(:password, :password_confirmation)) @user.assign_attributes(attrs.except(:password, :password_confirmation))
@user.errors.add(:base, "Enter your current password to change your email or password") @user.errors.add(:base, :current_password_needed)
return render :edit, status: :unprocessable_entity return render :edit, status: :unprocessable_entity
end end
@user.assign_attributes(attrs) @user.assign_attributes(attrs)
if @user.save if @user.save
@user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password) @user.sessions.where.not(id: Current.session.id).destroy_all if attrs.key?(:password)
redirect_to root_path, notice: "Profile updated." redirect_to root_path, notice: t("flash.profiles.profile_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -28,6 +28,6 @@ class ProfilesController < ApplicationController
def sign_out_others def sign_out_others
count = current_user.sessions.where.not(id: Current.session.id).destroy_all.size count = current_user.sessions.where.not(id: Current.session.id).destroy_all.size
redirect_to edit_profile_path, notice: "Signed out #{helpers.pluralize(count, 'other session')}." redirect_to edit_profile_path, notice: t("flash.profiles.signed_out_others", count: count)
end end
end end
@@ -18,17 +18,17 @@ class RecordVersionsController < ApplicationController
def restore def restore
version = RecordVersion.where(aircraft_id: @aircraft.id, event: "unlink", item_type: SHARED.keys).find(params[:id]) version = RecordVersion.where(aircraft_id: @aircraft.id, event: "unlink", item_type: SHARED.keys).find(params[:id])
record = SHARED.fetch(version.item_type).find_by(id: version.item_id) record = SHARED.fetch(version.item_type).find_by(id: version.item_id)
return redirect_to(aircraft_record_versions_path(@aircraft), alert: "That record no longer exists.") unless record return redirect_to(aircraft_record_versions_path(@aircraft), alert: t("flash.record_versions.that_record_no_longer")) unless record
c = version.changes_hash c = version.changes_hash
if c["applies_to"] == "component" if c["applies_to"] == "component"
component = @aircraft.components.find_by(id: c["component_id"]) component = @aircraft.components.find_by(id: c["component_id"])
return redirect_to(aircraft_record_versions_path(@aircraft), alert: "That component no longer exists; edit the record's applicability instead.") unless component return redirect_to(aircraft_record_versions_path(@aircraft), alert: t("flash.record_versions.that_component_no_longer")) unless component
record.components << component unless record.components.include?(component) record.components << component unless record.components.include?(component)
else else
record.aircraft << @aircraft unless record.aircraft.include?(@aircraft) record.aircraft << @aircraft unless record.aircraft.include?(@aircraft)
end end
log_event(version.item_type == "AirworthinessDirective" ? "ad" : "inspection", "Restored: #{record} applies again") log_event(version.item_type == "AirworthinessDirective" ? "ad" : "inspection", "Restored: #{record} applies again")
redirect_to aircraft_record_versions_path(@aircraft), notice: "#{record} applies to #{@aircraft.tail_number} again." redirect_to aircraft_record_versions_path(@aircraft), notice: t("flash.record_versions.applies_to_again", record: record, tail_number: @aircraft.tail_number)
end end
# Whether an unlink can still be undone (the record exists and isn't linked that way now). # Whether an unlink can still be undone (the record exists and isn't linked that way now).
@@ -10,7 +10,7 @@ class RecordsPackagesController < ApplicationController
Dir[dir.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago } Dir[dir.join("*.zip")].each { |old| File.delete(old) if File.mtime(old) < 1.hour.ago }
path = dir.join("#{SecureRandom.hex(12)}.zip").to_s path = dir.join("#{SecureRandom.hex(12)}.zip").to_s
package.write_to(path) package.write_to(path)
log_event("aircraft", "Records package downloaded") log_event("aircraft", t("flash.records_packages.records_package_downloaded"))
# Generic binary, not application/zip: Safari unzips zip downloads into a # Generic binary, not application/zip: Safari unzips zip downloads into a
# folder ("Open safe files"); the package should stay one file to hand over. # folder ("Open safe files"); the package should stay one file to hand over.
send_file path, filename: package.filename, type: "application/octet-stream", disposition: "attachment" send_file path, filename: package.filename, type: "application/octet-stream", disposition: "attachment"
+1 -1
View File
@@ -1,7 +1,7 @@
# One search box across the records of the aircraft the user can see # One search box across the records of the aircraft the user can see
# (or one aircraft, from its own pages). # (or one aircraft, from its own pages).
class SearchesController < ApplicationController class SearchesController < ApplicationController
rate_limit to: 60, within: 1.minute, with: -> { redirect_to root_path, alert: "Too many searches; wait a moment." } rate_limit to: 60, within: 1.minute, with: -> { redirect_to root_path, alert: t("flash.searches.too_many_searches_wait") }
def show def show
fleet = current_user.accessible_aircraft.ordered.to_a fleet = current_user.accessible_aircraft.ordered.to_a
+9 -10
View File
@@ -1,45 +1,44 @@
class SessionsController < ApplicationController class SessionsController < ApplicationController
allow_unauthenticated_access only: %i[new create two_factor verify_two_factor] allow_unauthenticated_access only: %i[new create two_factor verify_two_factor]
rate_limit to: 10, within: 3.minutes, only: %i[create verify_two_factor], with: -> { redirect_to new_session_url, alert: "Try again later." } rate_limit to: 10, within: 3.minutes, only: %i[create verify_two_factor], with: -> { redirect_to new_session_url, alert: t("flash.sessions.try_again_later") }
FAILED = "Try another email address or password. After #{User::LOCK_AFTER} failed tries in a row an account is locked for #{User::LOCK_FOR.inspect}.".freeze
def new def new
end end
def create def create
return redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? return redirect_to new_session_path, alert: t("flash.sessions.sign_in_with", label: Sso.label) unless Sso.password_login?
if (user = User.authenticate_with_lockout(email_address: params[:email_address], password: params[:password])) && user.disabled? if (user = User.authenticate_with_lockout(email_address: params[:email_address], password: params[:password])) && user.disabled?
redirect_to new_session_path, alert: "This account is disabled." redirect_to new_session_path, alert: t("flash.sessions.this_account_is_disabled")
elsif user elsif user
begin_sign_in user, return_to: after_authentication_url begin_sign_in user, return_to: after_authentication_url
else else
redirect_to new_session_path(email_address: params[:email_address].to_s.first(200)), alert: FAILED redirect_to new_session_path(email_address: params[:email_address].to_s.first(200)), alert: t("flash.sessions.failed", tries: User::LOCK_AFTER, minutes: User::LOCK_FOR.in_minutes.to_i)
end end
end end
# Second step for accounts with an authenticator app. # Second step for accounts with an authenticator app.
def two_factor def two_factor
redirect_to new_session_path, alert: "Sign in again." unless pending_otp_user redirect_to new_session_path, alert: t("flash.sessions.sign_in_again") unless pending_otp_user
end end
def verify_two_factor def verify_two_factor
user = pending_otp_user user = pending_otp_user
return redirect_to(new_session_path, alert: "That took too long. Sign in again.") unless user return redirect_to(new_session_path, alert: t("flash.sessions.that_took_too_long")) unless user
if user.locked? if user.locked?
reset_session reset_session
redirect_to new_session_path, alert: FAILED redirect_to new_session_path, alert: t("flash.sessions.failed", tries: User::LOCK_AFTER, minutes: User::LOCK_FOR.in_minutes.to_i)
elsif user.verify_second_factor(params[:code]) elsif user.verify_second_factor(params[:code])
user.clear_failed_sign_ins! user.clear_failed_sign_ins!
return_to = after_authentication_url return_to = after_authentication_url
reset_session reset_session
start_new_session_for user start_new_session_for user
notice = user.recovery_codes_left < 3 ? "Signed in. You have #{user.recovery_codes_left} recovery codes left: make new ones on your profile." : nil notice = user.recovery_codes_left < 3 ? t("flash.sessions.few_recovery_codes", count: user.recovery_codes_left) : nil
redirect_to return_to, notice: notice redirect_to return_to, notice: notice
else else
user.register_failed_sign_in! user.register_failed_sign_in!
redirect_to two_factor_session_path, alert: "That code didn't match. Try the current code from your authenticator app, or a recovery code." redirect_to two_factor_session_path, alert: t("flash.sessions.that_code_didn_t")
end end
end end
+1 -1
View File
@@ -12,7 +12,7 @@ class SetupController < ApplicationController
@user.admin = true @user.admin = true
if @user.save if @user.save
start_new_session_for @user start_new_session_for @user
redirect_to root_path, notice: "Welcome! You're the administrator. Add your first aircraft." redirect_to root_path, notice: t("flash.setup.welcome_you_re_the")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
+4 -4
View File
@@ -6,8 +6,8 @@ class ShareTokensController < ApplicationController
token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at)) token = @aircraft.share_tokens.new(params.require(:share_token).permit(:label, :privilege, :expires_at))
token.created_by = current_user token.created_by = current_user
if token.save if token.save
log_event("aircraft", "Share link created (#{token.privilege})", notes: token.label) log_event("aircraft", t("flash.share_tokens.share_link_created_2", privilege: token.privilege), notes: token.label)
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link created." redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.share_tokens.share_link_created")
else else
redirect_to aircraft_aircraft_roles_path(@aircraft), alert: token.errors.full_messages.to_sentence redirect_to aircraft_aircraft_roles_path(@aircraft), alert: token.errors.full_messages.to_sentence
end end
@@ -16,7 +16,7 @@ class ShareTokensController < ApplicationController
def destroy def destroy
token = @aircraft.share_tokens.find(params[:id]) token = @aircraft.share_tokens.find(params[:id])
token.destroy! token.destroy!
log_event("aircraft", "Share link revoked", notes: token.label) log_event("aircraft", t("flash.share_tokens.share_link_revoked_2"), notes: token.label)
redirect_to aircraft_aircraft_roles_path(@aircraft), notice: "Share link revoked." redirect_to aircraft_aircraft_roles_path(@aircraft), notice: t("flash.share_tokens.share_link_revoked")
end end
end end
+7 -7
View File
@@ -7,8 +7,8 @@ class SignInLinksController < ApplicationController
allow_unauthenticated_access allow_unauthenticated_access
before_action :require_email_sign_in before_action :require_email_sign_in
before_action :set_user_by_token, only: %i[show consume] before_action :set_user_by_token, only: %i[show consume]
rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_sign_in_link_path, alert: "Try again later." } rate_limit to: 5, within: 15.minutes, only: :create, with: -> { redirect_to new_sign_in_link_path, alert: t("flash.sign_in_links.try_again_later") }
rate_limit to: 20, within: 15.minutes, only: :consume, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 20, within: 15.minutes, only: :consume, with: -> { redirect_to new_session_path, alert: t("flash.sign_in_links.try_again_later_2") }
def new def new
end end
@@ -18,25 +18,25 @@ class SignInLinksController < ApplicationController
SessionsMailer.sign_in_link(user).deliver_later SessionsMailer.sign_in_link(user).deliver_later
end end
# Same answer either way, so this can't be used to find accounts. # Same answer either way, so this can't be used to find accounts.
redirect_to new_session_path, notice: "If there's an account for that address, a sign-in link is on its way. It works once, for 15 minutes." redirect_to new_session_path, notice: t("flash.sign_in_links.if_there_s_an")
end end
def show def show
end end
def consume def consume
return redirect_to new_session_path, alert: "This account is disabled." if @user.disabled? return redirect_to new_session_path, alert: t("flash.sign_in_links.this_account_is_disabled") if @user.disabled?
begin_sign_in @user, return_to: root_path, notice: "Signed in." # signing in also spends the link begin_sign_in @user, return_to: root_path, notice: t("flash.sign_in_links.signed_in") # signing in also spends the link
end end
private private
def require_email_sign_in def require_email_sign_in
redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? redirect_to new_session_path, alert: t("flash.sign_in_links.sign_in_with", label: Sso.label) unless Sso.password_login?
end end
def set_user_by_token def set_user_by_token
@user = User.find_by_token_for(:email_sign_in, params[:token].to_s) @user = User.find_by_token_for(:email_sign_in, params[:token].to_s)
redirect_to new_sign_in_link_path, alert: "That sign-in link has expired or was already used. Get a new one below." unless @user redirect_to new_sign_in_link_path, alert: t("flash.sign_in_links.that_sign_in_link") unless @user
end end
end end
@@ -3,22 +3,22 @@ class SigningInvitationsController < ApplicationController
include AircraftScoped include AircraftScoped
before_action :require_owner! before_action :require_owner!
before_action :set_entry before_action :set_entry
rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: "Too many invitations; try again later." } rate_limit to: 10, within: 1.hour, only: :create, with: -> { redirect_back fallback_location: root_path, alert: t("flash.signing_invitations.too_many_invitations_try") }
def new def new
@invitation = @entry.signing_invitations.new @invitation = @entry.signing_invitations.new
end end
def create def create
return redirect_to(aircraft_logbook_entry_path(@aircraft, @entry), alert: "This entry is already signed.") if @entry.signed? return redirect_to(aircraft_logbook_entry_path(@aircraft, @entry), alert: t("flash.signing_invitations.this_entry_is_already")) if @entry.signed?
unless MailSettings.configured? unless MailSettings.configured?
return redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: "Email isn't set up, so invitations can't be sent (Admin → About)." return redirect_to aircraft_logbook_entry_path(@aircraft, @entry), alert: t("flash.signing_invitations.email_isn_t_set")
end end
@invitation = @entry.signing_invitations.new(params.require(:signing_invitation).permit(:email, :message).merge(invited_by: current_user)) @invitation = @entry.signing_invitations.new(params.require(:signing_invitation).permit(:email, :message).merge(invited_by: current_user))
if @invitation.save if @invitation.save
SigningInvitationMailer.invite(@invitation, @invitation.token).deliver_later SigningInvitationMailer.invite(@invitation, @invitation.token).deliver_later
log_event("logbook", "Signature requested from #{@invitation.email} (#{@entry.date} entry)") log_event("logbook", t("flash.signing_invitations.signature_requested_from_entry", email: @invitation.email, date: @entry.date))
redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: "Invitation sent to #{@invitation.email}. The link works once, for #{SigningInvitation::VALID_FOR.inspect}." redirect_to aircraft_logbook_entry_path(@aircraft, @entry), notice: t("flash.signing_invitations.invitation_sent_to_the", email: @invitation.email, _: SigningInvitation::VALID_FOR.inspect)
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
+16 -16
View File
@@ -17,8 +17,8 @@ class SquawksController < ApplicationController
def create def create
@squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user)) @squawk = @aircraft.squawks.new(squawk_params.merge(reported_by: current_user))
if @squawk.save if @squawk.save
log_event("squawk", "Squawk reported: #{@squawk.priority_label}", notes: @squawk.issue_reported.truncate(200)) log_event("squawk", t("flash.squawks.squawk_reported_2", priority_label: @squawk.priority_label), notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reported." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reported")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -30,8 +30,8 @@ class SquawksController < ApplicationController
@squawk.assign_attributes(squawk_params.except(:attachments)) @squawk.assign_attributes(squawk_params.except(:attachments))
change_attachments change_attachments
if @squawk.save if @squawk.save
log_event("squawk", "Squawk updated") log_event("squawk", t("flash.squawks.squawk_updated_2"))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk updated." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -42,7 +42,7 @@ class SquawksController < ApplicationController
def resolution def resolution
@entry = @aircraft.logbook_entries.new(date: Date.current, entry_type: "MAINTENANCE", log_type: "AC", @entry = @aircraft.logbook_entries.new(date: Date.current, entry_type: "MAINTENANCE", log_type: "AC",
aircraft_hours_at_entry: @aircraft.current_hours, aircraft_hours_at_entry: @aircraft.current_hours,
text: "Corrected: #{@squawk.issue_reported}", component: @squawk.component, text: t("flash.squawks.corrected_text", issue: @squawk.issue_reported), component: @squawk.component,
component_hours_at_entry: @squawk.component&.hours_in_service, component_hours_at_entry: @squawk.component&.hours_in_service,
component_since_overhaul_at_entry: @squawk.component&.hours_since_overhaul) component_since_overhaul_at_entry: @squawk.component&.hours_since_overhaul)
@entry.log_type = "ENG" if @squawk.component&.engine? @entry.log_type = "ENG" if @squawk.component&.engine?
@@ -56,13 +56,13 @@ class SquawksController < ApplicationController
@entry = @aircraft.logbook_entries.new(resolution_entry_params.merge(entry_type: "MAINTENANCE")) @entry = @aircraft.logbook_entries.new(resolution_entry_params.merge(entry_type: "MAINTENANCE"))
@entry.assign_parts(params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {}, @aircraft) @entry.assign_parts(params.fetch(:logbook_entry, {}).permit(parts: {})[:parts]&.to_h || {}, @aircraft)
return render(:resolution, status: :unprocessable_entity) unless @entry.save return render(:resolution, status: :unprocessable_entity) unless @entry.save
log_event("logbook", "Logbook entry added: #{@entry.date}") log_event("logbook", t("flash.squawks.logbook_entry_added", date: @entry.date))
@entry @entry
when "existing" then @aircraft.logbook_entries.find_by(id: params[:logbook_entry_id]) when "existing" then @aircraft.logbook_entries.find_by(id: params[:logbook_entry_id])
end end
@squawk.resolve!(notes: params[:resolution_notes], logbook_entry: entry) @squawk.resolve!(notes: params[:resolution_notes], logbook_entry: entry)
log_event("squawk", "Squawk resolved", notes: @squawk.issue_reported.truncate(200)) log_event("squawk", t("flash.squawks.squawk_resolved_2"), notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk resolved#{' and recorded in the logbook' if entry}." redirect_to aircraft_squawks_path(@aircraft), notice: t(entry ? "flash.squawks.resolved_logged" : "flash.squawks.squawk_resolved")
end end
def deferral; end def deferral; end
@@ -70,8 +70,8 @@ class SquawksController < ApplicationController
def defer def defer
if @squawk.defer(checks: params[:checks], name: params[:deferred_by_name], role: params[:deferred_by_role], if @squawk.defer(checks: params[:checks], name: params[:deferred_by_name], role: params[:deferred_by_role],
action: params[:deferral_action], notes: params[:deferral_notes]) action: params[:deferral_action], notes: params[:deferral_notes])
log_event("squawk", "Inoperative item deferred (91.213(d))", notes: @squawk.issue_reported.truncate(200)) log_event("squawk", t("flash.squawks.inoperative_item_deferred_91"), notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Deferred. Keep the placard in place until it's fixed." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.deferred_keep_the_placard")
else else
render :deferral, status: :unprocessable_entity render :deferral, status: :unprocessable_entity
end end
@@ -79,20 +79,20 @@ class SquawksController < ApplicationController
def undefer def undefer
@squawk.undefer! @squawk.undefer!
log_event("squawk", "Deferral removed", notes: @squawk.issue_reported.truncate(200)) log_event("squawk", t("flash.squawks.deferral_removed_2"), notes: @squawk.issue_reported.truncate(200))
redirect_to aircraft_squawks_path(@aircraft), notice: "Deferral removed." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.deferral_removed")
end end
def reopen def reopen
@squawk.update!(resolved: false, resolved_at: nil) @squawk.update!(resolved: false, resolved_at: nil)
log_event("squawk", "Squawk reopened") log_event("squawk", t("flash.squawks.squawk_reopened_2"))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk reopened." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_reopened")
end end
def destroy def destroy
@squawk.destroy! @squawk.destroy!
log_event("squawk", "Squawk deleted") log_event("squawk", t("flash.squawks.squawk_deleted_2"))
redirect_to aircraft_squawks_path(@aircraft), notice: "Squawk deleted." redirect_to aircraft_squawks_path(@aircraft), notice: t("flash.squawks.squawk_deleted")
end end
private private
+11 -13
View File
@@ -9,7 +9,7 @@
class SsoController < ApplicationController class SsoController < ApplicationController
allow_unauthenticated_access only: %i[callback failure] allow_unauthenticated_access only: %i[callback failure]
before_action :require_sso before_action :require_sso
rate_limit to: 20, within: 3.minutes, only: :callback, with: -> { redirect_to new_session_path, alert: "Try again later." } rate_limit to: 20, within: 3.minutes, only: :callback, with: -> { redirect_to new_session_path, alert: t("flash.sso.try_again_later") }
def callback def callback
auth = request.env["omniauth.auth"] auth = request.env["omniauth.auth"]
@@ -20,11 +20,10 @@ class SsoController < ApplicationController
user = User.find_by(sso_uid: auth.uid) || link_by_email(auth) || create_user(auth) user = User.find_by(sso_uid: auth.uid) || link_by_email(auth) || create_user(auth)
unless user unless user
email = auth.info&.email.presence email = auth.info&.email.presence
return redirect_to new_session_path, alert: "There's no account for #{email || 'that sign-in'} here yet. " \ return redirect_to new_session_path, alert: t("flash.sso.there_s_no_account", email: email || t("flash.sso.that_sign_in"), provider: Sso.label)
"Ask an administrator to add you, or sign in with your password and link #{Sso.label} from your profile."
end end
return redirect_to new_session_path, alert: "This account is disabled." if user.disabled? return redirect_to new_session_path, alert: t("flash.sso.this_account_is_disabled") if user.disabled?
sync_admin(user, auth) sync_admin(user, auth)
return_to = session[:return_to_after_authenticating] return_to = session[:return_to_after_authenticating]
@@ -34,22 +33,21 @@ class SsoController < ApplicationController
end end
# OmniAuth's error codes; anything else (network errors…) is logged, not shown. # OmniAuth's error codes; anything else (network errors…) is logged, not shown.
FAILURES = { "invalid_credentials" => "invalid credentials", "csrf_detected" => "the sign-in expired, try again", FAILURES = %w[invalid_credentials csrf_detected access_denied timeout].freeze
"access_denied" => "access denied", "timeout" => "timed out" }.freeze
def failure def failure
reason = FAILURES[params[:message].to_s] reason = t(params[:message], scope: "flash.sso.failures") if FAILURES.include?(params[:message].to_s)
Rails.logger.warn("[sso] sign-in failed: #{params[:message].to_s.truncate(300)}") unless reason Rails.logger.warn("[sso] sign-in failed: #{params[:message].to_s.truncate(300)}") unless reason
redirect_to(authenticated? ? edit_profile_path : new_session_path, redirect_to(authenticated? ? edit_profile_path : new_session_path,
alert: "#{Sso.label} sign-in failed (#{reason || "couldn't reach or verify #{Sso.label}; see the server log"}).") alert: t("flash.sso.failed", provider: Sso.label, reason: reason || t("flash.sso.unreachable", provider: Sso.label)))
end end
def destroy def destroy
unless Sso.password_login? unless Sso.password_login?
return redirect_to edit_profile_path, alert: "Password sign-in is off, so unlinking #{Sso.label} would lock you out." return redirect_to edit_profile_path, alert: t("flash.sso.password_sign_in_is", label: Sso.label)
end end
current_user.update!(sso_uid: nil) current_user.update!(sso_uid: nil)
redirect_to edit_profile_path, notice: "#{Sso.label} unlinked. Sign in with your email and password from now on." redirect_to edit_profile_path, notice: t("flash.sso.unlinked_sign_in_with", label: Sso.label)
end end
private private
@@ -61,16 +59,16 @@ class SsoController < ApplicationController
# Signed in again (e.g. to sign a logbook entry): note when, and go back. # Signed in again (e.g. to sign a logbook entry): note when, and go back.
def reauthenticated(auth) def reauthenticated(auth)
session[:reauthenticated_at] = Time.current.to_i session[:reauthenticated_at] = Time.current.to_i
redirect_to session.delete(:after_reauth).presence || edit_profile_path, notice: "Signed in again with #{Sso.label}." redirect_to session.delete(:after_reauth).presence || edit_profile_path, notice: t("flash.sso.signed_in_again_with", label: Sso.label)
end end
def link(auth) def link(auth)
owner = User.find_by(sso_uid: auth.uid) owner = User.find_by(sso_uid: auth.uid)
if owner && owner != current_user if owner && owner != current_user
redirect_to edit_profile_path, alert: "That #{Sso.label} account is already linked to another user." redirect_to edit_profile_path, alert: t("flash.sso.that_account_is_already", label: Sso.label)
else else
current_user.update!(sso_uid: auth.uid) current_user.update!(sso_uid: auth.uid)
redirect_to edit_profile_path, notice: "#{Sso.label} linked. You can now sign in with it." redirect_to edit_profile_path, notice: t("flash.sso.linked_you_can_now", label: Sso.label)
end end
end end
@@ -7,10 +7,10 @@ class StandardInspectionsController < ApplicationController
def create def create
added = StandardInspections.add!(@aircraft, params[:templates]) added = StandardInspections.add!(@aircraft, params[:templates])
if added.any? if added.any?
log_event("inspection", "Standard inspections added", notes: added.map(&:name).join(", ")) log_event("inspection", t("flash.standard_inspections.standard_inspections_added"), notes: added.map(&:name).join(", "))
redirect_to aircraft_inspections_path(@aircraft), notice: "Added #{added.map(&:name).to_sentence}. Record when each was last done to see when it's next due." redirect_to aircraft_inspections_path(@aircraft), notice: t("flash.standard_inspections.added_record_when_each", items: added.map(&:name).to_sentence)
else else
redirect_to new_aircraft_standard_inspections_path(@aircraft), alert: "Nothing new was chosen." redirect_to new_aircraft_standard_inspections_path(@aircraft), alert: t("flash.standard_inspections.nothing_new_was_chosen")
end end
end end
end end
+6 -6
View File
@@ -1,10 +1,10 @@
# Profile → Two-factor: set up an authenticator app (TOTP) for password and # Profile → Two-factor: set up an authenticator app (TOTP) for password and
# emailed-link sign-in, turn it off, or make new recovery codes. # emailed-link sign-in, turn it off, or make new recovery codes.
class TwoFactorsController < ApplicationController class TwoFactorsController < ApplicationController
rate_limit to: 10, within: 5.minutes, only: %i[create destroy recovery_codes], with: -> { redirect_to edit_profile_path(anchor: "two-factor"), alert: "Try again later." } rate_limit to: 10, within: 5.minutes, only: %i[create destroy recovery_codes], with: -> { redirect_to edit_profile_path(anchor: "two-factor"), alert: t("flash.two_factors.try_again_later") }
def new def new
return redirect_to(back_path, notice: "Two-factor is already on.") if current_user.otp_enabled? return redirect_to(back_path, notice: t("flash.two_factors.two_factor_is_already")) if current_user.otp_enabled?
session[:pending_otp_secret] ||= User.new_otp_secret session[:pending_otp_secret] ||= User.new_otp_secret
@secret = session[:pending_otp_secret] @secret = session[:pending_otp_secret]
svg = RQRCode::QRCode.new(User.otp_uri(@secret, current_user.email_address)).as_svg(module_size: 4, use_path: true, viewbox: true) svg = RQRCode::QRCode.new(User.otp_uri(@secret, current_user.email_address)).as_svg(module_size: 4, use_path: true, viewbox: true)
@@ -20,22 +20,22 @@ class TwoFactorsController < ApplicationController
log_security("turned on two-factor") log_security("turned on two-factor")
render :codes render :codes
else else
redirect_to new_two_factor_path(return_to: params[:return_to]), alert: "That code didn't match. Check the time on your phone and try the current code." redirect_to new_two_factor_path(return_to: params[:return_to]), alert: t("flash.two_factors.that_code_didn_t")
end end
end end
def recovery_codes def recovery_codes
return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code]) return redirect_to(edit_profile_path(anchor: "two-factor"), alert: t("flash.two_factors.that_code_didn_t_2")) unless current_user.verify_second_factor(params[:code])
@codes = current_user.enable_otp!(current_user.otp_secret) @codes = current_user.enable_otp!(current_user.otp_secret)
log_security("made new recovery codes") log_security("made new recovery codes")
render :codes render :codes
end end
def destroy def destroy
return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code]) return redirect_to(edit_profile_path(anchor: "two-factor"), alert: t("flash.two_factors.that_code_didn_t_3")) unless current_user.verify_second_factor(params[:code])
current_user.disable_otp! current_user.disable_otp!
log_security("turned off two-factor") log_security("turned off two-factor")
redirect_to edit_profile_path(anchor: "two-factor"), notice: "Two-factor is off." redirect_to edit_profile_path(anchor: "two-factor"), notice: t("flash.two_factors.two_factor_is_off")
end end
private private
@@ -6,23 +6,23 @@ class UserCertificatesController < ApplicationController
certificate = current_user.certificates.new(certificate_params) certificate = current_user.certificates.new(certificate_params)
back = safe_return_to || edit_profile_path(anchor: "certificates") back = safe_return_to || edit_profile_path(anchor: "certificates")
if certificate.save if certificate.save
redirect_to back, notice: "#{certificate.kind_label} certificate added." redirect_to back, notice: t("flash.user_certificates.certificate_added", kind_label: certificate.kind_label)
else else
redirect_to back, alert: "Certificate not added: #{certificate.errors.full_messages.to_sentence}." redirect_to back, alert: t("flash.user_certificates.certificate_not_added", items: certificate.errors.full_messages.to_sentence)
end end
end end
def update def update
if @certificate.update(certificate_params) if @certificate.update(certificate_params)
redirect_to edit_profile_path(anchor: "certificates"), notice: "Certificate updated." redirect_to edit_profile_path(anchor: "certificates"), notice: t("flash.user_certificates.certificate_updated")
else else
redirect_to edit_profile_path(anchor: "certificates"), alert: "Certificate not updated: #{@certificate.errors.full_messages.to_sentence}." redirect_to edit_profile_path(anchor: "certificates"), alert: t("flash.user_certificates.certificate_not_updated", items: @certificate.errors.full_messages.to_sentence)
end end
end end
def destroy def destroy
@certificate.destroy! @certificate.destroy!
redirect_to edit_profile_path(anchor: "certificates"), notice: "Certificate removed." redirect_to edit_profile_path(anchor: "certificates"), notice: t("flash.user_certificates.certificate_removed")
end end
private private
@@ -19,8 +19,8 @@ class WeightBalanceRecordsController < ApplicationController
def create def create
@record = @aircraft.weight_balance_records.new(record_params) @record = @aircraft.weight_balance_records.new(record_params)
if @record.save if @record.save
log_event("aircraft", "Weight & balance recorded: #{@record.empty_weight} lb @ #{@record.empty_arm} in") log_event("aircraft", t("flash.weight_balance_records.weight_balance_recorded_lb", empty_weight: @record.empty_weight, empty_arm: @record.empty_arm))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Weight & balance saved." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.weight_balance_records.weight_balance_saved")
else else
render :new, status: :unprocessable_entity render :new, status: :unprocessable_entity
end end
@@ -30,8 +30,8 @@ class WeightBalanceRecordsController < ApplicationController
def update def update
if @record.update(record_params) if @record.update(record_params)
log_event("aircraft", "Weight & balance updated (#{@record.date})") log_event("aircraft", t("flash.weight_balance_records.weight_balance_updated_2", date: @record.date))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Weight & balance updated." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.weight_balance_records.weight_balance_updated")
else else
render :edit, status: :unprocessable_entity render :edit, status: :unprocessable_entity
end end
@@ -39,8 +39,8 @@ class WeightBalanceRecordsController < ApplicationController
def destroy def destroy
@record.destroy! @record.destroy!
log_event("aircraft", "Weight & balance record deleted (#{@record.date})") log_event("aircraft", t("flash.weight_balance_records.weight_balance_record_deleted", date: @record.date))
redirect_to aircraft_weight_balance_records_path(@aircraft), notice: "Record deleted." redirect_to aircraft_weight_balance_records_path(@aircraft), notice: t("flash.weight_balance_records.record_deleted")
end end
private private
+4 -4
View File
@@ -5,7 +5,7 @@
# <%= f.field :public, as: :checkbox, label: "Show on share links" %> # <%= f.field :public, as: :checkbox, label: "Show on share links" %>
class AppFormBuilder < ActionView::Helpers::FormBuilder class AppFormBuilder < ActionView::Helpers::FormBuilder
def field(method, as: :text, label: nil, hint: nil, collection: nil, include_blank: false, wrapper: {}, **opts) def field(method, as: :text, label: nil, hint: nil, collection: nil, include_blank: false, wrapper: {}, **opts)
label_text = label || method.to_s.humanize label_text = label || (object.class.respond_to?(:human_attribute_name) ? object.class.human_attribute_name(method) : method.to_s.humanize)
errors = object.respond_to?(:errors) ? object.errors[method] : [] errors = object.respond_to?(:errors) ? object.errors[method] : []
if as == :checkbox if as == :checkbox
@@ -35,7 +35,7 @@ class AppFormBuilder < ActionView::Helpers::FormBuilder
@template.content_tag(:div, class: wrapper[:class]) do @template.content_tag(:div, class: wrapper[:class]) do
label(method, label_text, class: "label") + input + label(method, label_text, class: "label") + input +
(hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) + (hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) +
errors.map { |e| @template.content_tag(:p, "#{label_text} #{e}", class: "field-error") }.join.html_safe errors.map { |e| @template.content_tag(:p, I18n.t("errors.format", attribute: label_text, message: e), class: "field-error") }.join.html_safe
end end
end end
@@ -49,10 +49,10 @@ class AppFormBuilder < ActionView::Helpers::FormBuilder
label(every, label, class: "label") + label(every, label, class: "label") +
@template.content_tag(:div, class: "flex gap-2") do @template.content_tag(:div, class: "flex gap-2") do
number_field(every, class: "input min-w-0 flex-1", min: 1, step: 1, inputmode: "numeric") + number_field(every, class: "input min-w-0 flex-1", min: 1, step: 1, inputmode: "numeric") +
select(:"#{name}_unit", CalendarInterval::UNITS.invert, {}, class: "input w-auto", "aria-label": "#{label} unit") select(:"#{name}_unit", CalendarInterval::UNITS.invert, {}, class: "input w-auto", "aria-label": I18n.t("helpers.form.interval_unit", label: label))
end + end +
(hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) + (hint ? @template.content_tag(:p, hint, class: "hint") : "".html_safe) +
errors.map { |e| @template.content_tag(:p, "#{label} #{e}", class: "field-error") }.join.html_safe errors.map { |e| @template.content_tag(:p, I18n.t("errors.format", attribute: label, message: e), class: "field-error") }.join.html_safe
end end
end end
+16 -16
View File
@@ -2,32 +2,32 @@ module AircraftHelper
# Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only] # Tabs on the aircraft pages: [label, path, controller names that highlight it, owner_only]
def aircraft_tabs(aircraft) def aircraft_tabs(aircraft)
[ [
[ "Overview", aircraft_path(aircraft), %w[aircraft] ], [ I18n.t("helpers.aircraft.overview"), aircraft_path(aircraft), %w[aircraft] ],
[ "Components", aircraft_components_path(aircraft), %w[components] ], [ I18n.t("helpers.aircraft.components"), aircraft_components_path(aircraft), %w[components] ],
[ "Squawks", aircraft_squawks_path(aircraft), %w[squawks] ], [ I18n.t("helpers.aircraft.squawks"), aircraft_squawks_path(aircraft), %w[squawks] ],
[ "Flights", aircraft_flight_logs_path(aircraft), %w[flight_logs flight_imports air_trail_exports airport_codes] ], [ I18n.t("helpers.aircraft.flights"), aircraft_flight_logs_path(aircraft), %w[flight_logs flight_imports air_trail_exports airport_codes] ],
[ "Oil & Fuel", aircraft_consumable_records_path(aircraft), %w[consumable_records oil_analyses] ], [ I18n.t("helpers.aircraft.oil_fuel"), aircraft_consumable_records_path(aircraft), %w[consumable_records oil_analyses] ],
[ "Logbook", aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ], [ I18n.t("helpers.aircraft.logbook"), aircraft_logbook_entries_path(aircraft), %w[logbook_entries] ],
[ "Inspections", aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ], [ I18n.t("helpers.aircraft.inspections"), aircraft_inspections_path(aircraft), %w[inspections inspection_types inspection_records] ],
[ "ADs", aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances ad_imports] ], [ I18n.t("helpers.aircraft.ads"), aircraft_airworthiness_directives_path(aircraft), %w[airworthiness_directives ad_compliances ad_imports] ],
[ "Documents", aircraft_documents_path(aircraft), %w[documents document_collections] ], [ I18n.t("helpers.aircraft.documents"), aircraft_documents_path(aircraft), %w[documents document_collections] ],
[ "Major Records", aircraft_major_records_path(aircraft), %w[major_records] ], [ I18n.t("helpers.aircraft.major_records"), aircraft_major_records_path(aircraft), %w[major_records] ],
[ "W&B", aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ], [ I18n.t("helpers.aircraft.w_b"), aircraft_weight_balance_records_path(aircraft), %w[weight_balance_records loading_setups] ],
[ "Notes", aircraft_notes_path(aircraft), %w[notes] ], [ I18n.t("helpers.aircraft.notes"), aircraft_notes_path(aircraft), %w[notes] ],
[ "Activity", aircraft_events_path(aircraft), %w[events record_versions] ] [ I18n.t("helpers.aircraft.activity"), aircraft_events_path(aircraft), %w[events record_versions] ]
] ]
end end
def component_options(aircraft, include_blank: true) def component_options(aircraft, include_blank: true)
opts = aircraft.components.where.not(status: "DISPOSED").includes(:component_type).map { [ _1.to_s, _1.id ] } opts = aircraft.components.where.not(status: "DISPOSED").includes(:component_type).map { [ _1.to_s, _1.id ] }
include_blank ? [ [ "— None —", nil ] ] + opts : opts include_blank ? [ [ I18n.t("helpers.aircraft.none"), nil ] ] + opts : opts
end end
def document_options(aircraft) def document_options(aircraft)
[ [ "— None —", nil ] ] + aircraft.documents.ordered.map { [ _1.name, _1.id ] } [ [ I18n.t("helpers.aircraft.none"), nil ] ] + aircraft.documents.ordered.map { [ _1.name, _1.id ] }
end end
def logbook_options(aircraft) def logbook_options(aircraft)
[ [ "— None —", nil ] ] + aircraft.logbook_entries.recent_first.limit(300).map { [ "#{_1.date} – #{_1.text.truncate(60)}", _1.id ] } [ [ I18n.t("helpers.aircraft.none"), nil ] ] + aircraft.logbook_entries.recent_first.limit(300).map { [ I18n.t("helpers.aircraft.text", date: _1.date, truncate: (_1.text.truncate(60))), _1.id ] }
end end
end end
+13 -17
View File
@@ -7,19 +7,19 @@ module ApplicationHelper
# How dates and times read across the app: "Nov 8, 2026", "Nov 8, 2026 14:05". # How dates and times read across the app: "Nov 8, 2026", "Nov 8, 2026 14:05".
# (Signatures and the record history keep exact UTC timestamps, 2026-11-08 14:05 UTC.) # (Signatures and the record history keep exact UTC timestamps, 2026-11-08 14:05 UTC.)
def fmt_date(value) def fmt_date(value)
value ? value.to_date.strftime("%b %-d, %Y") : "—" value ? l(value.to_date, format: :app) : "—"
end end
def fmt_time(value) def fmt_time(value)
value ? value.in_time_zone.strftime("%b %-d, %Y %H:%M") : "—" value ? l(value.in_time_zone, format: :app) : "—"
end end
# Secondary actions (imports, exports, printing, tools) behind one "More" # Secondary actions (imports, exports, printing, tools) behind one I18n.t("helpers.application.more")
# button, so each section shows only its main action. The block gives the # button, so each section shows only its main action. The block gives the
# items: links or button_to forms with class "menu-item". # items: links or button_to forms with class "menu-item".
def more_menu(label = "More", small: false, &block) def more_menu(label = I18n.t("helpers.application.more"), small: false, &block)
tag.details(class: "relative", data: { controller: "dropdown", action: "click@window->dropdown#closeOutside keydown.esc@window->dropdown#close" }) do tag.details(class: "relative", data: { controller: "dropdown", action: "click@window->dropdown#closeOutside keydown.esc@window->dropdown#close" }) do
tag.summary(class: [ "btn-secondary list-none [&::-webkit-details-marker]:hidden", ("btn-sm" if small) ], title: "More actions") do tag.summary(class: [ "btn-secondary list-none [&::-webkit-details-marker]:hidden", ("btn-sm" if small) ], title: I18n.t("helpers.application.more_actions")) do
safe_join([ label, tag.span("▾", class: "text-xs", "aria-hidden": true) ], " ") safe_join([ label, tag.span("▾", class: "text-xs", "aria-hidden": true) ], " ")
end + tag.div(capture(&block), class: "menu") end + tag.div(capture(&block), class: "menu")
end end
@@ -29,7 +29,7 @@ module ApplicationHelper
def airworthiness_badge(status, large: false) def airworthiness_badge(status, large: false)
tag.span(status.label, class: [ "badge-#{AIRWORTHINESS_COLORS[status.status]}", ("text-sm px-3 py-1" if large) ], tag.span(status.label, class: [ "badge-#{AIRWORTHINESS_COLORS[status.status]}", ("text-sm px-3 py-1" if large) ],
title: Airworthiness::DISCLAIMER) title: Airworthiness.disclaimer)
end end
# Badge class (or text class) for one airworthiness issue. # Badge class (or text class) for one airworthiness issue.
@@ -39,22 +39,18 @@ module ApplicationHelper
{ "RED" => "text-red-700", "LIMITED" => "text-sky-700", "INFO" => "text-slate-600" }.fetch(issue.severity, "text-amber-700") { "RED" => "text-red-700", "LIMITED" => "text-sky-700", "INFO" => "text-slate-600" }.fetch(issue.severity, "text-amber-700")
end end
COMPLIANCE_BADGES = { COMPLIANCE_COLORS = { "compliant" => "green", "due_soon" => "orange", "overdue" => "red", "no_compliance" => "red",
"compliant" => [ "green", "Compliant" ], "due_soon" => [ "orange", "Due Soon" ], "never_completed" => "red", "conditional" => "gray", "not_applicable" => "gray" }.freeze
"overdue" => [ "red", "Overdue" ], "no_compliance" => [ "red", "No Record" ],
"never_completed" => [ "red", "Never Completed" ], "conditional" => [ "gray", "Conditional" ],
"not_applicable" => [ "gray", "N/A" ]
}.freeze
def compliance_badge(status) def compliance_badge(status)
color, text = COMPLIANCE_BADGES.fetch(status, [ "gray", status.to_s.humanize ]) color = COMPLIANCE_COLORS.fetch(status, "gray")
tag.span(text, class: "badge-#{color}") tag.span(t(status, scope: "helpers.application.compliance", default: status.to_s.humanize), class: "badge-#{color}")
end end
def life_badge(status) def life_badge(status)
return "" unless status return "" unless status
color, text = { overdue: [ "red", "Overdue" ], due_soon: [ "orange", "Due Soon" ], ok: [ "green", "OK" ] }[status] color = { overdue: "red", due_soon: "orange", ok: "green" }[status]
tag.span(text, class: "badge-#{color}") tag.span(t(status, scope: "helpers.application.life"), class: "badge-#{color}")
end end
def squawk_priority_badge(squawk) def squawk_priority_badge(squawk)
@@ -78,7 +74,7 @@ module ApplicationHelper
link_to ad.name, link[0], class: "link", target: "_blank", rel: "noopener noreferrer", title: link[1] link_to ad.name, link[0], class: "link", target: "_blank", rel: "noopener noreferrer", title: link[1]
end end
def delete_button(label, path, confirm: "Are you sure?", **opts) def delete_button(label, path, confirm: I18n.t("helpers.application.are_you_sure"), **opts)
button_to label, path, method: :delete, form: { data: { turbo_confirm: confirm }, class: "inline" }, button_to label, path, method: :delete, form: { data: { turbo_confirm: confirm }, class: "inline" },
class: opts[:class] || "btn-danger btn-sm" class: opts[:class] || "btn-danger btn-sm"
end end
+5 -5
View File
@@ -21,11 +21,11 @@ module FlightLogsHelper
[ "CHT", recording.cht_keys, "°F", CYLINDER_COLORS ], [ "CHT", recording.cht_keys, "°F", CYLINDER_COLORS ],
[ "EGT", recording.egt_keys, "°F", CYLINDER_COLORS ], [ "EGT", recording.egt_keys, "°F", CYLINDER_COLORS ],
[ "RPM", [ :rpm ], "rpm" ], [ "RPM", [ :rpm ], "rpm" ],
[ "Manifold pressure", [ :map ], "inHg" ], [ I18n.t("helpers.flight_logs.manifold_pressure"), [ :map ], "inHg" ],
[ "Fuel flow", [ :fuel_flow ], "gph" ], [ I18n.t("helpers.flight_logs.fuel_flow"), [ :fuel_flow ], "gph" ],
[ "Oil temp", [ :oil_t ], "°F" ], [ I18n.t("helpers.flight_logs.oil_temp"), [ :oil_t ], "°F" ],
[ "Oil pressure", [ :oil_p ], "psi" ], [ I18n.t("helpers.flight_logs.oil_pressure"), [ :oil_p ], "psi" ],
[ "Volts", [ :volts ], "V" ] [ I18n.t("helpers.flight_logs.volts"), [ :volts ], "V" ]
].filter_map do |title, keys, unit, colors| ].filter_map do |title, keys, unit, colors|
keys = keys.select { recording.channels.key?(_1) } keys = keys.select { recording.channels.key?(_1) }
{ title: title, keys: keys, unit: unit, colors: colors || [ CHART_COLOR ] } if keys.any? { title: title, keys: keys, unit: unit, colors: colors || [ CHART_COLOR ] } if keys.any?
+2 -2
View File
@@ -10,7 +10,7 @@ module OilAnalysesHelper
def oil_property(analysis, key) def oil_property(analysis, key)
value = analysis.property(key) or return "—" value = analysis.property(key) or return "—"
_, unit = OilAnalysis::PROPERTIES.fetch(key) unit = OilAnalysis::PROPERTY_UNITS.fetch(key)
number = number_with_precision(value, precision: 2, strip_insignificant_zeros: true) number = number_with_precision(value, precision: 2, strip_insignificant_zeros: true)
unit.present? ? "#{number} #{unit}" : number unit.present? ? "#{number} #{unit}" : number
end end
@@ -24,7 +24,7 @@ module OilAnalysesHelper
value = analysis.value(element) value = analysis.value(element)
flagged = analysis.flagged?(element) flagged = analysis.flagged?(element)
content = tag.span(ppm(value), class: [ "tabular-nums", ("font-semibold text-red-700" if flagged) ], content = tag.span(ppm(value), class: [ "tabular-nums", ("font-semibold text-red-700" if flagged) ],
title: ("Over #{OilAnalysis::FLAG_RATIO}× the lab average" if flagged)) title: (I18n.t("helpers.oil_analyses.over_the_lab_average", _: (OilAnalysis::FLAG_RATIO)) if flagged))
avg = analysis.average(element) avg = analysis.average(element)
avg ? safe_join([ content, tag.div("(#{ppm(avg)})", class: "text-xs text-slate-500 tabular-nums") ]) : content avg ? safe_join([ content, tag.div("(#{ppm(avg)})", class: "text-xs text-slate-500 tabular-nums") ]) : content
end end
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Airport code field with suggestions from the airport database. // Airport code field with suggestions from the airport database.
// <div data-controller="airport-autocomplete" data-airport-autocomplete-url-value="/airports/search?aircraft_id=1"> // <div data-controller="airport-autocomplete" data-airport-autocomplete-url-value="/airports/search?aircraft_id=1">
@@ -108,7 +109,7 @@ export default class extends Controller {
const code = this.inputTarget.value.trim().toUpperCase() const code = this.inputTarget.value.trim().toUpperCase()
const match = this.results.find((a) => a.code === code || (a.aka || []).includes(code)) const match = this.results.find((a) => a.code === code || (a.aka || []).includes(code))
if (match) this.setHint(this.describeAirport(match)) if (match) this.setHint(this.describeAirport(match))
else if (code.length >= 2 && code.length <= 4 && !code.includes(" ")) this.setHint("Not in the airport database", true) else if (code.length >= 2 && code.length <= 4 && !code.includes(" ")) this.setHint(t("airports.not_found"), true)
else this.setHint("") else this.setHint("")
} }
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { DirectUpload } from "@rails/activestorage" import { DirectUpload } from "@rails/activestorage"
// Bulk document upload. Picked files (or a whole folder) are listed with an // Bulk document upload. Picked files (or a whole folder) are listed with an
@@ -53,7 +54,7 @@ export default class extends Controller {
defaultName(item) { defaultName(item) {
const parts = item.path.split("/") const parts = item.path.split("/")
if (this.groupTarget.checked && parts.length > 1) return parts[parts.length - 2] if (this.groupTarget.checked && parts.length > 1) return parts[parts.length - 2]
return parts[parts.length - 1].replace(/\.[^.]+$/, "").replace(/_/g, " ").replace(/\s+/g, " ").trim() || "Untitled" return parts[parts.length - 1].replace(/\.[^.]+$/, "").replace(/_/g, " ").replace(/\s+/g, " ").trim() || t("bulk_upload.untitled")
} }
render() { render() {
@@ -72,7 +73,7 @@ export default class extends Controller {
name.type = "text" name.type = "text"
name.className = "input" name.className = "input"
name.value = item.name name.value = item.name
name.setAttribute("aria-label", `Document name for ${item.path}`) name.setAttribute("aria-label", t("bulk_upload.name_for", { path: item.path }))
name.disabled = this.uploading name.disabled = this.uploading
name.addEventListener("input", () => { item.name = name.value; item.custom = true; this.updateSummary() }) name.addEventListener("input", () => { item.name = name.value; item.custom = true; this.updateSummary() })
@@ -90,7 +91,7 @@ export default class extends Controller {
remove.type = "button" remove.type = "button"
remove.className = "btn-secondary btn-sm" remove.className = "btn-secondary btn-sm"
remove.textContent = "✕" remove.textContent = "✕"
remove.setAttribute("aria-label", `Remove ${item.path}`) remove.setAttribute("aria-label", t("bulk_upload.remove", { path: item.path }))
remove.disabled = this.uploading remove.disabled = this.uploading
remove.addEventListener("click", () => { this.items.splice(index, 1); this.render() }) remove.addEventListener("click", () => { this.items.splice(index, 1); this.render() })
@@ -109,9 +110,9 @@ export default class extends Controller {
updateSummary() { updateSummary() {
const files = this.items.length const files = this.items.length
const docs = new Set(this.items.map((item) => item.name.trim() || "Untitled")).size const docs = new Set(this.items.map((item) => item.name.trim() || t("bulk_upload.untitled"))).size
this.summaryTarget.textContent = `${files} ${files === 1 ? "file" : "files"} → ${docs} ${docs === 1 ? "document" : "documents"}` this.summaryTarget.textContent = `${files} ${files === 1 ? "file" : "files"} → ${docs} ${docs === 1 ? "document" : "documents"}`
this.submitTarget.textContent = files ? `Upload ${docs} ${docs === 1 ? "document" : "documents"}` : "Upload" this.submitTarget.textContent = files ? t("bulk_upload.upload_count", { count: docs }) : t("bulk_upload.upload")
} }
size(bytes) { size(bytes) {
@@ -124,9 +125,9 @@ export default class extends Controller {
if (this.ready) return if (this.ready) return
event.preventDefault() event.preventDefault()
if (this.uploading) return if (this.uploading) return
if (this.items.length === 0) return this.say("Choose some files to upload.") if (this.items.length === 0) return this.say(t("bulk_upload.choose_files"))
if (this.items.some((item) => item.file.size > this.maxBytesValue)) { if (this.items.some((item) => item.file.size > this.maxBytesValue)) {
return this.say("Remove the files marked in red first.") return this.say(t("bulk_upload.remove_red"))
} }
this.items.forEach((item) => { if (item.state === "error") item.state = "pending" }) this.items.forEach((item) => { if (item.state === "error") item.state = "pending" })
@@ -134,11 +135,11 @@ export default class extends Controller {
const queue = this.items.filter((item) => item.state === "pending") const queue = this.items.filter((item) => item.state === "pending")
const total = queue.length const total = queue.length
let finished = 0 let finished = 0
this.say(`Uploading 0 of ${total}…`) this.say(t("bulk_upload.uploading", { done: 0, total }))
const worker = async () => { const worker = async () => {
for (let item = queue.shift(); item; item = queue.shift()) { for (let item = queue.shift(); item; item = queue.shift()) {
await this.upload(item) await this.upload(item)
this.say(`Uploading ${++finished} of ${total}…`) this.say(t("bulk_upload.uploading", { done: ++finished, total }))
} }
} }
await Promise.all([ worker(), worker(), worker() ]) await Promise.all([ worker(), worker(), worker() ])
@@ -156,7 +157,7 @@ export default class extends Controller {
} }
this.uploading = false this.uploading = false
this.ready = true this.ready = true
this.say("Saving…") this.say(t("bulk_upload.saving"))
// When nothing was left to upload this all ran inside the click's submit // When nothing was left to upload this all ran inside the click's submit
// event, during which the browser ignores requestSubmit, so wait a tick. // event, during which the browser ignores requestSubmit, so wait a tick.
setTimeout(() => this.element.requestSubmit()) setTimeout(() => this.element.requestSubmit())
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Interactive viewer for engine monitor charts. Clicking a chart opens it large // Interactive viewer for engine monitor charts. Clicking a chart opens it large
// with higher-resolution data (fetched once, on first open): a crosshair shows // with higher-resolution data (fetched once, on first open): a crosshair shows
@@ -35,7 +36,7 @@ export default class extends Controller {
this.render() this.render()
} catch (error) { } catch (error) {
this.statusTarget.hidden = false this.statusTarget.hidden = false
this.statusTarget.textContent = `Couldn't load the engine data (${error.message}).` this.statusTarget.textContent = t("engine.load_failed", { message: error.message })
} }
} }
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Fills a new logbook entry from a template: the wording, and when the // Fills a new logbook entry from a template: the wording, and when the
// template sets them, the entry type, the logbook (which also picks the // template sets them, the entry type, the logbook (which also picks the
@@ -9,7 +10,7 @@ export default class extends Controller {
apply() { apply() {
const option = this.templateTarget.selectedOptions[0] const option = this.templateTarget.selectedOptions[0]
if (!option?.dataset.text) return if (!option?.dataset.text) return
if (this.textTarget.value.trim() && !confirm("Replace the entry text with this template?")) return if (this.textTarget.value.trim() && !confirm(t("entry_template.confirm"))) return
const { text, entryType, logType, certificate } = option.dataset const { text, entryType, logType, certificate } = option.dataset
this.textTarget.value = text this.textTarget.value = text
if (entryType && this.hasEntryTypeTarget) this.entryTypeTarget.value = entryType if (entryType && this.hasEntryTypeTarget) this.entryTypeTarget.value = entryType
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Fills a textarea with suggested text (asks before replacing what's there). // Fills a textarea with suggested text (asks before replacing what's there).
export default class extends Controller { export default class extends Controller {
@@ -8,7 +9,7 @@ export default class extends Controller {
insert(event) { insert(event) {
event.preventDefault() event.preventDefault()
const field = this.fieldTarget const field = this.fieldTarget
if (field.value.trim() && !confirm("Replace what's in the box with the suggested text?")) return if (field.value.trim() && !confirm(t("insert_text.confirm"))) return
field.value = this.textValue field.value = this.textValue
field.focus() field.focus()
field.setSelectionRange(0, 0) field.setSelectionRange(0, 0)
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Write / Preview tabs for a Markdown textarea. The preview is rendered by the // Write / Preview tabs for a Markdown textarea. The preview is rendered by the
// server, with the same Markdown rules and sanitizing as the saved note. // server, with the same Markdown rules and sanitizing as the saved note.
@@ -17,7 +18,7 @@ export default class extends Controller {
async preview() { async preview() {
this.select(true) this.select(true)
this.outputTarget.textContent = "Loading preview…" this.outputTarget.textContent = t("markdown.loading")
const token = document.querySelector("meta[name=csrf-token]")?.content const token = document.querySelector("meta[name=csrf-token]")?.content
try { try {
const response = await fetch(this.urlValue, { const response = await fetch(this.urlValue, {
@@ -29,7 +30,7 @@ export default class extends Controller {
if (!response.ok) throw new Error(`HTTP ${response.status}`) if (!response.ok) throw new Error(`HTTP ${response.status}`)
this.outputTarget.innerHTML = await response.text() // sanitized server-side this.outputTarget.innerHTML = await response.text() // sanitized server-side
} catch (error) { } catch (error) {
this.outputTarget.textContent = `Couldn't load the preview (${error.message}).` this.outputTarget.textContent = t("markdown.load_failed", { message: error.message })
} }
} }
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { nextDue, describeDue } from "next_due" import { nextDue, describeDue } from "next_due"
// Live next-due preview (and prefill of an AD's next-due tach reading) from // Live next-due preview (and prefill of an AD's next-due tach reading) from
@@ -40,12 +41,12 @@ export default class extends Controller {
if (!this.hasPreviewTarget) return if (!this.hasPreviewTarget) return
const rule = this.currentRule const rule = this.currentRule
let text let text
if (this.isPermanent) text = "Permanent compliance or not applicable: never due again." if (this.isPermanent) text = t("next_due.permanent")
else if (!this.ruleTarget.value) text = "" else if (!this.ruleTarget.value) text = ""
else if (!rule) text = "One-time: no recurring due date." else if (!rule) text = t("next_due.one_time")
else { else {
if (this.hasDueHoursTarget && this.manual) due = { ...due, hours: parseFloat(this.dueHoursTarget.value) } 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." text = describeDue(due) ? t("next_due.next_due", { due: describeDue(due) }) : t("next_due.enter")
} }
this.previewTarget.textContent = text this.previewTarget.textContent = text
this.previewTarget.hidden = text === "" this.previewTarget.hidden = text === ""
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue, formFields, newKey } from "controllers/offline_queue" import { queue, formFields, newKey } from "controllers/offline_queue"
// The Log Flight form: with no connection, the flight is kept on this device // The Log Flight form: with no connection, the flight is kept on this device
@@ -48,7 +49,7 @@ export default class extends Controller {
try { try {
await queue.add(item) await queue.add(item)
} catch (_) { } catch (_) {
this.say("No connection, and this browser can't store the flight. Write it down and log it when you're back online.") this.say(t("offline.no_storage"))
return return
} }
this.prefillFrom(item) this.prefillFrom(item)
@@ -56,7 +57,7 @@ export default class extends Controller {
this.keyTarget.value = newKey() this.keyTarget.value = newKey()
this.pending = null this.pending = null
window.scrollTo({ top: 0 }) window.scrollTo({ top: 0 })
this.say("No connection: flight saved on this device. It's sent automatically when you're back online. Log the next leg below, or close the app.") this.say(t("offline.saved_on_device"))
document.dispatchEvent(new CustomEvent("offline-queue:changed")) document.dispatchEvent(new CustomEvent("offline-queue:changed"))
} }
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
import { queue } from "controllers/offline_queue" import { queue } from "controllers/offline_queue"
// On every page: sends flights logged offline once there's a connection, and // On every page: sends flights logged offline once there's a connection, and
@@ -29,7 +30,7 @@ export default class extends Controller {
for (const item of items.filter((i) => !i.error)) { for (const item of items.filter((i) => !i.error)) {
const result = await this.send(item) const result = await this.send(item)
if (result === "sent") { await queue.remove(item.id); sent++ } if (result === "sent") { await queue.remove(item.id); sent++ }
else if (result === "signin") { this.show("Sign in to send the flights logged offline."); return } else if (result === "signin") { this.show(t("offline.sign_in")); return }
else if (result === "offline") break else if (result === "offline") break
else { item.error = result; await queue.put(item) } else { item.error = result; await queue.put(item) }
} }
@@ -52,15 +53,15 @@ export default class extends Controller {
const html = await response.text() const html = await response.text()
const doc = new DOMParser().parseFromString(html, "text/html") const doc = new DOMParser().parseFromString(html, "text/html")
const message = [ ...doc.querySelectorAll("[role=alert], .field-error") ].map((e) => e.textContent.trim()).filter(Boolean).join(" ") const message = [ ...doc.querySelectorAll("[role=alert], .field-error") ].map((e) => e.textContent.trim()).filter(Boolean).join(" ")
return message || `Not accepted (${response.status}).` return message || t("offline.not_accepted", { status: response.status })
} }
status(items, sent = 0) { status(items, sent = 0) {
const failed = items.filter((i) => i.error) const failed = items.filter((i) => i.error)
const waiting = items.length - failed.length const waiting = items.length - failed.length
const parts = [] const parts = []
if (sent) parts.push(`Sent ${sent} flight${sent > 1 ? "s" : ""} logged offline.`) if (sent) parts.push(t("offline.sent", { count: sent }))
if (waiting) parts.push(`${waiting} flight${waiting > 1 ? "s" : ""} logged offline waiting for a connection.`) if (waiting) parts.push(t("offline.waiting", { count: waiting }))
this.show(parts.join(" "), failed) this.show(parts.join(" "), failed)
} }
@@ -72,7 +73,7 @@ export default class extends Controller {
const date = (item.fields.find(([ n ]) => n === "flight_log[date]") || [])[1] || "" const date = (item.fields.find(([ n ]) => n === "flight_log[date]") || [])[1] || ""
const row = document.createElement("p") const row = document.createElement("p")
row.textContent = `${item.tail} flight ${date} logged offline wasn't accepted: ${item.error} ` row.textContent = `${item.tail} flight ${date} logged offline wasn't accepted: ${item.error} `
const discard = Object.assign(document.createElement("button"), { type: "button", textContent: "Discard", className: "btn-secondary btn-sm ml-1" }) const discard = Object.assign(document.createElement("button"), { type: "button", textContent: t("offline.discard"), className: "btn-secondary btn-sm ml-1" })
discard.addEventListener("click", async () => { await queue.remove(item.id); this.sync() }) discard.addEventListener("click", async () => { await queue.remove(item.id); this.sync() })
row.append(discard) row.append(discard)
banner.append(row) banner.append(row)
@@ -1,7 +1,7 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
const CHOICES = ["system", "light", "dark"] const CHOICES = ["system", "light", "dark"]
const LABELS = { system: "System", light: "Light", dark: "Dark" }
// Light / dark / follow-the-OS theme toggle. The choice is kept in // Light / dark / follow-the-OS theme toggle. The choice is kept in
// localStorage; the layout's inline script applies it before first paint. // localStorage; the layout's inline script applies it before first paint.
@@ -40,7 +40,7 @@ export default class extends Controller {
this.element.querySelectorAll("[data-theme-icon]").forEach((icon) => { this.element.querySelectorAll("[data-theme-icon]").forEach((icon) => {
icon.classList.toggle("hidden", icon.dataset.themeIcon !== choice) icon.classList.toggle("hidden", icon.dataset.themeIcon !== choice)
}) })
const label = `Theme: ${LABELS[choice]}${choice === "system" ? ` (${theme})` : ""}` const label = choice === "system" ? t("theme.system", { theme: t(`theme.${theme}`) }) : t("theme.label", { choice: t(`theme.${choice}`) })
this.element.title = label this.element.title = label
this.element.setAttribute("aria-label", label) this.element.setAttribute("aria-label", label)
if (changed) window.dispatchEvent(new CustomEvent("theme:change", { detail: { theme } })) if (changed) window.dispatchEvent(new CustomEvent("theme:change", { detail: { theme } }))
@@ -1,4 +1,5 @@
import { Controller } from "@hotwired/stimulus" import { Controller } from "@hotwired/stimulus"
import { t } from "i18n"
// Loading calculator: takeoff and landing weight and CG from the empty // Loading calculator: takeoff and landing weight and CG from the empty
// weight & moment plus each station's load, checked against max gross weight, // weight & moment plus each station's load, checked against max gross weight,
@@ -42,19 +43,19 @@ export default class extends Controller {
this.show("landing", landing) this.show("landing", landing)
if (!loaded) { if (!loaded) {
this.messagesTarget.replaceChildren(Object.assign(document.createElement("li"), { className: "text-slate-500", textContent: "Enter the loading to check weight and CG." })) this.messagesTarget.replaceChildren(Object.assign(document.createElement("li"), { className: "text-slate-500", textContent: t("wb.enter_loading") }))
this.draw(takeoff, landing) this.draw(takeoff, landing)
return return
} }
if (this.maxGrossValue && takeoff.weight > this.maxGrossValue) { if (this.maxGrossValue && takeoff.weight > this.maxGrossValue) {
messages.push([ "bad", `Takeoff weight is ${(takeoff.weight - this.maxGrossValue).toFixed(1)} lb over the maximum of ${this.maxGrossValue} lb.` ]) messages.push([ "bad", t("wb.over_gross", { over: (takeoff.weight - this.maxGrossValue).toFixed(1), max: this.maxGrossValue }) ])
} }
if (this.envelopeValue.length >= 3) { if (this.envelopeValue.length >= 3) {
for (const [ name, point ] of [ [ "Takeoff", takeoff ], [ "Landing", landing ] ]) { for (const [ name, point ] of [ [ t("wb.takeoff"), takeoff ], [ t("wb.landing"), landing ] ]) {
if (!this.inside(point)) messages.push([ "bad", `${name} CG ${point.cg.toFixed(2)} in at ${point.weight.toFixed(0)} lb is outside the envelope.` ]) if (!this.inside(point)) messages.push([ "bad", t("wb.outside", { name, cg: point.cg.toFixed(2), weight: point.weight.toFixed(0) }) ])
} }
} }
if (!messages.length) messages.push([ "ok", "Within the limits entered here." ]) if (!messages.length) messages.push([ "ok", t("wb.within_limits") ])
this.messagesTarget.replaceChildren(...messages.map(([ kind, text ]) => { this.messagesTarget.replaceChildren(...messages.map(([ kind, text ]) => {
const li = document.createElement("li") const li = document.createElement("li")
li.className = kind === "ok" ? "text-emerald-700" : "text-red-700" li.className = kind === "ok" ? "text-emerald-700" : "text-red-700"
+22
View File
@@ -0,0 +1,22 @@
// Strings for the page's scripts: the "js" keys of config/locales, which the
// layout puts in <script type="application/json" id="i18n">.
// t("bulk_upload.uploading", { done: 1, total: 4 })
// t("offline.sent", { count: 2 }) // one/other plurals pick by count
let strings
function load() {
if (!strings) {
try { strings = JSON.parse(document.getElementById("i18n")?.textContent || "{}") } catch { strings = {} }
}
return strings
}
export function t(key, vars = {}) {
let value = key.split(".").reduce((node, part) => node?.[part], load())
if (value && typeof value === "object") value = value[vars.count === 1 ? "one" : "other"]
if (typeof value !== "string") return key
return value.replace(/%\{(\w+)\}/g, (_, name) => vars[name] ?? "")
}
// The page's language, for number and date formatting.
export const locale = () => document.documentElement.lang || "en"
+5 -3
View File
@@ -1,3 +1,5 @@
import { t, locale } from "i18n"
// Next-due math, mirroring Compliance.next_due in app/services/compliance.rb: // 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 // 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). // to the hours at completion. Dates are "YYYY-MM-DD" strings (no timezones).
@@ -24,11 +26,11 @@ export function nextDue(rule, dateStr, hours) {
export function describeDue(due) { export function describeDue(due) {
const parts = [] const parts = []
if (due.hours != null) parts.push(`${due.hours.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 })} tach`) if (due.hours != null) parts.push(t("next_due.tach", { hours: due.hours.toLocaleString(locale(), { minimumFractionDigits: 1, maximumFractionDigits: 1 }) }))
if (due.date) { if (due.date) {
const [y, mo, d] = due.date.split("-").map(Number) 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" })) parts.push(new Date(y, mo - 1, d).toLocaleDateString(locale(), { month: "short", day: "numeric", year: "numeric" }))
} }
if (parts.length === 0) return "" if (parts.length === 0) return ""
return parts.length > 1 ? `${parts.join(" or ")}, whichever comes first` : parts[0] return parts.length > 1 ? t("next_due.either", { first: parts[0], second: parts[1] }) : parts[0]
} }
+15 -14
View File
@@ -33,11 +33,11 @@ class LogbookTranscriptionJob < ApplicationJob
readable = pages.each_with_index.filter_map do |attachment, index| readable = pages.each_with_index.filter_map do |attachment, index|
type = attachment.blob.content_type type = attachment.blob.content_type
if type == "application/pdf" if type == "application/pdf"
next warn("Page #{index + 1} (#{attachment.filename}) is over #{LogbookTranscriber::MAX_PDF_BYTES / 1.megabyte} MB, too large to transcribe.") if attachment.blob.byte_size > LogbookTranscriber::MAX_PDF_BYTES next warn(I18n.t("jobs.logbook_transcription.pdf_too_large", page: index + 1, file: attachment.filename, mb: LogbookTranscriber::MAX_PDF_BYTES / 1.megabyte)) if attachment.blob.byte_size > LogbookTranscriber::MAX_PDF_BYTES
elsif !LogbookTranscriber::IMAGE_TYPES.include?(type) elsif !LogbookTranscriber::IMAGE_TYPES.include?(type)
next warn("Page #{index + 1} (#{attachment.filename}) isn't a JPEG, PNG, GIF, WebP or PDF, so it wasn't transcribed.") next warn(I18n.t("jobs.logbook_transcription.wrong_type", page: index + 1, file: attachment.filename))
elsif attachment.blob.byte_size > LogbookTranscriber::MAX_IMAGE_BYTES elsif attachment.blob.byte_size > LogbookTranscriber::MAX_IMAGE_BYTES
next warn("Page #{index + 1} (#{attachment.filename}) is over 5 MB, too large to transcribe. Scan it at a lower resolution.") next warn(I18n.t("jobs.logbook_transcription.image_too_large", page: index + 1, file: attachment.filename))
end end
{ attachment: attachment, number: index + 1, pdf: type == "application/pdf" } { attachment: attachment, number: index + 1, pdf: type == "application/pdf" }
end end
@@ -50,10 +50,10 @@ class LogbookTranscriptionJob < ApplicationJob
def transcribe_pdf(page) def transcribe_pdf(page)
result = @transcriber.transcribe([ payload(page) ]) result = @transcriber.transcribe([ payload(page) ])
note_skipped(result, ->(i) { "#{page[:attachment].filename} page #{i + 1}" }) note_skipped(result, ->(i) { I18n.t("jobs.logbook_transcription.file_page", file: page[:attachment].filename, page: i + 1) })
result.entries.sort_by { _1["page_start"].to_i }.each { save(_1, page[:number]) } result.entries.sort_by { _1["page_start"].to_i }.each { save(_1, page[:number]) }
rescue LogbookTranscriber::Error => e rescue LogbookTranscriber::Error => e
warn("#{page[:attachment].filename} wasn't transcribed: #{e.message}.") warn(I18n.t("jobs.logbook_transcription.file_failed", file: page[:attachment].filename, message: e.message))
ensure ensure
tick(1) tick(1)
end end
@@ -81,12 +81,12 @@ class LogbookTranscriptionJob < ApplicationJob
rescue LogbookTranscriber::Error => e rescue LogbookTranscriber::Error => e
held.each { save(_1[:entry], _1[:number]) } # keep what the previous batch read held.each { save(_1[:entry], _1[:number]) } # keep what the previous batch read
held = [] held = []
pages = batch.size == 1 ? "Page #{batch.first[:number]} wasn't" : "Pages #{batch.first[:number]}–#{batch.last[:number]} weren't" warn(batch.size == 1 ? I18n.t("jobs.logbook_transcription.page_failed", page: batch.first[:number], message: e.message)
warn("#{pages} transcribed: #{e.message}.") : I18n.t("jobs.logbook_transcription.pages_failed", first: batch.first[:number], last: batch.last[:number], message: e.message))
tick(n.zero? ? batch.size : batch.size - 1) tick(n.zero? ? batch.size : batch.size - 1)
next next
end end
note_skipped(result, ->(i) { "page #{batch[i]&.dig(:number) || '?'}" }) note_skipped(result, ->(i) { I18n.t("jobs.logbook_transcription.page", page: batch[i]&.dig(:number) || "?") })
entries = result.entries.sort_by { _1["page_start"].to_i } entries = result.entries.sort_by { _1["page_start"].to_i }
held = [] held = []
@@ -109,10 +109,11 @@ class LogbookTranscriptionJob < ApplicationJob
def save(entry, page_number) def save(entry, page_number)
date = parse_date(entry["date"]) date = parse_date(entry["date"])
text = entry["text"].to_s.strip.presence || "[no text read]" text = entry["text"].to_s.strip.presence || I18n.t("jobs.logbook_transcription.no_text")
unless date unless date
text = "[date unreadable] #{text}" text = "#{I18n.t('jobs.logbook_transcription.date_unreadable')} #{text}"
warn("An entry on page #{page_number} had no readable date#{@last_date ? "; it was given the previous entry's date (#{@last_date})" : ' and was dated today'}. Please check it.") warn(@last_date ? I18n.t("jobs.logbook_transcription.no_date_previous", page: page_number, date: @last_date)
: I18n.t("jobs.logbook_transcription.no_date_today", page: page_number))
end end
date ||= @last_date || Date.current date ||= @last_date || Date.current
@last_date = date @last_date = date
@@ -128,14 +129,14 @@ class LogbookTranscriptionJob < ApplicationJob
verified: false, transcription_confidence: (entry["confidence"] if %w[high medium low].include?(entry["confidence"])) verified: false, transcription_confidence: (entry["confidence"] if %w[high medium low].include?(entry["confidence"]))
) )
@import.increment!(:entries_created) @import.increment!(:entries_created)
warn("The #{date} entry on page #{page_number} was hard to read. Please check it against the scan.") if entry["confidence"] == "low" warn(I18n.t("jobs.logbook_transcription.hard_to_read", date: date, page: page_number)) if entry["confidence"] == "low"
end end
def note_skipped(result, label) def note_skipped(result, label)
forms = result.non_logbook_pages.map { label.(_1) } forms = result.non_logbook_pages.map { label.(_1) }
unreadable = result.unparseable_pages.map { label.(_1) } unreadable = result.unparseable_pages.map { label.(_1) }
warn("Not logbook entries (forms, tags…), so nothing was transcribed from: #{forms.uniq.to_sentence}.") if forms.any? warn(I18n.t("jobs.logbook_transcription.not_entries", pages: forms.uniq.to_sentence)) if forms.any?
warn("Too hard to read: #{unreadable.uniq.to_sentence}.") if unreadable.any? warn(I18n.t("jobs.logbook_transcription.unreadable", pages: unreadable.uniq.to_sentence)) if unreadable.any?
end end
def parse_date(value) def parse_date(value)
+3 -3
View File
@@ -2,7 +2,7 @@ class AdminMailer < ApplicationMailer
def records_alert(user, backup, check) def records_alert(user, backup, check)
@backup = backup @backup = backup
@check = check @check = check
mail subject: "Records check needs attention", to: user.email_address mail subject: t(".subject"), to: user.email_address
end end
def offsite_alert(user, run) def offsite_alert(user, run)
@@ -10,9 +10,9 @@ class AdminMailer < ApplicationMailer
mail subject: run.kind == "restore_test" ? "Off-site restore test failed" : "Off-site backup failed", to: user.email_address mail subject: run.kind == "restore_test" ? "Off-site restore test failed" : "Off-site backup failed", to: user.email_address
end end
def test_email(user, via: "from Admin → About") def test_email(user, via: t(".via_about"))
@user = user @user = user
@via = via @via = via
mail subject: "Test email from Simple Aircraft Manager", to: user.email_address mail subject: t(".subject"), to: user.email_address
end end
end end
+1 -1
View File
@@ -1,6 +1,6 @@
class PasswordsMailer < ApplicationMailer class PasswordsMailer < ApplicationMailer
def reset(user) def reset(user)
@user = user @user = user
mail subject: "Reset your password", to: user.email_address mail subject: t(".subject"), to: user.email_address
end end
end end
+2 -2
View File
@@ -31,8 +31,8 @@ class ReminderMailer < ApplicationMailer
@audit_due = self.class.audit_due_for?(user) && AuditRun.next_due @audit_due = self.class.audit_due_for?(user) && AuditRun.next_due
@drs_due = self.class.drs_due_for(user) @drs_due = self.class.drs_due_for(user)
overdue = @items.sum { |_, issues, _| issues.count { _1.severity.in?(%w[RED LIMITED]) } } overdue = @items.sum { |_, issues, _| issues.count { _1.severity.in?(%w[RED LIMITED]) } }
subject = overdue.positive? ? "#{overdue} #{'item'.pluralize(overdue)} overdue" : "Maintenance coming due" subject = overdue.positive? ? t(".subject_overdue", count: overdue) : t(".subject_due")
subject = (@certificates.any? ? "Certificate expiring" : (@audit_due ? "Records audit due" : "Refresh the AD list from DRS")) if @items.empty? subject = t(@certificates.any? ? ".subject_certificate" : (@audit_due ? ".subject_audit" : ".subject_drs")) if @items.empty?
mail subject: [ subject, @items.map { _1.first.tail_number }.to_sentence.presence ].compact.join(": "), to: user.email_address mail subject: [ subject, @items.map { _1.first.tail_number }.to_sentence.presence ].compact.join(": "), to: user.email_address
end end
end end
+2 -2
View File
@@ -2,11 +2,11 @@ class SessionsMailer < ApplicationMailer
def sign_in_link(user) def sign_in_link(user)
@user = user @user = user
@token = user.generate_token_for(:email_sign_in) @token = user.generate_token_for(:email_sign_in)
mail subject: "Your sign-in link", to: user.email_address mail subject: t(".subject"), to: user.email_address
end end
def locked(user) def locked(user)
@user = user @user = user
mail subject: "Your account was locked after failed sign-ins", to: user.email_address mail subject: t(".subject"), to: user.email_address
end end
end end
+1 -1
View File
@@ -3,6 +3,6 @@ class SignatureMailer < ApplicationMailer
def signed(signature) def signed(signature)
@signature = signature @signature = signature
@entry = signature.logbook_entry @entry = signature.logbook_entry
mail subject: "You signed a logbook entry for #{@entry.aircraft.tail_number}", to: signature.signer_email mail subject: t(".subject", tail_number: @entry.aircraft.tail_number), to: signature.signer_email
end end
end end
+1 -1
View File
@@ -3,6 +3,6 @@ class SigningInvitationMailer < ApplicationMailer
@invitation = invitation @invitation = invitation
@entry = invitation.logbook_entry @entry = invitation.logbook_entry
@url = invited_signing_url(token) @url = invited_signing_url(token)
mail subject: "Please sign a logbook entry for #{@entry.aircraft.tail_number}", to: invitation.email mail subject: t(".subject", tail_number: @entry.aircraft.tail_number), to: invitation.email
end end
end end
+3 -9
View File
@@ -1,12 +1,7 @@
class AdCompliance < ApplicationRecord class AdCompliance < ApplicationRecord
include Versioned include Versioned
# Method of compliance, recorded per 91.417(a)(2)(v). # Method of compliance, recorded per 91.417(a)(2)(v).
METHODS = { METHODS = LabelSet.new("ad_compliance.methods", %w[inspection terminating amoc not_applicable])
"inspection" => "Inspection",
"terminating" => "Terminating action (no further action)",
"amoc" => "Alternative method of compliance (AMOC)",
"not_applicable" => "Not applicable to this aircraft"
}.freeze
belongs_to :airworthiness_directive belongs_to :airworthiness_directive
belongs_to :aircraft, optional: true belongs_to :aircraft, optional: true
@@ -18,7 +13,7 @@ class AdCompliance < ApplicationRecord
validates :compliance_method, inclusion: { in: METHODS.keys } validates :compliance_method, inclusion: { in: METHODS.keys }
before_validation :apply_method before_validation :apply_method
before_validation :fill_revision before_validation :fill_revision
validate { errors.add(:base, "Must belong to an aircraft or component") unless aircraft_id || component_id } validate { errors.add(:base, :needs_owner) unless aircraft_id || component_id }
validate :next_due_is_a_future_reading validate :next_due_is_a_future_reading
before_validation :fill_next_due, if: -> { next_due_at_time.to_d.zero? } before_validation :fill_next_due, if: -> { next_due_at_time.to_d.zero? }
@@ -66,7 +61,6 @@ class AdCompliance < ApplicationRecord
return if closed? || due <= 0 return if closed? || due <= 0
base = aircraft_hours_at_compliance || aircraft&.current_hours base = aircraft_hours_at_compliance || aircraft&.current_hours
return unless base && due <= base return unless base && due <= base
errors.add(:next_due_at_time, "must be a #{aircraft&.time_basis || 'tach'} reading after the compliance hours (#{base}). " \ errors.add(:next_due_at_time, :not_future_reading, meter: Aircraft::TIME_BASES[aircraft&.time_basis || "tach"].downcase, base: base, example: base + 100)
"For “every 100 hours” enter #{base + 100}, not 100")
end end
end end
+4 -9
View File
@@ -1,10 +1,5 @@
class Aircraft < ApplicationRecord class Aircraft < ApplicationRecord
STATUSES = { STATUSES = LabelSet.new("aircraft.statuses", %w[AVAILABLE MX GROUND UNAVAILABLE])
"AVAILABLE" => "Available",
"MX" => "In Maintenance",
"GROUND" => "Grounded",
"UNAVAILABLE" => "Unavailable"
}.freeze
has_one_attached :picture has_one_attached :picture
@@ -33,12 +28,12 @@ class Aircraft < ApplicationRecord
# Which clock counts as time in service for maintenance (14 CFR 1.1 defines # Which clock counts as time in service for maintenance (14 CFR 1.1 defines
# it as takeoff to landing; many owners use tach, some Hobbs). # it as takeoff to landing; many owners use tach, some Hobbs).
TIME_BASES = { "tach" => "Tach", "hobbs" => "Hobbs" }.freeze TIME_BASES = LabelSet.new("aircraft.time_bases", %w[tach hobbs])
validates :tail_number, presence: true validates :tail_number, presence: true
validates :time_basis, inclusion: { in: TIME_BASES.keys } validates :time_basis, inclusion: { in: TIME_BASES.keys }
validates :status, inclusion: { in: STATUSES.keys } validates :status, inclusion: { in: STATUSES.keys }
validates :icao_type, format: { with: /\A[A-Z0-9]{1,4}\z/, message: "must be an ICAO type designator like C150" }, allow_blank: true validates :icao_type, format: { with: /\A[A-Z0-9]{1,4}\z/, message: :icao_type }, allow_blank: true
normalizes :icao_type, with: ->(t) { t.strip.upcase.presence } normalizes :icao_type, with: ->(t) { t.strip.upcase.presence }
validate :picture_is_image validate :picture_is_image
@@ -86,7 +81,7 @@ class Aircraft < ApplicationRecord
def picture_is_image def picture_is_image
if picture.attached? && !picture.content_type.to_s.start_with?("image/") if picture.attached? && !picture.content_type.to_s.start_with?("image/")
errors.add(:picture, "must be an image") errors.add(:picture, :not_image)
end end
end end
end end
+1 -7
View File
@@ -1,11 +1,5 @@
class AircraftEvent < ApplicationRecord class AircraftEvent < ApplicationRecord
CATEGORIES = { CATEGORIES = LabelSet.new("aircraft_event.categories", %w[hours flight component squawk note oil fuel logbook ad inspection document aircraft role major_record oil_analysis])
"hours" => "Hours Update", "flight" => "Flight", "component" => "Component",
"squawk" => "Squawk", "note" => "Note", "oil" => "Oil", "fuel" => "Fuel",
"logbook" => "Logbook", "ad" => "Airworthiness Directive", "inspection" => "Inspection",
"document" => "Document", "aircraft" => "Aircraft", "role" => "Role",
"major_record" => "Major Repair/Alteration", "oil_analysis" => "Oil Analysis"
}.freeze
belongs_to :aircraft belongs_to :aircraft
belongs_to :user, optional: true belongs_to :user, optional: true
+1 -1
View File
@@ -14,6 +14,6 @@ class AircraftImport < ApplicationRecord
# "12 components, 140 logbook entries, …" for whatever was imported. # "12 components, 140 logbook entries, …" for whatever was imported.
def summary def summary
counts.select { |_, n| n.to_i.positive? }.map { |key, n| "#{n} #{key.to_s.humanize(capitalize: false).then { n == 1 ? _1.singularize : _1 }}" }.to_sentence counts.select { |_, n| n.to_i.positive? }.map { |key, n| I18n.t(key, scope: "models.aircraft_import.counts", count: n.to_i) }.to_sentence
end end
end end
+1 -1
View File
@@ -1,5 +1,5 @@
class AircraftRole < ApplicationRecord class AircraftRole < ApplicationRecord
ROLES = { "owner" => "Owner", "pilot" => "Pilot" }.freeze ROLES = LabelSet.new("aircraft_role.roles", %w[owner pilot])
belongs_to :aircraft belongs_to :aircraft
belongs_to :user belongs_to :user
+1 -1
View File
@@ -4,7 +4,7 @@ class Airport < ApplicationRecord
KINDS = %w[small_airport medium_airport large_airport seaplane_base heliport balloonport closed].freeze KINDS = %w[small_airport medium_airport large_airport seaplane_base heliport balloonport closed].freeze
KIND_RANK = { "large_airport" => 0, "medium_airport" => 1, "small_airport" => 2, "seaplane_base" => 3, KIND_RANK = { "large_airport" => 0, "medium_airport" => 1, "small_airport" => 2, "seaplane_base" => 3,
"heliport" => 4, "balloonport" => 5, "closed" => 9 }.freeze "heliport" => 4, "balloonport" => 5, "closed" => 9 }.freeze
KIND_LABELS = { "seaplane_base" => "seaplane base", "heliport" => "heliport", "balloonport" => "balloonport", "closed" => "closed" }.freeze KIND_LABELS = LabelSet.new("airport.kinds", %w[seaplane_base heliport balloonport closed])
# Custom airports (admin-added) use their identifier as the AirTrail code. # Custom airports (admin-added) use their identifier as the AirTrail code.
before_validation(if: :custom?) { self.airtrail_code = ident } before_validation(if: :custom?) { self.airtrail_code = ident }
+1 -1
View File
@@ -12,6 +12,6 @@ class AirportUpdate < ApplicationRecord
def in_progress? = status.in?(%w[queued running]) def in_progress? = status.in?(%w[queued running])
def summary def summary
"#{created_count} added, #{updated_count} updated, #{removed_count} removed" I18n.t("models.airport_update.summary", added: created_count, updated: updated_count, removed: removed_count)
end end
end end
+4 -7
View File
@@ -1,10 +1,7 @@
class AirworthinessDirective < ApplicationRecord class AirworthinessDirective < ApplicationRecord
COMPLIANCE_TYPES = { "standard" => "Standard", "conditional" => "Conditional" }.freeze COMPLIANCE_TYPES = LabelSet.new("airworthiness_directive.compliance_types", %w[standard conditional])
BULLETIN_TYPES = { BULLETIN_TYPES = LabelSet.new("airworthiness_directive.bulletin_types", %w[ad saib sb alert other])
"ad" => "Airworthiness Directive", "saib" => "Special Airworthiness Information Bulletin", BULLETIN_LABELS = LabelSet.new("airworthiness_directive.bulletin_labels", %w[ad saib sb alert other])
"sb" => "Service Bulletin", "alert" => "Airworthiness Alert", "other" => "Other"
}.freeze
BULLETIN_LABELS = { "ad" => "AD", "saib" => "SAIB", "sb" => "SB", "alert" => "Alert", "other" => "Bulletin" }.freeze
include CalendarInterval include CalendarInterval
calendar_interval :recurring, days: :recurring_days, months: :recurring_months, blank: 0 calendar_interval :recurring, days: :recurring_days, months: :recurring_months, blank: 0
@@ -36,7 +33,7 @@ class AirworthinessDirective < ApplicationRecord
# exports carry one per AD; it can also be pasted in). DRS links use an # exports carry one per AD; it can also be pasted in). DRS links use an
# internal document id, so they can't be derived from the AD number. # internal document id, so they can't be derived from the AD number.
def reference_link def reference_link
[ document_url, "View AD" ] if document_url.present? [ document_url, I18n.t("models.airworthiness_directive.view") ] if document_url.present?
end end
def conditional? = compliance_type == "conditional" def conditional? = compliance_type == "conditional"
+5 -5
View File
@@ -1,9 +1,9 @@
class Component < ApplicationRecord class Component < ApplicationRecord
include Versioned include Versioned
include CalendarInterval include CalendarInterval
STATUSES = { "SPARE" => "Spare Part", "IN-USE" => "In Service", "DISPOSED" => "Disposed" }.freeze STATUSES = LabelSet.new("component.statuses", %w[SPARE IN-USE DISPOSED])
# What "since overhaul" counts from, and how logbooks abbreviate it. # What "since overhaul" counts from, and how logbooks abbreviate it.
OVERHAUL_KINDS = { "major" => "Major overhaul", "factory_overhaul" => "Factory overhaul", "factory_new" => "Factory new or rebuilt (zero time)" }.freeze OVERHAUL_KINDS = LabelSet.new("component.overhaul_kinds", %w[major factory_overhaul factory_new])
OVERHAUL_ABBREVIATIONS = { "major" => "SMOH", "factory_overhaul" => "SFOH", "factory_new" => "SNEW" }.freeze OVERHAUL_ABBREVIATIONS = { "major" => "SMOH", "factory_overhaul" => "SFOH", "factory_new" => "SNEW" }.freeze
calendar_interval :replacement, days: :replacement_days, months: :replacement_months calendar_interval :replacement, days: :replacement_days, months: :replacement_months
@@ -41,7 +41,7 @@ class Component < ApplicationRecord
# SMOH / SFOH / SNEW when the overhaul type is known; engines and # SMOH / SFOH / SNEW when the overhaul type is known; engines and
# propellers otherwise "TSO", and other parts (filters…) "since service". # propellers otherwise "TSO", and other parts (filters…) "since service".
def since_overhaul_abbreviation def since_overhaul_abbreviation
OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind) { engine? || propeller? ? "TSO" : "Since service" } OVERHAUL_ABBREVIATIONS.fetch(overhaul_kind) { engine? || propeller? ? "TSO" : I18n.t("models.component.since_service") }
end end
# Its sub-components, and theirs. # Its sub-components, and theirs.
@@ -132,7 +132,7 @@ class Component < ApplicationRecord
def parent_on_same_aircraft def parent_on_same_aircraft
return unless parent_component return unless parent_component
errors.add(:parent_component, "can't be itself") if parent_component_id == id && id errors.add(:parent_component, :itself) if parent_component_id == id && id
errors.add(:parent_component, "must be on the same aircraft") if parent_component.aircraft_id != aircraft_id errors.add(:parent_component, :other_aircraft) if parent_component.aircraft_id != aircraft_id
end end
end end
+3 -3
View File
@@ -9,7 +9,7 @@
module CalendarInterval module CalendarInterval
extend ActiveSupport::Concern extend ActiveSupport::Concern
UNITS = { "days" => "days", "months" => "months", "years" => "years" }.freeze UNITS = LabelSet.new("calendar_interval.units", %w[days months years])
# [count, unit] for display, from the stored columns. # [count, unit] for display, from the stored columns.
def self.split(days, months) def self.split(days, months)
@@ -22,7 +22,7 @@ module CalendarInterval
def self.label(days, months) def self.label(days, months)
count, unit = split(days, months) count, unit = split(days, months)
count && "#{count} #{count == 1 ? unit.singularize : unit}" count && I18n.t("models.calendar_interval.counts.#{unit}", count: count)
end end
class_methods do class_methods do
@@ -70,7 +70,7 @@ module CalendarInterval
next unless instance_variable_defined?(every_ivar) next unless instance_variable_defined?(every_ivar)
raw = instance_variable_get(every_ivar).to_s.strip raw = instance_variable_get(every_ivar).to_s.strip
next if raw.empty? || Integer(raw, 10, exception: false)&.positive? next if raw.empty? || Integer(raw, 10, exception: false)&.positive?
errors.add(:"#{name}_every", "must be a whole number more than 0") errors.add(:"#{name}_every", :positive_whole_number)
end end
end end
end end
+2 -2
View File
@@ -18,10 +18,10 @@ module UploadValidation
Array(public_send(name).attachments).each do |att| Array(public_send(name).attachments).each do |att|
next unless att.blob next unless att.blob
unless ALLOWED_CONTENT_TYPES.include?(att.blob.content_type) unless ALLOWED_CONTENT_TYPES.include?(att.blob.content_type)
errors.add(name, "#{att.filename} is not an allowed file type") errors.add(name, :file_type, file: att.filename.to_s)
end end
limit = UploadValidation.max_size limit = UploadValidation.max_size
errors.add(name, "#{att.filename} is over the #{limit / 1.megabyte} MB upload limit") if att.blob.byte_size > limit errors.add(name, :file_size, file: att.filename.to_s, limit: limit / 1.megabyte) if att.blob.byte_size > limit
end end
end end
end end
+1 -1
View File
@@ -1,5 +1,5 @@
class ConsumableRecord < ApplicationRecord class ConsumableRecord < ApplicationRecord
TYPES = { "oil" => "Oil", "fuel" => "Fuel" }.freeze TYPES = LabelSet.new("consumable_record.types", %w[oil fuel])
UNITS = { "oil" => "qt", "fuel" => "gal" }.freeze UNITS = { "oil" => "qt", "fuel" => "gal" }.freeze
belongs_to :aircraft belongs_to :aircraft
+1 -7
View File
@@ -2,13 +2,7 @@ class Document < ApplicationRecord
include Versioned include Versioned
include UploadValidation include UploadValidation
TYPES = { TYPES = LabelSet.new("document.types", %w[LOG ALTER REPORT ESTIMATE DISC INVOICE AIRCRAFT REGISTRATION AIRWORTHINESS_CERT INSURANCE RADIO OTHER])
"LOG" => "Logbook", "ALTER" => "Alteration Record", "REPORT" => "Report",
"ESTIMATE" => "Estimate", "DISC" => "Discrepancy List", "INVOICE" => "Receipt / Invoice",
"AIRCRAFT" => "Aircraft Record", "REGISTRATION" => "Registration Certificate",
"AIRWORTHINESS_CERT" => "Airworthiness Certificate", "INSURANCE" => "Insurance Policy",
"RADIO" => "Radio Station License", "OTHER" => "Other"
}.freeze
# An expired registration means the aircraft may not be flown (14 CFR # An expired registration means the aircraft may not be flown (14 CFR
# 91.203(a)(2)); renewal takes a while, so warn earlier. # 91.203(a)(2)); renewal takes a while, so warn earlier.
GROUNDING_EXPIRY_TYPES = %w[REGISTRATION].freeze GROUNDING_EXPIRY_TYPES = %w[REGISTRATION].freeze
+1 -1
View File
@@ -1,5 +1,5 @@
class DocumentCollection < ApplicationRecord class DocumentCollection < ApplicationRecord
VISIBILITIES = { "private" => "Private", "status" => "All share links", "maintenance" => "Maintenance only" }.freeze VISIBILITIES = LabelSet.new("document_collection.visibilities", %w[private status maintenance])
belongs_to :aircraft belongs_to :aircraft
has_many :documents, dependent: :destroy has_many :documents, dependent: :destroy
Loaded 100 of 313 files, more files were not shown because too many files have changed in this diff. Show more