]> Dogcows Code - chaz/homebank2ledger/blob - lib/App/HomeBank2Ledger.pm
Version 0.003
[chaz/homebank2ledger] / lib / App / HomeBank2Ledger.pm
1 package App::HomeBank2Ledger;
2 # ABSTRACT: A tool to convert HomeBank files to Ledger format
3
4
5 use warnings FATAL => 'all'; # temp fatal all
6 use strict;
7
8 use App::HomeBank2Ledger::Formatter;
9 use App::HomeBank2Ledger::Ledger;
10 use File::HomeBank;
11 use Getopt::Long 2.38 qw(GetOptionsFromArray);
12 use Pod::Usage;
13
14 our $VERSION = '0.003'; # VERSION
15
16 my %ACCOUNT_TYPES = ( # map HomeBank account types to Ledger accounts
17 bank => 'Assets:Bank',
18 cash => 'Assets:Cash',
19 asset => 'Assets:Fixed Assets',
20 creditcard => 'Liabilities:Credit Card',
21 liability => 'Liabilities',
22 stock => 'Assets:Stock',
23 mutualfund => 'Assets:Mutual Fund',
24 income => 'Income',
25 expense => 'Expenses',
26 equity => 'Equity',
27 );
28 my %STATUS_SYMBOLS = (
29 cleared => 'cleared',
30 reconciled => 'cleared',
31 remind => 'pending',
32 );
33 my $UNKNOWN_ACCOUNT = 'Assets:Unknown';
34 my $OPENING_BALANCES_ACCOUNT = 'Equity:Opening Balances';
35
36
37 sub main {
38 my $class = shift;
39 my $self = bless {}, $class;
40
41 my $opts = $self->parse_args(@_);
42
43 if ($opts->{version}) {
44 print "homebank2ledger ${VERSION}\n";
45 exit 0;
46 }
47 if ($opts->{help}) {
48 pod2usage(-exitval => 0, -verbose => 99, -sections => [qw(NAME SYNOPSIS OPTIONS)]);
49 }
50 if ($opts->{manual}) {
51 pod2usage(-exitval => 0, -verbose => 2);
52 }
53 if (!$opts->{input}) {
54 print STDERR "Input file is required.\n";
55 exit(1);
56 }
57
58 my $homebank = File::HomeBank->new(file => $opts->{input});
59
60 my $formatter = eval { $self->formatter($homebank, $opts) };
61 if (my $err = $@) {
62 if ($err =~ /^Invalid formatter/) {
63 print STDERR "Invalid format: $opts->{format}\n";
64 exit 2;
65 }
66 die $err;
67 }
68
69 my $ledger = $self->convert_homebank_to_ledger($homebank, $opts);
70
71 $self->print_to_file($formatter->format($ledger), $opts->{output});
72
73 exit 0;
74 }
75
76
77 sub formatter {
78 my $self = shift;
79 my $homebank = shift;
80 my $opts = shift || {};
81
82 return App::HomeBank2Ledger::Formatter->new(
83 type => $opts->{format},
84 account_width => $opts->{account_width},
85 name => $homebank->title,
86 file => $homebank->file,
87 );
88 }
89
90
91 sub convert_homebank_to_ledger {
92 my $self = shift;
93 my $homebank = shift;
94 my $opts = shift || {};
95
96 my $ledger = App::HomeBank2Ledger::Ledger->new;
97
98 my $transactions = $homebank->sorted_transactions;
99 my $accounts = $homebank->accounts;
100 my $categories = $homebank->categories;
101
102 # determine full Ledger account names
103 for my $account (@$accounts) {
104 my $type = $ACCOUNT_TYPES{$account->{type}} || $UNKNOWN_ACCOUNT;
105 $account->{ledger_name} = "${type}:$account->{name}";
106 }
107 for my $category (@$categories) {
108 my $type = $category->{flags}{income} ? 'Income' : 'Expenses';
109 my $full_name = $homebank->full_category_name($category->{key});
110 $category->{ledger_name} = "${type}:${full_name}";
111 }
112
113 # handle renaming and marking excluded accounts
114 for my $item (@$accounts, @$categories) {
115 while (my ($re, $replacement) = each %{$opts->{rename_accounts}}) {
116 $item->{ledger_name} =~ s/$re/$replacement/;
117 }
118 for my $re (@{$opts->{exclude_accounts}}) {
119 $item->{excluded} = 1 if $item->{ledger_name} =~ /$re/;
120 }
121 }
122
123 my $has_initial_balance = grep { $_->{initial} && !$_->{excluded} } @$accounts;
124
125 if ($opts->{accounts}) {
126 my @accounts = map { $_->{ledger_name} } grep { !$_->{excluded} } @$accounts, @$categories;
127
128 push @accounts, $opts->{default_account};
129 push @accounts, $OPENING_BALANCES_ACCOUNT if $has_initial_balance;
130
131 $ledger->add_accounts(@accounts);
132 }
133
134 if ($opts->{payees}) {
135 my $payees = $homebank->payees;
136 my @payees = map { $_->{name} } @$payees;
137
138 $ledger->add_payees(@payees);
139 }
140
141 if ($opts->{tags}) {
142 my $tags = $homebank->tags;
143
144 $ledger->add_tags(@$tags);
145 }
146
147 my %commodities;
148
149 for my $currency (@{$homebank->currencies}) {
150 my $commodity = {
151 symbol => $currency->{symbol},
152 format => $homebank->format_amount(1_000, $currency),
153 iso => $currency->{iso},
154 name => $currency->{name},
155 };
156 $commodities{$currency->{key}} = {
157 %$commodity,
158 syprf => $currency->{syprf},
159 dchar => $currency->{dchar},
160 gchar => $currency->{gchar},
161 frac => $currency->{frac},
162 };
163
164 $ledger->add_commodities($commodity) if $opts->{commodities};
165 }
166
167 if ($has_initial_balance) {
168 # transactions are sorted, so the first transaction is the oldest
169 my $first_date = $opts->{opening_date} || $transactions->[0]{date};
170 if ($first_date !~ /^\d{4}-\d{2}-\d{2}$/) {
171 die "Opening date must be in the form YYYY-MM-DD.\n";
172 }
173
174 my @postings;
175
176 for my $account (@$accounts) {
177 next if !$account->{initial} || $account->{excluded};
178
179 push @postings, {
180 account => $account->{ledger_name},
181 amount => $account->{initial},
182 commodity => $commodities{$account->{currency}},
183 };
184 }
185
186 push @postings, {
187 account => $OPENING_BALANCES_ACCOUNT,
188 };
189
190 $ledger->add_transactions({
191 date => $first_date,
192 payee => 'Opening Balance',
193 status => 'cleared',
194 postings => \@postings,
195 });
196 }
197
198 my %seen;
199
200 TRANSACTION:
201 for my $transaction (@$transactions) {
202 next if $seen{$transaction->{transfer_key} || ''};
203
204 my $account = $homebank->find_account_by_key($transaction->{account});
205 my $amount = $transaction->{amount};
206 my $status = $STATUS_SYMBOLS{$transaction->{status} || ''} || '';
207 my $paymode = $transaction->{paymode} || ''; # internaltransfer
208 my $memo = $transaction->{wording} || '';
209 my $payee = $homebank->find_payee_by_key($transaction->{payee});
210 my $tags = _split_tags($transaction->{tags});
211
212 my @postings;
213
214 push @postings, {
215 account => $account->{ledger_name},
216 amount => $amount,
217 commodity => $commodities{$account->{currency}},
218 payee => $payee->{name},
219 memo => $memo,
220 status => $status,
221 tags => $tags,
222 };
223
224 if ($paymode eq 'internaltransfer') {
225 my $paired_transaction = $homebank->find_transaction_transfer_pair($transaction);
226
227 my $dst_account = $homebank->find_account_by_key($transaction->{dst_account});
228 if (!$dst_account) {
229 if ($paired_transaction) {
230 $dst_account = $homebank->find_account_by_key($paired_transaction->{account});
231 }
232 if (!$dst_account) {
233 warn "Skipping internal transfer transaction with no destination account.\n";
234 next TRANSACTION;
235 }
236 }
237
238 $seen{$transaction->{transfer_key}}++ if $transaction->{transfer_key};
239 $seen{$paired_transaction->{transfer_key}}++ if $paired_transaction->{transfer_key};
240
241 my $paired_payee = $homebank->find_payee_by_key($paired_transaction->{payee});
242
243 push @postings, {
244 account => $dst_account->{ledger_name},
245 amount => $paired_transaction->{amount} || -$transaction->{amount},
246 commodity => $commodities{$dst_account->{currency}},
247 payee => $paired_payee->{name},
248 memo => $paired_transaction->{wording} || '',
249 status => $STATUS_SYMBOLS{$paired_transaction->{status} || ''} || $status,
250 tags => _split_tags($paired_transaction->{tags}),
251 };
252 }
253 elsif ($transaction->{flags}{split}) {
254 my @amounts = split(/\|\|/, $transaction->{split_amount} || '');
255 my @memos = split(/\|\|/, $transaction->{split_memo} || '');
256 my @categories = split(/\|\|/, $transaction->{split_category} || '');
257
258 for (my $i = 0; $amounts[$i]; ++$i) {
259 my $amount = -$amounts[$i];
260 my $category = $homebank->find_category_by_key($categories[$i]);
261 my $memo = $memos[$i] || '';
262 my $other_account = $category ? $category->{ledger_name} : $opts->{default_account};
263
264 push @postings, {
265 account => $other_account,
266 commodity => $commodities{$account->{currency}},
267 amount => $amount,
268 payee => $payee->{name},
269 memo => $memo,
270 status => $status,
271 tags => $tags,
272 };
273 }
274 }
275 else { # with or without category
276 my $category = $homebank->find_category_by_key($transaction->{category});
277 my $other_account = $category ? $category->{ledger_name} : $opts->{default_account};
278 push @postings, {
279 account => $other_account,
280 commodity => $commodities{$account->{currency}},
281 amount => -$transaction->{amount},
282 payee => $payee->{name},
283 memo => $memo,
284 status => $status,
285 tags => $tags,
286 };
287 }
288
289 # skip excluded accounts
290 for my $posting (@postings) {
291 for my $re (@{$opts->{exclude_accounts}}) {
292 next TRANSACTION if $posting->{account} =~ /$re/;
293 }
294 }
295
296 $ledger->add_transactions({
297 date => $transaction->{date},
298 payee => $payee->{name},
299 memo => $memo,
300 postings => \@postings,
301 });
302 }
303
304 return $ledger;
305 }
306
307
308 sub print_to_file {
309 my $self = shift;
310 my $str = shift;
311 my $filepath = shift;
312
313 my $out_fh = \*STDOUT;
314 if ($filepath) {
315 open($out_fh, '>', $filepath) or die "open failed: $!";
316 }
317 print $out_fh $str;
318 }
319
320
321 sub parse_args {
322 my $self = shift;
323 my @args = @_;
324
325 my %opts = (
326 version => 0,
327 help => 0,
328 manual => 0,
329 input => undef,
330 output => undef,
331 format => 'ledger',
332 account_width => 40,
333 accounts => 1,
334 payees => 1,
335 tags => 1,
336 commodities => 1,
337 opening_date => '',
338 default_account => 'Expenses:No Category',
339 rename_accounts => {},
340 exclude_accounts => [],
341 );
342
343 GetOptionsFromArray(\@args,
344 'version|V' => \$opts{version},
345 'help|h|?' => \$opts{help},
346 'manual|man' => \$opts{manual},
347 'input|file|i=s' => \$opts{input},
348 'output|o=s' => \$opts{output},
349 'format|f=s' => \$opts{format},
350 'account-width=i' => \$opts{account_width},
351 'accounts!' => \$opts{accounts},
352 'payees!' => \$opts{payees},
353 'tags!' => \$opts{tags},
354 'commodities!' => \$opts{commodities},
355 'opening-date=s' => \$opts{opening_date},
356 'default-account=s' => \$opts{default_account},
357 'rename-account|r=s' => \%{$opts{rename_accounts}},
358 'exclude-account|x=s' => \@{$opts{exclude_accounts}},
359 ) or pod2usage(-exitval => 1, -verbose => 99, -sections => [qw(SYNOPSIS OPTIONS)]);
360
361 $opts{input} = shift @args if !$opts{input};
362
363 return \%opts;
364 }
365
366 sub _split_tags {
367 my $tags = shift;
368 return [split(/\h+/, $tags || '')];
369 }
370
371 1;
372
373 __END__
374
375 =pod
376
377 =encoding UTF-8
378
379 =head1 NAME
380
381 App::HomeBank2Ledger - A tool to convert HomeBank files to Ledger format
382
383 =head1 VERSION
384
385 version 0.003
386
387 =head1 SYNOPSIS
388
389 App::HomeBank2Ledger->main(@args);
390
391 =head1 DESCRIPTION
392
393 This module is part of the L<homebank2ledger> script.
394
395 =head1 METHODS
396
397 =head2 main
398
399 App::HomeBank2Ledger->main(@args);
400
401 Run the script and exit; does not return.
402
403 =head2 formatter
404
405 $formatter = $app->formatter($homebank, $opts);
406
407 Generate a L<App::HomeBank2Ledger::Formatter>.
408
409 =head2 convert_homebank_to_ledger
410
411 my $ledger = $app->convert_homebank_to_ledger($homebank, $opts);
412
413 Converts a L<File::HomeBank> to a L<App::HomeBank2Ledger::Ledger>.
414
415 =head2 print_to_file
416
417 $app->print_to_file($str);
418 $app->print_to_file($str, $filepath);
419
420 Print a string to a file (or STDOUT).
421
422 =head2 parse_args
423
424 $opts = $app->parse_args(@args);
425
426 Parse command-line arguments.
427
428 =head1 BUGS
429
430 Please report any bugs or feature requests on the bugtracker website
431 L<https://github.com/chazmcgarvey/homebank2ledger/issues>
432
433 When submitting a bug or request, please include a test-file or a
434 patch to an existing test-file that illustrates the bug or desired
435 feature.
436
437 =head1 AUTHOR
438
439 Charles McGarvey <chazmcgarvey@brokenzipper.com>
440
441 =head1 COPYRIGHT AND LICENSE
442
443 This software is Copyright (c) 2019 by Charles McGarvey.
444
445 This is free software, licensed under:
446
447 The MIT (X11) License
448
449 =cut
This page took 0.057273 seconds and 4 git commands to generate.