mirror of
https://github.com/maybe-finance/maybe.git
synced 2025-08-05 05:25:24 +02:00
Use new balance components in activity feed (#2511)
* Balance reconcilations with new components * Fix materializer and test assumptions * Fix investment valuation calculations and recon display * Lint fixes * Balance series uses new component fields
This commit is contained in:
parent
3f92fe0f6f
commit
f7f6ebb091
17 changed files with 723 additions and 539 deletions
|
@ -17,7 +17,7 @@
|
|||
|
||||
<div class="flex items-center gap-4">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-medium"><%= balance_trend.current.format %></span>
|
||||
<span class="font-medium"><%= end_balance_money.format %></span>
|
||||
<%= render DS::Tooltip.new(text: "The end of day balance, after all transactions and adjustments", placement: "left", size: "sm") %>
|
||||
</div>
|
||||
<%= helpers.icon "chevron-down", class: "group-open:rotate-180" %>
|
||||
|
@ -25,73 +25,12 @@
|
|||
</div>
|
||||
</summary>
|
||||
|
||||
<div class="p-4 space-y-3">
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
Start of day balance
|
||||
<%= render DS::Tooltip.new(text: "The account balance at the beginning of this day, before any transactions or value changes", placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed border-secondary">
|
||||
<dd class="font-bold"><%= start_balance_money.format %></dd>
|
||||
</dl>
|
||||
|
||||
<% if account.balance_type == :investment %>
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
Δ Cash
|
||||
<%= render DS::Tooltip.new(text: "Net change in cash from deposits, withdrawals, and other cash transactions during the day", placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed border-secondary">
|
||||
<dd><%= cash_change_money.format %></dd>
|
||||
</dl>
|
||||
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
Δ Holdings
|
||||
<%= render DS::Tooltip.new(text: "Net change in investment holdings value from buying, selling, or market price movements", placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed border-secondary">
|
||||
<dd><%= holdings_change_money.format %></dd>
|
||||
</dl>
|
||||
<div class="p-4">
|
||||
<% if balance %>
|
||||
<%= render UI::Account::BalanceReconciliation.new(balance: balance, account: account) %>
|
||||
<% else %>
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
Δ Cash
|
||||
<%= render DS::Tooltip.new(text: "Net change in cash balance from all transactions during the day", placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed border-secondary">
|
||||
<dd><%= cash_change_money.format %></dd>
|
||||
</dl>
|
||||
<p class="text-sm text-secondary">No balance data available for this date</p>
|
||||
<% end %>
|
||||
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
End of day balance
|
||||
<%= render DS::Tooltip.new(text: "The calculated balance after all transactions but before any manual adjustments or reconciliations", placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed border-secondary">
|
||||
<dd class="font-medium"><%= end_balance_before_adjustments_money.format %></dd>
|
||||
</dl>
|
||||
|
||||
<hr class="border border-primary">
|
||||
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
Δ Value adjustments
|
||||
<%= render DS::Tooltip.new(text: "Adjustments are either manual reconciliations made by the user or adjustments due to market price changes throughout the day", placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed border-secondary">
|
||||
<dd><%= adjustments_money.format %></dd>
|
||||
</dl>
|
||||
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
Closing balance
|
||||
<%= render DS::Tooltip.new(text: "The final account balance for the day, after all transactions and adjustments have been applied", placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed border-primary">
|
||||
<dd class="font-bold"><%= end_balance_money.format %></dd>
|
||||
</dl>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
class UI::Account::ActivityDate < ApplicationComponent
|
||||
attr_reader :account, :data
|
||||
|
||||
delegate :date, :entries, :balance_trend, :cash_balance_trend, :holdings_value_trend, :transfers, to: :data
|
||||
delegate :date, :entries, :balance, :transfers, to: :data
|
||||
|
||||
def initialize(account:, data:)
|
||||
@account = account
|
||||
|
@ -16,28 +16,8 @@ class UI::Account::ActivityDate < ApplicationComponent
|
|||
account
|
||||
end
|
||||
|
||||
def start_balance_money
|
||||
balance_trend.previous
|
||||
end
|
||||
|
||||
def cash_change_money
|
||||
cash_balance_trend.value
|
||||
end
|
||||
|
||||
def holdings_change_money
|
||||
holdings_value_trend.value
|
||||
end
|
||||
|
||||
def end_balance_before_adjustments_money
|
||||
balance_trend.previous + cash_change_money + holdings_change_money
|
||||
end
|
||||
|
||||
def adjustments_money
|
||||
end_balance_money - end_balance_before_adjustments_money
|
||||
end
|
||||
|
||||
def end_balance_money
|
||||
balance_trend.current
|
||||
balance&.end_balance_money || Money.new(0, account.currency)
|
||||
end
|
||||
|
||||
def broadcast_refresh!
|
||||
|
|
22
app/components/UI/account/balance_reconciliation.html.erb
Normal file
22
app/components/UI/account/balance_reconciliation.html.erb
Normal file
|
@ -0,0 +1,22 @@
|
|||
<div class="space-y-3">
|
||||
<% reconciliation_items.each_with_index do |item, index| %>
|
||||
<% if item[:style] == :subtotal %>
|
||||
<hr class="border border-primary">
|
||||
<% end %>
|
||||
|
||||
<dl class="flex gap-4 items-center text-sm text-primary">
|
||||
<dt class="flex items-center gap-2">
|
||||
<%= item[:label] %>
|
||||
<%= render DS::Tooltip.new(text: item[:tooltip], placement: "left", size: "sm") %>
|
||||
</dt>
|
||||
<hr class="grow border-dashed <%= item[:style] == :final ? "border-primary" : "border-secondary" %>">
|
||||
<dd class="<%= item[:style] == :start || item[:style] == :final ? "font-bold" : item[:style] == :subtotal ? "font-medium" : "" %>">
|
||||
<%= item[:value].format %>
|
||||
</dd>
|
||||
</dl>
|
||||
|
||||
<% if item[:style] == :adjustment %>
|
||||
<hr class="border border-primary">
|
||||
<% end %>
|
||||
<% end %>
|
||||
</div>
|
155
app/components/UI/account/balance_reconciliation.rb
Normal file
155
app/components/UI/account/balance_reconciliation.rb
Normal file
|
@ -0,0 +1,155 @@
|
|||
class UI::Account::BalanceReconciliation < ApplicationComponent
|
||||
attr_reader :balance, :account
|
||||
|
||||
def initialize(balance:, account:)
|
||||
@balance = balance
|
||||
@account = account
|
||||
end
|
||||
|
||||
def reconciliation_items
|
||||
case account.accountable_type
|
||||
when "Depository", "OtherAsset", "OtherLiability"
|
||||
default_items
|
||||
when "CreditCard"
|
||||
credit_card_items
|
||||
when "Investment"
|
||||
investment_items
|
||||
when "Loan"
|
||||
loan_items
|
||||
when "Property", "Vehicle"
|
||||
asset_items
|
||||
when "Crypto"
|
||||
crypto_items
|
||||
else
|
||||
default_items
|
||||
end
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def default_items
|
||||
items = [
|
||||
{ label: "Start balance", value: balance.start_balance_money, tooltip: "The account balance at the beginning of this day", style: :start },
|
||||
{ label: "Net cash flow", value: net_cash_flow, tooltip: "Net change in balance from all transactions during the day", style: :flow }
|
||||
]
|
||||
|
||||
if has_adjustments?
|
||||
items << { label: "End balance", value: end_balance_before_adjustments, tooltip: "The calculated balance after all transactions", style: :subtotal }
|
||||
items << { label: "Adjustments", value: total_adjustments, tooltip: "Manual reconciliations or other adjustments", style: :adjustment }
|
||||
end
|
||||
|
||||
items << { label: "Final balance", value: balance.end_balance_money, tooltip: "The final account balance for the day", style: :final }
|
||||
items
|
||||
end
|
||||
|
||||
def credit_card_items
|
||||
items = [
|
||||
{ label: "Start balance", value: balance.start_balance_money, tooltip: "The balance owed at the beginning of this day", style: :start },
|
||||
{ label: "Charges", value: balance.cash_outflows_money, tooltip: "New charges made during the day", style: :flow },
|
||||
{ label: "Payments", value: balance.cash_inflows_money * -1, tooltip: "Payments made to the card during the day", style: :flow }
|
||||
]
|
||||
|
||||
if has_adjustments?
|
||||
items << { label: "End balance", value: end_balance_before_adjustments, tooltip: "The calculated balance after all transactions", style: :subtotal }
|
||||
items << { label: "Adjustments", value: total_adjustments, tooltip: "Manual reconciliations or other adjustments", style: :adjustment }
|
||||
end
|
||||
|
||||
items << { label: "Final balance", value: balance.end_balance_money, tooltip: "The final balance owed for the day", style: :final }
|
||||
items
|
||||
end
|
||||
|
||||
def investment_items
|
||||
items = [
|
||||
{ label: "Start balance", value: balance.start_balance_money, tooltip: "The total portfolio value at the beginning of this day", style: :start }
|
||||
]
|
||||
|
||||
# Change in brokerage cash (includes deposits, withdrawals, and cash from trades)
|
||||
items << { label: "Change in brokerage cash", value: net_cash_flow, tooltip: "Net change in cash from deposits, withdrawals, and trades", style: :flow }
|
||||
|
||||
# Change in holdings from trading activity
|
||||
items << { label: "Change in holdings (buys/sells)", value: net_non_cash_flow, tooltip: "Impact on holdings from buying and selling securities", style: :flow }
|
||||
|
||||
# Market price changes
|
||||
items << { label: "Change in holdings (market price activity)", value: balance.net_market_flows_money, tooltip: "Change in holdings value from market price movements", style: :flow }
|
||||
|
||||
if has_adjustments?
|
||||
items << { label: "End balance", value: end_balance_before_adjustments, tooltip: "The calculated balance after all activity", style: :subtotal }
|
||||
items << { label: "Adjustments", value: total_adjustments, tooltip: "Manual reconciliations or other adjustments", style: :adjustment }
|
||||
end
|
||||
|
||||
items << { label: "Final balance", value: balance.end_balance_money, tooltip: "The final portfolio value for the day", style: :final }
|
||||
items
|
||||
end
|
||||
|
||||
def loan_items
|
||||
items = [
|
||||
{ label: "Start principal", value: balance.start_balance_money, tooltip: "The principal balance at the beginning of this day", style: :start },
|
||||
{ label: "Net principal change", value: net_non_cash_flow, tooltip: "Principal payments and new borrowing during the day", style: :flow }
|
||||
]
|
||||
|
||||
if has_adjustments?
|
||||
items << { label: "End principal", value: end_balance_before_adjustments, tooltip: "The calculated principal after all transactions", style: :subtotal }
|
||||
items << { label: "Adjustments", value: balance.non_cash_adjustments_money, tooltip: "Manual reconciliations or other adjustments", style: :adjustment }
|
||||
end
|
||||
|
||||
items << { label: "Final principal", value: balance.end_balance_money, tooltip: "The final principal balance for the day", style: :final }
|
||||
items
|
||||
end
|
||||
|
||||
def asset_items # Property/Vehicle
|
||||
items = [
|
||||
{ label: "Start value", value: balance.start_balance_money, tooltip: "The asset value at the beginning of this day", style: :start },
|
||||
{ label: "Net value change", value: net_total_flow, tooltip: "All value changes including improvements and depreciation", style: :flow }
|
||||
]
|
||||
|
||||
if has_adjustments?
|
||||
items << { label: "End value", value: end_balance_before_adjustments, tooltip: "The calculated value after all changes", style: :subtotal }
|
||||
items << { label: "Adjustments", value: total_adjustments, tooltip: "Manual value adjustments or appraisals", style: :adjustment }
|
||||
end
|
||||
|
||||
items << { label: "Final value", value: balance.end_balance_money, tooltip: "The final asset value for the day", style: :final }
|
||||
items
|
||||
end
|
||||
|
||||
def crypto_items
|
||||
items = [
|
||||
{ label: "Start balance", value: balance.start_balance_money, tooltip: "The crypto holdings value at the beginning of this day", style: :start }
|
||||
]
|
||||
|
||||
items << { label: "Buys", value: balance.cash_outflows_money * -1, tooltip: "Crypto purchases during the day", style: :flow } if balance.cash_outflows != 0
|
||||
items << { label: "Sells", value: balance.cash_inflows_money, tooltip: "Crypto sales during the day", style: :flow } if balance.cash_inflows != 0
|
||||
items << { label: "Market changes", value: balance.net_market_flows_money, tooltip: "Value changes from market price movements", style: :flow } if balance.net_market_flows != 0
|
||||
|
||||
if has_adjustments?
|
||||
items << { label: "End balance", value: end_balance_before_adjustments, tooltip: "The calculated balance after all activity", style: :subtotal }
|
||||
items << { label: "Adjustments", value: total_adjustments, tooltip: "Manual reconciliations or other adjustments", style: :adjustment }
|
||||
end
|
||||
|
||||
items << { label: "Final balance", value: balance.end_balance_money, tooltip: "The final crypto holdings value for the day", style: :final }
|
||||
items
|
||||
end
|
||||
|
||||
def net_cash_flow
|
||||
balance.cash_inflows_money - balance.cash_outflows_money
|
||||
end
|
||||
|
||||
def net_non_cash_flow
|
||||
balance.non_cash_inflows_money - balance.non_cash_outflows_money
|
||||
end
|
||||
|
||||
def net_total_flow
|
||||
net_cash_flow + net_non_cash_flow + balance.net_market_flows_money
|
||||
end
|
||||
|
||||
def total_adjustments
|
||||
balance.cash_adjustments_money + balance.non_cash_adjustments_money
|
||||
end
|
||||
|
||||
def has_adjustments?
|
||||
balance.cash_adjustments != 0 || balance.non_cash_adjustments != 0
|
||||
end
|
||||
|
||||
def end_balance_before_adjustments
|
||||
balance.end_balance_money - total_adjustments
|
||||
end
|
||||
end
|
|
@ -2,7 +2,7 @@
|
|||
# This data object is useful for avoiding N+1 queries and having an easy way to pass around the required data to the
|
||||
# activity feed component in controllers and background jobs that refresh it.
|
||||
class Account::ActivityFeedData
|
||||
ActivityDateData = Data.define(:date, :entries, :balance_trend, :cash_balance_trend, :holdings_value_trend, :transfers)
|
||||
ActivityDateData = Data.define(:date, :entries, :balance, :transfers)
|
||||
|
||||
attr_reader :account, :entries
|
||||
|
||||
|
@ -17,9 +17,7 @@ class Account::ActivityFeedData
|
|||
ActivityDateData.new(
|
||||
date: date,
|
||||
entries: date_entries,
|
||||
balance_trend: balance_trend_for_date(date),
|
||||
cash_balance_trend: cash_balance_trend_for_date(date),
|
||||
holdings_value_trend: holdings_value_trend_for_date(date),
|
||||
balance: balance_for_date(date),
|
||||
transfers: transfers_for_date(date)
|
||||
)
|
||||
end
|
||||
|
@ -27,193 +25,61 @@ class Account::ActivityFeedData
|
|||
end
|
||||
|
||||
private
|
||||
def balance_trend_for_date(date)
|
||||
build_trend_for_date(date, :balance_money)
|
||||
end
|
||||
|
||||
def cash_balance_trend_for_date(date)
|
||||
date_entries = grouped_entries[date] || []
|
||||
has_valuation = date_entries.any?(&:valuation?)
|
||||
|
||||
if has_valuation
|
||||
# When there's a valuation, calculate cash change from transaction entries only
|
||||
transactions = date_entries.select { |e| e.transaction? }
|
||||
cash_change = sum_entries_with_exchange_rates(transactions, date) * -1
|
||||
|
||||
start_balance = start_balance_for_date(date)
|
||||
Trend.new(
|
||||
current: start_balance.cash_balance_money + cash_change,
|
||||
previous: start_balance.cash_balance_money
|
||||
)
|
||||
else
|
||||
build_trend_for_date(date, :cash_balance_money)
|
||||
end
|
||||
end
|
||||
|
||||
def holdings_value_trend_for_date(date)
|
||||
date_entries = grouped_entries[date] || []
|
||||
has_valuation = date_entries.any?(&:valuation?)
|
||||
|
||||
if has_valuation
|
||||
# When there's a valuation, calculate holdings change from trade entries only
|
||||
trades = date_entries.select { |e| e.trade? }
|
||||
holdings_change = sum_entries_with_exchange_rates(trades, date)
|
||||
|
||||
start_balance = start_balance_for_date(date)
|
||||
start_holdings = start_balance.balance_money - start_balance.cash_balance_money
|
||||
Trend.new(
|
||||
current: start_holdings + holdings_change,
|
||||
previous: start_holdings
|
||||
)
|
||||
else
|
||||
build_trend_for_date(date) do |balance|
|
||||
balance.balance_money - balance.cash_balance_money
|
||||
end
|
||||
end
|
||||
def balance_for_date(date)
|
||||
balances_by_date[date]
|
||||
end
|
||||
|
||||
def transfers_for_date(date)
|
||||
date_entries = grouped_entries[date] || []
|
||||
return [] if date_entries.empty?
|
||||
|
||||
date_transaction_ids = date_entries.select(&:transaction?).map(&:entryable_id)
|
||||
return [] if date_transaction_ids.empty?
|
||||
|
||||
# Convert to Set for O(1) lookups
|
||||
date_transaction_id_set = Set.new(date_transaction_ids)
|
||||
|
||||
transfers.select { |txfr|
|
||||
date_transaction_id_set.include?(txfr.inflow_transaction_id) ||
|
||||
date_transaction_id_set.include?(txfr.outflow_transaction_id)
|
||||
}
|
||||
transfers_by_date[date] || []
|
||||
end
|
||||
|
||||
def build_trend_for_date(date, method = nil)
|
||||
start_balance = start_balance_for_date(date)
|
||||
end_balance = end_balance_for_date(date)
|
||||
|
||||
if block_given?
|
||||
Trend.new(
|
||||
current: yield(end_balance),
|
||||
previous: yield(start_balance)
|
||||
)
|
||||
else
|
||||
Trend.new(
|
||||
current: end_balance.send(method),
|
||||
previous: start_balance.send(method)
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
# Finds the balance on date, or the most recent balance before it ("last observation carried forward")
|
||||
def start_balance_for_date(date)
|
||||
@start_balance_for_date ||= {}
|
||||
@start_balance_for_date[date] ||= last_observed_balance_before_date(date.prev_day) || generate_fallback_balance(date)
|
||||
end
|
||||
|
||||
# Finds the balance on date, or the most recent balance before it ("last observation carried forward")
|
||||
def end_balance_for_date(date)
|
||||
@end_balance_for_date ||= {}
|
||||
@end_balance_for_date[date] ||= last_observed_balance_before_date(date) || generate_fallback_balance(date)
|
||||
end
|
||||
|
||||
RequiredExchangeRate = Data.define(:date, :from, :to)
|
||||
|
||||
def grouped_entries
|
||||
@grouped_entries ||= entries.group_by(&:date)
|
||||
end
|
||||
|
||||
def needs_exchange_rates?
|
||||
entries.any? { |entry| entry.currency != account.currency }
|
||||
end
|
||||
def balances_by_date
|
||||
@balances_by_date ||= begin
|
||||
return {} if entries.empty?
|
||||
|
||||
def required_exchange_rates
|
||||
multi_currency_entries = entries.select { |entry| entry.currency != account.currency }
|
||||
|
||||
multi_currency_entries.map do |entry|
|
||||
RequiredExchangeRate.new(date: entry.date, from: entry.currency, to: account.currency)
|
||||
end.uniq
|
||||
end
|
||||
|
||||
# If the account has entries denominated in a different currency than the main account, we attach necessary
|
||||
# exchange rates required to "roll up" the entry group balance into the normal account currency.
|
||||
def exchange_rates
|
||||
return [] unless needs_exchange_rates?
|
||||
|
||||
@exchange_rates ||= begin
|
||||
rate_requirements = required_exchange_rates
|
||||
return [] if rate_requirements.empty?
|
||||
|
||||
# Use ActiveRecord's or chain for better performance
|
||||
conditions = rate_requirements.map do |req|
|
||||
ExchangeRate.where(date: req.date, from_currency: req.from, to_currency: req.to)
|
||||
end.reduce(:or)
|
||||
|
||||
conditions.to_a
|
||||
dates = grouped_entries.keys
|
||||
account.balances
|
||||
.where(date: dates, currency: account.currency)
|
||||
.index_by(&:date)
|
||||
end
|
||||
end
|
||||
|
||||
def exchange_rate_for(date, from_currency, to_currency)
|
||||
return 1.0 if from_currency == to_currency
|
||||
def transfers_by_date
|
||||
@transfers_by_date ||= begin
|
||||
return {} if transaction_ids.empty?
|
||||
|
||||
rate = exchange_rates.find { |r| r.date == date && r.from_currency == from_currency && r.to_currency == to_currency }
|
||||
rate&.rate || 1.0 # Fallback to 1:1 if no rate found
|
||||
end
|
||||
transfers = Transfer
|
||||
.where(inflow_transaction_id: transaction_ids)
|
||||
.or(Transfer.where(outflow_transaction_id: transaction_ids))
|
||||
.to_a
|
||||
|
||||
def sum_entries_with_exchange_rates(entries, date)
|
||||
return Money.new(0, account.currency) if entries.empty?
|
||||
# Group transfers by the date of their transaction entries
|
||||
result = Hash.new { |h, k| h[k] = [] }
|
||||
|
||||
entries.sum do |entry|
|
||||
amount = entry.amount_money
|
||||
if entry.currency != account.currency
|
||||
rate = exchange_rate_for(date, entry.currency, account.currency)
|
||||
Money.new(amount.amount * rate, account.currency)
|
||||
else
|
||||
amount
|
||||
entries.each do |entry|
|
||||
next unless entry.transaction? && transaction_ids.include?(entry.entryable_id)
|
||||
|
||||
transfers.each do |transfer|
|
||||
if transfer.inflow_transaction_id == entry.entryable_id ||
|
||||
transfer.outflow_transaction_id == entry.entryable_id
|
||||
result[entry.date] << transfer
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# We read balances so we can show "start of day" -> "end of day" balances for each entry date group in the feed
|
||||
def balances
|
||||
@balances ||= begin
|
||||
return [] if entries.empty?
|
||||
|
||||
min_date = entries.min_by(&:date).date.prev_day
|
||||
max_date = entries.max_by(&:date).date
|
||||
|
||||
account.balances.where(date: min_date..max_date, currency: account.currency).order(:date).to_a
|
||||
# Remove duplicates
|
||||
result.transform_values(&:uniq)
|
||||
end
|
||||
end
|
||||
|
||||
def transaction_ids
|
||||
entries.select { |entry| entry.transaction? }.map(&:entryable_id)
|
||||
end
|
||||
|
||||
def transfers
|
||||
return [] if entries.select { |e| e.transaction? && e.transaction.transfer? }.empty?
|
||||
return [] if transaction_ids.empty?
|
||||
|
||||
@transfers ||= Transfer.where(inflow_transaction_id: transaction_ids).or(Transfer.where(outflow_transaction_id: transaction_ids)).to_a
|
||||
end
|
||||
|
||||
# Use binary search since balances are sorted by date
|
||||
def last_observed_balance_before_date(date)
|
||||
idx = balances.bsearch_index { |b| b.date > date }
|
||||
|
||||
if idx
|
||||
idx > 0 ? balances[idx - 1] : nil
|
||||
else
|
||||
balances.last
|
||||
end
|
||||
end
|
||||
|
||||
def generate_fallback_balance(date)
|
||||
Balance.new(
|
||||
account: account,
|
||||
date: date,
|
||||
balance: 0,
|
||||
currency: account.currency
|
||||
)
|
||||
@transaction_ids ||= entries
|
||||
.select(&:transaction?)
|
||||
.map(&:entryable_id)
|
||||
.compact
|
||||
end
|
||||
end
|
||||
|
|
|
@ -82,8 +82,8 @@ class Account::ReconciliationManager
|
|||
balance_record = account.balances.find_by(date: date, currency: account.currency)
|
||||
|
||||
{
|
||||
cash_balance: balance_record&.cash_balance,
|
||||
balance: balance_record&.balance
|
||||
cash_balance: balance_record&.end_cash_balance,
|
||||
balance: balance_record&.end_balance
|
||||
}
|
||||
end
|
||||
end
|
||||
|
|
|
@ -14,4 +14,18 @@ class Balance < ApplicationRecord
|
|||
|
||||
scope :in_period, ->(period) { period.nil? ? all : where(date: period.date_range) }
|
||||
scope :chronological, -> { order(:date) }
|
||||
|
||||
def balance_trend
|
||||
Trend.new(
|
||||
current: end_balance_money,
|
||||
previous: start_balance_money,
|
||||
favorable_direction: favorable_direction
|
||||
)
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def favorable_direction
|
||||
flows_factor == -1 ? "down" : "up"
|
||||
end
|
||||
end
|
||||
|
|
|
@ -29,16 +29,16 @@ class Balance::BaseCalculator
|
|||
end
|
||||
end
|
||||
|
||||
def cash_adjustments_for_date(start_cash, net_cash_flows, valuation)
|
||||
return 0 unless valuation && account.balance_type != :non_cash
|
||||
def cash_adjustments_for_date(start_cash, end_cash, net_cash_flows)
|
||||
return 0 unless account.balance_type != :non_cash
|
||||
|
||||
valuation.amount - start_cash - net_cash_flows
|
||||
end_cash - start_cash - net_cash_flows
|
||||
end
|
||||
|
||||
def non_cash_adjustments_for_date(start_non_cash, non_cash_flows, valuation)
|
||||
return 0 unless valuation && account.balance_type == :non_cash
|
||||
def non_cash_adjustments_for_date(start_non_cash, end_non_cash, non_cash_flows)
|
||||
return 0 unless account.balance_type == :non_cash
|
||||
|
||||
valuation.amount - start_non_cash - non_cash_flows
|
||||
end_non_cash - start_non_cash - non_cash_flows
|
||||
end
|
||||
|
||||
# If holdings value goes from $100 -> $200 (change_holdings_value is $100)
|
||||
|
|
|
@ -8,21 +8,21 @@ class Balance::ChartSeriesBuilder
|
|||
end
|
||||
|
||||
def balance_series
|
||||
build_series_for(:balance)
|
||||
build_series_for(:end_balance)
|
||||
rescue => e
|
||||
Rails.logger.error "Balance series error: #{e.message} for accounts #{@account_ids}"
|
||||
raise
|
||||
end
|
||||
|
||||
def cash_balance_series
|
||||
build_series_for(:cash_balance)
|
||||
build_series_for(:end_cash_balance)
|
||||
rescue => e
|
||||
Rails.logger.error "Cash balance series error: #{e.message} for accounts #{@account_ids}"
|
||||
raise
|
||||
end
|
||||
|
||||
def holdings_balance_series
|
||||
build_series_for(:holdings_balance)
|
||||
build_series_for(:end_holdings_balance)
|
||||
rescue => e
|
||||
Rails.logger.error "Holdings balance series error: #{e.message} for accounts #{@account_ids}"
|
||||
raise
|
||||
|
@ -37,13 +37,20 @@ class Balance::ChartSeriesBuilder
|
|||
|
||||
def build_series_for(column)
|
||||
values = query_data.map do |datum|
|
||||
# Map column names to their start equivalents
|
||||
previous_column = case column
|
||||
when :end_balance then :start_balance
|
||||
when :end_cash_balance then :start_cash_balance
|
||||
when :end_holdings_balance then :start_holdings_balance
|
||||
end
|
||||
|
||||
Series::Value.new(
|
||||
date: datum.date,
|
||||
date_formatted: I18n.l(datum.date, format: :long),
|
||||
value: Money.new(datum.send(column), currency),
|
||||
trend: Trend.new(
|
||||
current: Money.new(datum.send(column), currency),
|
||||
previous: Money.new(datum.send("previous_#{column}"), currency),
|
||||
previous: Money.new(datum.send(previous_column), currency),
|
||||
favorable_direction: favorable_direction
|
||||
)
|
||||
)
|
||||
|
@ -88,66 +95,57 @@ class Balance::ChartSeriesBuilder
|
|||
WITH dates AS (
|
||||
SELECT generate_series(DATE :start_date, DATE :end_date, :interval::interval)::date AS date
|
||||
UNION DISTINCT
|
||||
SELECT :end_date::date -- Pass in date to ensure timezone-aware "today" date
|
||||
), aggregated_balances AS (
|
||||
SELECT
|
||||
d.date,
|
||||
-- Total balance (assets positive, liabilities negative)
|
||||
SUM(
|
||||
CASE WHEN accounts.classification = 'asset'
|
||||
THEN COALESCE(last_bal.balance, 0)
|
||||
ELSE -COALESCE(last_bal.balance, 0)
|
||||
END * COALESCE(er.rate, 1) * :sign_multiplier::integer
|
||||
) AS balance,
|
||||
-- Cash-only balance
|
||||
SUM(
|
||||
CASE WHEN accounts.classification = 'asset'
|
||||
THEN COALESCE(last_bal.cash_balance, 0)
|
||||
ELSE -COALESCE(last_bal.cash_balance, 0)
|
||||
END * COALESCE(er.rate, 1) * :sign_multiplier::integer
|
||||
) AS cash_balance,
|
||||
-- Holdings value (balance ‑ cash)
|
||||
SUM(
|
||||
CASE WHEN accounts.classification = 'asset'
|
||||
THEN COALESCE(last_bal.balance, 0) - COALESCE(last_bal.cash_balance, 0)
|
||||
ELSE 0
|
||||
END * COALESCE(er.rate, 1) * :sign_multiplier::integer
|
||||
) AS holdings_balance
|
||||
FROM dates d
|
||||
JOIN accounts ON accounts.id = ANY(array[:account_ids]::uuid[])
|
||||
|
||||
-- Last observation carried forward (LOCF), use the most recent balance on or before the chart date
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT b.balance, b.cash_balance
|
||||
FROM balances b
|
||||
WHERE b.account_id = accounts.id
|
||||
AND b.date <= d.date
|
||||
ORDER BY b.date DESC
|
||||
LIMIT 1
|
||||
) last_bal ON TRUE
|
||||
|
||||
-- Last observation carried forward (LOCF), use the most recent exchange rate on or before the chart date
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT er.rate
|
||||
FROM exchange_rates er
|
||||
WHERE er.from_currency = accounts.currency
|
||||
AND er.to_currency = :target_currency
|
||||
AND er.date <= d.date
|
||||
ORDER BY er.date DESC
|
||||
LIMIT 1
|
||||
) er ON TRUE
|
||||
GROUP BY d.date
|
||||
SELECT :end_date::date -- Ensure end date is included
|
||||
)
|
||||
SELECT
|
||||
date,
|
||||
balance,
|
||||
cash_balance,
|
||||
holdings_balance,
|
||||
COALESCE(LAG(balance) OVER (ORDER BY date), 0) AS previous_balance,
|
||||
COALESCE(LAG(cash_balance) OVER (ORDER BY date), 0) AS previous_cash_balance,
|
||||
COALESCE(LAG(holdings_balance) OVER (ORDER BY date), 0) AS previous_holdings_balance
|
||||
FROM aggregated_balances
|
||||
ORDER BY date
|
||||
d.date,
|
||||
-- Use flows_factor: already handles asset (+1) vs liability (-1)
|
||||
COALESCE(SUM(last_bal.end_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS end_balance,
|
||||
COALESCE(SUM(last_bal.end_cash_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS end_cash_balance,
|
||||
-- Holdings only for assets (flows_factor = 1)
|
||||
COALESCE(SUM(
|
||||
CASE WHEN last_bal.flows_factor = 1
|
||||
THEN last_bal.end_non_cash_balance
|
||||
ELSE 0
|
||||
END * COALESCE(er.rate, 1) * :sign_multiplier::integer
|
||||
), 0) AS end_holdings_balance,
|
||||
-- Previous balances
|
||||
COALESCE(SUM(last_bal.start_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS start_balance,
|
||||
COALESCE(SUM(last_bal.start_cash_balance * last_bal.flows_factor * COALESCE(er.rate, 1) * :sign_multiplier::integer), 0) AS start_cash_balance,
|
||||
COALESCE(SUM(
|
||||
CASE WHEN last_bal.flows_factor = 1
|
||||
THEN last_bal.start_non_cash_balance
|
||||
ELSE 0
|
||||
END * COALESCE(er.rate, 1) * :sign_multiplier::integer
|
||||
), 0) AS start_holdings_balance
|
||||
FROM dates d
|
||||
CROSS JOIN accounts
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT b.end_balance,
|
||||
b.end_cash_balance,
|
||||
b.end_non_cash_balance,
|
||||
b.start_balance,
|
||||
b.start_cash_balance,
|
||||
b.start_non_cash_balance,
|
||||
b.flows_factor
|
||||
FROM balances b
|
||||
WHERE b.account_id = accounts.id
|
||||
AND b.date <= d.date
|
||||
ORDER BY b.date DESC
|
||||
LIMIT 1
|
||||
) last_bal ON TRUE
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT er.rate
|
||||
FROM exchange_rates er
|
||||
WHERE er.from_currency = accounts.currency
|
||||
AND er.to_currency = :target_currency
|
||||
AND er.date <= d.date
|
||||
ORDER BY er.date DESC
|
||||
LIMIT 1
|
||||
) er ON TRUE
|
||||
WHERE accounts.id = ANY(array[:account_ids]::uuid[])
|
||||
GROUP BY d.date
|
||||
ORDER BY d.date
|
||||
SQL
|
||||
end
|
||||
end
|
||||
|
|
|
@ -2,10 +2,10 @@ class Balance::ForwardCalculator < Balance::BaseCalculator
|
|||
def calculate
|
||||
Rails.logger.tagged("Balance::ForwardCalculator") do
|
||||
start_cash_balance = derive_cash_balance_on_date_from_total(
|
||||
total_balance: 0,
|
||||
total_balance: account.opening_anchor_balance,
|
||||
date: account.opening_anchor_date
|
||||
)
|
||||
start_non_cash_balance = 0
|
||||
start_non_cash_balance = account.opening_anchor_balance - start_cash_balance
|
||||
|
||||
calc_start_date.upto(calc_end_date).map do |date|
|
||||
valuation = sync_cache.get_valuation(date)
|
||||
|
@ -24,6 +24,9 @@ class Balance::ForwardCalculator < Balance::BaseCalculator
|
|||
flows = flows_for_date(date)
|
||||
market_value_change = market_value_change_on_date(date, flows)
|
||||
|
||||
cash_adjustments = cash_adjustments_for_date(start_cash_balance, end_cash_balance, (flows[:cash_inflows] - flows[:cash_outflows]) * flows_factor)
|
||||
non_cash_adjustments = non_cash_adjustments_for_date(start_non_cash_balance, end_non_cash_balance, (flows[:non_cash_inflows] - flows[:non_cash_outflows]) * flows_factor)
|
||||
|
||||
output_balance = build_balance(
|
||||
date: date,
|
||||
balance: end_cash_balance + end_non_cash_balance,
|
||||
|
@ -34,8 +37,8 @@ class Balance::ForwardCalculator < Balance::BaseCalculator
|
|||
cash_outflows: flows[:cash_outflows],
|
||||
non_cash_inflows: flows[:non_cash_inflows],
|
||||
non_cash_outflows: flows[:non_cash_outflows],
|
||||
cash_adjustments: cash_adjustments_for_date(start_cash_balance, flows[:cash_inflows] - flows[:cash_outflows], valuation),
|
||||
non_cash_adjustments: non_cash_adjustments_for_date(start_non_cash_balance, flows[:non_cash_inflows] - flows[:non_cash_outflows], valuation),
|
||||
cash_adjustments: cash_adjustments,
|
||||
non_cash_adjustments: non_cash_adjustments,
|
||||
net_market_flows: market_value_change
|
||||
)
|
||||
|
||||
|
@ -75,4 +78,8 @@ class Balance::ForwardCalculator < Balance::BaseCalculator
|
|||
def derive_end_non_cash_balance(start_non_cash_balance:, date:)
|
||||
derive_non_cash_balance(start_non_cash_balance, date, direction: :forward)
|
||||
end
|
||||
|
||||
def flows_factor
|
||||
account.asset? ? 1 : -1
|
||||
end
|
||||
end
|
||||
|
|
|
@ -28,9 +28,20 @@ class Balance::Materializer
|
|||
end
|
||||
|
||||
def update_account_info
|
||||
calculated_balance = @balances.sort_by(&:date).last&.balance || 0
|
||||
calculated_holdings_value = @holdings.select { |h| h.date == Date.current }.sum(&:amount) || 0
|
||||
calculated_cash_balance = calculated_balance - calculated_holdings_value
|
||||
# Query fresh balance from DB to get generated column values
|
||||
current_balance = account.balances
|
||||
.where(currency: account.currency)
|
||||
.order(date: :desc)
|
||||
.first
|
||||
|
||||
if current_balance
|
||||
calculated_balance = current_balance.end_balance
|
||||
calculated_cash_balance = current_balance.end_cash_balance
|
||||
else
|
||||
# Fallback if no balance exists
|
||||
calculated_balance = 0
|
||||
calculated_cash_balance = 0
|
||||
end
|
||||
|
||||
Rails.logger.info("Balance update: cash=#{calculated_cash_balance}, total=#{calculated_balance}")
|
||||
|
||||
|
@ -48,14 +59,23 @@ class Balance::Materializer
|
|||
current_time = Time.now
|
||||
account.balances.upsert_all(
|
||||
@balances.map { |b| b.attributes
|
||||
.slice("date", "balance", "cash_balance", "currency")
|
||||
.slice("date", "balance", "cash_balance", "currency",
|
||||
"start_cash_balance", "start_non_cash_balance",
|
||||
"cash_inflows", "cash_outflows",
|
||||
"non_cash_inflows", "non_cash_outflows",
|
||||
"net_market_flows",
|
||||
"cash_adjustments", "non_cash_adjustments",
|
||||
"flows_factor")
|
||||
.merge("updated_at" => current_time) },
|
||||
unique_by: %i[account_id date currency]
|
||||
)
|
||||
end
|
||||
|
||||
def purge_stale_balances
|
||||
deleted_count = account.balances.delete_by("date < ?", account.start_date)
|
||||
sorted_balances = @balances.sort_by(&:date)
|
||||
oldest_calculated_balance_date = sorted_balances.first&.date
|
||||
newest_calculated_balance_date = sorted_balances.last&.date
|
||||
deleted_count = account.balances.delete_by("date < ? OR date > ?", oldest_calculated_balance_date, newest_calculated_balance_date)
|
||||
Rails.logger.info("Purged #{deleted_count} stale balances") if deleted_count > 0
|
||||
end
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue