Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Skip investment accounts when detecting bills and income (#3565)

Brian Espinoza871f47857616
diff --git a/app/models/recurring_transaction/identifier.rb b/app/models/recurring_transaction/identifier.rb
index 54c0e487cc..d45d5bfa0d 100644
--- a/app/models/recurring_transaction/identifier.rb
+++ b/app/models/recurring_transaction/identifier.rb
@@ -20,6 +20,21 @@ class RecurringTransaction
# worth offering as a bill or income starting point.
MINIMUM_CANDIDATE_AMOUNT = 1
+ # Accounts whose activity is never a bill or an income source. Brokerage and
+ # retirement feeds deliver dividends, reinvestments and payroll
+ # contributions as plain Transaction rows rather than Trades, on a fixed
+ # monthly cadence and in tightly clustered amounts -- the exact shape the
+ # detector looks for. Left in, a fund's monthly dividend is offered as a
+ # subscription, and a 401k contribution is detected as recurring INCOME
+ # because it is an inflow to the account, which inflates cash-flow
+ # projections. Trades are already skipped via the entryable_type filter;
+ # this covers the same activity when a provider reports it as a transaction.
+ #
+ # accountable_type is nullable, and SQL NOT IN never matches NULL, so the
+ # predicates below admit NULL explicitly rather than silently dropping
+ # entries from an account whose type was never set.
+ NON_BILLABLE_ACCOUNTABLE_TYPES = %w[Investment Crypto].freeze
+
# Read-only: recurring-shaped patterns NOT already covered by an
# existing series, for the add-dialog picker. Two consistent
# occurrences are enough to OFFER a candidate (the automatic pipeline
@@ -50,6 +65,7 @@ class RecurringTransaction
inflows = family.entries
.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
.where(entryable_type: "Transaction")
+ .where("accounts.accountable_type IS NULL OR accounts.accountable_type NOT IN (?)", NON_BILLABLE_ACCOUNTABLE_TYPES)
.where("entries.date >= ?", lookback.ago.to_date)
.where("entries.amount < 0")
.where.not("transactions.kind": Transaction::TRANSFER_KINDS)
@@ -199,6 +215,7 @@ class RecurringTransaction
entries_with_transactions = family.entries
.joins("INNER JOIN transactions ON transactions.id = entries.entryable_id")
.where(entryable_type: "Transaction")
+ .where("accounts.accountable_type IS NULL OR accounts.accountable_type NOT IN (?)", NON_BILLABLE_ACCOUNTABLE_TYPES)
.where("entries.date >= ?", three_months_ago)
.where.not("transactions.kind": Transaction::TRANSFER_KINDS)
.includes(:entryable)
diff --git a/db/migrate/20260914200000_retire_recurring_series_on_investment_accounts.rb b/db/migrate/20260914200000_retire_recurring_series_on_investment_accounts.rb
new file mode 100644
index 0000000000..455eefa895
--- /dev/null
+++ b/db/migrate/20260914200000_retire_recurring_series_on_investment_accounts.rb
@@ -0,0 +1,70 @@
+# Detection now skips Investment and Crypto accounts, but filtering the source
+# query does nothing to series that were already detected. Pipeline#run!
+# generates occurrences for every active series regardless of origin, so
+# without this an existing install keeps its phantom bills -- and, worse, keeps
+# counting retirement contributions as recurring income.
+#
+# `ended` is the tombstone status the detector reads and will not recreate.
+class RetireRecurringSeriesOnInvestmentAccounts < ActiveRecord::Migration[7.2]
+ # Deliberately two COMMITTED steps rather than one transaction: status first,
+ # so the window in which a concurrent request can generate for these series
+ # is as small as possible.
+ #
+ # It is NOT zero. OccurrenceGenerator#generate! tests the in-memory series
+ # object, so a request that loaded the row before the UPDATE committed can
+ # still insert scheduled occurrences after the DELETE below. The cleanup is
+ # therefore best-effort, and that is fine: BillsController#payable_series_ids
+ # scopes to active/inactive, so occurrences on an ended series are never
+ # listed, and the next generate! call loads current state and returns 0. Any
+ # row that slips through is invisible and self-limiting.
+ #
+ # Closing it completely would mean serialising the request path -- a
+ # behaviour change well outside what this migration should carry.
+ disable_ddl_transaction!
+
+ NON_BILLABLE = %w[Investment Crypto].freeze
+
+ def up
+ quoted_types = NON_BILLABLE.map { |t| connection.quote(t) }.join(",")
+
+ target_ids = select_values(<<~SQL)
+ SELECT recurring_transactions.id
+ FROM recurring_transactions
+ JOIN accounts ON accounts.id = recurring_transactions.account_id
+ WHERE accounts.accountable_type IN (#{quoted_types})
+ SQL
+
+ return if target_ids.empty?
+
+ quoted_ids = target_ids.map { |id| connection.quote(id) }.join(",")
+
+ # 1. Close the generation path first.
+ retired = update(<<~SQL)
+ UPDATE recurring_transactions
+ SET status = 'ended', updated_at = NOW()
+ WHERE id IN (#{quoted_ids})
+ AND status <> 'ended'
+ SQL
+
+ # 2. Then drop the re-generatable future (best-effort, see above). Scoped to
+ # every target series, not just the ones retired above, so a
+ # partially-applied run -- or a row inserted by a racing request -- is
+ # cleaned up on a re-run. Paid, skipped and missed rows are history.
+ execute <<~SQL
+ DELETE FROM recurring_occurrences
+ WHERE recurring_transaction_id IN (#{quoted_ids})
+ AND status = 'scheduled'
+ SQL
+
+ say "Retired #{retired} recurring series detected from investment/crypto accounts"
+ end
+
+ # Genuinely irreversible: the prior status of each series and the deleted
+ # occurrences are not recorded anywhere, so a rollback cannot restore them.
+ # Returning successfully would drop the version from schema_migrations and
+ # report a rollback that did not happen.
+ def down
+ raise ActiveRecord::IrreversibleMigration,
+ "Retired investment-account series cannot be restored"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 4fd32a519b..26bda9969b 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
-ActiveRecord::Schema[8.1].define(version: 2026_09_13_000000) do
+ActiveRecord::Schema[8.1].define(version: 2026_09_14_200000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
enable_extension "pgcrypto"
diff --git a/test/models/assistant/function/get_bill_audit_test.rb b/test/models/assistant/function/get_bill_audit_test.rb
index 65657eb9a0..973152598e 100644
--- a/test/models/assistant/function/get_bill_audit_test.rb
+++ b/test/models/assistant/function/get_bill_audit_test.rb
@@ -61,8 +61,12 @@ class Assistant::Function::GetBillAuditTest < ActiveSupport::TestCase
end
test "undeclared candidates never include accounts the user cannot reach" do
+ # `connected` is owned by the admin and shared with nobody, which is the
+ # only property this test needs. It previously used `investment`, but the
+ # detector now skips Investment/Crypto accounts outright, which made the
+ # positive control fail for a reason unrelated to reachability.
3.times do |i|
- accounts(:investment).entries.create!(
+ accounts(:connected).entries.create!(
date: Date.current - i.months, amount: 25, currency: "USD",
name: "BROKERAGE FEE", entryable: Transaction.new
)
@@ -70,7 +74,7 @@ class Assistant::Function::GetBillAuditTest < ActiveSupport::TestCase
admin_names = call_tool[:undeclared_candidates][:items].map { |item| item[:name] }
assert_includes admin_names, "BROKERAGE FEE",
- "positive control: the admin can see the investment-account pattern"
+ "positive control: the admin can see a pattern on an account they own"
member_result = Assistant::Function::GetBillAudit.new(users(:family_member)).call
member_names = member_result[:undeclared_candidates][:items].map { |item| item[:name] }
diff --git a/test/models/recurring_transaction/identifier_test.rb b/test/models/recurring_transaction/identifier_test.rb
index 9fb152a415..6c46c60ae7 100644
--- a/test/models/recurring_transaction/identifier_test.rb
+++ b/test/models/recurring_transaction/identifier_test.rb
@@ -7,6 +7,63 @@ class RecurringTransaction::IdentifierTest < ActiveSupport::TestCase
@family.recurring_transactions.destroy_all
end
+ test "investment account activity is not offered as a bill or an income source" do
+ # Brokerage and retirement feeds deliver dividends, reinvestments and
+ # payroll contributions as plain Transaction rows, monthly and tightly
+ # clustered -- the exact shape the detector looks for.
+ investment = accounts(:investment)
+ assert_equal "Investment", investment.accountable_type
+
+ 3.times do |i|
+ # A monthly dividend reinvestment: looks exactly like a subscription.
+ investment.entries.create!(
+ date: (i + 1).months.ago.to_date,
+ amount: 7.24,
+ currency: "USD",
+ name: "REINVESTMENT FIDELITY US BOND INDEX",
+ entryable: Transaction.new
+ )
+
+ # A payroll 401k contribution: an inflow, so it reads as recurring income.
+ investment.entries.create!(
+ date: (i + 1).months.ago.to_date,
+ amount: -437.50,
+ currency: "USD",
+ name: "LEGAL & GENERAL S&P DC CIT",
+ entryable: Transaction.new
+ )
+ end
+
+ # Crypto is excluded by the same constant. Without its own entries the test
+ # would still pass if "Crypto" were dropped from NON_BILLABLE_ACCOUNTABLE_TYPES.
+ crypto = accounts(:crypto)
+ assert_equal "Crypto", crypto.accountable_type
+
+ 3.times do |i|
+ crypto.entries.create!(
+ date: (i + 1).months.ago.to_date, amount: 12.50, currency: "USD",
+ name: "EXCHANGE TRADING FEE", entryable: Transaction.new
+ )
+ crypto.entries.create!(
+ date: (i + 1).months.ago.to_date, amount: -60.00, currency: "USD",
+ name: "STAKING REWARD", entryable: Transaction.new
+ )
+ end
+
+ bill_names = @identifier.candidate_patterns(sign: :outflow, min_occurrences: 2).map { |p| p[:name] }
+ assert_not_includes bill_names, "REINVESTMENT FIDELITY US BOND INDEX"
+ assert_not_includes bill_names, "EXCHANGE TRADING FEE"
+
+ income_names = @identifier.income_source_candidates(min_occurrences: 2).map { |c| c[:name] }
+ assert_not_includes income_names, "LEGAL & GENERAL S&P DC CIT"
+ assert_not_includes income_names, "STAKING REWARD"
+
+ # And the automatic pipeline does not create series for them either.
+ assert_no_difference "@family.recurring_transactions.count" do
+ @identifier.identify_recurring_patterns
+ end
+ end
+
test "candidate_patterns offers undeclared recurring shapes and skips claimed, junk, and wrong-sign ones" do
account = @family.accounts.first