Загрузка данных
import sys
import os
from re import search
import pymysql
from PyQt6 import QtWidgets, QtCore, QtGui
from resources.ui.main_ui import Ui_MainWindow
from resources.ui.auth_ui import Ui_Form
def resources_path(relative_path):
base_path = getattr(sys, "_MEIPASS", os.path.abspath("."))
return os.path.join(base_path, relative_path)
# функция подключения к бд
def get_conn():
conn = pymysql.connect(
host="localhost",
user="root",
password="",
database="boots_shop",
charset="utf8",
)
cursor = conn.cursor()
return conn, cursor
class AuthWindow(QtWidgets.QWidget, Ui_Form):
def __init__(self):
super().__init__()
self.setupUi(self)
self.setWindowTitle("Авторизация")
self.setWindowIcon(QtGui.QIcon(resources_path("resources/icons/iconn.ico")))
self.btn_exit.clicked.connect(self.close)
self.btn_guest.clicked.connect(self.login_guest)
self.btn_enter.clicked.connect(self.login)
def login_guest(self): # вход в систему гостя
self.open_main_window(0,"Гость", 1)
def login(self): # вход в систему через логин и пароль с проверкой
if self.le_login.text() == "" and self.le_password.text() == "":
QtWidgets.QMessageBox.information(self, "заполните поля", "Введите логин и пароль")
else:
try:
conn, cursor = get_conn()
cursor.execute("SELECT id_user, username, role_id FROM user WHERE login = %s AND password = %s",(self.le_login.text(), self.le_password.text()))
user = cursor.fetchone()
cursor.close()
conn.close()
if user:
id_user, username, role_id = user
self.open_main_window(id_user, username, role_id)
else: QtWidgets.QMessageBox.warning(self, "Ошибка", "введите верные логин и пароль")
except Exception as e:
QtWidgets.QMessageBox.critical(self, "Критическая ошибка", f"ошибка: {e}")
def open_main_window(self, id_user, username, role_id):
self.main = MainWindow(id_user, username, role_id)
self.main.show()
self.close()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, id_user, username, role_id):
super().__init__()
self.setupUi(self)
self.setWindowTitle("Обувной магазин")
self.setWindowIcon(QtGui.QIcon(resources_path("resources/icons/iconn.ico")))
self.btn_exit.clicked.connect(self.exit)
self.lbl_username.setText(username)
self.role_id = role_id
self.id_user = id_user
product_tab = self.tabWidget.indexOf(self.tabProducts)
order_tab = self.tabWidget.indexOf(self.tabOrders)
# ограничение функционала в зависимости от роли пользователя
if role_id == 1 or role_id == 2:
self.btn_add.setVisible(False)
self.le_search.setVisible(False)
self.cmbx_filtr.setVisible(False)
self.cmbx_sort.setVisible(False)
self.tabWidget.setTabVisible(order_tab, False)
elif role_id == 3:
self.btn_add.setVisible(False)
self.le_search.setVisible(True)
self.cmbx_filtr.setVisible(True)
self.cmbx_sort.setVisible(True)
self.tabWidget.setTabVisible(order_tab, True)
elif role_id == 4:
self.btn_add.setVisible(True)
self.le_search.setVisible(True)
self.cmbx_filtr.setVisible(True)
self.cmbx_sort.setVisible(True)
self.tabWidget.setTabVisible(order_tab, True)
self.le_search.textChanged.connect(self.load_data)
self.cmbx_filtr.currentIndexChanged.connect(self.load_data)
self.cmbx_sort.currentIndexChanged.connect(self.load_data)
self.load_data()
if role_id == 3 or role_id == 4:
self.load_orders()
def exit(self):
self.auth = AuthWindow()
self.auth.show()
self.close()
def clear_data(self):
layout = self.scrollAreaWidgetProducts.layout()
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
# загрузка данных о товаре из бд
def load_data(self):
self.clear_data()
search = self.le_search.text()
query = """SELECT p.id_product, p.product_name, c.category, p.description, m.manufacturer,
pr.provider, p.price, u.unit, p.quantity, p.discount, p.photo
FROM product p
JOIN category c ON p.category_id = c.id_category
JOIN manufacturer m ON p.manufacturer_id = m.id_manufacturer
JOIN provider pr ON p.provider_id = pr.id_provider
JOIN unit u ON p.unit_id = u.id_unit
WHERE p.product_name LIKE %s
"""
params = [f"%{search}%"]
if self.cmbx_filtr.currentIndex() == 1:
query += " AND pr.provider = %s"
params.append("Биг")
elif self.cmbx_filtr.currentIndex() == 2:
query += " AND pr.provider = %s"
params.append("Мини")
if self.cmbx_sort.currentIndex() == 1:
query += " ORDER BY p.quantity DESC"
elif self.cmbx_sort.currentIndex() == 2:
query += " ORDER BY p.quantity ASC"
conn, cursor = get_conn()
cursor.execute(query, params)
data = cursor.fetchall()
cursor.close()
conn.close()
for row in data:
self.add_card(row)
self.scrollAreaWidgetProducts.layout().addStretch()
# добавление карточек
def add_card(self, data):
frame = QtWidgets.QFrame()
frame.setFrameShape(QtWidgets.QFrame.Shape.Box)
frame.setFixedSize(720, 150)
if data[8] == 0: frame.setStyleSheet("background-color: blue")
elif data[9] > 15: frame.setStyleSheet("background-color: #2E8B57")
layout = QtWidgets.QHBoxLayout(frame)
img_lbl = QtWidgets.QLabel()
img_lbl.setScaledContents(True)
img_lbl.setFixedSize(100, 100)
image_path = resources_path(os.path.join("resources", "images", data[10] if data[10] else ""))
placeholder_path = resources_path(os.path.join("resources", "images", "placeholder.jpg"))
if os.path.exists(image_path) and data[10]:
img_lbl.setPixmap(QtGui.QPixmap(image_path))
else: img_lbl.setPixmap(QtGui.QPixmap(placeholder_path))
layout.addWidget(img_lbl)
info_layout = QtWidgets.QVBoxLayout()
info_layout.addWidget(QtWidgets.QLabel(f"Категория: {data[2]} | Название: {data[1]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Описание: {data[3]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Производитель: {data[4]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Поставщик: {data[5]}"))
price = float(data[6])
discount = int(data[9])
price_layout = QtWidgets.QHBoxLayout()
if discount > 0:
new_price = price * (1 - discount/100)
old_price_lbl = QtWidgets.QLabel(f"{price:.2f} р")
old_font = old_price_lbl.font()
old_font.setStrikeOut(True)
old_price_lbl.setFont(old_font)
old_price_lbl.setStyleSheet("color:red")
new_price_lbl = QtWidgets.QLabel(f"{new_price:.2f} р")
price_layout.addWidget(old_price_lbl)
price_layout.addWidget(new_price_lbl)
else:
price_lbl = QtWidgets.QLabel(f"{price:.2f} р")
price_layout.addWidget(price_lbl)
info_layout.addLayout(price_layout)
info_layout.addWidget(QtWidgets.QLabel(f"Единица измерения: {data[7]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Количество на складе: {data[8]}"))
layout.addLayout(info_layout)
layout.addStretch()
discount_layout = QtWidgets.QVBoxLayout()
discount_lbl = QtWidgets.QLabel(f"Скидка: {data[9]}%")
discount_layout.addWidget(discount_lbl)
layout.addLayout(discount_layout)
self.scrollAreaWidgetProducts.layout().addWidget(frame)
def clear_orders(self):
layout = self.scrollAreaWidgetOrders.layout()
while layout.count():
item = layout.takeAt(0)
widget = item.widget()
if widget is not None:
widget.deleteLater()
def load_orders(self):
self.clear_orders()
conn, cursor = get_conn()
cursor.execute("""SELECT o.id_orders, p.product_name, u.username, s.status,
o.adress, o.date_order, o.date_delivery
FROM orders o
JOIN product p ON o.product_id = p.id_product
JOIN user u ON o.user_id = u.id_user
JOIN status s ON o.status_id = s.id_status""")
data = cursor.fetchall()
cursor.close()
conn.close()
for row in data:
self.add_order(row)
self.scrollAreaWidgetOrders.layout().addStretch()
def add_order(self, data):
frame = QtWidgets.QFrame()
frame.setFrameShape(QtWidgets.QFrame.Shape.Box)
frame.setFixedSize(700, 200)
layout = QtWidgets.QHBoxLayout(frame)
info_layout = QtWidgets.QVBoxLayout()
info_layout.addWidget(QtWidgets.QLabel(f"Артикул заказа: {data[0]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Название: {data[1]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Покупатель: {data[2]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Стутус: {data[3]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Адрес пункта выдачи: {data[4]}"))
info_layout.addWidget(QtWidgets.QLabel(f"Дата заказа: {data[5]}"))
layout.addLayout(info_layout)
layout.addStretch()
self.scrollAreaWidgetOrders.layout().addWidget(frame)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = AuthWindow()
window.show()
sys.exit(app.exec())