]> Dogcows Code - chaz/homebank2ledger/blob - lib/App/HomeBank2Ledger/Formatter/Beancount.pm
Version 0.009
[chaz/homebank2ledger] / lib / App / HomeBank2Ledger / Formatter / Beancount.pm
1 package App::HomeBank2Ledger::Formatter::Beancount;
2 # ABSTRACT: Beancount formatter
3
4
5 use v5.10.1; # defined-or
6 use warnings;
7 use strict;
8
9 use App::HomeBank2Ledger::Util qw(commify rtrim);
10 use Scalar::Util qw(looks_like_number);
11
12 use parent 'App::HomeBank2Ledger::Formatter';
13
14 our $VERSION = '0.009'; # VERSION
15
16 my %STATUS_SYMBOLS = (
17 cleared => '*',
18 pending => '!',
19 );
20 my $UNKNOWN_DATE = '0001-01-01';
21
22 sub _croak { require Carp; Carp::croak(@_) }
23
24 sub format {
25 my $self = shift;
26 my $ledger = shift;
27
28 my @out = (
29 $self->format_header,
30 $self->format_accounts($ledger),
31 $self->format_commodities($ledger),
32 # $self->format_payees,
33 # $self->format_tags,
34 $self->format_transactions($ledger),
35 );
36
37 return join($/, map { rtrim($_) } @out);
38 }
39
40
41 sub format_header {
42 my $self = shift;
43
44 my @out;
45
46 if (my $name = $self->name) {
47 push @out, "; Name: $name";
48 }
49 if (my $file = $self->file) {
50 push @out, "; File: $file";
51 }
52
53 push @out, '';
54
55 return @out;
56 }
57
58
59 sub format_accounts {
60 my $self = shift;
61 my $ledger = shift;
62
63 my @out;
64
65 for my $account (sort @{$ledger->accounts}) {
66 my $oldest_transaction = $self->_find_oldest_transaction_by_account($account, $ledger);
67 my $account_date = $oldest_transaction->{date} || $UNKNOWN_DATE;
68 $account = $self->_format_account($account);
69
70 push @out, "${account_date} open ${account}";
71 }
72 push @out, '';
73
74 return @out;
75 }
76
77
78 sub format_commodities {
79 my $self = shift;
80 my $ledger = shift;
81
82 my @out;
83
84 for my $commodity (@{$ledger->commodities}) {
85 my $oldest_transaction = $self->_find_oldest_transaction_by_commodity($commodity, $ledger);
86 my $commodity_date = $oldest_transaction->{date} || $UNKNOWN_DATE;
87
88 push @out, "${commodity_date} commodity $commodity->{iso}";
89 push @out, ' name: '.$self->_format_string($commodity->{name}) if $commodity->{name};
90 }
91
92 push @out, '';
93
94 return @out;
95 }
96
97
98 sub format_transactions {
99 my $self = shift;
100 my $ledger = shift;
101
102 my @out;
103
104 for my $transaction (@{$ledger->transactions}) {
105 push @out, $self->_format_transaction($transaction);
106 }
107
108 return @out;
109 }
110
111 sub _format_transaction {
112 my $self = shift;
113 my $transaction = shift;
114
115 my $account_width = $self->account_width;
116
117 my $date = $transaction->{date};
118 my $status = $transaction->{status};
119 my $payee = $transaction->{payee} || '';
120 my $memo = $transaction->{note} // $transaction->{memo} // '';
121 my @postings = @{$transaction->{postings}};
122
123 my @out;
124
125 # figure out the Ledger transaction status
126 my $status_symbol = $STATUS_SYMBOLS{$status || ''};
127 if (!$status_symbol) {
128 my %posting_statuses = map { ($_->{status} || '') => 1 } @postings;
129 if (keys(%posting_statuses) == 1) {
130 my ($status) = keys %posting_statuses;
131 $status_symbol = $STATUS_SYMBOLS{$status || 'none'} || '';
132 }
133 }
134
135 push @out, sprintf('%s%s%s%s', $date,
136 $status_symbol && ' '.$status_symbol || ' *', # status (or "txn") is required
137 ($payee || $memo) && ' '.$self->_format_string($payee),
138 $memo && ' '.$self->_format_string($memo),
139 );
140
141 if (my %tags = map { $_ => 1 } map { @{$_->{tags} || []} } @postings) {
142 my @tags = map { "#$_" } keys %tags;
143 $out[-1] .= ' '.join(' ', @tags);
144 }
145
146 my $metadata = $transaction->{metadata} || {};
147 for my $key (sort keys %$metadata) {
148 my $value = looks_like_number($metadata->{$key}) ? $metadata->{$key}
149 : $self->_format_string($metadata->{$key});
150 push @out, " ; ${key}: ${value}";
151 }
152
153 for my $posting (@postings) {
154 my @line;
155
156 my $posting_status_symbol = '';
157 if (!$status_symbol) {
158 $posting_status_symbol = $STATUS_SYMBOLS{$posting->{status} || ''} || '';
159 }
160
161 my $account = $self->_format_account($posting->{account});
162
163 push @line, ($posting_status_symbol ? " $posting_status_symbol " : ' ');
164 push @line, sprintf("\%-${account_width}s", $account);
165 push @line, ' ';
166 if (defined $posting->{amount}) {
167 push @line, $self->_format_amount($posting->{amount}, $posting->{commodity});
168 my $lot = $posting->{lot} || {};
169 my $lot_price = $lot->{price} // $posting->{lot_price};
170 my $lot_date = $lot->{date} // $posting->{lot_date};
171 my $lot_ref = $lot->{ref} // $posting->{lot_ref};
172 if ($lot_price || $lot_date || $lot_ref) {
173 push @line, ' {',
174 join(', ',
175 $lot_price ? $self->_format_amount($lot_price->{amount}, $lot_price->{commodity}) : (),
176 $lot_date ? $lot_date : (),
177 $lot_ref ? $self->_format_string($lot_ref) : (),
178 ),
179 '}';
180 }
181 if (my $cost = $posting->{total_cost} // $posting->{cost}) {
182 my $is_total = defined $posting->{total_cost};
183 my $cost_symbol = $is_total ? '@@' : '@';
184 push @line, ' ', $cost_symbol, ' ',
185 $self->_format_amount($cost->{amount}, $cost->{commodity});
186 }
187 }
188
189 push @out, join('', @line);
190
191 my $metadata = $posting->{metadata} || {};
192 for my $key (sort keys %$metadata) {
193 my $value = looks_like_number($metadata->{$key}) ? $metadata->{$key}
194 : $self->_format_string($metadata->{$key});
195 push @out, " ; ${key}: ${value}";
196 }
197 }
198
199 push @out, '';
200
201 return @out;
202 }
203
204 sub _format_account {
205 my $self = shift;
206 my $account = shift;
207 $account =~ s/[^A-Za-z0-9:]+/-/g;
208 $account =~ s/-+/-/g;
209 $account =~ s/(?:^|(?<=:))([a-z])/uc($1)/eg;
210 return $account;
211 }
212
213 sub _format_string {
214 my $self = shift;
215 my $str = shift;
216 $str =~ s/"/\\"/g;
217 return "\"$str\"";
218 }
219
220 sub _format_amount {
221 my $self = shift;
222 my $amount = shift;
223 my $commodity = shift or _croak 'Must provide a valid currency';
224
225 my $format = "\% .$commodity->{frac}f";
226 my ($whole, $fraction) = split(/\./, sprintf($format, $amount));
227 $fraction ||= 0;
228
229 # beancount doesn't support different notations
230 my $num = commify($whole);
231 if ($commodity->{frac}) {
232 $num .= ".$fraction";
233 }
234
235 $num = "$num $commodity->{iso}";
236
237 return $num;
238 }
239
240 sub _find_oldest_transaction_by_account {
241 my $self = shift;
242 my $account = shift;
243 my $ledger = shift;
244
245 $account = $self->_format_account($account);
246
247 my $oldest = $self->{oldest_transaction_by_account};
248 if (!$oldest) {
249 # build index
250 for my $transaction (@{$ledger->transactions}) {
251 for my $posting (@{$transaction->{postings}}) {
252 my $account = $self->_format_account($posting->{account});
253
254 if ($transaction->{date} lt ($oldest->{$account}{date} || '9999-99-99')) {
255 $oldest->{$account} = $transaction;
256 }
257 }
258 }
259
260 $self->{oldest_transaction_by_account} = $oldest;
261 }
262
263 return $oldest->{$account};
264 }
265
266 sub _find_oldest_transaction_by_commodity {
267 my $self = shift;
268 my $commodity = shift;
269 my $ledger = shift;
270
271 my $oldest = $self->{oldest_transaction_by_commodity};
272 if (!$oldest) {
273 # build index
274 for my $transaction (@{$ledger->transactions}) {
275 for my $posting (@{$transaction->{postings}}) {
276 my $symbol = $posting->{commodity}{symbol};
277 next if !$symbol;
278
279 if ($transaction->{date} lt ($oldest->{$symbol}{date} || '9999-99-99')) {
280 $oldest->{$symbol} = $transaction;
281 }
282 }
283 }
284
285 $self->{oldest_transaction_by_commodity} = $oldest;
286 }
287
288 return $oldest->{$commodity->{symbol}};
289 }
290
291 1;
292
293 __END__
294
295 =pod
296
297 =encoding UTF-8
298
299 =head1 NAME
300
301 App::HomeBank2Ledger::Formatter::Beancount - Beancount formatter
302
303 =head1 VERSION
304
305 version 0.009
306
307 =head1 DESCRIPTION
308
309 This is a formatter for L<Beancount|https://beancount.github.io/docs/index.html>.
310
311 =head1 METHODS
312
313 =head2 format_header
314
315 @lines = $formatter->format_header;
316
317 Get formatted header. For example,
318
319 ; Name: My Finances
320 ; File: path/to/finances.xhb
321
322 =head2 format_accounts
323
324 @lines = $formatter->format_accounts($ledger);
325
326 Get formatted accounts. For example,
327
328 2003-02-14 open Assets:Bank:Credit-Union:Savings
329 2003-02-14 open Assets:Bank:Credit-Union:Checking
330 ...
331
332 =head2 format_commodities
333
334 @lines = $formatter->format_commodities($ledger);
335
336 Get formattted commodities. For example,
337
338 2003-02-14 commodity USD
339 name: "US Dollar"
340 ...
341
342 =head2 format_transactions
343
344 @lines = $formatter->format_transactions($ledger);
345
346 Get formatted transactions. For example,
347
348 2003-02-14 * "Opening Balance"
349 Assets:Bank:Credit-Union:Savings 458.21 USD
350 Assets:Bank:Credit-Union:Checking 194.17 USD
351 Equity:Opening-Balances
352
353 ...
354
355 =head1 SEE ALSO
356
357 L<App::HomeBank2Ledger::Formatter>
358
359 =head1 BUGS
360
361 Please report any bugs or feature requests on the bugtracker website
362 L<https://github.com/chazmcgarvey/homebank2ledger/issues>
363
364 When submitting a bug or request, please include a test-file or a
365 patch to an existing test-file that illustrates the bug or desired
366 feature.
367
368 =head1 AUTHOR
369
370 Charles McGarvey <chazmcgarvey@brokenzipper.com>
371
372 =head1 COPYRIGHT AND LICENSE
373
374 This software is Copyright (c) 2019 by Charles McGarvey.
375
376 This is free software, licensed under:
377
378 The MIT (X11) License
379
380 =cut
This page took 0.053406 seconds and 4 git commands to generate.