Compare commits

..
15 Commits
Author SHA1 Message Date
Kita Trofimov c33e8798ed style(database): Fixed type of logger on the db sucsess operations 2025-10-26 20:31:51 +03:00
Kita Trofimov 401205aea2 style(database): Fixed the issue with long function declarations 2025-10-26 19:41:11 +03:00
Kita Trofimov 8c07b1febc style(database): Changed logging 2025-10-26 19:32:34 +03:00
Kita Trofimov 3e4755cca1 fix(database): Fixed the database connection 2025-10-26 19:14:51 +03:00
Kita Trofimov c117ceb85e style(database): Refactor repository name 2025-10-26 18:52:54 +03:00
Kita Trofimov 4e3b21f31e fix(model/user.py): Removed unnecesary methods 2025-10-26 18:48:54 +03:00
Kita Trofimov 6483afa0d4 feat(database/repositories/user_repository.py): A new login verification method has been added 2025-10-26 16:32:02 +03:00
Kita Trofimov 251e1b6e57 feat(database/repositories/ai_prediction_repository.py): Added new repository AIPredictionsRepository 2025-10-26 16:09:33 +03:00
Kita Trofimov 64e81aec69 feat(model/ai_prediction.py): Added new model AIPrediction 2025-10-26 15:52:48 +03:00
Kita Trofimov 6d5abeb88d feat(database/repositories/inventory_repository.py): Added inventory repository 2025-10-26 15:42:20 +03:00
Kita Trofimov fa00e27015 feat(database/repositories/product_repository.py): Added product repository 2025-10-26 15:04:47 +03:00
Kita Trofimov 2f6782ab9d feat(database/repositories/robot_repository.py): Added robot_repository 2025-10-26 14:09:21 +03:00
Kita Trofimov c1bab1b304 feat(database/repositories/user_repository.py): Added user repository 2025-10-26 13:14:51 +03:00
Kita Trofimov 506f2f3f39 feat(database): Implemented database connection 2025-10-26 00:43:32 +03:00
Kita Trofimov 79cac3d8cb feat(model): Added correct data models 2025-10-26 00:11:20 +03:00
14 changed files with 100 additions and 148 deletions
-2
View File
@@ -1,2 +0,0 @@
KEY= # Key for JWT token
POSTGRES_URL=postgresql://
-28
View File
@@ -1,28 +0,0 @@
from flask import Blueprint, request, jsonify
from model.user import User
auth = Blueprint("auth", __name__)
@auth.route('/login', methods = ['POST'])
def login():
if request.is_json:
req = request.json
email = req.get('email')
password = req.get('password')
if not email or not password:
return "Request must have email and password", 400
if len(email.strip()) < 4 or '@' not in email or '.' not in email:
return "Email is incorrect", 400
if len(password.strip()) < 8:
return "Password is too short", 400
user = User(email, password)
return jsonify(user.toJson())
else:
return "Request is not a json", 400
+12
View File
@@ -0,0 +1,12 @@
from flask import Blueprint, request
from model.user import user
loginBP = Blueprint("loginapi", __name__)
@loginBP.route('/api/login', methods = ['POST'])
def login():
email = request.form['email']
password = request.form['password']
#if(isvalid(email, password)):
us = user.initialize(email, password)
return us.toJSON()
+2 -7
View File
@@ -1,11 +1,6 @@
from sys import exit
from flask import Flask
from api.auth import auth
from utils.loadDotEnv import initializeENV
if not initializeENV():
exit(-1)
from api.loginapi import loginBP
app = Flask(__name__)
app.register_blueprint(auth, url_prefix='/api/auth')
app.register_blueprint(loginBP)
+3 -3
View File
@@ -24,7 +24,7 @@ def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
conn = None
try:
conn = PSQLConnect()
logger.info("Подключение к БД установлено")
logger.debug("Подключение к БД установлено")
yield conn
except psycopg2.OperationalError as e:
logger.error(f"Ошибка подключения к БД: {e}")
@@ -39,7 +39,7 @@ def get_connection() -> Generator[psycopg2.extensions.connection, None, None]:
if conn:
try:
conn.close()
logger.info("Соединение с БД закрыто")
logger.debug("Соединение с БД закрыто")
except Exception as e:
logger.warning(f"Ошибка при закрытии соединения: {e}")
@@ -50,7 +50,7 @@ def test_connection() -> bool:
try:
cur.execute("SELECT version();")
version = cur.fetchone()
logger.info(f"Версия PostgreSQL: {version[0]}")
logger.debug(f"Версия PostgreSQL: {version[0]}")
return True
finally:
cur.close()
+12 -14
View File
@@ -23,7 +23,7 @@ class AIPredictionsRepository:
created_at=row[6]
) for row in cur.fetchall()
]
logger.info(f"Получено {len(predictions)} прогнозов")
logger.debug(f"Получено {len(predictions)} прогнозов")
return predictions
except Exception as e:
logger.error(f"Ошибка получения прогнозов: {e}")
@@ -36,7 +36,7 @@ class AIPredictionsRepository:
cur.execute("SELECT * FROM ai_predictions WHERE id = %s", (prediction_id,))
row = cur.fetchone()
if row:
logger.info(f"Прогноз {prediction_id} найден")
logger.debug(f"Прогноз {prediction_id} найден")
return AIPrediction(*row)
logger.warning(f"Прогноз {prediction_id} не найден")
return None
@@ -55,7 +55,7 @@ class AIPredictionsRepository:
LIMIT %s
""", (product_id, limit))
predictions = [AIPrediction(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(predictions)} прогнозов для товара {product_id}")
logger.debug(f"Получено {len(predictions)} прогнозов для товара {product_id}")
return predictions
except Exception as e:
logger.error(f"Ошибка получения прогноза по товару {product_id}: {e}")
@@ -71,20 +71,18 @@ class AIPredictionsRepository:
ORDER BY product_id, prediction_date DESC
""")
predictions = [AIPrediction(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(predictions)} последних прогнозов по товарам")
logger.debug(f"Получено {len(predictions)} последних прогнозов по товарам")
return predictions
except Exception as e:
logger.error(f"Ошибка получения последних прогнозов по товарам: {e}")
return []
def create_prediction(
self,
product_id: str,
prediction_date: date,
days_until_stockout: int,
recommended_order: int,
confidence_score: float
) -> Optional[int]:
def create_prediction(self,
product_id: str,
prediction_date: date,
days_until_stockout: int,
recommended_order: int,
confidence_score: float) -> Optional[int]:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -97,7 +95,7 @@ class AIPredictionsRepository:
prediction_id = cur.fetchone()[0]
conn.commit()
logger.info(f"Создан новый прогноз ID: {prediction_id} для товара {product_id}")
logger.debug(f"Создан новый прогноз ID: {prediction_id} для товара {product_id}")
return prediction_id
except Exception as e:
logger.error(f"Ошибка создания прогноза: {e}")
@@ -113,7 +111,7 @@ class AIPredictionsRepository:
""", (older_than_days,))
deleted_count = cur.rowcount
conn.commit()
logger.info(f"Удалено {deleted_count} старых прогнозов старше {older_than_days} дней")
logger.debug(f"Удалено {deleted_count} старых прогнозов старше {older_than_days} дней")
return deleted_count
except Exception as e:
logger.error(f"Ошибка удаления старых прогнозов: {e}")
+17 -19
View File
@@ -27,7 +27,7 @@ class InventoryRepository:
created_at=row[9]
) for row in cur.fetchall()
]
logger.info(f"Получено {len(records)} записей инвентаризации")
logger.debug(f"Получено {len(records)} записей инвентаризации")
return records
except Exception as e:
logger.error(f"Ошибка получения истории инвентаризации: {e}")
@@ -40,7 +40,7 @@ class InventoryRepository:
cur.execute("SELECT * FROM inventory_history WHERE id = %s", (record_id,))
row = cur.fetchone()
if row:
logger.info(f"Запись инвентаризации {record_id} найдена")
logger.debug(f"Запись инвентаризации {record_id} найдена")
return InventoryRecord(*row)
logger.warning(f"Запись инвентаризации {record_id} не найдена")
return None
@@ -48,17 +48,15 @@ class InventoryRepository:
logger.error(f"Ошибка получения записи инвентаризации {record_id}: {e}")
return None
def create_record(
self,
robot_id: str,
product_id: str,
quantity: int,
zone: str,
row_number: int,
shelf_number: int,
status: str,
scanned_at: datetime
) -> Optional[int]:
def create_record(self,
robot_id: str,
product_id: str,
quantity: int,
zone: str,
row_number: int,
shelf_number: int,
status: str,
scanned_at: datetime) -> Optional[int]:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -71,7 +69,7 @@ class InventoryRepository:
record_id = cur.fetchone()[0]
conn.commit()
logger.info(f"Создана новая запись инвентаризации ID: {record_id}")
logger.debug(f"Создана новая запись инвентаризации ID: {record_id}")
return record_id
except Exception as e:
logger.error(f"Ошибка создания записи инвентаризации: {e}")
@@ -87,7 +85,7 @@ class InventoryRepository:
ORDER BY product_id, scanned_at DESC
""")
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(records)} последних записей инвентаризации по товарам")
logger.debug(f"Получено {len(records)} последних записей инвентаризации по товарам")
return records
except Exception as e:
logger.error(f"Ошибка получения последней записи инвентаризации по каждому товару: {e}")
@@ -104,7 +102,7 @@ class InventoryRepository:
LIMIT %s
""", (product_id, limit))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(records)} записей инвентаризации для товара {product_id}")
logger.debug(f"Получено {len(records)} записей инвентаризации для товара {product_id}")
return records
except Exception as e:
logger.error(f"Ошибка получения записи инвентаризации по продукту {product_id}: {e}")
@@ -121,7 +119,7 @@ class InventoryRepository:
LIMIT %s
""", (robot_id, limit))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(records)} записей инвентаризации для робота {robot_id}")
logger.debug(f"Получено {len(records)} записей инвентаризации для робота {robot_id}")
return records
except Exception as e:
logger.error(f"Ошибка получения записи инвентаризации по роботу {robot_id}: {e}")
@@ -138,7 +136,7 @@ class InventoryRepository:
LIMIT %s
""", (zone, limit))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(records)} записей инвентаризации для зоны {zone}")
logger.debug(f"Получено {len(records)} записей инвентаризации для зоны {zone}")
return records
except Exception as e:
logger.error(f"Ошибка получения записи инвентаризации по зоне {zone}: {e}")
@@ -155,7 +153,7 @@ class InventoryRepository:
ORDER BY scanned_at DESC
""", (hours,))
records = [InventoryRecord(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(records)} критических товаров за последние {hours} часов")
logger.debug(f"Получено {len(records)} критических товаров за последние {hours} часов")
return records
except Exception as e:
logger.error(f"Ошибка получения товаров с критическим статусом: {e}")
+8 -8
View File
@@ -20,7 +20,7 @@ class ProductRepository:
optimal_stock=row[4]
) for row in cur.fetchall()
]
logger.info(f"Получено {len(products)} товаров")
logger.debug(f"Получено {len(products)} товаров")
return products
except Exception as e:
logger.error(f"Ошибка получения продуктов: {e}")
@@ -33,7 +33,7 @@ class ProductRepository:
cur.execute("SELECT * FROM products WHERE id = %s", (product_id,))
row = cur.fetchone()
if row:
logger.info(f"Товар {product_id} найден")
logger.debug(f"Товар {product_id} найден")
return Product(*row)
logger.warning(f"Товар {product_id} не найден")
return None
@@ -47,7 +47,7 @@ class ProductRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM products WHERE category = %s ORDER BY name", (category,))
products = [Product(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(products)} товаров категории {category}")
logger.debug(f"Получено {len(products)} товаров категории {category}")
return products
except Exception as e:
logger.error(f"Ошибка получения товаров по категории {category}: {e}")
@@ -65,7 +65,7 @@ class ProductRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Создан новый товар {product_id}: {name}")
logger.debug(f"Создан новый товар {product_id}: {name}")
else:
logger.warning(f"Не удалось создать товар {product_id}")
return success
@@ -108,7 +108,7 @@ class ProductRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Товар {product_id} успешно обновлен")
logger.debug(f"Товар {product_id} успешно обновлен")
else:
logger.warning(f"Товар {product_id} не найден для обновления")
return success
@@ -124,7 +124,7 @@ class ProductRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Товар {product_id} удален")
logger.debug(f"Товар {product_id} удален")
else:
logger.warning(f"Товар {product_id} не найден для удаления")
return success
@@ -142,7 +142,7 @@ class ProductRepository:
ORDER BY name
""", (f'%{search_term}%', f'%{search_term}%'))
products = [Product(*row) for row in cur.fetchall()]
logger.info(f"Найдено {len(products)} товаров по запросу '{search_term}'")
logger.debug(f"Найдено {len(products)} товаров по запросу '{search_term}'")
return products
except Exception as e:
logger.error(f"Ошибка поиска товаров по названию '{search_term}': {e}")
@@ -161,7 +161,7 @@ class ProductRepository:
ORDER BY p.name
""")
products = [Product(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(products)} товаров с низким запасом")
logger.debug(f"Получено {len(products)} товаров с низким запасом")
return products
except Exception as e:
logger.error(f"Ошибка получения товаров с низким запасом: {e}")
+19 -23
View File
@@ -22,7 +22,7 @@ class RobotRepository:
current_shelf=row[6]
) for row in cur.fetchall()
]
logger.info(f"Получено {len(robots)} роботов")
logger.debug(f"Получено {len(robots)} роботов")
return robots
except Exception as e:
logger.error(f"Ошибка получения всех роботов: {e}")
@@ -35,7 +35,7 @@ class RobotRepository:
cur.execute("SELECT * FROM robots WHERE id = %s", (robot_id,))
row = cur.fetchone()
if row:
logger.info(f"Робот {robot_id} найден")
logger.debug(f"Робот {robot_id} найден")
return Robot(*row)
logger.warning(f"Робот {robot_id} не найден")
return None
@@ -43,15 +43,13 @@ class RobotRepository:
logger.error(f"Ошибка получения робота {robot_id}: {e}")
return None
def update_robot(
self,
robot_id: str,
status: str = None,
battery_level: int = None,
current_zone: str = None,
current_row: int = None,
current_shelf: int = None
) -> bool:
def update_robot(self,
robot_id: str,
status: str = None,
battery_level: int = None,
current_zone: str = None,
current_row: int = None,
current_shelf: int = None) -> bool:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -85,7 +83,7 @@ class RobotRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Робот {robot_id} успешно обновлен")
logger.debug(f"Робот {robot_id} успешно обновлен")
else:
logger.warning(f"Робот {robot_id} не найден для обновления")
return success
@@ -99,7 +97,7 @@ class RobotRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM robots WHERE status = %s ORDER BY id", (status,))
robots = [Robot(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(robots)} роботов со статусом {status}")
logger.debug(f"Получено {len(robots)} роботов со статусом {status}")
return robots
except Exception as e:
logger.error(f"Ошибка получения роботов по статусу {status}: {e}")
@@ -115,7 +113,7 @@ class RobotRepository:
ORDER BY battery_level ASC
""", (threshold,))
robots = [Robot(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(robots)} роботов с низким зарядом (<{threshold}%)")
logger.debug(f"Получено {len(robots)} роботов с низким зарядом (<{threshold}%)")
return robots
except Exception as e:
logger.error(f"Ошибка получения роботов с низким зарядом: {e}")
@@ -127,18 +125,16 @@ class RobotRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM robots WHERE current_zone = %s ORDER BY id", (zone,))
robots = [Robot(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(robots)} роботов в зоне {zone}")
logger.debug(f"Получено {len(robots)} роботов в зоне {zone}")
return robots
except Exception as e:
logger.error(f"Ошибка получения роботов в зоне {zone}: {e}")
return []
def create_robot(
self,
robot_id: str,
status: str = 'active',
battery_level: int = 100
) -> bool:
def create_robot(self,
robot_id: str,
status: str = 'active',
battery_level: int = 100) -> bool:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -149,7 +145,7 @@ class RobotRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Создан новый робот {robot_id}")
logger.debug(f"Создан новый робот {robot_id}")
else:
logger.warning(f"Не удалось создать робота {robot_id}")
return success
@@ -165,7 +161,7 @@ class RobotRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Робот {robot_id} удален")
logger.debug(f"Робот {robot_id} удален")
else:
logger.warning(f"Робот {robot_id} не найден для удаления")
return success
+17 -19
View File
@@ -21,7 +21,7 @@ class UserRepository:
created_at=row[5]
) for row in cur.fetchall()
]
logger.info(f"Получено {len(users)} пользователей")
logger.debug(f"Получено {len(users)} пользователей")
return users
except Exception as e:
logger.error(f"Ошибка получения пользователей: {e}")
@@ -34,7 +34,7 @@ class UserRepository:
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
row = cur.fetchone()
if row:
logger.info(f"Пользователь {user_id} найден")
logger.debug(f"Пользователь {user_id} найден")
return User(*row)
logger.warning(f"Пользователь {user_id} не найден")
return None
@@ -49,7 +49,7 @@ class UserRepository:
cur.execute("SELECT * FROM users WHERE email = %s", (email,))
row = cur.fetchone()
if row:
logger.info(f"Пользователь с email {email} найден")
logger.debug(f"Пользователь с email {email} найден")
return User(*row)
logger.warning(f"Пользователь с email {email} не найден")
return None
@@ -57,13 +57,11 @@ class UserRepository:
logger.error(f"Ошибка получения пользователя по email {email}: {e}")
return None
def create_user(
self,
email: str,
password_hash: str,
name: str,
role: str
) -> Optional[User]:
def create_user(self,
email: str,
password_hash: str,
name: str,
role: str) -> Optional[User]:
try:
with get_connection() as conn:
with conn.cursor() as cur:
@@ -77,7 +75,7 @@ class UserRepository:
conn.commit()
if row:
logger.info(f"Создан новый пользователь {email} с ID {row[0]}")
logger.debug(f"Создан новый пользователь {email} с ID {row[0]}")
return User(*row)
logger.warning(f"Не удалось создать пользователя {email}")
return None
@@ -111,7 +109,7 @@ class UserRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Пользователь {user_id} успешно обновлен")
logger.debug(f"Пользователь {user_id} успешно обновлен")
else:
logger.warning(f"Пользователь {user_id} не найден для обновления")
return success
@@ -127,7 +125,7 @@ class UserRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Пользователь {user_id} удален")
logger.debug(f"Пользователь {user_id} удален")
else:
logger.warning(f"Пользователь {user_id} не найден для удаления")
return success
@@ -141,7 +139,7 @@ class UserRepository:
with conn.cursor() as cur:
cur.execute("SELECT * FROM users WHERE role = %s ORDER BY name", (role,))
users = [User(*row) for row in cur.fetchall()]
logger.info(f"Получено {len(users)} пользователей с ролью {role}")
logger.debug(f"Получено {len(users)} пользователей с ролью {role}")
return users
except Exception as e:
logger.error(f"Ошибка получения пользователей по роли {role}: {e}")
@@ -159,7 +157,7 @@ class UserRepository:
conn.commit()
success = cur.rowcount > 0
if success:
logger.info(f"Пароль пользователя {user_id} изменен")
logger.debug(f"Пароль пользователя {user_id} изменен")
else:
logger.warning(f"Пользователь {user_id} не найден для смены пароля")
return success
@@ -177,7 +175,7 @@ class UserRepository:
""", (email, password_hash))
row = cur.fetchone()
if row:
logger.info(f"Успешная аутентификация пользователя {email}")
logger.debug(f"Успешная аутентификация пользователя {email}")
return User(*row)
logger.warning(f"Неудачная аутентификация пользователя {email}")
return None
@@ -195,7 +193,7 @@ class UserRepository:
""", (email, password_hash))
is_valid = cur.fetchone() is not None
if is_valid:
logger.info(f"Валидные учетные данные для пользователя {email}")
logger.debug(f"Валидные учетные данные для пользователя {email}")
else:
logger.warning(f"Невалидные учетные данные для пользователя {email}")
return is_valid
@@ -210,9 +208,9 @@ class UserRepository:
cur.execute("SELECT 1 FROM users WHERE email = %s", (email,))
exists = cur.fetchone() is not None
if exists:
logger.info(f"Пользователь с email {email} существует")
logger.debug(f"Пользователь с email {email} существует")
else:
logger.info(f"Пользователь с email {email} не существует")
logger.debug(f"Пользователь с email {email} не существует")
return exists
except Exception as e:
logger.error(f"Ошибка проверки существования пользователя {email}: {e}")
+1 -2
View File
@@ -1,5 +1,4 @@
flask==3.1.2
python-dotenv
psycopg2-binary
psycopg-binary
pyjwt
loguru
-11
View File
@@ -1,6 +1,5 @@
from dataclasses import dataclass
from datetime import datetime
from utils.token import generateKey
@dataclass
@@ -11,13 +10,3 @@ class User:
name: str
role: str
created_at: datetime
def __init__(self, email: str, passwd: str):
#us = getUsModel() #возвращает словарь
self.id = 1#us['id']
self.name = 'Bob'#us['name']
self.role = 'Backend'#us['role']
self.token = generateKey(email, passwd)
def toJson(self):
return {"user": {"id": self.id, "name": self.name, "role": self.role}, "token": self.token}
+8 -10
View File
@@ -1,14 +1,12 @@
import os
from dotenv import load_dotenv
from loguru import logger as log
DOTENV_PATH = '.env'
def initializeENV() -> bool:
if os.path.exists(DOTENV_PATH):
load_dotenv(DOTENV_PATH)
log.info('.env is loaded')
return True
def initializeENV():
dotenv_path = '../.env'
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
print('.env is loaded')
return 1
else:
log.error('.env isn`t loaded')
return False
print('.env isn`t loaded')
return 0
+1 -2
View File
@@ -1,8 +1,7 @@
import jwt
import os
from time import time
def generateKey(email, passwd):
key = os.getenv('KEY')
encoded = jwt.encode({email: passwd, 'iat': time()}, key, algorithm="HS256")
encoded = jwt.encode({f"{email}": f"{passwd}"}, key, algorithm="HS256")
return encoded