Files
sure/app/models/balance/sync_cache.rb
StalkerSea e4cfee0267 Fix income trades (interest/dividend) wiping security holdings to $0 (#2673)
Income trades created via Trade::CreateForm#create_income_trade set
price: 0 on the Trade record. This zero price was ingested by
PortfolioCache#load_prices as a valid price source, causing
ForwardCalculator#build_holdings to compute holding amount = qty * 0 = $0,
and overriding the security's market price on that date.

Additionally, Balance::BaseCalculator#flows_for_date misclassified income
trades (qty=0) as sells, producing spurious non_cash_outflows.

Fixes:
- PortfolioCache#load_prices: filter out zero-price trades from trade
  price sources using .select { |t| t.entryable.price&.positive? }
- Balance::BaseCalculator#flows_for_date: separate income trades from
  regular trades using their qty (income trades have qty=0), so they
  contribute only to cash flows, not non-cash flows
- Balance::SyncCache#converted_entries: preserve the entryable association
  target on duped entries so that e.entryable.qty access doesn't N+1

Fixes #2672
2026-07-14 01:33:35 +02:00

57 lines
1.7 KiB
Ruby

class Balance::SyncCache
def initialize(account)
@account = account
end
def get_valuation(date)
entries_by_date[date]&.find { |e| e.valuation? }
end
def get_holdings_value(date)
holdings_value_by_date[date] || 0
end
def get_entries(date)
entries_by_date[date]&.select { |e| e.transaction? || e.trade? } || []
end
private
attr_reader :account
def entries_by_date
@entries_by_date ||= converted_entries.group_by(&:date)
end
def holdings_value_by_date
@holdings_value_by_date ||= account.holdings.each_with_object(Hash.new(0)) do |h, totals|
begin
converted = Money.new(h.amount, h.currency).exchange_to(account.currency, date: h.date).amount
rescue Money::ConversionError
converted = h.amount # fallback to 1:1 conversion rate if exchange rate unavailable
end
totals[h.date] += converted
end
end
def converted_entries
@converted_entries ||= account.entries.excluding_split_parents.includes(:entryable).order(:date).to_a.map do |e|
converted_entry = e.dup
# dup does not copy the association cache, so the entryable would
# be re-fetched on access. Copy it to keep the preload active.
converted_entry.association(:entryable).target = e.entryable
custom_rate = e.entryable.exchange_rate if e.entryable.respond_to?(:exchange_rate)
# Use Money#exchange_to with custom rate if available, standard lookup otherwise
converted_entry.amount = converted_entry.amount_money.exchange_to(
account.currency,
date: e.date,
custom_rate: custom_rate
).amount
converted_entry.currency = account.currency
converted_entry
end
end
end