Skip to content

Commit

Permalink
deleted searsh widget
Browse files Browse the repository at this point in the history
  • Loading branch information
MakzaR committed Jun 23, 2020
1 parent d00fa34 commit 8b3e5b0
Show file tree
Hide file tree
Showing 13 changed files with 121 additions and 88 deletions.
35 changes: 22 additions & 13 deletions src/DAL/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,33 @@

from src.DAL.auth import AbstractAuthorization, ConcreteAuthorization
from src.DAL.currencies import AbstractCurrenciesGetter, ConcreteCurrencyGetter
from src.DAL.currency_history import AbstractCurrencyHistoryGetter, ConcreteCurrencyHistoryGetter
from src.DAL.currency_history import (
AbstractCurrencyHistoryGetter,
ConcreteCurrencyHistoryGetter,
)
from src.DAL.operation_maker import AbstractOperationMaker, ConcreteOperationMaker
from src.DAL.operations import AbstractOperationsGetter, ConcreteOperationsGetter
from src.DAL.user_currencies import (
AbstractUserCurrencyGetter,
ConcreteUserCurrencyGetter,
)
from src.DAL.user_getter import ConcreteUserGetter, AbstractUserGetter
from src.DAL.user_getter import AbstractUserGetter, ConcreteUserGetter
from src.DAL.utils import run_in_threadpool
from src.models.currency import Currency, UserCurrency, CurrencyHistory
from src.models.currency import Currency, CurrencyHistory, UserCurrency
from src.models.operation import OperationToShow, OperationType
from src.models.user import User


class Client:
def __init__(
self,
authorization: AbstractAuthorization = ConcreteAuthorization(),
currencies_getter: AbstractCurrenciesGetter = ConcreteCurrencyGetter(),
user_currencies_getter: AbstractUserCurrencyGetter = ConcreteUserCurrencyGetter(),
user_operations_getter: AbstractOperationsGetter = ConcreteOperationsGetter(),
currency_history_getter: AbstractCurrencyHistoryGetter = ConcreteCurrencyHistoryGetter(),
operation_maker: AbstractOperationMaker = ConcreteOperationMaker(),
user_getter: AbstractUserGetter = ConcreteUserGetter()
self,
authorization: AbstractAuthorization = ConcreteAuthorization(),
currencies_getter: AbstractCurrenciesGetter = ConcreteCurrencyGetter(),
user_currencies_getter: AbstractUserCurrencyGetter = ConcreteUserCurrencyGetter(),
user_operations_getter: AbstractOperationsGetter = ConcreteOperationsGetter(),
currency_history_getter: AbstractCurrencyHistoryGetter = ConcreteCurrencyHistoryGetter(),
operation_maker: AbstractOperationMaker = ConcreteOperationMaker(),
user_getter: AbstractUserGetter = ConcreteUserGetter(),
):
self._authorization: AbstractAuthorization = authorization
self._currencies_getter: AbstractCurrenciesGetter = currencies_getter
Expand Down Expand Up @@ -57,7 +60,13 @@ def get_currency_history(self, currency_id: int) -> List[CurrencyHistory]:
return self._currency_history_getter.get(currency_id)

@run_in_threadpool
def make_operation(self, operation_type: OperationType, user: User, currency: UserCurrency, amount: Decimal):
def make_operation(
self,
operation_type: OperationType,
user: User,
currency: UserCurrency,
amount: Decimal,
):
return self._operation_maker.make(operation_type, user, currency, amount)

@run_in_threadpool
Expand All @@ -66,4 +75,4 @@ def get_user(self, user_id: int) -> User:

@run_in_threadpool
def get_user_currency(self, user_id: int, currency_id: int) -> UserCurrency:
return self._user_currencies_getter.get_currency(user_id,currency_id)
return self._user_currencies_getter.get_currency(user_id, currency_id)
6 changes: 4 additions & 2 deletions src/DAL/currency_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
from typing import List

import requests
from pydantic import parse_obj_as
from requests import Response

from src.models.currency import CurrencyHistory
from src.urls import Urls
from pydantic import parse_obj_as


class AbstractCurrencyHistoryGetter(ABC):
Expand All @@ -17,5 +17,7 @@ def get(self, currency_id: int) -> List[CurrencyHistory]:

class ConcreteCurrencyHistoryGetter(AbstractCurrencyHistoryGetter):
def get(self, currency_id: int) -> List[CurrencyHistory]:
response: Response = requests.get(f'{Urls.CURRENCIES.value}/{currency_id}/history')
response: Response = requests.get(
f'{Urls.CURRENCIES.value}/{currency_id}/history'
)
return parse_obj_as(List[CurrencyHistory], response.json())
37 changes: 28 additions & 9 deletions src/DAL/operation_maker.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,48 @@
from requests import Response

from src.exceptions import DALError
from src.models.currency import CurrencyHistory, Currency, UserCurrency
from src.models.currency import UserCurrency
from src.models.operation import OperationType
from src.models.user import User
from src.urls import Urls


