The personal finance app for everyone (by everyone)
Ruby
Add search and filters to the merchant page (#4663)
Dov Benyomin Sohacheskiee72c11a0af5
diff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex 7c0c051823..93f0cdc8f5 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -1,5 +1,6 @@class AccountsController < ApplicationControllerinclude StreamExtensions+ include FilterClearablebefore_action :set_account, only: %i[show sparkline sync set_default remove_default clear_filter]before_action :set_manageable_account, only: %i[logo_options toggle_active toggle_exclude_from_reports destroy unlink confirm_unlink select_provider]@@ -225,21 +226,7 @@ class AccountsController < ApplicationController# 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])+ redirect_to account_path(@account, q: without_cleared_filter(activity_search_params.to_h), tab: "activity", page: params[:page], per_page: params[:per_page])enddef sparklinediff --git a/app/controllers/concerns/filter_clearable.rb b/app/controllers/concerns/filter_clearable.rbnew file mode 100644index 0000000000..d47384d02a--- /dev/null+++ b/app/controllers/concerns/filter_clearable.rb@@ -0,0 +1,18 @@+module FilterClearable+ extend ActiveSupport::Concern++ private+ def without_cleared_filter(q_params)+ param_key = params[:param_key]++ if q_params[param_key].is_a?(Array)+ q_params[param_key].delete(params[: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?+ q_params.presence+ end+enddiff --git a/app/controllers/merchants_controller.rb b/app/controllers/merchants_controller.rbindex 21ec10fea2..a443477794 100644--- a/app/controllers/merchants_controller.rb+++ b/app/controllers/merchants_controller.rb@@ -1,6 +1,9 @@class MerchantsController < ApplicationController+ include FilterClearable+def show@merchant = find_merchant+ @q = search_params@breadcrumbs = [[ t("breadcrumbs.home"), root_path ],@@ -10,8 +13,10 @@ class MerchantsController < ApplicationController@accessible_account_ids = Current.user.accessible_accounts.pluck(:id)@search = merchant_search- @expense_totals = merchant_search(types: [ "expense" ]).totals- @average_expense_money = @expense_totals.expense_money / @expense_totals.count if @expense_totals.count.positive?+ if @q[:types].blank? || @q[:types].include?("expense")+ @expense_totals = merchant_search(types: [ "expense" ]).totals+ @average_expense_money = @expense_totals.expense_money / @expense_totals.count if @expense_totals.count.positive?+ end@first_date, @last_date = @search.transactions_scope.pick(Arel.sql("MIN(entries.date)"), Arel.sql("MAX(entries.date)"))@pagy, @transactions = pagy(@@ -27,7 +32,10 @@ class MerchantsController < ApplicationController@split_parents = load_split_parents@split_parent_entry_ids = Entry.split_parent_ids_among(@transactions.map { |t| t.entry.id })@projected_recurring = []- @q = {}+ end++ def clear_filter+ redirect_to merchant_path(find_merchant, q: without_cleared_filter(search_params), page: params[:page], per_page: params[:per_page])endprivate@@ -38,11 +46,20 @@ class MerchantsController < ApplicationControllerdef merchant_search(**filters)Transaction::Search.new(Current.family,- filters: { merchants: [ @merchant.name ], **filters },+ filters: { **@q.symbolize_keys, merchants: [ @merchant.name ], **filters },accessible_account_ids: @accessible_account_ids)end+ def search_params+ q = params.fetch(:q, {}).permit(+ :search, :start_date, :end_date, :amount, :amount_operator,+ accounts: [], categories: [], tags: [], types: [], status: []+ ).to_h.compact_blank+ q.delete("amount_operator") unless q["amount"].present?+ q+ end+def load_split_parentsreturn {} unless Current.user.show_split_grouped?diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex a6ea171228..6c904a3589 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -1,5 +1,6 @@class TransactionsController < ApplicationControllerinclude EntryableResource+ include FilterClearablebefore_action :set_entry_for_unlock, only: :unlockbefore_action :set_entry_for_tags, only: :update_tags@@ -104,25 +105,11 @@ class TransactionsController < ApplicationControllerdef clear_filterupdated_params = {- "q" => search_params,+ "q" => without_cleared_filter(search_params),"page" => params[:page],"per_page" => params[:per_page]}- q_params = updated_params["q"] || {}-- 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-- updated_params["q"] = q_params.presence-# Add flag to indicate filters were explicitly clearedupdated_params["filter_cleared"] = "1" if updated_params["q"].blank?diff --git a/app/views/merchants/show.html.erb b/app/views/merchants/show.html.erbindex 8269863b69..82247ae60b 100644--- a/app/views/merchants/show.html.erb+++ b/app/views/merchants/show.html.erb@@ -26,7 +26,9 @@<h2 class="text-base font-medium text-primary"><%= t(".summary") %></h2><dl class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-x-10 gap-y-3"><%= render DS::DetailRow.new(label: t(".total_transactions"), value: totals.count.to_s, align: :center, value_class: "privacy-sensitive") %>- <%= render DS::DetailRow.new(label: t(".total_spending"), value: format_money(@expense_totals.expense_money), align: :center, value_class: "privacy-sensitive") %>+ <% if @expense_totals %>+ <%= render DS::DetailRow.new(label: t(".total_spending"), value: format_money(@expense_totals.expense_money), align: :center, value_class: "privacy-sensitive") %>+ <% end %><% if @average_expense_money %><%= render DS::DetailRow.new(label: t(".average_transaction"), value: format_money(@average_expense_money), align: :center, value_class: "privacy-sensitive") %><% end %>@@ -37,5 +39,63 @@</dl><% end %>+ <div>+ <%= form_with url: merchant_path(@merchant),+ id: "merchant-transactions-search",+ scope: :q,+ method: :get,+ data: { controller: "auto-submit-form" } do |form| %>+ <%= hidden_field_tag :per_page, params[:per_page] %>++ <div class="flex gap-2">+ <%= render DS::SearchInput.new(+ name: "q[search]",+ value: @q[:search],+ placeholder: t("transactions.searches.form.search_placeholder"),+ class: "grow",+ data: { auto_submit_form_target: "auto" }+ ) %>++ <%= render DS::Popover.new(variant: "button", no_padding: true) do |popover| %>+ <% popover.with_button(+ id: "merchant-filters-button",+ type: "button",+ text: t("transactions.searches.form.filter"),+ variant: "outline",+ icon: "list-filter"+ ) %>++ <% popover.with_custom_content do %>+ <%= render "transactions/searches/menu",+ form: form,+ exclude: [ "merchant_filter", "ai_filter", "attachment_filter" ],+ clear_filters_path: merchant_path(@merchant, per_page: params[:per_page]) %>+ <% end %>+ <% end %>+ </div>+ <% end %>++ <% filter_badges = @q.except(:amount_operator) %>+ <% if filter_badges.present? %>+ <ul id="merchant-transaction-filters" class="flex items-center flex-wrap gap-2 mt-4">+ <% filter_badges.each do |param_key, param_value| %>+ <% if param_key == "amount" %>+ <%= render "transactions/searches/filters/badge",+ param_key: "amount",+ param_value: "#{transaction_amount_operator_label(@q[:amount_operator])} #{param_value}",+ clear_filter_path: clear_filter_merchant_path(@merchant, param_key: "amount", param_value: param_value, **request.query_parameters) %>+ <% else %>+ <% Array(param_value).each do |value| %>+ <%= render "transactions/searches/filters/badge",+ param_key: param_key,+ param_value: value,+ clear_filter_path: clear_filter_merchant_path(@merchant, param_key: param_key, param_value: value, **request.query_parameters) %>+ <% end %>+ <% end %>+ <% end %>+ </ul>+ <% end %>+ </div>+<%= render "transactions/list", transactions: @transactions, projected_recurring: @projected_recurring, q: @q, pagy: @pagy, toolbar: false %></div>diff --git a/config/routes.rb b/config/routes.rbindex 3fa96361d7..c17c5d18b5 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -542,7 +542,9 @@ Rails.application.routes.draw doendend- resources :merchants, only: :show+ resources :merchants, only: :show do+ delete :clear_filter, on: :member+ endresources :family_merchants, only: %i[index new create edit update destroy] docollection dodiff --git a/test/controllers/merchants_controller_test.rb b/test/controllers/merchants_controller_test.rbindex 21fce71785..a92010cf2d 100644--- a/test/controllers/merchants_controller_test.rb+++ b/test/controllers/merchants_controller_test.rb@@ -78,4 +78,62 @@ class MerchantsControllerTest < ActionDispatch::IntegrationTestassert_response :not_foundend++ test "filters the list and summary by the search" do+ create_transaction(account: accounts(:depository), name: "Netflix basic", merchant: @merchant, amount: 10)+ create_transaction(account: accounts(:depository), name: "Netflix premium", merchant: @merchant, amount: 20)++ get merchant_url(@merchant, q: { search: "premium" })++ assert_response :success+ assert_match "Netflix premium", response.body+ assert_no_match "Netflix basic", response.body+ assert_select "dt", text: "Total spending" do |dt|+ assert_equal "$20.00", dt.first.next_element.text.strip+ end+ assert_select "#merchant-transaction-filters form[action^=?]", clear_filter_merchant_path(@merchant)+ end++ test "leaves spending out of the summary when the type filter excludes expenses" do+ create_transaction(account: accounts(:depository), name: "Netflix plan", merchant: @merchant, amount: 10)+ create_transaction(account: accounts(:depository), name: "Netflix refund", merchant: @merchant, amount: -10)++ get merchant_url(@merchant, q: { types: [ "income" ] })++ assert_response :success+ assert_select "dt", text: "Total spending", count: 0+ assert_select "dt", text: "Average transaction", count: 0+ end++ test "keeps the page size when filtering" do+ get merchant_url(@merchant, per_page: 10, q: { search: "plan" })++ assert_select "#merchant-transactions-search input[type=hidden][name=per_page][value='10']"+ assert_select "a[href=?]", merchant_path(@merchant, per_page: 10), text: "Clear filters"+ end++ test "keeps the page's merchant when another one is passed in the filters" do+ create_transaction(account: accounts(:depository), name: "Netflix plan", merchant: @merchant)+ create_transaction(account: accounts(:depository), name: "Amazon order", merchant: merchants(:amazon))++ get merchant_url(@merchant, q: { merchants: [ merchants(:amazon).name ] })++ assert_response :success+ assert_match "Netflix plan", response.body+ assert_no_match "Amazon order", response.body+ end++ test "clearing a filter keeps the others" do+ delete clear_filter_merchant_url(@merchant, param_key: "categories", param_value: "Food", q: { search: "plan", categories: [ "Food", "Income" ] })++ assert_redirected_to merchant_path(@merchant, q: { search: "plan", categories: [ "Income" ] })+ end++ test "does not clear filters on another family's merchant" do+ other = families(:empty).merchants.create!(name: "Elsewhere")++ delete clear_filter_merchant_url(other, param_key: "search")++ assert_response :not_found+ endend