]> Dogcows Code - chaz/homebank2ledger/blob - lib/App/HomeBank2Ledger/Formatter/Beancount.pm
Version 0.010
[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.008'; # 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->{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_price = $posting->{lot_price};
169 my $lot_date = $posting->{lot_date};
170 my $lot_ref = $posting->{lot_ref};
171 if ($lot_price || $lot_date || $lot_ref) {
172 push @line, ' {',
173 join(', ',
174 $lot_price ? $self->_format_amount($lot_price->{amount}, $lot_price->{commodity}) : (),
175 $lot_date ? $lot_date : (),
176 $lot_ref ? $self->_format_string($lot_ref) : (),
177 ),
178 '}';
179 }
180 if (my $cost = $posting->{total_cost} // $posting->{cost}) {
181 my $is_total = defined $posting->{total_cost};
182 my $cost_symbol = $is_total ? '@@' : '@';
183 push @line, ' ', $cost_symbol, ' ',
184 $self->_format_amount($cost->{amount}, $cost->{commodity});
185 }
186 }
187
188 push @out, join('', @line);
189
190 my $metadata = $posting->{metadata} || {};
191 for my $key (sort keys %$metadata) {
192 my $value = looks_like_number($metadata->{$key}) ? $metadata->{$key}
193 : $self->_format_string($metadata->{$key});
194 push @out, " ; ${key}: ${value}";
195 }
196 }
197
198 push @out, '';
199
200 return @out;
201 }
202
203 sub _format_account {
204 my $self = shift;
205 my $account = shift;
206 $account =~ s/[^A-Za-z0-9:]+/-/g;
207 $account =~ s/-+/-/g;
208 $account =~ s/(?:^|(?<=:))([a-z])/uc($1)/eg;
209 return $account;
210 }
211
212 sub _format_string {
213 my $self = shift;
214 my $str = shift;
215 $str =~ s/"/\\"/g;
216 return "\"$str\"";
217 }
218
219 sub _format_amount {
220 my $self = shift;
221 my $amount = shift;
222 my $commodity = shift or _croak 'Must provide a valid currency';
223
224 my $format = "\% .$commodity->{frac}f";
225 my ($whole, $fraction) = split(/\./, sprintf($format, $amount));
226 $fraction ||= 0;
227
228 # beancount doesn't support different notations
229 my $num = commify($whole);
230 if ($commodity->{frac}) {
231 $num .= ".$fraction";
232 }
233
234 $num = "$num $commodity->{iso}";
235
236 return $num;
237 }
238
239 sub _find_oldest_transaction_by_account {
240 my $self = shift;
241 my $account = shift;
242 my $ledger = shift;
243
244 $account = $self->_format_account($account);
245
246 my $oldest = $self->{oldest_transaction_by_account};
247 if (!$oldest) {
248 # build index
249 for my $transaction (@{$ledger->transactions}) {
250 for my $posting (@{$transaction->{postings}}) {
251 my $account = $self->_format_account($posting->{account});
252
253 if ($transaction->{date} lt ($oldest->{$account}{date} || '9999-99-99')) {
254 $oldest->{$account} = $transaction;
255 }
256 }
257 }
258
259 $self->{oldest_transaction_by_account} = $oldest;
260 }
261
262 return $oldest->{$account};
263 }
264
265 sub _find_oldest_transaction_by_commodity {
266 my $self = shift;
267 my $commodity = shift;
268 my $ledger = shift;
269
270 my $oldest = $self->{oldest_transaction_by_commodity};
271 if (!$oldest) {
272 # build index
273 for my $transaction (@{$ledger->transactions}) {
274 for my $posting (@{$transaction->{postings}}) {
275 my $symbol = $posting->{commodity}{symbol};
276 next if !$symbol;
277
278 if ($transaction->{date} lt ($oldest->{$symbol}{date} || '9999-99-99')) {
279 $oldest->{$symbol} = $transaction;
280 }
281 }
282 }
283
284 $self->{oldest_transaction_by_commodity} = $oldest;
285 }
286
287 return $oldest->{$commodity->{symbol}};
288 }
289
290 1;
291
292 __END__
293
294 =pod
295
296 =encoding UTF-8
297
298 =head1 NAME
299
300 App::HomeBank2Ledger::Formatter::Beancount - Beancount formatter
301
302 =head1 VERSION
303
304 version 0.008
305
306 =head1 DESCRIPTION
307
308 This is a formatter for L<Beancount|http://furius.ca/beancount/>.
309
310 =head1 METHODS
311
312 =head2 format_header
313
314 @lines = $formatter->format_header;
315
316 Get formatted header. For example,
317
318 ; Name: My Finances
319 ; File: path/to/finances.xhb
320
321 =head2 format_accounts
322
323 @lines = $formatter->format_accounts($ledger);
324
325 Get formatted accounts. For example,
326
327 2003-02-14 open Assets:Bank:Credit-Union:Savings
328 2003-02-14 open Assets:Bank:Credit-Union:Checking
329 ...
330
331 =head2 format_commodities
332
333 @lines = $formatter->format_commodities($ledger);
334
335 Get formattted commodities. For example,
336
337 2003-02-14 commodity USD
338 name: "US Dollar"
339 ...
340
341 =head2 format_transactions
342
343 @lines = $formatter->format_transactions($ledger);
344
345 Get formatted transactions. For example,
346
347 2003-02-14 * "Opening Balance"
348 Assets:Bank:Credit-Union:Savings 458.21 USD
349 Assets:Bank:Credit-Union:Checking 194.17 USD
350 Equity:Opening-Balances
351
352 ...
353
354 =head1 SEE ALSO
355
356 L<App::HomeBank2Ledger::Formatter>
357
358 =head1 BUGS
359
360 Please report any bugs or feature requests on the bugtracker website
361 L<https://github.com/chazmcgarvey/homebank2ledger/issues>
362
363 When submitting a bug or request, please include a test-file or a
364 patch to an existing test-file that illustrates the bug or desired
365 feature.
366
367 =head1 AUTHOR
368
369 Charles McGarvey <chazmcgarvey@brokenzipper.com>
370
371 =head1 COPYRIGHT AND LICENSE
372
373 This software is Copyright (c) 2019 by Charles McGarvey.
374
375 This is free software, licensed under:
376
377 The MIT (X11) License
378
379 =cut
This page took 0.053239 seconds and 4 git commands to generate.