Browse code

Add boobank-history.

Xavier G authored on08/11/2017 17:11:27
Showing1 changed files

1 1
new file mode 100755
... ...
@@ -0,0 +1,71 @@
1
+#!/usr/bin/env python
2
+# -*- coding: utf-8 -*-
3
+
4
+import os
5
+import sys
6
+import json
7
+import time
8
+from prettytable import PrettyTable
9
+from termcolor import colored
10
+
11
+MAX_AGE = 24 * 60 * 60
12
+
13
+CURRENCIES = {
14
+    'EUR': '€',
15
+    'USD': '$',
16
+    'GBP': '£',
17
+    'YEN': '¥'
18
+}
19
+
20
+def main():
21
+    table = get_table()
22
+    filepath = sys.argv[1]
23
+    history = get_history(filepath)
24
+    for operation in history.get('data', []):
25
+        add_operation(table, operation)
26
+    print(table)
27
+    timestamp = history.get('timestamp', time.time())
28
+    timestamp = format_timestamp_colored(timestamp, MAX_AGE)
29
+    print('Data cached on %s' % timestamp)
30
+
31
+def get_history(history_json_path):
32
+    if history_json_path == '-':
33
+        return json.load(sys.stdin)
34
+    else:
35
+        with open(history_json_path, 'r') as filedesc:
36
+            return json.load(filedesc)
37
+
38
+def get_table():
39
+    pt = PrettyTable()
40
+    pt.field_names = ['Date', 'Label', 'Amount']
41
+    pt.field_names = [colored(x, 'white', attrs=['bold']) for x in pt.field_names]
42
+    pt.align = 'l'
43
+    pt.align[pt.field_names[2]] = 'r'
44
+    return pt
45
+
46
+def add_operation(table, operation):
47
+    date = colored(operation.get('date'), 'cyan')
48
+    label = colored(operation.get('label')[:80], 'cyan')
49
+    amount = format_amount(operation)
50
+    table.add_row([date, label, amount])
51
+
52
+def format_amount(account):
53
+    amount = account.get('amount')
54
+    currency = account.get('currency', 'EUR')
55
+    amount_format = '%12.2f '
56
+    amount_format += CURRENCIES.get(currency, currency)
57
+
58
+    amount_color = 'green' if amount >= 0 else 'red'
59
+    amount_attr = []
60
+    return colored(amount_format % amount, amount_color, attrs=amount_attr)
61
+
62
+def format_timestamp_colored(timestamp, max_age):
63
+    result = format_timestamp(timestamp)
64
+    color = 'red' if timestamp + max_age < time.time() else 'green'
65
+    return colored(result, color)
66
+
67
+def format_timestamp(timestamp):
68
+    return time.strftime('%A %Y-%m-%d %H:%M:%S %Z', time.localtime(timestamp))
69
+
70
+if __name__ == '__main__':
71
+    main()