2024-12-10 17:41:20 -05:00
|
|
|
# The current system calculates a single, end-of-day balance every day for each account for simplicity.
|
|
|
|
# In most cases, this is sufficient. However, for the "Activity View", we need to show intraday balances
|
|
|
|
# to show users how each entry affects their balances. This class calculates intraday balances by
|
|
|
|
# interpolating between end-of-day balances.
|
2025-04-14 11:40:34 -04:00
|
|
|
class Balance::TrendCalculator
|
2024-12-10 17:41:20 -05:00
|
|
|
BalanceTrend = Struct.new(:trend, :cash, keyword_init: true)
|
|
|
|
|
2025-05-08 12:25:53 -04:00
|
|
|
def initialize(balances)
|
2024-12-10 17:41:20 -05:00
|
|
|
@balances = balances
|
|
|
|
end
|
|
|
|
|
2025-05-08 12:25:53 -04:00
|
|
|
def trend_for(date)
|
|
|
|
balance = @balances.find { |b| b.date == date }
|
|
|
|
prior_balance = @balances.find { |b| b.date == date - 1.day }
|
2024-12-10 17:41:20 -05:00
|
|
|
|
2025-05-08 12:25:53 -04:00
|
|
|
return BalanceTrend.new(trend: nil) unless balance.present?
|
2024-12-10 17:41:20 -05:00
|
|
|
|
|
|
|
BalanceTrend.new(
|
2025-02-21 11:57:59 -05:00
|
|
|
trend: Trend.new(
|
2025-05-08 12:25:53 -04:00
|
|
|
current: Money.new(balance.balance, balance.currency),
|
2025-07-15 11:42:41 -04:00
|
|
|
previous: prior_balance.present? ? Money.new(prior_balance.balance, balance.currency) : nil,
|
2025-05-08 12:25:53 -04:00
|
|
|
favorable_direction: balance.account.favorable_direction
|
2024-12-10 17:41:20 -05:00
|
|
|
),
|
2025-05-08 12:25:53 -04:00
|
|
|
cash: Money.new(balance.cash_balance, balance.currency),
|
2024-12-10 17:41:20 -05:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
2025-05-08 12:25:53 -04:00
|
|
|
attr_reader :balances
|
2024-12-10 17:41:20 -05:00
|
|
|
end
|