The personal finance app for everyone (by everyone)
Ruby
Namespace User section preferences by page (#4763)
jaysbeekay1351a895fccf
diff --git a/app/javascript/controllers/reports_section_controller.js b/app/javascript/controllers/reports_section_controller.jsindex 76aedf0064..c89265063f 100644--- a/app/javascript/controllers/reports_section_controller.js+++ b/app/javascript/controllers/reports_section_controller.js@@ -1,10 +1,18 @@import { Controller } from "@hotwired/stimulus";+// The collapse control for every page built on the Reports section+// framework. It keeps the Reports name because renaming it would touch every+// Reports data attribute for no behaviour change.export default class extends Controller {static targets = ["content", "chevron", "button"];+ // `url` and `preferenceKey` default to the Reports literals, so the Reports+ // page, which passes neither, posts to its own endpoint under its own key.+ // Another page passes both.static values = {sectionKey: String,collapsed: Boolean,+ url: { type: String, default: "/reports/update_preferences" },+ preferenceKey: { type: String, default: "reports" },};connect() {@@ -55,7 +63,7 @@ export default class extends Controller {async savePreference(collapsed) {const preferences = {- reports_collapsed_sections: {+ [`${this.preferenceKeyValue}_collapsed_sections`]: {[this.sectionKeyValue]: collapsed,},};@@ -70,7 +78,7 @@ export default class extends Controller {}try {- const response = await fetch("/reports/update_preferences", {+ const response = await fetch(this.urlValue, {method: "PATCH",headers: {"Content-Type": "application/json",diff --git a/app/models/user.rb b/app/models/user.rbindex 24101358a3..189b166ab6 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -753,16 +753,35 @@ class User < ApplicationRecordendend- # Reports preferences management- def reports_section_collapsed?(section_key)- preferences&.dig("reports_collapsed_sections", section_key) == true- end-- def reports_section_order- preferences&.[]("reports_section_order") || default_reports_section_order- end+ # Section preferences for the pages built on the Reports section+ # framework. Each page is a namespace; its order lives under+ # "<namespace>_section_order" and its collapsed set under+ # "<namespace>_collapsed_sections", so two pages never read or write each+ # other's keys. Reports' original keys are the "reports" namespace, so+ # nothing already stored changes meaning.+ SECTION_NAMESPACES = %w[reports].freeze++ def section_order(namespace)+ prefix = section_namespace!(namespace)+ preferences&.[]("#{prefix}_section_order") || default_section_order(prefix)+ end++ def section_collapsed?(namespace, section_key)+ prefix = section_namespace!(namespace)+ preferences&.dig("#{prefix}_collapsed_sections", section_key) == true+ end++ # `order` replaces the namespace's order; `collapsed` merges into the+ # namespace's collapsed set (one key per toggle, so quick successive+ # toggles keep each other's state). The namespace decides which keys are+ # written: a caller cannot reach another page's keys through this method.+ def update_section_preferences(namespace, order: nil, collapsed: nil)+ prefix = section_namespace!(namespace)+ prefs = {}+ prefs["#{prefix}_section_order"] = order unless order.nil?+ prefs["#{prefix}_collapsed_sections"] = collapsed unless collapsed.nil?+ return true if prefs.empty?- def update_reports_preferences(prefs)with_locked_preferences do |updated_prefs|prefs.each do |key, value|if value.is_a?(Hash)@@ -775,6 +794,23 @@ class User < ApplicationRecordendend+ # Reports preferences management+ def reports_section_collapsed?(section_key)+ section_collapsed?("reports", section_key)+ end++ def reports_section_order+ section_order("reports")+ end++ def update_reports_preferences(prefs)+ update_section_preferences(+ "reports",+ order: prefs["reports_section_order"],+ collapsed: prefs["reports_collapsed_sections"]+ )+ end+# Transactions preferences managementdef show_split_grouped?preferences&.dig("show_split_grouped") != false@@ -873,6 +909,17 @@ class User < ApplicationRecorddef default_reports_section_order%w[trends_insights transactions_breakdown]end++ def default_section_order(namespace)+ send("default_#{section_namespace!(namespace)}_section_order")+ end++ def section_namespace!(namespace)+ namespace = namespace.to_s+ raise ArgumentError, "unknown section namespace #{namespace.inspect}" unless SECTION_NAMESPACES.include?(namespace)++ namespace+ enddef ensure_valid_profile_imagereturn unless profile_image.attached?diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rbindex 7f91799172..d1aa1c0856 100644--- a/test/application_system_test_case.rb+++ b/test/application_system_test_case.rb@@ -115,9 +115,9 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase.performend- # Lets a dashboard or reports test wait for the section order PATCH: once- # it answers, <html> carries data-order-saved with the response status.- # data-order-requests counts the PATCHes as soon as they are sent.+ # Lets a dashboard or reports test wait for a section order or collapse+ # PATCH: once it answers, <html> carries data-order-saved with the response+ # status. data-order-requests counts the PATCHes as soon as they are sent.# Waits for the sortable-list controller to connect first, so keys sent# next are handled.def record_saved_section_order@@ -134,7 +134,8 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCasepage.execute_script(<<~JS)const originalFetch = window.fetch;window.fetch = (url, init) => {- if (typeof init?.body !== "string" || !init.body.includes("section_order")) {+ const body = init?.body;+ if (typeof body !== "string" || !(body.includes("section_order") || body.includes("collapsed_sections"))) {return originalFetch(url, init);}const { dataset } = document.documentElement;diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex 519f678f9d..d053a2c73e 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -9,6 +9,34 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest@family = @user.familyend+ test "renders sections in the order and collapse state stored under the reports keys" do+ @user.update_columns(preferences: (@user.preferences || {}).merge(+ "reports_section_order" => %w[transactions_breakdown trends_insights],+ "reports_collapsed_sections" => { "trends_insights" => true }+ ))++ get reports_path++ assert_response :success+ keys = css_select("[data-section-key]").map { |node| node["data-section-key"] }+ assert_equal %w[transactions_breakdown trends_insights], keys.first(2)+ assert_select "[data-section-key=trends_insights][data-reports-section-collapsed-value=?]", "true"+ assert_select "[data-section-key=transactions_breakdown][data-reports-section-collapsed-value=?]", "false"+ end++ test "the reports preferences endpoint stores order and collapse under the reports keys" do+ @user.update_columns(preferences: (@user.preferences || {}).merge("reports_collapsed_sections" => { "net_worth" => true }))++ patch update_preferences_reports_path,+ params: { preferences: { reports_section_order: %w[trends_insights net_worth], reports_collapsed_sections: { trends_insights: true } } },+ as: :json++ assert_response :ok+ @user.reload+ assert_equal %w[trends_insights net_worth], @user.preferences["reports_section_order"]+ assert_equal({ "net_worth" => true, "trends_insights" => true }, @user.preferences["reports_collapsed_sections"])+ end+# The per-trade line under the realised-gains card rendered# `Money.new(gain.value, Current.family.currency)` -- taking the number out of# the Trend and re-labelling it as family currency with no conversion at all.diff --git a/test/models/user_test.rb b/test/models/user_test.rbindex 71e046e404..42dddccbae 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -832,6 +832,56 @@ class UserTest < ActiveSupport::TestCaseassert_equal %w[transactions_breakdown], @user.preferences["reports_section_order"]end+ test "Reports reads the order and collapsed set already stored under its original keys" do+ # Written straight to the column, as preferences saved before the+ # namespaced readers existed were.+ @user.update_columns(preferences: {+ "reports_section_order" => %w[transactions_breakdown net_worth trends_insights],+ "reports_collapsed_sections" => { "net_worth" => true, "trends_insights" => false }+ })+ @user.reload++ assert_equal %w[transactions_breakdown net_worth trends_insights], @user.reports_section_order+ assert_equal @user.reports_section_order, @user.section_order("reports")+ assert @user.reports_section_collapsed?("net_worth")+ assert @user.section_collapsed?("reports", "net_worth")+ assert_not @user.reports_section_collapsed?("trends_insights")+ assert_not @user.reports_section_collapsed?("transactions_breakdown")+ end++ test "update_reports_preferences keeps writing the original keys and merges each toggle" do+ @user.update!(preferences: { "reports_section_order" => %w[net_worth], "reports_collapsed_sections" => { "net_worth" => true } })++ @user.update_reports_preferences({ "reports_collapsed_sections" => { "trends_insights" => true } })+ @user.reload++ assert_equal %w[net_worth], @user.preferences["reports_section_order"], "a toggle must not write an order"+ assert_equal({ "net_worth" => true, "trends_insights" => true }, @user.preferences["reports_collapsed_sections"])++ @user.update_reports_preferences({ "reports_section_order" => %w[trends_insights net_worth] })+ @user.reload++ assert_equal %w[trends_insights net_worth], @user.preferences["reports_section_order"]+ assert_equal({ "net_worth" => true, "trends_insights" => true }, @user.preferences["reports_collapsed_sections"])+ assert_equal %w[reports_collapsed_sections reports_section_order], @user.preferences.keys.sort+ end++ test "section preferences reject an unknown namespace" do+ assert_raises(ArgumentError) { @user.section_order("dashboard") }+ assert_raises(ArgumentError) { @user.section_collapsed?("dashboard", "net_worth") }+ assert_raises(ArgumentError) { @user.update_section_preferences("settings", order: []) }+ end++ # Safe navigation skips its arguments when the receiver is nil, so the+ # namespace check has to run before preferences is read.+ test "section preferences reject an unknown namespace when preferences is nil" do+ @user.preferences = nil++ assert_raises(ArgumentError) { @user.section_order("dashboard") }+ assert_raises(ArgumentError) { @user.section_collapsed?("dashboard", "net_worth") }+ assert_not @user.section_collapsed?("reports", "net_worth")+ end+test "handles missing nested keys in preferences for collapsed sections" do@user.update!(preferences: { "section_order" => %w[cashflow] })diff --git a/test/system/reports_test.rb b/test/system/reports_test.rbindex 7fed3edbdb..2888ef2369 100644--- a/test/system/reports_test.rb+++ b/test/system/reports_test.rb@@ -92,6 +92,24 @@ class ReportsTest < ApplicationSystemTestCaseassert_operator saved_order.index(moved), :<, saved_order.index(above)end+ # The collapse control sends the page's CSRF token and saves nothing without+ # one, and the test environment renders none unless forgery protection is on.+ test "collapsing a section saves it under the reports keys" do+ original = ActionController::Base.allow_forgery_protection+ ActionController::Base.allow_forgery_protection = true+ user = users(:family_admin)+ visit reports_path(period_type: :monthly)+ record_saved_section_order++ find("section[data-section-key='transactions_breakdown'] button[data-reports-section-target='button']").click++ assert_selector "section[data-section-key='transactions_breakdown'] button[aria-expanded='false']"+ assert_selector "html[data-order-saved='200']"+ assert_equal true, user.reload.preferences.dig("reports_collapsed_sections", "transactions_breakdown")+ ensure+ ActionController::Base.allow_forgery_protection = original+ end+privatedef clicked_hotkeyspage.evaluate_script("window.clickedHotkeys")