The personal finance app for everyone (by everyone)
Ruby
Add category/tag/merchant/type filters to account activity feed (#3814)
GFR39e18c751cfb
diff --git a/app/components/UI/account/activity_feed.html.erb b/app/components/UI/account/activity_feed.html.erbindex 354fb6413b..459834849f 100644--- a/app/components/UI/account/activity_feed.html.erb+++ b/app/components/UI/account/activity_feed.html.erb@@ -52,6 +52,7 @@scope: :q,method: :get,data: { controller: "auto-submit-form" } do |form| %>+ <%= hidden_field_tag :tab, "activity" %><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">@@ -61,7 +62,7 @@<%= form.search_field :search,placeholder: t("accounts.show.activity.search.placeholder"),- value: search,+ value: q[:search],class: "form-field__input placeholder:text-sm placeholder:text-secondary","data-auto-submit-form-target": "auto" %></div>@@ -69,7 +70,7 @@<%= render DS::Popover.new(variant: "button", no_padding: true) do |popover| %><% popover.with_button(- id: "activity-status-filter-button",+ id: "activity-filters-button",type: "button",text: t("accounts.show.activity.filter"),variant: "outline",@@ -77,40 +78,10 @@) %><% popover.with_custom_content do %>- <div class="p-3 space-y-3 min-w-[160px]">- <p class="text-xs font-medium text-secondary uppercase"><%= t("accounts.show.activity.status") %></p>- <div class="flex items-center gap-3">- <%= check_box_tag "q[status][]",- "confirmed",- params.dig(:q, :status)&.include?("confirmed"),- id: "q_status_confirmed",- class: "checkbox checkbox--light",- form: "entries-search",- onchange: "document.getElementById('entries-search').requestSubmit()" %>- <%= label_tag "q_status_confirmed", t("accounts.show.activity.confirmed"), class: "text-sm text-primary" %>- </div>- <div class="flex items-center gap-3">- <%= check_box_tag "q[status][]",- "pending",- params.dig(:q, :status)&.include?("pending"),- id: "q_status_pending",- class: "checkbox checkbox--light",- form: "entries-search",- onchange: "document.getElementById('entries-search').requestSubmit()" %>- <%= label_tag "q_status_pending", t("accounts.show.activity.pending"), class: "text-sm text-primary" %>- </div>- <p class="text-xs font-medium text-secondary uppercase pt-1"><%= t("accounts.show.activity.category") %></p>- <div class="flex items-center gap-3">- <%= check_box_tag "q[uncategorized]",- "1",- params.dig(:q, :uncategorized) == "1",- id: "q_uncategorized",- class: "checkbox checkbox--light",- form: "entries-search",- onchange: "document.getElementById('entries-search').requestSubmit()" %>- <%= label_tag "q_uncategorized", t("accounts.show.activity.uncategorized_only"), class: "text-sm text-primary" %>- </div>- </div>+ <%= render "transactions/searches/menu",+ form: form,+ exclude: [ "account_filter", "ai_filter" ],+ clear_filters_path: helpers.account_path(account, tab: "activity") %><% end %><% end %><% end %>@@ -125,6 +96,29 @@<%= helpers.icon("list-todo") %><% end %></div>++ <ul id="account-activity-filters" class="flex items-center flex-wrap gap-2 mb-4">+ <% q.reject { |key| key == "amount_operator" }.each do |param_key, param_value| %>+ <% unless param_value.blank? %>+ <% if param_key == "amount" %>+ <% amount_operator = helpers.transaction_amount_operator_label(q[:amount_operator]) %>+ <%= render partial: "transactions/searches/filters/badge", locals: {+ param_key: "amount",+ param_value: "#{amount_operator} #{param_value}",+ clear_filter_path: helpers.clear_filter_account_path(account, param_key: "amount", param_value: param_value, **request.query_parameters)+ } %>+ <% else %>+ <% Array(param_value).each do |value| %>+ <%= render partial: "transactions/searches/filters/badge", locals: {+ param_key: param_key,+ param_value: value,+ clear_filter_path: helpers.clear_filter_account_path(account, param_key: param_key, param_value: value, **request.query_parameters)+ } %>+ <% end %>+ <% end %>+ <% end %>+ <% end %>+ </ul></div><% if activity_dates.empty? %>diff --git a/app/components/UI/account/activity_feed.rb b/app/components/UI/account/activity_feed.rbindex bb7fa3a128..6572e746e6 100644--- a/app/components/UI/account/activity_feed.rb+++ b/app/components/UI/account/activity_feed.rb@@ -1,10 +1,10 @@class UI::Account::ActivityFeed < ApplicationComponent- attr_reader :feed_data, :pagy, :search+ attr_reader :feed_data, :pagy, :q- def initialize(feed_data:, pagy:, search: nil)+ def initialize(feed_data:, pagy:, q: {})@feed_data = feed_data@pagy = pagy- @search = search+ @q = q || {}enddef iddiff --git a/app/components/UI/account_page.rb b/app/components/UI/account_page.rbindex dadf391f9c..1469450c9b 100644--- a/app/components/UI/account_page.rb+++ b/app/components/UI/account_page.rb@@ -2,7 +2,7 @@ class UI::AccountPage < ApplicationComponentattr_reader :account, :chart_view, :chart_period, :loan_chart, :as_of, :statement_coverage, :statements,:reconciliation_statuses, :can_manage_statements- renders_one :activity_feed, ->(feed_data:, pagy:, search:) { UI::Account::ActivityFeed.new(feed_data: feed_data, pagy: pagy, search: search) }+ renders_one :activity_feed, ->(feed_data:, pagy:, q:) { UI::Account::ActivityFeed.new(feed_data: feed_data, pagy: pagy, q: q) }# `loan_chart` is the Loan::PayoffChart payload the controller built for a# loan account, nil for every other type and for a loan with no schedule.diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex c601e9eefa..d67c369a8d 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -1,7 +1,7 @@class AccountsController < ApplicationControllerinclude StreamExtensions- before_action :set_account, only: %i[show sparkline sync set_default remove_default]+ before_action :set_account, only: %i[show sparkline sync set_default remove_default clear_filter]before_action :set_manageable_account, only: %i[toggle_active toggle_exclude_from_reports destroy unlink confirm_unlink select_provider]before_action :ensure_linked_account, only: %i[confirm_unlink unlink]include Periodable@@ -91,8 +91,8 @@ class AccountsController < ApplicationController# date beside a table shaded against another.@as_of = Date.current@accessible_account_ids = Current.user.accessible_accounts.pluck(:id).to_set- @q = params.fetch(:q, {}).permit(:search, :uncategorized, status: [])- entries = @account.entries.excluding_split_parents.search(@q).reverse_chronological.includes(:entryable)+ @q = activity_search_params+ entries = @account.entries.excluding_split_parents.search(@q, family).reverse_chronological.includes(:entryable)if statement_tab_active?build_statement_tab_datareturn render_statement_tab_frame if statement_tab_frame_request?@@ -198,6 +198,27 @@ class AccountsController < ApplicationControllerredirect_to account_path(@account)end+ # 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.+ def clear_filter+ q_params = activity_search_params.to_h++ param_key = params[:param_key]+ param_value = params[:param_value]++ if q_params[param_key].is_a?(Array)+ q_params[param_key].delete(param_value)+ q_params.delete(param_key) if q_params[param_key].empty?+ else+ q_params.delete(param_key)+ end++ q_params.delete("amount_operator") unless q_params["amount"].present?++ redirect_to account_path(@account, q: q_params.presence, tab: "activity", page: params[:page], per_page: params[:per_page])+ end+def sparklineetag_key = @account.family.build_cache_key("#{@account.id}_sparkline_#{Account::Chartable::SPARKLINE_CACHE_VERSION}", invalidate_on_data_updates: true)@@ -386,6 +407,15 @@ class AccountsController < ApplicationControllerCurrent.familyend+ def activity_search_params+ q = params.fetch(:q, {}).permit(+ :search, :start_date, :end_date, :amount, :amount_operator,+ categories: [], tags: [], merchants: [], types: [], status: []+ )+ q.delete(:amount_operator) unless q[:amount].present?+ q+ end+# Shares the "per page" preference with TransactionsController's# prev_transaction_page_params so the page size the user picks on either# the account activity feed or the global transactions page applies to both.diff --git a/app/helpers/transactions_helper.rb b/app/helpers/transactions_helper.rbindex ca01192315..60a9a0439f 100644--- a/app/helpers/transactions_helper.rb+++ b/app/helpers/transactions_helper.rb@@ -1,7 +1,10 @@module TransactionsHelper+ # @param exclude [Array<String>] filter keys to leave out (e.g. the account+ # tab doesn't apply to the account activity feed, which is already scoped+ # to one account)# @return [Array<Hash>] the filters offered above the transaction list, each# with the key its partial is named for, a translated label and an icon- def transaction_search_filters+ def transaction_search_filters(exclude: [])[{ key: "account_filter", label: t("transactions.search.filters.account"), icon: "layers" },{ key: "date_filter", label: t("transactions.search.filters.date"), icon: "calendar" },@@ -13,7 +16,7 @@ module TransactionsHelper{ key: "merchant_filter", label: t("transactions.search.filters.merchant"), icon: "store" },{ key: "ai_filter", label: t("transactions.search.filters.ai"), icon: "sparkles" },{ key: "attachment_filter", label: t("transactions.search.filters.attachment"), icon: "paperclip" }- ]+ ].reject { |filter| exclude.include?(filter[:key]) }end# @param label [String] a stored investment_activity_label such as "Sweep In"@@ -34,6 +37,20 @@ module TransactionsHelpertransaction_search_filters[0]end+ # Shared between the transactions page and the account activity feed's+ # amount filter badge, so the label doesn't drift out of sync with the+ # options offered in filters/_amount_filter.html.erb.+ # @param operator [String, nil] "equal", "greater" or "less"+ # @return [String] the translated operator label+ def transaction_amount_operator_label(operator)+ case operator+ when "equal" then t("transactions.searches.search.equal_to")+ when "greater" then t("transactions.searches.search.greater_than")+ when "less" then t("transactions.searches.search.less_than")+ else operator.to_s+ end+ end+# A split child is only folded under its parent when the user asked for# grouping and the current view is rendering grouped.#diff --git a/app/models/entry.rb b/app/models/entry.rbindex 816dfe6a90..e0cceb454c 100644--- a/app/models/entry.rb+++ b/app/models/entry.rb@@ -565,8 +565,11 @@ class Entry < ApplicationRecordendclass << self- def search(params)- EntrySearch.new(params).build_query(all)+ # `family` is positional (not a keyword) on purpose: several callers pass+ # the filters as a bare keyword-style hash (`search(status: [...])`), and+ # a keyword parameter here would capture those as kwargs instead.+ def search(params, family = nil)+ EntrySearch.new(params, family: family).build_query(all)end# arbitrary cutoff date to avoid expensive sync operationsdiff --git a/app/models/entry_search.rb b/app/models/entry_search.rbindex d32867ca37..266112e8b6 100644--- a/app/models/entry_search.rb+++ b/app/models/entry_search.rb@@ -5,13 +5,25 @@ class EntrySearchattribute :search, :stringattribute :amount, :stringattribute :amount_operator, :string- attribute :types, :string+ attribute :types, array: trueattribute :status, array: true- attribute :uncategorized, :booleanattribute :accounts, array: trueattribute :account_ids, array: trueattribute :start_date, :stringattribute :end_date, :string+ attribute :categories, array: true+ attribute :tags, array: true+ attribute :merchants, array: true++ attr_reader :family++ # `family` is only required to scope the category-name lookup in+ # Transaction::Search.apply_category_filter (see #1480); every other filter+ # here works without it.+ def initialize(filters = {}, family: nil)+ @family = family+ super(filters)+ endclass << selfdef apply_search_filter(scope, search)@@ -59,15 +71,6 @@ class EntrySearchqueryend- # Uncategorized means what it means everywhere else (the Transactions- # "Uncategorized" filter, the uncategorized badge, Quick Categorize):- # Entry.uncategorized_transactions, which skips transfers and excluded entries.- def apply_uncategorized_filter(scope, uncategorized)- return scope unless uncategorized-- scope.where(id: Entry.uncategorized_transactions.select(:id))- end-def apply_status_filter(scope, statuses)return scope unless statuses.present?return scope if statuses.uniq.sort == %w[confirmed pending] # Both selected = no filter@@ -110,7 +113,27 @@ class EntrySearchquery = self.class.apply_amount_filter(query, amount, amount_operator)query = self.class.apply_accounts_filter(query, accounts, account_ids)query = self.class.apply_status_filter(query, status)- query = self.class.apply_uncategorized_filter(query, uncategorized)++ if transaction_specific_filters?+ # Only Transaction entries have a category/merchant/type/tags, so this+ # join is skipped unless one of those filters is active. Most of+ # Transaction::Search's apply_* methods exclude non-Transaction entries+ # as a side effect of their own conditions, but apply_type_filter+ # doesn't when every type is selected (it's a no-op then) — so exclude+ # non-Transaction entries explicitly here instead of relying on that.+ query = query.joins("LEFT JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")+ query = query.where(entries: { entryable_type: "Transaction" })+ query = Transaction::Search.apply_category_filter(query, categories, family)+ query = Transaction::Search.apply_type_filter(query, types)+ query = Transaction::Search.apply_merchant_filter(query, merchants)+ query = Transaction::Search.apply_tag_filter(query, tags)+ end+queryend++ private+ def transaction_specific_filters?+ categories.present? || types.present? || merchants.present? || tags.present?+ endenddiff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rbindex 209362fea6..cb4608fcba 100644--- a/app/models/transaction/search.rb+++ b/app/models/transaction/search.rb@@ -2,6 +2,147 @@ class Transaction::Searchinclude ActiveModel::Modelinclude ActiveModel::Attributes+ class << self+ # Filter by category, supporting the synthetic "Uncategorized" bucket and+ # its budget-tracking exclusions. Shared with EntrySearch (see+ # https://github.com/we-promise/sure/issues/1480), so `query` need not be+ # rooted on Transaction: it only needs a `transactions` table already+ # joined in (EntrySearch adds that join explicitly before calling this).+ #+ # `family` scopes the category-name lookup so two families that each+ # named a category the same way don't cross-contaminate the parent-id+ # match. Required (rather than silently falling back to a global+ # Category.all scope) so a future caller that forgets to thread family+ # through fails loudly instead of resolving parent categories across+ # every family's data.+ def apply_category_filter(query, categories, family)+ return query unless categories.present?+ raise ArgumentError, "family is required to filter by category" if family.nil?++ include_uncategorized = categories.include?(Category::UNCATEGORIZED_FILTER_VALUE)+ real_categories = categories - [ Category::UNCATEGORIZED_FILTER_VALUE ]++ parent_category_ids = family.categories.where(name: real_categories).pluck(:id)++ # The Uncategorized bucket answers "which rows have no category", so it+ # excludes only the kinds that have nothing to categorize — the paired+ # legs of a Transfer. Shared with Entry.uncategorized_transactions so+ # this list, the uncategorized badge count and the Quick Categorize+ # wizard can't drift apart. https://github.com/we-promise/sure/issues/2592+ #+ # For a non-Transaction entry (Valuation, Trade) `transactions.kind` is+ # NULL (no joined transaction row), so `NOT IN (...)` evaluates to NULL+ # and the row is excluded — no separate entryable_type guard needed.+ uncategorized_condition = "categories.id IS NULL AND transactions.kind NOT IN (?)"+ uncategorized_excluded_kinds = Transaction::UNCATEGORIZED_EXCLUDED_KINDS++ query = query.joins("LEFT JOIN categories ON categories.id = transactions.category_id")++ if parent_category_ids.empty?+ if include_uncategorized+ query.where(+ "categories.name IN (?) OR (#{uncategorized_condition})",+ real_categories.presence || [], uncategorized_excluded_kinds+ )+ else+ query.where(categories: { name: real_categories })+ end+ else+ if include_uncategorized+ query.where(+ "categories.name IN (?) OR categories.parent_id IN (?) OR (#{uncategorized_condition})",+ real_categories, parent_category_ids, uncategorized_excluded_kinds+ )+ else+ query.where(+ "categories.name IN (?) OR categories.parent_id IN (?)",+ real_categories, parent_category_ids+ )+ end+ end+ end++ # Filter by type (expense, income, or transfer). Table-qualified so it+ # works whether `query`'s own model is Transaction or (via EntrySearch) Entry.+ def apply_type_filter(query, types)+ return query unless types.present?+ return query if types.sort == [ "expense", "income", "transfer" ]++ case types.sort+ when [ "transfer" ]+ query.where(transactions: { kind: Transaction::TRANSFER_KINDS })+ when [ "expense" ]+ query.where("entries.amount >= 0").where.not(transactions: { kind: Transaction::TRANSFER_KINDS })+ when [ "income" ]+ query.where("entries.amount < 0").where.not(transactions: { kind: Transaction::TRANSFER_KINDS })+ when [ "expense", "transfer" ]+ query.where("entries.amount >= 0 OR transactions.kind IN (?)", Transaction::TRANSFER_KINDS)+ when [ "income", "transfer" ]+ query.where("entries.amount < 0 OR transactions.kind IN (?)", Transaction::TRANSFER_KINDS)+ when [ "expense", "income" ]+ query.where.not(transactions: { kind: Transaction::TRANSFER_KINDS })+ else+ query+ end+ end++ # Filter by merchant name, supporting the synthetic "No merchant" bucket.+ def apply_merchant_filter(query, merchants)+ return query unless merchants.present?++ include_no_merchant = merchants.include?(Merchant::NO_MERCHANT_FILTER_VALUE)+ real_merchants = merchants - [ Merchant::NO_MERCHANT_FILTER_VALUE ]++ query = query.joins("LEFT JOIN merchants ON merchants.id = transactions.merchant_id")++ if include_no_merchant+ # entries.entryable_type guards this branch specifically: without it,+ # a non-Transaction entry (no joined transaction row, so+ # merchants.id is also NULL) would satisfy "merchants.id IS NULL" and+ # wrongly show up under "No merchant" once EntrySearch reuses this.+ query.where(+ "(merchants.name IN (?) OR merchants.id IS NULL) AND entries.entryable_type = 'Transaction'",+ real_merchants+ )+ else+ query.where(merchants: { name: real_merchants })+ end+ end++ # Filter by tag name, matching any transaction that carries at least one+ # of the given tags (or, via the synthetic "Untagged" bucket, none at all).+ def apply_tag_filter(query, tags)+ return query unless tags.present?++ include_untagged = tags.include?(Tag::UNTAGGED_FILTER_VALUE)+ real_tags = tags - [ Tag::UNTAGGED_FILTER_VALUE ]++ # Use a subquery instead of an INNER/LEFT JOIN: `.joins(:tags)` fans out to+ # one row per matching tag, so a transaction tagged with two of the+ # filtered tags produces two rows and double-counts in the summary+ # box (COUNT / SUM) even though the list renders it once. A top-level+ # `.distinct` doesn't work either, since PostgreSQL rejects DISTINCT+ # combined with reverse_chronological's CASE-expression ORDER BY unless+ # that expression is also in the select list (PG::InvalidColumnReference).+ # `query` is already scoped to the current family, so the subquery+ # inherits that scoping too.+ # See https://github.com/we-promise/sure/issues/3174+ tagging_join = "LEFT JOIN taggings ON taggings.taggable_id = transactions.id AND taggings.taggable_type = 'Transaction'"+ tags_join = "LEFT JOIN tags ON tags.id = taggings.tag_id"++ matching_ids = if include_untagged+ # Same entryable_type guard as the merchant filter above: a+ # non-Transaction entry has no taggings row either, so tags.id is+ # NULL and would otherwise match "Untagged".+ query.joins(tagging_join).joins(tags_join)+ .where("(tags.name IN (?) OR tags.id IS NULL) AND entries.entryable_type = 'Transaction'", real_tags)+ .distinct.select(:id)+ else+ query.joins(tagging_join).joins(tags_join).where(tags: { name: real_tags }).distinct.select(:id)+ end+ query.where(id: matching_ids)+ end+ end# Automatic-categorization provenance filter values (used by the view)AI_STATUSES = %w[current history].freeze@@ -42,11 +183,11 @@ class Transaction::Searchquery = query.where(entries: { account_id: accessible_account_ids }) unless accessible_account_ids.nil?query = apply_active_accounts_filter(query, active_accounts_only)- query = apply_category_filter(query, categories)- query = apply_type_filter(query, types)+ query = self.class.apply_category_filter(query, categories, family)+ query = self.class.apply_type_filter(query, types)query = apply_status_filter(query, status)- query = apply_merchant_filter(query, merchants)- query = apply_tag_filter(query, tags)+ query = self.class.apply_merchant_filter(query, merchants)+ query = self.class.apply_tag_filter(query, tags)query = apply_ai_status_filter(query, ai_status)query = apply_attachment_status_filter(query, attachment_status)query = EntrySearch.apply_search_filter(query, search)@@ -137,114 +278,6 @@ class Transaction::Searchend- # Filter transactions by category, supporting uncategorized and budget exclusions- def apply_category_filter(query, categories)- return query unless categories.present?-- include_uncategorized = categories.include?(Category::UNCATEGORIZED_FILTER_VALUE)- real_categories = categories - [ Category::UNCATEGORIZED_FILTER_VALUE ]-- # Get parent category IDs for the given category names- parent_category_ids = family.categories.where(name: real_categories).pluck(:id)-- # The Uncategorized bucket answers "which rows have no category", so it- # excludes only the kinds that have nothing to categorize — the paired- # legs of a Transfer. Shared with Entry.uncategorized_transactions so- # this list, the uncategorized badge count and the Quick Categorize- # wizard can't drift apart. https://github.com/we-promise/sure/issues/2592- uncategorized_condition = "categories.id IS NULL AND transactions.kind NOT IN (?)"- uncategorized_excluded_kinds = Transaction::UNCATEGORIZED_EXCLUDED_KINDS-- # Build condition based on whether parent_category_ids is empty- if parent_category_ids.empty?- if include_uncategorized- query = query.left_joins(:category).where(- "categories.name IN (?) OR (#{uncategorized_condition})",- real_categories.presence || [], uncategorized_excluded_kinds- )- else- query = query.left_joins(:category).where(categories: { name: real_categories })- end- else- if include_uncategorized- query = query.left_joins(:category).where(- "categories.name IN (?) OR categories.parent_id IN (?) OR (#{uncategorized_condition})",- real_categories, parent_category_ids, uncategorized_excluded_kinds- )- else- query = query.left_joins(:category).where(- "categories.name IN (?) OR categories.parent_id IN (?)",- real_categories, parent_category_ids- )- end- end-- query- end-- # Filter transactions by type (expense, income, or transfer)- def apply_type_filter(query, types)- return query unless types.present?- return query if types.sort == [ "expense", "income", "transfer" ]-- case types.sort- when [ "transfer" ]- query.where(kind: Transaction::TRANSFER_KINDS)- when [ "expense" ]- query.where("entries.amount >= 0").where.not(kind: Transaction::TRANSFER_KINDS)- when [ "income" ]- query.where("entries.amount < 0").where.not(kind: Transaction::TRANSFER_KINDS)- when [ "expense", "transfer" ]- query.where("entries.amount >= 0 OR transactions.kind IN (?)", Transaction::TRANSFER_KINDS)- when [ "income", "transfer" ]- query.where("entries.amount < 0 OR transactions.kind IN (?)", Transaction::TRANSFER_KINDS)- when [ "expense", "income" ]- query.where.not(kind: Transaction::TRANSFER_KINDS)- else- query- end- end-- # Filter transactions by merchant name- def apply_merchant_filter(query, merchants)- return query unless merchants.present?-- include_no_merchant = merchants.include?(Merchant::NO_MERCHANT_FILTER_VALUE)- real_merchants = merchants - [ Merchant::NO_MERCHANT_FILTER_VALUE ]-- if include_no_merchant- query.left_joins(:merchant).where("merchants.name IN (?) OR merchants.id IS NULL", real_merchants)- else- query.joins(:merchant).where(merchants: { name: real_merchants })- end- end-- # Filter transactions by tag name, matching any transaction that carries- # at least one of the given tags.- def apply_tag_filter(query, tags)- return query unless tags.present?-- include_untagged = tags.include?(Tag::UNTAGGED_FILTER_VALUE)- real_tags = tags - [ Tag::UNTAGGED_FILTER_VALUE ]-- # Use a subquery instead of an INNER/LEFT JOIN: `.joins(:tags)` fans out to- # one row per matching tag, so a transaction tagged with two of the- # filtered tags produces two rows and double-counts in the summary- # box (COUNT / SUM) even though the list renders it once. A top-level- # `.distinct` doesn't work either, since PostgreSQL rejects DISTINCT- # combined with reverse_chronological's CASE-expression ORDER BY unless- # that expression is also in the select list (PG::InvalidColumnReference).- # `query` is already scoped to the current family, so the subquery- # inherits that scoping too.- # See https://github.com/we-promise/sure/issues/3174- matching_ids = if include_untagged- query.left_joins(:tags).where("tags.name IN (?) OR tags.id IS NULL", real_tags).distinct.select(:id)- else- query.joins(:tags).where(tags: { name: real_tags }).distinct.select(:id)- end- query.where(id: matching_ids)- end-# Filter by automatic-categorization provenance. Uses EXISTS so a# transaction with both an ai and a bayes enrichment row can't be# duplicated in the list or double-counted in totals (see #3174).diff --git a/app/views/accounts/show.html.erb b/app/views/accounts/show.html.erbindex edb1548d97..975c618def 100644--- a/app/views/accounts/show.html.erb+++ b/app/views/accounts/show.html.erb@@ -11,5 +11,5 @@reconciliation_statuses: @statement_reconciliation_statuses,can_manage_statements: @can_manage_statements) do |account_page| %>- <%= account_page.with_activity_feed(feed_data: @activity_feed_data, pagy: @pagy, search: @q[:search]) %>+ <%= account_page.with_activity_feed(feed_data: @activity_feed_data, pagy: @pagy, q: @q) %><% end %>diff --git a/app/views/transactions/searches/_menu.html.erb b/app/views/transactions/searches/_menu.html.erbindex 2de3555c15..13d0601788 100644--- a/app/views/transactions/searches/_menu.html.erb+++ b/app/views/transactions/searches/_menu.html.erb@@ -1,14 +1,15 @@-<%# locals: (form:) %>+<%# locals: (form:, exclude: [], clear_filters_path: nil) %>+<% filters = transaction_search_filters(exclude: exclude) %><%= render DS::Tabs.new(variant: :unstyled,- active_tab: get_default_transaction_search_filter[:key],+ active_tab: filters.first[:key],active_btn_classes: "bg-surface text-primary",inactive_btn_classes: "text-secondary hover:bg-container-inset") do |tabs| %><div id="transaction-filters-menu" class="flex flex-col md:flex-row h-[50vh] lg:max-h-auto z-10 md:h-80 w-full md:w-[540px] top-12 right-0 overflow-hidden"><%= tabs.with_nav(classes: "shrink-0 flex w-full md:w-44 flex-row md:flex-col items-start p-3 text-sm font-medium text-secondary border-b md:border-b-0 md:border-r border-secondary overflow-x-auto md:overflow-x-visible md:overflow-y-auto") do |nav| %>- <% transaction_search_filters.each do |filter| %>+ <% filters.each do |filter| %><%= nav.with_btn(id: filter[:key], label: filter[:label], classes: "w-full px-3 py-2 flex gap-2 items-center rounded-md") do %><%= icon(filter[:icon]) %><%= tag.span(filter[:label], class: "text-sm font-medium") %>@@ -18,7 +19,7 @@<div class="flex flex-col grow overflow-y-auto"><div class="grow p-3 border-b border-secondary overflow-y-auto">- <% transaction_search_filters.each do |filter| %>+ <% filters.each do |filter| %><%= tabs.with_panel(tab_id: filter[:key]) do %><%= render partial: get_transaction_search_filter_partial_path(filter), locals: { form: form } %><% end %>@@ -31,7 +32,7 @@<%= render DS::Link.new(text: t(".clear_filters"),variant: "ghost",- href: transactions_path(clear_filters: true),+ href: clear_filters_path || transactions_path(clear_filters: true),) %><% end %></div>diff --git a/app/views/transactions/searches/_search.html.erb b/app/views/transactions/searches/_search.html.erbindex 0108d95abd..3b113811d8 100644--- a/app/views/transactions/searches/_search.html.erb+++ b/app/views/transactions/searches/_search.html.erb@@ -4,16 +4,7 @@<% @q.reject { |key| key == "amount_operator" }.each do |param_key, param_value| %><% unless param_value.blank? %><% if param_key == "amount" %>- <% amount_operator = case @q[:amount_operator]- when "equal"- t(".equal_to")- when "greater"- t(".greater_than")- when "less"- t(".less_than")- else- t(@q[:amount_operator])- end %>+ <% amount_operator = transaction_amount_operator_label(@q[:amount_operator]) %><%= render partial: "transactions/searches/filters/badge", locals: { param_key: "amount", param_value: "#{amount_operator} #{param_value}" } %><% else %><% Array(param_value).each do |value| %>diff --git a/app/views/transactions/searches/filters/_badge.html.erb b/app/views/transactions/searches/filters/_badge.html.erbindex 41dc345cd3..53cfe595f8 100644--- a/app/views/transactions/searches/filters/_badge.html.erb+++ b/app/views/transactions/searches/filters/_badge.html.erb@@ -1,4 +1,4 @@-<%# locals: (param_key:, param_value:) %>+<%# locals: (param_key:, param_value:, clear_filter_path: nil) %><li class="flex items-center gap-1 text-sm border border-secondary rounded-3xl p-1.5"><% if param_key == "start_date" || param_key == "end_date" %><div class="flex items-center gap-2">@@ -68,7 +68,7 @@</div><% end %>- <%= button_to clear_filter_transactions_path(param_key: param_key, param_value: param_value, **request.query_parameters),+ <%= button_to clear_filter_path || clear_filter_transactions_path(param_key: param_key, param_value: param_value, **request.query_parameters),method: :delete,data: { turbo: false },class: "flex items-center cursor-pointer" do %>diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex 7448bf64c1..be1f7cf50e 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -92,8 +92,6 @@ en:activity:amount: Amountbalance: Balance- category: Category- confirmed: Confirmeddate: Dateentries: entriesentry: entry@@ -105,13 +103,10 @@ en:new_transaction: New transactionnew_transfer: New transferno_entries: No entries found- pending: Pendingsearch:placeholder: Search entries by namesearch_placeholder: Search entries by name- status: Statustitle: Activity- uncategorized_only: Uncategorized onlychart:balance: Balanceowed: Amount oweddiff --git a/config/routes.rb b/config/routes.rbindex 070ed62fde..5bcedf4899 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -690,6 +690,7 @@ Rails.application.routes.draw doget :select_providerget :confirm_unlinkdelete :unlink+ delete :clear_filterendcollection dodiff --git a/test/controllers/accounts_controller_test.rb b/test/controllers/accounts_controller_test.rbindex 5668ea3976..a4916c0799 100644--- a/test/controllers/accounts_controller_test.rb+++ b/test/controllers/accounts_controller_test.rb@@ -21,10 +21,9 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestuncategorized = create_transaction(account: @account, name: "Uncategorized Filter Target", category: nil)categorized = create_transaction(account: @account, name: "Categorized Filter Decoy", category: categories(:food_and_drink))- get account_url(@account, q: { uncategorized: "1" })+ get account_url(@account, q: { categories: [ Category::UNCATEGORIZED_FILTER_VALUE ] })assert_response :success- assert_select "input#q_uncategorized[checked]"assert_match uncategorized.name, response.bodyassert_no_match categorized.name, response.bodyend@@ -473,6 +472,78 @@ class AccountsControllerTest < ActionDispatch::IntegrationTestassert_select "a[role='menuitemradio'][aria-checked='true'][href*='start_date=']", count: 1end+ test "show filter menu offers the same filters as transactions except the account tab" do+ get account_url(@account)++ assert_response :success+ assert_select "#transaction-filters-menu button[data-id=?]", "account_filter", count: 0+ assert_select "#transaction-filters-menu button[data-id=?]", "category_filter", count: 1+ assert_select "#transaction-filters-menu button[data-id=?]", "tag_filter", count: 1+ assert_select "#transaction-filters-menu button[data-id=?]", "merchant_filter", count: 1+ assert_select "#transaction-filters-menu button[data-id=?]", "type_filter", count: 1+ end++ test "show filters activity by category and excludes non-Transaction entries" do+ categorized = create_transaction(name: "Categorized", amount: 50, account: @account, category: categories(:food_and_drink))+ uncategorized = create_transaction(name: "Uncategorized", amount: 60, account: @account)+ valuation = @account.entries.create!(+ name: "Balance update", date: 1.day.ago.to_date, amount: 1000, currency: "USD", entryable: Valuation.new+ )++ get account_url(@account), params: { q: { categories: [ "Food & Drink" ] } }++ assert_response :success+ assert_select "##{dom_id(categorized)}"+ assert_select "##{dom_id(uncategorized)}", count: 0+ assert_select "##{dom_id(valuation)}", count: 0+ end++ test "show renders a badge for each active filter" do+ get account_url(@account), params: { q: { categories: [ "Food & Drink" ], search: "grocery" } }++ assert_response :success+ assert_select "#account-activity-filters li", count: 2+ end++ test "show renders badge delete links that preserve the other active filters" do+ get account_url(@account), params: { q: { categories: [ "Food & Drink" ], search: "grocery" } }++ assert_response :success+ doc = Nokogiri::HTML::Document.parse(response.body)+ badge = doc.css("#account-activity-filters li").find { |li| li.text.include?("Food & Drink") }+ form = badge&.at_css("form")++ assert_not_nil form, "expected the category badge to render a delete form"+ action_uri = URI.parse(form["action"])+ action_params = Rack::Utils.parse_nested_query(action_uri.query)++ # Regression: the badge's delete link must carry the *other* active+ # filters along (like clear_filter_transactions_path does via+ # request.query_parameters), or clearing one filter wipes them all.+ assert_equal "grocery", action_params.dig("q", "search"),+ "clearing the category badge must not drop the search filter from the delete link"+ end++ test "clear_filter removes only the targeted filter value and preserves the rest" do+ delete clear_filter_account_url(@account), params: {+ q: { categories: [ "Food & Drink" ], search: "grocery" },+ param_key: "categories",+ param_value: "Food & Drink"+ }++ assert_redirected_to account_url(@account, q: { search: "grocery" }, tab: "activity", page: nil, per_page: nil)+ end++ test "clear_filter drops the amount_operator once amount is cleared" do+ delete clear_filter_account_url(@account), params: {+ q: { amount: "50", amount_operator: "equal" },+ param_key: "amount",+ param_value: "50"+ }++ assert_redirected_to account_url(@account, q: nil, tab: "activity", page: nil, per_page: nil)+ end+test "show renders without missing translations" doget account_url(@account)diff --git a/test/helpers/transactions_helper_test.rb b/test/helpers/transactions_helper_test.rbindex 5391408f11..4ece956bd1 100644--- a/test/helpers/transactions_helper_test.rb+++ b/test/helpers/transactions_helper_test.rb@@ -134,6 +134,15 @@ class TransactionsHelperTest < ActionView::TestCaserefute_includes row[:value], "\\\""end+ # Regression: passing the raw operator straight to t() raised+ # I18n::ArgumentError for nil/blank (an empty key) and resolved a whole+ # translation subtree for a dotted value like "transactions.search".+ test "falls back to the raw operator instead of translating unknown or blank values" do+ assert_equal "", transaction_amount_operator_label(nil)+ assert_equal "foo", transaction_amount_operator_label("foo")+ assert_equal "transactions.search", transaction_amount_operator_label("transactions.search")+ end+test "falls back to a raw JSON dump for providers with no structured rendering" dodetails = build_transaction_extra_details(transaction_with({ "someprovider" => { "a" => 1 } }))diff --git a/test/models/account/entry_test.rb b/test/models/account/entry_test.rbindex 01ee4163b4..351d536e86 100644--- a/test/models/account/entry_test.rb+++ b/test/models/account/entry_test.rb@@ -73,13 +73,13 @@ class EntryTest < ActiveSupport::TestCasecategorized = create_transaction(account: account, name: "Has a category", category: categories(:food_and_drink))transfer_leg = create_transaction(account: account, name: "Transfer leg", category: nil, kind: "funds_movement")- ids = account.entries.search(uncategorized: true).pluck(:id)+ ids = account.entries.search({ categories: [ Category::UNCATEGORIZED_FILTER_VALUE ] }, account.family).pluck(:id)assert_includes ids, uncategorized.idassert_not_includes ids, categorized.idassert_not_includes ids, transfer_leg.id- assert_includes account.entries.search(uncategorized: false).pluck(:id), categorized.id+ assert_includes account.entries.search({ categories: [ categories(:food_and_drink).name ] }, account.family).pluck(:id), categorized.idendtest "status filter matches pending transactions for every supported provider via EntrySearch" dodiff --git a/test/models/entry_search_test.rb b/test/models/entry_search_test.rbnew file mode 100644index 0000000000..cd98ed9107--- /dev/null+++ b/test/models/entry_search_test.rb@@ -0,0 +1,132 @@+require "test_helper"++class EntrySearchTest < ActiveSupport::TestCase+ include EntriesTestHelper++ setup do+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @account.entries.delete_all+ end++ test "search filters entries by category, tag, merchant and type like Transaction::Search" do+ food = create_transaction(account: @account, amount: 100, category: categories(:food_and_drink))+ other = create_transaction(account: @account, amount: 100, category: categories(:income))++ result_ids = @account.entries.search(+ { categories: [ "Food & Drink" ] }, @family+ ).pluck(:id)++ assert_includes result_ids, food.id+ assert_not_includes result_ids, other.id+ end++ test "category filter excludes non-Transaction entries (Valuations, Trades)" do+ uncategorized_txn = create_transaction(account: @account, amount: 100)+ valuation = create_valuation(account: @account)++ result_ids = @account.entries.search(+ { categories: [ Category::UNCATEGORIZED_FILTER_VALUE ] }, @family+ ).pluck(:id)++ assert_includes result_ids, uncategorized_txn.id+ assert_not_includes result_ids, valuation.id+ end++ test "type filter excludes non-Transaction entries" do+ expense = create_transaction(account: @account, amount: 100, kind: "standard")+ valuation = create_valuation(account: @account)++ result_ids = @account.entries.search({ types: [ "expense" ] }).pluck(:id)++ assert_includes result_ids, expense.id+ assert_not_includes result_ids, valuation.id+ end++ test "type filter excludes non-Transaction entries even when every type is selected" do+ expense = create_transaction(account: @account, amount: 100, kind: "standard")+ valuation = create_valuation(account: @account)++ result_ids = @account.entries.search({ types: [ "expense", "income", "transfer" ] }).pluck(:id)++ assert_includes result_ids, expense.id+ assert_not_includes result_ids, valuation.id+ end++ test "merchant filter's No merchant bucket excludes non-Transaction entries" do+ without_merchant = create_transaction(account: @account, amount: 100)+ valuation = create_valuation(account: @account)++ result_ids = @account.entries.search(+ { merchants: [ Merchant::NO_MERCHANT_FILTER_VALUE ] }+ ).pluck(:id)++ assert_includes result_ids, without_merchant.id+ assert_not_includes result_ids, valuation.id+ end++ test "tag filter's Untagged bucket excludes non-Transaction entries" do+ without_tag = create_transaction(account: @account, amount: 100)+ valuation = create_valuation(account: @account)++ result_ids = @account.entries.search(+ { tags: [ Tag::UNTAGGED_FILTER_VALUE ] }+ ).pluck(:id)++ assert_includes result_ids, without_tag.id+ assert_not_includes result_ids, valuation.id+ end++ test "merchant filter for a real merchant name still excludes Valuations" do+ with_merchant = create_transaction(account: @account, amount: 100, merchant: merchants(:netflix))+ valuation = create_valuation(account: @account)++ result_ids = @account.entries.search(+ { merchants: [ merchants(:netflix).name ] }+ ).pluck(:id)++ assert_includes result_ids, with_merchant.id+ assert_not_includes result_ids, valuation.id+ end++ test "tag filter for a real tag name still excludes Valuations" do+ with_tag = create_transaction(account: @account, amount: 100, tags: [ tags(:one) ])+ valuation = create_valuation(account: @account)++ result_ids = @account.entries.search(+ { tags: [ tags(:one).name ] }+ ).pluck(:id)++ assert_includes result_ids, with_tag.id+ assert_not_includes result_ids, valuation.id+ end++ test "search / date / amount / status filters still apply to every entry type" do+ valuation = create_valuation(account: @account, amount: 5000)+ valuation.update!(name: "Reconciliation valuation")+ txn = create_transaction(account: @account, amount: 100, name: "Reconciliation check")++ result_ids = @account.entries.search({ search: "reconciliation" }).pluck(:id)++ assert_includes result_ids, valuation.id+ assert_includes result_ids, txn.id+ end++ test "without a transaction-specific filter, non-Transaction entries are not excluded" do+ valuation = create_valuation(account: @account)+ txn = create_transaction(account: @account, amount: 100)++ result_ids = @account.entries.search({}).pluck(:id)++ assert_includes result_ids, valuation.id+ assert_includes result_ids, txn.id+ end++ test "family is not required unless a category filter is used" do+ txn = create_transaction(account: @account, amount: 100, merchant: merchants(:netflix))++ result_ids = @account.entries.search({ merchants: [ merchants(:netflix).name ] }).pluck(:id)++ assert_includes result_ids, txn.id+ end+enddiff --git a/test/models/transaction/search_test.rb b/test/models/transaction/search_test.rbindex ee759e6580..a0f8220404 100644--- a/test/models/transaction/search_test.rb+++ b/test/models/transaction/search_test.rb@@ -350,6 +350,12 @@ class Transaction::SearchTest < ActiveSupport::TestCaseendend+ test "apply_category_filter requires family when categories are present" do+ assert_raises(ArgumentError) do+ Transaction::Search.apply_category_filter(Transaction.all, [ "Food & Drink" ], nil)+ end+ end+# Totals method tests (lifted from Transaction::TotalsTest)test "totals computes basic expense and income totals" dodiff --git a/test/system/account_activity_test.rb b/test/system/account_activity_test.rbindex 1423143240..4265d3386e 100644--- a/test/system/account_activity_test.rb+++ b/test/system/account_activity_test.rb@@ -70,6 +70,38 @@ class AccountActivityTest < ApplicationSystemTestCaseassert_operator page_scroll_width, :<=, viewport_widthend+ test "account activity filter menu has no account tab and can filter by category" do+ visit account_url(@account, tab: "activity")++ find("#activity-filters-button").click++ within "#transaction-filters-menu" do+ assert_no_selector "button[data-id='account_filter']"+ assert_selector "button[data-id='category_filter']"++ find("button[data-id='category_filter']").click+ check categories(:food_and_drink).name, allow_label_click: true+ click_button "Apply"+ end++ assert_selector "#account-activity-filters li", text: categories(:food_and_drink).name+ assert_selector "##{dom_id(@transaction_entry)}"+ assert_no_selector "##{dom_id(@valuation_entry)}"+ end++ test "clearing a filter badge on account activity removes just that filter" do+ visit account_url(@account, tab: "activity", q: { categories: [ categories(:food_and_drink).filter_value ] })++ assert_selector "#account-activity-filters li", text: categories(:food_and_drink).name++ within "#account-activity-filters li", text: categories(:food_and_drink).name do+ click_button+ end++ assert_no_selector "#account-activity-filters li"+ assert_selector "##{dom_id(@valuation_entry)}"+ end+test "account activity keeps long category names from overlapping the amount on wide screens" docategory = categories(:food_and_drink)category.update!(name: "Super Long Category Name That Should Stop Before The Amount On Wide Screens Too")diff --git a/test/system/account_activity_uncategorized_filter_test.rb b/test/system/account_activity_uncategorized_filter_test.rbindex a8c9a3453c..94351bf718 100644--- a/test/system/account_activity_uncategorized_filter_test.rb+++ b/test/system/account_activity_uncategorized_filter_test.rb@@ -17,8 +17,13 @@ class AccountActivityUncategorizedFilterTest < ApplicationSystemTestCaseassert_selector "##{dom_id(@categorized)}"assert_selector "##{dom_id(@uncategorized)}"- click_button "Filter"- check "Uncategorized only"+ find("#activity-filters-button").click++ within "#transaction-filters-menu" do+ find("button[data-id='category_filter']").click+ check Category.uncategorized.display_name, allow_label_click: true+ click_button "Apply"+ endassert_no_selector "##{dom_id(@categorized)}"assert_selector "##{dom_id(@uncategorized)}"