diff --git a/.env.example b/.env.example index b0565ec..8ffb0a9 100644 --- a/.env.example +++ b/.env.example @@ -8,6 +8,10 @@ SECRET_KEY_BASE=change-me # The host name people use to reach the app (used in email links). APP_HOST=aircraft.example.com + +# The installation's time zone (scheduled jobs run on its clock; people see +# their own zone, from Profile or their device). Default UTC. +# TZ=America/New_York # true: the app redirects to HTTPS and sets secure cookies (use behind a TLS # proxy such as Traefik, Caddy or Cloudflare Tunnel). false: plain HTTP on a LAN. FORCE_SSL=true diff --git a/README.md b/README.md index b087d72..db0dd07 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,7 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai | `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. | | `VAPID_PUBLIC_KEY`, `VAPID_PRIVATE_KEY` | Optional. The key pair that signs push notifications (generate with `bin/rails runner 'k = WebPush.generate_key; puts k.public_key, k.private_key'`). Without them the app generates a pair once and keeps it in `storage/vapid_keys.json`. Changing it turns notifications off on every device until they're turned on again. | +| `TZ` | Optional. The installation's time zone, Docker's standard setting, e.g. `America/New_York`: scheduled jobs (nightly backup, the 7am overdue check, Monday reminders) run on its clock, and it's used for anyone whose device zone isn't known yet. Each person sees times in their own zone (Profile, or their device). Default `UTC`. | | `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. | | `LOGBOOK_AI_MODEL`, `LOGBOOK_AI_EFFORT` | Optional. The Claude model and effort used for transcription (default `claude-opus-5-5`, `high`). | diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 992eed4..f840134 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,6 +1,7 @@ class ApplicationController < ActionController::Base default_form_builder AppFormBuilder include Authentication + include TimeZones allow_browser versions: :modern prepend_before_action :redirect_to_setup diff --git a/app/controllers/concerns/time_zones.rb b/app/controllers/concerns/time_zones.rb new file mode 100644 index 0000000..6ad28c3 --- /dev/null +++ b/app/controllers/concerns/time_zones.rb @@ -0,0 +1,31 @@ +# Each request runs in the viewer's time zone: the one chosen in Profile, else +# the device's (a "tz" cookie the page sets from the browser), else the +# installation's default (TZ). That decides how times show and +# what "today" is (e.g. a new flight's date). Signatures, the record history +# and exports keep exact UTC timestamps. +module TimeZones + extend ActiveSupport::Concern + + included do + around_action :use_time_zone + helper_method :device_time_zone, :device_time_zone_label + end + + private + + def use_time_zone(&) + Time.use_zone(Current.user&.time_zone.presence || device_time_zone || Time.zone_default, &) + end + + # "(GMT-08:00) Pacific Time (US & Canada)" for America/Los_Angeles. + def device_time_zone_label + return unless (zone = ActiveSupport::TimeZone[device_time_zone.to_s]) + (ActiveSupport::TimeZone.all.find { _1.tzinfo.identifier == zone.tzinfo.identifier } || zone).to_s + end + + # The browser's zone, when it's one we know. + def device_time_zone + name = cookies[:tz].to_s.first(64) + ActiveSupport::TimeZone[name] && name if name.present? + end +end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index 141d616..0fb3c99 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -7,7 +7,7 @@ class ProfilesController < ApplicationController # left open somewhere can't be turned into a takeover of the account. def update @user = current_user - attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation, :reminder_emails) + attrs = params.require(:user).permit(:name, :email_address, :password, :password_confirmation, :reminder_emails, :time_zone) attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? new_email = User.normalize_value_for(:email_address, attrs[:email_address].to_s) if attrs.key?(:email_address) sensitive = (new_email && new_email != @user.email_address) || attrs.key?(:password) diff --git a/app/javascript/application.js b/app/javascript/application.js index d69b738..7232da6 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -42,6 +42,15 @@ window.addEventListener("beforeinstallprompt", (event) => { document.dispatchEvent(new CustomEvent("install:available")) }) +// The device's time zone, so times show in it and "today" is the local date +// (unless a zone is chosen in Profile). +try { + const zone = Intl.DateTimeFormat().resolvedOptions().timeZone + if (zone && !document.cookie.split("; ").includes(`tz=${encodeURIComponent(zone)}`)) { + document.cookie = `tz=${encodeURIComponent(zone)}; path=/; max-age=31536000; samesite=lax` + } +} catch (_) { /* no Intl */ } + // Label each table cell with its column header, so phone CSS can show rows as // cards ("Status: In Service"). Skips tables marked .table-keep. function labelTableCells(root = document) { diff --git a/app/mailers/reminder_mailer.rb b/app/mailers/reminder_mailer.rb index bae6396..0839031 100644 --- a/app/mailers/reminder_mailer.rb +++ b/app/mailers/reminder_mailer.rb @@ -25,6 +25,12 @@ class ReminderMailer < ApplicationMailer end def weekly(user) + Time.use_zone(user.time_zone.presence || Time.zone_default) { weekly_in_zone(user) } + end + + private + + def weekly_in_zone(user) @user = user @items = self.class.items_for(user) @certificates = self.class.expiring_certificates_for(user) diff --git a/app/models/system_info.rb b/app/models/system_info.rb index 042397c..cf7f199 100644 --- a/app/models/system_info.rb +++ b/app/models/system_info.rb @@ -52,7 +52,7 @@ class SystemInfo "SQLite" => SQLite3::SQLITE_VERSION, "Bundler" => Bundler::VERSION, t(:environment) => Rails.env, - t(:time_zone) => Time.zone.name + t(:time_zone) => Time.zone_default.name } end diff --git a/app/models/user.rb b/app/models/user.rb index 1ee4711..14b75ee 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -3,6 +3,9 @@ class User < ApplicationRecord has_many :sessions, dependent: :destroy has_many :aircraft_roles, dependent: :destroy has_many :push_subscriptions, dependent: :delete_all + + normalizes :time_zone, with: ->(z) { z.strip.presence } + validates :time_zone, inclusion: { in: ->(_) { ActiveSupport::TimeZone.all.map(&:name) } }, allow_nil: true has_many :aircraft, through: :aircraft_roles has_one :air_trail_connection, dependent: :destroy has_many :certificates, -> { ordered }, class_name: "UserCertificate", dependent: :destroy diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb index 313c5ea..f6080d5 100644 --- a/app/views/profiles/edit.html.erb +++ b/app/views/profiles/edit.html.erb @@ -5,6 +5,13 @@ <%= f.field :email_address, as: :email, label: t(".email") %> <%= f.field :reminder_emails, as: :checkbox, label: t(".weekly_maintenance_reminders"), hint: t(MailSettings.configured? ? ".a_monday_email_about_overdue" : ".reminders_once_email_set_up") %> +
+ <%= f.label :time_zone, t(".time_zone"), class: "label" %> + <%= f.time_zone_select :time_zone, ActiveSupport::TimeZone.us_zones, + { include_blank: t(".time_zone_automatic", zone: device_time_zone_label || t(".time_zone_unknown")) }, + class: "input" %> +

