The personal finance app for everyone (by everyone)
Ruby
Fix investment-transfer follow-ups from #3719 (#4064)
GFR7e1d93613f82
diff --git a/app/components/DS/category_select.html.erb b/app/components/DS/category_select.html.erbindex 165d6e6f8f..b6be70933d 100644--- a/app/components/DS/category_select.html.erb+++ b/app/components/DS/category_select.html.erb@@ -27,7 +27,7 @@<span data-category-select-target="selectionContainer"class="text-secondary">- <% selected = categories.find { |c| c.id.to_s == selected_id } %>+ <% selected = selected_category %><% if selected %><%= render partial: "categories/badge",diff --git a/app/components/DS/category_select.rb b/app/components/DS/category_select.rbindex f8e152de3b..c534ee82a5 100644--- a/app/components/DS/category_select.rb+++ b/app/components/DS/category_select.rb@@ -5,6 +5,7 @@ class DS::CategorySelect < DesignSystemComponentform:,categories:,selected_id: nil,+ selected_category: nil,disabled: false,auto_submit: false,blank_label: nil@@ -12,11 +13,18 @@ class DS::CategorySelect < DesignSystemComponent@form = form@categories = categories@selected_id = selected_id&.to_s+ @selected_category = selected_category@disabled = disabled@auto_submit = auto_submit@blank_label = blank_labelend+ # A category shown as the selection without being one of `categories`,+ # e.g. a virtual or read-only category on a disabled select.+ def selected_category+ @selected_category || categories.find { |category| category.id.to_s == selected_id }+ end+def field_name"#{form.object_name}[category_id]"enddiff --git a/app/controllers/accounts_controller.rb b/app/controllers/accounts_controller.rbindex fe1ed88688..101d822123 100644--- a/app/controllers/accounts_controller.rb+++ b/app/controllers/accounts_controller.rb@@ -122,7 +122,8 @@ class AccountsController < ApplicationControllerrecords: txn_entryables,associations: {transfer_as_outflow: { inflow_transaction: { entry: :account } },- transfer_as_inflow: { outflow_transaction: { entry: :account } }+ # :category for the read-only category an inflow leg shows (Transaction#category_set_on_transfer_outflow?)+ transfer_as_inflow: { outflow_transaction: [ :category, { entry: :account } ] }}).calldiff --git a/app/controllers/transaction_categories_controller.rb b/app/controllers/transaction_categories_controller.rbindex 95c5dd7314..a0c1593560 100644--- a/app/controllers/transaction_categories_controller.rb+++ b/app/controllers/transaction_categories_controller.rb@@ -4,6 +4,9 @@ class TransactionCategoriesController < ApplicationControllerdef update@entry = Current.accessible_entries.transactions.find(params[:transaction_id])return unless require_account_permission!(@entry.account, :annotate, redirect_path: transaction_path(@entry))+ # The inflow leg of a matched transfer shows its outflow's category+ # read-only (Transaction#category_set_on_transfer_outflow?).+ return head(:unprocessable_entity) if @entry.transaction.category_set_on_transfer_outflow?@entry.update!(entry_params)diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rbindex 3103ecdd3d..38b44c47bb 100644--- a/app/controllers/transactions_controller.rb+++ b/app/controllers/transactions_controller.rb@@ -33,8 +33,9 @@ class TransactionsController < ApplicationController# - outflow rows need inflow_transaction (to_account) for both# counterpart display and Transfer#categorizable?/#payment?# - inflow rows need outflow_transaction (from_account) for- # counterpart display, and inflow_transaction (to_account)- # for the category menu on the same row+ # counterpart display, inflow_transaction (to_account)+ # for the category menu on the same row, and the+ # outflow's category, which the inflow row shows{transfer_as_outflow: {inflow_transaction: { entry: :account }@@ -43,7 +44,7 @@ class TransactionsController < ApplicationController{transfer_as_inflow: {inflow_transaction: { entry: :account },- outflow_transaction: { entry: :account }+ outflow_transaction: [ :category, { entry: :account } ]}})@@ -708,7 +709,7 @@ class TransactionsController < ApplicationController# read_write users can only annotate (category, tags, notes, merchant).# read_only users cannot update anything.def permitted_entry_params- case entry_permission+ permitted = case entry_permissionwhen :owner, :full_controlentry_paramswhen :read_write@@ -721,6 +722,14 @@ class TransactionsController < ApplicationControllerelse{} # read_only — no edits allowedend++ # A matched transfer's category lives on its outflow leg; a category+ # sent for the inflow leg would look saved but never reach a budget.+ if permitted[:entryable_attributes]&.key?(:category_id) && @entry.transaction.category_set_on_transfer_outflow?+ permitted[:entryable_attributes] = permitted[:entryable_attributes].except(:category_id)+ end++ permittedenddef search_paramsdiff --git a/app/helpers/categories_helper.rb b/app/helpers/categories_helper.rbindex 87c2086658..47a574ed16 100644--- a/app/helpers/categories_helper.rb+++ b/app/helpers/categories_helper.rb@@ -19,6 +19,29 @@ module CategoriesHelpercolor: Category::TRADE_COLORend+ # The outflow's category an inflow leg of a categorizable transfer shows+ # read-only (Transaction#category_set_on_transfer_outflow?), or nil when it+ # shows none. Like the counterpart name in transactions/_transaction, it is+ # hidden when the viewer cannot access the outflow's account.+ def transfer_outflow_category(transaction, accessible_account_ids: @accessible_account_ids)+ return unless transaction.category_set_on_transfer_outflow?++ from_account_id = transaction.transfer.outflow_transaction.entry.account_id+ visible = if accessible_account_ids+ accessible_account_ids.include?(from_account_id)+ else+ Current.user.present? && Current.user.accessible_accounts.exists?(id: from_account_id)+ end+ return unless visible++ transaction.transfer.outflow_transaction.category || Category.uncategorized+ end++ # The badge a transaction shows when its category is not editable.+ def read_only_category(transaction)+ transfer_outflow_category(transaction) || (transaction.payment? ? payment_category : transfer_category)+ end+def family_categories[ Category.uncategorized ].concat(Current.family.categories.alphabetically_by_hierarchy)enddiff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rbindex 111921dcdb..50e1c29ccb 100644--- a/app/models/account/provider_import_adapter.rb+++ b/app/models/account/provider_import_adapter.rb@@ -1067,11 +1067,18 @@ class Account::ProviderImportAdapterprivate+ # Loads the transfer together with both legs, their entries and accounts in+ # one joined query, so Transfer#kind_for_leg reads them without the lazy+ # loads it would otherwise pay on every re-imported row. Looked up per row+ # rather than memoized per adapter: most processors build an adapter per+ # row, and some link or destroy transfers mid-sync (Trade Republic), so a+ # memo would be both costlier and stale.def matched_transfer_for(entry)return nil unless entry.persisted?transaction_id = entry.transaction.id- Transfer.where(inflow_transaction_id: transaction_id).or(Transfer.where(outflow_transaction_id: transaction_id)).first+ transfers = Transfer.eager_load(inflow_transaction: { entry: :account }, outflow_transaction: { entry: :account })+ transfers.where(inflow_transaction_id: transaction_id).or(transfers.where(outflow_transaction_id: transaction_id)).firstend# Memoized per adapter instance (which is per-account). Membership indiff --git a/app/models/investment_flow_statement.rb b/app/models/investment_flow_statement.rbindex 4d7418e008..964897dfb2 100644--- a/app/models/investment_flow_statement.rb+++ b/app/models/investment_flow_statement.rb@@ -9,7 +9,8 @@ class InvestmentFlowStatement"COALESCE(ABS(SUM(CASE WHEN transactions.investment_activity_label = 'Withdrawal' " \"THEN entries.amount ELSE 0 END)), 0)")- private_constant :CONTRIBUTIONS_TOTAL_SQL, :WITHDRAWALS_TOTAL_SQL+ INVESTMENT_ACCOUNT_TYPES = %w[Investment Crypto].freeze+ private_constant :CONTRIBUTIONS_TOTAL_SQL, :WITHDRAWALS_TOTAL_SQL, :INVESTMENT_ACCOUNT_TYPESattr_reader :family, :user@@ -20,13 +21,15 @@ class InvestmentFlowStatement# Get contribution/withdrawal totals for a perioddef period_totals(period: Period.current_month)- scope = family.transactions+ base = family.transactions.visible.excluding_pending.where(entries: { date: period.date_range })- .where(kind: %w[standard investment_contribution]).where(investment_activity_label: %w[Contribution Withdrawal])+ scope = base.where(kind: %w[standard investment_contribution])+ .or(matched_investment_flows(base))+if useraccount_ids = family.accounts.included_in_finances_for(user).included_in_reports.select(:id)scope = scope.where(entries: { account_id: account_ids })@@ -45,4 +48,30 @@ class InvestmentFlowStatementendPeriodTotals = Data.define(:contributions, :withdrawals, :net_flow)++ private+ # Matching a provider "Contribution" or "Withdrawal" on an investment/crypto+ # account to its cash counterpart turns that leg into funds_movement+ # (Transfer#kind_for_leg), so the kind filter above would drop it. Count it+ # when the other leg is outside the investment/crypto accounts, the same+ # endpoint rule Transfer.kind_for_account uses. Movements between investment+ # or crypto accounts stay internal and are not counted.+ def matched_investment_flows(base)+ matched_flow(base, label: "Contribution", leg: :inflow_transaction_id, counterpart: :outflow_transaction)+ .or(matched_flow(base, label: "Withdrawal", leg: :outflow_transaction_id, counterpart: :inflow_transaction))+ end++ def matched_flow(base, label:, leg:, counterpart:)+ base+ .where(kind: "funds_movement")+ .where("transactions.investment_activity_label = ?", label)+ .where(entries: { account_id: family.accounts.where(accountable_type: INVESTMENT_ACCOUNT_TYPES).select(:id) })+ .where(+ id: Transfer+ .joins(counterpart => { entry: :account })+ .where(accounts: { family_id: family.id })+ .where.not(accounts: { accountable_type: INVESTMENT_ACCOUNT_TYPES })+ .select(leg)+ )+ endenddiff --git a/app/models/transaction.rb b/app/models/transaction.rbindex 5263da260c..2cc13f7c65 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -160,16 +160,28 @@ class Transaction < ApplicationRecord# stay editable, same as a regular transaction, since there's no# counterpart to defer to and no other way for the user to fix a# provider mislabel.- # - Once matched, both legs defer to Transfer#categorizable?, which is- # based on the (stable) destination account rather than either leg's- # kind, so both legs of e.g. a loan payment agree and stay correct- # even if an older provider sync left a stale kind on this- # transaction.+ # - Once matched, the category belongs to the outflow leg, the one+ # budgets and reports count. Only that leg is editable, and only when+ # Transfer#categorizable?, which is based on the (stable) destination+ # account rather than either leg's kind, so it stays correct even if+ # an older provider sync left a stale kind on this transaction. The+ # inflow leg shows the outflow's category instead (see+ # #category_set_on_transfer_outflow?), since a category picked there+ # would look saved but never reach a budget.def category_editable?+ return false if category_set_on_transfer_outflow?return true unless transfer?return true unless transfer- transfer.categorizable?+ transfer.categorizable? && transfer.outflow_transaction_id == id+ end++ # The inflow leg of a categorizable transfer: its category is the+ # outflow's, shown read-only. Decided by the Transfer record rather than+ # this leg's kind, so editing the kind (e.g. to standard) cannot bypass+ # the outflow's ownership.+ def category_set_on_transfer_outflow?+ transfer_as_inflow.present? && transfer_as_inflow.categorizable?end# Whether this non-editable transfer leg is a liability payment (showndiff --git a/app/models/transfer/investment_kind_reconciler.rb b/app/models/transfer/investment_kind_reconciler.rbnew file mode 100644index 0000000000..243951c039--- /dev/null+++ b/app/models/transfer/investment_kind_reconciler.rb@@ -0,0 +1,75 @@+# Brings the stored kinds of transfers into investment/crypto accounts in line+# with Transfer#kind_for_leg. Older syncs and match paths left some of these+# legs on a kind the current rules no longer give them, e.g. an+# investment-to-investment outflow still marked investment_contribution+# (counted as a budgeted expense), or a matched brokerage inflow a provider+# sync turned back into investment_contribution. Provider syncs only repair+# the rows they happen to replay, so history outside the replay window keeps+# the old kinds until this runs.+#+# Bounded and idempotent:+# - only transfers whose destination is an investment or crypto account;+# - only legs whose current kind is one of Transaction::TRANSFER_KINDS, so a+# kind the user chose (standard, one_time) is never overwritten;+# - excluded entries and transactions with a locked kind are left alone;+# - a second run finds nothing to change.+#+# Entries created or matched through Transfer::Creator and the match dialog+# are user_modified by design, so that flag does not mark a user's choice of+# kind here and is not a reason to skip a leg.+class Transfer::InvestmentKindReconciler+ INVESTMENT_TYPES = %w[Investment Crypto].freeze++ Result = Data.define(:checked, :changed)++ def initialize(scope: Transfer.all, dry_run: false)+ @scope = scope+ @dry_run = dry_run+ end++ def run+ checked = 0+ changed = Hash.new(0)++ transfers.find_each do |transfer|+ checked += 1++ [ transfer.inflow_transaction, transfer.outflow_transaction ].each do |transaction|+ next unless repairable?(transaction)++ expected = transfer.kind_for_leg(transaction)+ next if transaction.kind == expected++ changed["#{transaction.kind}->#{expected}"] += 1+ repair!(transaction, expected) unless dry_run+ end+ end++ Result.new(checked: checked, changed: changed)+ end++ private+ attr_reader :scope, :dry_run++ def transfers+ scope+ .joins(inflow_transaction: { entry: :account })+ .where(accounts: { accountable_type: INVESTMENT_TYPES })+ .includes(inflow_transaction: { entry: :account }, outflow_transaction: { entry: :account })+ end++ def repairable?(transaction)+ Transaction::TRANSFER_KINDS.include?(transaction.kind) &&+ !transaction.entry.excluded? &&+ !transaction.locked?(:kind)+ end++ def repair!(transaction, kind)+ now = Time.current+ Transaction.transaction do+ transaction.update_columns(kind: kind, updated_at: now)+ # Report and transaction-list caches are keyed on entries' updated_at.+ transaction.entry.update_columns(updated_at: now)+ end+ end+enddiff --git a/app/views/categories/_category_name_mobile.html.erb b/app/views/categories/_category_name_mobile.html.erbindex 0c18f39480..85c0fb0f56 100644--- a/app/views/categories/_category_name_mobile.html.erb+++ b/app/views/categories/_category_name_mobile.html.erb@@ -2,6 +2,6 @@<% if transaction.category_editable? %><%= transaction.category&.display_name || Category.uncategorized.display_name %><% else %>- <%= transaction.payment? ? payment_category.display_name : transfer_category.display_name %>+ <%= read_only_category(transaction).display_name %><% end %></span>diff --git a/app/views/transactions/_transaction_category.html.erb b/app/views/transactions/_transaction_category.html.erbindex 0da719edb5..d92889708f 100644--- a/app/views/transactions/_transaction_category.html.erb+++ b/app/views/transactions/_transaction_category.html.erb@@ -4,11 +4,18 @@<% if transaction.category_editable? %><%= render "categories/menu", transaction: transaction, in_split_group: in_split_group %><% else %>- <div class="hidden lg:flex">- <%= render "categories/badge", category: transaction.payment? ? payment_category : transfer_category %>+ <% category = read_only_category(transaction) %>+ <% set_on_outflow = transaction.category_set_on_transfer_outflow? %>+ <div class="hidden lg:flex items-center gap-1 min-w-0">+ <div class="<%= "opacity-60 cursor-not-allowed" if set_on_outflow %>">+ <%= render "categories/badge", category: category %>+ </div>+ <% if set_on_outflow %>+ <%= render DS::Tooltip.new(text: t("transactions.transaction_category.set_on_outflow")) %>+ <% end %></div><div class="flex lg:hidden">- <%= render "categories/badge_mobile", category: transaction.payment? ? payment_category : transfer_category %>+ <%= render "categories/badge_mobile", category: category %></div><% end %></div>diff --git a/app/views/transactions/show.html.erb b/app/views/transactions/show.html.erbindex 01f9e41fe4..ec59db9b53 100644--- a/app/views/transactions/show.html.erb+++ b/app/views/transactions/show.html.erb@@ -94,6 +94,21 @@blank_label: t(".uncategorized")) %><% end %>+ <% elsif @entry.transaction.category_set_on_transfer_outflow? %>+ <% outflow_category = transfer_outflow_category(@entry.transaction) %>+ <div class="space-y-1">+ <div class="opacity-60 cursor-not-allowed">+ <%= f.fields_for :entryable do |ef| %>+ <%= render DS::CategorySelect.new(+ form: ef,+ categories: [],+ selected_category: outflow_category || transfer_category,+ disabled: true+ ) %>+ <% end %>+ </div>+ <p class="text-xs text-secondary"><%= outflow_category ? t(".category_set_on_outflow") : t(".category_set_on_hidden_outflow") %></p>+ </div><% end %><% end %></div>diff --git a/config/locales/views/transactions/de.yml b/config/locales/views/transactions/de.ymlindex 8101daa94d..2d523ab68c 100644--- a/config/locales/views/transactions/de.yml+++ b/config/locales/views/transactions/de.yml@@ -35,7 +35,11 @@ de:merchant_label: Händlernew:new_transaction: Neue Transaktion+ transaction_category:+ set_on_outflow: "Die Kategorie gehört zur Abbuchung dieses Transfers und lässt sich nur dort ändern"show:+ category_set_on_hidden_outflow: "Dies ist die Gutschrift eines Transfers. Die Kategorie gehört zur Abbuchung auf einem Konto, auf das du keinen Zugriff hast, und lässt sich nur dort ändern."+ category_set_on_outflow: "Dies ist die Gutschrift eines Transfers. Die Kategorie gehört zur Abbuchung und lässt sich nur dort ändern, damit Budgets sie nur einmal zählen."account_label: Kontoamount: Betragcategory_label: Kategoriediff --git a/config/locales/views/transactions/en.yml b/config/locales/views/transactions/en.ymlindex 22d427a91e..d0f5e247f8 100644--- a/config/locales/views/transactions/en.yml+++ b/config/locales/views/transactions/en.yml@@ -61,7 +61,11 @@ en:updated: Transaction updatednew:new_transaction: New transaction+ transaction_category:+ set_on_outflow: "The category belongs to the outgoing side of this transfer and can only be changed there"show:+ category_set_on_hidden_outflow: "This is the incoming side of a transfer. Its category belongs to the outgoing side, on an account you cannot access, and can only be changed there."+ category_set_on_outflow: "This is the incoming side of a transfer. Its category belongs to the outgoing side and can only be changed there, so budgets count it once."keep_both: No, keep bothloan_payment: Loan Paymentmark_recurring: Mark as Recurringdiff --git a/lib/tasks/data_migration.rake b/lib/tasks/data_migration.rakeindex 724d017138..bd1de18e38 100644--- a/lib/tasks/data_migration.rake+++ b/lib/tasks/data_migration.rake@@ -246,4 +246,34 @@ namespace :data_migration doputs "✅ Provider settings migration complete."end++ desc "Reconcile stored kinds of transfers into investment/crypto accounts"+ # 2026-10-08: older syncs and match paths left some legs of transfers into+ # investment/crypto accounts on a kind the current rules no longer give them+ # (see Transfer::InvestmentKindReconciler). Provider syncs only repair the+ # rows they replay. Idempotent; only transfer kinds are rewritten, standard+ # and one_time are left alone. Report totals for affected periods can change,+ # and reverting the code later does not restore the previous kinds.+ #+ # DRY_RUN=1 print what would change without writing+ # FAMILY_ID=id limit the run to one family+ task reconcile_investment_transfer_kinds: :environment do+ dry_run = ActiveModel::Type::Boolean.new.cast(ENV["DRY_RUN"]) || false+ scope = Transfer.all++ if ENV["FAMILY_ID"].present?+ family = Family.find_by(id: ENV["FAMILY_ID"])+ abort "No family with id #{ENV["FAMILY_ID"]}" unless family+ scope = scope.where(inflow_transaction_id: family.transactions.select(:id))+ end++ result = Transfer::InvestmentKindReconciler.new(scope: scope, dry_run: dry_run).run++ puts "#{dry_run ? "Dry run: " : ""}checked #{result.checked} transfers into investment/crypto accounts"+ if result.changed.empty?+ puts "No legs needed a new kind."+ else+ result.changed.each { |change, count| puts " #{change}: #{count}" }+ end+ endenddiff --git a/test/controllers/transaction_categories_controller_test.rb b/test/controllers/transaction_categories_controller_test.rbindex d53a2e6bba..526c4de336 100644--- a/test/controllers/transaction_categories_controller_test.rb+++ b/test/controllers/transaction_categories_controller_test.rb@@ -63,4 +63,39 @@ class TransactionCategoriesControllerTest < ActionDispatch::IntegrationTestassert_response :successassert_not_includes response.body, "action_type=set_transaction_category"end++ test "a matched transfer's inflow leg does not take a category" do+ outflow, inflow = create_contribution_transfer+ category = categories(:income)++ patch transaction_category_url(inflow.entry),+ params: { entry: { entryable_type: "Transaction", entryable_attributes: { id: inflow.id, category_id: category.id } } },+ as: :turbo_stream++ assert_response :unprocessable_entity+ assert_nil inflow.reload.category_id+ assert_nil outflow.reload.category_id+ end++ test "a matched transfer's outflow leg still takes a category" do+ outflow, _inflow = create_contribution_transfer+ category = categories(:income)++ patch transaction_category_url(outflow.entry),+ params: { entry: { entryable_type: "Transaction", entryable_attributes: { id: outflow.id, category_id: category.id } } },+ as: :turbo_stream++ assert_response :success+ assert_equal category, outflow.reload.category+ end++ private+ def create_contribution_transfer+ outflow = Transaction.create!(kind: "investment_contribution")+ Entry.create!(account: accounts(:depository), entryable: outflow, name: "Contribution", amount: 500, currency: "USD", date: Date.current)+ inflow = Transaction.create!(kind: "funds_movement")+ Entry.create!(account: accounts(:investment), entryable: inflow, name: "Contribution", amount: -500, currency: "USD", date: Date.current)+ Transfer.create!(inflow_transaction: inflow, outflow_transaction: outflow, status: "confirmed")+ [ outflow, inflow ]+ endenddiff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rbindex 9516ced6bb..ffe35baf77 100644--- a/test/controllers/transactions_controller_test.rb+++ b/test/controllers/transactions_controller_test.rb@@ -1754,6 +1754,54 @@ endassert_no_match(/ai_status/, response.location)end+ test "update drops a category sent for a matched transfer's inflow leg" do+ outflow = Transaction.create!(kind: "investment_contribution")+ Entry.create!(account: accounts(:depository), entryable: outflow, name: "Contribution", amount: 500, currency: "USD", date: Date.current)+ inflow = Transaction.create!(kind: "funds_movement")+ inflow_entry = Entry.create!(account: accounts(:investment), entryable: inflow, name: "Contribution", amount: -500, currency: "USD", date: Date.current)+ Transfer.create!(inflow_transaction: inflow, outflow_transaction: outflow, status: "confirmed")++ patch transaction_url(inflow_entry), params: {+ entry: {+ notes: "Monthly savings",+ entryable_type: "Transaction",+ entryable_attributes: { id: inflow.id, category_id: categories(:income).id }+ }+ }++ assert_nil inflow.reload.category_id+ assert_equal "Monthly savings", inflow_entry.reload.notes+ end++ test "update drops a category for a matched inflow leg whose kind was edited to standard" do+ outflow = Transaction.create!(kind: "investment_contribution")+ Entry.create!(account: accounts(:depository), entryable: outflow, name: "Contribution", amount: 500, currency: "USD", date: Date.current)+ inflow = Transaction.create!(kind: "standard")+ inflow_entry = Entry.create!(account: accounts(:investment), entryable: inflow, name: "Contribution", amount: -500, currency: "USD", date: Date.current)+ Transfer.create!(inflow_transaction: inflow, outflow_transaction: outflow, status: "confirmed")++ patch transaction_url(inflow_entry), params: {+ entry: { entryable_type: "Transaction", entryable_attributes: { id: inflow.id, category_id: categories(:income).id } }+ }++ assert_nil inflow.reload.category_id+ end++ test "drawer shows a matched transfer's inflow leg with the outflow's category, disabled" do+ outflow = Transaction.create!(kind: "investment_contribution", category: categories(:income))+ Entry.create!(account: accounts(:depository), entryable: outflow, name: "Contribution", amount: 500, currency: "USD", date: Date.current)+ inflow = Transaction.create!(kind: "funds_movement")+ inflow_entry = Entry.create!(account: accounts(:investment), entryable: inflow, name: "Contribution", amount: -500, currency: "USD", date: Date.current)+ Transfer.create!(inflow_transaction: inflow, outflow_transaction: outflow, status: "confirmed")++ get transaction_url(inflow_entry), headers: { "Turbo-Frame" => "drawer" }++ assert_response :success+ assert_select "button#category_id_trigger[disabled]", text: /#{categories(:income).name}/+ assert_select "input[type=hidden][name='entry[entryable_attributes][category_id]'][disabled]"+ assert_match I18n.t("transactions.show.category_set_on_outflow"), response.body+ end+privatedef rendered_entry_idscss_select("turbo-frame[id^='entry_']").map { |node| node["id"].delete_prefix("entry_") }diff --git a/test/models/account/provider_import_adapter_test.rb b/test/models/account/provider_import_adapter_test.rbindex db60636e3b..acbda23b77 100644--- a/test/models/account/provider_import_adapter_test.rb+++ b/test/models/account/provider_import_adapter_test.rb@@ -260,6 +260,45 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseassert_equal "funds_movement", entry.transaction.reload.kindend+ test "deriving a matched leg's kind on re-import costs one query per row" do+ amounts = [ 150.00, 160.00, 170.00 ]+ amounts.each_with_index do |amount, i|+ Account::ProviderImportAdapter.new(accounts(:loan)).import_transaction(+ external_id: "up_loan_inflow_batch_#{i}", amount: -amount, currency: "USD",+ date: Date.current, name: "Loan Repayment Received", source: "up"+ )+ @adapter.import_transaction(+ external_id: "up_checking_outflow_batch_#{i}", amount: amount, currency: "USD",+ date: Date.current, name: "Loan Repayment", source: "up"+ )+ end+ @family.auto_match_transfers!++ # Up flags the outgoing legs as internal transfers, so the kind is derived+ # from each leg's transfer; without the hint the adapter derives nothing.+ reimport = lambda do |kind|+ ActiveRecord::Base.uncached do+ capture_sql_queries do+ amounts.each_with_index do |amount, i|+ Account::ProviderImportAdapter.new(@account).import_transaction(+ external_id: "up_checking_outflow_batch_#{i}", amount: amount, currency: "USD",+ date: Date.current, name: "Loan Repayment", source: "up", kind: kind+ )+ end+ end+ end+ end++ without_derivation = reimport.call(nil)+ with_derivation = reimport.call("funds_movement")++ assert_equal without_derivation.size + amounts.size, with_derivation.size,+ "the transfer, its legs and their accounts should load in one query per row"+ amounts.each_index do |i|+ assert_equal "loan_payment", @account.entries.find_by!(external_id: "up_checking_outflow_batch_#{i}").transaction.kind+ end+ end+test "updates existing transaction instead of creating duplicate" do# Create initial transactionentry = @adapter.import_transaction(@@ -1975,4 +2014,22 @@ class Account::ProviderImportAdapterTest < ActiveSupport::TestCaseassert_equal "outgoing_payment_sent", refreshed.extra.dig("wise", "status"),"the provider's own namespace should still refresh"end++ private++ def capture_sql_queries+ queries = []+ callback = lambda do |_name, _started, _finished, _unique_id, payload|+ next if payload[:cached]+ next if %w[SCHEMA TRANSACTION].include?(payload[:name])++ queries << payload[:sql].squish+ end++ ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do+ yield+ end++ queries+ endenddiff --git a/test/models/investment_flow_statement_test.rb b/test/models/investment_flow_statement_test.rbindex 2e0b5fbe60..cd17839adb 100644--- a/test/models/investment_flow_statement_test.rb+++ b/test/models/investment_flow_statement_test.rb@@ -41,7 +41,101 @@ class InvestmentFlowStatementTest < ActiveSupport::TestCaseassert_includes aggregate_queries.first, '"entries"."account_id" IN (SELECT DISTINCT "accounts"."id"'end+ test "a matched provider contribution still counts once after resync" do+ family = families(:dylan_family)+ brokerage = Account::ProviderImportAdapter.new(accounts(:investment))+ checking = Account::ProviderImportAdapter.new(accounts(:depository))+ period = Period.custom(start_date: Date.current, end_date: Date.current)+ expenses_before = IncomeStatement.new(family).expense_totals(period: period).total++ inflow = brokerage.import_transaction(+ external_id: "plaid_brokerage_contribution", amount: -500, currency: "USD",+ date: Date.current, name: "Contribution", source: "plaid",+ investment_activity_label: "Contribution"+ )+ outflow = checking.import_transaction(+ external_id: "plaid_checking_to_brokerage", amount: 500, currency: "USD",+ date: Date.current, name: "Transfer to brokerage", source: "plaid"+ )+ family.auto_match_transfers!+ assert inflow.transaction.reload.transfer.present?, "expected the two legs to be auto-matched"++ # The next sync replays the brokerage row; the matched inflow keeps funds_movement.+ brokerage.import_transaction(+ external_id: "plaid_brokerage_contribution", amount: -500, currency: "USD",+ date: Date.current, name: "Contribution", source: "plaid",+ investment_activity_label: "Contribution"+ )+ assert_equal "funds_movement", inflow.transaction.reload.kind+ assert_equal "investment_contribution", outflow.transaction.reload.kind++ totals = InvestmentFlowStatement.new(family).period_totals(period: period)+ assert_equal Money.new(500, "USD"), totals.contributions++ expenses_after = IncomeStatement.new(family).expense_totals(period: period).total+ assert_equal 500, expenses_after - expenses_before, "the contribution is budgeted once, on the cash leg"+ end++ test "a matched provider withdrawal still counts once" do+ family = families(:dylan_family)+ period = Period.custom(start_date: Date.current, end_date: Date.current)++ outflow = accounts(:investment).entries.create!(+ name: "Withdrawal", amount: 300, date: Date.current, currency: "USD",+ entryable: Transaction.new(kind: "standard", investment_activity_label: "Withdrawal")+ )+ accounts(:depository).entries.create!(+ name: "From brokerage", amount: -300, date: Date.current, currency: "USD",+ entryable: Transaction.new(kind: "standard")+ )+ family.auto_match_transfers!+ assert outflow.transaction.reload.transfer.present?, "expected the two legs to be auto-matched"+ assert_equal "funds_movement", outflow.transaction.kind++ totals = InvestmentFlowStatement.new(family).period_totals(period: period)+ assert_equal Money.new(300, "USD"), totals.withdrawals+ assert_equal Money.new(0, "USD"), totals.contributions+ end++ test "movements between investment and crypto accounts are not contributions" do+ family = families(:dylan_family)+ period = Period.custom(start_date: Date.current, end_date: Date.current)++ inflow = create_matched_contribution(family, from: accounts(:crypto), to: accounts(:investment))+ assert_equal "funds_movement", inflow.transaction.kind++ totals = InvestmentFlowStatement.new(family).period_totals(period: period)+ assert_equal Money.new(0, "USD"), totals.contributions+ end++ test "a matched contribution respects the viewer's account visibility" do+ family = families(:dylan_family)+ period = Period.custom(start_date: Date.current, end_date: Date.current)+ create_matched_contribution(family, from: accounts(:depository), to: accounts(:investment))++ member = users(:family_member)+ assert_not family.accounts.included_in_finances_for(member).include?(accounts(:investment))++ assert_equal Money.new(250, "USD"), InvestmentFlowStatement.new(family).period_totals(period: period).contributions+ assert_equal Money.new(0, "USD"), InvestmentFlowStatement.new(family, user: member).period_totals(period: period).contributions+ end+private+ def create_matched_contribution(family, from:, to:)+ inflow = to.entries.create!(+ name: "Contribution", amount: -250, date: Date.current, currency: "USD",+ entryable: Transaction.new(kind: "investment_contribution", investment_activity_label: "Contribution")+ )+ outflow = from.entries.create!(+ name: "Transfer out", amount: 250, date: Date.current, currency: "USD",+ entryable: Transaction.new(kind: "standard")+ )+ family.auto_match_transfers!+ assert inflow.transaction.reload.transfer.present?, "expected the two legs to be auto-matched"+ assert_equal outflow.transaction.id, inflow.transaction.transfer.outflow_transaction_id+ inflow+ end+def create_flow(label:, amount:, date:)@account.entries.create!(name: label,diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rbindex 48b331f735..e4f8f1f202 100644--- a/test/models/transaction_test.rb+++ b/test/models/transaction_test.rb@@ -158,17 +158,18 @@ class TransactionTest < ActiveSupport::TestCaseassert Transaction.new(kind: "cc_payment").category_editable?end- test "category_editable? defers both legs to Transfer#categorizable? when a Transfer record exists" do+ test "category_editable? keeps a matched transfer's category on its outflow leg" dooutflow_entry = create_transaction(date: Date.current, account: accounts(:depository), amount: 500, kind: "investment_contribution")inflow_entry = create_transaction(date: Date.current, account: accounts(:investment), amount: -500, kind: "funds_movement")Transfer.create!(inflow_transaction: inflow_entry.transaction, outflow_transaction: outflow_entry.transaction)- # Transfer#categorizable? is destination-account based, not leg based, so- # the inflow leg (whose stored kind is always "funds_movement" per- # Transfer::Creator) agrees with the outflow leg instead of being- # unconditionally locked.+ # Budgets count the outflow leg, so only that leg takes a category; the+ # inflow leg shows the outflow's category read-only instead of a picker+ # whose choice would never reach a budget.assert outflow_entry.transaction.reload.category_editable?- assert inflow_entry.transaction.reload.category_editable?+ assert_not outflow_entry.transaction.category_set_on_transfer_outflow?+ assert_not inflow_entry.transaction.reload.category_editable?+ assert inflow_entry.transaction.category_set_on_transfer_outflow?fm_outflow = create_transaction(date: Date.current, account: accounts(:depository), amount: 500, kind: "funds_movement")fm_inflow = create_transaction(date: Date.current, account: accounts(:connected), amount: -500, kind: "funds_movement")@@ -176,6 +177,17 @@ class TransactionTest < ActiveSupport::TestCaseassert_not fm_outflow.transaction.reload.category_editable?assert_not fm_inflow.transaction.reload.category_editable?+ assert_not fm_inflow.transaction.category_set_on_transfer_outflow?+ end++ test "a matched inflow leg stays read-only after its kind is edited to standard" do+ outflow_entry = create_transaction(date: Date.current, account: accounts(:depository), amount: 500, kind: "investment_contribution")+ inflow_entry = create_transaction(date: Date.current, account: accounts(:investment), amount: -500, kind: "funds_movement")+ Transfer.create!(inflow_transaction: inflow_entry.transaction, outflow_transaction: outflow_entry.transaction)+ inflow_entry.transaction.update!(kind: "standard")++ assert inflow_entry.transaction.reload.category_set_on_transfer_outflow?+ assert_not inflow_entry.transaction.category_editable?endtest "category_editable? stays true for the outflow leg even if a later sync leaves a stale funds_movement kind" dodiff --git a/test/models/transfer/investment_kind_reconciler_test.rb b/test/models/transfer/investment_kind_reconciler_test.rbnew file mode 100644index 0000000000..5e184b9a2e--- /dev/null+++ b/test/models/transfer/investment_kind_reconciler_test.rb@@ -0,0 +1,102 @@+require "test_helper"++class Transfer::InvestmentKindReconcilerTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ end++ test "repairs a legacy investment-to-investment outflow still marked as a contribution" do+ transfer = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "investment_contribution")++ result = Transfer::InvestmentKindReconciler.new.run++ assert_equal "funds_movement", transfer.outflow_transaction.reload.kind+ assert_equal "funds_movement", transfer.inflow_transaction.reload.kind+ assert_equal({ "investment_contribution->funds_movement" => 1 }, result.changed)+ end++ test "repairs a matched brokerage inflow an earlier sync turned back into a contribution" do+ transfer = create_transfer(from: accounts(:depository), to: accounts(:investment),+ outflow_kind: "investment_contribution", inflow_kind: "investment_contribution")++ Transfer::InvestmentKindReconciler.new.run++ assert_equal "funds_movement", transfer.inflow_transaction.reload.kind+ assert_equal "investment_contribution", transfer.outflow_transaction.reload.kind+ end++ test "repairs a legacy pair imported without a kind hint" do+ inflow = Account::ProviderImportAdapter.new(accounts(:investment)).import_transaction(+ external_id: "plaid_no_hint_in", amount: -80, currency: "USD", date: Date.current,+ name: "Deposit", source: "plaid"+ )+ outflow = Account::ProviderImportAdapter.new(accounts(:crypto)).import_transaction(+ external_id: "plaid_no_hint_out", amount: 80, currency: "USD", date: Date.current,+ name: "Withdrawal to brokerage", source: "plaid"+ )+ transfer = Transfer.create!(inflow_transaction: inflow.transaction, outflow_transaction: outflow.transaction, status: "confirmed")+ # State left by the old classification of investment-to-investment transfers.+ transfer.outflow_transaction.update_columns(kind: "investment_contribution")++ Transfer::InvestmentKindReconciler.new.run++ assert_equal "funds_movement", outflow.transaction.reload.kind+ end++ test "keeps kinds the user chose, excluded entries and locked kinds" do+ one_time = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "one_time")+ excluded = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "investment_contribution")+ excluded.outflow_transaction.entry.update_columns(excluded: true)+ locked = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "investment_contribution")+ locked.outflow_transaction.lock_attr!(:kind)++ Transfer::InvestmentKindReconciler.new.run++ assert_equal "one_time", one_time.outflow_transaction.reload.kind+ assert_equal "investment_contribution", excluded.outflow_transaction.reload.kind+ assert_equal "investment_contribution", locked.outflow_transaction.reload.kind+ end++ test "leaves transfers into other account types alone" do+ loan = create_transfer(from: accounts(:depository), to: accounts(:loan),+ outflow_kind: "loan_payment", inflow_kind: "loan_payment")++ result = Transfer::InvestmentKindReconciler.new.run++ assert_equal "loan_payment", loan.inflow_transaction.reload.kind+ assert_equal 0, result.checked+ end++ test "is idempotent and touches the entry so caches expire" do+ transfer = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "investment_contribution")+ entry = transfer.outflow_transaction.entry+ entry.update_columns(updated_at: 1.day.ago)++ Transfer::InvestmentKindReconciler.new.run+ assert entry.reload.updated_at > 1.minute.ago++ assert_empty Transfer::InvestmentKindReconciler.new.run.changed+ end++ test "dry run reports without writing" do+ transfer = create_transfer(from: accounts(:crypto), to: accounts(:investment), outflow_kind: "investment_contribution")++ result = Transfer::InvestmentKindReconciler.new(dry_run: true).run++ assert_equal({ "investment_contribution->funds_movement" => 1 }, result.changed)+ assert_equal "investment_contribution", transfer.outflow_transaction.reload.kind+ end++ private+ def create_transfer(from:, to:, outflow_kind:, inflow_kind: "funds_movement", amount: 100)+ inflow = to.entries.create!(+ name: "Transfer in", amount: -amount, date: Date.current, currency: "USD",+ entryable: Transaction.new(kind: inflow_kind)+ )+ outflow = from.entries.create!(+ name: "Transfer out", amount: amount, date: Date.current, currency: "USD",+ entryable: Transaction.new(kind: outflow_kind)+ )+ Transfer.create!(inflow_transaction: inflow.transaction, outflow_transaction: outflow.transaction, status: "confirmed")+ end+enddiff --git a/test/system/property_test.rb b/test/system/property_test.rbindex 24610146e4..07f321ddb7 100644--- a/test/system/property_test.rb+++ b/test/system/property_test.rb@@ -13,8 +13,7 @@ class PropertiesEditTest < ApplicationSystemTestCasetest "can persist property subtype" doclick_link "[system test] Property Account"- open_account_edit_dialog- assert_field "account_accountable_attributes_subtype", with: "single_family_home"+ assert_edit_dialog_field "account_accountable_attributes_subtype", with: "single_family_home"endprivate@@ -26,15 +25,20 @@ class PropertiesEditTest < ApplicationSystemTestCase# turbo-frame before the dialog is interactive — and can detach the menu# node mid-click ("Node with given id does not belong to the document"),# which Capybara does not auto-retry. Open via the account menu and retry- # until the edit form is present so the test is deterministic instead of- # racing the broadcast.- def open_account_edit_dialog- 3.times do+ # until the edit form shows the expected value. The value is checked inside+ # the retry: checking only that the field exists and asserting the value+ # afterwards lets a morph remove the modal in between, and the caller's+ # assertion then waits on a field that never comes back.+ def assert_edit_dialog_field(locator, with:)+ found = 3.times.any? do# A prior (slow) attempt may have already opened the edit form. Check# the field is enabled, not just present — the select briefly exists- # but disabled while the form finishes hydrating, and assert_field's- # default matcher (used by the caller) excludes disabled fields.- return if has_field?("account_accountable_attributes_subtype", wait: 0)+ # but disabled while the form finishes hydrating, and has_field?'s+ # default matcher excludes disabled fields.+ next true if has_field?(locator, with: with, wait: 0)+ # An open form with another value is a real failure; reopening the+ # dialog would not change the value, so let the final assertion report it.+ next false if has_field?(locator, wait: 0)beginwithin_testid("account-menu") do@@ -51,11 +55,13 @@ class PropertiesEditTest < ApplicationSystemTestCaseraise unless e.message.match?(/does not belong to the document|stale element reference/i,)- next+ next falseend- return if has_field?("account_accountable_attributes_subtype", wait: 2)+ has_field?(locator, with: with, wait: 2)end- assert_field "account_accountable_attributes_subtype"+ return pass if found++ assert_field locator, with: withenddef open_new_account_modaldiff --git a/test/views/transactions/transaction_category_view_test.rb b/test/views/transactions/transaction_category_view_test.rbindex c1e5767ccb..551625b842 100644--- a/test/views/transactions/transaction_category_view_test.rb+++ b/test/views/transactions/transaction_category_view_test.rb@@ -31,8 +31,9 @@ class Transactions::TransactionCategoryViewTest < ActionView::TestCaseassert_includes html, "category_dropdown"end- test "renders the category picker for an investment-contribution inflow leg" do- outflow_tx = Transaction.create!(kind: "investment_contribution")+ test "shows the outflow's category read-only on an investment-contribution inflow leg" do+ category = categories(:income)+ outflow_tx = Transaction.create!(kind: "investment_contribution", category: category)Entry.create!(account: accounts(:depository), entryable: outflow_tx,name: "Contribution", amount: 500, currency: "USD", date: Date.today@@ -47,10 +48,32 @@ class Transactions::TransactionCategoryViewTest < ActionView::TestCaseTransfer.create!(inflow_transaction: inflow_tx, outflow_transaction: outflow_tx, status: "confirmed")html = render(partial: "transactions/transaction_category", locals: {- transaction: inflow_tx, variant: "desktop", in_split_group: false+ transaction: inflow_tx.reload, variant: "desktop", in_split_group: false})- assert_includes html, "category_dropdown"+ assert_not_includes html, "category_dropdown"+ assert_includes html, category.display_name+ assert_includes html, I18n.t("transactions.transaction_category.set_on_outflow")+ end++ test "hides the outflow's category when the viewer cannot access the outflow's account" do+ category = categories(:income)+ owner_only = accounts(:investment).family.accounts.create!(+ owner: users(:family_admin), name: "Private checking", balance: 0, currency: "USD", accountable: Depository.new+ )+ outflow_tx = Transaction.create!(kind: "investment_contribution", category: category)+ Entry.create!(account: owner_only, entryable: outflow_tx, name: "Contribution", amount: 500, currency: "USD", date: Date.today)+ inflow_tx = Transaction.create!(kind: "funds_movement")+ Entry.create!(account: accounts(:investment), entryable: inflow_tx, name: "Contribution", amount: -500, currency: "USD", date: Date.today)+ Transfer.create!(inflow_transaction: inflow_tx, outflow_transaction: outflow_tx, status: "confirmed")++ @accessible_account_ids = [ accounts(:investment).id ]+ html = render(partial: "transactions/transaction_category", locals: {+ transaction: inflow_tx.reload, variant: "desktop", in_split_group: false+ })++ assert_not_includes html, category.display_name+ assert_includes html, transfer_category.display_nameendtest "renders the transfer badge instead of a picker for a regular funds-movement transfer" do