remove --default-account option
[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 $default_account_income = 'Income:Unknown';
127 my $default_account_expenses = 'Expenses:Unknown';
128
129 my $ledger = App::HomeBank2Ledger::Ledger->new;
130
131 my $transactions = $homebank->sorted_transactions;
132 my $accounts = $homebank->accounts;
133 my $categories = $homebank->categories;
134
135 # determine full Ledger account names
136 for my $account (@$accounts) {
137 my $type = $ACCOUNT_TYPES{$account->{type}} || $UNKNOWN_ACCOUNT;
138 $account->{ledger_name} = "${type}:$account->{name}";
139 }
140 for my $category (@$categories) {
141 my $type = $category->{flags}{income} ? 'Income' : 'Expenses';
142 my $full_name = $homebank->full_category_name($category->{key});
143 $category->{ledger_name} = "${type}:${full_name}";
144 }
145
146 # handle renaming and marking excluded accounts
147 for my $item (@$accounts, @$categories) {
148 while (my ($re, $replacement) = each %{$opts->{rename_accounts}}) {
149 $item->{ledger_name} =~ s/$re/$replacement/;
150 }
151 for my $re (@{$opts->{exclude_accounts}}) {
152 $item->{excluded} = 1 if $item->{ledger_name} =~ /$re/;
153 }
154 }
155 while (my ($re, $replacement) = each %{$opts->{rename_accounts}}) {
156 $default_account_income =~ s/$re/$replacement/;
157 $default_account_expenses =~ s/$re/$replacement/;
158 }
159
160 my $has_initial_balance = grep { $_->{initial} && !$_->{excluded} } @$accounts;
161
162 if ($opts->{accounts}) {
163 my @accounts = map { $_->{ledger_name} } grep { !$_->{excluded} } @$accounts, @$categories;
164
165 push @accounts, $default_account_income, $default_account_expenses;
166 push @accounts, $OPENING_BALANCES_ACCOUNT if $has_initial_balance;
167
168 $ledger->add_accounts(@accounts);
169 }
170
171 if ($opts->{payees}) {
172 my $payees = $homebank->payees;
173 my @payees = map { $_->{name} } @$payees;
174
175 $ledger->add_payees(@payees);
176 }
177
178 if ($opts->{tags}) {
179 my $tags = $homebank->tags;
180
181 $ledger->add_tags(@$tags);
182 }
183
184 my %commodities;
185
186 for my $currency (@{$homebank->currencies}) {
187 my $commodity = {
188 symbol => $currency->{symbol},
189 format => $homebank->format_amount(1_000, $currency),
190 iso => $currency->{iso},
191 name => $currency->{name},
192 };
193 $commodities{$currency->{key}} = {
194 %$commodity,
195 syprf => $currency->{syprf},
196 dchar => $currency->{dchar},
197 gchar => $currency->{gchar},
198 frac => $currency->{frac},
199 };
200
201 $ledger->add_commodities($commodity) if $opts->{commodities};
202 }
203
204 if ($has_initial_balance) {
205 # transactions are sorted, so the first transaction is the oldest
206 my $first_date = $opts->{opening_date} || $transactions->[0]{date};
207 if ($first_date !~ /^\d{4}-\d{2}-\d{2}$/) {
208 die "Opening date must be in the form YYYY-MM-DD.\n";
209 }
210
211 my @postings;
212
213 for my $account (@$accounts) {
214 next if !$account->{initial} || $account->{excluded};
215
216 push @postings, {
217 account => $account->{ledger_name},
218 amount => $account->{initial},
219 commodity => $commodities{$account->{currency}},
220 };
221 }
222
223 push @postings, {
224 account => $OPENING_BALANCES_ACCOUNT,
225 };
226
227 $ledger->add_transactions({
228 date => $first_date,
229 payee => 'Opening Balance',
230 status => 'cleared',
231 postings => \@postings,
232 });
233 }
234
235 my %seen;
236
237 TRANSACTION:
238 for my $transaction (@$transactions) {
239 next if $seen{$transaction->{transfer_key} || ''};
240
241 my $account = $homebank->find_account_by_key($transaction->{account});
242 my $amount = $transaction->{amount};
243 my $status = $STATUS_SYMBOLS{$transaction->{status} || ''} || '';
244 my $paymode = $transaction->{paymode} || ''; # internaltransfer
245 my $memo = $transaction->{wording} || '';
246 my $payee = $homebank->find_payee_by_key($transaction->{payee});
247 my $tags = _split_tags($transaction->{tags});
248
249 my @postings;
250
251 push @postings, {
252 account => $account->{ledger_name},
253 amount => $amount,
254 commodity => $commodities{$account->{currency}},
255 payee => $payee->{name},
256 memo => $memo,
257 status => $status,
258 tags => $tags,
259 };
260
261 if ($paymode eq 'internaltransfer') {
262 my $paired_transaction = $homebank->find_transaction_transfer_pair($transaction);
263
264 my $dst_account = $homebank->find_account_by_key($transaction->{dst_account});
265 if (!$dst_account) {
266 if ($paired_transaction) {
267 $dst_account = $homebank->find_account_by_key($paired_transaction->{account});
268 }
269 if (!$dst_account) {
270 warn "Skipping internal transfer transaction with no destination account.\n";
271 next TRANSACTION;
272 }
273 }
274
275 $seen{$transaction->{transfer_key}}++ if $transaction->{transfer_key};
276 $seen{$paired_transaction->{transfer_key}}++ if $paired_transaction->{transfer_key};
277
278 my $paired_payee = $homebank->find_payee_by_key($paired_transaction->{payee});
279
280 push @postings, {
281 account => $dst_account->{ledger_name},
282 amount => $paired_transaction->{amount} || -$transaction->{amount},
283 commodity => $commodities{$dst_account->{currency}},
284 payee => $paired_payee->{name},
285 memo => $paired_transaction->{wording} || '',
286 status => $STATUS_SYMBOLS{$paired_transaction->{status} || ''} || $status,
287 tags => _split_tags($paired_transaction->{tags}),
288 };
289 }
290 elsif ($transaction->{flags}{split}) {
291 my @amounts = split(/\|\|/, $transaction->{split_amount} || '');
292 my @memos = split(/\|\|/, $transaction->{split_memo} || '');
293 my @categories = split(/\|\|/, $transaction->{split_category} || '');
294
295 for (my $i = 0; $amounts[$i]; ++$i) {
296 my $amount = -$amounts[$i];
297 my $category = $homebank->find_category_by_key($categories[$i]);
298 my $memo = $memos[$i] || '';
299 my $other_account = $category ? $category->{ledger_name}
300 : $amount < 0 ? $default_account_income
301 : $default_account_expenses;
302
303 push @postings, {
304 account => $other_account,
305 commodity => $commodities{$account->{currency}},
306 amount => $amount,
307 payee => $payee->{name},
308 memo => $memo,
309 status => $status,
310 tags => $tags,
311 };
312 }
313 }
314 else { # with or without category
315 my $amount = -$transaction->{amount};
316 my $category = $homebank->find_category_by_key($transaction->{category});
317 my $other_account = $category ? $category->{ledger_name}
318 : $amount < 0 ? $default_account_income
319 : $default_account_expenses;
320
321 push @postings, {
322 account => $other_account,
323 commodity => $commodities{$account->{currency}},
324 amount => $amount,
325 payee => $payee->{name},
326 memo => $memo,
327 status => $status,
328 tags => $tags,
329 };
330 }
331
332 # skip excluded accounts
333 for my $posting (@postings) {
334 for my $re (@{$opts->{exclude_accounts}}) {
335 next TRANSACTION if $posting->{account} =~ /$re/;
336 }
337 }
338
339 $ledger->add_transactions({
340 date => $transaction->{date},
341 payee => $payee->{name},
342 memo => $memo,
343 postings => \@postings,
344 });
345 }
346
347 return $ledger;
348 }
349
350 =method print_to_file
351
352 $app->print_to_file($str);
353 $app->print_to_file($str, $filepath);
354
355 Print a string to a file (or STDOUT).
356
357 =cut
358
359 sub print_to_file {
360 my $self = shift;
361 my $str = shift;
362 my $filepath = shift;
363
364 my $out_fh = \*STDOUT;
365 if ($filepath) {
366 open($out_fh, '>', $filepath) or die "open failed: $!";
367 }
368 print $out_fh $str;
369 }
370
371 =method parse_args
372
373 $opts = $app->parse_args(@args);
374
375 Parse command-line arguments.
376
377 =cut
378
379 sub parse_args {
380 my $self = shift;
381 my @args = @_;
382
383 my %opts = (
384 version => 0,
385 help => 0,
386 manual => 0,
387 input => undef,
388 output => undef,
389 format => 'ledger',
390 account_width => 40,
391 accounts => 1,
392 payees => 1,
393 tags => 1,
394 commodities => 1,
395 opening_date => '',
396 rename_accounts => {},
397 exclude_accounts => [],
398 );
399
400 GetOptionsFromArray(\@args,
401 'version|V' => \$opts{version},
402 'help|h|?' => \$opts{help},
403 'manual|man' => \$opts{manual},
404 'input|file|i=s' => \$opts{input},
405 'output|o=s' => \$opts{output},
406 'format|f=s' => \$opts{format},
407 'account-width=i' => \$opts{account_width},
408 'accounts!' => \$opts{accounts},
409 'payees!' => \$opts{payees},
410 'tags!' => \$opts{tags},
411 'commodities!' => \$opts{commodities},
412 'opening-date=s' => \$opts{opening_date},
413 'rename-account|r=s' => \%{$opts{rename_accounts}},
414 'exclude-account|x=s' => \@{$opts{exclude_accounts}},
415 ) or pod2usage(-exitval => 1, -verbose => 99, -sections => [qw(SYNOPSIS OPTIONS)]);
416
417 $opts{input} = shift @args if !$opts{input};
418
419 return \%opts;
420 }
421
422 sub _split_tags {
423 my $tags = shift;
424 return [split(/\h+/, $tags || '')];
425 }
426
427 1;
This page took 0.066063 seconds and 4 git commands to generate.