]> Dogcows Code - chaz/homebank2ledger/blob - lib/App/HomeBank2Ledger.pm
Version 0.009
[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;
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.009'; # 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 $default_account_income = 'Income:Unknown';
97 my $default_account_expenses = 'Expenses:Unknown';
98
99 my $ledger = App::HomeBank2Ledger::Ledger->new;
100
101 my $transactions = $homebank->sorted_transactions;
102 my $accounts = $homebank->accounts;
103 my $categories = $homebank->categories;
104 my @budget;
105
106 # determine full Ledger account names
107 for my $account (@$accounts) {
108 my $type = $ACCOUNT_TYPES{$account->{type}} || $UNKNOWN_ACCOUNT;
109 $account->{ledger_name} = "${type}:$account->{name}";
110 }
111 for my $category (@$categories) {
112 my $type = $category->{flags}{income} ? 'Income' : 'Expenses';
113 my $full_name = $homebank->full_category_name($category->{key});
114 $category->{ledger_name} = "${type}:${full_name}";
115
116 if ($opts->{budget} && $category->{flags}{budget}) {
117 for my $month_num ($category->{flags}{custom} ? (1 .. 12) : 0) {
118 my $amount = $category->{budget_amounts}[$month_num] || 0;
119 next if !$amount && !$category->{flags}{forced};
120
121 $budget[$month_num]{$category->{ledger_name}} = $amount;
122 }
123 }
124 }
125
126 # handle renaming and marking excluded accounts
127 for my $item (@$accounts, @$categories) {
128 while (my ($re, $replacement) = each %{$opts->{rename_accounts}}) {
129 $item->{ledger_name} =~ s/$re/$replacement/;
130 }
131 for my $re (@{$opts->{exclude_accounts}}) {
132 $item->{excluded} = 1 if $item->{ledger_name} =~ /$re/;
133 }
134 }
135 while (my ($re, $replacement) = each %{$opts->{rename_accounts}}) {
136 $default_account_income =~ s/$re/$replacement/;
137 $default_account_expenses =~ s/$re/$replacement/;
138 }
139
140 my $has_initial_balance = grep { $_->{initial} && !$_->{excluded} } @$accounts;
141
142 if ($opts->{accounts}) {
143 my @accounts = map { $_->{ledger_name} } grep { !$_->{excluded} } @$accounts, @$categories;
144
145 push @accounts, $default_account_income if !grep { $_ eq $default_account_income } @accounts;
146 push @accounts, $default_account_expenses if !grep { $_ eq $default_account_expenses } @accounts;
147 push @accounts, $OPENING_BALANCES_ACCOUNT if $has_initial_balance;
148
149 $ledger->add_accounts(@accounts);
150 }
151
152 if ($opts->{payees}) {
153 my $payees = $homebank->payees;
154 my @payees = map { $_->{name} } @$payees;
155
156 $ledger->add_payees(@payees);
157 }
158
159 if ($opts->{tags}) {
160 my $tags = $homebank->tags;
161
162 $ledger->add_tags(@$tags);
163 }
164
165 my %commodities;
166
167 for my $currency (@{$homebank->currencies}) {
168 my $commodity = {
169 symbol => $currency->{symbol},
170 format => $homebank->format_amount(1_000, $currency),
171 iso => $currency->{iso},
172 name => $currency->{name},
173 };
174 $commodities{$currency->{key}} = {
175 %$commodity,
176 syprf => $currency->{syprf},
177 dchar => $currency->{dchar},
178 gchar => $currency->{gchar},
179 frac => $currency->{frac},
180 };
181
182 $ledger->add_commodities($commodity) if $opts->{commodities};
183 }
184
185 my $first_date;
186 if ($has_initial_balance) {
187 # transactions are sorted, so the first transaction is the oldest
188 $first_date = $opts->{opening_date} || $transactions->[0]{date};
189 if ($first_date !~ /^\d{4}-\d{2}-\d{2}$/) {
190 die "Opening date must be in the form YYYY-MM-DD.\n";
191 }
192
193 my @postings;
194
195 for my $account (@$accounts) {
196 next if !$account->{initial} || $account->{excluded};
197
198 push @postings, {
199 account => $account->{ledger_name},
200 amount => $account->{initial},
201 commodity => $commodities{$account->{currency}},
202 };
203 }
204
205 push @postings, {
206 account => $OPENING_BALANCES_ACCOUNT,
207 };
208
209 $ledger->add_transactions({
210 date => $first_date,
211 payee => 'Opening Balance',
212 status => 'cleared',
213 postings => \@postings,
214 });
215 }
216
217 if ($opts->{budget}) {
218 my ($first_year) = $first_date =~ /^(\d{4})/;
219
220 for my $month_num (0 .. 12) {
221 next if !$budget[$month_num];
222
223 my $payee = 'Monthly';
224 if (0 < $month_num) {
225 my $year = $first_year;
226 $year += 1 if sprintf('%04d-%02d-99', $first_year, $month_num) lt $first_date;
227 my $date = sprintf('%04d-%02d', $year, $month_num);
228 $payee = "Every 12 months from ${date}";
229 }
230 # my @MONTHS = qw(ALL Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
231 # $payee = "Monthly this $MONTHS[$month_num]" if 0 < $month_num;
232
233 my @postings;
234
235 for my $account (sort keys %{$budget[$month_num]}) {
236 my $amount = $budget[$month_num]{$account};
237 push @postings, {
238 account => $account,
239 amount => -$amount,
240 commodity => $commodities{$homebank->base_currency},
241 }
242 }
243 push @postings, {
244 account => 'Assets',
245 };
246
247 $ledger->add_transactions({
248 date => '~',
249 payee => $payee,
250 postings => \@postings,
251 });
252 }
253 }
254
255 my %seen;
256
257 TRANSACTION:
258 for my $transaction (@$transactions) {
259 next if $seen{$transaction->{transfer_key} || ''};
260
261 my $account = $homebank->find_account_by_key($transaction->{account});
262 my $amount = $transaction->{amount};
263 my $status = $STATUS_SYMBOLS{$transaction->{status} || ''} || '';
264 my $memo = $transaction->{wording} || '';
265 my $payee = $homebank->find_payee_by_key($transaction->{payee});
266 my $tags = _split_tags($transaction->{tags});
267 my $date = $transaction->{date};
268
269 my @postings;
270
271 push @postings, {
272 date => $date,
273 account => $account->{ledger_name},
274 amount => $amount,
275 commodity => $commodities{$account->{currency}},
276 payee => $payee->{name},
277 note => $memo,
278 status => $status,
279 tags => $tags,
280 };
281
282 if ($transaction->{dst_account}) { # is an internal transfer
283 my $paired_transaction = $homebank->find_transaction_transfer_pair($transaction);
284
285 my $dst_account = $homebank->find_account_by_key($transaction->{dst_account});
286 if (!$dst_account) {
287 if ($paired_transaction) {
288 $dst_account = $homebank->find_account_by_key($paired_transaction->{account});
289 }
290 if (!$dst_account) {
291 warn "Skipping internal transfer transaction with no destination account.\n";
292 next TRANSACTION;
293 }
294 }
295
296 $seen{$transaction->{transfer_key}}++ if $transaction->{transfer_key};
297 $seen{$paired_transaction->{transfer_key}}++ if $paired_transaction->{transfer_key};
298
299 my $paired_date = $paired_transaction && $paired_transaction->{date};
300 my $paired_payee = $homebank->find_payee_by_key($paired_transaction->{payee});
301
302 push @postings, {
303 date => $paired_date,
304 account => $dst_account->{ledger_name},
305 amount => $paired_transaction->{amount} || -$transaction->{amount},
306 commodity => $commodities{$dst_account->{currency}},
307 payee => $paired_payee->{name},
308 note => $paired_transaction->{wording} || '',
309 status => $STATUS_SYMBOLS{$paired_transaction->{status} || ''} || $status,
310 tags => _split_tags($paired_transaction->{tags}),
311 };
312 }
313 elsif ($transaction->{flags}{split}) {
314 my @amounts = split(/\|\|/, $transaction->{split_amount} || '');
315 my @memos = split(/\|\|/, $transaction->{split_memo} || '');
316 my @categories = split(/\|\|/, $transaction->{split_category} || '');
317
318 for (my $i = 0; $amounts[$i]; ++$i) {
319 my $amount = -$amounts[$i];
320 my $category = $homebank->find_category_by_key($categories[$i]);
321 my $memo = $memos[$i] || '';
322 my $other_account = $category ? $category->{ledger_name}
323 : $amount < 0 ? $default_account_income
324 : $default_account_expenses;
325
326 push @postings, {
327 account => $other_account,
328 commodity => $commodities{$account->{currency}},
329 amount => $amount,
330 payee => $payee->{name},
331 note => $memo,
332 status => $status,
333 tags => $tags,
334 };
335 }
336 }
337 else { # normal transaction with or without category
338 my $amount = -$transaction->{amount};
339 my $category = $homebank->find_category_by_key($transaction->{category});
340 my $other_account = $category ? $category->{ledger_name}
341 : $amount < 0 ? $default_account_income
342 : $default_account_expenses;
343
344 push @postings, {
345 account => $other_account,
346 commodity => $commodities{$account->{currency}},
347 amount => $amount,
348 payee => $payee->{name},
349 note => $memo,
350 status => $status,
351 tags => $tags,
352 };
353 }
354
355 # skip excluded accounts
356 for my $posting (@postings) {
357 for my $re (@{$opts->{exclude_accounts}}) {
358 next TRANSACTION if $posting->{account} =~ /$re/;
359 }
360 }
361
362 $ledger->add_transactions({
363 date => $date,
364 payee => $payee->{name},
365 memo => $memo,
366 postings => \@postings,
367 });
368 }
369
370 return $ledger;
371 }
372
373
374 sub print_to_file {
375 my $self = shift;
376 my $str = shift;
377 my $filepath = shift;
378
379 my $out_fh = \*STDOUT;
380 if ($filepath) {
381 open($out_fh, '>', $filepath) or die "open failed: $!";
382 }
383 print $out_fh $str;
384 }
385
386
387 sub parse_args {
388 my $self = shift;
389 my @args = @_;
390
391 my %opts = (
392 version => 0,
393 help => 0,
394 manual => 0,
395 input => undef,
396 output => undef,
397 format => 'ledger',
398 account_width => 40,
399 accounts => 1,
400 payees => 1,
401 tags => 1,
402 commodities => 1,
403 budget => 1,
404 opening_date => '',
405 rename_accounts => {},
406 exclude_accounts => [],
407 );
408
409 GetOptionsFromArray(\@args,
410 'version|V' => \$opts{version},
411 'help|h|?' => \$opts{help},
412 'manual|man' => \$opts{manual},
413 'input|file|i=s' => \$opts{input},
414 'output|o=s' => \$opts{output},
415 'format|f=s' => \$opts{format},
416 'account-width=i' => \$opts{account_width},
417 'accounts!' => \$opts{accounts},
418 'payees!' => \$opts{payees},
419 'tags!' => \$opts{tags},
420 'commodities!' => \$opts{commodities},
421 'budget!' => \$opts{budget},
422 'opening-date=s' => \$opts{opening_date},
423 'rename-account|r=s' => \%{$opts{rename_accounts}},
424 'exclude-account|x=s' => \@{$opts{exclude_accounts}},
425 ) or pod2usage(-exitval => 1, -verbose => 99, -sections => [qw(SYNOPSIS OPTIONS)]);
426
427 $opts{input} = shift @args if !$opts{input};
428 $opts{budget} = 0 if lc($opts{format}) ne 'ledger';
429
430 return \%opts;
431 }
432
433 sub _split_tags {
434 my $tags = shift;
435 return [split(/\h+/, $tags || '')];
436 }
437
438 1;
439
440 __END__
441
442 =pod
443
444 =encoding UTF-8
445
446 =head1 NAME
447
448 App::HomeBank2Ledger - A tool to convert HomeBank files to Ledger format
449
450 =head1 VERSION
451
452 version 0.009
453
454 =head1 SYNOPSIS
455
456 App::HomeBank2Ledger->main(@args);
457
458 =head1 DESCRIPTION
459
460 This module is part of the L<homebank2ledger> script.
461
462 =head1 METHODS
463
464 =head2 main
465
466 App::HomeBank2Ledger->main(@args);
467
468 Run the script and exit; does not return.
469
470 =head2 formatter
471
472 $formatter = $app->formatter($homebank, $opts);
473
474 Generate a L<App::HomeBank2Ledger::Formatter>.
475
476 =head2 convert_homebank_to_ledger
477
478 my $ledger = $app->convert_homebank_to_ledger($homebank, $opts);
479
480 Converts a L<File::HomeBank> to a L<App::HomeBank2Ledger::Ledger>.
481
482 =head2 print_to_file
483
484 $app->print_to_file($str);
485 $app->print_to_file($str, $filepath);
486
487 Print a string to a file (or STDOUT).
488
489 =head2 parse_args
490
491 $opts = $app->parse_args(@args);
492
493 Parse command-line arguments.
494
495 =head1 BUGS
496
497 Please report any bugs or feature requests on the bugtracker website
498 L<https://github.com/chazmcgarvey/homebank2ledger/issues>
499
500 When submitting a bug or request, please include a test-file or a
501 patch to an existing test-file that illustrates the bug or desired
502 feature.
503
504 =head1 AUTHOR
505
506 Charles McGarvey <chazmcgarvey@brokenzipper.com>
507
508 =head1 COPYRIGHT AND LICENSE
509
510 This software is Copyright (c) 2019 by Charles McGarvey.
511
512 This is free software, licensed under:
513
514 The MIT (X11) License
515
516 =cut
This page took 0.060982 seconds and 4 git commands to generate.