2020-03-27 20:14:22 +04:00
|
|
|
"""Transaction class implementation."""
|
2019-12-25 23:08:20 +04:00
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
from time import strftime, strptime, gmtime
|
2020-05-19 02:36:00 +04:00
|
|
|
from typing import Optional, List
|
2019-12-25 23:08:20 +04:00
|
|
|
|
2020-05-19 02:36:00 +04:00
|
|
|
__all__ = ["Transaction", "TYPE_INCOME", "TYPE_OUTCOME", "TIME_FORMAT"]
|
2019-12-25 23:08:20 +04:00
|
|
|
|
|
|
|
TYPE_INCOME = "in"
|
|
|
|
TYPE_OUTCOME = "out"
|
|
|
|
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
|
|
|
|
|
|
|
|
|
|
|
|
class Transaction:
|
2020-05-19 02:36:00 +04:00
|
|
|
"""An object that holds a transaction.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
- coins -- a list of numbers represent count for each face value;
|
|
|
|
- direction -- is this income or outcome. Takes TYPE_INCOME
|
|
|
|
or TYPE_OUTCOME;
|
|
|
|
- timestamp -- date and time formated accordingly to TIME_FORMAT."""
|
|
|
|
def __init__(self, coins: List[int], direction: str = TYPE_INCOME,
|
2019-12-25 23:08:20 +04:00
|
|
|
timestamp: Optional[str] = None) -> None:
|
|
|
|
self.coins = coins
|
|
|
|
if direction in [TYPE_INCOME, TYPE_OUTCOME]:
|
|
|
|
self.direction = direction
|
|
|
|
else:
|
|
|
|
raise ValueError(f"Direction may only be"
|
|
|
|
f"'{TYPE_INCOME}' or '{TYPE_OUTCOME}'")
|
|
|
|
if timestamp is None:
|
|
|
|
self.timestamp = strftime(TIME_FORMAT, gmtime())
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
strptime(timestamp, TIME_FORMAT)
|
|
|
|
except ValueError:
|
|
|
|
raise ValueError(f"Timestamp {timestamp} has wrong format. "
|
2020-03-27 20:14:22 +04:00
|
|
|
f"The right one is '{TIME_FORMAT}''")
|
2019-12-25 23:08:20 +04:00
|
|
|
self.timestamp = timestamp
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def from_string(transaction: str) -> Transaction:
|
|
|
|
"""Makes a Transaction object from its string output."""
|
|
|
|
timestamp, direction, coins = transaction.split()
|
|
|
|
|
2020-05-19 02:36:00 +04:00
|
|
|
coins = list(map(int, coins.split(",")))
|
2019-12-25 23:08:20 +04:00
|
|
|
return Transaction(coins, direction, timestamp)
|
|
|
|
|
|
|
|
def __str__(self) -> str:
|
|
|
|
return f"{self.timestamp} {self.direction} " \
|
|
|
|
f"{','.join(str(c) for c in self.coins)}"
|
|
|
|
|
|
|
|
def __repr__(self) -> str:
|
|
|
|
return f"Transaction(coins={self.coins!r}," \
|
|
|
|
f"direction={self.direction!r}, timestamp={self.timestamp!r})"
|