refactor: clean up unused code and duplicate handlers

- Removed duplicate admin callback handlers from main.py (moved to admin_panel.py)
- Removed unused methods from BotController (handle_admin_panel, handle_lottery_management, handle_conduct_lottery_admin, handle_conduct_lottery)
- Removed unused keyboard methods from ui.py (get_lottery_management_keyboard, get_lottery_keyboard, get_conduct_lottery_keyboard)
- Simplified IBotController interface to only essential methods
- Simplified IKeyboardBuilder interface to only used methods
- Fixed cmd_admin handler to directly show admin panel
- Bot now uses centralized admin handlers from admin_panel.py
This commit is contained in:
2025-11-17 08:00:39 +09:00
parent 0fdf01d1c7
commit 43d46ea6f8
5 changed files with 21 additions and 202 deletions

View File

@@ -1 +1 @@
788605
802748

70
main.py
View File

@@ -57,53 +57,25 @@ async def cmd_start(message: Message):
@router.message(Command("admin"))
async def cmd_admin(message: Message):
"""Обработчик команды /admin"""
async with get_controller() as controller:
if not controller.is_admin(message.from_user.id):
await message.answer("❌ Недостаточно прав для доступа к админ панели")
return
# Создаем callback query объект для совместимости
from aiogram.types import CallbackQuery
fake_callback = CallbackQuery(
id="admin_cmd",
from_user=message.from_user,
chat_instance="admin",
data="admin_panel",
message=message
)
await controller.handle_admin_panel(fake_callback)
"""Обработчик команды /admin - перенаправляет в admin_panel"""
from src.core.config import ADMIN_IDS
if message.from_user.id not in ADMIN_IDS:
await message.answer("❌ Недостаточно прав для доступа к админ панели")
return
# Отправляем сообщение с кнопкой админ панели
from src.components.ui import KeyboardBuilderImpl
kb = KeyboardBuilderImpl()
keyboard = kb.get_admin_keyboard()
text = "⚙️ **Панель администратора**\n\n"
text += "Выберите раздел для управления:"
await message.answer(text, reply_markup=keyboard, parse_mode="Markdown")
# === CALLBACK HANDLERS ===
@router.callback_query(F.data == "test_callback")
async def test_callback_handler(callback: CallbackQuery):
"""Тестовый callback handler"""
await callback.answer("✅ Тест прошел успешно! Колбэки работают.", show_alert=True)
@router.callback_query(F.data == "admin_panel")
async def admin_panel_handler(callback: CallbackQuery):
"""Обработчик админ панели"""
async with get_controller() as controller:
await controller.handle_admin_panel(callback)
@router.callback_query(F.data == "lottery_management")
async def lottery_management_handler(callback: CallbackQuery):
"""Обработчик управления розыгрышами (старый callback)"""
async with get_controller() as controller:
await controller.handle_lottery_management(callback)
@router.callback_query(F.data == "conduct_lottery_admin")
async def conduct_lottery_admin_handler(callback: CallbackQuery):
"""Обработчик выбора розыгрыша для проведения"""
async with get_controller() as controller:
await controller.handle_conduct_lottery_admin(callback)
@router.callback_query(F.data == "active_lotteries")
async def active_lotteries_handler(callback: CallbackQuery):
"""Обработчик показа активных розыгрышей"""
@@ -111,23 +83,11 @@ async def active_lotteries_handler(callback: CallbackQuery):
await controller.handle_active_lotteries(callback)
@router.callback_query(F.data.startswith("conduct_") & ~F.data.in_(["conduct_lottery_admin"]))
async def conduct_specific_lottery_handler(callback: CallbackQuery):
"""Обработчик проведения конкретного розыгрыша"""
async with get_controller() as controller:
await controller.handle_conduct_lottery(callback)
@router.callback_query(F.data == "back_to_main")
async def back_to_main_handler(callback: CallbackQuery):
"""Обработчик возврата в главное меню"""
async with get_controller() as controller:
await controller.handle_start(callback.message)
# === ЗАГЛУШКИ ДЛЯ ОСТАЛЬНЫХ CALLBACKS ===
# === ЗАГЛУШКИ НЕ НУЖНЫ - ВСЕ ФУНКЦИИ РЕАЛИЗОВАНЫ В РОУТЕРАХ ===
# Функции обрабатываются в:
# - admin_panel.py: создание розыгрышей, управление пользователями, счетами, чатом, статистика
# - registration_handlers.py: регистрация пользователей

View File

@@ -37,19 +37,10 @@ class KeyboardBuilderImpl(IKeyboardBuilder):
[InlineKeyboardButton(text="🔙 Назад", callback_data="back_to_main")]
]
return InlineKeyboardMarkup(inline_keyboard=buttons)
def get_lottery_management_keyboard(self):
"""Получить клавиатуру управления розыгрышами"""
buttons = [
[InlineKeyboardButton(text=" Создать розыгрыш", callback_data="admin_create_lottery")],
[InlineKeyboardButton(text="📝 Редактировать розыгрыш", callback_data="admin_edit_lottery")],
[InlineKeyboardButton(text="🎭 Настройка отображения победителей", callback_data="admin_winner_display_settings")],
[InlineKeyboardButton(text="📋 Список всех розыгрышей", callback_data="admin_list_all_lotteries")],
[InlineKeyboardButton(text="<EFBFBD> Завершить розыгрыш", callback_data="admin_finish_lottery")],
[InlineKeyboardButton(text="<EFBFBD> Удалить розыгрыш", callback_data="admin_delete_lottery")],
[InlineKeyboardButton(text="🔙 Назад", callback_data="admin_panel")]
]
return InlineKeyboardMarkup(inline_keyboard=buttons)
class MessageFormatterImpl(IMessageFormatter):
"""Реализация форматирования сообщений"""
def get_lottery_keyboard(self, lottery_id: int, is_admin: bool = False):
"""Получить клавиатуру для конкретного розыгрыша"""

