Skip to content

Commit

Permalink
add initial time series function to ProductBalance
Browse files Browse the repository at this point in the history
  • Loading branch information
dvanderbeek committed Apr 24, 2016
1 parent 08b79f1 commit 67ea632
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
17 changes: 17 additions & 0 deletions app/models/product_balance.rb
Expand Up @@ -12,4 +12,21 @@ def self.by_account
hsh[product_balance.account_id] = product_balance.amount_cents
end
end

def self.time_series(date_range = 1.month.ago.to_date..Date.current.to_date)
by_date = by_date(date_range)
date_range.each_with_object({}) do |date, hash|
hash[date] = by_date[date] || hash[date - 1] || starting_balance(as_of: date_range.first)
end
end

def self.by_date(date_range)
where(date: date_range).each_with_object({}) do |balance, hash|
hash[balance.date] = balance.amount_cents
end
end

def self.starting_balance(as_of: Date.current)
where('date < ?', as_of).order(date: :asc).last.try(:amount_cents) || 0
end
end
3 changes: 2 additions & 1 deletion app/views/accounts/index.html.haml
Expand Up @@ -39,4 +39,5 @@
%h4
Daily Balance
%small Accounts Receivable for Product 4 (in cents)
= debug Account.daily_balance(:accounts_receivable, for_product: 4, date_range: Date.new(2014, 12, 25)..Date.new(2015, 1, 15))
/ = debug Account.daily_balance(:accounts_receivable, for_product: 4, date_range: Date.new(2014, 12, 25)..Date.new(2015, 1, 15))
= debug ProductBalance.for_product(4).where(account: Account.accounts_receivable).time_series(Date.new(2014, 12, 25)..Date.new(2015, 1, 15))

0 comments on commit 67ea632

Please sign in to comment.