The personal finance app for everyone (by everyone)
Ruby
Count deposits and withdrawals, not trades, as investment contributions (#5070)
arnaurodondev50343bcb666a
diff --git a/app/models/demo/generator.rb b/app/models/demo/generator.rbindex ed1ac74a1d..96fb313b13 100644--- a/app/models/demo/generator.rb+++ b/app/models/demo/generator.rb@@ -1081,7 +1081,9 @@ class Demo::Generatorcurrency: to_account.currency,date: date)- Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: outflow.entryable)+ # Confirmed, as Transfer::Creator makes a transfer the user records: a+ # pending one is an auto-match suggestion, which reports leave unlinked.+ Transfer.create!(inflow_transaction: inflow.entryable, outflow_transaction: outflow.entryable, status: "confirmed")enddef load_securities!diff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rbindex d4e1b1ec68..82baf89e9a 100644--- a/app/models/investment_statement.rb+++ b/app/models/investment_statement.rb@@ -14,13 +14,15 @@ class InvestmentStatement# Get totals for a specific perioddef totals(period: Period.current_month)- account_ids = investment_account_ids+ account_ids = totals_account_idsresult = totals_query(account_ids: account_ids, date_range: period.date_range)PeriodTotals.new(contributions: Money.new(result[:contributions], family.currency),withdrawals: Money.new(result[:withdrawals], family.currency),+ buys: Money.new(result[:buys], family.currency),+ sells: Money.new(result[:sells], family.currency),dividends: Money.new(result[:dividends], family.currency),interest: Money.new(result[:interest], family.currency),trades_count: result[:trades_count],@@ -415,11 +417,7 @@ class InvestmentStatement# Investment accountsdef investment_accounts- @investment_accounts ||= begin- scope = family.accounts.visible.included_in_reports.where(accountable_type: %w[Investment Crypto])- scope = scope.included_in_finances_for(user) if user- scope- end+ @investment_accounts ||= report_accounts.where(accountable_type: %w[Investment Crypto])endprivate@@ -458,7 +456,7 @@ class InvestmentStatement@all_time_totals ||= totals(period: Period.all_time)end- PeriodTotals = Data.define(:contributions, :withdrawals, :dividends, :interest, :trades_count, :currency) do+ PeriodTotals = Data.define(:contributions, :withdrawals, :buys, :sells, :dividends, :interest, :trades_count, :currency) dodef net_flowcontributions - withdrawalsend@@ -853,19 +851,77 @@ class InvestmentStatement@investment_account_ids ||= investment_accounts.pluck(:id)end+ def report_accounts+ scope = family.accounts.visible.included_in_reports+ user ? scope.included_in_finances_for(user) : scope+ end++ # The accounts #totals reads: the investment accounts, plus the cash+ # account a broker settles their trades on when it keeps the cash in an+ # account of its own. Trade Republic does: its Cash account is a+ # depository account, and each trade's settlement there is linked to the+ # Portfolio or Crypto account as a confirmed transfer+ # (TradeRepublicAccount.settlement_account_ids_for). Taken as one scope,+ # those settlements are internal, like a buy paid from an investment+ # account's own cash, and money is counted where it enters or leaves the+ # broker: a transfer between the Cash account and the user's bank. As on+ # every account the totals read, a cash row counts only when it records+ # a flow (Totals#recorded_flow_sql), so card payments and other unlinked+ # rows on the Cash account are neither. Nor is a credit card or loan+ # payment made from it: Totals is told which accounts settle trades, and+ # leaves those payments out there (see Totals#recorded_flow_sql). Income+ # the broker books there (dividends, interest) is read with it. The Cash+ # account passes the same report and visibility filters as the investment+ # accounts. A user who does not have it in their finances therefore gets+ # the investment accounts alone, on which each settlement counts as a+ # contribution or a withdrawal again.+ #+ # Only a provider that books trade settlements this way is followed, not+ # every account of the same connection: a bank connection with a checking+ # and a brokerage account would otherwise make every deposit from that+ # checking account internal, and it would never be counted.+ def totals_account_ids+ @totals_account_ids ||= (investment_account_ids + settlement_account_ids).uniq+ end++ def settlement_account_ids+ @settlement_account_ids ||= if investment_account_ids.empty?+ []+ else+ report_accounts.where(id: TradeRepublicAccount.settlement_account_ids_for(investment_account_ids)).pluck(:id)+ end+ end+def totals_query(account_ids:, date_range:)if account_ids.empty?return Totals.new(family, account_ids: account_ids, date_range: date_range).callend- account_ids_hash = Digest::MD5.hexdigest(account_ids.sort.join(","))+ # Which of those accounts settle trades changes what Totals counts+ # (see Totals#recorded_flow_sql), so it is part of the key too.+ account_ids_hash = Digest::MD5.hexdigest("#{account_ids.sort.join(",")}|#{settlement_account_ids.sort.join(",")}")Rails.cache.fetch([- "investment_statement", "totals_query/v2", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, family.currency,+ "investment_statement", "totals_query/v3", ExchangeRate::CONVERSION_CACHE_VERSION, family.id, user&.id, family.currency,account_ids_hash, date_range.begin, date_range.end, family.entries_cache_version,# A rate stored later can complete totals that left an amount out.- ExchangeRate.updated_at_version- ]) { Totals.new(family, account_ids: account_ids, date_range: date_range).call }+ ExchangeRate.updated_at_version,+ transfers_version(account_ids)+ ]) { Totals.new(family, account_ids: account_ids, settlement_account_ids: settlement_account_ids, date_range: date_range).call }+ end++ # Contributions and withdrawals depend on which transactions a confirmed+ # Transfer links (Portfolio::FlowClassifier), and linking, confirming or+ # removing a transfer between two existing transactions need not write+ # to either entry, so entries_cache_version alone would miss it. The+ # count catches a removal; the timestamp catches a confirmation.+ def transfers_version(account_ids)+ leg_ids = Entry.where(account_id: account_ids, entryable_type: "Transaction").select(:entryable_id)+ count, max_at = Transfer+ .where(inflow_transaction_id: leg_ids)+ .or(Transfer.where(outflow_transaction_id: leg_ids))+ .pick(Arel.sql("count(*)"), Arel.sql("max(transfers.updated_at)"))+ "#{count}-#{max_at&.to_f}"enddef monetizable_currencydiff --git a/app/models/investment_statement/totals.rb b/app/models/investment_statement/totals.rbindex c6c62f128c..6c63a197de 100644--- a/app/models/investment_statement/totals.rb+++ b/app/models/investment_statement/totals.rb@@ -1,7 +1,14 @@class InvestmentStatement::Totals- def initialize(family, account_ids:, date_range:)+ # Transaction kinds a liability payment carries (Transfer.kind_for_account).+ LIABILITY_PAYMENT_KINDS = %w[cc_payment loan_payment].freeze++ # settlement_account_ids are the accounts among account_ids that a broker+ # settles trades on but that the user may also run as a current account+ # (InvestmentStatement#totals_account_ids); see #recorded_flow_sql.+ def initialize(family, account_ids:, date_range:, settlement_account_ids: [])@family = family@account_ids = account_ids+ @settlement_account_ids = Array(settlement_account_ids) & Array(account_ids)@date_range = date_rangeend@@ -13,6 +20,8 @@ class InvestmentStatement::Totals{contributions: result["contributions"]&.to_d || 0,withdrawals: result["withdrawals"]&.to_d || 0,+ buys: result["buys"]&.to_d || 0,+ sells: result["sells"]&.to_d || 0,dividends: result["dividends"]&.to_d || 0,interest: result["interest"]&.to_d || 0,trades_count: result["trades_count"]&.to_i || 0@@ -24,22 +33,46 @@ class InvestmentStatement::Totals{contributions: 0,withdrawals: 0,+ buys: 0,+ sells: 0,dividends: 0,interest: 0,trades_count: 0}end+ # The bound values are sanitized on their own and the classifier's+ # fragments spliced in afterwards: #sql_case is already sanitized, and+ # running it through sanitize_sql_array again would read any `:word` in+ # a label literal as a bind (see Portfolio::FlowClassifier#scope_ids_sql).def query_sql- ActiveRecord::Base.sanitize_sql_array([- aggregation_sql,- sql_params- ])+ aggregation_sql+ .sub("__FLOW_JOINS__") { flow_classifier.sql_joins }+ .gsub("__FLOW_CLASS__") { "(#{flow_classifier.sql_case})" }+ .gsub("__RECORDED_FLOW__") { recorded_flow_sql }end- # Aggregate trades by direction (buy vs sell)- # Buys (qty > 0) = contributions (cash going out to buy securities)- # Sells (qty < 0) = withdrawals (cash coming in from selling securities)+ # Contributions and withdrawals are money that entered or left the+ # accounts in scope: deposits, withdrawals, and transfers or journalled+ # positions whose other leg is outside the scope. Portfolio::FlowClassifier+ # decides that, with the same account ids the card reads as its scope, so+ # a transfer between two of those accounts is internal and counts on+ # neither side. A buy or a sale is internal to the account: it turns cash+ # into a security or back, so it is not money added or taken out.+ #+ # The classifier picks the direction from the sign (a Transaction) or the+ # quantity (a Trade), so ABS of the amount in its class is the size of+ # the flow.+ #+ # The card counts a flow only when the row says it is one (see+ # #recorded_flow_sql), not by the sign the classifier falls back to for+ # any other cash row. Only those rows, income and trades are read, and+ # the lateral `flow` subquery classifies each of them once (OFFSET 0+ # keeps the planner from inlining the CASE into both sums).+ #+ # Buys (qty > 0) and sells (qty < 0) are still summed, as before, under+ # their own names: the cash committed to buying securities and the cash+ # a sale brought back.## Investment income (dividends, interest) is aggregated by activity label# rather than by direction. Since #1311 these are recorded as Trades with@@ -48,45 +81,119 @@ class InvestmentStatement::Totals# Several providers store the same income as a Transaction carrying the# same label instead (Trading212, IBKR, Questrade, SnapTrade, Indexa# Capital, Kraken's fiat staking and earn rows), so income reads the label- # from whichever of the two the entry is. Only those labelled- # Transactions are joined in, and pending ones are left out until they- # post. A Transaction has no trades row, so it never reaches the- # direction branches or trades_count.+ # from whichever of the two the entry is. Pending transactions are left+ # out until they post, for income and flows alike. A Transaction has no+ # trades row, so it never reaches the buy and sell branches or+ # trades_count.## Income is summed signed and then negated, as Portfolio::FlowClassifier# requires: a negative amount is money in, so a margin-interest charge or# a dividend reversal carrying an income label reduces the total instead# of adding to it.#- # The direction branches additionally exclude income labels rather than+ # The buy and sell branches additionally exclude income labels rather than# relying on qty: 0 to keep the buckets disjoint. Without this guard such# a row would be counted twice: once by direction and once as income.## A row in a currency with no rate at all is left out, not counted at 1,# as in InvestmentStatement; ExchangeRate.rate_sql gives the- # nearest stored rate otherwise.+ # nearest stored rate otherwise. The lateral `fx` subquery looks the rate+ # up once per row: written into each of the six sums, its two correlated+ # lookups were priced six times over, and the estimate crossed+ # jit_above_cost.## account_ids is already scoped to the family's visible (draft/active)- # investment accounts, so the query trusts that input and skips a join back- # to accounts for family/status filtering.+ # investment accounts and the cash accounts that settle their trades+ # (InvestmentStatement#totals_account_ids), so the query trusts that input+ # and skips a join back to accounts for family/status filtering.# COALESCE keeps an unlabeled trade (NULL) out of the set.def income_label_sql"COALESCE(trades.investment_activity_label, '') IN ('Dividend', 'Interest')"end- def aggregation_sql- rate = ExchangeRate.rate_sql(from: "entries.currency", to: ":target_currency", on: "entries.date")+ def flow_classifier+ @flow_classifier ||= Portfolio::FlowClassifier.new(scope_account_ids: @account_ids)+ end++ # The rows that record a movement of money in or out: a Trade or a+ # Transaction labelled Contribution, Withdrawal or Transfer (the+ # classifier calls any other Trade internal), a Transaction of a transfer+ # kind, or a leg of a confirmed Transfer whose other leg is outside the+ # scope (flow_transfers and flow_counterpart_entries, joined by the+ # classifier). Transfer::Creator and Transfer#confirm! give both legs a+ # transfer kind; a link written another way (an import, an older row) can+ # leave them standard. Such a leg is still money in or out when its other+ # leg is outside the scope, and the classifier gives it its direction. With+ # the other leg in the scope it is not counted: the classifier resolves a+ # link only for a transfer kind or label and reads any other row by its+ # sign, so the move would count on both sides.+ #+ # Any other cash row is left out, even though the classifier gives it a+ # direction by its sign. Providers write investment activity that is not+ # a flow that way: SimpleFIN records buys and sales as unlabelled+ # Transactions, and Plaid labels its "cash" type, which covers dividends+ # and interest, "Other". Counting those by sign would bring back the+ # trades-as-contributions reading this card replaced. A manual deposit+ # counts once it is labelled Contribution.+ #+ # On a settlement account (Trade Republic's Cash account, which has an+ # IBAN and a card) a credit card or loan payment is not counted either,+ # unless it carries one of the labels above. That account is often the+ # user's current account: their card spending there is already not a+ # flow, and their salary is not one, so a card bill or a loan instalment+ # paid from it is spending too, not money taken out of the broker.+ # Counted, every month's bill would lower net contributions while the+ # income that paid it never raised them. A transfer to the user's other+ # accounts (funds_movement) still counts as a withdrawal.+ def recorded_flow_sql+ labels = (Portfolio::FlowClassifier::EXTERNAL_LABELS + [ Portfolio::FlowClassifier::TRANSFER_LABEL ])++ <<~SQL.squish+ (+ COALESCE(trades.investment_activity_label, transactions.investment_activity_label) IN (#{quote_list(labels)})+ OR (+ (+ transactions.kind IN (#{quote_list(Transaction::TRANSFER_KINDS)})+ OR (flow_transfers.inflow_transaction_id IS NOT NULL AND flow_counterpart_entries.account_id IS NULL)+ )+ #{settlement_payment_exclusion_sql}+ )+ )+ SQL+ end++ def settlement_payment_exclusion_sql+ return "" if @settlement_account_ids.empty?++ ids = ActiveRecord::Base.sanitize_sql_array([ "ARRAY[:ids]::uuid[]", { ids: @settlement_account_ids } ])+ "AND NOT (entries.account_id = ANY(#{ids}) AND transactions.kind IN (#{quote_list(LIABILITY_PAYMENT_KINDS)}))"+ end- <<~SQL+ def quote_list(values)+ values.map { |value| ActiveRecord::Base.connection.quote(value) }.join(", ")+ end++ def aggregation_sql+ ActiveRecord::Base.sanitize_sql_array([ <<~SQL, sql_params ])SELECT- COALESCE(SUM(CASE WHEN trades.qty > 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as contributions,- COALESCE(SUM(CASE WHEN trades.qty < 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * #{rate}) ELSE 0 END), 0) as withdrawals,- COALESCE(-SUM(CASE WHEN #{label_sql} = 'Dividend' THEN entries.amount * #{rate} ELSE 0 END), 0) as dividends,- COALESCE(-SUM(CASE WHEN #{label_sql} = 'Interest' THEN entries.amount * #{rate} ELSE 0 END), 0) as interest,+ COALESCE(SUM(CASE WHEN flow.flow_class = 'external_inflow' THEN ABS(entries.amount * fx.rate) ELSE 0 END), 0) as contributions,+ COALESCE(SUM(CASE WHEN flow.flow_class = 'external_outflow' THEN ABS(entries.amount * fx.rate) ELSE 0 END), 0) as withdrawals,+ COALESCE(SUM(CASE WHEN trades.qty > 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * fx.rate) ELSE 0 END), 0) as buys,+ COALESCE(SUM(CASE WHEN trades.qty < 0 AND NOT #{income_label_sql} THEN ABS(entries.amount * fx.rate) ELSE 0 END), 0) as sells,+ COALESCE(-SUM(CASE WHEN #{label_sql} = 'Dividend' THEN entries.amount * fx.rate ELSE 0 END), 0) as dividends,+ COALESCE(-SUM(CASE WHEN #{label_sql} = 'Interest' THEN entries.amount * fx.rate ELSE 0 END), 0) as interest,COUNT(trades.id) as trades_countFROM entries- LEFT JOIN trades ON trades.id = entries.entryable_id AND entries.entryable_type = 'Trade'- LEFT JOIN transactions ON transactions.id = entries.entryable_id AND entries.entryable_type = 'Transaction'+ __FLOW_JOINS__+ CROSS JOIN LATERAL (+ SELECT #{ExchangeRate.rate_sql(from: "entries.currency", to: ":target_currency", on: "entries.date")} AS rate+ OFFSET 0+ ) fx+ LEFT JOIN LATERAL (+ SELECT __FLOW_CLASS__ AS flow_class+ WHERE __RECORDED_FLOW__+ OFFSET 0+ ) flow ON trueWHERE entries.account_id IN (:account_ids)AND entries.date BETWEEN :start_date AND :end_dateAND entries.excluded = false@@ -94,7 +201,7 @@ class InvestmentStatement::Totalsentries.entryable_type = 'Trade'OR (entries.entryable_type = 'Transaction'- AND #{income_transaction_sql}+ AND (transactions.investment_activity_label IN ('Dividend', 'Interest') OR __RECORDED_FLOW__)#{Transaction.pending_providers_sql("transactions")}))@@ -105,10 +212,6 @@ class InvestmentStatement::Totals"COALESCE(trades.investment_activity_label, transactions.investment_activity_label)"end- def income_transaction_sql- "transactions.investment_activity_label IN ('Dividend', 'Interest')"- end-def sql_params{target_currency: @family.currency,diff --git a/app/models/portfolio/flow_classifier.rb b/app/models/portfolio/flow_classifier.rbindex 819f0795c9..8a4c399022 100644--- a/app/models/portfolio/flow_classifier.rb+++ b/app/models/portfolio/flow_classifier.rb@@ -138,25 +138,85 @@ class Portfolio::FlowClassifier# The joins #sql_case relies on. The caller's query must select FROM# `entries` and place this fragment before its WHERE clause.#- # One row per entry, which an aggregate embedding this relies on: the- # transfers join cannot fan out because Transfer validates- # inflow_transaction_id and outflow_transaction_id as unique and requires- # opposite amounts, so a transaction is a leg of at most one transfer. A- # writer that bypasses validations (insert_all) could break that, and a SUM- # over this join would then count the entry twice.+ # One row per entry, which an aggregate embedding this relies on.+ # Transfer#transfer_has_opposite_amounts makes a leg a transfer's inflow+ # while its amount is negative and its outflow while it is positive, and+ # Transfer validates each side as unique, so a transaction normally has one+ # transfer. Those checks run only when a transfer is saved. A leg's amount+ # can change sign afterwards (a provider re-sync writes it again), and such+ # a leg can then become another transfer's leg on the other side. One join+ # on either side would return both transfers, and a SUM would count the+ # entry twice.+ #+ # So the transfers are joined twice, once per side, and the sign chooses+ # between them without excluding either: flow_sign_transfers is the+ # transfer on the side the amount allows (the outflow while it is+ # positive, else the inflow), flow_other_transfers the one on the other+ # side, joined only when there is no flow_sign_transfers row, and+ # flow_transfers takes whichever was found. A leg whose sign+ # flipped on its own transfer, with no second transfer, keeps that link, as+ # do both legs of a pair whose amounts were negated together.+ # #confirmed_transfer_for picks the same transfer in Ruby.+ #+ # Two transfers on the preferred side, or on the other side when the+ # preferred one is missing, are still both joined. The uniqueness+ # validations rule that out only for writers that run them one at a time:+ # two racing writers, or rows written around the validations (insert_all),+ # can create it, since the table has a unique index on the pair only.+ #+ # Each join keeps the OR probe on both transfer columns, which uses the+ # index on each, and checks the side on top of it. Choosing the transfer+ # in a LATERAL ... ORDER BY ... LIMIT 1 instead gave one row in every case+ # but took the query out of its parallel plan and priced it past the JIT+ # inlining threshold; over five years it ran three to four times slower.+ #+ # The counterpart entry is only looked up among the scope's accounts, which+ # is all #transfer_resolution_sql asks of it: entries has no index on+ # entryable_id, and without the account bound the join reads every+ # Transaction entry in the database. InvestmentStatement::Totals#recorded_flow_sql+ # relies on this bound as well: there, a NULL counterpart means the other+ # leg is outside the scope.+ #+ # The security-transfer legs are joined grouped, one row per date,+ # security and quantity, so that join cannot fan out either (see+ # #security_transfer_legs_sql).+ #+ # Only a confirmed Transfer links two legs. An auto-match starts out+ # pending and, as Transfer#confirm! promises, an unconfirmed suggestion+ # never moves a report, so until the user confirms it each leg is+ # classified as if it were unlinked.def sql_joins<<~SQL.squishLEFT JOIN trades ON entries.entryable_type = 'Trade' AND trades.id = entries.entryable_idLEFT JOIN transactions ON entries.entryable_type = 'Transaction' AND transactions.id = entries.entryable_id- LEFT JOIN transfers flow_transfers+ LEFT JOIN transfers flow_sign_transfers+ ON entries.entryable_type = 'Transaction'+ AND flow_sign_transfers.status = 'confirmed'+ AND (flow_sign_transfers.inflow_transaction_id = transactions.id OR flow_sign_transfers.outflow_transaction_id = transactions.id)+ AND CASE WHEN entries.amount > 0 THEN flow_sign_transfers.outflow_transaction_id ELSE flow_sign_transfers.inflow_transaction_id END = transactions.id+ LEFT JOIN transfers flow_other_transfersON entries.entryable_type = 'Transaction'- AND (flow_transfers.inflow_transaction_id = transactions.id OR flow_transfers.outflow_transaction_id = transactions.id)+ AND flow_sign_transfers.id IS NULL+ AND flow_other_transfers.status = 'confirmed'+ AND (flow_other_transfers.inflow_transaction_id = transactions.id OR flow_other_transfers.outflow_transaction_id = transactions.id)+ AND CASE WHEN entries.amount > 0 THEN flow_other_transfers.inflow_transaction_id ELSE flow_other_transfers.outflow_transaction_id END = transactions.id+ CROSS JOIN LATERAL (+ SELECT+ COALESCE(flow_sign_transfers.inflow_transaction_id, flow_other_transfers.inflow_transaction_id) AS inflow_transaction_id,+ COALESCE(flow_sign_transfers.outflow_transaction_id, flow_other_transfers.outflow_transaction_id) AS outflow_transaction_id+ ) flow_transfersLEFT JOIN entries flow_counterpart_entriesON flow_counterpart_entries.entryable_type = 'Transaction'+ AND flow_counterpart_entries.account_id = ANY(#{scope_ids_sql})AND flow_counterpart_entries.entryable_id = CASEWHEN flow_transfers.inflow_transaction_id = transactions.id THEN flow_transfers.outflow_transaction_idELSE flow_transfers.inflow_transaction_idEND+ LEFT JOIN (#{security_transfer_legs_sql}) flow_security_transfers+ ON entries.entryable_type = 'Trade'+ AND flow_security_transfers.date = entries.date+ AND flow_security_transfers.security_id = trades.security_id+ AND flow_security_transfers.qty = -trades.qtySQLend@@ -229,7 +289,7 @@ class Portfolio::FlowClassifierenddef transfer_resolution(entry, transaction)- counterpart_account_id = transfer_counterpart_account_id(transaction)+ counterpart_account_id = transfer_counterpart_account_id(entry, transaction)if counterpart_account_id && scope_account_ids.include?(counterpart_account_id):internalelse@@ -237,17 +297,27 @@ class Portfolio::FlowClassifierendend- # The account on the other leg of a linked Transfer, by id only; the+ # The account on the other leg of a confirmed Transfer, by id only; the# counterpart account itself is never loaded, so a scope check cannot- # leak an account the user is not allowed to see.- def transfer_counterpart_account_id(transaction)- transfer = transaction.transfer_as_inflow || transaction.transfer_as_outflow+ # leak an account the user is not allowed to see. A pending auto-match+ # links nothing yet.+ def transfer_counterpart_account_id(entry, transaction)+ transfer = confirmed_transfer_for(entry, transaction)return nil unless transfercounterpart_id = transfer.inflow_transaction_id == transaction.id ? transfer.outflow_transaction_id : transfer.inflow_transaction_idEntry.where(entryable_type: "Transaction", entryable_id: counterpart_id).pick(:account_id)&.to_send+ # The transfer #sql_joins picks for this transaction: the confirmed one+ # on the side its sign allows (the outflow while its amount is positive,+ # else the inflow), else the confirmed one on the other side.+ def confirmed_transfer_for(entry, transaction)+ sides = %i[inflow_transaction_id outflow_transaction_id]+ sides.reverse! if entry.amount.positive?+ sides.lazy.map { |side| Transfer.confirmed.find_by(side => transaction.id) }.find(&:itself)+ end+# A security moved between accounts has no Transfer row; its other leg is# the opposite-quantity Transfer trade on the same security and date in# another account. entries.excluded is nullable, and a NULL leg is live@@ -281,22 +351,45 @@ class Portfolio::FlowClassifier"CASE WHEN flow_counterpart_entries.account_id = ANY(#{scope_ids_sql}) THEN 'internal' ELSE #{direction_sql} END"end+ # True when #security_transfer_legs_sql found a Transfer trade on the+ # same date and security, with the opposite quantity, in a scope account+ # other than this entry's. Each group carries the lowest and highest+ # account id among its legs, so a leg in another account exists exactly+ # when either differs from this entry's. With no group, both are NULL and+ # the CASE takes the direction.def security_transfer_counterpart_in_scope_sql<<~SQL.squish- EXISTS (- SELECT 1- FROM entries counterpart_entries- JOIN trades counterpart_trades- ON counterpart_trades.id = counterpart_entries.entryable_id- AND counterpart_entries.entryable_type = 'Trade'- WHERE counterpart_entries.account_id = ANY(#{scope_ids_sql})- AND counterpart_entries.account_id <> entries.account_id- AND counterpart_entries.date = entries.date- AND counterpart_entries.excluded IS NOT TRUE- AND counterpart_trades.security_id = trades.security_id- AND counterpart_trades.qty = -trades.qty- AND counterpart_trades.investment_activity_label = '#{TRANSFER_LABEL}'- )+ (flow_security_transfers.min_account_id <> entries.account_id+ OR flow_security_transfers.max_account_id <> entries.account_id)+ SQL+ end++ # Every live Transfer trade in the scope's accounts, grouped by date,+ # security and quantity. A correlated EXISTS asked the same question per+ # row, and the planner priced each probe against the whole scope, so its+ # estimate grew with the square of the entries and a few thousand crossed+ # jit_above_cost; JIT compilation then took longer than the query.+ # Grouped and hash-joined, the cost stays proportional to the rows read.+ #+ # entries.excluded is nullable, and a NULL leg is live here as it is to+ # #classify, hence IS NOT TRUE rather than = false. uuid has no MIN or+ # MAX, so the ids are compared as text.+ def security_transfer_legs_sql+ <<~SQL.squish+ SELECT+ counterpart_entries.date,+ counterpart_trades.security_id,+ counterpart_trades.qty,+ MIN(counterpart_entries.account_id::text)::uuid AS min_account_id,+ MAX(counterpart_entries.account_id::text)::uuid AS max_account_id+ FROM entries counterpart_entries+ JOIN trades counterpart_trades+ ON counterpart_trades.id = counterpart_entries.entryable_id+ AND counterpart_entries.entryable_type = 'Trade'+ WHERE counterpart_entries.account_id = ANY(#{scope_ids_sql})+ AND counterpart_entries.excluded IS NOT TRUE+ AND counterpart_trades.investment_activity_label = '#{TRANSFER_LABEL}'+ GROUP BY counterpart_entries.date, counterpart_trades.security_id, counterpart_trades.qtySQLenddiff --git a/app/models/trade_republic_account.rb b/app/models/trade_republic_account.rbindex 3f36536307..ae415158b6 100644--- a/app/models/trade_republic_account.rb+++ b/app/models/trade_republic_account.rb@@ -25,6 +25,22 @@ class TradeRepublicAccount < ApplicationRecordvalidates :currency, presence: truevalidates :trade_republic_account_id, uniqueness: { scope: :trade_republic_item_id, allow_nil: true }+ # The Sure accounts that settle the trades of the accounts given: the Cash+ # account of each connection whose Portfolio or Crypto account is among+ # account_ids. ActivitiesProcessor#link_settlement_counterpart! books every+ # trade's cash on that account and links it to the securities account as a+ # confirmed transfer, so money reaches a split Portfolio or Crypto account+ # only through it. Returns a relation of account ids, for use as a subquery.+ def self.settlement_account_ids_for(account_ids)+ connection_ids = joins(:account_provider)+ .where(account_providers: { account_id: account_ids }, kind: %w[portfolio crypto])+ .select(:trade_republic_item_id)++ AccountProvider+ .where(provider_type: name, provider_id: where(kind: "cash", trade_republic_item_id: connection_ids).select(:id))+ .select(:account_id)+ end+def self.crypto_isin?(isin)isin.to_s.strip.upcase.start_with?(CRYPTO_ISIN_PREFIX)enddiff --git a/test/models/demo/generator_test.rb b/test/models/demo/generator_test.rbindex 05d7583819..3de139c679 100644--- a/test/models/demo/generator_test.rb+++ b/test/models/demo/generator_test.rb@@ -161,6 +161,25 @@ class Demo::GeneratorTest < ActiveSupport::TestCaseendend+ # The demo's transfers are recorded ones, not auto-match suggestions. The+ # investment card counts only a confirmed transfer's leg as a flow, so+ # left pending, the quarterly HSA contributions showed as none.+ test "demo transfers are confirmed and count as the HSA's contributions" do+ @family.update!(currency: "USD")+ generator = Demo::Generator.new(seed: 42)+ generator.send(:create_realistic_categories!, @family)+ generator.send(:create_realistic_accounts!, @family)+ generator.send(:generate_additional_savings_transfers!)++ hsa = @family.accounts.find_by!(name: "Fidelity HSA Investment")+ deposits = hsa.entries.where(name: "HSA Contribution")+ assert deposits.any?, "the demo must record HSA contributions, or this asserts nothing"+ assert_equal [ "confirmed" ], Transfer.joins(inflow_transaction: :entry).where(entries: { account_id: hsa.id }).distinct.pluck(:status)++ totals = InvestmentStatement::Totals.new(@family, account_ids: [ hsa.id ], date_range: deposits.minimum(:date)..Date.current).call+ assert_equal(-deposits.sum(:amount), totals[:contributions])+ end+# The demo family's loans were bare Loan.new records -- no rate, no term, and# the mortgage's principal a transaction rather than an opening valuation --# so none of them had a schedule to show. The mortgage is adjustable withdiff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rbindex 9b97eb06f4..a1e919be94 100644--- a/test/models/investment_statement_test.rb+++ b/test/models/investment_statement_test.rb@@ -542,7 +542,7 @@ class InvestmentStatementTest < ActiveSupport::TestCaseassert_equal 0, totals.trades_countend- # A buy in a currency with no rate is not a $1-per-unit contribution (#3640).+ # A buy in a currency with no rate is not a $1-per-unit buy (#3640).test "totals leave out a trade in a currency with no rate at all" doperiod = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)usd_account = create_investment_account(balance: 500)@@ -553,7 +553,7 @@ class InvestmentStatementTest < ActiveSupport::TestCasetotals = @statement.totals(period: period)- assert_equal Money.new(120, "USD"), totals.contributions+ assert_equal Money.new(120, "USD"), totals.buysassert_equal 2, totals.trades_countend@@ -575,8 +575,10 @@ class InvestmentStatementTest < ActiveSupport::TestCasetotals = nilqueries = capture_sql_queries { totals = statement.totals(period: period) }- assert_equal Money.new(120, "USD"), totals.contributions- assert_equal Money.new(40, "USD"), totals.withdrawals+ assert_equal Money.new(120, "USD"), totals.buys+ assert_equal Money.new(40, "USD"), totals.sells+ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawalsassert_equal 2, totals.trades_countaggregate_queries = queries.grep(/SUM\(CASE WHEN trades\.qty > 0/)@@ -618,8 +620,9 @@ class InvestmentStatementTest < ActiveSupport::TestCasetotals = @statement.totals(period: period)# qty: 0 keeps income out of both direction branches- assert_equal Money.new(120, "USD"), totals.contributions- assert_equal Money.new(0, "USD"), totals.withdrawals+ assert_equal Money.new(120, "USD"), totals.buys+ assert_equal Money.new(0, "USD"), totals.sells+ assert_equal Money.new(0, "USD"), totals.contributionsassert_equal Money.new(50, "USD"), totals.dividendsend@@ -657,7 +660,7 @@ class InvestmentStatementTest < ActiveSupport::TestCasetest "labeled non-income trades still count by direction" do# Only Dividend/Interest are excluded from the direction buckets; Buy, Sell- # and Reinvestment keep their existing contribution/withdrawal treatment.+ # and Reinvestment keep their existing buy/sell treatment.period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)account = create_investment_account(balance: 500)@@ -668,9 +671,10 @@ class InvestmentStatementTest < ActiveSupport::TestCasetotals = @statement.totals(period: period)- assert_equal Money.new(150, "USD"), totals.contributions- # Reinvestment is deliberately not folded into dividend income; doing so- # would require removing it from contributions too.+ assert_equal Money.new(150, "USD"), totals.buys+ # Neither is money added to the account.+ assert_equal Money.new(0, "USD"), totals.contributions+ # Reinvestment is deliberately not folded into dividend income.assert_equal Money.new(0, "USD"), totals.dividendsend@@ -792,12 +796,11 @@ class InvestmentStatementTest < ActiveSupport::TestCaseassert_equal 1, totals.trades_countend- test "contributions and withdrawals count trades only, not external cash transactions" do- # None of the non-trade entries below is income, so reading labelled- # transactions for income must not let them move the direction buckets.- # Totals#contributions is the cash committed to buying securities:- # counting the 800 deposit and the 1 000 buy it funded would count that- # money twice.+ test "contributions and withdrawals count external flows, and buys and sells count trades" do+ # None of the non-trade entries below is income, so reading transactions+ # for flows must not move the income buckets, and the trades must not+ # move the flow buckets: counting the 800 deposit and the 1 000 buy it+ # funded would count that money twice.period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)account = create_investment_account(balance: 500)checking = @family.accounts.create!(name: "Checking", balance: 5000, currency: "USD", accountable: Depository.new)@@ -808,14 +811,475 @@ class InvestmentStatementTest < ActiveSupport::TestCasecreate_labelled_transaction(account: account, label: "Withdrawal", amount: 50, date: period.start_date)create_labelled_transaction(account: account, label: nil, kind: "investment_contribution", amount: -200, date: period.start_date)create_linked_transfer(family: @family, from: checking, to: account, amount: 800, date: period.start_date)+ # Pending and excluded flows wait, as pending income does+ create_labelled_transaction(account: account, label: "Contribution", amount: -70, date: period.start_date, extra: { "plaid" => { "pending" => true } })+ create_labelled_transaction(account: account, label: "Contribution", amount: -90, date: period.start_date, excluded: true)+ # Outside the period+ create_labelled_transaction(account: account, label: "Contribution", amount: -999, date: period.start_date - 1.day)++ totals = @statement.totals(period: period)++ assert_equal Money.new(1300, "USD"), totals.contributions+ assert_equal Money.new(50, "USD"), totals.withdrawals+ assert_equal Money.new(1000, "USD"), totals.buys, "only the buy is a buy"+ assert_equal Money.new(200, "USD"), totals.sells, "only the sale is a sell"+ assert_equal Money.new(0, "USD"), totals.total_income+ assert_equal 2, totals.trades_count+ end++ test "contributions convert foreign-currency flows into family currency" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 500, currency: "EUR")+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: period.start_date, rate: 1.1)++ create_labelled_transaction(account: account, label: "Contribution", amount: -100, date: period.start_date)++ assert_equal Money.new(110, "USD"), @statement.totals(period: period).contributions+ end++ # A deposit follows the same rule as a trade (#3640): no rate at all leaves+ # it out rather than counting it at 1.+ test "a contribution in a currency with no rate at all is left out, not counted at 1" do+ ExchangeRate.stubs(:provider).returns(nil)+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ usd_account = create_investment_account(balance: 500)+ krw_account = create_investment_account(balance: 500_000, currency: "KRW")++ create_labelled_transaction(account: usd_account, label: "Contribution", amount: -100, date: period.start_date)+ create_labelled_transaction(account: krw_account, label: "Contribution", amount: -500_000, date: period.start_date)+ create_labelled_transaction(account: krw_account, label: "Withdrawal", amount: 200_000, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(100, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals+ end++ test "a contribution with no rate on its day uses the nearest stored rate" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 500, currency: "EUR")+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: period.start_date - 60.days, rate: 1.2)++ create_labelled_transaction(account: account, label: "Contribution", amount: -100, date: period.start_date)+ create_labelled_transaction(account: account, label: "Withdrawal", amount: 50, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(120, "USD"), totals.contributions+ assert_equal Money.new(60, "USD"), totals.withdrawals+ end++ test "a deposit and the buy it funds count once, as a contribution" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000)++ # The deposit is the money added; the buy only turns part of it into shares.+ create_labelled_transaction(account: account, label: "Contribution", amount: -1000, date: period.start_date)+ create_portfolio_trade(account: account, qty: 8, price: 100, date: period.start_date)totals = @statement.totals(period: period)- assert_equal Money.new(1000, "USD"), totals.contributions, "only the buy is a contribution"- assert_equal Money.new(200, "USD"), totals.withdrawals, "only the sale is a withdrawal"+ assert_equal Money.new(1000, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals+ assert_equal Money.new(800, "USD"), totals.buys+ end++ test "a buy paid for with cash already in the account is not a contribution" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000, cash_balance: 1000)++ create_portfolio_trade(account: account, qty: 5, price: 100, date: period.start_date)+ # A rebalance: selling one position to buy another moves no money in or out.+ create_portfolio_trade(account: account, qty: -2, price: 100, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals+ assert_equal Money.new(500, "USD"), totals.buys+ assert_equal Money.new(200, "USD"), totals.sellsassert_equal 2, totals.trades_countend+ test "a withdrawal counts, whether labelled or a transfer to an account outside the card" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000)+ checking = @family.accounts.create!(name: "Checking", balance: 5000, currency: "USD", accountable: Depository.new)++ create_labelled_transaction(account: account, label: "Withdrawal", amount: 150, date: period.start_date)+ create_linked_transfer(family: @family, from: account, to: checking, amount: 250, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(400, "USD"), totals.withdrawals+ assert_equal Money.new(0, "USD"), totals.contributions+ end++ test "a transfer between two investment accounts on the card is neither a contribution nor a withdrawal" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ from = create_investment_account(balance: 1000)+ to = create_investment_account(balance: 1000)++ create_linked_transfer(family: @family, from: from, to: to, amount: 600, date: period.start_date)+ # The same move booked by the broker on both sides, with each leg labelled+ # as if the money came from outside, then linked and confirmed: the link+ # wins.+ out_leg = create_labelled_transaction(account: from, label: "Withdrawal", amount: 40, date: period.start_date)+ in_leg = create_labelled_transaction(account: to, label: "Contribution", amount: -40, date: period.start_date)+ Transfer.create!(outflow_transaction: out_leg.entryable, inflow_transaction: in_leg.entryable).confirm!++ totals = @statement.totals(period: period)++ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals+ end++ # Auto-matching creates pending transfers, and Transfer#confirm! promises an+ # unconfirmed suggestion never moves reports. Until it is confirmed, each+ # leg is what its label says.+ test "an unconfirmed transfer suggestion does not change contributions or withdrawals" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ from = create_investment_account(balance: 1000)+ to = create_investment_account(balance: 1000)++ out_leg = create_labelled_transaction(account: from, label: "Withdrawal", amount: 40, date: period.start_date)+ in_leg = create_labelled_transaction(account: to, label: "Contribution", amount: -40, date: period.start_date)+ transfer = Transfer.create!(outflow_transaction: out_leg.entryable, inflow_transaction: in_leg.entryable)+ assert transfer.pending?++ totals = @statement.totals(period: period)++ assert_equal Money.new(40, "USD"), totals.contributions+ assert_equal Money.new(40, "USD"), totals.withdrawals+ end++ # The totals depend on transfers, and linking or unlinking two existing+ # transactions does not always write to their entries.+ test "creating, confirming and removing a transfer each refresh the cached totals" do+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ from = create_investment_account(balance: 1000)+ to = create_investment_account(balance: 1000)+ out_leg = create_labelled_transaction(account: from, label: "Withdrawal", amount: 40, date: period.start_date)+ in_leg = create_labelled_transaction(account: to, label: "Contribution", amount: -40, date: period.start_date)+ contributions = -> { InvestmentStatement.new(@family.reload, user: nil).totals(period: period).contributions }++ assert_equal Money.new(40, "USD"), contributions.call++ transfer = Transfer.create!(outflow_transaction: out_leg.entryable, inflow_transaction: in_leg.entryable, status: "confirmed")+ assert_equal Money.new(0, "USD"), contributions.call, "after a confirmed link"++ transfer.destroy!+ assert_equal Money.new(40, "USD"), contributions.call, "after the link is removed"++ suggestion = Transfer.create!(outflow_transaction: out_leg.entryable, inflow_transaction: in_leg.entryable)+ assert_equal Money.new(40, "USD"), contributions.call, "a suggestion changes nothing"++ suggestion.confirm!+ assert_equal Money.new(0, "USD"), contributions.call, "after the suggestion is confirmed"+ end++ # PlaidAccount maps Plaid's investment type "cash", the type of its+ # dividend and interest rows, to the "Other" label.+ test "an Other cash row is neither a contribution nor a withdrawal" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000)++ create_labelled_transaction(account: account, label: "Other", amount: -25, date: period.start_date)+ create_labelled_transaction(account: account, label: "Other", amount: 10, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals+ end++ # SimpleFIN writes every investment-account activity, buys and sales+ # included, as an unlabelled standard Transaction.+ test "an unlabelled cash row is neither a contribution nor a withdrawal" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000)++ create_labelled_transaction(account: account, label: nil, amount: 500, date: period.start_date)+ create_labelled_transaction(account: account, label: nil, amount: -300, date: period.start_date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals+ end++ # A link written without Transfer::Creator or #confirm! (an import, an+ # older row) can leave both legs standard and unlabelled. Between two+ # accounts on the card such a pair counts on neither side; from a bank+ # account outside it, the investment leg is still a contribution.+ test "a confirmed transfer with unlabelled standard legs counts only when its other leg is off the card" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ from = create_investment_account(balance: 1000)+ to = create_investment_account(balance: 1000)+ checking = @family.accounts.create!(name: "Checking", balance: 5000, currency: "USD", accountable: Depository.new)++ link = lambda do |out_account, in_account, label, amount|+ out_leg = create_labelled_transaction(account: out_account, label: label, amount: amount, date: period.start_date)+ in_leg = create_labelled_transaction(account: in_account, label: label, amount: -amount, date: period.start_date)+ Transfer.create!(outflow_transaction: out_leg.entryable, inflow_transaction: in_leg.entryable, status: "confirmed")+ assert_equal "standard", in_leg.entryable.reload.kind, "precondition: the link did not change the leg's kind"+ end++ link.call(from, to, nil, 40)+ link.call(from, to, "Other", 41)++ totals = @statement.totals(period: period)++ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals++ link.call(checking, to, nil, 300)++ totals = InvestmentStatement.new(@family).totals(period: period)++ assert_equal Money.new(300, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals+ end++ # A security moved in from another account is internal to a scope holding+ # both legs. Two opposite legs in two other accounts still make one+ # counterpart: the lookup is grouped, so the moved-in leg is read once and+ # neither the buys nor the trade count grow.+ #+ # Withdrawals is not asserted: it reads 0 here although ten shares left the+ # scope net. The classifier asks whether an opposite leg exists, not how+ # many legs pair up, so the second source leg is internal too. That is a+ # known limit of the classifier, not the intended answer.+ test "a security transfer with two opposite legs in scope is read once" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ target = create_investment_account(balance: 1000)+ source_a = create_investment_account(balance: 1000)+ source_b = create_investment_account(balance: 1000)+ security = create_portfolio_security+ date = period.start_date++ create_portfolio_trade(account: target, security: security, qty: 10, price: 50, label: "Transfer", date: date)+ create_portfolio_trade(account: source_a, security: security, qty: -10, price: 50, label: "Transfer", date: date)+ create_portfolio_trade(account: source_b, security: security, qty: -10, price: 50, label: "Transfer", date: date)++ totals = @statement.totals(period: period)++ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(500, "USD"), totals.buys+ assert_equal Money.new(1000, "USD"), totals.sells+ assert_equal 3, totals.trades_count+ end++ # With its Cash account linked, Trade Republic books each trade's cash on+ # that account and links it to the Portfolio account as a confirmed+ # transfer. The Cash account is part of the broker, so these are trade+ # settlements, not money added or taken out.+ test "Trade Republic buys and sales settled on its Cash account are neither contributions nor withdrawals" do+ portfolio, cash = create_split_trade_republic_connection+ sync_trade_republic(portfolio, [+ trade_republic_order(id: "evt_buy", quantity: "2.0", signed_amount: -1024.92, date: "2026-07-15"),+ trade_republic_order(id: "evt_sell", quantity: "-1.0", signed_amount: 529.0, date: "2026-07-20")+ ])+ sync_trade_republic(cash, [])+ assert_equal 2, Transfer.confirmed.count, "precondition: both settlements are linked to the portfolio"++ totals = InvestmentStatement.new(@family.reload).totals(period: july_2026)++ assert_equal Money.new(0, "EUR"), totals.contributions+ assert_equal Money.new(0, "EUR"), totals.withdrawals+ assert_equal 2, totals.trades_count+ assert_equal Money.new(1024.92, "EUR"), totals.buys+ end++ # The money enters the broker once, when it reaches the Cash account from+ # the user's bank. The buy it then funds moves it within the broker. Income+ # Trade Republic books on the Cash account is the portfolio's income, and+ # spending from it is not read as a withdrawal, as on any other cash row.+ test "a bank deposit into Trade Republic Cash counts once, not again when it buys shares" do+ portfolio, cash = create_split_trade_republic_connection+ bank = @family.accounts.create!(name: "Bank", balance: 5000, currency: "EUR", accountable: Depository.new)+ bank_leg = create_labelled_transaction(account: bank, label: nil, amount: 2000, date: Date.new(2026, 7, 10))++ sync_trade_republic(portfolio, [ trade_republic_order(id: "evt_buy", quantity: "2.0", signed_amount: -800, date: "2026-07-15") ])+ sync_trade_republic(cash, [+ { id: "evt_deposit", timestamp: "2026-07-10T10:00:00Z", category: "PAYMENT_RECEIVED", detail: { amount: "2000.00", currency: "EUR" } },+ { id: "evt_dividend", timestamp: "2026-07-18T10:00:00Z", category: "DIVIDEND", detail: { amount: "12.50", currency: "EUR" } },+ { id: "evt_card", timestamp: "2026-07-19T10:00:00Z", category: "POC_CREATED", eventType: "CARD_TRANSACTION", title: "Bakery", detail: { amount: "4.20", currency: "EUR" } }+ ])+ cash_account = cash.current_account+ deposit = cash_account.entries.find_by!(external_id: "trade_republic_event_evt_deposit")+ # As auto-matching suggests it and the user then confirms it.+ Transfer.create!(inflow_transaction: deposit.entryable, outflow_transaction: bank_leg.entryable).confirm!++ totals = InvestmentStatement.new(@family.reload).totals(period: july_2026)++ assert_equal Money.new(2000, "EUR"), totals.contributions+ assert_equal Money.new(0, "EUR"), totals.withdrawals+ assert_equal Money.new(800, "EUR"), totals.buys+ assert_equal Money.new(12.5, "EUR"), totals.dividends+ end++ # Only a broker that settles trades on a cash account of its own is read+ # with it. A bank connection holding both a checking and a brokerage+ # account keeps them apart, so a deposit from that checking account is+ # still a contribution.+ test "a checking account on the same connection as a brokerage account stays off the card" do+ item = PlaidItem.create!(family: @family, plaid_id: "item_#{SecureRandom.hex(4)}", access_token: "token", name: "Bank")+ brokerage = create_investment_account(balance: 1000)+ checking = @family.accounts.create!(name: "Checking", balance: 5000, currency: "USD", accountable: Depository.new)+ { brokerage => "investment", checking => "depository" }.each do |account, type|+ plaid_account = item.plaid_accounts.create!(name: account.name, plaid_id: SecureRandom.hex(4), plaid_type: type, currency: "USD", current_balance: account.balance)+ AccountProvider.create!(account: account, provider: plaid_account)+ end+ create_linked_transfer(family: @family, from: checking, to: brokerage, amount: 500, date: Date.current)++ totals = @statement.totals(period: Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month))++ assert_equal Money.new(500, "USD"), totals.contributions+ end++ # Transfer checks the signs of its legs only when it is saved, so a leg+ # whose amount later changes sign (a provider re-sync writes it again) can+ # become another transfer's leg on the other side. The leg is still one+ # withdrawal.+ test "a transaction that became another transfer's leg after a sign change counts once" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000)+ checking = @family.accounts.create!(name: "Checking", balance: 5000, currency: "USD", accountable: Depository.new)+ savings = @family.accounts.create!(name: "Savings", balance: 5000, currency: "USD", accountable: Depository.new)++ leg = create_linked_transfer(family: @family, from: checking, to: account, amount: 100, date: period.start_date).inflow_transaction.entry+ leg.update!(amount: 100)+ savings_leg = create_labelled_transaction(account: savings, label: nil, amount: -100, kind: "funds_movement", date: period.start_date)+ Transfer.create!(outflow_transaction: leg.entryable, inflow_transaction: savings_leg.entryable, status: "confirmed")++ totals = @statement.totals(period: period)++ assert_equal Money.new(100, "USD"), totals.withdrawals+ assert_equal Money.new(0, "USD"), totals.contributions+ end++ # A leg whose sign flips with no second transfer to take its place keeps+ # its link: the sign only chooses between transfers, it never drops one.+ test "a transfer between two investment accounts stays internal when a leg changes sign" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ from = create_investment_account(balance: 1000)+ to = create_investment_account(balance: 1000)+ transfer = create_linked_transfer(family: @family, from: from, to: to, amount: 200, date: period.start_date)++ transfer.inflow_transaction.entry.update!(amount: 200)+ totals = @statement.totals(period: period)+ assert_equal Money.new(0, "USD"), totals.contributions+ assert_equal Money.new(0, "USD"), totals.withdrawals, "one leg flipped"++ # A provider whose sign convention inverts both legs.+ transfer.outflow_transaction.entry.update!(amount: -200)+ totals = @statement.totals(period: period)+ assert_equal Money.new(0, "USD"), totals.contributions, "both legs flipped"+ assert_equal Money.new(0, "USD"), totals.withdrawals, "both legs flipped"+ end++ # A re-sync that inverts a settlement's sign writes the Cash leg and its+ # Portfolio counterpart (always the Cash leg's negation) together, and+ # #link_settlement_counterpart! leaves an existing link as it is.+ test "a Trade Republic settlement whose amounts were negated together is still internal" do+ portfolio, cash = create_split_trade_republic_connection+ sync_trade_republic(portfolio, [ trade_republic_order(id: "evt_buy", quantity: "2.0", signed_amount: -500, date: "2026-07-15") ])+ sync_trade_republic(cash, [])+ transfer = Transfer.confirmed.sole+ [ transfer.inflow_transaction.entry, transfer.outflow_transaction.entry ].each { |entry| entry.update!(amount: -entry.amount) }++ totals = InvestmentStatement.new(@family.reload).totals(period: july_2026)++ assert_equal Money.new(0, "EUR"), totals.contributions+ assert_equal Money.new(0, "EUR"), totals.withdrawals+ end++ # Trade Republic Cash has an IBAN and a card, and many users run it as+ # their current account. A card bill or a loan instalment paid from it is+ # spending, as the card purchases on it are; a transfer to the user's bank+ # still takes money out of the broker.+ test "credit card and loan payments from Trade Republic Cash are not withdrawals" do+ portfolio, cash = create_split_trade_republic_connection+ sync_trade_republic(portfolio, [])+ sync_trade_republic(cash, [])+ cash_account = cash.current_account+ card = @family.accounts.create!(name: "Card", balance: 1000, currency: "EUR", accountable: CreditCard.new)+ loan = @family.accounts.create!(name: "Loan", balance: 10000, currency: "EUR", accountable: Loan.new)+ bank = @family.accounts.create!(name: "Bank", balance: 1000, currency: "EUR", accountable: Depository.new)+ date = Date.new(2026, 7, 20)+ create_linked_transfer(family: @family, from: cash_account, to: card, amount: 800, date: date)+ create_linked_transfer(family: @family, from: cash_account, to: loan, amount: 400, date: date)+ create_linked_transfer(family: @family, from: cash_account, to: bank, amount: 300, date: date)+ assert_equal %w[cc_payment funds_movement loan_payment],+ cash_account.entries.where(entryable_type: "Transaction").map { |entry| entry.entryable.kind }.sort, "precondition: the kinds Transfer::Creator gives"++ totals = InvestmentStatement.new(@family.reload).totals(period: july_2026)++ assert_equal Money.new(300, "EUR"), totals.withdrawals+ assert_equal Money.new(0, "EUR"), totals.contributions++ # A label the user sets still decides.+ cash_account.entries.joins("JOIN transactions ON transactions.id = entries.entryable_id")+ .find_by!(transactions: { kind: "cc_payment" }).entryable.update!(investment_activity_label: "Withdrawal")+ assert_equal Money.new(1100, "EUR"), InvestmentStatement.new(@family.reload).totals(period: july_2026).withdrawals+ end++ # Only the settlement account is read as a current account. A credit card+ # paid from a brokerage account still takes money out of it.+ test "a credit card payment from an investment account is a withdrawal" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000)+ card = @family.accounts.create!(name: "Card", balance: 1000, currency: "USD", accountable: CreditCard.new)+ create_linked_transfer(family: @family, from: account, to: card, amount: 250, date: period.start_date)++ assert_equal Money.new(250, "USD"), @statement.totals(period: period).withdrawals+ end++ # Totals used to turn JIT off with SET LOCAL inside a savepoint. RELEASE+ # does not undo SET LOCAL, so a caller already in a transaction ran the+ # rest of it with JIT off.+ test "totals leave the jit setting of the caller's transaction as it was" do+ period = Period.custom(start_date: Date.current.beginning_of_month, end_date: Date.current.end_of_month)+ account = create_investment_account(balance: 1000)+ create_labelled_transaction(account: account, label: "Contribution", amount: -100, date: period.start_date)+ connection = ActiveRecord::Base.connection++ ActiveRecord::Base.transaction do+ before = connection.select_value("SHOW jit")+ assert_equal Money.new(100, "USD"), @statement.totals(period: period).contributions+ assert_equal before, connection.select_value("SHOW jit")+ end+ end++ # The classifier's security-transfer check used to be a correlated EXISTS+ # the planner priced per row against every other row, so its estimate grew+ # with the square of the entries: these 4,500 trades put it near 300,000,+ # past jit_above_cost, and JIT compilation then took longer than the+ # query. The grouped join keeps it in the low thousands.+ test "the totals query is planned below jit_above_cost" do+ accounts = Array.new(3) { create_investment_account(balance: 1000) }+ security = create_portfolio_security+ now = Time.current+ trades = Array.new(4500) do |n|+ { id: SecureRandom.uuid, security_id: security.id, qty: n.even? ? 2 : -1, price: 10, currency: "USD",+ investment_activity_label: n % 3 == 0 ? "Transfer" : "Buy", created_at: now, updated_at: now }+ end+ Trade.insert_all!(trades)+ Entry.insert_all!(trades.each_with_index.map do |trade, n|+ { account_id: accounts[n % 3].id, entryable_type: "Trade", entryable_id: trade[:id], amount: trade[:qty] * 10,+ currency: "USD", date: Date.current - (n / 3) % 360, name: "Trade", created_at: now, updated_at: now }+ end)+ connection = ActiveRecord::Base.connection+ connection.execute("ANALYZE entries, trades, transactions, transfers")++ sql = InvestmentStatement::Totals.new(@family, account_ids: accounts.map(&:id), date_range: 1.year.ago.to_date..Date.current).send(:query_sql)+ cost = JSON.parse(connection.select_value("EXPLAIN (FORMAT JSON) #{sql}")).first.dig("Plan", "Total Cost")++ assert_operator cost, :<, connection.select_value("SHOW jit_above_cost").to_f+ end+test "current_holdings memoizes so repeated dashboard-style calls issue a single query" doaccount = create_investment_account(balance: 2100, currency: "USD")security = Security.create!(ticker: "AAPL", name: "Apple")@@ -853,7 +1317,7 @@ class InvestmentStatementTest < ActiveSupport::TestCaseperiod = Period.last_30_daysRails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)- dummy_result = { contributions: 0, withdrawals: 0, dividends: 0, interest: 0, trades_count: 0 }+ dummy_result = { contributions: 0, withdrawals: 0, buys: 0, sells: 0, dividends: 0, interest: 0, trades_count: 0 }InvestmentStatement::Totals.expects(:new).twice.returns(stub(call: dummy_result))statement = InvestmentStatement.new(@family)@@ -868,7 +1332,7 @@ class InvestmentStatementTest < ActiveSupport::TestCaseperiod = Period.last_30_daysRails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)- dummy_result = { contributions: 0, withdrawals: 0, dividends: 0, interest: 0, trades_count: 0 }+ dummy_result = { contributions: 0, withdrawals: 0, buys: 0, sells: 0, dividends: 0, interest: 0, trades_count: 0 }InvestmentStatement::Totals.expects(:new).twice.returns(stub(call: dummy_result))InvestmentStatement.new(@family).totals(period: period)@@ -2074,6 +2538,44 @@ class InvestmentStatementTest < ActiveSupport::TestCase).createend+ def july_2026+ Period.custom(start_date: Date.new(2026, 7, 1), end_date: Date.new(2026, 7, 31))+ end++ # A Trade Republic connection with its Portfolio and Cash accounts both+ # linked, as account setup creates them. Returns the provider accounts.+ def create_split_trade_republic_connection+ @family.update!(currency: "EUR")+ item = TradeRepublicItem.create!(family: @family, name: "Trade Republic", currency: "EUR", phone_number: "+4917000#{rand(10**6)}")+ %w[portfolio cash].map do |kind|+ provider_account = item.trade_republic_accounts.create!(+ name: kind, kind: kind, trade_republic_account_id: "#{kind}:DESTMT", currency: "EUR", raw_timeline_payload: []+ )+ provider_account.ensure_account_provider!(Account.create_from_trade_republic_account(provider_account))+ provider_account.reload+ end+ end++ # The Cash account also reads the Portfolio's order executions, to book+ # their settlements, so the Portfolio syncs first.+ def sync_trade_republic(provider_account, events)+ provider_account.update!(raw_timeline_payload: events)+ TradeRepublicAccount::ActivitiesProcessor.new(provider_account.reload).process+ end++ def trade_republic_order(id:, quantity:, signed_amount:, date:)+ {+ id: id,+ timestamp: "#{date}T09:30:00Z",+ category: "orderExecution",+ title: "Core S&P 500 USD (Acc)",+ detail: {+ isin: "IE00B5BMR087", name: "Core S&P 500 USD (Acc)", quantity: quantity,+ amount: signed_amount.abs.to_s, signed_amount: signed_amount, currency: "EUR"+ }+ }+ end+def create_trade(account:, qty:, amount:, date:)account.entries.create!(name: "Trade #{SecureRandom.hex(3)}",diff --git a/test/models/portfolio/flow_classifier_test.rb b/test/models/portfolio/flow_classifier_test.rbindex de04785aa8..6dcc29857d 100644--- a/test/models/portfolio/flow_classifier_test.rb+++ b/test/models/portfolio/flow_classifier_test.rb@@ -164,6 +164,92 @@ class Portfolio::FlowClassifierTest < ActiveSupport::TestCaseassert_equal :external_outflow, @brokerage_scope.classify_ids([ outflow.id ])[outflow.id]end+ test "a pending transfer suggestion links nothing until it is confirmed" do+ outflow = create_labelled_transaction(account: @brokerage, label: "Withdrawal", amount: 40)+ inflow = create_labelled_transaction(account: @ira, label: "Contribution", amount: -40)+ transfer = Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable)+ assert transfer.pending?++ assert_equal :external_outflow, @family_scope.classify(outflow.reload)+ assert_equal :external_inflow, @family_scope.classify(inflow.reload)+ by_sql = @family_scope.classify_ids([ outflow.id, inflow.id ])+ assert_equal :external_outflow, by_sql[outflow.id]+ assert_equal :external_inflow, by_sql[inflow.id]++ transfer.confirm!++ assert_equal :internal, @family_scope.classify(outflow.reload)+ assert_equal :internal, @family_scope.classify_ids([ outflow.id ])[outflow.id]+ end++ # Transfer checks the signs only when it is saved. A leg whose amount+ # changes sign afterwards (a provider re-sync writes the amount again) can+ # become another transfer's leg on the other side, and the transfers join+ # would then match both. Each form takes the transfer on the side the+ # leg's sign allows: the inflow while it is negative, the outflow while it+ # is positive.+ test "a transaction on two transfers is linked on the side its sign allows" do+ first = create_linked_transfer(family: @family, from: @checking, to: @brokerage, amount: 100)+ leg = first.inflow_transaction.entry+ leg.update!(amount: 100)+ ira_leg = create_labelled_transaction(account: @ira, label: nil, amount: -100, kind: "funds_movement")+ Transfer.create!(outflow_transaction: leg.entryable, inflow_transaction: ira_leg.entryable, status: "confirmed")++ assert_equal [ first.id ], Transfer.where(inflow_transaction_id: leg.entryable_id).pluck(:id), "precondition: still the first transfer's inflow"+ assert_equal :internal, @family_scope.classify(leg.reload)+ assert_equal({ leg.id => :internal }, @family_scope.classify_ids([ leg.id ]))+ assert_equal 1, Entry.where(id: leg.id).joins(@family_scope.sql_joins).count, "one row per entry"+ end++ # The sign only chooses between transfers. With no transfer on the side a+ # flipped leg's sign allows, its own transfer still links it, in both forms.+ test "a transfer leg whose sign changed keeps its link when it has no other transfer" do+ transfer = create_linked_transfer(family: @family, from: @ira, to: @brokerage, amount: 200)+ inflow = transfer.inflow_transaction.entry+ outflow = transfer.outflow_transaction.entry+ inflow.update!(amount: 200)++ assert_equal :internal, @family_scope.classify(inflow.reload)+ assert_equal({ inflow.id => :internal, outflow.id => :internal }, @family_scope.classify_ids([ inflow.id, outflow.id ]))++ outflow.update!(amount: -200)++ assert_equal :internal, @family_scope.classify(outflow.reload)+ assert_equal({ inflow.id => :internal, outflow.id => :internal }, @family_scope.classify_ids([ inflow.id, outflow.id ]))+ # Each leg's counterpart still decides: from the brokerage alone, the IRA is outside.+ assert_equal :external_outflow, @brokerage_scope.classify(inflow.reload)+ assert_equal({ inflow.id => :external_outflow }, @brokerage_scope.classify_ids([ inflow.id ]))+ end++ # Rows written around Transfer's validations can put one transaction on+ # several transfers. The other side is read only when the sign's side has+ # no transfer, so extra transfers there do not multiply the entry's row,+ # and a pending transfer on a side never hides a confirmed one there.+ test "extra transfers written around the validations do not change a transaction's link" do+ first = create_linked_transfer(family: @family, from: @checking, to: @brokerage, amount: 100)+ leg = first.inflow_transaction.entry+ ira_leg = create_labelled_transaction(account: @ira, label: nil, amount: -100, kind: "funds_movement")+ savings = @family.accounts.create!(name: "Savings", balance: 5000, currency: "USD", accountable: Depository.new)+ savings_leg = create_labelled_transaction(account: savings, label: nil, amount: -100, kind: "funds_movement")+ now = Time.current+ Transfer.insert_all([ ira_leg, savings_leg ].map { |inflow| { inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: leg.entryable_id, status: "confirmed", created_at: now, updated_at: now } })++ assert_equal 1, Entry.where(id: leg.id).joins(@family_scope.sql_joins).count, "one row per entry"+ assert_equal :external_inflow, @family_scope.classify(leg.reload)+ assert_equal({ leg.id => :external_inflow }, @family_scope.classify_ids([ leg.id ]))++ # The sign's side now holds a pending transfer next to the confirmed one.+ pending_leg = create_labelled_transaction(account: @ira, label: nil, amount: 100, kind: "funds_movement")+ Transfer.insert_all([ { inflow_transaction_id: leg.entryable_id, outflow_transaction_id: pending_leg.entryable_id, status: "pending", created_at: now - 1.day, updated_at: now } ])+ # Written again after the pending one, so an unordered lookup meets the pending one first.+ first_attrs = first.attributes.slice("inflow_transaction_id", "outflow_transaction_id", "status", "amount", "created_at", "updated_at")+ Transfer.where(id: first.id).delete_all+ Transfer.insert_all([ first_attrs ])++ assert_equal :external_inflow, @family_scope.classify(leg.reload)+ assert_equal({ leg.id => :external_inflow }, @family_scope.classify_ids([ leg.id ]))+ end+test "an investment contribution from outside the scope is an external inflow" dotransfer = create_linked_transfer(family: @family, from: @checking, to: @brokerage, amount: 1000)inflow = transfer.inflow_transaction.entry@@ -224,6 +310,38 @@ class Portfolio::FlowClassifierTest < ActiveSupport::TestCaseassert_equal :external_outflow, @family_scope.classify_ids([ out_leg.id ])[out_leg.id]end+ # The opposite leg has to sit in another account. One in the same account+ # is a second move of the same position, not where this one came from. Once+ # a leg in another account joins, the in-leg has a counterpart in another+ # account, that leg has the in-leg, and the same-account leg still has none.+ #+ # The SQL form compares the entry's account with the lowest and the+ # highest account id among the opposite legs, so the scenario runs with+ # fixed ids in both orders: the other account's id below the in-leg's, and+ # above it.+ test "a security transfer's opposite leg in its own account is not its counterpart" do+ low = @family.accounts.create!(id: "00000000-0000-4000-8000-000000000001", name: "Low", balance: 1000, cash_balance: 0, currency: "USD", accountable: Investment.new)+ high = @family.accounts.create!(id: "ffffffff-ffff-4fff-bfff-fffffffffffe", name: "High", balance: 1000, cash_balance: 0, currency: "USD", accountable: Investment.new)+ scope = Portfolio::FlowClassifier.new(scope_account_ids: [ low.id, high.id ])++ [ [ low, high ], [ high, low ] ].each do |own, other|+ security = create_portfolio_security++ in_leg = create_portfolio_trade(account: own, security: security, qty: 10, price: 50, label: "Transfer")+ same_account_out = create_portfolio_trade(account: own, security: security, qty: -10, price: 50, label: "Transfer")++ assert_equal :external_inflow, scope.classify(in_leg)+ assert_equal :external_inflow, scope.classify_ids([ in_leg.id ])[in_leg.id]++ other_out = create_portfolio_trade(account: other, security: security, qty: -10, price: 50, label: "Transfer")+ ids = [ in_leg.id, same_account_out.id, other_out.id ]++ expected = { in_leg.id => :internal, same_account_out.id => :external_outflow, other_out.id => :internal }+ assert_equal expected, ids.index_with { |id| scope.classify(Entry.find(id)) }, "own account #{own.name}"+ assert_equal expected, scope.classify_ids(ids), "own account #{own.name}"+ end+ end+test "an unlabelled or Other trade is internal" dounlabelled = create_portfolio_trade(account: @brokerage, qty: 2, price: 10, label: nil)unlabelled.entryable.update!(investment_activity_label: nil)