View File

@@ -59,67 +59,6 @@ class BotController(IBotController):
reply_markup=keyboard
)
async def handle_admin_panel(self, callback: CallbackQuery):
"""Обработать админ панель"""
if not self.is_admin(callback.from_user.id):
await callback.answer("❌ Недостаточно прав", show_alert=True)
return
text = "⚙️ **Панель администратора**\n\n"
text += "Выберите раздел для управления:"
keyboard = self.keyboard_builder.get_admin_keyboard()
await callback.message.edit_text(
text,
reply_markup=keyboard,
parse_mode="Markdown"
)
async def handle_lottery_management(self, callback: CallbackQuery):
"""Обработать управление розыгрышами"""
if not self.is_admin(callback.from_user.id):
await callback.answer("❌ Недостаточно прав", show_alert=True)
return
text = "🎯 **Управление розыгрышами**\n\n"
text += "Выберите действие:"
keyboard = self.keyboard_builder.get_lottery_management_keyboard()
await callback.message.edit_text(
text,
reply_markup=keyboard,
parse_mode="Markdown"
)
async def handle_conduct_lottery_admin(self, callback: CallbackQuery):
"""Обработать выбор розыгрыша для проведения"""
if not self.is_admin(callback.from_user.id):
await callback.answer("❌ Недостаточно прав", show_alert=True)
return
# Получаем активные розыгрыши
lotteries = await self.lottery_service.get_active_lotteries()
if not lotteries:
await callback.answer("❌ Нет активных розыгрышей", show_alert=True)
return
text = "🎯 **Выберите розыгрыш для проведения:**\n\n"
for lottery in lotteries:
participants_count = await self.participation_repo.get_count_by_lottery(lottery.id)
text += f"🎲 {lottery.title} ({participants_count} участников)\n"
keyboard = self.keyboard_builder.get_conduct_lottery_keyboard(lotteries)
await callback.message.edit_text(
text,
reply_markup=keyboard,
parse_mode="Markdown"
)
async def handle_active_lotteries(self, callback: CallbackQuery):
"""Показать активные розыгрыши"""
lotteries = await self.lottery_repo.get_active()
@@ -152,40 +91,4 @@ class BotController(IBotController):
text,
reply_markup=keyboard,
parse_mode="Markdown"
)
async def handle_conduct_lottery(self, callback: CallbackQuery):
"""Провести конкретный розыгрыш"""
if not self.is_admin(callback.from_user.id):
await callback.answer("❌ Недостаточно прав", show_alert=True)
return
try:
lottery_id = int(callback.data.split("_")[1])
except (ValueError, IndexError):
await callback.answer("❌ Неверный формат данных", show_alert=True)
return
# Проводим розыгрыш
results = await self.lottery_service.conduct_draw(lottery_id)
if not results:
await callback.answer("Не удалось провести розыгрыш", show_alert=True)
return
# Форматируем результаты
text = "🎉 **Розыгрыш завершен!**\n\n"
winners = [result['winner'] for result in results.values()]
winners_text = self.message_formatter.format_winners_list(winners)
text += winners_text
keyboard = self.keyboard_builder.get_admin_keyboard()
await callback.message.edit_text(
text,
reply_markup=keyboard,
parse_mode="Markdown"
)
await callback.answer("✅ Розыгрыш успешно проведен!", show_alert=True)
)

View File

@@ -130,30 +130,10 @@ class IBotController(ABC):
"""Обработать команду /start"""
pass
@abstractmethod
async def handle_admin_panel(self, callback):
"""Обработать admin panel"""
pass
@abstractmethod
async def handle_lottery_management(self, callback):
"""Обработать управление розыгрышами"""
pass
@abstractmethod
async def handle_conduct_lottery_admin(self, callback):
"""Обработать выбор розыгрыша для проведения"""
pass
@abstractmethod
async def handle_active_lotteries(self, callback):
"""Обработать показ активных розыгрышей"""
pass
@abstractmethod
async def handle_conduct_lottery(self, callback):
"""Обработать проведение конкретного розыгрыша"""
pass
class IMessageFormatter(ABC):
@@ -181,19 +161,4 @@ class IKeyboardBuilder(ABC):
@abstractmethod
def get_admin_keyboard(self):
"""Получить админскую клавиатуру"""
pass
@abstractmethod
def get_lottery_keyboard(self, lottery_id: int, is_admin: bool):
"""Получить клавиатуру для розыгрыша"""
pass
@abstractmethod
def get_lottery_management_keyboard(self):
"""Получить клавиатуру управления розыгрышами"""
pass
@abstractmethod
def get_conduct_lottery_keyboard(self, lotteries: List[Lottery]):
"""Получить клавиатуру для выбора розыгрыша для проведения"""
pass