]> Dogcows Code - chaz/homebank2ledger/blob - lib/App/HomeBank2Ledger/Formatter/Beancount.pm
7e3f7852bba326f7213d7c592c4fe47938f6c659
[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.006'; # 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
227 # beancount doesn't support different notations
228 my $num = join('.', commify($whole), $fraction);
229
230 $num = "$num $commodity->{iso}";
231
232 return $num;
233 }
234
235 sub _find_oldest_transaction_by_account {
236 my $self = shift;
237 my $account = shift;
238 my $ledger = shift;
239
240 $account = $self->_format_account($account);
241
242 my $oldest = $self->{oldest_transaction_by_account};
243 if (!$oldest) {
244 # build index
245 for my $transaction (@{$ledger->transactions}) {
246 for my $posting (@{$transaction->{postings}}) {
247 my $account = $self->_format_account($posting->{account});
248
249 if ($transaction->{date} lt ($oldest->{$account}{date} || '9999-99-99')) {
250 $oldest->{$account} = $transaction;
251 }
252 }
253 }
254
255 $self->{oldest_transaction_by_account} = $oldest;
256 }
257
258 return $oldest->{$account};
259 }
260
261 sub _find_oldest_transaction_by_commodity {
262 my $self = shift;
263 my $commodity = shift;
264 my $ledger = shift;
265
266 my $oldest = $self->{oldest_transaction_by_commodity};
267 if (!$oldest) {
268 # build index
269 for my $transaction (@{$ledger->transactions}) {
270 for my $posting (@{$transaction->{postings}}) {
271 my $symbol = $posting->{commodity}{symbol};
272 next if !$symbol;
273
274 if ($transaction->{date} lt ($oldest->{$symbol}{date} || '9999-99-99')) {
275 $oldest->{$symbol} = $transaction;
276 }
277 }
278 }
279
280 $self->{oldest_transaction_by_commodity} = $oldest;
281 }
282
283 return $oldest->{$commodity->{symbol}};
284 }
285
286 1;
287
288 __END__
289
290 =pod
291
292 =encoding UTF-8
293
294 =head1 NAME
295
296 App::HomeBank2Ledger::Formatter::Beancount - Beancount formatter
297
298 =head1 VERSION
299
300 version 0.006
301
302 =head1 DESCRIPTION
303
304 This is a formatter for L<Beancount|http://furius.ca/beancount/>.
305
306 =head1 METHODS
307
308 =head2 format_header
309
310 @lines = $formatter->format_header;
311
312 Get formatted header. For example,
313
314 ; Name: My Finances
315 ; File: path/to/finances.xhb
316
317 =head2 format_accounts
318
319 @lines = $formatter->format_accounts($ledger);
320
321 Get formatted accounts. For example,
322
323 2003-02-14 open Assets:Bank:Credit-Union:Savings
324 2003-02-14 open Assets:Bank:Credit-Union:Checking
325 ...
326
327 =head2 format_commodities
328
329 @lines = $formatter->format_commodities($ledger);
330
331 Get formattted commodities. For example,
332
333 2003-02-14 commodity USD
334 name: "US Dollar"
335 ...
336
337 =head2 format_transactions
338
339 @lines = $formatter->format_transactions($ledger);
340
341 Get formatted transactions. For example,
342
343 2003-02-14 * "Opening Balance"
344 Assets:Bank:Credit-Union:Savings 458.21 USD
345 Assets:Bank:Credit-Union:Checking 194.17 USD
346 Equity:Opening-Balances
347
348 ...
349
350 =head1 SEE ALSO
351
352 L<App::HomeBank2Ledger::Formatter>
353
354 =head1 BUGS
355
356 Please report any bugs or feature requests on the bugtracker website
357 L<https://github.com/chazmcgarvey/homebank2ledger/issues>
358
359 When submitting a bug or request, please include a test-file or a
360 patch to an existing test-file that illustrates the bug or desired
361 feature.
362
363 =head1 AUTHOR
364
365 Charles McGarvey <chazmcgarvey@brokenzipper.com>
366
367 =head1 COPYRIGHT AND LICENSE
368
369 This software is Copyright (c) 2019 by Charles McGarvey.
370
371 This is free software, licensed under:
372
373 The MIT (X11) License
374
375 =cut
This page took 0.051231 seconds and 4 git commands to generate.