diff --git a/app/models/income_statement.rb b/app/models/income_statement.rb index 9c20904d1..cc38ecc16 100644 --- a/app/models/income_statement.rb +++ b/app/models/income_statement.rb @@ -147,7 +147,12 @@ class IncomeStatement ActiveRecord::Base.sanitize_sql_array([ <<~SQL, SELECT + -- Group both legs of a linked transfer together, while keeping standalone + -- (non-transfer) entries as independent rows. COALESCE(e.transfer_id, e.id) AS group_id, + -- Count each transfer once as outflow: + -- 1) positive-leg sum for standard source-side outflows + -- 2) abs(negative-leg sum) for provider/import cases where only inflow leg exists GREATEST( SUM(CASE WHEN e.amount > 0 THEN e.amount * COALESCE(er.rate, 1) ELSE 0 END), ABS(SUM(CASE WHEN e.amount < 0 THEN e.amount * COALESCE(er.rate, 1) ELSE 0 END)) diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rb index 95f199970..1fb0bf563 100644 --- a/test/models/income_statement_test.rb +++ b/test/models/income_statement_test.rb @@ -364,6 +364,34 @@ class IncomeStatementTest < ActiveSupport::TestCase assert_equal 300, outflow_total.to_i end + test "investment contribution outflow total counts inflow leg when source account is not included in finances" do + user = users(:family_member) + investment_account = @family.accounts.create!( + name: "Shared Brokerage", + currency: @family.currency, + balance: 5000, + owner: users(:family_admin), + accountable: Investment.new + ) + + transfer = Transfer::Creator.new( + family: @family, + source_account_id: @checking_account.id, + destination_account_id: investment_account.id, + date: Date.current, + amount: 300 + ).create + transfer.inflow_transaction.update!(kind: "investment_contribution") + + @checking_account.share_with!(user, permission: "read_only", include_in_finances: false) + investment_account.share_with!(user, permission: "read_only", include_in_finances: true) + + income_statement = IncomeStatement.new(@family, user: user) + outflow_total = income_statement.investment_contributions_outflow_total(period: Period.last_30_days) + + assert_equal 300, outflow_total.to_i + end + # Tax-Advantaged Account Exclusion Tests test "excludes transactions from tax-advantaged Roth IRA accounts" do # Create a Roth IRA (tax-exempt) investment account