50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
|
"""Implementation of Transaction class."""
|
||
|
|
||
|
from __future__ import annotations
|
||
|
from time import strftime, strptime, gmtime
|
||
|
from typing import Optional
|
||
|
|
||
|
__all__ = ["Transaction", "TYPE_INCOME", "TYPE_OUTCOME"]
|
||
|
|
||
|
TYPE_INCOME = "in"
|
||
|
TYPE_OUTCOME = "out"
|
||
|
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
|
||
|
|
||
|
|
||
|
class Transaction:
|
||
|
"""Represents a single transaction.
|
||
|
Consists of array of coins' list, direction and timestamp."""
|
||
|
def __init__(self, coins, direction: str = TYPE_INCOME,
|
||
|
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. "
|
||
|
f"The right one is {TIME_FORMAT}")
|
||
|
self.timestamp = timestamp
|
||
|
|
||
|
@staticmethod
|
||
|
def from_string(transaction: str) -> Transaction:
|
||
|
"""Makes a Transaction object from its string output."""
|
||
|
timestamp, direction, coins = transaction.split()
|
||
|
|
||
|
coins = [int(coin) for coin in coins.split(",")]
|
||
|
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})"
|