ofx-parser 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,4 @@
1
+ == 1.0.0 / 2007-06-24
2
+
3
+ * Initial release.
4
+
@@ -0,0 +1,12 @@
1
+ History.txt
2
+ Manifest.txt
3
+ README.txt
4
+ Rakefile
5
+ lib/class-extension.rb
6
+ lib/ofx-parser.rb
7
+ lib/ofx.rb
8
+ lib/sic.rb
9
+ test/fixtures/banking.ofx.sgml
10
+ test/fixtures/creditcard.ofx.sgml
11
+ test/fixtures/with_spaces.ofx.sgml
12
+ test/test_ofx_parser.rb
@@ -0,0 +1,103 @@
1
+ == ofx-parser
2
+ by Andrew A. Smith
3
+
4
+ http://ofx-parser.rubyforge.org/
5
+ http://rubyforge.org/projects/ofx-parser/
6
+
7
+ == DESCRIPTION:
8
+
9
+ ofx-parser is a ruby library to parse a realistic subset of the lengthy OFX 1.x specification.
10
+
11
+ == FEATURES/PROBLEMS:
12
+
13
+ * Reads OFX responses - i.e. those downloaded from financial institutions and
14
+ puts it into a usable object graph.
15
+ * Supports the 3 main message sets: banking, credit card and investment
16
+ accounts, as well as the required 'sign on' set.
17
+ * Knows about SIC codes - if your institution provides them.
18
+ See http://www.eeoc.gov/stats/jobpat/siccodes.html
19
+ * Monetary amounts can be retrieved either as a raw string, or in pennies.
20
+ * Supports OFX timestamps.
21
+
22
+ == SYNOPSIS:
23
+
24
+ Supports bank accounts:
25
+
26
+ require 'rubygems'
27
+ require 'ofx-parser'
28
+
29
+ ofx = OfxParser::OfxParser.parse(open("bank-statement.ofx"))
30
+
31
+ ofx.bank_account.number # => '103333333333'
32
+ ofx.bank_account.routing_number # => '033000033'
33
+ ofx.bank_account.balance # => '123.45'
34
+ ofx.bank_account.balance_in_pennies # => 12345
35
+
36
+ ofx.bank_account.statement.start_date # => DateTime
37
+ ofx.bank_account.statement.end_date # => DateTime
38
+
39
+ ofx.bank_account.statement.transactions.size # => 4
40
+
41
+ ofx.bank_account.statement.transactions.first.payee # => "FOO, INC."
42
+ ofx.bank_account.statement.transactions.first.type # => :DEBIT
43
+ ofx.bank_account.statement.transactions.first.amount # => '-11.11'
44
+ ofx.bank_account.statement.transactions.first.amount_in_pennies # => -1111
45
+
46
+ Also supports credit cards...
47
+
48
+ ofx = OfxParser::OfxParser.parse(open("creditcard-statement.ofx"))
49
+
50
+ ofx.credit_card.remaining_credit # => '19000.0'
51
+ ofx.credit_card.remaining_credit_in_pennies # => '1900000'
52
+
53
+ ofx.credit_card.statement.start_date # => DateTime
54
+ ofx.credit_card.statement.end_date # => DateTime
55
+
56
+ ofx.credit_card.statement.transactions.size # => 10
57
+
58
+ ofx.credit_card.statement.transactions.first.type # => :DEBIT
59
+ ofx.credit_card.statement.transactions.first.amount # => '-19.17'
60
+ ofx.credit_card.statement.transactions.first.amount_in_pennies # => '-1917'
61
+ ofx.credit_card.statement.transactions.first.sic # => '7933'
62
+ ofx.credit_card.statement.transactions.first.sic_desc # => 'BOWLING CENTERS'
63
+ ofx.credit_card.statement.transactions.first.payee # => 'SUNSET BOWLING'
64
+
65
+ Working on investment accounts...
66
+
67
+ == REQUIREMENTS:
68
+
69
+ * hpricot >= 0.6
70
+
71
+ == INSTALL:
72
+
73
+ * gem install ofx-parser
74
+
75
+ == LICENSE:
76
+
77
+ Copyright (c) 2007, Andrew A. Smith
78
+ All rights reserved.
79
+
80
+ Redistribution and use in source and binary forms, with or without modification,
81
+ are permitted provided that the following conditions are met:
82
+
83
+ * Redistributions of source code must retain the above copyright notice,
84
+ this list of conditions and the following disclaimer.
85
+
86
+ * Redistributions in binary form must reproduce the above copyright notice,
87
+ this list of conditions and the following disclaimer in the documentation
88
+ and/or other materials provided with the distribution.
89
+
90
+ * Neither the name of the copyright owner nor the names of its contributors
91
+ may be used to endorse or promote products derived from this software
92
+ without specific prior written permission.
93
+
94
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
95
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
96
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
97
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
98
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
99
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
100
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
101
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
102
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
103
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,18 @@
1
+ require 'rubygems'
2
+ require 'hoe'
3
+ $:.unshift(File.dirname(__FILE__) + "/lib")
4
+ require 'ofx-parser'
5
+
6
+ Hoe.new('ofx-parser', OfxParser::VERSION) do |p|
7
+ p.author = 'Andrew A. Smith'
8
+ p.email = 'andy@tinnedfruit.org'
9
+ p.rubyforge_name = 'ofx-parser'
10
+ p.summary = 'ofx-parser is a ruby library for parsing OFX 1.x data.'
11
+ p.description = p.paragraphs_of('README.txt', 2..5).join("\n\n")
12
+ p.url = 'http://ofx-parser.rubyforge.org/'
13
+ p.changes = p.paragraphs_of('History.txt', 0..1).join("\n\n")
14
+ p.remote_rdoc_dir = '' # Release to root
15
+ p.extra_deps << ["hpricot", ">= 0.6"]
16
+ p.need_zip = true
17
+ p.need_tar = false
18
+ end
@@ -0,0 +1,154 @@
1
+ # = class_extension.rb
2
+ #
3
+ # == Copyright (c) 2006 Daniel Schierbeck
4
+ #
5
+ # Ruby License
6
+ #
7
+ # This module is free software. You may use, modify, and/or redistribute this
8
+ # software under the same terms as Ruby.
9
+ #
10
+ # This program is distributed in the hope that it will be useful, but WITHOUT
11
+ # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
12
+ # FOR A PARTICULAR PURPOSE.
13
+ #
14
+ # == Special Thanks
15
+ #
16
+ # Thanks to Trans, Nobu and Ulysses for their original on this concept.
17
+ #
18
+ # == Authors and Contributors
19
+ #
20
+ # * Daniel Schierbeck
21
+ # * Thomas Sawyer
22
+ # * Nobu Nakada
23
+ # * Ulysses
24
+
25
+ # Author:: Daniel Schierbeck
26
+ # Copyright:: Copyright (c) 2006 Daniel Schierbeck
27
+ # License:: Ruby License
28
+
29
+ #
30
+
31
+ class Module #:nodoc: all
32
+
33
+ alias_method :append_features_without_class_extension, :append_features
34
+
35
+ # = class_extension
36
+ #
37
+ # Normally when including modules, class/module methods are not
38
+ # extended. To achieve this behavior requires some clever
39
+ # Ruby Karate. Instead class_extension provides an easy to use
40
+ # and clean solution. Simply place the extending class methods
41
+ # in a block of the special module method #class_extension.
42
+ #
43
+ # module Mix
44
+ # def inst_meth
45
+ # puts 'inst_meth'
46
+ # end
47
+ #
48
+ # class_extension do
49
+ # def class_meth
50
+ # "Class Method!"
51
+ # end
52
+ # end
53
+ # end
54
+ #
55
+ # class X
56
+ # include Mix
57
+ # end
58
+ #
59
+ # X.class_meth #=> "Class Method!"
60
+ #
61
+
62
+ def class_extension(&block)
63
+ @class_extension ||= Module.new do
64
+ def self.append_features(mod)
65
+ append_features_without_class_extension(mod)
66
+ end
67
+ end
68
+ @class_extension.module_eval(&block) if block_given?
69
+ @class_extension
70
+ end
71
+
72
+ private :class_extension
73
+
74
+ def append_features(mod)
75
+ append_features_without_class_extension(mod)
76
+ mod.extend(class_extension)
77
+ if mod.instance_of? Module
78
+ mod.__send__(:class_extension).__send__(:include, class_extension)
79
+ end
80
+ end
81
+
82
+ end
83
+
84
+ class Class #:nodoc: all
85
+ undef_method :class_extension
86
+ end
87
+
88
+
89
+
90
+ # _____ _
91
+ # |_ _|__ ___| |_
92
+ # | |/ _ \/ __| __|
93
+ # | | __/\__ \ |_
94
+ # |_|\___||___/\__|
95
+ #
96
+
97
+ =begin test
98
+
99
+ require 'test/unit'
100
+
101
+ class TC_ClassMethods < Test::Unit::TestCase
102
+
103
+ # fixture
104
+
105
+ module N
106
+ class_extension do
107
+ def n ; 43 ; end
108
+ def s ; self ; end
109
+ end
110
+ extend class_extension
111
+ end
112
+
113
+ class X
114
+ include N
115
+ def n ; 11 ; end
116
+ end
117
+
118
+ module K
119
+ include N
120
+ class_extension do
121
+ def n ; super + 1 ; end
122
+ end
123
+ end
124
+
125
+ class Z
126
+ include K
127
+ end
128
+
129
+ # tests
130
+
131
+ def test_01
132
+ assert_equal( 43, N.n )
133
+ assert_equal( N, N.s )
134
+ end
135
+ def test_02
136
+ assert_equal( 43, X.n )
137
+ assert_equal( X, X.s )
138
+ end
139
+ def test_03
140
+ assert_equal( 11, X.new.n )
141
+ end
142
+ def test_04
143
+ assert_equal( 43, K.n ) #notic the difference!
144
+ assert_equal( K, K.s )
145
+ end
146
+ def test_05
147
+ assert_equal( 44, Z.n )
148
+ assert_equal( Z, Z.s )
149
+ end
150
+
151
+ end
152
+
153
+ =end
154
+
@@ -0,0 +1,175 @@
1
+ require 'hpricot'
2
+ require 'time'
3
+ require 'date'
4
+
5
+ %w(class-extension ofx sic).each do |fn|
6
+ require File.dirname(__FILE__) + "/#{fn}"
7
+ end
8
+
9
+ module OfxParser
10
+ VERSION = '1.0.0'
11
+
12
+ class OfxParser
13
+
14
+ # Creates and returns an Ofx instance when given a well-formed OFX document,
15
+ # complete with the mandatory key:pair header.
16
+ def self.parse(ofx)
17
+ ofx = ofx.respond_to?(:read) ? ofx.read.to_s : ofx.to_s
18
+
19
+ return Ofx.new if ofx == ""
20
+
21
+ header, body = pre_process(ofx)
22
+
23
+ ofx_out = parse_body(body)
24
+ ofx_out.header = header
25
+ ofx_out
26
+ end
27
+
28
+ # Designed to make the main OFX body parsable. This means adding closing tags
29
+ # to the SGML to make it parsable by hpricot.
30
+ #
31
+ # Returns an array of 2 elements:
32
+ # * header as a hash,
33
+ # * body as an evily pre-processed string ready for parsing by hpricot.
34
+ def self.pre_process(ofx)
35
+ header, body = ofx.split(/\n\n/)
36
+
37
+ header = Hash[*header.split(/:|\n/)]
38
+
39
+ body.gsub!(/>\s+</m, '><')
40
+ body.gsub!(/\s+</m, '<')
41
+ body.gsub!(/>\s+/m, '>')
42
+ body.gsub!(/<(\w+?)>([^<]+)/m, '<\1>\2</\1>')
43
+
44
+ [header, body]
45
+ end
46
+
47
+ # Takes an OFX datetime string of the format:
48
+ # * YYYYMMDDHHMMSS.XXX[gmt offset:tz name]
49
+ # * YYYYMMDD
50
+ # * YYYYMMDDHHMMSS
51
+ # * YYYYMMDDHHMMSS.XXX
52
+ #
53
+ # Returns a DateTime object. Milliseconds (XXX) are ignored.
54
+ def self.parse_datetime(date)
55
+ if /\A\s*
56
+ (\d{4})(\d{2})(\d{2}) ?# YYYYMMDD 1,2,3
57
+ (?:(\d{2})(\d{2})(\d{2}))? ?# HHMMSS - optional 4,5,6
58
+ (?:\.(\d{3}))? ?# .XXX - optional 7
59
+ (?:\[(-?\d+)\:\w{3}\])? ?# [-n:TZ] - optional 8,9
60
+ \s*\z/ix =~ date
61
+ year = $1.to_i
62
+ mon = $2.to_i
63
+ day = $3.to_i
64
+ hour = $4.to_i
65
+ min = $5.to_i
66
+ sec = $6.to_i
67
+ # DateTime does not support usecs.
68
+ # usec = 0
69
+ # usec = $7.to_f * 1000000 if $7
70
+ off = Rational($8.to_i, 24) # offset as a fraction of day. :|
71
+ DateTime.civil(year, mon, day, hour, min, sec, off)
72
+ end
73
+ end
74
+
75
+ private
76
+ def self.parse_body(body)
77
+ doc = Hpricot.XML(body)
78
+
79
+ ofx = Ofx.new
80
+
81
+ ofx.sign_on = build_signon((doc/"SIGNONMSGSRSV1/SONRS"))
82
+ ofx.bank_account = build_bank((doc/"BANKMSGSRSV1/STMTTRNRS")) unless (doc/"BANKMSGSRSV1").empty?
83
+ ofx.credit_card = build_credit((doc/"CREDITCARDMSGSRSV1/CCSTMTTRNRS")) unless (doc/"CREDITCARDMSGSRSV1").empty?
84
+ #build_investment((doc/"SIGNONMSGSRQV1"))
85
+
86
+ ofx
87
+ end
88
+
89
+ def self.build_signon(doc)
90
+ sign_on = SignOn.new
91
+ sign_on.status = build_status((doc/"STATUS"))
92
+ sign_on.date = parse_datetime((doc/"DTSERVER").inner_text)
93
+ sign_on.language = (doc/"LANGUAGE").inner_text
94
+
95
+ sign_on.institute = Institute.new
96
+ sign_on.institute.name = ((doc/"FI")/"ORG").inner_text
97
+ sign_on.institute.id = ((doc/"FI")/"FID").inner_text
98
+ sign_on
99
+ end
100
+
101
+ def self.build_bank(doc)
102
+ acct = BankAccount.new
103
+
104
+ acct.transaction_uid = (doc/"TRNUID").inner_text.strip
105
+ acct.number = (doc/"STMTRS/BANKACCTFROM/ACCTID").inner_text
106
+ acct.routing_number = (doc/"STMTRS/BANKACCTFROM/BANKID").inner_text
107
+ acct.type = (doc/"STMTRS/BANKACCTFROM/ACCTTYPE").inner_text.strip
108
+ acct.balance = (doc/"STMTRS/LEDGERBAL/BALAMT").inner_text
109
+ acct.balance_date = parse_datetime((doc/"STMTRS/LEDGERBAL/DTASOF").inner_text)
110
+
111
+ statement = Statement.new
112
+ statement.currency = (doc/"STMTRS/CURDEF").inner_text
113
+ statement.start_date = parse_datetime((doc/"STMTRS/BANKTRANLIST/DTSTART").inner_text)
114
+ statement.end_date = parse_datetime((doc/"STMTRS/BANKTRANLIST/DTEND").inner_text)
115
+ acct.statement = statement
116
+
117
+ statement.transactions = (doc/"STMTRS/BANKTRANLIST/STMTTRN").collect do |t|
118
+ build_transaction(t)
119
+ end
120
+
121
+ acct
122
+ end
123
+
124
+ def self.build_credit(doc)
125
+ acct = CreditAccount.new
126
+
127
+ acct.number = (doc/"CCSTMTRS/CCACCTFROM/ACCTID").inner_text
128
+ acct.transaction_uid = (doc/"TRNUID").inner_text.strip
129
+ acct.balance = (doc/"CCSTMTRS/LEDGERBAL/BALAMT").inner_text
130
+ acct.balance_date = parse_datetime((doc/"CCSTMTRS/LEDGERBAL/DTASOF").inner_text)
131
+ acct.remaining_credit = (doc/"CCSTMTRS/AVAILBAL/BALAMT").inner_text
132
+ acct.remaining_credit_date = parse_datetime((doc/"CCSTMTRS/AVAILBAL/DTASOF").inner_text)
133
+
134
+ statement = Statement.new
135
+ statement.currency = (doc/"CCSTMTRS/CURDEF").inner_text
136
+ statement.start_date = parse_datetime((doc/"CCSTMTRS/BANKTRANLIST/DTSTART").inner_text)
137
+ statement.end_date = parse_datetime((doc/"CCSTMTRS/BANKTRANLIST/DTEND").inner_text)
138
+ acct.statement = statement
139
+
140
+ statement.transactions = (doc/"CCSTMTRS/BANKTRANLIST/STMTTRN").collect do |t|
141
+ build_transaction(t)
142
+ end
143
+
144
+ acct
145
+ end
146
+
147
+ # for credit and bank transactions.
148
+ def self.build_transaction(t)
149
+ transaction = Transaction.new
150
+ transaction.type = (t/"TRNTYPE").inner_text
151
+ transaction.date = parse_datetime((t/"DTPOSTED").inner_text)
152
+ transaction.amount = (t/"TRNAMT").inner_text
153
+ transaction.fit_id = (t/"FITID").inner_text
154
+ transaction.payee = (t/"PAYEE").inner_text + (t/"NAME").inner_text
155
+ transaction.memo = (t/"MEMO").inner_text
156
+ transaction.sic = (t/"SIC").inner_text
157
+ transaction.check_number = (t/"CHECKNUM").inner_text if transaction.type == :CHECK
158
+ transaction
159
+ end
160
+
161
+
162
+ def self.build_investment(doc)
163
+
164
+ end
165
+
166
+ def self.build_status(doc)
167
+ status = Status.new
168
+ status.code = (doc/"CODE").inner_text
169
+ status.severity = (doc/"SEVERITY").inner_text
170
+ status.message = (doc/"MESSAGE").inner_text
171
+ status
172
+ end
173
+
174
+ end
175
+ end