Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(transactions): filter by AI / AI history categorization status (#3603)

Arnav Joshia09107c57ed3
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index 9aeaa75489..c17fc06244 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -708,13 +708,17 @@ class TransactionsController < ApplicationController
:start_date, :end_date, :search, :amount,
:amount_operator, :active_accounts_only,
accounts: [], account_ids: [],
- categories: [], merchants: [], types: [], tags: [], status: []
+ categories: [], merchants: [], types: [], tags: [], status: [], ai_status: []
)
.to_h
.compact_blank
cleaned_params.delete(:amount_operator) unless cleaned_params[:amount].present?
+ if cleaned_params[:ai_status]
+ cleaned_params[:ai_status] &= Transaction::Search::AI_STATUSES
+ cleaned_params.delete(:ai_status) if cleaned_params[:ai_status].empty?
+ end
cleaned_params
end
diff --git a/app/helpers/transactions_helper.rb b/app/helpers/transactions_helper.rb
index 2e1d51a322..954794789b 100644
--- a/app/helpers/transactions_helper.rb
+++ b/app/helpers/transactions_helper.rb
@@ -10,7 +10,8 @@ module TransactionsHelper
{ key: "amount_filter", label: t("transactions.search.filters.amount"), icon: "hash" },
{ 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: "merchant_filter", label: t("transactions.search.filters.merchant"), icon: "store" },
+ { key: "ai_filter", label: t("transactions.search.filters.ai"), icon: "sparkles" }
]
end
diff --git a/app/models/concerns/enrichable.rb b/app/models/concerns/enrichable.rb
index 9a5bf05d29..e409ad41b7 100644
--- a/app/models/concerns/enrichable.rb
+++ b/app/models/concerns/enrichable.rb
@@ -175,6 +175,14 @@ module Enrichable
# Delete AI enrichment records
removed_count = ai_enrichments.delete_all
+
+ # Views and totals filtered on provenance are cached under
+ # Family#entries_cache_version, which only moves when an entry's
+ # timestamp changes. delete_all skips callbacks, so touch the record
+ # like a normal save would; `has_one :entry, touch: true` carries it to
+ # the entry. This stays inside the transaction so the cache invalidation
+ # commits or rolls back with the deletion.
+ touch if removed_count.positive?
end
removed_count
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index 6d59912990..b8ddc97fb5 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -114,6 +114,9 @@ class Transaction < ApplicationRecord
# Providers that support pending transaction flags
PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up monobank mercury redbark financekit].freeze
+ # DataEnrichment sources that represent automatic category assignment
+ AUTO_CATEGORY_SOURCES = %w[ai bayes].freeze
+
# Pre-computed SQL fragment for subqueries that check if a transaction (aliased as "t") is pending.
# Stored as a constant so static analysis can verify it contains no user input.
PENDING_CHECK_SQL = PENDING_PROVIDERS
diff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rb
index 1603c20383..4cc2f4a18c 100644
--- a/app/models/transaction/search.rb
+++ b/app/models/transaction/search.rb
@@ -2,6 +2,9 @@ class Transaction::Search
include ActiveModel::Model
include ActiveModel::Attributes
+ # Automatic-categorization provenance filter values (used by the view)
+ AI_STATUSES = %w[current history].freeze
+
attribute :search, :string
attribute :amount, :string
attribute :amount_operator, :string
@@ -14,6 +17,7 @@ class Transaction::Search
attribute :categories, array: true
attribute :merchants, array: true
attribute :tags, array: true
+ attribute :ai_status, array: true
attribute :active_accounts_only, :boolean, default: true
attr_reader :family, :accessible_account_ids
@@ -40,6 +44,7 @@ class Transaction::Search
query = apply_status_filter(query, status)
query = apply_merchant_filter(query, merchants)
query = apply_tag_filter(query, tags)
+ query = apply_ai_status_filter(query, ai_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)
@@ -235,6 +240,34 @@ class Transaction::Search
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).
+ def apply_ai_status_filter(query, statuses)
+ wanted = Array(statuses) & AI_STATUSES
+ return query if wanted.empty?
+
+ case wanted.sort
+ when [ "current" ]
+ query.where(auto_enrichment_exists_sql("de.value = to_jsonb(transactions.category_id::text)"), sources: Transaction::AUTO_CATEGORY_SOURCES)
+ when [ "history" ]
+ query
+ .where(auto_enrichment_exists_sql, sources: Transaction::AUTO_CATEGORY_SOURCES)
+ .where.not(auto_enrichment_exists_sql("de.value = to_jsonb(transactions.category_id::text)"), sources: Transaction::AUTO_CATEGORY_SOURCES)
+ else
+ query.where(auto_enrichment_exists_sql, sources: Transaction::AUTO_CATEGORY_SOURCES)
+ end
+ end
+
+ # Correlated EXISTS predicate over the transaction's automatic category
+ # enrichments. to_jsonb(NULL::text) is NULL, so an uncategorized
+ # transaction never satisfies the "matches current category" variant.
+ def auto_enrichment_exists_sql(extra_condition = nil)
+ sql = "EXISTS (SELECT 1 FROM data_enrichments de WHERE de.enrichable_type = 'Transaction' AND de.enrichable_id = transactions.id AND de.attribute_name = 'category_id' AND de.source IN (:sources)"
+ sql += " AND #{extra_condition}" if extra_condition
+ 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/_menu.html.erb b/app/views/transactions/searches/_menu.html.erb
index c424b20ed4..2de3555c15 100644
--- a/app/views/transactions/searches/_menu.html.erb
+++ b/app/views/transactions/searches/_menu.html.erb
@@ -7,7 +7,7 @@
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") do |nav| %>
+ <%= 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| %>
<%= 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]) %>
diff --git a/app/views/transactions/searches/filters/_ai_filter.html.erb b/app/views/transactions/searches/filters/_ai_filter.html.erb
new file mode 100644
index 0000000000..d12dc1262d
--- /dev/null
+++ b/app/views/transactions/searches/filters/_ai_filter.html.erb
@@ -0,0 +1,32 @@
+<%# locals: (form:) %>
+
+<div class="p-2 space-y-3">
+ <div class="flex items-center gap-3" data-filter-name="current">
+ <%= form.check_box :ai_status,
+ {
+ multiple: true,
+ checked: @q[:ai_status]&.include?("current"),
+ class: "checkbox checkbox--light"
+ },
+ "current",
+ nil %>
+ <div>
+ <%= form.label :ai_status, t(".current"), value: "current", class: "text-sm text-primary" %>
+ <p class="text-xs text-secondary"><%= t(".current_description") %></p>
+ </div>
+ </div>
+ <div class="flex items-center gap-3" data-filter-name="history">
+ <%= form.check_box :ai_status,
+ {
+ multiple: true,
+ checked: @q[:ai_status]&.include?("history"),
+ class: "checkbox checkbox--light"
+ },
+ "history",
+ nil %>
+ <div>
+ <%= form.label :ai_status, t(".history"), value: "history", class: "text-sm text-primary" %>
+ <p class="text-xs text-secondary"><%= t(".history_description") %></p>
+ </div>
+ </div>
+</div>
diff --git a/app/views/transactions/searches/filters/_badge.html.erb b/app/views/transactions/searches/filters/_badge.html.erb
index 05933e8343..d7ddafdfe7 100644
--- a/app/views/transactions/searches/filters/_badge.html.erb
+++ b/app/views/transactions/searches/filters/_badge.html.erb
@@ -52,6 +52,11 @@
<div class="flex items-center gap-2">
<p><%= Category.uncategorized_name %></p>
</div>
+ <% elsif param_key == "ai_status" %>
+ <div class="flex items-center gap-2 px-1">
+ <%= icon(param_value == "current" ? "sparkles" : "history", size: "sm") %>
+ <p><%= t(".ai_#{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.yml
index ae47864669..559e143bcf 100644
--- a/config/locales/views/transactions/en.yml
+++ b/config/locales/views/transactions/en.yml
@@ -266,6 +266,7 @@ en:
category: Category
tag: Tag
merchant: Merchant
+ ai: AI
convert_to_trade:
title: Convert to Security Trade
description: Convert this transaction into a trade with security details
@@ -334,6 +335,13 @@ en:
transfer: Transfer
confirmed: Confirmed
pending: Pending
+ ai_current: AI
+ ai_history: AI history
+ ai_filter:
+ current: AI
+ current_description: Category is still the one assigned automatically (AI or Bayes).
+ history: AI history
+ history_description: Was auto-categorized, but the category has been changed since.
type_filter:
expense: Expense
income: Income
diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rb
index 4b2c571572..31889c6262 100644
--- a/test/controllers/transactions_controller_test.rb
+++ b/test/controllers/transactions_controller_test.rb
@@ -1632,6 +1632,61 @@ end
Rails.cache = original_cache
end
+ test "index with ai_status=current renders the AI filter badge" do
+ @entry.entryable.enrich_attribute(:category_id, categories(:income).id, source: "ai")
+
+ get transactions_url(q: { ai_status: [ "current" ] })
+
+ assert_response :success
+ assert_select "#transaction-search-filters li p", text: "AI", count: 1
+ assert_select "#entry_#{@entry.id}", count: 1
+ end
+
+ test "index with ai_status=history renders the AI history filter badge" do
+ @entry.entryable.enrich_attribute(:category_id, categories(:income).id, source: "ai")
+ @entry.entryable.update!(category: categories(:subcategory))
+
+ get transactions_url(q: { ai_status: [ "history" ] })
+
+ assert_response :success
+ assert_select "#transaction-search-filters li p", text: "AI history", count: 1
+ assert_select "#entry_#{@entry.id}", count: 1
+ end
+
+ test "index with ai_status=current excludes history-only transactions" do
+ @entry.entryable.enrich_attribute(:category_id, categories(:income).id, source: "ai")
+ @entry.entryable.update!(category: categories(:subcategory))
+
+ get transactions_url(q: { ai_status: [ "current" ] })
+
+ assert_response :success
+ assert_select "#transaction-search-filters li p", text: "AI", count: 1
+ assert_select "#entry_#{@entry.id}", count: 0
+ end
+
+ test "index ignores unsupported ai_status values without rendering a badge" do
+ get transactions_url(q: { ai_status: [ "bogus" ] })
+
+ assert_response :success
+ assert_select "#transaction-search-filters li", count: 0
+ assert_no_match(/translation missing/, response.body)
+
+ # The bogus value must be dropped entirely, not applied as a filter
+ assert_select "#entry_#{@entry.id}", count: 1
+ end
+
+ test "clear_filter removes an ai_status value and redirects" do
+ delete clear_filter_transactions_url(
+ param_key: "ai_status",
+ param_value: "current",
+ q: { ai_status: [ "current" ] }
+ )
+
+ assert_response :redirect
+ assert_includes response.location, "filter_cleared=1"
+ assert_no_match(/ai_status/, response.location)
+ end
+
private
def rendered_entry_ids
css_select("turbo-frame[id^='entry_']").map { |node| node["id"].delete_prefix("entry_") }
diff --git a/test/jobs/clear_ai_cache_job_test.rb b/test/jobs/clear_ai_cache_job_test.rb
index 61b0d9586a..66d7e23cf2 100644
--- a/test/jobs/clear_ai_cache_job_test.rb
+++ b/test/jobs/clear_ai_cache_job_test.rb
@@ -59,6 +59,24 @@ class ClearAiCacheJobTest < ActiveSupport::TestCase
assert_equal 0, completion_entry.metadata["entries_removed"]
end
+ test "bumps entries_cache_version so provenance-filtered caches invalidate" do
+ create_ai_enrichment(@transaction, "category_id")
+ before = @family.reload.entries_cache_version
+
+ ClearAiCacheJob.perform_now(@family)
+
+ assert_not_equal before, @family.reload.entries_cache_version
+ end
+
+ test "rolls back the enrichment deletion when the cache touch fails" do
+ enrichment = create_ai_enrichment(@transaction, "category_id")
+ Transaction.any_instance.stubs(:touch).raises(StandardError, "touch failed")
+
+ ClearAiCacheJob.perform_now(@family)
+
+ assert DataEnrichment.exists?(enrichment.id), "deletion should roll back with the failed touch"
+ end
+
test "warns instead of failing silently when no family is given" do
ClearAiCacheJob.perform_now(nil)
diff --git a/test/models/transaction/search_test.rb b/test/models/transaction/search_test.rb
index 06cfe06028..45f79a77e9 100644
--- a/test/models/transaction/search_test.rb
+++ b/test/models/transaction/search_test.rb
@@ -1009,4 +1009,115 @@ class Transaction::SearchTest < ActiveSupport::TestCase
assert_equal 1, totals.count, "a single transaction tagged with all three must be counted once"
assert_equal Money.new(42, "USD"), totals.expense_money
end
+
+ test "ai_status current returns transactions whose auto-assigned category still applies" do
+ tx_a = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+ tx_a.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
+
+ tx_b = create_transaction(account: @checking_account, amount: 50, kind: "standard").entryable
+ tx_b.enrich_attribute(:category_id, categories(:income).id, source: "bayes")
+
+ tx_c = create_transaction(account: @checking_account, amount: 25, kind: "standard").entryable
+ tx_c.enrich_attribute(:category_id, categories(:income).id, source: "ai")
+ tx_c.update!(category: categories(:food_and_drink))
+
+ tx_d = create_transaction(account: @checking_account, amount: 10, kind: "standard").entryable
+
+ result_ids = Transaction::Search.new(@family, filters: { ai_status: [ "current" ] })
+ .transactions_scope.pluck(:id)
+
+ assert_equal [ tx_a.id, tx_b.id ].sort, result_ids.sort
+ assert_not_includes result_ids, tx_c.id, "a changed-afterwards category is history, not current"
+ assert_not_includes result_ids, tx_d.id
+ end
+
+ test "ai_status history returns transactions changed after auto-categorization" do
+ tx_a = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+ tx_a.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
+
+ tx_c = create_transaction(account: @checking_account, amount: 25, kind: "standard").entryable
+ tx_c.enrich_attribute(:category_id, categories(:income).id, source: "ai")
+ tx_c.update!(category: categories(:food_and_drink))
+
+ tx_d = create_transaction(account: @checking_account, amount: 10, kind: "standard").entryable
+
+ result_ids = Transaction::Search.new(@family, filters: { ai_status: [ "history" ] })
+ .transactions_scope.pluck(:id)
+
+ assert_equal [ tx_c.id ], result_ids
+ assert_not_includes result_ids, tx_a.id, "a still-current assignment is not history"
+ assert_not_includes result_ids, tx_d.id
+ end
+
+ test "ai_status with both values returns any automatic enrichment" do
+ tx_a = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+ tx_a.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
+
+ tx_c = create_transaction(account: @checking_account, amount: 25, kind: "standard").entryable
+ tx_c.enrich_attribute(:category_id, categories(:income).id, source: "ai")
+ tx_c.update!(category: categories(:food_and_drink))
+
+ tx_d = create_transaction(account: @checking_account, amount: 10, kind: "standard").entryable
+
+ result_ids = Transaction::Search.new(@family, filters: { ai_status: [ "current", "history" ] })
+ .transactions_scope.pluck(:id)
+
+ assert_equal [ tx_a.id, tx_c.id ].sort, result_ids.sort
+ assert_not_includes result_ids, tx_d.id
+ end
+
+ test "ai_status empty or absent leaves the scope unchanged" do
+ tx = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+
+ assert_equal [ tx.id ], Transaction::Search.new(@family).transactions_scope.pluck(:id)
+ assert_equal [ tx.id ], Transaction::Search.new(@family, filters: { ai_status: [] }).transactions_scope.pluck(:id)
+ end
+
+ test "ai_status ignores values outside the whitelist" do
+ tx = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+
+ result_ids = Transaction::Search.new(@family, filters: { ai_status: [ "bogus" ] })
+ .transactions_scope.pluck(:id)
+
+ assert_equal [ tx.id ], result_ids
+ end
+
+ test "a transaction with matching ai and bayes rows is returned and counted once" do
+ tx = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+ tx.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
+ tx.update!(category: categories(:income))
+ tx.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "bayes")
+
+ search = Transaction::Search.new(@family, filters: { ai_status: [ "current" ] })
+
+ assert_equal [ tx.id ], search.transactions_scope.pluck(:id)
+ assert_equal 1, search.totals.count, "two matching enrichment rows must not double-count (see #3174)"
+ end
+
+ test "ai_status composes with the categories filter" do
+ tx_a = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+ tx_a.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
+
+ tx_b = create_transaction(account: @checking_account, amount: 50, kind: "standard").entryable
+ tx_b.enrich_attribute(:category_id, categories(:income).id, source: "ai")
+
+ result_ids = Transaction::Search.new(@family, filters: { ai_status: [ "current" ], categories: [ "Food & Drink" ] })
+ .transactions_scope.pluck(:id)
+
+ assert_equal [ tx_a.id ], result_ids
+ end
+
+ test "clearing the category after auto-categorization counts as history" do
+ tx = create_transaction(account: @checking_account, amount: 100, kind: "standard").entryable
+ tx.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "ai")
+ tx.update!(category: nil)
+
+ history_ids = Transaction::Search.new(@family, filters: { ai_status: [ "history" ] })
+ .transactions_scope.pluck(:id)
+ current_ids = Transaction::Search.new(@family, filters: { ai_status: [ "current" ] })
+ .transactions_scope.pluck(:id)
+
+ assert_equal [ tx.id ], history_ids
+ assert_empty current_ids
+ end
end