Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

List each IANA time zone once in a searchable select (#4755)

GFRa44752e6aa66
diff --git a/app/helpers/languages_helper.rb b/app/helpers/languages_helper.rb
index ba9b3fc5bf..644e6292db 100644
--- a/app/helpers/languages_helper.rb
+++ b/app/helpers/languages_helper.rb
@@ -395,12 +395,43 @@ module LanguagesHelper
.sort_by { |label, locale| label }
end
- def timezone_options
- ActiveSupport::TimeZone.all
- .sort_by { |tz| [ tz.utc_offset, tz.name ] }
- .map do |tz|
- name = tz.name.split(" - ").first.gsub(" (US & Canada)", "")
- [ "(#{tz.formatted_offset}) #{name}", tz.tzinfo.identifier ]
- end
+ # tzdata renamed these zones but Rails still maps to the old spelling.
+ # Hosts that ship the legacy names as plain zone files would otherwise list
+ # both, and TZInfo cannot tell they are the same zone.
+ RENAMED_TIMEZONES = { "Europe/Kiev" => "Europe/Kyiv", "Asia/Rangoon" => "Asia/Yangon" }.freeze
+
+ # One option per IANA zone, since Family#timezone stores the identifier and
+ # several of Rails' friendly names share one (e.g. Moscow and St. Petersburg).
+ # A saved identifier outside the list (e.g. an old spelling) is added, in
+ # place of its renamed zone, so it stays selected.
+ def timezone_options(current = nil)
+ rows = LanguagesHelper.timezone_option_rows
+ zone = ActiveSupport::TimeZone[current] if current.present?
+
+ if zone && rows.none? { |row| row[:identifier] == current }
+ rows = (rows.reject { |row| row[:identifier] == RENAMED_TIMEZONES[current] } << LanguagesHelper.timezone_option_row(current, zone))
+ .sort_by { |row| [ row[:offset], row[:identifier] ] }
+ end
+
+ rows.map { |row| [ row[:label], row[:identifier] ] }
+ end
+
+ # Labels use each zone's standard (base) offset, which daylight saving time
+ # does not change, so the list only changes with tzdata and is built once per process.
+ def self.timezone_option_rows
+ @timezone_option_rows ||= begin
+ identifiers = TZInfo::Timezone.all_country_zone_identifiers | ActiveSupport::TimeZone.all.map { |tz| tz.tzinfo.identifier }
+ identifiers -= RENAMED_TIMEZONES.select { |_, renamed| identifiers.include?(renamed) }.keys
+
+ identifiers
+ .filter_map { |identifier| (zone = ActiveSupport::TimeZone[identifier]) && timezone_option_row(identifier, zone) }
+ .sort_by { |row| [ row[:offset], row[:identifier] ] }
+ .freeze
+ end
+ end
+
+ def self.timezone_option_row(identifier, zone)
+ offset = zone.utc_offset
+ { identifier: identifier, offset: offset, label: "(#{ActiveSupport::TimeZone.seconds_to_utc_offset(offset)}) #{identifier.tr("_", " ")}" }
end
end
diff --git a/app/javascript/controllers/list_filter_controller.js b/app/javascript/controllers/list_filter_controller.js
index 880f2209df..c2b33206fa 100644
--- a/app/javascript/controllers/list_filter_controller.js
+++ b/app/javascript/controllers/list_filter_controller.js
@@ -89,10 +89,13 @@ export default class extends Controller {
// modifier letters (e.g. the Hawaiian ʻokina) — so a query of just one of
// those would normalize to "", and "".includes() matches everything,
// silently showing every row instead of filtering.
+ // Underscores read as spaces, so an identifier typed as "America/New_York"
+ // finds its label "America/New York".
normalize(value) {
return value
.normalize("NFD")
.replace(/\p{Mark}/gu, "")
+ .replaceAll("_", " ")
.toLowerCase();
}
diff --git a/app/models/family.rb b/app/models/family.rb
index b2fe1f6026..2ecd7519d6 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -258,6 +258,14 @@ class Family < ApplicationRecord
validates :auto_generate_transaction_names, inclusion: { in: [ true, false ] }
validates :investment_contributions_as_spending, inclusion: { in: [ true, false ] }
validates :categories_locked, inclusion: { in: [ true, false ] }
+ # The searchable timezone select submits "" while no zone is saved yet;
+ # store nil so provider date parsing keeps its default instead of raising.
+ # Rails' friendly names (e.g. "Pacific Time (US & Canada)") are stored as
+ # their IANA identifier, the value the timezone select offers.
+ normalizes :timezone, with: ->(timezone) {
+ timezone = timezone.strip
+ ActiveSupport::TimeZone::MAPPING[timezone] || timezone.presence
+ }
validate :timezone_must_be_a_known_zone, if: :timezone_changed?
validate :currency_must_be_known, if: :currency_changed?
diff --git a/app/views/settings/preferences/show.html.erb b/app/views/settings/preferences/show.html.erb
index 03372def8c..a144c6dbae 100644
--- a/app/views/settings/preferences/show.html.erb
+++ b/app/views/settings/preferences/show.html.erb
@@ -8,9 +8,11 @@
{ label: t(".language"), include_blank: t(".language_auto") },
{ data: { auto_submit_form_target: "auto" } } %>
<%= form.fields_for :family do |family_form| %>
- <%= family_form.select :timezone,
- timezone_options,
- { label: t(".timezone") },
+ <%= family_form.collection_select :timezone,
+ timezone_options(family_form.object.timezone),
+ :last,
+ :first,
+ { label: t(".timezone"), searchable: true },
{ data: { auto_submit_form_target: "auto" } } %>
<%= family_form.select :date_format,
Family::DATE_FORMATS,
diff --git a/test/controllers/settings/preferences_controller_test.rb b/test/controllers/settings/preferences_controller_test.rb
index 66b6f997d9..a8938cd93a 100644
--- a/test/controllers/settings/preferences_controller_test.rb
+++ b/test/controllers/settings/preferences_controller_test.rb
@@ -11,6 +11,18 @@ class Settings::PreferencesControllerTest < ActionDispatch::IntegrationTest
assert_response :success
end
+ test "shows the saved timezone instead of another city sharing its zone" do
+ users(:family_admin).family.update!(timezone: "Europe/Moscow")
+
+ get settings_preferences_url
+
+ assert_response :success
+ assert_select "input[type=hidden][name='user[family_attributes][timezone]'][value='Europe/Moscow']"
+ assert_select "button#timezone_trigger", text: "(+03:00) Europe/Moscow"
+ assert_select "[role=option][data-value='Europe/Moscow']", count: 1
+ assert_select "[role=option][aria-selected=true][data-value='Europe/Moscow']", count: 1
+ end
+
test "admins see the investing-as-spending toggle" do
get settings_preferences_url
diff --git a/test/helpers/languages_helper_test.rb b/test/helpers/languages_helper_test.rb
new file mode 100644
index 0000000000..219a8448fe
--- /dev/null
+++ b/test/helpers/languages_helper_test.rb
@@ -0,0 +1,81 @@
+require "test_helper"
+
+class LanguagesHelperTest < ActionView::TestCase
+ # The zone list is cached per process with the offsets current when it was
+ # built. Another test may have built it under travel_to, when some zones had
+ # a different standard offset, so rebuild it at the real time.
+ setup do
+ LanguagesHelper.instance_variable_set(:@timezone_option_rows, nil)
+ end
+
+ test "timezone options have unique values so the saved zone stays selected" do
+ values = timezone_options.map(&:last)
+
+ assert_equal values.uniq, values
+ end
+
+ test "timezone options list renamed zones only under their current name" do
+ values = timezone_options.map(&:last)
+
+ LanguagesHelper::RENAMED_TIMEZONES.each do |old_name, new_name|
+ assert_includes values, new_name
+ assert_not_includes values, old_name
+ end
+ end
+
+ test "timezone options list each IANA zone with its identifier" do
+ moscow = timezone_options.select { |_, value| value == "Europe/Moscow" }
+
+ assert_equal [ [ "(+03:00) Europe/Moscow", "Europe/Moscow" ] ], moscow
+ assert_includes timezone_options.map(&:last), "America/Argentina/Cordoba"
+ end
+
+ test "timezone options cover every zone offered by Rails" do
+ rails_identifiers = ActiveSupport::TimeZone.all.map { |tz| tz.tzinfo.identifier }
+ renamed = rails_identifiers.map { |identifier| LanguagesHelper::RENAMED_TIMEZONES.fetch(identifier, identifier) }
+
+ assert_empty renamed - timezone_options.map(&:last)
+ end
+
+ test "timezone options are sorted by offset and use readable labels" do
+ offsets = timezone_options.map { |_, value| ActiveSupport::TimeZone[value].utc_offset }
+
+ assert_equal offsets.sort, offsets
+ assert_includes timezone_options, [ "(-05:00) America/New York", "America/New_York" ]
+ end
+
+ test "timezone labels show the standard offset during daylight saving time too" do
+ travel_to Time.utc(2024, 7, 1, 12) do
+ LanguagesHelper.instance_variable_set(:@timezone_option_rows, nil)
+
+ assert_includes timezone_options, [ "(-05:00) America/New York", "America/New_York" ]
+ assert_includes timezone_options, [ "(+01:00) Europe/Berlin", "Europe/Berlin" ]
+ end
+ end
+
+ test "timezone options show a saved old spelling in place of its renamed zone" do
+ base = timezone_options
+ # Hosts without tzdata's legacy names cannot resolve "Europe/Kiev".
+ ActiveSupport::TimeZone.stubs(:[]).with("Europe/Kiev").returns(stub(utc_offset: 2.hours.to_i))
+
+ options = timezone_options("Europe/Kiev")
+
+ assert_includes options, [ "(+02:00) Europe/Kiev", "Europe/Kiev" ]
+ assert_not_includes options.map(&:last), "Europe/Kyiv"
+ assert_equal base.size, options.size
+ end
+
+ test "timezone options add any other saved zone outside the list" do
+ base = timezone_options
+ ActiveSupport::TimeZone.stubs(:[]).with("US/Eastern").returns(stub(utc_offset: -5.hours.to_i))
+
+ options = timezone_options("US/Eastern")
+
+ assert_includes options, [ "(-05:00) US/Eastern", "US/Eastern" ]
+ assert_equal base.size + 1, options.size
+ end
+
+ test "timezone options ignore an unknown saved zone" do
+ assert_equal timezone_options, timezone_options("Not/AZone")
+ end
+end
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index 2046674d8e..1133549ec1 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -593,6 +593,20 @@ class FamilyTest < ActiveSupport::TestCase
assert family.valid?
end
+ test "stores an empty timezone from the settings form as nil" do
+ family = families(:dylan_family)
+ family.update!(timezone: "")
+
+ assert_nil family.reload.timezone
+ end
+
+ test "stores a Rails zone name as its IANA identifier" do
+ family = families(:dylan_family)
+ family.update!(timezone: " Pacific Time (US & Canada) ")
+
+ assert_equal "America/Los_Angeles", family.reload.timezone
+ end
+
test "does not re-validate an existing invalid timezone when saving unrelated changes" do
family = families(:dylan_family)
# Bypasses validations, simulating data that predates this validation --
diff --git a/test/system/settings/preferences_test.rb b/test/system/settings/preferences_test.rb
new file mode 100644
index 0000000000..223c1f01dc
--- /dev/null
+++ b/test/system/settings/preferences_test.rb
@@ -0,0 +1,27 @@
+require "application_system_test_case"
+
+class Settings::PreferencesTest < ApplicationSystemTestCase
+ setup do
+ sign_in @user = users(:family_admin)
+ @user.family.update!(timezone: "America/New_York")
+ end
+
+ test "finds a time zone by its identifier, saves it and keeps it after reload" do
+ visit settings_preferences_path
+
+ trigger = find("button#timezone_trigger")
+ container = trigger.ancestor("div.relative", match: :first)
+ trigger.click
+ container.find("input[type='search']", visible: true).set("Asia/Ho_Chi")
+ container.find("[role='listbox'] [role='option'][data-value='Asia/Ho_Chi_Minh']", visible: true).click
+
+ assert_text "(+07:00) Asia/Ho Chi Minh"
+ # The form auto-submits; wait for the save before reloading the page.
+ page.document.synchronize do
+ raise Capybara::ExpectationNotMet unless @user.family.reload.timezone == "Asia/Ho_Chi_Minh"
+ end
+
+ visit settings_preferences_path
+ assert_selector "button#timezone_trigger", text: "(+07:00) Asia/Ho Chi Minh"
+ end
+end