2024-02-02 09:05:04 -06:00
|
|
|
class Account < ApplicationRecord
|
2024-02-24 02:18:30 +00:00
|
|
|
broadcasts_refreshes
|
2024-02-02 09:05:04 -06:00
|
|
|
belongs_to :family
|
2024-02-20 09:07:55 -05:00
|
|
|
has_many :balances, class_name: "AccountBalance"
|
|
|
|
has_many :valuations
|
2024-02-23 21:34:33 -05:00
|
|
|
has_many :transactions
|
2024-02-02 11:09:31 -06:00
|
|
|
|
2024-02-09 14:26:54 +00:00
|
|
|
delegated_type :accountable, types: Accountable::TYPES, dependent: :destroy
|
2024-02-02 23:06:29 +00:00
|
|
|
|
2024-02-03 15:38:52 -05:00
|
|
|
delegate :type_name, to: :accountable
|
2024-02-10 16:18:56 -06:00
|
|
|
before_create :check_currency
|
|
|
|
|
2024-02-22 11:35:06 -05:00
|
|
|
def balance_series(period)
|
|
|
|
filtered_balances = balances.in_period(period).order(:date)
|
|
|
|
return nil if filtered_balances.empty?
|
|
|
|
|
|
|
|
series_data = [ nil, *filtered_balances ].each_cons(2).map do |previous, current|
|
|
|
|
trend = current&.trend(previous)
|
|
|
|
{ data: current, trend: { amount: trend&.amount, direction: trend&.direction, percent: trend&.percent } }
|
|
|
|
end
|
|
|
|
|
|
|
|
last_balance = series_data.last[:data]
|
|
|
|
|
|
|
|
{
|
|
|
|
series_data: series_data,
|
|
|
|
last_balance: last_balance.balance,
|
|
|
|
trend: last_balance.trend(series_data.first[:data])
|
|
|
|
}
|
2024-02-20 09:07:55 -05:00
|
|
|
end
|
|
|
|
|
2024-02-22 11:35:06 -05:00
|
|
|
def valuation_series
|
|
|
|
series_data = [ nil, *valuations.order(:date) ].each_cons(2).map do |previous, current|
|
|
|
|
{ value: current, trend: current&.trend(previous) }
|
|
|
|
end
|
|
|
|
|
|
|
|
series_data.reverse_each
|
2024-02-20 09:07:55 -05:00
|
|
|
end
|
|
|
|
|
2024-02-10 16:18:56 -06:00
|
|
|
def check_currency
|
|
|
|
if self.original_currency == self.family.currency
|
|
|
|
self.converted_balance = self.original_balance
|
|
|
|
self.converted_currency = self.original_currency
|
|
|
|
else
|
|
|
|
self.converted_balance = ExchangeRate.convert(self.original_currency, self.family.currency, self.original_balance)
|
|
|
|
self.converted_currency = self.family.currency
|
|
|
|
end
|
|
|
|
end
|
2024-02-02 09:05:04 -06:00
|
|
|
end
|