Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Align uncategorized Transactions filter with dashboard aggregate (fix #2592) (#3293)

jaysbeekay5825ae81cfe6
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index 6b2255e5b7..eb09ed8018 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -479,7 +479,7 @@ class TransactionsController < ApplicationController
# active status (AccountsController#toggle_active) doesn't touch `entries`
# or `AccountShare`, so it wouldn't otherwise bust this cache.
def uncategorized_count_cache_key
- "transactions_uncategorized_count/v3/#{Current.family.id}/#{Current.user.id}/" \
+ "transactions_uncategorized_count/v4/#{Current.family.id}/#{Current.user.id}/" \
"#{Current.family.entries_version}/#{Current.family.accounts_status_version}/#{Current.account_share_version}"
end
diff --git a/app/models/entry.rb b/app/models/entry.rb
index 14ff608518..3cfd7f25b9 100644
--- a/app/models/entry.rb
+++ b/app/models/entry.rb
@@ -102,18 +102,24 @@ class Entry < ApplicationRecord
joins(:account).where(accounts: { family_id: family.id })
end
- # Uncategorized, non-transfer transaction entries on draft or active accounts.
+ # Uncategorized transaction entries on draft or active accounts.
# Caller is responsible for scoping to accessible entries before applying this scope.
+ #
+ # Uses Transaction::UNCATEGORIZED_EXCLUDED_KINDS rather than TRANSFER_KINDS so
+ # the badge count and Quick Categorize wizard cover exactly what the
+ # Transactions "Uncategorized" filter lists — notably the budget-tracked
+ # loan_payment / investment_contribution transfers the dashboard already
+ # counts, which were previously uncategorizable from any surface (#2592).
scope :uncategorized_transactions, -> {
joins(:account)
.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'")
.where(accounts: { status: %w[draft active] })
.where(transactions: { category_id: nil })
- .where.not(transactions: { kind: Transaction::TRANSFER_KINDS })
+ .where.not(transactions: { kind: Transaction::UNCATEGORIZED_EXCLUDED_KINDS })
.where(entries: { excluded: false })
}
- # Returns uncategorized, non-transfer entries whose name matches the given filter string.
+ # Returns uncategorized entries whose name matches the given filter string.
# Used by the Quick Categorize Wizard to preview which transactions a rule would affect.
# @param entries [ActiveRecord::Relation] pre-scoped entries (caller controls authorization)
def self.uncategorized_matching(entries, filter, transaction_type = nil)
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index aa6bf88c0f..8f7a6e0f4f 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -85,6 +85,23 @@ class Transaction < ApplicationRecord
# they represent real cash outflow from a budgeting perspective.
BUDGET_EXCLUDED_KINDS = %w[funds_movement one_time cc_payment].freeze
+ # Kinds that never belong in the "Uncategorized" bucket, whichever surface
+ # asks for it (the Transactions category filter, the uncategorized badge
+ # count, the Quick Categorize wizard). These are the paired legs of a
+ # Transfer between the user's own accounts, so they have nothing to
+ # categorize. Every other kind with a NULL category does.
+ #
+ # This is deliberately neither of the two lists above:
+ # - vs TRANSFER_KINDS: loan_payment and investment_contribution are
+ # budget-tracked outflows the dashboard counts under Uncategorized, so
+ # hiding them left the dashboard figure unreproducible from the list
+ # with no way to find the transactions (see #2592).
+ # - vs BUDGET_EXCLUDED_KINDS: one_time is a real, categorizable
+ # expense/income that is only excluded from budget *analytics* so it
+ # doesn't skew medians. "Has no category" and "counts toward the
+ # budget" are different questions; only the former belongs here.
+ UNCATEGORIZED_EXCLUDED_KINDS = %w[funds_movement cc_payment].freeze
+
# All valid investment activity labels (for UI dropdown)
ACTIVITY_LABELS = [
"Buy", "Sell", "Sweep In", "Sweep Out", "Dividend", "Reinvestment",
diff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rb
index e61acfcfb8..dabd909624 100644
--- a/app/models/transaction/search.rb
+++ b/app/models/transaction/search.rb
@@ -18,12 +18,14 @@ class Transaction::Search
attr_reader :family, :accessible_account_ids
+ # Initialize a transaction search with optional filters and accessible accounts
def initialize(family, filters: {}, accessible_account_ids: nil)
@family = family
@accessible_account_ids = accessible_account_ids
super(filters)
end
+ # Get the filtered transactions scope based on all applied filters
def transactions_scope
@transactions_scope ||= begin
# This already joins entries + accounts. To avoid expensive double-joins, don't join them again (causes full table scan)
@@ -47,12 +49,15 @@ class Transaction::Search
end
end
- # Computes totals for the specific search
- # Note: Excludes tax-advantaged accounts (401k, IRA, etc.) from totals calculation
- # because those transactions are retirement savings, not daily income/expenses.
+ # Compute totals for the specific search, excluding tax-advantaged accounts
def totals
@totals ||= begin
- Rails.cache.fetch("transaction_search_totals/v2/#{cache_key_base}") do
+ # v3: bumped because the Uncategorized filter's exclusion set changed
+ # (see #2592) -- without a version bump, a totals entry cached under
+ # the old logic would keep being served (same cache_key_base) after
+ # deploy, disagreeing with the (uncached) transactions_scope list
+ # until entries_cache_version next changes for that family.
+ Rails.cache.fetch("transaction_search_totals/v3/#{cache_key_base}") do
scope = transactions_scope
# Exclude tax-advantaged accounts from totals calculation
@@ -98,6 +103,7 @@ class Transaction::Search
end
end
+ # Generate cache key based on search filters and family state
def cache_key_base
[
family.id,
@@ -111,6 +117,7 @@ class Transaction::Search
private
Totals = Data.define(:count, :income_money, :expense_money, :transfer_inflow_money, :transfer_outflow_money)
+ # Filter query to include only active accounts if requested
def apply_active_accounts_filter(query, active_accounts_only_filter)
if active_accounts_only_filter
query.where(accounts: { status: [ "draft", "active" ] })
@@ -120,6 +127,7 @@ class Transaction::Search
end
+ # Filter transactions by category, supporting uncategorized and budget exclusions
def apply_category_filter(query, categories)
return query unless categories.present?
@@ -131,14 +139,20 @@ class Transaction::Search
# 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 || [], Transaction::TRANSFER_KINDS
+ real_categories.presence || [], uncategorized_excluded_kinds
)
else
query = query.left_joins(:category).where(categories: { name: real_categories })
@@ -147,7 +161,7 @@ class Transaction::Search
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, Transaction::TRANSFER_KINDS
+ real_categories, parent_category_ids, uncategorized_excluded_kinds
)
else
query = query.left_joins(:category).where(
@@ -160,6 +174,7 @@ class Transaction::Search
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" ]
@@ -182,6 +197,7 @@ class Transaction::Search
end
end
+ # Filter transactions by merchant name
def apply_merchant_filter(query, merchants)
return query unless merchants.present?
@@ -221,6 +237,7 @@ class Transaction::Search
query.where(id: matching_ids)
end
+ # Filter transactions by status (pending or confirmed)
def apply_status_filter(query, statuses)
return query unless statuses.present?
return query if statuses.uniq.sort == [ "confirmed", "pending" ] # Both selected = no filter
diff --git a/test/models/transaction/search_test.rb b/test/models/transaction/search_test.rb
index a742679d7d..00b68f260a 100644
--- a/test/models/transaction/search_test.rb
+++ b/test/models/transaction/search_test.rb
@@ -107,10 +107,16 @@ class Transaction::SearchTest < ActiveSupport::TestCase
kind: "funds_movement"
)
- uncategorized_loan_payment = create_transaction(
- account: @loan_account,
- amount: 300,
- kind: "loan_payment"
+ uncategorized_cc_payment = create_transaction(
+ account: @credit_card_account,
+ amount: 250,
+ kind: "cc_payment"
+ )
+
+ uncategorized_one_time = create_transaction(
+ account: @checking_account,
+ amount: 275,
+ kind: "one_time"
)
# Search for uncategorized transactions
@@ -120,9 +126,67 @@ class Transaction::SearchTest < ActiveSupport::TestCase
# Should include standard uncategorized transactions
assert_includes uncategorized_ids, uncategorized_standard.entryable.id
- # Should exclude all transfer kinds (TRANSFER_KINDS) even if uncategorized
+ # UNCATEGORIZED_EXCLUDED_KINDS (funds_movement, cc_payment) are paired legs
+ # of a Transfer between the user's own accounts, so there is nothing to
+ # categorize and they never land in the uncategorized bucket.
assert_not_includes uncategorized_ids, uncategorized_transfer.entryable.id
- assert_not_includes uncategorized_ids, uncategorized_loan_payment.entryable.id
+ assert_not_includes uncategorized_ids, uncategorized_cc_payment.entryable.id
+
+ # one_time is NOT excluded: it's a real expense/income the user flagged so
+ # it doesn't skew budget medians, and it is still categorizable. Excluding
+ # it would make an uncategorized one-time transaction undiscoverable
+ # through its actual category state.
+ assert_includes uncategorized_ids, uncategorized_one_time.entryable.id,
+ "one_time is excluded from budget analytics, not from categorization"
+ end
+
+ test "uncategorized filter lists budget-tracked transfers (loan_payment, investment_contribution)" do
+ # Regression for https://github.com/we-promise/sure/issues/2592
+ # The dashboard Cashflow widget counts uncategorized loan_payment /
+ # investment_contribution transactions under Outflows → Uncategorized,
+ # but the Transactions page filter used TRANSFER_KINDS and hid them, so
+ # the widget's figure could not be reproduced from the list — and the
+ # transactions could not be found, let alone categorized. These two kinds
+ # are budget-tracked outflows (the intentional-tracking contract also
+ # asserted by the BudgetCategoriesController drilldown tests), so they
+ # stay listed.
+ loan_payment = create_transaction(account: @loan_account, amount: 300, kind: "loan_payment")
+ investment_contribution = create_transaction(account: @checking_account, amount: 400, kind: "investment_contribution")
+
+ uncategorized_ids = Transaction::Search.new(@family, filters: { categories: [ Category.uncategorized.name ] })
+ .transactions_scope.pluck(:id)
+
+ assert_includes uncategorized_ids, loan_payment.entryable.id,
+ "uncategorized loan_payment is visible on the dashboard; the list must include it (see #2592)"
+ assert_includes uncategorized_ids, investment_contribution.entryable.id,
+ "uncategorized investment_contribution is visible on the dashboard; the list must include it (see #2592)"
+ end
+
+ test "uncategorized filter and Entry.uncategorized_transactions agree on every kind" do
+ # The Transactions filter, the uncategorized badge count and the Quick
+ # Categorize wizard must describe the same set, or the badge promises rows
+ # the list won't show (and vice versa). Both read
+ # Transaction::UNCATEGORIZED_EXCLUDED_KINDS; this pins them together.
+ made = Transaction.kinds.keys.index_with do |kind|
+ account = kind == "loan_payment" ? @loan_account : @checking_account
+ create_transaction(account: account, amount: 100, kind: kind).entryable.id
+ end
+
+ filter_ids = Transaction::Search.new(@family, filters: { categories: [ Category.uncategorized.name ] })
+ .transactions_scope.pluck(:id).to_set
+ wizard_ids = @family.entries.uncategorized_transactions.pluck(:entryable_id).to_set
+
+ made.each do |kind, id|
+ assert_equal filter_ids.include?(id), wizard_ids.include?(id),
+ "#{kind}: Transactions filter and Entry.uncategorized_transactions disagree"
+ end
+
+ Transaction::UNCATEGORIZED_EXCLUDED_KINDS.each do |kind|
+ assert_not_includes filter_ids, made.fetch(kind), "#{kind} must not be uncategorizable"
+ end
+ (Transaction.kinds.keys - Transaction::UNCATEGORIZED_EXCLUDED_KINDS).each do |kind|
+ assert_includes filter_ids, made.fetch(kind), "#{kind} has no category and must be listed"
+ end
end
test "filtering for only Uncategorized returns only uncategorized transactions" do