The personal finance app for everyone (by everyone)
Ruby
Add attachments filter to transactions list (#4161)
Roman Zippff51e7e2d96a
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex d59b29e27f..397b574a52 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -732,13 +732,16 @@ class TransactionsController < ApplicationControllerpermittedend+ # Permitted search filters from the q param, with blank values and+ # unsupported ai_status / attachment_status values dropped.def search_paramscleaned_params = params.fetch(:q, {}).permit(:start_date, :end_date, :search, :amount,:amount_operator, :active_accounts_only,accounts: [], account_ids: [],- categories: [], merchants: [], types: [], tags: [], status: [], ai_status: []+ categories: [], merchants: [], types: [], tags: [], status: [], ai_status: [],+ attachment_status: []).to_h.compact_blank@@ -750,6 +753,11 @@ class TransactionsController < ApplicationControllercleaned_params.delete(:ai_status) if cleaned_params[:ai_status].empty?end+ if cleaned_params[:attachment_status]+ cleaned_params[:attachment_status] &= Transaction::Search::ATTACHMENT_STATUSES+ cleaned_params.delete(:attachment_status) if cleaned_params[:attachment_status].empty?+ end+cleaned_paramsenddiff --git a/app/helpers/transactions_helper.rb b/app/helpers/transactions_helper.rbindex 954794789b..9471a1212b 100644--- a/app/helpers/transactions_helper.rb+++ b/app/helpers/transactions_helper.rb@@ -11,7 +11,8 @@ module TransactionsHelper{ key: "category_filter", label: t("transactions.search.filters.category"), icon: "shapes" },{ key: "tag_filter", label: t("transactions.search.filters.tag"), icon: "tags" },{ key: "merchant_filter", label: t("transactions.search.filters.merchant"), icon: "store" },- { key: "ai_filter", label: t("transactions.search.filters.ai"), icon: "sparkles" }+ { key: "ai_filter", label: t("transactions.search.filters.ai"), icon: "sparkles" },+ { key: "attachment_filter", label: t("transactions.search.filters.attachment"), icon: "paperclip" }]enddiff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rbindex 4cc2f4a18c..1e5603f981 100644--- a/app/models/transaction/search.rb+++ b/app/models/transaction/search.rb@@ -5,6 +5,8 @@ class Transaction::Search# Automatic-categorization provenance filter values (used by the view)AI_STATUSES = %w[current history].freeze+ ATTACHMENT_STATUSES = %w[with without].freeze+attribute :search, :stringattribute :amount, :stringattribute :amount_operator, :string@@ -18,6 +20,7 @@ class Transaction::Searchattribute :merchants, array: trueattribute :tags, array: trueattribute :ai_status, array: true+ attribute :attachment_status, array: trueattribute :active_accounts_only, :boolean, default: trueattr_reader :family, :accessible_account_ids@@ -45,6 +48,7 @@ class Transaction::Searchquery = apply_merchant_filter(query, merchants)query = 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)query = EntrySearch.apply_date_filters(query, start_date, end_date)query = EntrySearch.apply_amount_filter(query, amount, amount_operator)@@ -268,6 +272,29 @@ class Transaction::Searchsql + ")"end+ # EXISTS, not a join: several files on one transaction would duplicate+ # it in the list and double-count it in totals.+ def apply_attachment_status_filter(query, statuses)+ wanted = Array(statuses) & ATTACHMENT_STATUSES+ return query unless wanted.one?++ # Splitting leaves files on the hidden parent, so a split child counts+ # as attached when its parent is.+ attached_sql = <<~SQL.squish+ EXISTS (+ SELECT 1 FROM active_storage_attachments asa+ WHERE asa.record_type = 'Transaction'+ AND asa.name = 'attachments'+ AND asa.record_id IN (+ transactions.id,+ (SELECT pe.entryable_id FROM entries pe WHERE pe.id = entries.parent_entry_id)+ )+ )+ SQL++ wanted == [ "with" ] ? query.where(attached_sql) : query.where.not(attached_sql)+ end+# Filter transactions by status (pending or confirmed)def apply_status_filter(query, statuses)return query unless statuses.present?diff --git a/app/views/transactions/searches/filters/_attachment_filter.html.erb b/app/views/transactions/searches/filters/_attachment_filter.html.erbnew file mode 100644index 0000000000..0997cbf826--- /dev/null+++ b/app/views/transactions/searches/filters/_attachment_filter.html.erb@@ -0,0 +1,17 @@+<%# locals: (form:) %>++<div class="p-2 space-y-3">+ <% Transaction::Search::ATTACHMENT_STATUSES.each do |status| %>+ <div class="flex items-center gap-3" data-filter-name="<%= status %>">+ <%= form.check_box :attachment_status,+ {+ multiple: true,+ checked: @q[:attachment_status]&.include?(status),+ class: "checkbox checkbox--light"+ },+ status,+ nil %>+ <%= form.label :attachment_status, t(".#{status}"), value: status, class: "text-sm text-primary" %>+ </div>+ <% end %>+</div>diff --git a/app/views/transactions/searches/filters/_badge.html.erb b/app/views/transactions/searches/filters/_badge.html.erbindex d7ddafdfe7..1a6ecaeb58 100644--- a/app/views/transactions/searches/filters/_badge.html.erb+++ b/app/views/transactions/searches/filters/_badge.html.erb@@ -57,6 +57,11 @@<%= icon(param_value == "current" ? "sparkles" : "history", size: "sm") %><p><%= t(".ai_#{param_value}") %></p></div>+ <% elsif param_key == "attachment_status" %>+ <div class="flex items-center gap-2 px-1">+ <%= icon("paperclip", size: "sm") %>+ <p><%= t(".attachment_#{param_value}") %></p>+ </div><% else %><div class="flex items-center gap-2"><p><%= param_value %></p>diff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex d0f5e247f8..fe1bc8d1be 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -274,6 +274,7 @@ en:tag: Tagmerchant: Merchantai: AI+ attachment: Attachmentconvert_to_trade:title: Convert to Security Tradedescription: Convert this transaction into a trade with security details@@ -344,6 +345,11 @@ en:pending: Pendingai_current: AIai_history: AI history+ attachment_with: With attachment+ attachment_without: Without attachment+ attachment_filter:+ with: With attachment+ without: Without attachmentai_filter:current: AIcurrent_description: Category is still the one assigned automatically (AI or Bayes).diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 216db9ac16..d0cddc6c3b 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -1787,6 +1787,53 @@ endassert_no_match(/ai_status/, response.location)end+ test "index with attachment_status=with lists only transactions that have a file" do+ @entry.entryable.attachments.attach(io: StringIO.new("invoice"), filename: "invoice.pdf", content_type: "application/pdf")++ get transactions_url(q: { attachment_status: [ "with" ] })++ assert_response :success+ assert_select "#transaction-search-filters li p", text: "With attachment", count: 1+ assert_select "#entry_#{@entry.id}", count: 1+ end++ test "index with attachment_status=without hides transactions that have a file" do+ @entry.entryable.attachments.attach(io: StringIO.new("invoice"), filename: "invoice.pdf", content_type: "application/pdf")++ get transactions_url(q: { attachment_status: [ "without" ] })++ assert_response :success+ assert_select "#transaction-search-filters li p", text: "Without attachment", count: 1+ assert_select "#entry_#{@entry.id}", count: 0+ end++ test "index offers the attachment filter in the filter menu" do+ get transactions_url++ assert_response :success+ assert_select "#transaction-filters-menu input[type=checkbox][name='q[attachment_status][]']", count: 2+ end++ test "index ignores unsupported attachment_status values without rendering a badge" do+ get transactions_url(q: { attachment_status: [ "bogus" ] })++ assert_response :success+ assert_select "#transaction-search-filters li", count: 0+ assert_select "#entry_#{@entry.id}", count: 1+ end++ test "clear_filter removes an attachment_status value and redirects" do+ delete clear_filter_transactions_url(+ param_key: "attachment_status",+ param_value: "without",+ q: { attachment_status: [ "without" ] }+ )++ assert_response :redirect+ assert_includes response.location, "filter_cleared=1"+ assert_no_match(/attachment_status/, response.location)+ end+test "an unconfirmed auto-matched transfer keeps its category menu in the list" dooutflow = create_transaction(account: accounts(:depository), amount: 500, name: "PENDING_MATCH_OUT").transactioninflow = create_transaction(account: accounts(:credit_card), amount: -500).transactiondiff --git a/test/models/transaction/search_test.rb b/test/models/transaction/search_test.rbindex 45f79a77e9..c16416faba 100644--- a/test/models/transaction/search_test.rb+++ b/test/models/transaction/search_test.rb@@ -1120,4 +1120,92 @@ class Transaction::SearchTest < ActiveSupport::TestCaseassert_equal [ tx.id ], history_idsassert_empty current_idsend++ test "attachment_status with returns only transactions that have a file" do+ with_file = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable+ attach_file(with_file)++ without_file = create_transaction(account: @checking_account, amount: 50, kind: "standard").entryable++ result_ids = Transaction::Search.new(@family, filters: { attachment_status: [ "with" ] })+ .transactions_scope.pluck(:id)++ assert_equal [ with_file.id ], result_ids+ assert_not_includes result_ids, without_file.id+ end++ test "attachment_status without returns only transactions that have no file" do+ with_file = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable+ attach_file(with_file)++ without_file = create_transaction(account: @checking_account, amount: 50, kind: "standard").entryable++ result_ids = Transaction::Search.new(@family, filters: { attachment_status: [ "without" ] })+ .transactions_scope.pluck(:id)++ assert_equal [ without_file.id ], result_ids+ end++ test "attachment_status with both, no or unknown values leaves the scope unchanged" do+ with_file = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable+ attach_file(with_file)++ without_file = create_transaction(account: @checking_account, amount: 50, kind: "standard").entryable++ expected = [ with_file.id, without_file.id ].sort++ [ [ "with", "without" ], [], [ "bogus" ] ].each do |statuses|+ result_ids = Transaction::Search.new(@family, filters: { attachment_status: statuses })+ .transactions_scope.pluck(:id)++ assert_equal expected, result_ids.sort, "attachment_status #{statuses.inspect} must not filter"+ end+ end++ test "a transaction with several files is returned and counted once" do+ tx = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable+ attach_file(tx, filename: "invoice.pdf")+ attach_file(tx, filename: "receipt.pdf")++ search = Transaction::Search.new(@family, filters: { attachment_status: [ "with" ] })++ assert_equal [ tx.id ], search.transactions_scope.pluck(:id)+ assert_equal 1, search.totals.count+ end++ test "split children count as attached when the file is on their parent" do+ parent = create_transaction(account: @checking_account, amount: 100, kind: "standard")+ attach_file(parent.entryable)+ child_ids = parent.split!([ { name: "Part one", amount: 60 }, { name: "Part two", amount: 40 } ]).map(&:entryable_id)++ plain = create_transaction(account: @checking_account, amount: 25, kind: "standard").entryable++ with_ids = Transaction::Search.new(@family, filters: { attachment_status: [ "with" ] })+ .transactions_scope.pluck(:id)+ without_ids = Transaction::Search.new(@family, filters: { attachment_status: [ "without" ] })+ .transactions_scope.pluck(:id)++ assert_equal child_ids.sort, with_ids.sort+ assert_equal [ plain.id ], without_ids+ end++ test "a split child's own file does not mark its siblings as attached" do+ parent = create_transaction(account: @checking_account, amount: 100, kind: "standard")+ with_file, without_file = parent.split!([ { name: "Part one", amount: 60 }, { name: "Part two", amount: 40 } ]).map(&:entryable)+ attach_file(with_file)++ with_ids = Transaction::Search.new(@family, filters: { attachment_status: [ "with" ] })+ .transactions_scope.pluck(:id)+ without_ids = Transaction::Search.new(@family, filters: { attachment_status: [ "without" ] })+ .transactions_scope.pluck(:id)++ assert_equal [ with_file.id ], with_ids+ assert_equal [ without_file.id ], without_ids+ end++ private+ # Attaches a small PDF to the transaction.+ def attach_file(transaction, filename: "invoice.pdf")+ transaction.attachments.attach(io: StringIO.new("invoice"), filename: filename, content_type: "application/pdf")+ endend