The personal finance app for everyone (by everyone)
Ruby
Handle `investment_contribution` classification and update related logic.
luckyPipewrench196d12466f15
diff --git a/app/components/UI/account/activity_feed.html.erb b/app/components/UI/account/activity_feed.html.erbindex 14c9b36e45..38c179552d 100644--- a/app/components/UI/account/activity_feed.html.erb+++ b/app/components/UI/account/activity_feed.html.erb@@ -32,6 +32,13 @@data: { turbo_frame: :modal }) %><% end %><% end %>++ <% menu.with_item(+ variant: "link",+ text: t("accounts.show.activity.new_transfer"),+ icon: "arrow-right-left",+ href: new_transfer_path,+ data: { turbo_frame: :modal }) %><% end %></div>diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 932edf57f2..3c28db52a8 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -150,13 +150,15 @@ class Account::ProviderImportAdapter# Auto-set kind for internal movements and contributionsauto_kind = nil+ auto_category = nilif Transaction::INTERNAL_MOVEMENT_LABELS.include?(detected_label)auto_kind = "funds_movement"elsif detected_label == "Contribution"auto_kind = "investment_contribution"+ auto_category = account.family.categories.find_by(name: "Investment Contributions")end- # Set investment activity label and kind if detected+ # Set investment activity label, kind, and category if detectedif entry.entryable.is_a?(Transaction)if detected_label.present? && entry.transaction.investment_activity_label.blank?entry.transaction.assign_attributes(investment_activity_label: detected_label)@@ -165,6 +167,10 @@ class Account::ProviderImportAdapterif auto_kind.present?entry.transaction.assign_attributes(kind: auto_kind)end++ if auto_category.present? && entry.transaction.category_id.blank?+ entry.transaction.assign_attributes(category: auto_category)+ endendentry.save!diff --git a/app/models/income_statement/category_stats.rb b/app/models/income_statement/category_stats.rbindex f4eb2815f1..0552ebc621 100644--- a/app/models/income_statement/category_stats.rb+++ b/app/models/income_statement/category_stats.rb@@ -35,8 +35,8 @@ class IncomeStatement::CategoryStatsSELECTc.id as category_id,date_trunc(:interval, ae.date) as period,- CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,- SUM(ae.amount * COALESCE(er.rate, 1)) as total+ CASE WHEN t.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,+ SUM(CASE WHEN t.kind = 'investment_contribution' THEN ABS(ae.amount * COALESCE(er.rate, 1)) ELSE ae.amount * COALESCE(er.rate, 1) END) as totalFROM transactions tJOIN entries ae ON ae.entryable_id = t.id AND ae.entryable_type = 'Transaction'JOIN accounts a ON a.id = ae.account_id@@ -47,11 +47,11 @@ class IncomeStatement::CategoryStatser.to_currency = :target_currency)WHERE a.family_id = :family_id- AND t.kind NOT IN ('funds_movement', 'one_time', 'cc_payment', 'investment_contribution')+ AND t.kind NOT IN ('funds_movement', 'one_time', 'cc_payment')AND ae.excluded = falseAND (t.extra -> 'simplefin' ->> 'pending')::boolean IS DISTINCT FROM trueAND (t.extra -> 'plaid' ->> 'pending')::boolean IS DISTINCT FROM true- GROUP BY c.id, period, CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END+ GROUP BY c.id, period, CASE WHEN t.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END)SELECTcategory_id,diff --git a/app/models/income_statement/family_stats.rb b/app/models/income_statement/family_stats.rbindex 48b0d95077..bfaae6fa56 100644--- a/app/models/income_statement/family_stats.rb+++ b/app/models/income_statement/family_stats.rb@@ -33,8 +33,8 @@ class IncomeStatement::FamilyStatsWITH period_totals AS (SELECTdate_trunc(:interval, ae.date) as period,- CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,- SUM(ae.amount * COALESCE(er.rate, 1)) as total+ CASE WHEN t.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,+ SUM(CASE WHEN t.kind = 'investment_contribution' THEN ABS(ae.amount * COALESCE(er.rate, 1)) ELSE ae.amount * COALESCE(er.rate, 1) END) as totalFROM transactions tJOIN entries ae ON ae.entryable_id = t.id AND ae.entryable_type = 'Transaction'JOIN accounts a ON a.id = ae.account_id@@ -44,11 +44,11 @@ class IncomeStatement::FamilyStatser.to_currency = :target_currency)WHERE a.family_id = :family_id- AND t.kind NOT IN ('funds_movement', 'one_time', 'cc_payment', 'investment_contribution')+ AND t.kind NOT IN ('funds_movement', 'one_time', 'cc_payment')AND ae.excluded = falseAND (t.extra -> 'simplefin' ->> 'pending')::boolean IS DISTINCT FROM trueAND (t.extra -> 'plaid' ->> 'pending')::boolean IS DISTINCT FROM true- GROUP BY period, CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END+ GROUP BY period, CASE WHEN t.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END)SELECTclassification,diff --git a/app/models/income_statement/totals.rb b/app/models/income_statement/totals.rbindex ffcb468b1e..1de3e081c0 100644--- a/app/models/income_statement/totals.rb+++ b/app/models/income_statement/totals.rb@@ -56,7 +56,7 @@ class IncomeStatement::TotalsSELECTc.id as category_id,c.parent_id as parent_category_id,- CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,+ CASE WHEN at.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,ABS(SUM(ae.amount * COALESCE(er.rate, 1))) as total,COUNT(ae.id) as transactions_count,false as is_uncategorized_investment@@ -69,11 +69,11 @@ class IncomeStatement::Totalser.from_currency = ae.currency ANDer.to_currency = :target_currency)- WHERE at.kind NOT IN ('funds_movement', 'one_time', 'cc_payment', 'investment_contribution')+ WHERE at.kind NOT IN ('funds_movement', 'one_time', 'cc_payment')AND ae.excluded = falseAND a.family_id = :family_idAND a.status IN ('draft', 'active')- GROUP BY c.id, c.parent_id, CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END;+ GROUP BY c.id, c.parent_id, CASE WHEN at.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END;SQLend@@ -82,7 +82,7 @@ class IncomeStatement::TotalsSELECTc.id as category_id,c.parent_id as parent_category_id,- CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,+ CASE WHEN at.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END as classification,ABS(SUM(ae.amount * COALESCE(er.rate, 1))) as total,COUNT(ae.id) as entry_count,false as is_uncategorized_investment@@ -95,7 +95,7 @@ class IncomeStatement::Totalser.from_currency = ae.currency ANDer.to_currency = :target_currency)- WHERE at.kind NOT IN ('funds_movement', 'one_time', 'cc_payment', 'investment_contribution')+ WHERE at.kind NOT IN ('funds_movement', 'one_time', 'cc_payment')AND (at.investment_activity_label IS NULLOR at.investment_activity_label NOT IN ('Transfer', 'Sweep In', 'Sweep Out', 'Exchange')@@ -103,7 +103,7 @@ class IncomeStatement::TotalsAND ae.excluded = falseAND a.family_id = :family_idAND a.status IN ('draft', 'active')- GROUP BY c.id, c.parent_id, CASE WHEN ae.amount < 0 THEN 'income' ELSE 'expense' END+ GROUP BY c.id, c.parent_id, CASE WHEN at.kind = 'investment_contribution' THEN 'expense' WHEN ae.amount < 0 THEN 'income' ELSE 'expense' ENDSQLenddiff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rbindex e46a664720..b4311415f6 100644--- a/app/models/transaction/search.rb+++ b/app/models/transaction/search.rb@@ -49,8 +49,8 @@ class Transaction::SearchRails.cache.fetch("transaction_search_totals/#{cache_key_base}") doresult = transactions_scope.select(- "COALESCE(SUM(CASE WHEN entries.amount >= 0 AND transactions.kind NOT IN ('funds_movement', 'cc_payment', 'investment_contribution') THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as expense_total",- "COALESCE(SUM(CASE WHEN entries.amount < 0 AND transactions.kind NOT IN ('funds_movement', 'cc_payment', 'investment_contribution') THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as income_total",+ "COALESCE(SUM(CASE WHEN transactions.kind = 'investment_contribution' THEN ABS(entries.amount * COALESCE(er.rate, 1)) WHEN entries.amount >= 0 AND transactions.kind NOT IN ('funds_movement', 'cc_payment') THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as expense_total",+ "COALESCE(SUM(CASE WHEN entries.amount < 0 AND transactions.kind NOT IN ('funds_movement', 'cc_payment', 'investment_contribution') THEN ABS(entries.amount * COALESCE(er.rate, 1)) ELSE 0 END), 0) as income_total","COUNT(entries.id) as transactions_count").joins(@@ -100,14 +100,14 @@ class Transaction::Searchif parent_category_ids.empty?query = query.left_joins(:category).where("categories.name IN (?) OR (- categories.id IS NULL AND (transactions.kind NOT IN ('funds_movement', 'cc_payment', 'investment_contribution'))+ categories.id IS NULL AND (transactions.kind NOT IN ('funds_movement', 'cc_payment')))",categories)elsequery = query.left_joins(:category).where("categories.name IN (?) OR categories.parent_id IN (?) OR (- categories.id IS NULL AND (transactions.kind NOT IN ('funds_movement', 'cc_payment', 'investment_contribution'))+ categories.id IS NULL AND (transactions.kind NOT IN ('funds_movement', 'cc_payment')))",categories, parent_category_ids)@@ -125,8 +125,11 @@ class Transaction::Searchreturn query if types.sort == [ "expense", "income", "transfer" ]transfer_condition = "transactions.kind IN ('funds_movement', 'cc_payment', 'loan_payment')"- expense_condition = "entries.amount >= 0"- income_condition = "entries.amount <= 0"+ # investment_contribution is always an expense regardless of amount sign+ # (handles both manual outflows and provider-imported inflows like 401k contributions)+ investment_contribution_condition = "transactions.kind = 'investment_contribution'"+ expense_condition = "(entries.amount >= 0 OR #{investment_contribution_condition})"+ income_condition = "(entries.amount <= 0 AND NOT #{investment_contribution_condition})"condition = case types.sortwhen [ "transfer" ]diff --git a/app/models/transfer/creator.rb b/app/models/transfer/creator.rbindex 8ea93a9cee..61bbadeebd 100644--- a/app/models/transfer/creator.rb+++ b/app/models/transfer/creator.rb@@ -27,18 +27,25 @@ class Transfer::Creatordef outflow_transactionname = "#{name_prefix} to #{destination_account.name}"+ kind = outflow_transaction_kindTransaction.new(- kind: outflow_transaction_kind,+ kind: kind,+ category: (investment_contributions_category if kind == "investment_contribution"),entry: source_account.entries.build(amount: amount.abs,currency: source_account.currency,date: date,name: name,+ user_modified: true, # Protect from provider sync claiming this entry))end+ def investment_contributions_category+ source_account.family.categories.find_by(name: "Investment Contributions")+ end+def inflow_transactionname = "#{name_prefix} from #{source_account.name}"@@ -49,6 +56,7 @@ class Transfer::Creatorcurrency: destination_account.currency,date: date,name: name,+ user_modified: true, # Protect from provider sync claiming this entry))end@@ -70,11 +78,21 @@ class Transfer::Creator"loan_payment"elsif destination_account.liability?"cc_payment"+ elsif destination_is_investment? && !source_is_investment?+ "investment_contribution"else"funds_movement"endend+ def destination_is_investment?+ destination_account.investment? || destination_account.crypto?+ end++ def source_is_investment?+ source_account.investment? || source_account.crypto?+ end+def name_prefixif destination_account.liability?"Payment"diff --git a/app/views/transfers/_form.html.erb b/app/views/transfers/_form.html.erbindex d584cb7c25..b32e597075 100644--- a/app/views/transfers/_form.html.erb+++ b/app/views/transfers/_form.html.erb@@ -11,8 +11,8 @@</section><section class="space-y-2">- <%= f.collection_select :from_account_id, Current.family.accounts.manual.alphabetically, :id, :name, { prompt: t(".select_account"), label: t(".from") }, required: true %>- <%= f.collection_select :to_account_id, Current.family.accounts.manual.alphabetically, :id, :name, { prompt: t(".select_account"), label: t(".to") }, required: true %>+ <%= f.collection_select :from_account_id, Current.family.accounts.alphabetically, :id, :name, { prompt: t(".select_account"), label: t(".from") }, required: true %>+ <%= f.collection_select :to_account_id, Current.family.accounts.alphabetically, :id, :name, { prompt: t(".select_account"), label: t(".to") }, required: true %><%= f.number_field :amount, label: t(".amount"), required: true, min: 0, placeholder: "100", step: 0.00000001 %><%= f.date_field :date, value: transfer.inflow_transaction&.entry&.date || Date.current, label: t(".date"), required: true, max: Date.current %></section>diff --git a/config/locales/views/accounts/en.yml b/config/locales/views/accounts/en.ymlindex 939d175afd..71b5a33fb6 100644--- a/config/locales/views/accounts/en.yml+++ b/config/locales/views/accounts/en.yml@@ -59,6 +59,7 @@ en:new_activity: New activitynew_balance: New balancenew_transaction: New transaction+ new_transfer: New transferno_entries: No entries foundpending: Pendingsearch:diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rbindex e4af61d66a..7231626a20 100644--- a/test/models/income_statement_test.rb+++ b/test/models/income_statement_test.rb@@ -286,7 +286,7 @@ class IncomeStatementTest < ActiveSupport::TestCaseassert_equal Money.new(1050, @family.currency), totals.expense_money # 900 + 150end- test "excludes investment_contribution transactions from income statement" do+ test "includes investment_contribution transactions as expenses in income statement" do# Create a transfer to investment account (marked as investment_contribution)investment_contribution = create_transaction(account: @checking_account,@@ -298,9 +298,39 @@ class IncomeStatementTest < ActiveSupport::TestCaseincome_statement = IncomeStatement.new(@family)totals = income_statement.totals(date_range: Period.last_30_days.date_range)- # investment_contribution should be excluded (it's in the exclusion list)- assert_equal 4, totals.transactions_count # Only original 4 transactions+ # investment_contribution should be included as an expense (visible in cashflow)+ assert_equal 5, totals.transactions_count # Original 4 + investment_contributionassert_equal Money.new(1000, @family.currency), totals.income_money- assert_equal Money.new(900, @family.currency), totals.expense_money+ assert_equal Money.new(1900, @family.currency), totals.expense_money # 900 + 1000 investment+ end++ test "includes provider-imported investment_contribution inflows as expenses" do+ # Simulates a 401k contribution that was auto-deducted from payroll+ # Provider imports this as an inflow to the investment account (negative amount)+ # but it should still appear as an expense in cashflow++ investment_account = @family.accounts.create!(+ name: "401k",+ currency: @family.currency,+ balance: 10000,+ accountable: Investment.new+ )++ # Provider-imported contribution shows as inflow (negative amount) to the investment account+ # kind is investment_contribution, which should be treated as expense regardless of sign+ provider_contribution = create_transaction(+ account: investment_account,+ amount: -500, # Negative = inflow to account+ category: nil,+ kind: "investment_contribution"+ )++ income_statement = IncomeStatement.new(@family)+ totals = income_statement.totals(date_range: Period.last_30_days.date_range)++ # The provider-imported contribution should appear as an expense+ assert_equal 5, totals.transactions_count # Original 4 + provider contribution+ assert_equal Money.new(1000, @family.currency), totals.income_money+ assert_equal Money.new(1400, @family.currency), totals.expense_money # 900 + 500 (abs of -500)endenddiff --git a/test/models/transfer/creator_test.rb b/test/models/transfer/creator_test.rbindex f6d9379baa..ff168509f6 100644--- a/test/models/transfer/creator_test.rb+++ b/test/models/transfer/creator_test.rb@@ -9,7 +9,14 @@ class Transfer::CreatorTest < ActiveSupport::TestCase@amount = 100end- test "creates basic transfer" do+ test "creates investment contribution when transferring from depository to investment" do+ # Ensure the Investment Contributions category exists with all required attributes+ investment_category = @family.categories.find_or_create_by!(name: "Investment Contributions") do |c|+ c.color = "#0d9488"+ c.lucide_icon = "trending-up"+ c.classification = "expense"+ end+creator = Transfer::Creator.new(family: @family,source_account_id: @source_account.id,@@ -22,17 +29,16 @@ class Transfer::CreatorTest < ActiveSupport::TestCaseassert transfer.persisted?assert_equal "confirmed", transfer.status- assert transfer.regular_transfer?- assert_equal "transfer", transfer.transfer_type- # Verify outflow transaction (from source account)+ # Verify outflow transaction is marked as investment_contributionoutflow = transfer.outflow_transaction- assert_equal "funds_movement", outflow.kind+ assert_equal "investment_contribution", outflow.kindassert_equal @amount, outflow.entry.amountassert_equal @source_account.currency, outflow.entry.currencyassert_equal "Transfer to #{@destination_account.name}", outflow.entry.name+ assert_equal investment_category, outflow.category, "Should auto-assign Investment Contributions category"- # Verify inflow transaction (to destination account)+ # Verify inflow transaction (always funds_movement)inflow = transfer.inflow_transactionassert_equal "funds_movement", inflow.kindassert_equal(@amount * -1, inflow.entry.amount)@@ -40,14 +46,13 @@ class Transfer::CreatorTest < ActiveSupport::TestCaseassert_equal "Transfer from #{@source_account.name}", inflow.entry.nameend- test "creates multi-currency transfer" do- # Use crypto account which has USD currency but different from source- crypto_account = accounts(:crypto)+ test "creates basic transfer between depository accounts" do+ other_depository = @family.accounts.create!(name: "Savings", balance: 1000, currency: "USD", accountable: Depository.new)creator = Transfer::Creator.new(family: @family,source_account_id: @source_account.id,- destination_account_id: crypto_account.id,+ destination_account_id: other_depository.id,date: @date,amount: @amount)@@ -55,13 +60,46 @@ class Transfer::CreatorTest < ActiveSupport::TestCasetransfer = creator.createassert transfer.persisted?+ assert_equal "confirmed", transfer.statusassert transfer.regular_transfer?assert_equal "transfer", transfer.transfer_type- # Verify outflow transaction+ # Verify outflow transaction (depository to depository = funds_movement)outflow = transfer.outflow_transactionassert_equal "funds_movement", outflow.kind+ assert_nil outflow.category, "Should NOT auto-assign category for regular transfers"++ # Verify inflow transaction+ inflow = transfer.inflow_transaction+ assert_equal "funds_movement", inflow.kind+ end++ test "creates investment contribution when transferring from depository to crypto" do+ # Use crypto account - transfer from depository should be investment_contribution+ crypto_account = accounts(:crypto)+ investment_category = @family.categories.find_or_create_by!(name: "Investment Contributions") do |c|+ c.color = "#0d9488"+ c.lucide_icon = "trending-up"+ c.classification = "expense"+ end++ creator = Transfer::Creator.new(+ family: @family,+ source_account_id: @source_account.id,+ destination_account_id: crypto_account.id,+ date: @date,+ amount: @amount+ )++ transfer = creator.create++ assert transfer.persisted?++ # Verify outflow transaction is investment_contribution (not funds_movement)+ outflow = transfer.outflow_transaction+ assert_equal "investment_contribution", outflow.kindassert_equal "Transfer to #{crypto_account.name}", outflow.entry.name+ assert_equal investment_category, outflow.category# Verify inflow transaction with currency handlinginflow = transfer.inflow_transaction@@ -70,6 +108,32 @@ class Transfer::CreatorTest < ActiveSupport::TestCaseassert_equal crypto_account.currency, inflow.entry.currencyend+ test "creates funds_movement for investment to investment transfer (rollover)" do+ # Rollover case: investment → investment should stay as funds_movement+ other_investment = @family.accounts.create!(name: "IRA", balance: 5000, currency: "USD", accountable: Investment.new)++ creator = Transfer::Creator.new(+ family: @family,+ source_account_id: @destination_account.id, # investment account+ destination_account_id: other_investment.id,+ date: @date,+ amount: @amount+ )++ transfer = creator.create++ assert transfer.persisted?++ # Verify outflow is funds_movement (NOT investment_contribution for rollovers)+ outflow = transfer.outflow_transaction+ assert_equal "funds_movement", outflow.kind+ assert_nil outflow.category, "Should NOT auto-assign category for investment→investment transfers"++ # Verify inflow+ inflow = transfer.inflow_transaction+ assert_equal "funds_movement", inflow.kind+ end+test "creates loan payment" doloan_account = accounts(:loan)