add Transaction class and collect transactions for each account

This commit is contained in:
josh committed 2013-08-03 18:59:41 -04:00
1 parent 79219686aa
commit 9596272c29
4 files changed
+47

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
require "gnucash/account"
require "gnucash/book"
require "gnucash/transaction"
require "gnucash/version"
module Gnucash
+9
View File
@@ -3,6 +3,7 @@ module Gnucash
attr_accessor :name
attr_accessor :type
attr_accessor :id
attr_accessor :transactions
def initialize(book, node)
@book = book
@@ -12,6 +13,7 @@ module Gnucash
@id = node.xpath('act:id').text
@parent_id = node.xpath('act:parent').text
@parent_id = nil if @parent_id == ""
@transactions = []
end
def full_name
@@ -24,5 +26,12 @@ module Gnucash
end
prefix + name
end
def add_transaction(txn, value)
@transactions << {
txn: txn,
value: value,
}
end
end
end
+8
View File
@@ -4,6 +4,7 @@ require "nokogiri"
module Gnucash
class Book
attr_accessor :accounts
attr_accessor :transactions
def initialize(fname)
@ng = Nokogiri.XML(Zlib::GzipReader.open(fname).read)
@@ -13,6 +14,7 @@ module Gnucash
end
@book_node = book_nodes.first
build_accounts
build_transactions
end
def find_account_by_id(id)
@@ -26,5 +28,11 @@ module Gnucash
Account.new(self, act_node)
end
end
def build_transactions
@transactions = @book_node.xpath('gnc:transaction').map do |txn_node|
Transaction.new(self, txn_node)
end
end
end
end
+29
View File
@@ -0,0 +1,29 @@
module Gnucash
class Transaction
attr_accessor :value
attr_accessor :id
def initialize(book, node)
@book = book
@node = node
@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
{
account_id: split_node.xpath('split:account').text,
value: value_parts.first.to_i,
}
end
@splits.each do |split|
account = @book.find_account_by_id(split[:account_id])
raise "Could not find account with ID #{split[:account_id]} for transaction #{@id}" unless account
account.add_transaction(self, split[:value])
end
end
end
end