Files
new_lottery_bot/src/components/ui.py
Andrey K. Choi 4e2c8981c2
All checks were successful
continuous-integration/drone/push Build is passing
chat restore
2026-02-09 20:07:46 +09:00

135 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import List
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton
from src.interfaces.base import IKeyboardBuilder, IMessageFormatter
from src.core.models import Lottery, Winner
class KeyboardBuilderImpl(IKeyboardBuilder):
"""Реализация построителя клавиатур"""
def get_main_keyboard(self, is_admin: bool = False, is_registered: bool = False):
"""Получить главную клавиатуру"""
buttons = [
[InlineKeyboardButton(text="🎲 Активные розыгрыши", callback_data="active_lotteries")],
[InlineKeyboardButton(text="💬 Войти в чат", callback_data="enter_chat")]
]
# Показываем кнопку регистрации только незарегистрированным пользователям (не админам)
if not is_admin and not is_registered:
buttons.append([InlineKeyboardButton(text="📝 Зарегистрироваться", callback_data="start_registration")])
if is_admin:
buttons.extend([
[InlineKeyboardButton(text="⚙️ Админ панель", callback_data="admin_panel")],
[InlineKeyboardButton(text=" Создать розыгрыш", callback_data="admin_create_lottery")]
])
return InlineKeyboardMarkup(inline_keyboard=buttons)
def get_admin_keyboard(self):
"""Получить админскую клавиатуру"""
buttons = [
[InlineKeyboardButton(text="🎲 Управление розыгрышами", callback_data="admin_lotteries")],
[InlineKeyboardButton(text="👥 Управление участниками", callback_data="admin_participants")],
[InlineKeyboardButton(text="👑 Управление победителями", callback_data="admin_winners")],
[InlineKeyboardButton(text="💬 Сообщения пользователей", callback_data="admin_messages")],
[InlineKeyboardButton(text="📊 Статистика", callback_data="admin_stats")],
[InlineKeyboardButton(text="⚙️ Настройки", callback_data="admin_settings")],
[InlineKeyboardButton(text="🔙 Назад", callback_data="back_to_main")]
]
return InlineKeyboardMarkup(inline_keyboard=buttons)
class MessageFormatterImpl(IMessageFormatter):
"""Реализация форматирования сообщений"""
def get_lottery_keyboard(self, lottery_id: int, is_admin: bool = False):
"""Получить клавиатуру для конкретного розыгрыша"""
buttons = [
[InlineKeyboardButton(text="🎯 Участвовать", callback_data=f"join_{lottery_id}")]
]
if is_admin:
buttons.extend([
[InlineKeyboardButton(text="🎲 Провести розыгрыш", callback_data=f"conduct_{lottery_id}")],
[InlineKeyboardButton(text="✏️ Редактировать", callback_data=f"edit_{lottery_id}")],
[InlineKeyboardButton(text="❌ Удалить", callback_data=f"delete_{lottery_id}")]
])
buttons.append([InlineKeyboardButton(text="🔙 Назад", callback_data="active_lotteries")])
return InlineKeyboardMarkup(inline_keyboard=buttons)
def get_conduct_lottery_keyboard(self, lotteries: List[Lottery]):
"""Получить клавиатуру для выбора розыгрыша для проведения"""
buttons = []
for lottery in lotteries:
text = f"🎲 {lottery.title}"
if len(text) > 50:
text = text[:47] + "..."
buttons.append([InlineKeyboardButton(text=text, callback_data=f"conduct_{lottery.id}")])
buttons.append([InlineKeyboardButton(text="🔙 Назад", callback_data="lottery_management")])
return InlineKeyboardMarkup(inline_keyboard=buttons)
class MessageFormatterImpl(IMessageFormatter):
"""Реализация форматирования сообщений"""
def format_lottery_info(self, lottery: Lottery, participants_count: int) -> str:
"""Форматировать информацию о розыгрыше"""
text = f"🎲 **{lottery.title}**\n\n"
if lottery.description:
text += f"📝 {lottery.description}\n\n"
text += f"👥 Участников: {participants_count}\n"
if lottery.prizes:
text += "\n🏆 **Призы:**\n"
for i, prize in enumerate(lottery.prizes, 1):
text += f"{i}. {prize}\n"
status = "🟢 Активный" if lottery.is_active and not lottery.is_completed else "🔴 Завершен"
text += f"\n📊 Статус: {status}"
if lottery.created_at:
text += f"\n📅 Создан: {lottery.created_at.strftime('%d.%m.%Y %H:%M')}"
return text
def format_winners_list(self, winners: List[Winner]) -> str:
"""Форматировать список победителей"""
if not winners:
return "🎯 Победители не определены"
text = "🏆 **Победители:**\n\n"
for winner in winners:
place_emoji = {1: "🥇", 2: "🥈", 3: "🥉"}.get(winner.place, "🏅")
if winner.user:
name = winner.user.first_name or f"Пользователь {winner.user.telegram_id}"
else:
name = winner.account_number or "Неизвестный участник"
text += f"{place_emoji} **{winner.place} место:** {name}\n"
if winner.prize:
text += f" 🎁 Приз: {winner.prize}\n"
text += "\n"
return text
def format_admin_stats(self, stats: dict) -> str:
"""Форматировать административную статистику"""
text = "📊 **Статистика системы**\n\n"
text += f"👥 Всего пользователей: {stats.get('total_users', 0)}\n"
text += f"✅ Зарегистрированных: {stats.get('registered_users', 0)}\n"
text += f"🎲 Всего розыгрышей: {stats.get('total_lotteries', 0)}\n"
text += f"🟢 Активных розыгрышей: {stats.get('active_lotteries', 0)}\n"
text += f"✅ Завершенных розыгрышей: {stats.get('completed_lotteries', 0)}\n"
text += f"🎯 Всего участий: {stats.get('total_participations', 0)}\n"
return text