class AbstractOperationMaker(ABC):
@abstractmethod
def make(self, operation_type: OperationType, user: User, currency: UserCurrency, amount: Decimal) -> None:
def make(
self,
operation_type: OperationType,
user: User,
currency: UserCurrency,
amount: Decimal,
) -> None:
pass


class ConcreteOperationMaker(AbstractOperationMaker):
def make(self, operation_type: OperationType, user: User, currency: UserCurrency, amount: Decimal) -> None:
if operation_type == OperationType.BUY and user.money < amount * currency.purchasing_price:
def make(
self,
operation_type: OperationType,
user: User,
currency: UserCurrency,
amount: Decimal,
) -> None:
if (
operation_type == OperationType.BUY
and user.money < amount * currency.purchasing_price
):
raise DALError('У вас недостаточно средств')
if operation_type == OperationType.SELL and amount > currency.amount:
raise DALError('У вас нет такого кол-ва валюты')

response: Response = requests.post(f'{Urls.USERS.value}/{user.id}/currencies', json={'currency_id': currency.id,
'operation': operation_type.value,
'amount': str(amount),
'time': datetime.strftime(currency.time,
'%Y-%m-%d %H:%M:%S')})
response: Response = requests.post(
f'{Urls.USERS.value}/{user.id}/currencies',
json={
'currency_id': currency.id,
'operation': operation_type.value,
'amount': str(amount),
'time': datetime.strftime(currency.time, '%Y-%m-%d %H:%M:%S'),
},
)
if response.status_code == HTTPStatus.BAD_REQUEST:
raise DALError('Данные устарели, обновите и попробуйте еще раз')
6 changes: 5 additions & 1 deletion src/DAL/user_currencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,11 @@ class ConcreteUserCurrencyGetter(AbstractUserCurrencyGetter):
def get_currency(self, user_id: int, currency_id: int) -> UserCurrency:
res = requests.get(f'{Urls.USERS.value}/{user_id}/currencies/{currency_id}')
if res.status_code == HTTPStatus.BAD_REQUEST:
return self._get_currency(CurrencyItem(user_id=user_id, currency_id=currency_id, amount=Decimal('0')))
return self._get_currency(
CurrencyItem(
user_id=user_id, currency_id=currency_id, amount=Decimal('0')
)
)
return self._get_currency(CurrencyItem.parse_obj(res.json()))

def _get_currency(self, currency_item: CurrencyItem) -> UserCurrency:
Expand Down
2 changes: 1 addition & 1 deletion src/exceptions.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
class DALError(Exception):
pass
pass
2 changes: 1 addition & 1 deletion src/models/currency.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime, date
from datetime import datetime
from decimal import Decimal

from pydantic import BaseModel
Expand Down
15 changes: 10 additions & 5 deletions src/view/buy_window.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from decimal import Decimal

from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QMessageBox
from requests.exceptions import ConnectionError

from src.DAL.client import Client
from src.exceptions import DALError
Expand All @@ -8,8 +11,7 @@
from src.models.operation import OperationType
from src.models.user import User
from ui.buy_window import Ui_BuyWindow
from decimal import Decimal
from requests.exceptions import ConnectionError


class BuyWindow(Ui_BuyWindow, QMainWindow):
def __init__(self, parent, client: Client, user: User, currency: UserCurrency):
Expand All @@ -29,15 +31,18 @@ def buy(self):
except Exception:
raise DALError('Кол-во должно быть числом')
try:
self._client.make_operation(OperationType.BUY, self._user, self._currency, d)
self._client.make_operation(
OperationType.BUY, self._user, self._currency, d
)
self.parent.refresh()
self.close()
except ConnectionError:
QMessageBox().warning(self, 'Ошибка', str(Message.CONNECTION_ERROR.value))
QMessageBox().warning(
self, 'Ошибка', str(Message.CONNECTION_ERROR.value)
)

except DALError as e:
QMessageBox().warning(self, 'Ошибка', str(e))


def init(self):
self.show()
52 changes: 35 additions & 17 deletions src/view/currency_window.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from datetime import datetime
from typing import List, Dict, Optional
from typing import List

import pyqtgraph as pg
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QMessageBox
from requests.exceptions import ConnectionError

from src.DAL.client import Client
from src.message import Message
Expand All @@ -12,7 +13,7 @@
from src.view.buy_window import BuyWindow
from src.view.sell_wndow import SellWindow
from ui.currency import Ui_CurrencyWindow
from requests.exceptions import ConnectionError


class CurrencyWindow(Ui_CurrencyWindow, QMainWindow):
def __init__(self, parent, user: User, currency: UserCurrency):
Expand All @@ -28,25 +29,49 @@ def __init__(self, parent, user: User, currency: UserCurrency):

self.setWindowTitle(currency.name)

