#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright © 2017-2019 Xavier G. <xavier.boobank@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. """ boobank-history takes a JSON file, as created by boobank-cacher when running and caching a "boobank history" command, and display its contents. """ import time import argparse from prettytable import PrettyTable from termcolor import colored from boobank_utils import format_amount, load_json, format_timestamp_colored from boobank_utils import MAX_AGE, DEFAULT_CURRENCY, COLORING_SIMPLE def parse_args(): """ Parse command-line arguments. """ description = 'Display the contents of a cached "boobank history" JSON file.' args_parser = argparse.ArgumentParser(description=description) args_parser.add_argument('json_file', nargs='?', default='-', help='JSON file to display') args_parser.add_argument('-c', '--count', default=None, type=int, help='Maximum number of operations to display.') return args_parser.parse_args() def main(): """ Main function. """ args = parse_args() filepath = args.json_file max_operations = args.count history = load_json(filepath) timestamp = history.get('timestamp', time.time()) table = get_table(timestamp) i = 0 for operation in history.get('data', []): add_operation(table, operation) i += 1 if max_operations and i == max_operations: break print(table) def get_table(timestamp): """ Create and return the PrettyTable instance used to display data. """ ptable = PrettyTable() field_names = ['Date', 'Label', 'Amount'] field_names = [colored(x, 'white', attrs=['bold']) for x in field_names] timestamp = format_timestamp_colored(timestamp, MAX_AGE) field_names[1] += ' -- data cached on %s' % timestamp ptable.field_names = field_names ptable.align = 'l' ptable.align[ptable.field_names[2]] = 'r' return ptable def add_operation(table, operation): """ Add the given bank operation to the given PrettyTable instance. """ date = colored(operation.get('date'), 'cyan') label = colored(operation.get('label')[:80], 'cyan') currency = operation.get('currency', DEFAULT_CURRENCY) amount = format_amount(float(operation['amount']), currency, COLORING_SIMPLE) table.add_row([date, label, amount]) if __name__ == '__main__': main()