balance.py (3003B) - raw
1 from typing import List
2
3 from utils.read_file import entry
4 from utils.register import currencies, complete_prices
5 from utils.colored_output import *
6
7
8 class tree:
9 def __init__(self, name: str, value: currencies = None) -> None:
10 self.name = name
11 self.value = value
12 self.children = []
13
14
15 def compute_value(self):
16 if self.value is not None:
17 return
18
19 self.value = currencies()
20 for child in reversed(self.children):
21 child.compute_value()
22 for price in child.value:
23 self.value.add_money(price)
24
25
26 def add_child(self, name: str, value: currencies = None):
27 self.children.append(tree(name, value))
28
29
30 def add_value(self, price: str):
31 if self.value is None:
32 self.value = currencies()
33
34 self.value.add_money(price)
35
36
37 def get_child_with_name(self, name: str):
38 for child in self.children:
39 if name == child.name:
40 return child
41
42 return None
43
44
45 def __contains__(self, name: str) -> bool:
46 for child in self.children:
47 if name == child.name:
48 return True
49
50 return False
51
52
53 def __str__(self, level=0, ignore_level = False) -> str:
54 self.children.sort(key=lambda child: child.name)
55
56 result = ''
57 if not ignore_level:
58 for price in self.value:
59 result += price_f(f'{price:>20}') + '\n'
60
61 result = result.rstrip()
62 result += ' ' + ' '*(2 * level)
63
64 if len(self.children) == 1:
65 result += account_f(self.name + ':')
66 for child in self.children:
67 result += child.__str__(level + 1, ignore_level = True)
68
69 else:
70 result += account_f(self.name) + '\n'
71 for child in self.children:
72 result += child.__str__(level + 1)
73
74 return result
75
76
77 class accounts_tree:
78 def __init__(self) -> None:
79 self.my_accounts = tree(name='root')
80
81 def add_transaction(self, name_acc: str, price: str):
82 search = self.my_accounts
83
84 for name in name_acc.split(':'):
85 if name not in search:
86 search.add_child(name)
87
88 search = search.get_child_with_name(name)
89
90 search.add_value(price)
91
92
93 def __str__(self) -> str:
94 self.my_accounts.children.sort(key=lambda child: child.name)
95 self.my_accounts.compute_value()
96
97 result = ''
98 for child in self.my_accounts.children:
99 result += str(child)
100
101 result += '--------------------\n'
102 for price in self.my_accounts.value:
103 result += price_f(f'{price:>20}') + '\n'
104
105 return result.rstrip()
106
107
108
109 def print_balance(my_entries: List[entry]):
110 my_tree = accounts_tree()
111
112 for ent in my_entries:
113 complete_prices(ent)
114
115 for trans in ent.transactions:
116 my_tree.add_transaction(trans[0], str(trans[1]))
117
118 print(my_tree)