1
0
Fork 0

Fixed all the shit I broke. ;)

This commit is contained in:
Alexander Andreev 2020-07-07 02:30:21 +04:00
parent 5c7a484352
commit 33ec32cb18
5 changed files with 38 additions and 25 deletions

View File

@ -1,4 +1,4 @@
build: piggybank setup.cfg README.md build: piggybank/* setup.cfg README.md
python setup.py sdist bdist_wheel python setup.py sdist bdist_wheel
install: install:
python -m pip install --upgrade dist/piggybank-1.0.0-py3-none-any.whl --user python -m pip install --upgrade dist/piggybank-1.0.0-py3-none-any.whl --user

View File

@ -2,10 +2,11 @@
from re import search, split from re import search, split
from sys import argv, stderr from sys import argv, stderr
from os.path import exists
from typing import List from typing import List
from piggybank import VERSION, CURRENCIES from piggybank import VERSION, CURRENCIES
from piggybank.configuration import Configuration from piggybank.configuration import Configuration, DEFAULT_CONFIGURATION_FILE
from piggybank.currency import Currency, BaseCurrencyError from piggybank.currency import Currency, BaseCurrencyError
from piggybank.piggybank import PiggyBank from piggybank.piggybank import PiggyBank
from piggybank.transaction import sum_transactions, TYPE_INCOME, TYPE_OUTCOME from piggybank.transaction import sum_transactions, TYPE_INCOME, TYPE_OUTCOME
@ -71,13 +72,16 @@ def parse_arguments(args: str) -> dict:
def print_transactions(pb: PiggyBank) -> None: def print_transactions(pb: PiggyBank) -> None:
cur = CURRENCIES[pb.currency] currency = CURRENCIES[pb.currency]
names = (currency.currency_symbol.format(n//100) if n >= 100 \
else currency.fraction_symbol.format(n) \
for n in currency.face_values)
def print_separator(l: str, m: str, r: str): def print_separator(l: str, m: str, r: str):
print(f"{l}{''*21}{m}{''*5}{m}{m.join([''*12]*cur.count)}{r}") print(f"{l}{''*21}{m}{''*5}{m}{m.join([''*12]*len(currency))}{r}")
print_separator("", "", "") print_separator("", "", "")
print(f"{'Timestamp':^21}┃ I/O ┃" \ print(f"{'Timestamp':^21}┃ I/O ┃" \
f"{''.join(f'{n:^12}' for n in cur.coin_names)}") f"{''.join(f'{n:^12}' for n in names)}")
print_separator("", "", "") print_separator("", "", "")
for t in pb.transactions: for t in pb.transactions:
print(f"{t.timestamp.replace('T', ' ')} " print(f"{t.timestamp.replace('T', ' ')} "
@ -86,21 +90,24 @@ def print_transactions(pb: PiggyBank) -> None:
print_separator("", "", "") print_separator("", "", "")
def print_summary(pb: PiggyBank) -> None: def print_summary(pb: PiggyBank) -> None:
cur = CURRENCIES[pb.currency] currency = CURRENCIES[pb.currency]
names = (currency.currency_symbol.format(n//100) if n >= 100 \
else currency.fraction_symbol.format(n) \
for n in currency.face_values)
def print_separator(l: str, lm: str, rm: str, r:str): def print_separator(l: str, lm: str, rm: str, r:str):
print(f"{l}{''*27}{lm}{rm.join([''*12]*cur.count)}{r}") print(f"{l}{''*27}{lm}{rm.join([''*12]*len(currency))}{r}")
print_separator("", "", "", "") print_separator("", "", "", "")
print(f"{cur.name:^27}{''.join(f'{n:^12}' for n in cur.coin_names)}") print(f"{currency.name:^27}{''.join(f'{n:^12}' for n in names)}")
print_separator("", "", "", "") print_separator("", "", "", "")
s = sum_transactions(pb.transactions) s = sum_transactions(pb.transactions)
print(f"{'Counts':^27}{''.join(f'{c:^12}' for c in s)}") print(f"{'Counts':^27}{''.join(f'{c:^12}' for c in s)}")
print_separator("", "", "", "") print_separator("", "", "", "")
s = cur * s s = currency * s
print(f"{'Sums in currency':^27}{''.join(f'{c/100:^12.2f}' for c in s)}") print(f"{'Sums in currency':^27}{''.join(f'{c/100:^12.2f}' for c in s)}")
print_separator("", "", "", "") print_separator("", "", "", "")
s = sum(s) s = sum(s)
print(f"{'Total in currency':^27}{s/100:^{12*cur.count+cur.count-1}.2f}") print(f"{'Total in currency':^27}{s/100:^{12*len(currency)+len(currency)-1}.2f}")
print_separator("", "", "", "") print_separator("", "", "", "")
@ -146,19 +153,23 @@ def main():
exit() exit()
try: try:
if not exists(DEFAULT_CONFIGURATION_FILE):
Configuration.write_default_to_file(DEFAULT_CONFIGURATION_FILE)
load_currencies() load_currencies()
try: try:
pb = PiggyBank.from_file(args["file"]) pb = PiggyBank.from_file(args["file"])
except FileNotFoundError: except FileNotFoundError:
if args["action"] == "in": if args["action"] == 'in':
currency = Configuration()["default-currency"] \ currency = Configuration()["default-currency"] \
if args["currency"] is None else args["currency"] if not args["currency"] else args["currency"]
pb = PiggyBank(currency) pb = PiggyBank(currency)
else: else:
raise FileNotFoundError(f"{args['file']} is missing.") raise FileNotFoundError(f"{args['file']} is missing.")
if args["action"] in ["in", "from"]: if args["action"] in ["in", "from"]:
coins = complement_list_of_coins(args["coins"], pb.currency, coins = complement_list_of_coins(args["coins"], pb.currency,
args["reversed"]) args["reversed"])
pb.transact(coins, TYPE_INCOME if args["action"] == "in" \ pb.transact(coins, TYPE_INCOME if args["action"] == "in" \
else TYPE_OUTCOME) else TYPE_OUTCOME)
pb.save(args["file"]) pb.save(args["file"])
@ -177,4 +188,4 @@ def main():
f"{type(err).__name__}:", err, file=stderr) f"{type(err).__name__}:", err, file=stderr)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -15,7 +15,8 @@ from os.path import exists, join
from platform import system from platform import system
from typing import Union from typing import Union
__all__ = ["Configuration", "get_configuration_path"] __all__ = ["Configuration", "get_configuration_path",
"DEFAULT_CONFIGURATION_FILE"]
def get_configuration_path() -> str: def get_configuration_path() -> str:
@ -34,10 +35,10 @@ default-currency = SRUB
# Format is following: # Format is following:
# <ISO>;<CURRENCY NAME>;<COINS COUNT>;{}<FRACTION SYMBOL>,{}<CURRENCY SYMBOL>;<FACE VALUES> # <ISO>;<CURRENCY NAME>;<COINS COUNT>;{}<FRACTION SYMBOL>,{}<CURRENCY SYMBOL>;<FACE VALUES>
# "{}" is used as a placeholder for where to put digits. # "{}" is used as a placeholder for where to put digits.
currency.RUB = RUB;Russian ruble;8;{}коп.,{};1,5,10,50,100,200,500,1000 currency.RUB = RUB;Russian ruble;8;{} коп.,{};1,5,10,50,100,200,500,1000
currency.SRUB = SRUB;Russian ruble (no 1 and 5 kopek);6;{}коп.,{};10,50,100,200,500,1000 currency.SRUB = SRUB;Russian ruble;6;{} коп.,{};10,50,100,200,500,1000
currency.BYN = BYN;Belarusian ruble;8;{}коп.,{}р.;1,2,5,10,20,50,100,200 currency.BYN = BYN;Belarusian ruble;8;{} коп.,{}р.;1,2,5,10,20,50,100,200
currency.UAH = UAH;Ukrainian hryvnia;10;{}коп.,{};1,2,5,10,25,50,100,200,500,1000 currency.UAH = UAH;Ukrainian hryvnia;10;{} коп.,{};1,2,5,10,25,50,100,200,500,1000
currency.USD = USD;US Dollar;6;{}¢,${};1,5,10,25,50,100 currency.USD = USD;US Dollar;6;{}¢,${};1,5,10,25,50,100
currency.EUR = EUR;Euro;8;{}c,{};1,2,5,10,20,50,100,200 currency.EUR = EUR;Euro;8;{}c,{};1,2,5,10,20,50,100,200
currency.GBP = GBP;Pound sterling;9;{}p,£{};1,2,5,10,20,25,50,100,200 currency.GBP = GBP;Pound sterling;9;{}p,£{};1,2,5,10,20,25,50,100,200
@ -56,7 +57,7 @@ class Configuration:
raise FileNotFoundError() raise FileNotFoundError()
def load(self) -> None: def load(self) -> None:
for line in open(self._configuration_file, 'r'): for line in open(self._configuration_file, 'r', encoding='utf8'):
if line[0] in ['#', '\n']: if line[0] in ['#', '\n']:
continue continue
key, value = line[:-1].split(" = ") key, value = line[:-1].split(" = ")
@ -71,7 +72,7 @@ class Configuration:
@staticmethod @staticmethod
def write_default_to_file(self, path: str = DEFAULT_CONFIGURATION_FILE) -> None: def write_default_to_file(self, path: str = DEFAULT_CONFIGURATION_FILE) -> None:
"""Writes default configuration to a file. Overrides existing.""" """Writes default configuration to a file. Overrides existing."""
with open(path, 'w') as cf: with open(path, 'w', encoding='utf8') as cf:
cf.write(DEFAULT_CONFIGURATION_FILE_CONTENT) cf.write(DEFAULT_CONFIGURATION_FILE_CONTENT)
@property @property

View File

@ -112,9 +112,10 @@ class Currency:
@staticmethod @staticmethod
def from_string(currency: str) -> Currency: def from_string(currency: str) -> Currency:
"""Creates a Currency object from its string representation.""" """Creates a Currency object from its string representation."""
iso, name, count, frac_sym, cur_sym, fv = currency.split(";") iso, name, count, syms, fv = currency.split(';')
frac_sym, cur_sym = syms.split(',')
return Currency(iso, name, int(count), frac_sym, cur_sym, return Currency(iso, name, int(count), frac_sym, cur_sym,
list(map(int, fv.split(",")))) list(map(int, fv.split(','))))
def __mul__(self, lst: List[int]) -> List[float]: def __mul__(self, lst: List[int]) -> List[float]:
return self.multiply(lst) return self.multiply(lst)

View File

@ -4,8 +4,8 @@ from __future__ import annotations
from os.path import exists from os.path import exists
from typing import List from typing import List
from piggybank import PIGGYBANK_FILE_EXTENSION from piggybank import PIGGYBANK_FILE_EXTENSION, CURRENCIES
from piggybank.currencies import CURRENCIES, CurrencyIsNotSupportedError from piggybank.currency import CurrencyIsNotSupportedError
from piggybank.transaction import Transaction, sum_transactions, TYPE_INCOME from piggybank.transaction import Transaction, sum_transactions, TYPE_INCOME
__all__ = ["PiggyBank"] __all__ = ["PiggyBank"]