def set_text_info(self, selling_price, buying_price, account):
def set_text_info(
self, selling_price, buying_price, account, currency_amount, currency_name
):
self.buyingPrice.setText('Cтоимость покупки: ' + str(buying_price) + ' у.е.')
self.sellingPrice.setText('Стоимость продажи: ' + str(selling_price) + ' у.е.')
self.account.setText('На счёте: ' + str(account) + ' у.е.')
self.account.setText(
'На счёте: '
+ str(account)
+ ' у.е. | '
+ str(currency_amount)
+ ' '
+ currency_name
)

def draw_graphs(self):
self.graphicsView.plotItem.clear()
self._user = self._client.get_user(self._user.id)
self._currency = self._client.get_user_currency(self._user.id, self._currency.id)
self._currency = self._client.get_user_currency(
self._user.id, self._currency.id
)
pg.setConfigOptions(antialias=True)
history_items: List[CurrencyHistory] = self._client.get_currency_history(self._currency.id)
selling_prices = list(map(lambda item: float(item.selling_price), history_items))
purchasing_prices = list(map(lambda item: float(item.purchasing_price), history_items))
history_items: List[CurrencyHistory] = self._client.get_currency_history(
self._currency.id
)
selling_prices = list(
map(lambda item: float(item.selling_price), history_items)
)
purchasing_prices = list(
map(lambda item: float(item.purchasing_price), history_items)
)
time = {}
for i in range(len(history_items)):
if i == 0 or i == len(history_items) - 1:
time[i] = datetime.strftime(history_items[i].time, '%Y-%m-%d %H:%M:%S')
else:
time[i] = ''
self.set_text_info(selling_prices[-1], purchasing_prices[-1], str(self._user.money))
self.set_text_info(
selling_prices[-1],
purchasing_prices[-1],
str(self._user.money),
'ТУТ КОЛ-ВО ВАЛЮТЫ У ПОЛЬЗОВАТЕЛЯ',
self._currency.name,
)
self.graphicsView.setBackground('w')

self.graphicsView.addLegend()
Expand All @@ -71,13 +96,7 @@ def draw_graphs(self):
)

self.plot(
list(time.keys()),
selling_prices,
'Цена продажи',
(255, 0, 0),
1.5,
'o',
5,
list(time.keys()), selling_prices, 'Цена продажи', (255, 0, 0), 1.5, 'o', 5,
)

def plot(self, x, y, plot_name, color, width, symbol, symbol_size):
Expand All @@ -102,7 +121,6 @@ def sell(self):

def refresh(self):
try:
self.graphicsView.plotItem.clear()
self.init()
except ConnectionError:
QMessageBox().warning(self, 'Ошибка', str(Message.CONNECTION_ERROR.value))
Expand Down
1 change: 0 additions & 1 deletion src/view/login_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from src.DAL.client import Client
from src.message import Message
from src.view.main_window import MainWindow
# from src.view.utils import show_error
from ui.auth_form import Ui_AuthorizationForm


Expand Down
19 changes: 7 additions & 12 deletions src/view/main_window.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMainWindow, QPushButton, QTableWidgetItem, QMessageBox
from PyQt5.QtWidgets import QMainWindow, QMessageBox, QPushButton, QTableWidgetItem
from requests.exceptions import ConnectionError

from src.DAL.client import Client
Expand All @@ -9,7 +9,6 @@
from src.models.operation import OperationType
from src.models.user import User
from src.view.currency_window import CurrencyWindow
# from src.view.utils import show_error
from ui.main import Ui_MainWindow


Expand All @@ -19,30 +18,24 @@ def __init__(self, user: User, parent):
self.setupUi(self)
self.user: User = user

self.searchButton.clicked.connect(self.search_item)
self.refreshButton.clicked.connect(self.refresh_tables)
self._client = Client()

'''Логика кнопки поиска'''

def search_item(self):
pass

'''Логика кнопки обновления'''

def refresh_tables(self):
self.init()

'''Тут чистый треш, но я просто тестил заполнение данных'''

def fill_all_currencies(self):
self.allCurrenciesTable.clear()
currencies = self._client.get_all_currencies()
labels = ['Название', 'Цена продажи', 'Цена покупки', '']
create_headers(self.allCurrenciesTable, labels)
for i in currencies:
detail_button = QPushButton('Подробнее')
detail_button.clicked.connect(lambda a, i=i: self.show_details(self.user, UserCurrency(**i.dict())))
detail_button.clicked.connect(
lambda a, i=i: self.show_details(self.user, UserCurrency(**i.dict()))
)
row = self.allCurrenciesTable.rowCount()
self.allCurrenciesTable.setRowCount(row + 1)

Expand All @@ -64,7 +57,9 @@ def fill_my_currencies(self):
currencies = self._client.get_user_currencies(self.user.id)
for i in currencies:
detail_button = QPushButton('Подробнее')
detail_button.clicked.connect(lambda f, i=i: self.show_details(self.user, i))
detail_button.clicked.connect(
lambda f, i=i: self.show_details(self.user, i)
)
row = self.myCurrenciesTable.rowCount()
self.myCurrenciesTable.setRowCount(row + 1)

Expand Down
Loading

0 comments on commit 8b3e5b0

Please sign in to comment.