<%= t(".time_zone_hint", now: fmt_time(Time.current)) %>

+
<%= f.field :password, as: :password, label: t(".new_password"), hint: t(".leave_blank_to_keep_your", min: User::PASSWORD_MIN), autocomplete: "new-password" %> <%= f.field :password_confirmation, as: :password, label: t(".confirm_new_password"), autocomplete: "new-password" %>
diff --git a/config/application.rb b/config/application.rb index c104bb1..b9f4e3a 100644 --- a/config/application.rb +++ b/config/application.rb @@ -36,7 +36,11 @@ module SimpleAircraftManager # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # - # config.time_zone = "Central Time (US & Canada)" + # The installation's time zone, from Docker's standard TZ (e.g. + # "America/New_York"): for scheduled jobs and for anyone whose device zone + # isn't known yet. Each person's own zone comes from Profile or their + # device (TimeZones). Not a zone name (unset, or e.g. ":/etc/localtime"): UTC. + config.time_zone = ActiveSupport::TimeZone[ENV["TZ"].to_s] ? ENV["TZ"] : "UTC" # config.eager_load_paths << Rails.root.join("extras") # Small resized copies of photos (squawk thumbnails), made with libvips. diff --git a/config/locales/en.yml b/config/locales/en.yml index 03beeb7..e9874b1 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -654,7 +654,7 @@ en: 'yes': 'yes' 'no': 'no' environment: Environment - time_zone: Time zone + time_zone: Default time zone sso: Single sign-on sso_only: "%{provider}, password sign-in off" not_configured: not configured @@ -3008,6 +3008,10 @@ en: notifications_on: Turn on notifications_off: Turn off notifications_test: Send a test + time_zone: Time zone + time_zone_automatic: 'Automatic: this device (%{zone})' + time_zone_unknown: not known yet + time_zone_hint: 'How times show and what “today” is, for example a new flight''s date. Now: %{now}. Signatures and the record history always show UTC.' record_versions: index: record_history: "%{tail_number} Record history" diff --git a/config/recurring.yml b/config/recurring.yml index f5292d8..a96d1ae 100644 --- a/config/recurring.yml +++ b/config/recurring.yml @@ -9,28 +9,30 @@ # priority: 2 # schedule: at 5am every day +# Times are in the installation's time zone (TZ, default UTC). +<% zone = ActiveSupport::TimeZone[ENV["TZ"].to_s]&.tzinfo&.identifier || "UTC" %> production: clear_solid_queue_finished_jobs: command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" schedule: every hour at minute 12 purge_abandoned_uploads: command: "ActiveStorage::Blob.unattached.where(created_at: ..2.days.ago).find_each(&:purge_later)" - schedule: every day at 4am + schedule: every day at 4am <%= zone %> dedupe_storage: command: "ActiveStorage::Blob.service.try(:sweep)" - schedule: every day at 4:30am + schedule: every day at 4:30am <%= zone %> weekly_reminders: class: WeeklyReminderJob - schedule: every monday at 12pm + schedule: every monday at 12pm <%= zone %> ad_watch: class: AdWatchJob - schedule: every sunday at 10am + schedule: every sunday at 10am <%= zone %> document_text: class: DocumentTextJob - schedule: every day at 2am + schedule: every day at 2am <%= zone %> overdue_notifications: class: OverdueNotificationJob - schedule: every day at 7am + schedule: every day at 7am <%= zone %> records_integrity: class: RecordsIntegrityJob - schedule: every day at 3:30am + schedule: every day at 3:30am <%= zone %> diff --git a/db/migrate/20261114010000_add_time_zone_to_users.rb b/db/migrate/20261114010000_add_time_zone_to_users.rb new file mode 100644 index 0000000..ac71a20 --- /dev/null +++ b/db/migrate/20261114010000_add_time_zone_to_users.rb @@ -0,0 +1,6 @@ +class AddTimeZoneToUsers < ActiveRecord::Migration[8.1] + def change + # The user's time zone for showing times; blank follows their device. + add_column :users, :time_zone, :string + end +end diff --git a/db/schema.rb b/db/schema.rb index ef879da..b78c23b 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2026_11_13_010000) do +ActiveRecord::Schema[8.1].define(version: 2026_11_14_010000) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -837,6 +837,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_13_010000) do t.integer "otp_last_used_at" t.json "otp_recovery_codes" t.string "calendar_token" + t.string "time_zone" t.index ["calendar_token"], name: "index_users_on_calendar_token", unique: true t.index ["email_address"], name: "index_users_on_email_address", unique: true t.index ["sso_uid"], name: "index_users_on_sso_uid", unique: true diff --git a/docs/guide/profile.md b/docs/guide/profile.md index 7b429f3..88cfdc2 100644 --- a/docs/guide/profile.md +++ b/docs/guide/profile.md @@ -8,6 +8,8 @@ Change your name, email and password. Leave the password blank to keep the curre **Weekly maintenance reminders**: on Mondays the app emails owners about anything overdue or coming due on their aircraft, and certificates about to expire. Untick it to stop them. (Emails need the administrator to have set up email.) +**Time zone** is *Automatic* by default: times show in your device's zone, and "today" (for example a new flight's date) is your local date. Choose a zone to use it on every device. Signatures and the record history always show UTC. + ## Two-factor sign-in **Set up** adds a code from an authenticator app on your phone (Google Authenticator, Microsoft Authenticator, 1Password, Authy…) to password and emailed-link sign-in, so a stolen password alone can't get in. It also asks for the code when you sign a logbook entry with your password. diff --git a/test/integration/time_zones_test.rb b/test/integration/time_zones_test.rb new file mode 100644 index 0000000..dfc5579 --- /dev/null +++ b/test/integration/time_zones_test.rb @@ -0,0 +1,63 @@ +require "test_helper" + +# Times show in the viewer's zone (Profile, else their device, else the +# installation default), and "today" is their local date. +class TimeZonesTest < ActionDispatch::IntegrationTest + setup do + @user = create_user("pilot@example.com") + @a = create_aircraft(pilot: @user) + end + + # 02:00 UTC on Nov 15 is still Nov 14 in the US. + def at_night_utc(&) = travel_to(Time.utc(2026, 11, 15, 2, 0), &) + + def new_flight_date + get new_aircraft_flight_log_path(@a) + css_select("input[name='flight_log[date]']").first["value"] + end + + test "a zone chosen in Profile sets today's date and how times show" do + @user.update!(time_zone: "Eastern Time (US & Canada)") + at_night_utc do + sign_in @user + assert_equal "2026-11-14", new_flight_date + get edit_profile_path + assert_select "select[name='user[time_zone]'] option[selected][value='Eastern Time (US & Canada)']" + assert_match "Nov 14, 2026 21:00", response.body # the profile's "Now:" + end + end + + test "without a choice, the device's zone is used; without that, the default" do + at_night_utc do + sign_in @user + assert_equal "2026-11-15", new_flight_date # UTC: device not known yet + cookies[:tz] = "America/Los_Angeles" + assert_equal "2026-11-14", new_flight_date + get edit_profile_path + assert_select "select[name='user[time_zone]'] option[value='']", /Automatic: this device \(.*Pacific/ + cookies[:tz] = "Not/AZone" + assert_equal "2026-11-15", new_flight_date # unknown names are ignored + end + end + + test "the time zone is saved from Profile, and unknown ones are refused" do + sign_in @user + patch profile_path, params: { user: { time_zone: "Alaska" } } + assert_equal "Alaska", @user.reload.time_zone + patch profile_path, params: { user: { time_zone: "Mars/Olympus" } } + assert_equal "Alaska", @user.reload.time_zone + patch profile_path, params: { user: { time_zone: "" } } + assert_nil @user.reload.time_zone # back to automatic + end + + test "the weekly email works out dates in the recipient's zone" do + @user.update!(time_zone: "Hawaii") + zone = nil + original = ReminderMailer.method(:items_for) + ReminderMailer.define_singleton_method(:items_for) { |_| (zone = Time.zone.name) && [] } + at_night_utc { ReminderMailer.weekly(@user).message } + assert_equal "Hawaii", zone + ensure + ReminderMailer.define_singleton_method(:items_for, original) if original + end +end