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