Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add preview-gated portfolio page shell (#4764)

jaysbeekay7f1b51e30431
diff --git a/app/controllers/portfolios_controller.rb b/app/controllers/portfolios_controller.rb
new file mode 100644
index 0000000000..39aee80114
--- /dev/null
+++ b/app/controllers/portfolios_controller.rb
@@ -0,0 +1,60 @@
+class PortfoliosController < ApplicationController
+ # Registered before Periodable's set_period, so a request the gate turns
+ # away never saves its `period` param as the user's default.
+ before_action :require_preview_features!
+
+ include Periodable
+
+ def show
+ # `as_of` is captured once and passed down, so every section that takes a
+ # date reads the same one and the partials stay pure (no Date.current /
+ # Current.family lookups of their own).
+ @as_of = Date.current
+ @statement = Current.family.investment_statement(user: Current.user)
+ registry = Portfolio::SectionRegistry.new(
+ statement: @statement,
+ period: @period,
+ as_of: @as_of,
+ user: Current.user
+ )
+ @empty = registry.empty?
+ @sections = @empty ? [] : registry.sections
+
+ @breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.portfolio"), nil ] ]
+ end
+
+ def update_preferences
+ # `require` passes a scalar through, and indexing a String by key raises,
+ # so a body whose `preferences` is not an object is refused here.
+ return head :bad_request unless params[:preferences].is_a?(ActionController::Parameters)
+
+ if Current.user.update_section_preferences(
+ "portfolio",
+ order: preferences_params["portfolio_section_order"],
+ collapsed: preferences_params["portfolio_collapsed_sections"]
+ )
+ head :ok
+ else
+ head :unprocessable_entity
+ end
+ end
+
+ private
+ # Allow-list: only the two portfolio keys, and within them only the
+ # registry's own section keys, so nothing is stored that the registry
+ # would never read. User#update_section_preferences drops any value that
+ # is not an array of keys or a hash of flags.
+ def preferences_params
+ @preferences_params ||= begin
+ prefs = params.require(:preferences)
+ known = Portfolio::SectionRegistry::KEYS
+ order = prefs[:portfolio_section_order]
+ collapsed = prefs[:portfolio_collapsed_sections]
+
+ {
+ "portfolio_section_order" => (order.map(&:to_s) & known if order.is_a?(Array)),
+ "portfolio_collapsed_sections" => (collapsed.to_unsafe_h.slice(*known) if collapsed.respond_to?(:to_unsafe_h))
+ }
+ end
+ end
+end
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb
index 8e4612c138..a671129e4d 100644
--- a/app/controllers/reports_controller.rb
+++ b/app/controllers/reports_controller.rb
@@ -22,6 +22,10 @@ class ReportsController < ApplicationController
end
def update_preferences
+ # `require` passes a scalar through, and indexing a String by key raises,
+ # so a body whose `preferences` is not an object is refused here.
+ return head :bad_request unless params[:preferences].is_a?(ActionController::Parameters)
+
if Current.user.update_reports_preferences(preferences_params)
head :ok
else
@@ -146,11 +150,13 @@ class ReportsController < ApplicationController
end
def preferences_params
+ # Only the two reports keys are passed on; User#update_section_preferences
+ # drops any value that is not an array of keys or a hash of flags.
prefs = params.require(:preferences)
- {}.tap do |permitted|
- permitted["reports_collapsed_sections"] = prefs[:reports_collapsed_sections].to_unsafe_h if prefs[:reports_collapsed_sections]
- permitted["reports_section_order"] = prefs[:reports_section_order] if prefs[:reports_section_order]
- end
+ {
+ "reports_collapsed_sections" => prefs[:reports_collapsed_sections],
+ "reports_section_order" => prefs[:reports_section_order]
+ }
end
def build_reports_sections
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index 2e1c33ee84..1081316bdd 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -65,7 +65,7 @@ module ApplicationHelper
# The chevron for a DS::Disclosure summary_content slot; it turns as the disclosure opens.
def disclosure_chevron
- icon "chevron-right", size: "sm", class: "motion-safe:transition-transform group-open:rotate-90"
+ icon "chevron-right", size: "sm", class: "[details[open]>summary_&]:rotate-90 motion-safe:transition-transform motion-safe:duration-150"
end
# Convert alpha (0-1) to 8-digit hex (00-FF)
@@ -146,6 +146,24 @@ module ApplicationHelper
end
end
+ # The family-wide investment hub. Preview-gated (hidden entirely without the
+ # flag) and desktop-only: the bottom bar already carries five entries at the
+ # width it has, and the hub is a wide, multi-section page. `desktop_only`
+ # is filtered out of the mobile bar in the layout, the mirror of the
+ # `mobile_only` flag the Assistant entry uses.
+ def portfolio_nav_item
+ preview_gated_nav_item(
+ {
+ name: t("layouts.application.nav.portfolio"),
+ path: portfolio_path,
+ icon: "briefcase",
+ icon_custom: false,
+ active: page_active?(portfolio_path),
+ desktop_only: true
+ }
+ )
+ end
+
# Wrapper around I18n.l to support custom date formats
def format_date(object, format = :default, options = {})
date = object.to_date
diff --git a/app/javascript/controllers/reports_section_controller.js b/app/javascript/controllers/reports_section_controller.js
index c89265063f..4aa15e63f1 100644
--- a/app/javascript/controllers/reports_section_controller.js
+++ b/app/javascript/controllers/reports_section_controller.js
@@ -1,10 +1,11 @@
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.
+// Saves whether a section on a page built on the Reports section framework is
+// collapsed. The section's <details> opens and closes itself; this saves the
+// state its `toggle` event reports. 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"];
+ static targets = ["details"];
// `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.
@@ -15,50 +16,14 @@ export default class extends Controller {
preferenceKey: { type: String, default: "reports" },
};
- connect() {
- if (this.collapsedValue) {
- this.collapse(false);
- }
- }
+ // `toggle` also fires for the open state the page was rendered with, so
+ // only a change from the saved state is sent.
+ save() {
+ const collapsed = !this.detailsTarget.open;
+ if (collapsed === this.collapsedValue) return;
- toggle(event) {
- event.preventDefault();
- if (this.collapsedValue) {
- this.expand();
- } else {
- this.collapse();
- }
- }
-
- handleToggleKeydown(event) {
- // Handle Enter and Space keys for keyboard accessibility
- if (event.key === "Enter" || event.key === " ") {
- event.preventDefault();
- event.stopPropagation(); // Prevent section's keyboard handler from firing
- this.toggle(event);
- }
- }
-
- collapse(persist = true) {
- this.contentTarget.classList.add("hidden");
- this.chevronTarget.classList.add("-rotate-90");
- this.collapsedValue = true;
- if (this.hasButtonTarget) {
- this.buttonTarget.setAttribute("aria-expanded", "false");
- }
- if (persist) {
- this.savePreference(true);
- }
- }
-
- expand() {
- this.contentTarget.classList.remove("hidden");
- this.chevronTarget.classList.remove("-rotate-90");
- this.collapsedValue = false;
- if (this.hasButtonTarget) {
- this.buttonTarget.setAttribute("aria-expanded", "true");
- }
- this.savePreference(false);
+ this.collapsedValue = collapsed;
+ this.savePreference(collapsed);
}
async savePreference(collapsed) {
diff --git a/app/javascript/controllers/sortable_list_controller.js b/app/javascript/controllers/sortable_list_controller.js
index b07fb444da..826d679861 100644
--- a/app/javascript/controllers/sortable_list_controller.js
+++ b/app/javascript/controllers/sortable_list_controller.js
@@ -231,8 +231,11 @@ export default class extends Controller {
this.showDropPosition(this.currentTouchX, this.currentTouchY);
}
- touchEnd() {
+ touchEnd(event) {
this.cancelHold();
+ // Letting go of a hold is not a tap: keep the browser from clicking what
+ // is under the finger, such as a header that opens and closes the item.
+ if (this.holdActivated) event.preventDefault();
if (!this.holdActivated || !this.isTouching || !this.draggedElement) {
this.resetTouchState();
diff --git a/app/models/portfolio/section_registry.rb b/app/models/portfolio/section_registry.rb
new file mode 100644
index 0000000000..12c2993a15
--- /dev/null
+++ b/app/models/portfolio/section_registry.rb
@@ -0,0 +1,91 @@
+# The list of sections the portfolio hub renders, in the order the user last
+# left them.
+#
+# Same shape as ReportsController#build_reports_sections -- a hash per section
+# with `key`, an i18n `title` key, a `partial`, its `locals`, and the `visible`
+# / `collapsible` flags -- so the Reports section chrome (drag to reorder,
+# chevron to collapse) renders it unchanged. It lives here rather than in the
+# controller because the ordering rule and the section list are domain
+# decisions the controller only renders, and because a PORO can be unit-tested
+# without a request.
+#
+# Every local a partial needs is passed in. Nothing here (and nothing in the
+# partials) reads Date.current or Current.family: the controller captures one
+# `as_of` and one statement per request and hands them down, so the sections
+# that take a date all read the same one.
+class Portfolio::SectionRegistry
+ # The built-in section keys, in declaration order. The preferences
+ # endpoint accepts only these, so a saved order or collapsed set cannot
+ # carry arbitrary strings into the user's preferences.
+ KEYS = %w[accounts].freeze
+
+ attr_reader :statement, :period, :as_of, :user, :extra_sections
+
+ # `extra_sections` are appended after the built-ins, in the order given. It
+ # is the seam that keeps this list open: a section can be added (or a test
+ # can add one) without editing the built-in list.
+ def initialize(statement:, period:, as_of:, user:, extra_sections: [])
+ @statement = statement
+ @period = period
+ @as_of = as_of
+ @user = user
+ @extra_sections = extra_sections || []
+ end
+
+ # True when the viewer counts no investment account; the page shows its
+ # empty state instead of the sections. Reads the same loaded list as the
+ # cards, so the accounts are queried once per request.
+ def empty?
+ accounts_for_cards.empty?
+ end
+
+ def sections
+ all = built_in_sections + extra_sections
+
+ # Order by the user's saved order; anything the saved order doesn't
+ # mention (a section added since they last dragged one) is appended in
+ # declaration order, so a new section always appears rather than
+ # disappearing until the next drag. Same rule as Reports.
+ # `uniq` before the lookup: a saved order that repeats a key would
+ # otherwise render that section once per occurrence. The endpoint
+ # deduplicates what it writes, but an order written by anything else
+ # still has to render once.
+ ordered = Array(user&.section_order("portfolio")).uniq.filter_map do |key|
+ all.find { |section| section[:key] == key }
+ end
+
+ # Matched by key, never by comparing whole section hashes: a section's
+ # locals carry the statement and whatever it has memoised, and the order
+ # must not depend on how those compare.
+ placed = ordered.map { |section| section[:key] }
+ ordered + all.reject { |section| placed.include?(section[:key]) }
+ end
+
+ private
+ def built_in_sections
+ [
+ {
+ key: "accounts",
+ title: "portfolios.sections.accounts",
+ partial: "portfolios/accounts",
+ locals: shared_locals.merge(accounts: accounts_for_cards),
+ visible: accounts_for_cards.any?,
+ collapsible: true
+ }
+ ]
+ end
+
+ # The accounts the cards show, in name order (id breaks ties, so
+ # same-named cards keep their places), with every record the logo reads
+ # (the attachment, the accountable's colour, the provider links and the
+ # provider each falls back to) loaded here rather than once per card.
+ def accounts_for_cards
+ @accounts_for_cards ||= statement.investment_accounts.with_attached_logo
+ .includes(:accountable, :plaid_account, :simplefin_account, account_providers: :provider)
+ .alphabetically.order(:id).to_a
+ end
+
+ def shared_locals
+ { statement: statement, period: period, as_of: as_of }
+ end
+end
diff --git a/app/models/user.rb b/app/models/user.rb
index 189b166ab6..29bb1c2a24 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -754,39 +754,51 @@ class User < ApplicationRecord
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
+ # framework (Reports, the portfolio hub). 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
+ # nothing already stored changes meaning. Each namespace maps to its
+ # default order; the portfolio's is read from its registry so the two
+ # lists cannot drift.
+ SECTION_DEFAULT_ORDERS = {
+ "reports" => %w[trends_insights transactions_breakdown].freeze,
+ "portfolio" => Portfolio::SectionRegistry::KEYS
+ }.freeze
def section_order(namespace)
prefix = section_namespace!(namespace)
- preferences&.[]("#{prefix}_section_order") || default_section_order(prefix)
+ stored = preferences&.[]("#{prefix}_section_order")
+ stored.is_a?(Array) ? stored.map(&:to_s).uniq : SECTION_DEFAULT_ORDERS.fetch(prefix).dup
end
def section_collapsed?(namespace, section_key)
prefix = section_namespace!(namespace)
- preferences&.dig("#{prefix}_collapsed_sections", section_key) == true
+ collapsed = preferences&.[]("#{prefix}_collapsed_sections")
+ collapsed.is_a?(Hash) && collapsed[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.
+ # Only an array of keys (deduplicated) and a hash of key => flag are stored;
+ # any other shape is dropped, since the readers index into them.
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?
+ prefs["#{prefix}_section_order"] = order.map(&:to_s).uniq if order.is_a?(Array)
+ collapsed = collapsed.to_unsafe_h if collapsed.respond_to?(:to_unsafe_h)
+ if collapsed.is_a?(Hash)
+ prefs["#{prefix}_collapsed_sections"] = collapsed.to_h { |key, flag| [ key.to_s, ActiveModel::Type::Boolean.new.cast(flag) == true ] }
+ end
return true if prefs.empty?
with_locked_preferences do |updated_prefs|
prefs.each do |key, value|
if value.is_a?(Hash)
- updated_prefs[key] ||= {}
- updated_prefs[key] = updated_prefs[key].merge(value)
+ stored = updated_prefs[key]
+ updated_prefs[key] = (stored.is_a?(Hash) ? stored : {}).merge(value)
else
updated_prefs[key] = value
end
@@ -906,17 +918,9 @@ class User < ApplicationRecord
%w[insights_feed cashflow_sankey outflows_donut net_worth_chart balance_sheet]
end
- def 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)
+ raise ArgumentError, "unknown section namespace #{namespace.inspect}" unless SECTION_DEFAULT_ORDERS.key?(namespace)
namespace
end
diff --git a/app/views/accounts/_balance_card.html.erb b/app/views/accounts/_balance_card.html.erb
new file mode 100644
index 0000000000..bb95fc2bb0
--- /dev/null
+++ b/app/views/accounts/_balance_card.html.erb
@@ -0,0 +1,14 @@
+<%# locals: (account:, href:, truncate: false, focus_ring: false) %>
+<%# An account's logo, name, type and balance as one link. `truncate` keeps a
+ long name or type on one line inside a narrow grid cell, with the balance
+ beside it unbroken. %>
+<%= link_to href, class: class_names("bg-container-inset rounded-lg p-4 flex items-center justify-between hover:bg-container-hover transition-colors", "focus-ring" => focus_ring) do %>
+ <div class="<%= class_names("flex items-center gap-3", "min-w-0" => truncate) %>">
+ <%= render "accounts/logo", account: account, size: "sm" %>
+ <%= tag.div class: ("min-w-0" if truncate) do %>
+ <p class="<%= class_names("font-medium text-primary text-sm", "truncate" => truncate) %>"><%= account.name %></p>
+ <p class="<%= class_names("text-xs text-secondary", "truncate" => truncate) %>"><%= account.short_subtype_label %></p>
+ <% end %>
+ </div>
+ <p class="<%= class_names("font-medium text-primary privacy-sensitive", "whitespace-nowrap" => truncate) %>"><%= format_money(account.balance_money) %></p>
+<% end %>
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 1379d7ada3..2a18a1b1e9 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -14,6 +14,7 @@ else
bills_nav_item,
{ name: t(".nav.reports"), path: reports_path, icon: "chart-bar", icon_custom: false, active: page_active?(reports_path) },
plan_nav_item,
+ portfolio_nav_item,
({ name: t(".nav.assistant"), path: chats_path, icon: "icon-assistant", icon_custom: true, active: page_active?(chats_path), mobile_only: true } if assistant_enabled)
].compact
end %>
@@ -224,7 +225,7 @@ end %>
<%# MOBILE - Bottom Nav %>
<%= tag.nav class: "lg:hidden fixed bottom-0 left-0 right-0 bg-surface z-10 border-t border-tertiary flex justify-around pb-[env(safe-area-inset-bottom)]",
data: { viewport_target: "bottomNav" } do %>
- <% mobile_nav_items.each do |nav_item| %>
+ <% mobile_nav_items.reject { |item| item[:desktop_only] }.each do |nav_item| %>
<%= render "layouts/shared/nav_item", **nav_item %>
<% end %>
<% end %>
diff --git a/app/views/layouts/shared/_nav_item.html.erb b/app/views/layouts/shared/_nav_item.html.erb
index 4f9a0b24dd..b45d946aba 100644
--- a/app/views/layouts/shared/_nav_item.html.erb
+++ b/app/views/layouts/shared/_nav_item.html.erb
@@ -1,4 +1,4 @@
-<%# locals: (name:, path:, icon:, icon_custom:, active:, mobile_only: false, preview: false) %>
+<%# locals: (name:, path:, icon:, icon_custom:, active:, mobile_only: false, desktop_only: false, preview: false) %>
<%= link_to path, class: "space-y-1 group block relative pb-1 focus-ring rounded-lg", aria: { current: ("page" if active) } do %>
<div class="grow flex flex-col lg:flex-row gap-1 items-center">
diff --git a/app/views/portfolios/_accounts.html.erb b/app/views/portfolios/_accounts.html.erb
new file mode 100644
index 0000000000..fc0d586016
--- /dev/null
+++ b/app/views/portfolios/_accounts.html.erb
@@ -0,0 +1,8 @@
+<%# locals: (accounts:, statement:, period:, as_of:) %>
+
+<%# One card per investment account the user may count, straight to its holdings tab. %>
+<div id="portfolio-accounts" class="grid grid-cols-1 @2xl:grid-cols-2 @4xl:grid-cols-3 gap-3">
+ <% accounts.each do |account| %>
+ <%= render "accounts/balance_card", account: account, href: account_path(account, tab: "holdings"), truncate: true, focus_ring: true %>
+ <% end %>
+</div>
diff --git a/app/views/portfolios/_empty_state.html.erb b/app/views/portfolios/_empty_state.html.erb
new file mode 100644
index 0000000000..ca8f0ed4e6
--- /dev/null
+++ b/app/views/portfolios/_empty_state.html.erb
@@ -0,0 +1,14 @@
+<%= render DS::EmptyState.new(
+ icon: "briefcase",
+ title: t("portfolios.empty_state.title"),
+ description: t("portfolios.empty_state.description")
+ ) do |empty_state| %>
+ <% empty_state.with_action do %>
+ <%= render DS::Link.new(
+ text: t("portfolios.empty_state.add_account"),
+ href: new_account_path,
+ frame: :modal,
+ icon: "plus"
+ ) %>
+ <% end %>
+<% end %>
diff --git a/app/views/portfolios/show.html.erb b/app/views/portfolios/show.html.erb
new file mode 100644
index 0000000000..1b18deba2c
--- /dev/null
+++ b/app/views/portfolios/show.html.erb
@@ -0,0 +1,23 @@
+<%# Family-wide investment hub. Built on the Reports section framework, so the
+ sections drag to reorder and collapse exactly as Reports' do -- only the
+ preferences namespace and endpoint differ. %>
+<div class="@container space-y-6 pb-6 lg:pb-12">
+ <header>
+ <div class="flex items-center gap-2">
+ <h1 class="text-2xl font-semibold text-primary"><%= t(".title") %></h1>
+ <%= render DS::Pill.new(label: t("shared.preview"), size: :md) %>
+ </div>
+ <p class="text-sm text-secondary mt-1"><%= t(".subtitle") %></p>
+ </header>
+
+ <% if @empty %>
+ <%= render "portfolios/empty_state" %>
+ <% else %>
+ <%= render "shared/reorderable_sections",
+ sections: @sections,
+ namespace: "portfolio",
+ url: update_preferences_portfolio_path,
+ collapse_url: update_preferences_portfolio_path,
+ i18n_scope: "portfolios.show" %>
+ <% end %>
+</div>
diff --git a/app/views/reports/_investment_performance.html.erb b/app/views/reports/_investment_performance.html.erb
index c5774a6e45..7dc47cf343 100644
--- a/app/views/reports/_investment_performance.html.erb
+++ b/app/views/reports/_investment_performance.html.erb
@@ -167,7 +167,7 @@
<%= render DS::Disclosure.new(variant: :inline) do |disclosure| %>
<% disclosure.with_summary_content do %>
<span class="flex items-center gap-1 text-xs text-secondary hover:text-primary">
- <%= icon "chevron-right", size: "sm", class: "group-open:rotate-90 motion-safe:transition-transform motion-safe:duration-150" %>
+ <%= disclosure_chevron %>
<%= t("reports.investment_performance.view_details") %>
(<%= t("reports.investment_performance.holdings_count", count: data[:holdings].count) %>, <%= t("reports.investment_performance.sells_count", count: data[:sell_trades].count) %>)
</span>
@@ -225,16 +225,7 @@
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
<% investment_metrics[:accounts].each do |account| %>
- <%= link_to account_path(account), class: "bg-container-inset rounded-lg p-4 flex items-center justify-between hover:bg-container-hover transition-colors" do %>
- <div class="flex items-center gap-3">
- <%= render "accounts/logo", account: account, size: "sm" %>
- <div>
- <p class="font-medium text-primary text-sm"><%= account.name %></p>
- <p class="text-xs text-secondary"><%= account.short_subtype_label %></p>
- </div>
- </div>
- <p class="font-medium text-primary privacy-sensitive"><%= format_money(account.balance_money) %></p>
- <% end %>
+ <%= render "accounts/balance_card", account: account, href: account_path(account) %>
<% end %>
</div>
</div>
diff --git a/app/views/reports/index.html.erb b/app/views/reports/index.html.erb
index c31c60ba84..88f740571d 100644
--- a/app/views/reports/index.html.erb
+++ b/app/views/reports/index.html.erb
@@ -138,75 +138,11 @@
</section>
<%# Collapsible & Reorderable Sections %>
- <div data-controller="sortable-list"
- data-sortable-list-url-value="<%= update_preferences_reports_path %>"
- data-sortable-list-param-value="preferences.reports_section_order"
- data-sortable-list-hold-delay-value="800"
- data-sortable-list-own-keys-only-value="true"
- data-action="dragover->sortable-list#dragOver drop->sortable-list#drop turbo:before-visit@window->sortable-list#saveBeforeVisit"
- role="list"
- aria-label="<%= t("reports.index.sections_aria") %>">
- <% @reports_sections.each do |section| %>
- <% next unless section[:visible] %>
- <%# [-webkit-touch-callout:none] suppresses iOS Safari's native long-press
- link preview on the amount/percentage anchors inside this section —
- without it, the callout preempts the touch, fires touchcancel, and
- the press-and-hold drag gesture never gets a chance to activate
- (see #3132 review). %>
- <section
- class="bg-container rounded-xl shadow-border-xs transition-all mb-6 group focus:outline-none focus-visible:ring-2 focus-visible:ring-alpha-black-300 focus-visible:ring-offset-2 [-webkit-touch-callout:none]"
- data-sortable-list-target="item"
- data-sortable-list-id="<%= section[:key] %>"
- data-section-key="<%= section[:key] %>"
- data-controller="reports-section"
- data-reports-section-section-key-value="<%= section[:key] %>"
- data-reports-section-collapsed-value="<%= Current.user.reports_section_collapsed?(section[:key]) %>"
- draggable="true"
- tabindex="0"
- role="listitem"
- aria-grabbed="false"
- aria-label="<%= t(section[:title]) %> section. Press Enter or Space to grab for reordering, then use arrow keys to move."
- data-action="
- dragstart->sortable-list#dragStart
- dragend->sortable-list#dragEnd
- touchstart->sortable-list#touchStart
- touchmove->sortable-list#touchMove
- touchend->sortable-list#touchEnd
- touchcancel->sortable-list#touchCancel
- contextmenu->sortable-list#suppressContextMenu
- keydown->sortable-list#handleKeyDown">
- <div class="px-4 py-2 flex items-center justify-between">
- <div class="flex items-center gap-2">
- <button
- type="button"
- class="text-secondary hover:text-primary transition-colors p-0.5"
- data-action="click->reports-section#toggle keydown->reports-section#handleToggleKeydown"
- data-reports-section-target="button"
- aria-label="<%= t("reports.index.toggle_section") %>"
- aria-expanded="<%= !Current.user.reports_section_collapsed?(section[:key]) %>">
- <%= icon("chevron-down", size: "sm", class: "transition-transform", data: { reports_section_target: "chevron" }) %>
- </button>
- <h2 class="text-base font-medium">
- <%= t(section[:title]) %>
- </h2>
- <% if section[:preview] %>
- <%= render DS::Pill.new(label: t("shared.preview")) %>
- <% end %>
- </div>
- <%# A mouse grab hint. Keys only grab the section itself, so the hint
- stays out of the tab order instead of being an invisible stop. %>
- <span
- class="cursor-grab active:cursor-grabbing hidden lg:flex items-center justify-center w-6 h-6 text-secondary hover:text-primary transition-colors opacity-0 group-hover:opacity-100"
- aria-hidden="true">
- <%= icon("grip-vertical", size: "sm") %>
- </span>
- </div>
- <div class="p-4" data-reports-section-target="content">
- <%= render partial: section[:partial], locals: section[:locals] %>
- </div>
- </section>
- <% end %>
- </div>
+ <%= render "shared/reorderable_sections",
+ sections: @reports_sections,
+ namespace: "reports",
+ url: update_preferences_reports_path,
+ i18n_scope: "reports.index" %>
<% else %>
<%# Empty State %>
<section>
diff --git a/app/views/shared/_reorderable_sections.html.erb b/app/views/shared/_reorderable_sections.html.erb
new file mode 100644
index 0000000000..e620b7413c
--- /dev/null
+++ b/app/views/shared/_reorderable_sections.html.erb
@@ -0,0 +1,80 @@
+<%# locals: (sections:, namespace:, url:, i18n_scope:, collapse_url: nil) %>
+<%# The section list Reports and the portfolio page share: each visible section
+ drags to reorder (saved to `url` as preferences.<namespace>_section_order)
+ and collapses (saved under <namespace>_collapsed_sections). The collapse
+ state posts to the Reports endpoint unless `collapse_url` is given.
+ `i18n_scope` holds the page's `sections_aria` and `section_aria` labels. %>
+<div data-controller="sortable-list"
+ data-sortable-list-url-value="<%= url %>"
+ data-sortable-list-param-value="preferences.<%= namespace %>_section_order"
+ data-sortable-list-hold-delay-value="800"
+ data-sortable-list-own-keys-only-value="true"
+ data-action="dragover->sortable-list#dragOver drop->sortable-list#drop turbo:before-visit@window->sortable-list#saveBeforeVisit"
+ role="list"
+ aria-label="<%= t("#{i18n_scope}.sections_aria") %>">
+ <% sections.each do |section| %>
+ <% next unless section[:visible] %>
+ <% collapsed = Current.user.section_collapsed?(namespace, section[:key]) %>
+ <%# The section is the list item that drags and takes the reorder keys;
+ the DS::Disclosure inside it is the card that opens and closes.
+ [-webkit-touch-callout:none] keeps iOS Safari's long-press link preview
+ on links inside a section from cancelling the touch, which would stop
+ the press-and-hold drag from ever starting. %>
+ <section
+ class="rounded-xl transition-all mb-6 focus:outline-none focus-visible:ring-2 focus-visible:ring-focus-ring focus-visible:ring-offset-2 [-webkit-touch-callout:none]"
+ data-sortable-list-target="item"
+ data-sortable-list-id="<%= section[:key] %>"
+ data-section-key="<%= section[:key] %>"
+ data-controller="reports-section"
+ data-reports-section-section-key-value="<%= section[:key] %>"
+ data-reports-section-collapsed-value="<%= collapsed %>"
+ <% if collapse_url %>
+ data-reports-section-url-value="<%= collapse_url %>"
+ data-reports-section-preference-key-value="<%= namespace %>"
+ <% end %>
+ draggable="true"
+ tabindex="0"
+ role="listitem"
+ aria-grabbed="false"
+ aria-label="<%= t("#{i18n_scope}.section_aria", title: t(section[:title])) %>"
+ data-action="
+ dragstart->sortable-list#dragStart
+ dragend->sortable-list#dragEnd
+ touchstart->sortable-list#touchStart
+ touchmove->sortable-list#touchMove
+ touchend->sortable-list#touchEnd
+ touchcancel->sortable-list#touchCancel
+ contextmenu->sortable-list#suppressContextMenu
+ keydown->sortable-list#handleKeyDown">
+ <%= render DS::Disclosure.new(
+ variant: :card,
+ open: !collapsed,
+ body_class: "mt-4",
+ data: { reports_section_target: "details", action: "toggle->reports-section#save" }
+ ) do |disclosure| %>
+ <% disclosure.with_summary_content do %>
+ <div class="flex items-center justify-between">
+ <div class="flex items-center gap-2">
+ <%= disclosure_chevron %>
+ <h2 class="text-base font-medium">
+ <%= t(section[:title]) %>
+ </h2>
+ <% if section[:preview] %>
+ <%= render DS::Pill.new(label: t("shared.preview")) %>
+ <% end %>
+ </div>
+ <%# A mouse grab hint. Keys only grab the section itself, so the
+ hint stays out of the tab order instead of being an invisible
+ stop. %>
+ <span
+ class="cursor-grab active:cursor-grabbing hidden lg:flex items-center justify-center w-6 h-6 text-secondary hover:text-primary transition-colors opacity-0 group-hover:opacity-100"
+ aria-hidden="true">
+ <%= icon("grip-vertical", size: "sm") %>
+ </span>
+ </div>
+ <% end %>
+ <%= render partial: section[:partial], locals: section[:locals] %>
+ <% end %>
+ </section>
+ <% end %>
+</div>
diff --git a/config/locales/breadcrumbs/de.yml b/config/locales/breadcrumbs/de.yml
index 37485a52b5..2bfba6d1ea 100644
--- a/config/locales/breadcrumbs/de.yml
+++ b/config/locales/breadcrumbs/de.yml
@@ -61,6 +61,7 @@ de:
pending_duplicate_merges: Duplikatprüfung
plaid_items: Plaid
plan: Plan
+ portfolio: Portfolio
preferences: Einstellungen
profile: Profil
profiles: Profil
diff --git a/config/locales/breadcrumbs/en.yml b/config/locales/breadcrumbs/en.yml
index 4d4c0e77fc..71254d5e76 100644
--- a/config/locales/breadcrumbs/en.yml
+++ b/config/locales/breadcrumbs/en.yml
@@ -63,6 +63,7 @@ en:
pending_duplicate_merges: Duplicate review
plaid_items: Plaid
plan: Plan
+ portfolio: Portfolio
preferences: Preferences
profile: Profile Info
profiles: Profile Info
diff --git a/config/locales/views/layout/de.yml b/config/locales/views/layout/de.yml
index 2670bc8619..dd67755c44 100644
--- a/config/locales/views/layout/de.yml
+++ b/config/locales/views/layout/de.yml
@@ -9,6 +9,7 @@ de:
budgets: Budgets
home: Startseite
plan: Plan
+ portfolio: Portfolio
reports: Berichte
transactions: Transaktionen
goals: Ziele
diff --git a/config/locales/views/layout/en.yml b/config/locales/views/layout/en.yml
index ba0ee6639b..cc826ba435 100644
--- a/config/locales/views/layout/en.yml
+++ b/config/locales/views/layout/en.yml
@@ -16,6 +16,7 @@ en:
budgets: Budgets
home: Home
plan: Plan
+ portfolio: Portfolio
reports: Reports
goals: Goals
transactions: Transactions
diff --git a/config/locales/views/portfolios/de.yml b/config/locales/views/portfolios/de.yml
new file mode 100644
index 0000000000..298142f693
--- /dev/null
+++ b/config/locales/views/portfolios/de.yml
@@ -0,0 +1,14 @@
+---
+de:
+ portfolios:
+ empty_state:
+ add_account: Anlagekonto hinzufügen
+ description: Depot-, Vorsorge- und Krypto-Konten, die du in deine Finanzen und Berichte einbeziehst, erscheinen hier mit ihrem Saldo.
+ title: Keine Anlagekonten zum Anzeigen
+ sections:
+ accounts: Konten
+ show:
+ section_aria: "Abschnitt %{title}. Drücke Enter oder Leertaste, um ihn zum Umsortieren zu greifen, dann bewege ihn mit den Pfeiltasten."
+ sections_aria: Portfolio-Abschnitte
+ subtitle: Deine Anlagekonten und was jedes davon wert ist.
+ title: Portfolio
diff --git a/config/locales/views/portfolios/en.yml b/config/locales/views/portfolios/en.yml
new file mode 100644
index 0000000000..991ff2556e
--- /dev/null
+++ b/config/locales/views/portfolios/en.yml
@@ -0,0 +1,14 @@
+---
+en:
+ portfolios:
+ empty_state:
+ add_account: Add an investment account
+ description: Brokerage, retirement and crypto accounts you include in your finances and reports are listed here with their balance.
+ title: No investment accounts to show
+ sections:
+ accounts: Accounts
+ show:
+ section_aria: "%{title} section. Press Enter or Space to grab for reordering, then use arrow keys to move."
+ sections_aria: Portfolio sections
+ subtitle: Your investment accounts and what each one is worth.
+ title: Portfolio
diff --git a/config/locales/views/reports/ca.yml b/config/locales/views/reports/ca.yml
index d4e217871c..968cc1408a 100644
--- a/config/locales/views/reports/ca.yml
+++ b/config/locales/views/reports/ca.yml
@@ -61,7 +61,6 @@ ca:
subtitle: Visió completa de la teva salut financera
title: Informes
today: Avui
- toggle_section: Commuta la visibilitat de la secció
invalid_date_range: La data final no pot ser anterior a la inicial. Les dates
s'han intercanviat.
investment_flows:
diff --git a/config/locales/views/reports/de.yml b/config/locales/views/reports/de.yml
index de6b36fdf4..2266545833 100644
--- a/config/locales/views/reports/de.yml
+++ b/config/locales/views/reports/de.yml
@@ -7,8 +7,8 @@ de:
subtitle: Umfassende Einblicke in deine finanzielle Situation
export: CSV exportieren
print_report: Bericht drucken
+ section_aria: "Abschnitt %{title}. Drücke Enter oder Leertaste, um ihn zum Umsortieren zu greifen, dann bewege ihn mit den Pfeiltasten."
sections_aria: Berichtsbereiche
- toggle_section: "Sichtbarkeit des Bereichs umschalten"
periods:
monthly: Monatlich
quarterly: Vierteljährlich
diff --git a/config/locales/views/reports/en.yml b/config/locales/views/reports/en.yml
index 0809ec1612..562353d282 100644
--- a/config/locales/views/reports/en.yml
+++ b/config/locales/views/reports/en.yml
@@ -6,8 +6,8 @@ en:
subtitle: Comprehensive insights into your financial health
export: Export CSV
print_report: Print Report
+ section_aria: "%{title} section. Press Enter or Space to grab for reordering, then use arrow keys to move."
sections_aria: Reports sections
- toggle_section: "Toggle section visibility"
periods:
monthly: Monthly
quarterly: Quarterly
diff --git a/config/locales/views/reports/es.yml b/config/locales/views/reports/es.yml
index c3da9e502d..de00199b63 100644
--- a/config/locales/views/reports/es.yml
+++ b/config/locales/views/reports/es.yml
@@ -6,7 +6,6 @@ es:
subtitle: Información completa sobre tu salud financiera
export: Exportar CSV
print_report: Imprimir informe
- toggle_section: Mostrar / Ocultar sección
periods:
monthly: Mensual
quarterly: Trimestral
diff --git a/config/locales/views/reports/fr.yml b/config/locales/views/reports/fr.yml
index c93f0a2ddd..7bfc8f1c73 100644
--- a/config/locales/views/reports/fr.yml
+++ b/config/locales/views/reports/fr.yml
@@ -64,7 +64,6 @@ fr:
subtitle: Aperçus complets de votre santé financière
title: Rapports
today: Aujourd'hui
- toggle_section: Basculer la visibilité de la section
invalid_date_range: La date de fin ne peut pas être antérieure à la date de début.
Les dates ont été inversées.
investment_flows:
diff --git a/config/locales/views/reports/hu.yml b/config/locales/views/reports/hu.yml
index 433c22f97e..33acc0fd04 100644
--- a/config/locales/views/reports/hu.yml
+++ b/config/locales/views/reports/hu.yml
@@ -6,7 +6,6 @@ hu:
subtitle: Átfogó betekintés a pénzügyi helyzetedbe
export: CSV exportálása
print_report: Jelentés nyomtatása
- toggle_section: "Szakasz láthatóságának váltása"
periods:
monthly: Havi
quarterly: Negyedéves
diff --git a/config/locales/views/reports/id.yml b/config/locales/views/reports/id.yml
index 0c03095ac0..4c6ffe12a0 100644
--- a/config/locales/views/reports/id.yml
+++ b/config/locales/views/reports/id.yml
@@ -7,7 +7,6 @@ id:
export: Ekspor CSV
print_report: Cetak Laporan
sections_aria: Bagian laporan
- toggle_section: "Alihkan visibilitas bagian"
periods:
monthly: Bulanan
quarterly: Triwulanan
diff --git a/config/locales/views/reports/it.yml b/config/locales/views/reports/it.yml
index 78e8b62f52..c048aa1526 100644
--- a/config/locales/views/reports/it.yml
+++ b/config/locales/views/reports/it.yml
@@ -6,7 +6,6 @@ it:
subtitle: Analisi approfondita della tua salute finanziaria
export: Esporta CSV
print_report: Stampa rapporto
- toggle_section: "Mostra/nascondi sezione"
periods:
monthly: Mensile
quarterly: Trimestrale
diff --git a/config/locales/views/reports/nl.yml b/config/locales/views/reports/nl.yml
index 76a6091a84..f185191d90 100644
--- a/config/locales/views/reports/nl.yml
+++ b/config/locales/views/reports/nl.yml
@@ -7,7 +7,6 @@ nl:
export: "CSV exporteren"
print_report: "Rapport afdrukken"
sections_aria: "Rapportsecties"
- toggle_section: "Zichtbaarheid sectie wijzigen"
periods:
monthly: "Maandelijks"
quarterly: "Per kwartaal"
diff --git a/config/locales/views/reports/pl.yml b/config/locales/views/reports/pl.yml
index 4dd08518e0..eaa42987fa 100644
--- a/config/locales/views/reports/pl.yml
+++ b/config/locales/views/reports/pl.yml
@@ -61,7 +61,6 @@ pl:
subtitle: Kompleksowy wgląd w kondycję Twoich finansów
title: Raporty
today: Dziś
- toggle_section: Przełącz widoczność sekcji
invalid_date_range: Data końcowa nie może być wcześniejsza niż data początkowa.
Daty zostały zamienione.
investment_flows:
diff --git a/config/locales/views/reports/pt-BR.yml b/config/locales/views/reports/pt-BR.yml
index c2bff7417c..9fe41389ae 100644
--- a/config/locales/views/reports/pt-BR.yml
+++ b/config/locales/views/reports/pt-BR.yml
@@ -6,7 +6,6 @@ pt-BR:
subtitle: Insights completos sobre sua saúde financeira
export: Exportar CSV
print_report: Imprimir Relatório
- toggle_section: "Alternar visibilidade da seção"
periods:
monthly: Mensal
quarterly: Trimestral
diff --git a/config/locales/views/reports/pt-PT.yml b/config/locales/views/reports/pt-PT.yml
index 15406af450..7dd104492a 100644
--- a/config/locales/views/reports/pt-PT.yml
+++ b/config/locales/views/reports/pt-PT.yml
@@ -6,7 +6,6 @@ pt-PT:
subtitle: Informações abrangentes sobre a sua saúde financeira
export: Exportar CSV
print_report: Imprimir Relatório
- toggle_section: "Alternar a visibilidade da secção"
periods:
monthly: Mensal
quarterly: Trimestral
diff --git a/config/locales/views/reports/ru.yml b/config/locales/views/reports/ru.yml
index 941cd03f0c..0941f8c147 100644
--- a/config/locales/views/reports/ru.yml
+++ b/config/locales/views/reports/ru.yml
@@ -61,7 +61,6 @@ ru:
subtitle: Полный анализ вашего финансового состояния
title: Отчёты
today: Сегодня
- toggle_section: Переключить видимость раздела
invalid_date_range: Дата окончания не может быть раньше даты начала. Даты были
поменяны местами.
investment_flows:
diff --git a/config/locales/views/reports/tr.yml b/config/locales/views/reports/tr.yml
index ea2b8da8fc..8e20b05ec1 100644
--- a/config/locales/views/reports/tr.yml
+++ b/config/locales/views/reports/tr.yml
@@ -62,7 +62,6 @@ tr:
subtitle: Finansal sağlığınıza dair kapsamlı içgörüler
title: Raporlar
today: Bugün
- toggle_section: Bölüm görünürlüğünü değiştir
invalid_date_range: Bitiş tarihi başlangıç tarihinden önce olamaz. Tarihler yer
değiştirildi.
investment_flows:
diff --git a/config/locales/views/reports/uk.yml b/config/locales/views/reports/uk.yml
index 536cab5c36..6ea40390f0 100644
--- a/config/locales/views/reports/uk.yml
+++ b/config/locales/views/reports/uk.yml
@@ -5,7 +5,6 @@ uk:
subtitle: Комплексне уявлення про ваше фінансове здоров'я
export: Експорт CSV
print_report: Друк звіту
- toggle_section: "Переключити видимість розділу"
periods:
monthly: Щомісяця
quarterly: Щокварталу
diff --git a/config/locales/views/reports/vi.yml b/config/locales/views/reports/vi.yml
index 21ad5d6983..9f612f81a7 100644
--- a/config/locales/views/reports/vi.yml
+++ b/config/locales/views/reports/vi.yml
@@ -6,7 +6,6 @@ vi:
subtitle: Thông tin chi tiết toàn diện về sức khỏe tài chính của bạn
export: Xuất CSV
print_report: In báo cáo
- toggle_section: "Bật/tắt hiển thị phần"
periods:
monthly: Hàng tháng
quarterly: Hàng quý
diff --git a/config/locales/views/reports/zh-CN.yml b/config/locales/views/reports/zh-CN.yml
index f2072493cb..c839476bdd 100644
--- a/config/locales/views/reports/zh-CN.yml
+++ b/config/locales/views/reports/zh-CN.yml
@@ -7,7 +7,6 @@ zh-CN:
export: 导出 CSV
print_report: 打印报表
sections_aria: 报表各部分
- toggle_section: 切换模块可见性
periods:
monthly: 按月
quarterly: 按季度
diff --git a/config/locales/views/reports/zh-TW.yml b/config/locales/views/reports/zh-TW.yml
index 04b3a8f4d1..45816f9d3e 100644
--- a/config/locales/views/reports/zh-TW.yml
+++ b/config/locales/views/reports/zh-TW.yml
@@ -6,7 +6,6 @@ zh-TW:
subtitle: 深入洞察您的財務健康狀況
export: 匯出 CSV
print_report: 列印報表
- toggle_section: 切換區塊顯示狀態
periods:
monthly: 按月
quarterly: 按季
diff --git a/config/routes.rb b/config/routes.rb
index eee35a2ecf..680e86f141 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -505,6 +505,11 @@ Rails.application.routes.draw do
# Hub page fronting budgets + goals under a single "Plan" nav entry.
resource :plan, only: :show
+ # Family-wide investment hub, built on the Reports section framework.
+ resource :portfolio, only: :show do
+ patch :update_preferences
+ end
+
resources :budgets, only: %i[index show edit update], param: :month_year do
post :copy_previous, on: :member
get :picker, on: :collection
diff --git a/test/controllers/bills_controller_test.rb b/test/controllers/bills_controller_test.rb
index f66108f815..7a41ede665 100644
--- a/test/controllers/bills_controller_test.rb
+++ b/test/controllers/bills_controller_test.rb
@@ -2231,7 +2231,7 @@ class BillsControllerTest < ActionDispatch::IntegrationTest
assert_select "#{routine} .px-4.py-2\\.5", text: /#{I18n.t("bills.index.notices_routine", count: 2)}/
assert_select "#{routine}[class^='bg-'], #{routine}[class*=' bg-']", count: 0
# One chevron for both folds, not copies that drift apart.
- chevron = "svg[class*='group-open:rotate-90']"
+ chevron = "svg[class*=':rotate-90']"
chevrons = css_select("[data-persisted-disclosure-key-value='bills-suggested'] > summary #{chevron}, #{routine} #{chevron}")
assert_equal 2, chevrons.size
assert_equal 1, chevrons.map(&:to_html).uniq.size, "the folds' chevrons differ: #{chevrons.map { |svg| svg["class"] }.inspect}"
diff --git a/test/controllers/portfolios_controller_test.rb b/test/controllers/portfolios_controller_test.rb
new file mode 100644
index 0000000000..e9bc655a6d
--- /dev/null
+++ b/test/controllers/portfolios_controller_test.rb
@@ -0,0 +1,311 @@
+require "test_helper"
+
+class PortfoliosControllerTest < ActionDispatch::IntegrationTest
+ include SqlQueryCapture
+
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ enable_preview(@user)
+ sign_in @user
+ ensure_tailwind_build
+ end
+
+ test "redirects users without preview access to the dashboard" do
+ disable_preview(@user)
+
+ get portfolio_path
+
+ assert_redirected_to root_path
+ assert_equal I18n.t("preview.not_enabled"), flash[:alert]
+ end
+
+ # The class-level gate covers every action, so the one endpoint that writes
+ # cannot save preferences for a page its caller is not allowed to see.
+ test "preference writes are preview-gated like the page" do
+ disable_preview(@user)
+
+ patch update_preferences_portfolio_path,
+ params: { preferences: { portfolio_section_order: %w[accounts] } },
+ as: :json
+
+ assert_redirected_to root_path
+ assert_nil @user.reload.preferences["portfolio_section_order"]
+ end
+
+ test "a request the gate turns away does not save its period as the user's default" do
+ disable_preview(@user)
+ @user.update!(default_period: "last_30_days")
+
+ get portfolio_path(period: "last_5_years")
+
+ assert_redirected_to root_path
+ assert_equal "last_30_days", @user.reload.default_period
+ end
+
+ test "renders the hub and the accounts section" do
+ get portfolio_path
+
+ assert_response :success
+ assert_select "h1", text: I18n.t("portfolios.show.title")
+ assert_equal %w[accounts], css_select("[data-section-key]").map { |node| node["data-section-key"] }
+ assert_select "header + div[role=list]"
+ end
+
+ # No section reads the period yet, so the page offers no control that
+ # would change nothing.
+ test "the page carries no period picker" do
+ get portfolio_path(period: "last_5_years")
+
+ assert_response :success
+ assert_select "button[aria-label=?]", I18n.t("UI.period_picker.aria_label", period: "5Y"), count: 0
+ assert_select "a[href^=?]", "#{portfolio_path}?period=", count: 0
+ end
+
+ test "an unknown period falls back rather than erroring" do
+ get portfolio_path(period: "not_a_period")
+
+ assert_response :success
+ end
+
+ test "shows an empty state with an add-account link when the family has no investment accounts" do
+ user = users(:empty)
+ enable_preview(user)
+ sign_in user
+ assert_empty InvestmentStatement.new(user.family, user: user).investment_accounts
+
+ get portfolio_path
+
+ assert_response :success
+ assert_match I18n.t("portfolios.empty_state.title"), response.body
+ assert_select "a[href=?]", new_account_path
+ assert_select "[data-section-key]", count: 0
+ end
+
+ test "saves the section order and collapsed set under the portfolio namespace only" do
+ patch update_preferences_portfolio_path,
+ params: { preferences: { portfolio_section_order: %w[accounts], portfolio_collapsed_sections: { accounts: true } } },
+ as: :json
+
+ assert_response :ok
+ @user.reload
+ assert_equal %w[accounts], @user.preferences["portfolio_section_order"]
+ assert @user.section_collapsed?("portfolio", "accounts")
+ assert_nil @user.preferences["reports_section_order"]
+ assert_nil @user.preferences["reports_collapsed_sections"]
+ end
+
+ test "drops preference keys that are not the portfolio's own" do
+ patch update_preferences_portfolio_path,
+ params: { preferences: { reports_section_order: %w[x] } },
+ as: :json
+
+ assert_response :ok
+ assert_nil @user.reload.preferences["reports_section_order"]
+ end
+
+ # `kpis` is a key not in Portfolio::SectionRegistry::KEYS, and is dropped
+ # like any other unknown key.
+ test "drops section keys the registry does not know, in both shapes" do
+ patch update_preferences_portfolio_path,
+ params: { preferences: { portfolio_section_order: %w[kpis nonsense accounts], portfolio_collapsed_sections: { accounts: true, kpis: true, nonsense: true } } },
+ as: :json
+
+ assert_response :ok
+ @user.reload
+ assert_equal %w[accounts], @user.preferences["portfolio_section_order"]
+ assert_equal({ "accounts" => true }, @user.preferences["portfolio_collapsed_sections"],
+ "an unknown key must not be written into the user's preferences")
+ end
+
+ test "a preferences body that is not an object is refused and writes nothing" do
+ before = @user.reload.preferences.dup
+
+ patch update_preferences_portfolio_path, params: { preferences: "foo" }
+
+ assert_response :bad_request
+ assert_equal before, @user.reload.preferences
+ end
+
+ test "an order that is not a list leaves the saved order alone" do
+ @user.update!(preferences: @user.preferences.merge("portfolio_section_order" => %w[accounts]))
+
+ [ "accounts", { accounts: 1 } ].each do |order|
+ patch update_preferences_portfolio_path, params: { preferences: { portfolio_section_order: order } }, as: :json
+
+ assert_response :ok
+ assert_equal %w[accounts], @user.reload.preferences["portfolio_section_order"], "order #{order.inspect} must not be stored"
+ end
+ end
+
+ test "deduplicates the saved order, first occurrence winning" do
+ patch update_preferences_portfolio_path,
+ params: { preferences: { portfolio_section_order: %w[accounts accounts] } },
+ as: :json
+
+ assert_response :ok
+ assert_equal %w[accounts], @user.reload.preferences["portfolio_section_order"]
+ end
+
+ test "a collapsed payload that is not an object is dropped rather than raised on" do
+ patch update_preferences_portfolio_path,
+ params: { preferences: { portfolio_collapsed_sections: "true", portfolio_section_order: %w[accounts] } },
+ as: :json
+
+ assert_response :ok
+ @user.reload
+ assert_nil @user.preferences["portfolio_collapsed_sections"]
+ assert_equal %w[accounts], @user.preferences["portfolio_section_order"]
+ end
+
+ test "renders sections collapsed where the user left them" do
+ get portfolio_path
+ assert_select "[data-section-key=accounts][data-reports-section-collapsed-value=?]", "false"
+ assert_select "[data-section-key=accounts] > details[open] > summary"
+
+ @user.update_section_preferences("portfolio", collapsed: { "accounts" => true })
+ get portfolio_path
+
+ assert_response :success
+ assert_select "[data-section-key=accounts][data-reports-section-collapsed-value=?]", "true"
+ assert_select "[data-section-key=accounts] > details:not([open]) > summary"
+ end
+
+ test "the sortable container posts to the portfolio endpoint under its own namespace" do
+ get portfolio_path
+
+ assert_response :success
+ assert_select "[data-controller~=sortable-list][data-sortable-list-url-value=?][data-sortable-list-param-value=?]",
+ update_preferences_portfolio_path, "preferences.portfolio_section_order"
+ assert_select "[data-section-key=accounts][data-reports-section-url-value=?][data-reports-section-preference-key-value=?]",
+ update_preferences_portfolio_path, "portfolio"
+ end
+
+ test "the nav shows Portfolio on desktop only, and never without the preview flag" do
+ get portfolio_path
+
+ assert_response :success
+ assert_select "ul li a[href=?]", portfolio_path, minimum: 1
+ assert_select "nav[data-viewport-target=bottomNav] a[href=?]", portfolio_path, count: 0
+
+ disable_preview(@user)
+ get root_path
+
+ assert_response :success
+ assert_select "a[href=?]", portfolio_path, count: 0
+ end
+
+ # Portfolio is the only desktop-only entry, so every other item still
+ # reaches both bars: the mobile bar is the desktop rail without Portfolio,
+ # plus the mobile-only Assistant.
+ test "every other nav item still renders in both bars" do
+ get root_path
+ assert_response :success
+
+ desktop = css_select("ul li a").map { |link| link["href"] }
+ mobile = css_select("nav[data-viewport-target=bottomNav] a").map { |link| link["href"] }
+
+ assert_includes desktop, portfolio_path
+ assert_equal desktop - [ portfolio_path ], mobile - [ chats_path ]
+ assert_includes mobile, chats_path if @family.assistant_enabled?
+ end
+
+ test "accounts grid links every countable investment account to its holdings tab and skips excluded shares" do
+ other = users(:family_member)
+ shared = @family.accounts.create!(name: "Shared brokerage", balance: 500, currency: "USD", accountable: Investment.new, owner: other)
+ shared.share_with!(@user, permission: "read_only", include_in_finances: false)
+
+ get portfolio_path
+ assert_response :success
+
+ assert_select "#portfolio-accounts a[href=?]", account_path(accounts(:investment), tab: "holdings")
+ assert_select "#portfolio-accounts a[href=?]", account_path(shared, tab: "holdings"), count: 0
+ assert_equal InvestmentStatement.new(@family, user: @user).investment_accounts.count, css_select("#portfolio-accounts a").size
+ # The cards sit in a narrow grid cell, so they truncate and show focus.
+ assert_select "#portfolio-accounts a.focus-ring p.truncate", minimum: 2
+ end
+
+ # Each card's logo falls back to its provider's, read through
+ # AccountProvider#provider, so the provider records are loaded with the
+ # accounts rather than once per card.
+ test "the accounts grid loads provider-linked accounts without a query per card" do
+ link_investment_account(0)
+ one = provider_queries { get portfolio_path }
+
+ link_investment_account(1)
+ link_investment_account(2)
+ three = provider_queries { get portfolio_path }
+
+ assert_response :success
+ assert_select "#portfolio-accounts a", minimum: 3
+ assert_equal one, three, "loading the linked accounts' providers grew with the number of cards"
+ end
+
+ test "the investment accounts are queried once per page" do
+ queries = capture_sql_queries { get portfolio_path }
+
+ assert_response :success
+ assert_select "#portfolio-accounts a", minimum: 1
+ # The cards select `accounts.*`; an `any?`/`empty?` check selects `1 AS one`.
+ # The layout's sidebar reads accounts with its own select list.
+ matching = queries.select do |sql|
+ sql.match?(/\ASELECT (DISTINCT )?("accounts"\.\*|1 AS one) FROM "accounts"/) && sql.include?(%("accounts"."exclude_from_reports"))
+ end
+ assert_equal 1, matching.size, matching.join("\n")
+ end
+
+ # Without an id tiebreaker Postgres may return same-named accounts in any
+ # order, so the cards could swap places between requests. The ids descend
+ # in insertion order, so storage order and id order disagree.
+ test "accounts with the same name are listed in id order" do
+ same = %w[f d b].map do |digit|
+ @family.accounts.create!(id: "#{digit * 8}-0000-4000-8000-000000000000", name: "Same brokerage", balance: 100,
+ currency: "USD", accountable: Investment.new, owner: @user)
+ end
+
+ get portfolio_path
+
+ assert_response :success
+ hrefs = css_select("#portfolio-accounts a").map { |a| a["href"] }
+ shown = hrefs.filter_map { |href| same.find { |account| href == account_path(account, tab: "holdings") } }
+ assert_equal same.sort_by(&:id), shown
+ end
+
+ # The empty state shows whenever the viewer counts no investment account,
+ # which includes a family whose investment accounts are all excluded.
+ test "the empty state does not claim the family has no investment accounts" do
+ user = users(:empty)
+ enable_preview(user)
+ sign_in user
+ user.family.accounts.create!(name: "Excluded brokerage", balance: 100, currency: "USD", accountable: Investment.new,
+ owner: user, exclude_from_reports: true)
+
+ get portfolio_path
+
+ assert_response :success
+ assert_select "[data-section-key]", count: 0
+ assert_match I18n.t("portfolios.empty_state.title"), response.body
+ assert_no_match(/yet/i, I18n.t("portfolios.empty_state.title"))
+ end
+
+ private
+ def enable_preview(user)
+ user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true))
+ end
+
+ def disable_preview(user)
+ user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => false))
+ end
+
+ def link_investment_account(index)
+ account = @family.accounts.create!(name: "Linked brokerage #{index}", balance: 1_000, currency: "USD",
+ accountable: Investment.new, owner: @user)
+ provider = LunchflowAccount.create!(lunchflow_item: lunchflow_items(:one), account_id: "lf_portfolio_#{index}",
+ name: account.name, currency: "USD")
+ AccountProvider.create!(account: account, provider: provider)
+ end
+
+ def provider_queries(&block)
+ capture_sql_queries(&block).count { |sql| sql.include?(%(FROM "lunchflow_accounts")) }
+ end
+end
diff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rb
index acd397e2e7..f56e9ac392 100644
--- a/test/controllers/reports_controller_test.rb
+++ b/test/controllers/reports_controller_test.rb
@@ -22,6 +22,22 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
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"
+ assert_select "[data-section-key=trends_insights] > details:not([open])"
+ assert_select "[data-section-key=transactions_breakdown] > details[open]"
+ end
+
+ # Reports renders the shared section list with its own endpoint, param and
+ # labels, and leaves the collapse control on its default endpoint.
+ test "the section list posts to the reports endpoint under the reports keys" do
+ get reports_path
+
+ assert_response :success
+ assert_select "[data-controller~=sortable-list][data-sortable-list-url-value=?][data-sortable-list-param-value=?][aria-label=?]",
+ update_preferences_reports_path, "preferences.reports_section_order", I18n.t("reports.index.sections_aria")
+ assert_select "[data-section-key=net_worth][aria-label=?]",
+ "#{I18n.t("reports.net_worth.title")} section. Press Enter or Space to grab for reordering, then use arrow keys to move."
+ assert_select "[data-section-key=net_worth] > details > summary h2", text: I18n.t("reports.net_worth.title")
+ assert_select "[data-reports-section-url-value], [data-reports-section-preference-key-value]", count: 0
end
test "the reports preferences endpoint stores order and collapse under the reports keys" do
@@ -37,6 +53,36 @@ class ReportsControllerTest < ActionDispatch::IntegrationTest
assert_equal({ "net_worth" => true, "trends_insights" => true }, @user.preferences["reports_collapsed_sections"])
end
+ test "a scalar section order is not stored and the page still renders" do
+ @user.update_columns(preferences: (@user.preferences || {}).merge("reports_section_order" => %w[trends_insights net_worth]))
+
+ patch update_preferences_reports_path, params: { preferences: { reports_section_order: "x" } }, as: :json
+
+ assert_response :ok
+ assert_equal %w[trends_insights net_worth], @user.reload.preferences["reports_section_order"]
+
+ get reports_path
+ assert_response :success
+ end
+
+ test "a scalar collapsed set is not stored" do
+ @user.update_columns(preferences: (@user.preferences || {}).merge("reports_collapsed_sections" => { "net_worth" => true }))
+
+ patch update_preferences_reports_path, params: { preferences: { reports_collapsed_sections: "net_worth" } }, as: :json
+
+ assert_response :ok
+ assert_equal({ "net_worth" => true }, @user.reload.preferences["reports_collapsed_sections"])
+ end
+
+ test "a preferences body that is not an object is refused and writes nothing" do
+ before = @user.reload.preferences
+
+ patch update_preferences_reports_path, params: { preferences: "x" }, as: :json
+
+ assert_response :bad_request
+ assert_equal before, @user.reload.preferences
+ 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/helpers/application_helper_test.rb b/test/helpers/application_helper_test.rb
index 61876554fe..b20703108f 100644
--- a/test/helpers/application_helper_test.rb
+++ b/test/helpers/application_helper_test.rb
@@ -131,4 +131,21 @@ class ApplicationHelperTest < ActionView::TestCase
test "#mask_last4 handles values shorter than 4 characters" do
assert_equal "•••12", mask_last4("12")
end
+
+ # `group-open:` matches any open ancestor `.group`, so a chevron inside a
+ # closed disclosure nested in an open one would show as open.
+ test "#disclosure_chevron follows its own details element" do
+ classes = nil
+ singleton_class.send(:define_method, :lucide_icon) do |_key, **opts|
+ classes = CGI.unescapeHTML(opts[:class].to_s)
+ "<svg></svg>".html_safe
+ end
+
+ disclosure_chevron
+
+ assert_includes classes, "[details[open]>summary_&]:rotate-90"
+ assert_not_includes classes, "group-open:"
+ ensure
+ singleton_class.send(:remove_method, :lucide_icon) if singleton_class.method_defined?(:lucide_icon)
+ end
end
diff --git a/test/models/portfolio/section_registry_test.rb b/test/models/portfolio/section_registry_test.rb
new file mode 100644
index 0000000000..8a4a5e353d
--- /dev/null
+++ b/test/models/portfolio/section_registry_test.rb
@@ -0,0 +1,91 @@
+require "test_helper"
+
+class Portfolio::SectionRegistryTest < ActiveSupport::TestCase
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @period = Period.last_30_days
+ @as_of = Date.current
+ @statement = InvestmentStatement.new(@family, user: @user)
+ end
+
+ test "registers the built-in sections with their partials and locals" do
+ sections = registry.sections
+
+ assert_equal Portfolio::SectionRegistry::KEYS, sections.map { |s| s[:key] }
+ assert_equal %w[portfolios/accounts], sections.map { |s| s[:partial] }
+ assert sections.all? { |s| s[:collapsible] }
+
+ # Every partial gets its locals passed in: none of them reaches for
+ # Date.current or Current.family on its own.
+ sections.each do |section|
+ assert_equal({ statement: @statement, period: @period, as_of: @as_of }, section[:locals].slice(:statement, :period, :as_of),
+ "#{section[:key]} must receive the shared locals rather than reading them itself")
+ end
+ end
+
+ test "the accounts section is visible only when the family has investment accounts" do
+ assert registry.sections.find { |s| s[:key] == "accounts" }[:visible]
+
+ empty_statement = InvestmentStatement.new(families(:empty), user: nil)
+ empty = Portfolio::SectionRegistry.new(statement: empty_statement, period: @period, as_of: @as_of, user: @user).sections
+ assert_not empty.find { |s| s[:key] == "accounts" }[:visible]
+ end
+
+ # Created in reverse name order, so the cards come back by name only if the
+ # query asks for it.
+ test "the accounts section lists the cards in name order" do
+ zeta = @family.accounts.create!(name: "Zeta brokerage", balance: 100, currency: "USD", accountable: Investment.new, owner: @user)
+ alpha = @family.accounts.create!(name: "Alpha brokerage", balance: 100, currency: "USD", accountable: Investment.new, owner: @user)
+ @statement = InvestmentStatement.new(@family, user: @user)
+
+ cards = registry.sections.find { |s| s[:key] == "accounts" }[:locals][:accounts]
+
+ assert_includes cards, zeta
+ assert_operator cards.index(alpha), :<, cards.index(zeta)
+ assert_equal @statement.investment_accounts.to_a.sort_by(&:id), cards.sort_by(&:id),
+ "the cards must be exactly the statement's investment accounts"
+ end
+
+ test "orders sections by the user's saved order, appending anything it omits" do
+ @user.update_section_preferences("portfolio", order: %w[stub])
+
+ assert_equal %w[stub accounts], registry(extra_sections: [ stub_section ]).sections.map { |s| s[:key] }
+ end
+
+ test "a saved order that repeats a key renders that section once" do
+ @user.update_section_preferences("portfolio", order: %w[stub accounts stub])
+
+ keys = registry(extra_sections: [ stub_section ]).sections.map { |s| s[:key] }
+
+ assert_equal %w[stub accounts], keys
+ end
+
+ test "ignores keys in the saved order that no longer exist" do
+ @user.update_section_preferences("portfolio", order: %w[gone accounts])
+
+ assert_equal %w[accounts], registry.sections.map { |s| s[:key] }
+ end
+
+ test "appends extra sections after the built-ins" do
+ sections = registry(extra_sections: [ stub_section ]).sections
+
+ assert_equal %w[accounts stub], sections.map { |s| s[:key] }
+ end
+
+ private
+ def stub_section
+ { key: "stub", title: "portfolios.sections.accounts", partial: "portfolios/accounts",
+ locals: {}, visible: true, collapsible: true }
+ end
+
+ def registry(extra_sections: [])
+ Portfolio::SectionRegistry.new(
+ statement: @statement,
+ period: @period,
+ as_of: @as_of,
+ user: @user,
+ extra_sections: extra_sections
+ )
+ end
+end
diff --git a/test/models/user_test.rb b/test/models/user_test.rb
index 42dddccbae..08dce692a9 100644
--- a/test/models/user_test.rb
+++ b/test/models/user_test.rb
@@ -866,6 +866,40 @@ class UserTest < ActiveSupport::TestCase
assert_equal %w[reports_collapsed_sections reports_section_order], @user.preferences.keys.sort
end
+ test "section preferences are namespaced so two pages never touch each other's keys" do
+ @user.update!(preferences: {})
+
+ @user.update_section_preferences("reports", order: %w[transactions_breakdown], collapsed: { "trends_insights" => true })
+ @user.update_section_preferences("portfolio", order: %w[accounts], collapsed: { "accounts" => true })
+ @user.reload
+
+ assert_equal %w[transactions_breakdown], @user.section_order("reports")
+ assert_equal %w[accounts], @user.section_order("portfolio")
+ assert @user.section_collapsed?("reports", "trends_insights")
+ assert_not @user.section_collapsed?("reports", "accounts")
+ assert @user.section_collapsed?("portfolio", "accounts")
+ assert_not @user.section_collapsed?("portfolio", "trends_insights")
+
+ assert_equal %w[transactions_breakdown], @user.reports_section_order
+ assert @user.reports_section_collapsed?("trends_insights")
+ assert_equal %w[reports_section_order reports_collapsed_sections portfolio_section_order portfolio_collapsed_sections].sort,
+ @user.preferences.keys.sort
+ end
+
+ test "the portfolio order defaults to the registry's keys and collapsing writes no order" do
+ @user.update!(preferences: {})
+
+ assert_equal Portfolio::SectionRegistry::KEYS, @user.section_order("portfolio")
+ assert_not @user.section_collapsed?("portfolio", "accounts")
+
+ @user.update_section_preferences("portfolio", collapsed: { "accounts" => true })
+ @user.reload
+
+ assert @user.section_collapsed?("portfolio", "accounts")
+ assert_nil @user.preferences["portfolio_section_order"], "collapsing must not write an order"
+ assert_equal Portfolio::SectionRegistry::KEYS, @user.section_order("portfolio")
+ 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") }
@@ -882,6 +916,48 @@ class UserTest < ActiveSupport::TestCase
assert_not @user.section_collapsed?("reports", "net_worth")
end
+ # Both pages' endpoints write through this method, so the shapes the readers
+ # rely on (an array of keys, a hash of key => flag) are enforced here.
+ test "section preferences store only an array of keys and a hash of flags" do
+ @user.update!(preferences: { "reports_section_order" => %w[net_worth], "reports_collapsed_sections" => { "net_worth" => true } })
+
+ @user.update_section_preferences("reports", order: "net_worth", collapsed: "net_worth")
+ @user.reload
+
+ assert_equal %w[net_worth], @user.preferences["reports_section_order"], "a scalar order must not replace the stored one"
+ assert_equal({ "net_worth" => true }, @user.preferences["reports_collapsed_sections"], "a scalar collapsed set must not be stored")
+
+ @user.update_section_preferences("reports", order: [ "trends_insights", :net_worth, "trends_insights" ],
+ collapsed: { "trends_insights" => "true", net_worth: "0" })
+ @user.reload
+
+ assert_equal %w[trends_insights net_worth], @user.preferences["reports_section_order"]
+ assert_equal({ "net_worth" => false, "trends_insights" => true }, @user.preferences["reports_collapsed_sections"])
+ end
+
+ test "a stored section order that repeats a key reads each key once" do
+ @user.update_columns(preferences: { "reports_section_order" => %w[net_worth trends_insights net_worth] })
+
+ assert_equal %w[net_worth trends_insights], @user.section_order("reports")
+ end
+
+ test "a stored section order that is not an array reads as the default" do
+ @user.update_columns(preferences: { "reports_section_order" => "net_worth", "portfolio_section_order" => { "a" => 1 } })
+
+ assert_equal %w[trends_insights transactions_breakdown], @user.section_order("reports")
+ assert_equal Portfolio::SectionRegistry::KEYS, @user.section_order("portfolio")
+ end
+
+ test "a stored collapsed set that is not a hash reads as nothing collapsed and is replaced by a toggle" do
+ @user.update_columns(preferences: { "reports_collapsed_sections" => "net_worth" })
+
+ assert_not @user.section_collapsed?("reports", "net_worth")
+
+ @user.update_section_preferences("reports", collapsed: { "net_worth" => true })
+
+ assert_equal({ "net_worth" => true }, @user.reload.preferences["reports_collapsed_sections"])
+ end
+
test "handles missing nested keys in preferences for collapsed sections" do
@user.update!(preferences: { "section_order" => %w[cashflow] })
diff --git a/test/system/portfolios_test.rb b/test/system/portfolios_test.rb
new file mode 100644
index 0000000000..b869aba0cb
--- /dev/null
+++ b/test/system/portfolios_test.rb
@@ -0,0 +1,28 @@
+require "application_system_test_case"
+
+class PortfoliosTest < ApplicationSystemTestCase
+ setup do
+ @user = users(:family_admin)
+ @user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => true))
+ sign_in @user
+ end
+
+ # The collapse state is saved with the page's CSRF token and nothing is
+ # saved without one, and the test environment renders none unless forgery
+ # protection is on.
+ test "collapsing a section saves it under the portfolio keys, not the Reports ones" do
+ original = ActionController::Base.allow_forgery_protection
+ ActionController::Base.allow_forgery_protection = true
+ visit portfolio_path
+ record_saved_section_order
+
+ find("section[data-section-key='accounts'] summary").click
+
+ assert_selector "section[data-section-key='accounts'] details:not([open])"
+ assert_selector "html[data-order-saved='200']"
+ assert_equal true, @user.reload.preferences.dig("portfolio_collapsed_sections", "accounts")
+ assert_nil @user.preferences["reports_collapsed_sections"]
+ ensure
+ ActionController::Base.allow_forgery_protection = original
+ end
+end
diff --git a/test/system/reports_test.rb b/test/system/reports_test.rb
index 9f49b65ea1..b3ec3e0ae5 100644
--- a/test/system/reports_test.rb
+++ b/test/system/reports_test.rb
@@ -100,26 +100,114 @@ class ReportsTest < ApplicationSystemTestCase
assert_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.
+ # The collapse state is saved with the page's CSRF token and nothing is
+ # saved 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
+ with_forgery_protection do
+ 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
+ find("section[data-section-key='transactions_breakdown'] summary").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
+ assert_selector "section[data-section-key='transactions_breakdown'] details:not([open])"
+ assert_selector "html[data-order-saved='200']"
+ assert_equal true, user.reload.preferences.dig("reports_collapsed_sections", "transactions_breakdown")
+ end
+ end
+
+ test "expanding a collapsed section saves it as open" do
+ with_forgery_protection do
+ user = users(:family_admin)
+ user.update_section_preferences("reports", collapsed: { "transactions_breakdown" => true })
+ visit reports_path(period_type: :monthly)
+ record_saved_section_order
+
+ find("section[data-section-key='transactions_breakdown'] details:not([open]) > summary").click
+
+ assert_selector "section[data-section-key='transactions_breakdown'] details[open]"
+ assert_selector "html[data-order-saved='200']"
+ assert_equal false, user.reload.preferences.dig("reports_collapsed_sections", "transactions_breakdown")
+ end
+ end
+
+ # A <details> rendered open fires `toggle` once it is in the page. Only a
+ # change the user makes is saved, so the one collapse is the only request.
+ test "rendering the sections saves no collapse state" do
+ with_forgery_protection do
+ visit reports_path(period_type: :monthly)
+ record_saved_section_order
+ # A Turbo visit renders the sections again with the request counter
+ # already in place.
+ page.execute_script("document.body.dataset.before = true; Turbo.visit(window.location.href)")
+ assert_no_selector "body[data-before]"
+
+ find("section[data-section-key='transactions_breakdown'] summary").click
+
+ assert_selector "html[data-order-saved='200']"
+ assert_equal "1", page.evaluate_script("document.documentElement.dataset.orderRequests")
+ assert_equal({ "transactions_breakdown" => true }, users(:family_admin).reload.preferences["reports_collapsed_sections"])
+ end
+ end
+
+ # The header is a <summary>, its own tab stop after the section's grab stop:
+ # Enter there opens and closes the section and leaves reordering alone.
+ test "Enter on a section header collapses it instead of grabbing the section" do
+ section = find("section[data-section-key='transactions_breakdown']")
+ section.find("summary").send_keys(:enter)
+
+ assert_selector "section[data-section-key='transactions_breakdown'] details:not([open])"
+ assert_equal "false", section["aria-grabbed"]
+ end
+
+ # The whole header is the toggle, and a press-and-hold on it starts a drag.
+ # Letting go must not also open or close the section; a plain tap still does.
+ test "releasing a press-and-hold leaves the section as it was" do
+ section = find("section[data-section-key='transactions_breakdown']")
+ summary = section.find("summary")
+ page.execute_script(<<~JS, summary)
+ window.summaryClicks = 0;
+ arguments[0].addEventListener("click", () => window.summaryClicks++);
+ JS
+
+ touch(summary, hold: 1.2)
+ touch(summary, hold: 0)
+
+ assert_selector "section[data-section-key='transactions_breakdown'] details:not([open])"
+ assert_equal 1, page.evaluate_script("window.summaryClicks")
+ end
+
+ # Each section's card is a <details>, so a chevron inside it that turns with
+ # `group-open:` would follow the open section instead of its own panel.
+ test "a closed disclosure inside an open section shows its chevron closed" do
+ chevron = find("section[data-section-key='investment_performance'] details[open] details:not([open]) > summary svg", match: :first)
+
+ assert_equal "none", page.evaluate_script("getComputedStyle(arguments[0]).rotate", chevron)
end
private
def clicked_hotkeys
page.evaluate_script("window.clickedHotkeys")
end
+
+ def with_forgery_protection
+ original = ActionController::Base.allow_forgery_protection
+ ActionController::Base.allow_forgery_protection = true
+ yield
+ ensure
+ ActionController::Base.allow_forgery_protection = original
+ end
+
+ # Presses a finger on the element's centre for `hold` seconds, through
+ # the browser's touch input, so the browser decides whether a click follows.
+ def touch(element, hold:)
+ finger = Selenium::WebDriver::Interactions.pointer(:touch, name: "finger")
+ page.driver.browser.action(devices: [ finger ])
+ .move_to(element.native, device: "finger")
+ .pointer_down(:left, device: "finger")
+ .pause(device: finger, duration: hold)
+ .pointer_up(:left, device: "finger")
+ .perform
+ end
end
diff --git a/test/views/accounts/balance_card_view_test.rb b/test/views/accounts/balance_card_view_test.rb
new file mode 100644
index 0000000000..0c92e2c413
--- /dev/null
+++ b/test/views/accounts/balance_card_view_test.rb
@@ -0,0 +1,36 @@
+require "test_helper"
+
+class AccountsBalanceCardViewTest < ActionView::TestCase
+ # The fixture holds 10000 USD, so a card that drops the amount or its
+ # currency, or shows zero, fails the text match.
+ setup do
+ @account = accounts(:investment)
+ end
+
+ # The Reports investment card renders with the defaults, so these are the
+ # classes that page has always drawn.
+ test "the defaults draw the plain card" do
+ render partial: "accounts/balance_card", locals: { account: @account, href: "/accounts/1" }
+
+ assert_select "a[href='/accounts/1'][class=?]", "bg-container-inset rounded-lg p-4 flex items-center justify-between hover:bg-container-hover transition-colors" do
+ assert_select "> div[class=?]", "flex items-center gap-3" do
+ assert_select "> div:not([class])" do
+ assert_select "p[class=?]", "font-medium text-primary text-sm", text: @account.name
+ assert_select "p[class=?]", "text-xs text-secondary", text: @account.short_subtype_label
+ end
+ end
+ assert_select "> p[class=?]", "font-medium text-primary privacy-sensitive", text: "$10,000.00"
+ end
+ end
+
+ test "truncate and focus_ring fit the card to a narrow cell and show keyboard focus" do
+ render partial: "accounts/balance_card", locals: { account: @account, href: "/accounts/1", truncate: true, focus_ring: true }
+
+ assert_select "a.focus-ring" do
+ assert_select "> div.min-w-0 > div.min-w-0" do
+ assert_select "p.truncate", count: 2
+ end
+ assert_select "> p.whitespace-nowrap", text: "$10,000.00"
+ end
+ end
+end
diff --git a/test/views/layouts/shared/nav_item_view_test.rb b/test/views/layouts/shared/nav_item_view_test.rb
index b03bcbf376..26694a89a2 100644
--- a/test/views/layouts/shared/nav_item_view_test.rb
+++ b/test/views/layouts/shared/nav_item_view_test.rb
@@ -24,4 +24,15 @@ class NavItemViewTest < ActionView::TestCase
assert_not_includes html, "aria-current"
end
+
+ # The layout filters desktop-only items out of the bottom bar; the partial
+ # itself accepts the flag and draws the same link with or without it.
+ test "desktop_only defaults off and leaves the item's markup unchanged" do
+ locals = { name: "Reports", path: "/reports", icon: "chart-bar", icon_custom: false, active: false }
+
+ without_flag = render(partial: "layouts/shared/nav_item", locals: locals)
+
+ assert_equal without_flag, render(partial: "layouts/shared/nav_item", locals: locals.merge(desktop_only: false))
+ assert_equal without_flag, render(partial: "layouts/shared/nav_item", locals: locals.merge(desktop_only: true))
+ end
end