The personal finance app for everyone (by everyone)
Ruby
Add the holdings table section to the portfolio page (#5306)
jaysbeekay3f6dcaff03a6
diff --git a/app/components/DS/table.html.erb b/app/components/DS/table.html.erbindex d411633ecf..cf2451ab5a 100644--- a/app/components/DS/table.html.erb+++ b/app/components/DS/table.html.erb@@ -18,6 +18,11 @@<%= column.cell(row, index) %><% end %><% end %>+ <% if (detail = row_detail_content(row)) %>+ <tr id="<%= row_detail_id(index) %>" hidden>+ <td colspan="<%= columns.size %>" class="px-4 pb-4"><%= detail %></td>+ </tr>+ <% end %><% end %></tbody></table>diff --git a/app/components/DS/table.rb b/app/components/DS/table.rbindex 47695befec..1a464b6af6 100644--- a/app/components/DS/table.rb+++ b/app/components/DS/table.rb@@ -18,7 +18,7 @@ class DS::Table < DesignSystemComponentDS::Table::Column.new(header, cell: cell, sticky: sticky_header, inset: inset, **options)end- attr_reader :rows, :inset, :sticky_header, :label, :row_class, :row_opts, :opts+ attr_reader :rows, :inset, :sticky_header, :label, :row_class, :row_opts, :row_detail, :opts# @param rows [Enumerable] the records, one table row each# @param inset [Boolean] frame the table in container-inset, for a table that@@ -37,14 +37,25 @@ class DS::Table < DesignSystemComponent# @param row_opts [Proc, nil] called with each row, returns extra attributes for# its <tr>, e.g. a `clickable-row` controller so a click anywhere on the row# opens the link in its name cell+ # @param row_detail [Proc, nil] called with each row, returns markup for a+ # hidden row rendered straight after it and spanning every column, or nil+ # for none. A control in the row reveals it by pointing aria-controls at+ # #row_detail_id, e.g. a holding's per-account positions. Requires an `id:`,+ # which prefixes the detail ids so two tables on a page cannot collide.# @param opts [Hash] forwarded to the outer element; :class merges with the base classes- def initialize(rows:, inset: false, sticky_header: false, label: nil, row_class: nil, row_opts: nil, **opts)+ def initialize(rows:, inset: false, sticky_header: false, label: nil, row_class: nil, row_opts: nil, row_detail: nil, **opts)+ raise ArgumentError, "DS::Table needs an id: when given row_detail" if row_detail && opts[:id].blank?+ # The id prefixes the detail ids that aria-controls names, and a space+ # there reads as a second id.+ raise ArgumentError, "DS::Table's id must not contain whitespace when given row_detail" if row_detail && opts[:id].to_s.match?(/\s/)+@rows = rows@inset = inset@sticky_header = sticky_header@label = label@row_class = row_class@row_opts = row_opts+ @row_detail = row_detail@opts = optsend@@ -83,4 +94,14 @@ class DS::Table < DesignSystemComponentdef row_attributes(row)row_opts&.call(row) || {}end++ def row_detail_content(row)+ row_detail&.call(row).presence+ end++ # The detail row's id, prefixed with the table's own id so two tables on a+ # page cannot collide.+ def row_detail_id(index)+ "#{opts[:id]}-detail-#{index}"+ endenddiff --git a/app/components/DS/table/column.rb b/app/components/DS/table/column.rbindex 02d66302b2..e10c7a7f3a 100644--- a/app/components/DS/table/column.rb+++ b/app/components/DS/table/column.rb@@ -16,7 +16,9 @@ class DS::Table::Column < DesignSystemComponent# column that names each row# @param class [String, nil] extra classes for the body cells, e.g. "text-secondary"# or "privacy-sensitive"- def initialize(header, cell:, sticky: false, inset: false, align: :left, numeric: false, row_header: false, class: nil)+ # @param aria_sort [String, nil] "ascending" or "descending" on the column the+ # rows are sorted by; nil (the default) leaves the attribute off+ def initialize(header, cell:, sticky: false, inset: false, align: :left, numeric: false, row_header: false, class: nil, aria_sort: nil)@header = header@cell = cell@sticky = sticky@@ -26,6 +28,7 @@ class DS::Table::Column < DesignSystemComponentcandidate = align.to_s.to_sym@align = numeric ? :right : (ALIGNS.include?(candidate) ? candidate : :left)@row_header = row_header+ @aria_sort = aria_sort@cell_class = binding.local_variable_get(:class)end@@ -33,7 +36,7 @@ class DS::Table::Column < DesignSystemComponent# the one job a line is good at, separating the labels from the data; the# rows use the subdued rule between them.def call- tag.th header, scope: "col", class: class_names(+ tag.th header, scope: "col", aria: { sort: @aria_sort }.compact, class: class_names("px-4 py-3 border-b border-divider text-xs uppercase font-medium text-secondary",alignment_classes,# z-10 so a privacy-blurred amount, which paints in a layer of its own,diff --git a/app/controllers/portfolios_controller.rb b/app/controllers/portfolios_controller.rbindex 39aee80114..7f8b13a71f 100644--- a/app/controllers/portfolios_controller.rb+++ b/app/controllers/portfolios_controller.rb@@ -11,11 +11,17 @@ class PortfoliosController < ApplicationController# Current.family lookups of their own).@as_of = Date.current@statement = Current.family.investment_statement(user: Current.user)+ # Query-string state for the holdings sort, reduced to the statement's+ # whitelists so the sort links never carry anything else back into the URL.+ @sort = params[:sort].presence_in(InvestmentStatement::HOLDINGS_SORT_KEYS)+ @dir = params[:dir].presence_in(InvestmentStatement::HOLDINGS_SORT_DIRECTIONS)registry = Portfolio::SectionRegistry.new(statement: @statement,period: @period,as_of: @as_of,- user: Current.user+ user: Current.user,+ sort: @sort,+ dir: @dir)@empty = registry.empty?@sections = @empty ? [] : registry.sectionsdiff --git a/app/helpers/portfolios_helper.rb b/app/helpers/portfolios_helper.rbnew file mode 100644index 0000000000..d55d0c01d4--- /dev/null+++ b/app/helpers/portfolios_helper.rb@@ -0,0 +1,32 @@+module PortfoliosHelper+ # Where a holdings column header links: the same column flips direction,+ # another column opens on its natural direction (names ascending, figures+ # descending).+ def holdings_sort_link(key, active_sort:, active_dir:)+ next_dir = if active_sort == key+ active_dir == "asc" ? "desc" : "asc"+ else+ key == "name" ? "asc" : "desc"+ end+ portfolio_path(sort: key, dir: next_dir)+ end++ # The aria-sort value for a column header, or nil when it is not the+ # active sort (the attribute is omitted rather than set to "none").+ def holdings_aria_sort(key, active_sort:, active_dir:)+ return nil unless key && active_sort == key++ active_dir == "asc" ? "ascending" : "descending"+ end++ # A sortable holdings column's header: a link to its next sort, with the+ # direction's chevron on the active column.+ def holdings_sort_header(label, key, active_sort:, active_dir:)+ active = active_sort == key++ link_to holdings_sort_link(key, active_sort: active_sort, active_dir: active_dir),+ class: class_names("inline-flex items-center gap-1 hover:text-primary focus-ring rounded", "text-primary" => active) do+ safe_join([ label, (icon(active_dir == "asc" ? "chevron-up" : "chevron-down", size: "xs") if active) ].compact)+ end+ end+enddiff --git a/app/javascript/controllers/row_expander_controller.js b/app/javascript/controllers/row_expander_controller.jsnew file mode 100644index 0000000000..0639ae5c0b--- /dev/null+++ b/app/javascript/controllers/row_expander_controller.js@@ -0,0 +1,21 @@+import { Controller } from "@hotwired/stimulus";++// Connects to data-controller="row-expander", on the button that reveals a+// table row belonging to another row: the per-account positions under a+// consolidated holding on the portfolio page. A <details> element cannot live+// inside a <table>, so the button names its detail row through aria-controls,+// toggles that row's `hidden` attribute and mirrors the state in+// aria-expanded. Nothing is persisted.+export default class extends Controller {+ toggle() {+ const row = document.getElementById(+ this.element.getAttribute("aria-controls"),+ );+ if (!row) return;++ const willExpand = row.hidden;+ row.hidden = !willExpand;+ this.element.setAttribute("aria-expanded", String(willExpand));+ this.element.classList.toggle("rotate-90", willExpand);+ }+}diff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rbindex 679d8e4f8d..d4e1b1ec68 100644--- a/app/models/investment_statement.rb+++ b/app/models/investment_statement.rb@@ -220,6 +220,15 @@ class InvestmentStatementHOLDINGS_SORT_KEYS = %w[value weight return day_change name].freezeHOLDINGS_SORT_DIRECTIONS = %w[asc desc].freeze+ # The [sort, dir] #holdings_table_rows actually applies, so a caller can+ # show the table's headers the order its rows are in.+ def self.holdings_sort(sort, dir)+ [+ HOLDINGS_SORT_KEYS.include?(sort.to_s) ? sort.to_s : "value",+ HOLDINGS_SORT_DIRECTIONS.include?(dir.to_s) ? dir.to_s : "desc"+ ]+ end+def holdings_table_rows(sort: "value", dir: "desc")rolled_up = holdings_rolled_up_by_securityreturn [] if rolled_up.empty?@@ -679,9 +688,12 @@ class InvestmentStatement# accounts that hold it, in family currency.HoldingsTableRow = Data.define(:security, :positions, :accounts_count, :qty, :avg_cost, :amount, :weight,- :unrealized, :day_change, :missing_cost_basis+ :unrealized, :day_change, :day_change_positions, :missing_cost_basis) dodef ticker = security.ticker+ # The Day change sums only the positions with a previous snapshot, while+ # the row's value sums them all.+ def day_change_partial? = day_change.present? && day_change_positions < positions.sizedef name = security.name.presence || tickerdef amount_money = amountend@@ -733,13 +745,13 @@ class InvestmentStatementweight: total.zero? ? 0 : (value / total * 100).round(2),unrealized: unrealized,day_change: day_change,+ day_change_positions: day_changes.size,missing_cost_basis: missing_cost_basis)enddef sort_holdings_table_rows(rows, sort:, dir:)- sort = HOLDINGS_SORT_KEYS.include?(sort.to_s) ? sort.to_s : "value"- dir = HOLDINGS_SORT_DIRECTIONS.include?(dir.to_s) ? dir.to_s : "desc"+ sort, dir = self.class.holdings_sort(sort, dir)# Rows without the sorted figure go last whichever direction is asked.# Ties break by name, then security id, in both directions, so rows withdiff --git a/app/models/portfolio/section_registry.rb b/app/models/portfolio/section_registry.rbindex 12c2993a15..f200d63122 100644--- a/app/models/portfolio/section_registry.rb+++ b/app/models/portfolio/section_registry.rb@@ -17,18 +17,28 @@ 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+ KEYS = %w[holdings accounts].freeze- attr_reader :statement, :period, :as_of, :user, :extra_sections+ # Everything an account card's logo reads, preloaded onto the cards.+ CARD_PRELOADS = [ { logo_attachment: :blob }, :accountable, :plaid_account, :simplefin_account, { account_providers: :provider } ].freeze+ attr_reader :statement, :period, :as_of, :user, :sort, :dir, :extra_sections++ # `sort` and `dir` are the holdings table's query-string state, passed+ # through as given: the statement whitelists them+ # (InvestmentStatement::HOLDINGS_SORT_KEYS, HOLDINGS_SORT_DIRECTIONS) and+ # falls back to its defaults for anything else.+ ## `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: [])+ def initialize(statement:, period:, as_of:, user:, sort: nil, dir: nil, extra_sections: [])@statement = statement@period = period@as_of = as_of@user = user+ @sort = sort+ @dir = dir@extra_sections = extra_sections || []end@@ -64,6 +74,14 @@ class Portfolio::SectionRegistryprivatedef built_in_sections[+ {+ key: "holdings",+ title: "portfolios.sections.holdings",+ partial: "portfolios/holdings",+ locals: shared_locals.merge(rows: holdings_rows, sort: holdings_sort.first, dir: holdings_sort.last),+ visible: holdings_rows.any?,+ collapsible: true+ },{key: "accounts",title: "portfolios.sections.accounts",@@ -75,14 +93,30 @@ class Portfolio::SectionRegistry]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 holdings_rows+ @holdings_rows ||= statement.holdings_table_rows(sort: holdings_sort.first, dir: holdings_sort.last)+ end++ # The sort the statement applies, so the view marks the header the rows+ # are ordered by even when the requested one fell back.+ def holdings_sort+ @holdings_sort ||= InvestmentStatement.holdings_sort(sort, dir)+ end++ # The accounts the cards show, in name order (case-insensitive; 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.+ #+ # They are the statement's own records, sorted here, rather than a second+ # query: the holdings section's weights load the same accounts through the+ # statement, and the page reads them once.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+ @accounts_for_cards ||= begin+ accounts = statement.investment_accounts.to_a.sort_by { |account| [ account.name.downcase, account.id ] }+ ActiveRecord::Associations::Preloader.new(records: accounts, associations: CARD_PRELOADS).call+ accounts+ endenddef shared_localsdiff --git a/app/views/portfolios/_holding_positions.html.erb b/app/views/portfolios/_holding_positions.html.erbnew file mode 100644index 0000000000..e7c0c543ef--- /dev/null+++ b/app/views/portfolios/_holding_positions.html.erb@@ -0,0 +1,30 @@+<%# locals: (row:) %>++<%# A holding's positions, one per account, each opening the holding drawer.+ The row's missing-cost-basis badge explains itself only on hover, so the+ explanation is repeated here as text a keyboard or touch user can read. %>+<% if row.missing_cost_basis %>+ <p class="px-3 py-2 text-xs text-secondary"><%= t("portfolios.holdings.missing_cost_basis_hint") %></p>+<% end %>+<%= render DS::Table.new(rows: row.positions, inset: true, label: t("portfolios.holdings.positions_caption", ticker: row.ticker), data: { portfolio_positions: row.ticker }) do |table| %>+ <% table.with_column(t("portfolios.holdings.columns.account")) { |holding| holding.account.name } %>++ <% table.with_column(t("portfolios.holdings.columns.qty"), numeric: true, class: "text-secondary privacy-sensitive") { |holding| format_quantity(holding.qty, exact: holding.security.crypto?) } %>++ <%# avg_cost, not the raw column: the statement preloads the trade-history+ fallback for every holding, so a position whose basis is computed shows+ it here too. %>+ <% table.with_column(t("portfolios.holdings.columns.cost_basis_per_share"), numeric: true, class: "text-secondary privacy-sensitive") do |holding| %>+ <% if holding.avg_cost %>+ <%= format_money(holding.avg_cost) %>+ <% else %>+ <%= tag.span "—", title: t("portfolios.holdings.position_missing_cost_basis_hint") %>+ <% end %>+ <% end %>++ <% table.with_column(t("portfolios.holdings.columns.value"), numeric: true, class: "privacy-sensitive") { |holding| format_money(holding.amount_money) } %>++ <% table.with_column(tag.span(t("portfolios.holdings.open_position"), class: "sr-only"), align: :right) do |holding| %>+ <%= link_to t("portfolios.holdings.open_position"), holding_path(holding), data: { turbo_frame: :drawer }, class: "text-link hover:underline text-xs" %>+ <% end %>+<% end %>diff --git a/app/views/portfolios/_holdings.html.erb b/app/views/portfolios/_holdings.html.erbnew file mode 100644index 0000000000..4f08c810ce--- /dev/null+++ b/app/views/portfolios/_holdings.html.erb@@ -0,0 +1,94 @@+<%# locals: (statement:, period:, as_of:, rows:, sort:, dir:) %>++<%#+ One row per security across every account, sorted by the statement. Every+ figure on a row comes from HoldingsTableRow: nothing here calls+ Holding#avg_cost, #trend or #day_change on a summary row, each of which+ issues a query per holding, so the page's query count does not grow with+ rows. Each row reveals its per-account positions, each with the existing+ holding drawer, in a detail row of the table.+%>+<%+ sorting = { active_sort: sort.presence || "value", active_dir: dir.presence || "desc" }+ header = ->(label, key) { holdings_sort_header(label, key, **sorting) }+%>++<%= render DS::Table.new(+ rows: rows,+ inset: true,+ id: "portfolio-holdings",+ label: t("portfolios.holdings.label"),+ row_class: ->(_row) { "hover:bg-container-hover" },+ row_opts: ->(row) { { data: { portfolio_holding: row.ticker } } },+ row_detail: ->(row) { render("portfolios/holding_positions", row: row) }+ ) do |table| %>+ <% table.with_column(header.call(t("portfolios.holdings.columns.security"), "name"), row_header: true, aria_sort: holdings_aria_sort("name", **sorting)) do |row, index| %>+ <%# The name wraps rather than truncating: in an auto-layout table a+ nowrap cell is as wide as its whole text and pushes the table past+ its column, while a wrapping one shows the full name on one line when+ there is room and takes a second line when there is not. %>+ <div class="flex items-center gap-3 min-w-0">+ <%= render DS::Button.new(+ variant: :icon,+ size: :sm,+ icon: "chevron-right",+ class: "shrink-0 transition-transform",+ data: { controller: "row-expander", action: "row-expander#toggle" },+ aria: { expanded: false, controls: table.row_detail_id(index), label: t("portfolios.holdings.toggle_positions", ticker: row.ticker) }+ ) %>+ <% if (logo = row.security.display_logo_url).present? %>+ <%= image_tag logo, class: "w-8 h-8 rounded-full shrink-0", loading: "lazy", alt: row.ticker %>+ <% else %>+ <%= render DS::FilledIcon.new(variant: :text, text: row.name, size: "md", rounded: true) %>+ <% end %>+ <div class="min-w-0 space-y-0.5 text-left">+ <%= tag.p row.name, class: "wrap-anywhere" %>+ <div class="flex items-center gap-2">+ <%= tag.p row.ticker, class: "text-secondary text-xs uppercase" %>+ <% if row.missing_cost_basis %>+ <%= render DS::Pill.new(label: t("portfolios.holdings.missing_cost_basis"), title: t("portfolios.holdings.missing_cost_basis_hint"), tone: :warning, icon: "info", marker: false) %>+ <% end %>+ </div>+ </div>+ </div>+ <% end %>++ <% table.with_column(t("portfolios.holdings.columns.accounts"), numeric: true, class: "text-secondary") { |row| row.accounts_count.to_s } %>++ <% table.with_column(t("portfolios.holdings.columns.qty"), numeric: true, class: "privacy-sensitive") { |row| format_quantity(row.qty, exact: row.security.crypto?) } %>++ <% table.with_column(t("portfolios.holdings.columns.avg_cost"), numeric: true, class: "privacy-sensitive") do |row| %>+ <%= row.avg_cost ? format_money(row.avg_cost) : tag.span("—", class: "text-secondary") %>+ <% end %>++ <% table.with_column(header.call(t("portfolios.holdings.columns.value"), "value"), numeric: true, aria_sort: holdings_aria_sort("value", **sorting)) do |row| %>+ <%= tag.span format_money(row.amount_money), class: "privacy-sensitive", data: { portfolio_value: true } %>+ <% end %>++ <% table.with_column(header.call(t("portfolios.holdings.columns.weight"), "weight"), numeric: true, aria_sort: holdings_aria_sort("weight", **sorting)) do |row| %>+ <div class="flex justify-end items-center gap-2">+ <%= render DS::ProgressRing.new(percent: row.weight, size: 16, stroke_width: 2, show_percent: false) %>+ <%= number_to_percentage(row.weight, precision: 1) %>+ </div>+ <% end %>++ <% table.with_column(header.call(t("portfolios.holdings.columns.unrealized"), "return"), numeric: true, aria_sort: holdings_aria_sort("return", **sorting)) do |row| %>+ <% if row.unrealized %>+ <%= render "shared/trend_figure", trend: row.unrealized %>+ <% else %>+ <p class="text-secondary">—</p>+ <p class="text-xs text-secondary"><%= t("portfolios.holdings.no_cost_basis") %></p>+ <% end %>+ <% end %>++ <% table.with_column(header.call(t("portfolios.holdings.columns.day_change"), "day_change"), numeric: true, aria_sort: holdings_aria_sort("day_change", **sorting)) do |row| %>+ <% if row.day_change %>+ <%= render "shared/trend_figure",+ trend: row.day_change,+ note: (t("portfolios.holdings.day_change_partial", covered: row.day_change_positions, total: row.positions.size) if row.day_change_partial?),+ note_data: { day_change_partial: true } %>+ <% else %>+ <p class="text-secondary">—</p>+ <% end %>+ <% end %>+<% end %>diff --git a/app/views/shared/_trend_figure.html.erb b/app/views/shared/_trend_figure.html.erbnew file mode 100644index 0000000000..c0f2c0ed4c--- /dev/null+++ b/app/views/shared/_trend_figure.html.erb@@ -0,0 +1,11 @@+<%# locals: (trend:, note: nil, note_data: {}) %>++<%#+ A trend as two stacked lines for a numeric table cell: the signed amount,+ then its percentage in the page's locale, both in the trend's colour. An+ optional note, in secondary text, says what the figure leaves out.+%>+<%= tag.p format_money(trend.value), class: "privacy-sensitive", style: "color: #{trend.color};" %>+<%= tag.p "(#{trend.percent.finite? ? number_to_percentage(trend.percent, precision: 1) : trend.percent_formatted})",+ class: "text-xs privacy-sensitive", style: "color: #{trend.color};", data: { trend_percent: true } %>+<%= tag.p note, class: "text-xs text-secondary", data: note_data if note.present? %>diff --git a/config/locales/views/portfolios/de.yml b/config/locales/views/portfolios/de.ymlindex 298142f693..96547e06c8 100644--- a/config/locales/views/portfolios/de.yml+++ b/config/locales/views/portfolios/de.yml@@ -5,10 +5,32 @@ de:add_account: Anlagekonto hinzufügendescription: Depot-, Vorsorge- und Krypto-Konten, die du in deine Finanzen und Berichte einbeziehst, erscheinen hier mit ihrem Saldo.title: Keine Anlagekonten zum Anzeigen+ holdings:+ columns:+ account: Konto+ accounts: Konten+ avg_cost: Ø Kosten+ cost_basis_per_share: Kostenbasis je Anteil+ day_change: Tag+ qty: Menge+ security: Wertpapier+ unrealized: Unrealisierter G/V+ value: Wert+ weight: Gewichtung+ day_change_partial: "%{covered} von %{total} Positionen"+ label: Bestände+ missing_cost_basis: Keine Kostenbasis+ missing_cost_basis_hint: Mindestens eine Position hat keine bekannte Kostenbasis. Durchschnittskosten und Rendite berücksichtigen nur Positionen mit bekannter Kostenbasis.+ no_cost_basis: keine Kostenbasis+ open_position: Öffnen+ position_missing_cost_basis_hint: Diese Position hat keine bekannte Kostenbasis, daher hat sie keine Durchschnittskosten und fließt nicht in die Rendite der Zeile ein.+ positions_caption: Positionen in %{ticker} nach Konto+ toggle_positions: Positionen in %{ticker} anzeigensections:accounts: Konten+ holdings: Beständeshow: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.+ subtitle: Was du über deine Anlagekonten hinweg hältst, und was jedes Konto wert ist.title: Portfoliodiff --git a/config/locales/views/portfolios/en.yml b/config/locales/views/portfolios/en.ymlindex 991ff2556e..34e38dd75d 100644--- a/config/locales/views/portfolios/en.yml+++ b/config/locales/views/portfolios/en.yml@@ -5,10 +5,32 @@ en:add_account: Add an investment accountdescription: Brokerage, retirement and crypto accounts you include in your finances and reports are listed here with their balance.title: No investment accounts to show+ holdings:+ columns:+ account: Account+ accounts: Accounts+ avg_cost: Avg cost+ cost_basis_per_share: Cost basis per share+ day_change: Day+ qty: Qty+ security: Security+ unrealized: Unrealised P&L+ value: Value+ weight: Weight+ day_change_partial: "%{covered} of %{total} positions"+ label: Holdings+ missing_cost_basis: No cost basis+ missing_cost_basis_hint: At least one position has no known cost basis. The average cost and return cover only the positions that have one.+ no_cost_basis: no cost basis+ open_position: Open+ position_missing_cost_basis_hint: This position has no known cost basis, so it has no average cost and is left out of the row's return.+ positions_caption: Positions in %{ticker} by account+ toggle_positions: Show positions in %{ticker}sections:accounts: Accounts+ holdings: Holdingsshow: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.+ subtitle: What you hold across your investment accounts, and what each account is worth.title: Portfoliodiff --git a/test/components/DS/table_test.rb b/test/components/DS/table_test.rbindex 0980f5ccff..1b9cccc788 100644--- a/test/components/DS/table_test.rb+++ b/test/components/DS/table_test.rb@@ -120,6 +120,56 @@ class DS::TableTest < ViewComponent::TestCaseassert_selector "div#bills-table.hidden > div.table-scroll"end+ test "marks the sorted column's header with aria-sort and leaves the rest without it" do+ render_inline(DS::Table.new(rows: ROWS)) do |table|+ table.with_column("Name", aria_sort: "ascending") { |row| row[:name] }+ table.with_column("Amount", numeric: true) { |row| row[:amount] }+ end++ assert_selector "thead th:first-child[aria-sort='ascending']"+ assert_selector "thead th[aria-sort]", count: 1+ end++ # A detail row sits straight after the row it belongs to, hidden, spanning+ # every column, under an id the row's own cells can point a toggle at.+ test "renders a hidden detail row after each row the row_detail proc answers for" do+ detail = ->(row) { "Paid monthly" if row[:name] == "Rent" }+ render_inline(DS::Table.new(rows: ROWS, id: "bills", row_detail: detail)) do |table|+ table.with_column("Name") { |row, index| ApplicationController.helpers.tag.button(row[:name], aria: { controls: table.row_detail_id(index) }) }+ table.with_column("Amount", numeric: true) { |row| row[:amount] }+ end++ assert_selector "tbody tr", count: 3, visible: :all+ assert_selector "tbody tr:nth-child(2)#bills-detail-0[hidden] td[colspan='2']", text: "Paid monthly", visible: :all+ assert_selector "tbody tr:nth-child(1) button[aria-controls='bills-detail-0']"+ assert_selector "tbody tr:nth-child(3) td:first-child", text: "Internet"+ end++ test "renders no detail rows without a row_detail proc" do+ render_table(id: "bills")++ assert_selector "tbody tr", count: 2+ assert_no_selector "tbody tr[hidden]", visible: :all+ end++ # Detail ids are prefixed with the table's id; two tables without one would+ # hand out the same ids and a toggle would open the other table's row.+ test "requires an id when given a row_detail proc" do+ error = assert_raises(ArgumentError) { DS::Table.new(rows: ROWS, row_detail: ->(_row) { "x" }) }+ assert_match "id:", error.message++ assert_nothing_raised { DS::Table.new(rows: ROWS, id: "bills", row_detail: ->(_row) { "x" }) }+ assert_nothing_raised { DS::Table.new(rows: ROWS) }+ end++ # Detail ids land in aria-controls, which reads a space as a second id.+ test "a table with detail rows refuses an id with whitespace" do+ error = assert_raises(ArgumentError) { DS::Table.new(rows: ROWS, id: "payment schedule", row_detail: ->(_row) { "x" }) }+ assert_match "whitespace", error.message++ assert_nothing_raised { DS::Table.new(rows: ROWS, id: "payment schedule") }+ end+privatedef render_table(**options)render_inline(DS::Table.new(rows: ROWS, **options)) do |table|diff --git a/test/controllers/portfolios_controller_test.rb b/test/controllers/portfolios_controller_test.rbindex e9bc655a6d..b6e3767b6e 100644--- a/test/controllers/portfolios_controller_test.rb+++ b/test/controllers/portfolios_controller_test.rb@@ -43,12 +43,14 @@ class PortfoliosControllerTest < ActionDispatch::IntegrationTestassert_equal "last_30_days", @user.reload.default_periodend- test "renders the hub and the accounts section" do+ # The fixture family holds AAPL in accounts(:investment), so both sections+ # have something to show.+ test "renders the hub with its holdings and accounts sections" doget portfolio_pathassert_response :successassert_select "h1", text: I18n.t("portfolios.show.title")- assert_equal %w[accounts], css_select("[data-section-key]").map { |node| node["data-section-key"] }+ assert_equal %w[holdings accounts], css_select("[data-section-key]").map { |node| node["data-section-key"] }assert_select "header + div[role=list]"end@@ -118,6 +120,21 @@ class PortfoliosControllerTest < ActionDispatch::IntegrationTest"an unknown key must not be written into the user's preferences")end+ test "stores the holdings section in the saved order and collapsed set" do+ patch update_preferences_portfolio_path,+ params: { preferences: { portfolio_section_order: %w[accounts holdings], portfolio_collapsed_sections: { holdings: true } } },+ as: :json++ assert_response :ok+ @user.reload+ assert_equal %w[accounts holdings], @user.preferences["portfolio_section_order"]+ assert_equal({ "holdings" => true }, @user.preferences["portfolio_collapsed_sections"])++ get portfolio_path+ assert_equal %w[accounts holdings], css_select("[data-section-key]").map { |node| node["data-section-key"] }+ assert_select "[data-section-key=holdings][data-reports-section-collapsed-value=?]", "true"+ end+test "a preferences body that is not an object is refused and writes nothing" dobefore = @user.reload.preferences.dup@@ -288,6 +305,167 @@ class PortfoliosControllerTest < ActionDispatch::IntegrationTestassert_no_match(/yet/i, I18n.t("portfolios.empty_state.title"))end+ test "holdings table renders one row per security with its per-account positions" do+ second = create_second_aapl_account(qty: 20, price: 215)+ statement = InvestmentStatement.new(@family, user: @user)+ row = statement.holdings_table_rows.find { |r| r.ticker == "AAPL" }+ assert_equal 2, row.positions.size, "fixture must hold AAPL in two accounts"++ get portfolio_path+ assert_response :success++ assert_select "#portfolio-holdings tr[data-portfolio-holding='AAPL']", count: 1+ assert_select "#portfolio-holdings tr[data-portfolio-holding='AAPL'] [data-portfolio-value]", text: ApplicationController.helpers.format_money(row.amount_money)+ toggle = css_select("#portfolio-holdings tr[data-portfolio-holding='AAPL'] button[aria-expanded='false'][aria-controls]").first+ assert toggle, "the summary row must carry a collapsed toggle"+ detail = css_select("#portfolio-holdings tr##{toggle["aria-controls"]}[hidden]").first+ assert detail, "the toggle must point at the hidden detail row"+ positions = css_select(detail, "[data-portfolio-positions='AAPL'] a[href^='/holdings/']")+ assert_equal 2, positions.size+ assert_includes positions.map { |a| a["href"] }, holding_path(second.holdings.first)+ end++ test "holdings table sorts through links that flip the active column's direction" do+ zzz = Security.create!(ticker: "ZZZ", name: "Zeta")+ Holding.create!(account: accounts(:investment), security: zzz, date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD", cost_basis: 8, cost_basis_locked: true)++ get portfolio_path(sort: "name", dir: "asc")+ assert_response :success++ assert_equal %w[AAPL ZZZ], css_select("#portfolio-holdings tr[data-portfolio-holding]").map { |n| n["data-portfolio-holding"] }+ assert_select "#portfolio-holdings th[aria-sort='ascending'] a[href=?]", "#{portfolio_path}?dir=desc&sort=name"+ assert_select "#portfolio-holdings th a[href=?]", "#{portfolio_path}?dir=desc&sort=value"+ assert_select "#portfolio-holdings th[aria-sort]", count: 1++ get portfolio_path(sort: "value", dir: "asc")+ assert_equal %w[ZZZ AAPL], css_select("#portfolio-holdings tr[data-portfolio-holding]").map { |n| n["data-portfolio-holding"] }+ assert_select "#portfolio-holdings th[aria-sort='ascending'] a[href=?]", "#{portfolio_path}?dir=desc&sort=value"+ end++ # Anything outside the statement's whitelists falls back to the default+ # sort, value descending, and never reaches a link.+ test "holdings sort params are whitelisted before they reach the sort links" do+ get portfolio_path(sort: "drop table", dir: "sideways")+ assert_response :success++ assert_select "#portfolio-holdings th[aria-sort='descending'] a[href=?]", "#{portfolio_path}?dir=asc&sort=value"+ assert_select "#portfolio-holdings th[aria-sort]", count: 1+ assert_select "#portfolio-holdings a[href*=?]", "drop", count: 0+ assert_select "#portfolio-holdings a[href*=?]", "sideways", count: 0+ end++ test "holdings table flags a row whose position has no cost basis" do+ priced = Security.create!(ticker: "BASIS", name: "With basis")+ Holding.create!(account: accounts(:investment), security: priced, date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD", cost_basis: 8, cost_basis_locked: true)+ # Neither a stored basis nor a buy trade to compute one from, so+ # Holding#avg_cost is nil and the row is flagged. AAPL is deliberately+ # not the example: it has a fixture trade, so its basis is computable+ # even though nothing is stored on the holding.+ unknown = Security.create!(ticker: "NOBASIS", name: "Without basis")+ Holding.create!(account: accounts(:investment), security: unknown, date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD")+ # One security, a known basis in one account and none in another: the row+ # warns, yet still shows the average cost of the position that has one.+ partial = Security.create!(ticker: "PARTIAL", name: "Partly known basis")+ second_broker = accounts(:investment).family.accounts.create!(name: "Second broker", balance: 10, cash_balance: 0, currency: "USD", accountable: Investment.new)+ Holding.create!(account: accounts(:investment), security: partial, date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD", cost_basis: 8, cost_basis_locked: true)+ Holding.create!(account: second_broker, security: partial, date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD")++ get portfolio_path+ assert_response :success++ row_hint = I18n.t("portfolios.holdings.missing_cost_basis_hint")+ position_hint = I18n.t("portfolios.holdings.position_missing_cost_basis_hint")+ eight = Regexp.escape(ApplicationController.helpers.format_money(Money.new(8, "USD")))++ assert_select "tr[data-portfolio-holding='NOBASIS']", text: /#{I18n.t("portfolios.holdings.missing_cost_basis")}/+ assert_select "tr[data-portfolio-holding='NOBASIS'] span[title=?]", row_hint+ assert_select "[data-portfolio-positions='NOBASIS'] span[title=?]", position_hint, text: "—"+ assert_select "tr[data-portfolio-holding='AAPL']", text: /#{I18n.t("portfolios.holdings.missing_cost_basis")}/, count: 0,+ message: "AAPL's basis is computable from its trade, so the row must not warn"+ assert_select "tr[data-portfolio-holding='BASIS']", text: /#{I18n.t("portfolios.holdings.missing_cost_basis")}/, count: 0+ assert_select "tr[data-portfolio-holding='BASIS']", text: /#{eight}/++ assert_select "tr[data-portfolio-holding='PARTIAL'] span[title=?]", row_hint+ assert_select "tr[data-portfolio-holding='PARTIAL']", text: /#{eight}/,+ message: "a partly known basis still shows the average cost the row hint describes"+ assert_select "[data-portfolio-positions='PARTIAL'] span[title=?]", position_hint, count: 1+ # AAPL stores no basis but has a buy trade, so its position shows the+ # computed average cost rather than the missing-basis dash.+ aapl_cost = statement_avg_cost("AAPL")+ assert_select "[data-portfolio-positions='AAPL'] span[title=?]", position_hint, count: 0+ assert_select "[data-portfolio-positions='AAPL'] td", text: ApplicationController.helpers.format_money(aapl_cost)+ end++ test "holdings table renders its figures with design-system parts in the page's locale" do+ second = create_second_aapl_account(qty: 20, price: 215)+ statement = InvestmentStatement.new(@family, user: @user)+ row = statement.holdings_table_rows.find { |r| r.ticker == "AAPL" }+ assert row.unrealized, "precondition: AAPL has a return to show"++ get portfolio_path(locale: "de")+ assert_response :success++ aapl = "#portfolio-holdings tr[data-portfolio-holding='AAPL']"+ # DS::ProgressRing: a decorative svg the adjacent percentage labels, not+ # the legacy partial's hard-coded gray track.+ assert_select "#{aapl} svg[aria-hidden='true'] circle", minimum: 2+ assert_select "#{aapl} circle.text-gray-300", count: 0+ expected = I18n.with_locale(:de) { ApplicationController.helpers.number_to_percentage(row.unrealized.percent, precision: 1) }+ assert_select "#{aapl} [data-trend-percent]", text: "(#{expected})"+ assert_match ",", expected, "precondition: German writes a decimal comma"+ assert_select "#{aapl} p.wrap-anywhere", text: row.name+ assert_select "[data-portfolio-positions='AAPL'] th", text: I18n.t("portfolios.holdings.columns.cost_basis_per_share", locale: :de)+ assert second+ end++ # The row's warning badge explains itself on hover only through its title,+ # so the explanation is also visible text in the row's details.+ test "a row without a full cost basis explains it in its details as visible text" do+ unknown = Security.create!(ticker: "NOBASIS", name: "Without basis")+ Holding.create!(account: accounts(:investment), security: unknown, date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD")++ get portfolio_path+ assert_response :success++ toggle = css_select("#portfolio-holdings tr[data-portfolio-holding='NOBASIS'] button[aria-controls]").first+ assert_select "tr##{toggle["aria-controls"]} p", text: I18n.t("portfolios.holdings.missing_cost_basis_hint")+ end++ test "a day change that covers only some positions says how many" do+ security = Security.create!(ticker: "HALF", name: "Half covered")+ second_broker = @family.accounts.create!(name: "Second broker", balance: 900, cash_balance: 0, currency: "USD", accountable: Investment.new)+ Holding.create!(account: accounts(:investment), security: security, date: 1.day.ago.to_date, qty: 1, price: 100, amount: 100, currency: "USD")+ Holding.create!(account: accounts(:investment), security: security, date: Date.current, qty: 1, price: 120, amount: 120, currency: "USD")+ Holding.create!(account: second_broker, security: security, date: Date.current, qty: 9, price: 100, amount: 900, currency: "USD")++ get portfolio_path+ assert_response :success++ assert_select "tr[data-portfolio-holding='HALF'] [data-day-change-partial]",+ text: I18n.t("portfolios.holdings.day_change_partial", covered: 1, total: 2)+ assert_select "tr[data-portfolio-holding='AAPL'] [data-day-change-partial]", count: 0+ end++ test "the page's query count is bounded and does not grow with holdings" do+ build_portfolio(accounts: 10, securities: 6)+ baseline = capture_sql_queries { get portfolio_path }+ assert_response :success++ # Measured: 42 queries for this page (layout included) with the holdings+ # and accounts sections, 10 accounts and 60 holdings, none of them per+ # holding. The ceiling is that figure plus a little headroom, not a+ # guess; the assertion below is the one that matters.+ assert_operator baseline.size, :<=, PORTFOLIO_QUERY_CEILING, "GET /portfolio issued #{baseline.size} queries"++ build_portfolio(accounts: 10, securities: 2, existing_accounts: @family.accounts.where("name LIKE 'Bulk %'").to_a)+ grown = capture_sql_queries { get portfolio_path }+ assert_response :success++ assert_equal baseline.size, grown.size, "adding 20 holdings changed the query count:\n#{(grown - baseline).join("\n")}"+ end++ PORTFOLIO_QUERY_CEILING = 50+privatedef enable_preview(user)user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => true))@@ -308,4 +486,37 @@ class PortfoliosControllerTest < ActionDispatch::IntegrationTestdef provider_queries(&block)capture_sql_queries(&block).count { |sql| sql.include?(%(FROM "lunchflow_accounts")) }end++ def statement_avg_cost(ticker)+ row = InvestmentStatement.new(@family, user: @user).holdings_table_rows.find { |r| r.ticker == ticker }+ assert_nil row.positions.sole.cost_basis, "the premise: #{ticker} stores no cost basis"+ row.positions.sole.avg_cost+ end++ def create_second_aapl_account(qty:, price:)+ account = @family.accounts.create!(owner: @user, name: "Second Brokerage", balance: qty * price, cash_balance: 0, currency: "USD", accountable: Investment.new)+ Holding.create!(account: account, security: securities(:aapl), date: Date.current, qty: qty, price: price, amount: qty * price, currency: "USD")+ account+ end++ # `accounts` investment accounts each holding `securities` securities,+ # with a previous-day snapshot per position so day change has work to do.+ # Every other security has no stored cost basis, the shape a synced+ # brokerage produces, so a view that reached for Holding#avg_cost (and+ # its per-holding trades query) would show up in the count.+ def build_portfolio(accounts:, securities:, existing_accounts: nil)+ accounts = existing_accounts || Array.new(accounts) do |i|+ @family.accounts.create!(owner: @user, name: "Bulk #{i}", balance: 1000 * securities, cash_balance: 50, currency: "USD", accountable: Investment.new)+ end+ securities = Array.new(securities) do |i|+ Security.create!(ticker: "B#{SecureRandom.hex(3).upcase}#{i}", name: "Bulk security #{i}")+ end+ accounts.each do |account|+ securities.each_with_index do |security, index|+ basis = index.even? ? { cost_basis: 90, cost_basis_locked: true } : {}+ Holding.create!(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 95, amount: 950, currency: "USD", **basis)+ Holding.create!(account: account, security: security, date: Date.current, qty: 10, price: 100, amount: 1000, currency: "USD", **basis)+ end+ end+ endenddiff --git a/test/helpers/portfolios_helper_test.rb b/test/helpers/portfolios_helper_test.rbnew file mode 100644index 0000000000..98dff293ba--- /dev/null+++ b/test/helpers/portfolios_helper_test.rb@@ -0,0 +1,21 @@+require "test_helper"++class PortfoliosHelperTest < ActionView::TestCase+ include PortfoliosHelper++ test "a holdings header flips its own direction and opens another column on its natural one" do+ active = { active_sort: "value", active_dir: "desc" }++ assert_equal portfolio_path(sort: "value", dir: "asc"), holdings_sort_link("value", **active)+ assert_equal portfolio_path(sort: "value", dir: "desc"), holdings_sort_link("value", active_sort: "value", active_dir: "asc")+ assert_equal portfolio_path(sort: "name", dir: "asc"), holdings_sort_link("name", **active)+ assert_equal portfolio_path(sort: "weight", dir: "desc"), holdings_sort_link("weight", **active)+ end++ test "only the active holdings column carries an aria-sort value" do+ assert_equal "ascending", holdings_aria_sort("name", active_sort: "name", active_dir: "asc")+ assert_equal "descending", holdings_aria_sort("name", active_sort: "name", active_dir: "desc")+ assert_nil holdings_aria_sort("value", active_sort: "name", active_dir: "asc")+ assert_nil holdings_aria_sort(nil, active_sort: "name", active_dir: "asc")+ end+enddiff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rbindex b63e06159a..9b97eb06f4 100644--- a/test/models/investment_statement_test.rb+++ b/test/models/investment_statement_test.rb@@ -1764,6 +1764,27 @@ class InvestmentStatementTest < ActiveSupport::TestCaseassert_in_delta 900, statement.unrealized_gains, 0.001end+ # The Value column sums every position, so a Day change built from only the+ # positions with a previous snapshot says so, with how many it covers.+ test "holdings_table_rows marks a day change that covers only some positions" do+ security = Security.create!(ticker: "HALF", name: "Half covered")+ with_snapshot = create_investment_account(balance: 1_000)+ without_snapshot = create_investment_account(balance: 1_000)+ Holding.create!(account: with_snapshot, security: security, date: 1.day.ago.to_date, qty: 1, price: 100, amount: 100, currency: "USD")+ Holding.create!(account: with_snapshot, security: security, date: Date.current, qty: 1, price: 120, amount: 120, currency: "USD")+ Holding.create!(account: without_snapshot, security: security, date: Date.current, qty: 9, price: 100, amount: 900, currency: "USD")++ row = @statement.holdings_table_rows.find { |r| r.ticker == "HALF" }++ assert_equal Money.new(20, "USD"), row.day_change.value+ assert_equal [ 1, 2 ], [ row.day_change_positions, row.positions.size ]+ assert row.day_change_partial?++ Holding.create!(account: without_snapshot, security: security, date: 1.day.ago.to_date, qty: 9, price: 100, amount: 900, currency: "USD")+ full = InvestmentStatement.new(@family, user: nil).holdings_table_rows.find { |r| r.ticker == "HALF" }+ assert_not full.day_change_partial?, "every position has a snapshot"+ end+# A provider can report one security in two currencies in the same account on# the same day, and both rows are current. Each compares against its own# currency's previous snapshot, as Holding#day_change does, and the portfoliodiff --git a/test/models/portfolio/section_registry_test.rb b/test/models/portfolio/section_registry_test.rbindex 8a4a5e353d..cf550e8ecc 100644--- a/test/models/portfolio/section_registry_test.rb+++ b/test/models/portfolio/section_registry_test.rb@@ -13,7 +13,7 @@ class Portfolio::SectionRegistryTest < ActiveSupport::TestCasesections = registry.sectionsassert_equal Portfolio::SectionRegistry::KEYS, sections.map { |s| s[:key] }- assert_equal %w[portfolios/accounts], sections.map { |s| s[:partial] }+ assert_equal %w[portfolios/holdings 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@@ -47,10 +47,61 @@ class Portfolio::SectionRegistryTest < ActiveSupport::TestCase"the cards must be exactly the statement's investment accounts"end+ # The cards are the statement's own records, so the associations their+ # logos read have to be preloaded onto those records, not left to load per+ # card.+ test "the account cards come with everything their logos read preloaded" do+ logoed = accounts(:investment)+ logoed.logo.attach(io: StringIO.new("logo"), filename: "logo.png", content_type: "image/png")+ provider = LunchflowAccount.create!(lunchflow_item: lunchflow_items(:one), account_id: "lf_registry_logo",+ name: logoed.name, currency: "USD")+ AccountProvider.create!(account: logoed, provider: provider)+ @statement = InvestmentStatement.new(@family, user: @user)++ cards = registry.sections.find { |s| s[:key] == "accounts" }[:locals][:accounts]++ assert_not_empty cards+ cards.each do |account|+ %i[logo_attachment accountable plaid_account simplefin_account account_providers].each do |name|+ assert account.association(name).loaded?, "#{name} is not preloaded on #{account.name}"+ end+ end+ card = cards.find { |account| account.id == logoed.id }+ assert card.logo_attachment.association(:blob).loaded?, "the logo's blob is not preloaded"+ assert_not_empty card.account_providers+ card.account_providers.each do |link|+ assert link.association(:provider).loaded?, "the provider link's provider is not preloaded"+ end+ end++ test "the account cards ignore case when ordering by name" do+ lower = @family.accounts.create!(name: "alpha brokerage", balance: 100, currency: "USD", accountable: Investment.new, owner: @user)+ upper = @family.accounts.create!(name: "Beta 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_operator cards.index(lower), :<, cards.index(upper)+ end++ # The statement's query has no order of its own, so the tiebreak must not+ # lean on whatever order its rows arrive in: feed them in descending id.+ test "account cards with the same name are ordered by id whatever order the statement returns" do+ same = %w[b d f].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+ @statement.stubs(:investment_accounts).returns(@family.accounts.where(id: same.map(&:id)).order(id: :desc))++ cards = registry.sections.find { |s| s[:key] == "accounts" }[:locals][:accounts]++ assert_equal same.map(&:id), cards.map(&:id)+ 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] }+ assert_equal %w[stub holdings accounts], registry(extra_sections: [ stub_section ]).sections.map { |s| s[:key] }endtest "a saved order that repeats a key renders that section once" do@@ -58,19 +109,66 @@ class Portfolio::SectionRegistryTest < ActiveSupport::TestCasekeys = registry(extra_sections: [ stub_section ]).sections.map { |s| s[:key] }- assert_equal %w[stub accounts], keys+ assert_equal %w[stub accounts holdings], keysendtest "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] }+ assert_equal %w[accounts holdings], registry.sections.map { |s| s[:key] }endtest "appends extra sections after the built-ins" dosections = registry(extra_sections: [ stub_section ]).sections- assert_equal %w[accounts stub], sections.map { |s| s[:key] }+ assert_equal %w[holdings accounts stub], sections.map { |s| s[:key] }+ end++ # A family whose investment accounts hold nothing has no rows to list, so+ # the section stays out rather than drawing an empty table.+ test "the holdings section is visible only when the family holds a security" do+ assert registry.sections.find { |s| s[:key] == "holdings" }[:visible]++ Holding.where(account: @statement.investment_accounts).delete_all+ @statement = InvestmentStatement.new(@family, user: @user)+ sections = registry.sections++ assert_not sections.find { |s| s[:key] == "holdings" }[:visible]+ assert sections.find { |s| s[:key] == "accounts" }[:visible], "the accounts still list with nothing held"+ end++ # The statement falls back on its own for an unknown sort, so the view must+ # be told what it fell back to, or no header shows the sort it sees.+ test "passes the effective sort and direction to the holdings locals" do+ holdings = Portfolio::SectionRegistry.new(+ statement: @statement, period: @period, as_of: @as_of, user: @user, sort: "unsupported", dir: "asc"+ ).sections.find { |s| s[:key] == "holdings" }++ assert_equal [ "value", "asc" ], [ holdings[:locals][:sort], holdings[:locals][:dir] ]+ values = holdings[:locals][:rows].map { |row| row.amount.amount }+ assert_equal values.sort, values, "the rows are in the order the locals name"+ end++ test "passes the sort and direction through to the holdings locals" do+ # Ticker order and name order disagree for this one: it sorts last by+ # ticker and first by name, so a name sort that secretly ordered by+ # ticker would put it in the wrong place.+ zebra = Security.create!(ticker: "ZZZA", name: "Aardvark Holdings")+ Holding.create!(+ account: accounts(:investment), security: zebra, date: Date.current,+ qty: 1, price: 10, amount: 10, currency: "USD", cost_basis: 8, cost_basis_locked: true+ )++ holdings = Portfolio::SectionRegistry.new(+ statement: @statement, period: @period, as_of: @as_of, user: @user, sort: "name", dir: "asc"+ ).sections.find { |s| s[:key] == "holdings" }++ assert_equal "name", holdings[:locals][:sort]+ assert_equal "asc", holdings[:locals][:dir]+ rows = holdings[:locals][:rows]+ names = rows.map { |row| row.name.downcase }+ assert_equal names.sort, names, "sort: \"name\" must order by security name, not ticker"+ assert_equal "ZZZA", rows.first.ticker, "the name sort must put Aardvark first despite its ticker"endprivatediff --git a/test/system/portfolios_test.rb b/test/system/portfolios_test.rbindex b869aba0cb..c0af1ff3e3 100644--- a/test/system/portfolios_test.rb+++ b/test/system/portfolios_test.rb@@ -25,4 +25,63 @@ class PortfoliosTest < ApplicationSystemTestCaseensureActionController::Base.allow_forgery_protection = originalend++ test "a holding's toggle reveals and hides its per-account positions" do+ visit portfolio_path++ toggle = find("#portfolio-holdings tr[data-portfolio-holding='AAPL'] button[aria-controls]")+ detail_id = toggle["aria-controls"]+ assert_no_selector "##{detail_id}"++ toggle.click+ assert_selector "##{detail_id} [data-portfolio-positions='AAPL'] a[href^='/holdings/']"+ assert_equal "true", toggle["aria-expanded"]++ toggle.click+ assert_no_selector "##{detail_id}"+ assert_equal "false", toggle["aria-expanded"]+ end++ test "a holdings column header sorts the table and flips on a second click" do+ # Name and ticker order disagree ("Aardvark" before "Apple", ZZZ+ # after AAPL), so a name sort that compared tickers would fail.+ Holding.create!(account: accounts(:investment), security: Security.create!(ticker: "ZZZ", name: "Aardvark"),+ date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD")+ visit portfolio_path++ find("#portfolio-holdings th a[href*='sort=name']").click+ assert_selector "#portfolio-holdings th[aria-sort='ascending'] a[href*='sort=name']"+ assert_equal %w[ZZZ AAPL], all("#portfolio-holdings tr[data-portfolio-holding]").map { |row| row["data-portfolio-holding"] }++ find("#portfolio-holdings th a[href*='sort=name']").click+ assert_selector "#portfolio-holdings th[aria-sort='descending'] a[href*='sort=name']"+ assert_equal %w[AAPL ZZZ], all("#portfolio-holdings tr[data-portfolio-holding]").map { |row| row["data-portfolio-holding"] }+ end++ # A name that is clipped still sits in the DOM, so the assertion is on the+ # rendered box: nothing of the name hidden, and the table no wider than its+ # scroll region. With both sidebars closed the table fits its region, so an+ # overflow can only come from the name; the second name is too long for one+ # line and must wrap.+ test "a long security name shows in full without widening the holdings table" do+ @user.update_columns(show_sidebar: false, show_ai_sidebar: false)+ names = {+ "VTI" => "Vanguard Total Stock Market ETF",+ "VTIAX" => "Vanguard Total International Stock Index Fund Admiral Shares Accumulating Class Units Hedged To The Australian Dollar"+ }+ names.each do |ticker, name|+ Holding.create!(account: accounts(:investment), security: Security.create!(ticker: ticker, name: name),+ date: Date.current, qty: 1, price: 10, amount: 10, currency: "USD")+ end+ visit portfolio_path++ names.each do |ticker, name|+ shown = find("#portfolio-holdings tr[data-portfolio-holding='#{ticker}'] p", exact_text: name)+ assert page.evaluate_script("arguments[0].scrollWidth <= arguments[0].clientWidth", shown),+ "#{ticker}'s name is clipped"+ end+ region = find("#portfolio-holdings [role='region']")+ assert page.evaluate_script("arguments[0].scrollWidth <= arguments[0].clientWidth", region),+ "the holdings table overflows its scroll region"+ endend