~trufas/ledgeroni

ref: 2b5f5891a43f56b1c2c5e9f1ff826f57962137f4 ledgeroni/ledgeroni/commands/balance.py -rw-r--r-- 1.7 KiB
2b5f5891 — Rafael Castillo Don't include total in balance command when there's only one balance 1 year, 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
balance.py: Defines the `balance` subcommand
"""
import sys
import click
from colorama import Fore, Style

from ledgeroni.journal import Journal
from ledgeroni.query import MATCH_ALL
from ledgeroni.aggregate import AccountAggregate
from ledgeroni.util import format_amount
from ledgeroni import expression


@click.command()
@click.argument('filter_strs', nargs=-1)
@click.pass_context
def print_balance(ctx, filter_strs):
    "`ledger balance` subcommand"
    filter_query = MATCH_ALL
    if filter_strs:
        filter_query = expression.build_expression(' '.join(filter_strs))
    journal = Journal(query=filter_query)

    aggregate = AccountAggregate(query=filter_query)

    price_db = ctx.obj.get('PRICE_DB', None)
    if price_db:
        journal.add_from_file(price_db)

    for filename in ctx.obj.get('LEDGER_FILES', []):
        journal.add_from_file(filename)

    errors = journal.verify_transaction_balances()
    if errors:
        for error in errors:
            errstr = 'ERROR! Transaction unbalanced: {}'.format(error.header)
            click.echo(errstr, err=True)
        sys.exit(1)

    aggregate.add_from_journal(journal)

    balances = list(aggregate.iter_aggregates())
    _, _, total = balances[0]
    balances = balances[1:]
    for level, name, aggregate in balances:
        lvlstr = '\n'.join(format_amount(c, a)
                           for c, a in aggregate.items())
        lvlstr += '  ' * level + Fore.BLUE + name + Style.RESET_ALL
        click.echo(lvlstr)
    if len(balances) > 1:
        click.echo('-' * 20)
        totalstr = '\n'.join(format_amount(c, a)
                             for c, a in total.items())
        click.echo(totalstr)