109 lines
4.0 KiB
Python
109 lines
4.0 KiB
Python
import logging
|
||
from datetime import datetime
|
||
|
||
from aiogram.types import CallbackQuery
|
||
from aiogram_dialog import DialogManager
|
||
from aiogram_dialog.widgets.kbd import Select
|
||
from sqlalchemy import select
|
||
from sqlalchemy.exc import SQLAlchemyError
|
||
|
||
from shopbot.bot.database.db import async_session
|
||
from shopbot.bot.database.models import Account, UserModel
|
||
from shopbot.bot.states import PurchaseAccountsSG
|
||
|
||
ACCOUNT_INFO_TEMPLATE = (
|
||
"<b>Подробная информация об аккаунте:</b>\n\n"
|
||
"<b>💰 Цена:</b> {price:.2f}₽\n\n"
|
||
"<b>🔑 Логин:</b> {login}\n"
|
||
"<b>🔒 Пароль:</b> {password}\n\n"
|
||
"<b>🌍 Регион:</b> {region}\n"
|
||
"<b>🎮 Ранг:</b> {current_rank}\n"
|
||
"<b>🔪 Количество ножей:</b> {knife_count}\n"
|
||
"<b>🛡️ Количество агентов:</b> {agent_count}\n"
|
||
"<b>🖌️ Скины:</b> {skin_count}\n"
|
||
"<b>🗡️ Стоимость инвентаря:</b> {inventory_value}VP\n"
|
||
"<b>📈 Последний ранг:</b> {last_rank}\n"
|
||
"<b>🏅 Уровень:</b> {level}\n"
|
||
)
|
||
|
||
|
||
async def _format_account_info(account: Account) -> str:
|
||
return ACCOUNT_INFO_TEMPLATE.format(
|
||
price=account.price,
|
||
login=account.login,
|
||
password=account.password,
|
||
region=account.region,
|
||
current_rank=account.current_rank,
|
||
knife_count=account.knife_count,
|
||
agent_count=account.agent_count,
|
||
skin_count=account.skin_count,
|
||
inventory_value=account.inventory_value,
|
||
last_rank=account.last_rank,
|
||
level=account.level,
|
||
)
|
||
|
||
|
||
async def on_account_selected(
|
||
callback: CallbackQuery, select: Select, manager: DialogManager, item_id: int
|
||
):
|
||
manager.current_context().dialog_data["selected_account_id"] = int(item_id)
|
||
await manager.next()
|
||
|
||
|
||
async def on_buy_button_click(
|
||
callback: CallbackQuery, button, dialog_manager: DialogManager, **kwargs
|
||
):
|
||
account_id = dialog_manager.current_context().dialog_data.get("selected_account_id")
|
||
user_tg_id = callback.from_user.id
|
||
|
||
if not account_id:
|
||
await callback.message.answer("Ошибка: не выбран аккаунт для покупки.")
|
||
return
|
||
|
||
try:
|
||
async with async_session() as session:
|
||
async with session.begin():
|
||
account = await session.scalar(
|
||
select(Account).where(
|
||
Account.id == account_id,
|
||
Account.is_sold == False, # noqa: E712
|
||
)
|
||
)
|
||
if not account:
|
||
await callback.message.answer("Аккаунт не найден!")
|
||
return
|
||
|
||
user = await session.scalar(
|
||
select(UserModel).where(UserModel.tg_id == user_tg_id)
|
||
)
|
||
if not user:
|
||
await callback.message.answer("Ваш профиль не найден в системе!")
|
||
return
|
||
|
||
if user.balance < account.price:
|
||
difference = account.price - user.balance
|
||
await callback.message.answer(
|
||
f"Недостаточно средств для покупки аккаунта.\n"
|
||
f"Пополните баланс на {difference:.2f}₽."
|
||
)
|
||
return
|
||
|
||
user.balance -= account.price
|
||
user.purchased += 1
|
||
|
||
account.is_sold = True
|
||
account.buyer = user.tg_id
|
||
account.date_purchase = datetime.utcnow()
|
||
|
||
await session.commit()
|
||
|
||
dialog_manager.current_context().dialog_data[
|
||
"account_info"
|
||
] = await _format_account_info(account)
|
||
await dialog_manager.switch_to(PurchaseAccountsSG.purchase_completed)
|
||
|
||
except SQLAlchemyError as e:
|
||
logging.error(f"Database error: {e}", exc_info=True)
|
||
except Exception as e:
|
||
logging.error(f"An unexpected error occurred: {e}", exc_info=True)
|