kindwolf.org Git repositories woobank-utils / master bin / woobank-accounts
master

Tree @master (Download .tar.gz)

woobank-accounts @masterraw · history · blame

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2017-2022 Xavier G. <xavier.woobank@kindwolf.org>
# This work is free. You can redistribute it and/or modify it under the
# terms of the Do What The Fuck You Want To Public License, Version 2,
# as published by Sam Hocevar. See the COPYING file for more details.
"""
woobank-accounts takes one or several JSON files, as created by woobank-cacher
when running and caching a "woob bank list" command, and display their contents.
"""

import time
import argparse
from prettytable import PrettyTable
from termcolor import colored
from woobank_utils import format_amount, format_timestamp_colored, load_json
from woobank_utils import DEFAULT_CURRENCY, COLORING_THRESHOLD, MAX_AGE

def parse_args():
    """
    Parse command-line arguments.
    """
    description = 'Display the contents of cached "woob bank list" JSON files.'
    args_parser = argparse.ArgumentParser(description=description)
    args_parser.add_argument('json_file', nargs='*', default=['-'], help='JSON files to display')
    return args_parser.parse_args()

def main():
    """
    Main function.
    """
    args = parse_args()
    table = get_table()
    total = 0
    for filepath in args.json_file:
        accounts = load_json(filepath)
        timestamp = accounts.get('timestamp', time.time())
        for account in accounts.get('data', []):
            add_account(table, account, timestamp)
            total += float(account.get('balance'))
    print(table)
    total_line = '%-60s' % ''
    total_line += colored('Total: ', 'white', attrs=['bold'])
    total_line += format_amount(total, DEFAULT_CURRENCY, COLORING_THRESHOLD)
    print(total_line)

def get_table():
    """
    Create and return the PrettyTable instance used to display data.
    """
    ptable = PrettyTable()
    ptable.field_names = ['Account ID', 'Account name', 'Balance', 'Data cached on']
    ptable.field_names = [colored(x, 'white', attrs=['bold']) for x in ptable.field_names]
    ptable.align = 'r'
    ptable.align[ptable.field_names[1]] = 'l'
    ptable.align[ptable.field_names[3]] = 'c'
    return ptable

def add_account(table, account, cache_timestamp):
    """
    Add the given bank account to the given PrettyTable instance.
    """
    account_id = colored(account.get('id'), 'cyan')
    label = colored(account.get('label'), 'cyan')
    currency = account.get('currency', DEFAULT_CURRENCY)
    balance = format_amount(float(account['balance']), currency, COLORING_THRESHOLD)
    cache_date = format_timestamp_colored(cache_timestamp, MAX_AGE)
    table.add_row([account_id, label, balance, cache_date])

if __name__ == '__main__':
    main()