~trufas/ledgeroni

ref: 002c8ad49ffe32c6c08c8950de09f0f71a606906 ledgeroni/ledgeroni/commands/register.py -rw-r--r-- 2.2 KiB
002c8ad4 — Rafael Castillo Test against python 3.8 in CI 2 years 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""
register.py: Defines the `register subcommand`
"""
import itertools
from os import sys
import click
from colorama import Fore, Style

from ledgeroni.journal import Journal
from ledgeroni.util import format_amount
from ledgeroni import expression


def build_table(transaction, postings):
    "Generates the register table line by line"
    # This whole thing stinks, fix it
    line = [''] * 4

    line[0] = (transaction.date_str + ' ' + Style.BRIGHT +
               transaction.description + Style.RESET_ALL)
    for posting, amts in postings.items():
        line[1] = Fore.BLUE + posting + Style.RESET_ALL

        changes, totals = amts
        changes = [format_amount(c, a) for c, a in changes.items()]
        if totals:
            totals = [format_amount(c, a) for c, a in totals.items()]
        else:
            totals = ['{:>20}'.format('0')]
        for change, total in itertools.zip_longest(changes, totals,
                                                   fillvalue=' ' * 20):
            line[2], line[3] = change, total
            yield tuple(line)
            line[0] = Style.BRIGHT + Style.RESET_ALL
            line[1] = Fore.BLUE + Style.RESET_ALL


@click.command()
@click.argument('filter_strs', nargs=-1)
@click.pass_context
def print_register(ctx, filter_strs):
    "The `ledgeroni print` subcommand"
    filter_query = None
    if filter_strs:
        filter_query = expression.build_expression(' '.join(filter_strs))
    sorter = ctx.obj.get('SORTER', None)

    journal = Journal(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)

    if sorter:
        sorter.sort_journal(journal)

    for transaction, postings in journal.generate_running_total_report():
        for trans, post, change, total in build_table(transaction, postings):
            click.echo('{:<64} {:<50} {} {}'.format(
                trans, post, change, total))