add Value class; keep track of account balances over time
This commit is contained in:
parent
5ba8e2806c
commit
6c4f67e3da
@ -1,6 +1,7 @@
|
||||
require "gnucash/account"
|
||||
require "gnucash/book"
|
||||
require "gnucash/transaction"
|
||||
require "gnucash/value"
|
||||
require "gnucash/version"
|
||||
|
||||
module Gnucash
|
||||
|
@ -38,6 +38,15 @@ module Gnucash
|
||||
@transactions.sort! do |a, b|
|
||||
a[:txn].date <=> b[:txn].date
|
||||
end
|
||||
balance = Value.new(0)
|
||||
@balances = @transactions.map do |txn_hash|
|
||||
balance += txn_hash[:value]
|
||||
[txn_hash[:txn].date, balance]
|
||||
end
|
||||
end
|
||||
|
||||
def current_balance
|
||||
@balances.last[1] rescue Value.new(0)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
@ -10,13 +10,8 @@ module Gnucash
|
||||
@id = node.xpath('trn:id').text
|
||||
@date = node.xpath('trn:date-posted/ts:date').text.split(' ').first
|
||||
@splits = node.xpath('trn:splits/trn:split').map do |split_node|
|
||||
value_str = split_node.xpath('split:value').text
|
||||
value_parts = value_str.split('/')
|
||||
unless value_parts.size == 2 and value_parts[1] == '100'
|
||||
raise "Unexpected value format: #{value_str.inspect}"
|
||||
end
|
||||
value = Value.new(split_node.xpath('split:value').text)
|
||||
account_id = split_node.xpath('split:account').text
|
||||
value = value_parts.first.to_i
|
||||
account = @book.find_account_by_id(account_id)
|
||||
unless account
|
||||
raise "Could not find account with ID #{account_id} for transaction #{@id}"
|
||||
|
30
lib/gnucash/value.rb
Normal file
30
lib/gnucash/value.rb
Normal file
@ -0,0 +1,30 @@
|
||||
module Gnucash
|
||||
class Value
|
||||
attr_accessor :val
|
||||
def initialize(val)
|
||||
if val.is_a?(String)
|
||||
if val =~ /^(-?\d+)\/100$/
|
||||
@val = $1.to_i
|
||||
else
|
||||
raise "Unexpected value string: #{val.inspect}"
|
||||
end
|
||||
elsif val.is_a?(Fixnum)
|
||||
@val = val
|
||||
else
|
||||
raise "Unexpected value type: #{val.class}"
|
||||
end
|
||||
end
|
||||
|
||||
def +(other)
|
||||
Value.new(@val + other.val)
|
||||
end
|
||||
|
||||
def -(other)
|
||||
Value.new(@val - other.val)
|
||||
end
|
||||
|
||||
def to_s
|
||||
(@val / 100.0).round(2).to_s
|
||||
end
|
||||
end
|
||||
end
|
Loading…
x
Reference in New Issue
Block a user