The personal finance app for everyone (by everyone)
Ruby
Filter account activity by a range dragged on the chart (#4872)
Yong Cong Sin79bfe359e597
diff --git a/app/components/UI/account/activity_feed.html.erb b/app/components/UI/account/activity_feed.html.erbindex 899e22eb48..122916e8fe 100644--- a/app/components/UI/account/activity_feed.html.erb+++ b/app/components/UI/account/activity_feed.html.erb@@ -53,6 +53,13 @@method: :get,data: { controller: "auto-submit-form" } do |form| %><%= hidden_field_tag :tab, "activity" %>+ <%# The chart's range and view, so the badges' clear links (built from+ this search's query string) keep a range dragged on the chart. %>+ <% %w[start_date end_date chart_view].each do |chart_param| %>+ <% if helpers.params[chart_param].present? %>+ <%= hidden_field_tag chart_param, helpers.params[chart_param], id: nil %>+ <% end %>+ <% end %><div class="flex gap-2 mb-4"><div class="grow"><div class="flex items-center px-3 py-2 gap-2 border border-secondary rounded-lg focus-within:border-primary">diff --git a/app/components/UI/account/chart.html.erb b/app/components/UI/account/chart.html.erbindex 8c78ddb780..3fe34fe6c7 100644--- a/app/components/UI/account/chart.html.erb+++ b/app/components/UI/account/chart.html.erb@@ -28,6 +28,9 @@<div class="flex items-center gap-2"><% if account.supports_trades? %><%= form_with url: account_path(account), method: :get, data: { controller: "auto-submit-form" } do |form| %>+ <% chart_view_hidden_fields.each do |name, value| %>+ <%= hidden_field_tag name, value, id: nil %>+ <% end %><%= form.select :chart_view,[[t("UI.account.chart.views.total_value"), "balance"], [t("UI.account.chart.views.holdings"), "holdings_balance"], [t("UI.account.chart.views.cash"), "cash_balance"], [t("UI.account.chart.views.gains"), "gains"]],{ selected: view },@@ -41,6 +44,7 @@selected: period_picker_selected,url: account_path(account),extra_params: period_picker_extra_params,+ custom_extra_params: period_picker_custom_extra_params,options: period_picker_options) %></div>@@ -112,6 +116,8 @@class="w-full h-full privacy-sensitive"data-controller="time-series-chart"data-time-series-chart-selectable-value="true"+ data-time-series-chart-linked-range-params-value="<%= ACTIVITY_RANGE_PARAMS.to_json %>"+ data-time-series-chart-reset-params-value="<%= ACTIVITY_RESET_PARAMS.to_json %>"data-time-series-chart-data-value="<%= series.to_json %>"></div><% else %><div class="w-full h-full flex items-center justify-center">diff --git a/app/components/UI/account/chart.rb b/app/components/UI/account/chart.rbindex 476c887b1b..36e0ef1348 100644--- a/app/components/UI/account/chart.rb+++ b/app/components/UI/account/chart.rb@@ -10,14 +10,22 @@ class UI::Account::Chart < ApplicationComponent# The page's reference date travels inside the payload (`today`), so the# component takes no date of its own. `extra_repayment` is the Extra# repayments tab's Loan::ExtraRepayment, which the period picker keeps.- def initialize(account:, period: nil, view: nil, loan_chart: nil, extra_repayment: nil)+ # `activity_filters` are the activity feed's `q` params: the feed follows a+ # range dragged on this chart, and a period picked here keeps its filters.+ def initialize(account:, period: nil, view: nil, loan_chart: nil, extra_repayment: nil, activity_filters: nil)@account = account@period = period@view = view@loan_chart = loan_chart@extra_repayment = extra_repayment+ @activity_filters = activity_filters.to_h.stringify_keysend+ # The activity feed's own date params, which a range dragged on the chart+ # sets alongside the chart's, and the page param a new range drops.+ ACTIVITY_RANGE_PARAMS = [ %w[q[start_date] q[end_date]] ].freeze+ ACTIVITY_RESET_PARAMS = %w[page].freeze+def loan_chart?loan_chart.present?end@@ -210,11 +218,34 @@ class UI::Account::Chart < ApplicationComponent# What each period link carries besides the period. Picking one reloads# the page, which rebuilds an applied extra only from its params, so the# links keep it, and the tab it was applied from.+ #+ # They also keep the activity feed's filters, except a date filter a drag+ # set: a preset replaces the dragged range, so activity dates equal to that+ # range's bounds go with it. Activity dates set to anything else were set+ # by hand and stay.def period_picker_extra_params- return { chart_view: view } if account.supports_trades?- return {} unless @extra_repayment&.applied?+ with_activity_filters(chart_params, activity_filters_outliving_range)+ end- { tab: "extra_repayments", extra_payment: @extra_repayment.to_params }+ # The custom row re-applies the range already shown, so it keeps every+ # activity filter.+ def period_picker_custom_extra_params+ with_activity_filters(chart_params, @activity_filters)+ end++ # Hidden fields the chart-view select submits with the view, as+ # [name, value] pairs: a range dragged on the chart (a custom period, which+ # unlike a preset is not remembered for the user) and the activity feed's+ # filters, so switching between balance, holdings, cash and gains keeps the+ # selection and the activity it filters.+ def chart_view_hidden_fields+ fields = {}+ if @period && @period.key.blank?+ fields[:start_date] = @period.start_date.iso8601+ fields[:end_date] = @period.end_date.iso8601+ end+ fields[:q] = @activity_filters if @activity_filters.present?+ flatten_params(fields)end# A saved period the loan chart does not offer shows the whole life, so its@@ -248,6 +279,37 @@ class UI::Account::Chart < ApplicationComponentendprivate+ def chart_params+ return { chart_view: view } if account.supports_trades?+ return {} unless @extra_repayment&.applied?++ { tab: "extra_repayments", extra_payment: @extra_repayment.to_params }+ end++ def with_activity_filters(params, filters)+ filters.present? ? params.merge(q: filters) : params+ end++ def activity_filters_outliving_range+ return @activity_filters if period.key.present?++ @activity_filters.reject do |key, value|+ (key == "start_date" && value == period.start_date.iso8601) ||+ (key == "end_date" && value == period.end_date.iso8601)+ end+ end++ def flatten_params(value, prefix = nil)+ case value+ when Hash+ value.flat_map { |key, nested| flatten_params(nested, prefix ? "#{prefix}[#{key}]" : key.to_s) }+ when Array+ value.flat_map { |nested| flatten_params(nested, "#{prefix}[]") }+ else+ [ [ prefix, value.to_s ] ]+ end+ end+# Prefixes positive gains with "+"; other views keep plain Money formatting.def signed_format(money)return money.format unless view == "gains" && money.amount.positive?diff --git a/app/components/UI/account_page.html.erb b/app/components/UI/account_page.html.erbindex ba4172c887..9e5d4f1bde 100644--- a/app/components/UI/account_page.html.erb+++ b/app/components/UI/account_page.html.erb@@ -7,7 +7,7 @@<%= render UI::Account::HealthStatus.new(account: account) %><%= render UI::Account::Chart.new(account: account, period: chart_period, view: chart_view, loan_chart: loan_chart,- extra_repayment: extra_repayment) %>+ extra_repayment: extra_repayment, activity_filters: activity_filters) %><% if (fx_coverage_start = fx_coverage_start_date).present? %><div class="px-3">diff --git a/app/components/UI/account_page.rb b/app/components/UI/account_page.rbindex 2f589b66e6..44bf8698b1 100644--- a/app/components/UI/account_page.rb+++ b/app/components/UI/account_page.rb@@ -103,6 +103,12 @@ class UI::AccountPage < ApplicationComponent@extra_repayment ||= Loan::ExtraRepayment.new(amount: nil, currency: account.currency)end+ # The activity feed's filters. The feed follows a range dragged on the+ # chart, so the chart needs them to carry through a period pick.+ def activity_filters+ activity_feed? ? activity_feed.q : {}+ end+def tab_content_for(tab)case tabwhen :activitydiff --git a/app/components/UI/period_picker.rb b/app/components/UI/period_picker.rbindex d13ad9f71a..72eac02d41 100644--- a/app/components/UI/period_picker.rb+++ b/app/components/UI/period_picker.rb@@ -15,17 +15,22 @@ class UI::PeriodPicker < ApplicationComponent## NOTE: `url` must be a path without a query string; pass query state via# `extra_params` so the picker can compose `?period=…` cleanly.- attr_reader :selected, :selected_key, :url, :frame, :extra_params, :placement, :options+ attr_reader :selected, :selected_key, :url, :frame, :extra_params, :custom_extra_params, :placement, :options# `options` narrows the menu to [key, label] pairs, for a chart that offers# its own timescales under the shared period keys (the loan chart). Without# it every Period is offered under its own short label.- def initialize(selected:, url:, frame: nil, extra_params: {}, placement: "bottom-end", options: nil)+ #+ # `custom_extra_params` replaces `extra_params` on the custom row, for a page+ # whose presets drop state tied to the range they replace (the account page's+ # dragged activity dates) while re-applying that range keeps it.+ def initialize(selected:, url:, frame: nil, extra_params: {}, custom_extra_params: nil, placement: "bottom-end", options: nil)@selected = selected@selected_key = selected.respond_to?(:key) ? selected.key : selected.to_s@url = url@frame = frame@extra_params = (extra_params || {}).symbolize_keys+ @custom_extra_params = custom_extra_params&.symbolize_keys || @extra_params@placement = placement@options = optionsend@@ -79,7 +84,7 @@ class UI::PeriodPicker < ApplicationComponent# what an anchor gives for free. A checked radio you can focus, announce and# re-activate for no effect is exactly how a radio group behaves anyway.def custom_href- "#{url}?#{extra_params.merge(start_date: selected.start_date, end_date: selected.end_date).to_query}"+ "#{url}?#{custom_extra_params.merge(start_date: selected.start_date, end_date: selected.end_date).to_query}"end# Both pickers navigate a Turbo frame, and a frame navigation leaves thediff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex 578572ff2f..21256d609e 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -224,8 +224,12 @@ class AccountsController < ApplicationController# Mirrors TransactionsController#clear_filter, but simpler: the account# activity feed has no cross-request stored filters to update, so this only# needs to redirect with one param removed from the current query string.+ # The chart's range and view stay: clearing an activity date a chart drag+ # set must not also reset the chart.def clear_filter- redirect_to account_path(@account, q: without_cleared_filter(activity_search_params.to_h), tab: "activity", page: params[:page], per_page: params[:per_page])+ redirect_to account_path(@account, q: without_cleared_filter(activity_search_params.to_h), tab: "activity", page: params[:page], per_page: params[:per_page],+ start_date: params[:start_date], end_date: params[:end_date],+ chart_view: params[:chart_view])enddef sparklinediff --git a/app/javascript/controllers/time_series_chart_controller.js b/app/javascript/controllers/time_series_chart_controller.jsindex 420e030fef..c4d9837375 100644--- a/app/javascript/controllers/time_series_chart_controller.js+++ b/app/javascript/controllers/time_series_chart_controller.js@@ -12,6 +12,12 @@ export default class extends Controller {useLabels: { type: Boolean, default: true },useTooltip: { type: Boolean, default: true },selectable: { type: Boolean, default: false },+ // [startParam, endParam] pairs a drag-selected range also sets, for a page+ // whose other content filters by dates of its own and follows the chart.+ linkedRangeParams: { type: Array, default: [] },+ // Params a drag-selected range drops, such as the page of a list it now+ // filters.+ resetParams: { type: Array, default: [] },};_d3SvgMemo = null;@@ -692,10 +698,19 @@ export default class extends Controller {_navigateToDateRange(startDate, endDate) {const formatDate = d3.timeFormat("%Y-%m-%d");const url = new URL(window.location.href);+ const start = formatDate(startDate);+ const end = formatDate(endDate);url.searchParams.delete("period");- url.searchParams.set("start_date", formatDate(startDate));- url.searchParams.set("end_date", formatDate(endDate));+ for (const param of this.resetParamsValue) url.searchParams.delete(param);++ for (const [startParam, endParam] of [+ ["start_date", "end_date"],+ ...this.linkedRangeParamsValue,+ ]) {+ url.searchParams.set(startParam, start);+ url.searchParams.set(endParam, end);+ }Turbo.visit(url.toString());}diff --git a/test/components/UI/account/chart_test.rb b/test/components/UI/account/chart_test.rbindex 760e27bc35..ebcf90ac28 100644--- a/test/components/UI/account/chart_test.rb+++ b/test/components/UI/account/chart_test.rb@@ -331,7 +331,71 @@ class UI::Account::ChartTest < ViewComponent::TestCaseassert_equal family_oldest, component.period.start_dateend+ test "a range dragged on the chart also sets the activity feed's dates and drops its page" do+ render_inline(UI::Account::Chart.new(account: accounts(:depository)))++ chart = page.find("#lineChart")+ assert_equal [ %w[q[start_date] q[end_date]] ], JSON.parse(chart["data-time-series-chart-linked-range-params-value"])+ assert_equal %w[page], JSON.parse(chart["data-time-series-chart-reset-params-value"])+ end++ test "preset links drop activity dates a drag set and keep the other activity filters" do+ range = Period.custom(start_date: Date.new(2026, 1, 5), end_date: Date.new(2026, 2, 10))++ links = period_links(range, "start_date" => "2026-01-05", "end_date" => "2026-02-10", "search" => "coffee")++ links[:presets].each do |q|+ assert_equal({ "search" => "coffee" }, q)+ end+ assert_equal({ "start_date" => "2026-01-05", "end_date" => "2026-02-10", "search" => "coffee" }, links[:custom])+ end++ test "preset links keep activity dates set to something other than the dragged range" do+ range = Period.custom(start_date: Date.new(2026, 1, 5), end_date: Date.new(2026, 2, 10))++ links = period_links(range, "start_date" => "2026-01-05", "end_date" => "2026-01-31")++ links[:presets].each do |q|+ assert_equal({ "end_date" => "2026-01-31" }, q)+ end+ end++ test "period links keep array activity filters from the permitted params" do+ range = Period.custom(start_date: Date.new(2026, 1, 5), end_date: Date.new(2026, 2, 10))+ filters = ActionController::Parameters.new(start_date: "2026-01-05", end_date: "2026-02-10", categories: %w[Food Rent])+ .permit(:start_date, :end_date, categories: [])++ links = period_links(range, filters)++ links[:presets].each do |q|+ assert_equal({ "categories" => %w[Food Rent] }, q)+ end+ assert_equal %w[Food Rent], links[:custom]["categories"]+ end++ test "preset links keep activity dates while a preset is shown" do+ links = period_links(Period.last_30_days, "start_date" => 30.days.ago.to_date.iso8601, "end_date" => Date.current.iso8601)++ assert_nil links[:custom]+ links[:presets].each do |q|+ assert_equal({ "start_date" => 30.days.ago.to_date.iso8601, "end_date" => Date.current.iso8601 }, q)+ end+ end+private+ # The activity `q` each period link carries: one per preset, and the+ # custom row's when a custom range is shown.+ def period_links(period, activity_filters)+ account = accounts(:depository)+ render_inline(UI::Account::Chart.new(account: account, period: period, activity_filters: activity_filters))++ queries = page.all("a[role='menuitemradio']").map do |link|+ Rack::Utils.parse_nested_query(URI.parse(link[:href]).query)+ end+ custom = queries.find { |query| query.key?("start_date") }+ { presets: (queries - [ custom ]).map { |query| query["q"] || {} }, custom: custom&.dig("q") }+ end+# 10 shares at $100 market price; gain = 1000 - cost_basis * 10def create_holding(cost_basis:)Holding.create!(diff --git a/test/components/UI/period_picker_test.rb b/test/components/UI/period_picker_test.rbindex 02e777ee9f..a6b064b8a3 100644--- a/test/components/UI/period_picker_test.rb+++ b/test/components/UI/period_picker_test.rb@@ -89,6 +89,27 @@ class UI::PeriodPickerTest < ViewComponent::TestCaseassert_match(/end_date=#{custom_period.end_date}/, checked.first[:href])end+ test "custom_extra_params replace extra_params on the custom row only" do+ custom_period = Period.custom(start_date: 15.days.ago.to_date, end_date: Date.current)++ render_inline(UI::PeriodPicker.new(+ selected: custom_period, url: "/accounts/abc",+ extra_params: { chart_view: "balance" }, custom_extra_params: { chart_view: "gains" }+ ))++ links = page.all("a[role='menuitemradio']")+ assert links[0...-1].all? { |link| link[:href].include?("chart_view=balance") }+ assert_includes links.last[:href], "chart_view=gains"+ end++ test "the custom row takes extra_params without custom_extra_params" do+ custom_period = Period.custom(start_date: 15.days.ago.to_date, end_date: Date.current)++ render_inline(UI::PeriodPicker.new(selected: custom_period, url: "/", extra_params: { chart_view: "balance" }))++ assert_includes page.all("a[role='menuitemradio']").last[:href], "chart_view=balance"+ end+test "a preset selection renders no custom row" dorender_inline(UI::PeriodPicker.new(selected: Period.last_30_days, url: "/"))diff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 7fae2ca5c2..3871be20a1 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -1012,6 +1012,69 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to account_url(@account, q: { search: "grocery" }, tab: "activity", page: nil, per_page: nil)end+ test "clear_filter keeps the chart's range and view" do+ delete clear_filter_account_url(@account), params: {+ q: { start_date: "2026-01-05", end_date: "2026-02-10" },+ start_date: "2026-01-05", end_date: "2026-02-10", chart_view: "balance",+ param_key: "start_date",+ param_value: "2026-01-05"+ }++ assert_redirected_to account_url(@account, q: { end_date: "2026-02-10" }, tab: "activity",+ start_date: "2026-01-05", end_date: "2026-02-10", chart_view: "balance")+ end++ test "show's period links keep the activity filters but not the dates of the range they replace" do+ get account_url(@account), params: {+ start_date: "2026-01-05", end_date: "2026-02-10",+ q: { start_date: "2026-01-05", end_date: "2026-02-10", search: "grocery" }+ }++ assert_response :success+ preset = css_select("a[role='menuitemradio']").find { |link| link["href"].include?("period=last_90_days") }+ query = Rack::Utils.parse_nested_query(URI.parse(preset["href"]).query)+ assert_equal({ "search" => "grocery" }, query["q"])+ end++ test "show's chart-view select keeps a dragged range and the activity filters" do+ get account_url(accounts(:investment)), params: {+ start_date: "2026-01-05", end_date: "2026-02-10",+ q: { start_date: "2026-01-05", end_date: "2026-02-10", search: "grocery" }+ }++ assert_response :success+ form = css_select("form").find { |f| f.at_css("select[name='chart_view']") }+ hidden = form.css("input[type='hidden']").to_h { |input| [ input["name"], input["value"] ] }+ assert_equal "2026-01-05", hidden["start_date"]+ assert_equal "2026-02-10", hidden["end_date"]+ assert_equal "2026-01-05", hidden["q[start_date]"]+ assert_equal "2026-02-10", hidden["q[end_date]"]+ assert_equal "grocery", hidden["q[search]"]+ end++ test "show's chart-view select carries no range for a preset period" do+ get account_url(accounts(:investment)), params: { period: "last_90_days" }++ assert_response :success+ form = css_select("form").find { |f| f.at_css("select[name='chart_view']") }+ names = form.css("input[type='hidden']").map { |input| input["name"] }+ assert_not_includes names, "start_date"+ assert_not_includes names, "end_date"+ end++ test "show's activity search keeps the chart's range and view for its badges' clear links" do+ get account_url(accounts(:investment)), params: {+ start_date: "2026-01-05", end_date: "2026-02-10", chart_view: "holdings_balance", tab: "activity"+ }++ assert_response :success+ form = css_select("form").find { |f| f.at_css("input[name='q[search]']") }+ hidden = form.css("input[type='hidden']").to_h { |input| [ input["name"], input["value"] ] }+ assert_equal "2026-01-05", hidden["start_date"]+ assert_equal "2026-02-10", hidden["end_date"]+ assert_equal "holdings_balance", hidden["chart_view"]+ end+test "clear_filter drops the amount_operator once amount is cleared" dodelete clear_filter_account_url(@account), params: {q: { amount: "50", amount_operator: "equal" },diff --git a/test/system/account_chart_drag_select_test.rb b/test/system/account_chart_drag_select_test.rbindex dd03cf3718..cd60214bf0 100644--- a/test/system/account_chart_drag_select_test.rb+++ b/test/system/account_chart_drag_select_test.rb@@ -1,6 +1,8 @@require "application_system_test_case"class AccountChartDragSelectTest < ApplicationSystemTestCase+ include EntriesTestHelper+setup do@user = users(:family_admin)@account = accounts(:depository)@@ -16,4 +18,47 @@ class AccountChartDragSelectTest < ApplicationSystemTestCaseassert_current_path(%r{/accounts/#{@account.id}\?.*start_date=.*end_date=})end++ test "a dragged range filters the activity feed until a preset period replaces it" do+ inside = create_transaction(account: @account, name: "Inside the range", date: 15.days.ago.to_date)+ outside = create_transaction(account: @account, name: "Before the range", date: 60.days.ago.to_date)++ sign_in @user+ visit account_url(@account, period: "last_30_days", q: { search: "range" })+ assert_selector "##{dom_id(outside)}"++ drag_across find("#lineChart .drag-select-brush .overlay", visible: :all)++ assert_current_path(/q%5Bstart_date%5D=/)+ query = Rack::Utils.parse_nested_query(URI.parse(current_url).query)+ assert_equal query["start_date"], query.dig("q", "start_date")+ assert_equal query["end_date"], query.dig("q", "end_date")+ assert_equal "range", query.dig("q", "search")++ assert_selector "##{dom_id(inside)}"+ assert_no_selector "##{dom_id(outside)}"+ within "#account-activity-filters" do+ assert_selector "li", text: I18n.t("transactions.searches.filters.badge.on_or_after", date: query["start_date"])+ assert_selector "li", text: I18n.t("transactions.searches.filters.badge.on_or_before", date: query["end_date"])+ end++ find("button[aria-label^='#{I18n.t("UI.period_picker.aria_label", period: "")}']").click+ wait_for_turbo_load { click_link "90D" }++ assert_selector "button[aria-label='#{I18n.t("UI.period_picker.aria_label", period: "90D")}']"+ assert_selector "##{dom_id(outside)}"+ assert_no_selector "#account-activity-filters li", text: query["start_date"]+ assert_selector "#account-activity-filters li", text: "range"+ assert_no_current_path(/start_date/)+ end++ private+ # A pick renders its frame, then Turbo promotes it to a page visit that+ # pushes the new URL; wait for that visit before reading the URL.+ def wait_for_turbo_load+ execute_script("document.addEventListener('turbo:load', () => document.documentElement.dataset.turboLoaded = '', { once: true })")+ yield+ assert_selector "html[data-turbo-loaded]", visible: :all+ execute_script("delete document.documentElement.dataset.turboLoaded")+ endend