Created
June 10, 2014 15:43
-
-
Save bnmrrs/ff93241b74c91532a709 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Ledger::Balance | |
def balance(transaction=nil) | |
sum_of_credits(transaction) - sum_of_debits(transaction) | |
end | |
def amount_available(transaction=nil) | |
self.balance(transaction) | |
end | |
def spent | |
sum_of_debits | |
end | |
protected | |
def sum_of_credits(transaction=nil) | |
credits_sum = Ledger::Credit.select('COALESCE(SUM(credit),0) as credit').where(destination: self) | |
credits_sum = credits_sum.where('transaction_id <= ?', transaction) if transaction | |
credits_sum.first.credit | |
end | |
def sum_of_debits(transaction=nil) | |
debits_sum = Ledger::Debit.select('COALESCE(SUM(debit),0) as debit').where(destination: self) | |
debits_sum = credits_sum.where('transaction_id <= ?', transaction) if transaction | |
debits_sum.first.debit | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment