bot refactor
This commit is contained in:
163
bot/operations/users.py
Normal file
163
bot/operations/users.py
Normal file
@@ -0,0 +1,163 @@
|
||||
from asgiref.sync import sync_to_async
|
||||
from telegram import Update
|
||||
from telegram.ext import ContextTypes
|
||||
from telegram.ext import CallbackContext
|
||||
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from telegram import KeyboardButton, ReplyKeyboardMarkup
|
||||
|
||||
from hotels.models import Hotel, UserHotel
|
||||
from users.models import User
|
||||
|
||||
|
||||
async def edit_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Изменение имени пользователя."""
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
user_id = int(query.data.split("_")[2])
|
||||
context.user_data["edit_user_id"] = user_id
|
||||
|
||||
await query.edit_message_text("Введите новое имя пользователя:")
|
||||
|
||||
async def delete_user(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Удаление пользователя."""
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
user_id = int(query.data.split("_")[2])
|
||||
user = await sync_to_async(User.objects.get)(id=user_id)
|
||||
await sync_to_async(user.delete)()
|
||||
|
||||
await query.edit_message_text("Пользователь успешно удален.")
|
||||
|
||||
async def get_users_for_hotel(hotel_id):
|
||||
"""
|
||||
Получение пользователей, зарегистрированных в отеле с правами управления через бота.
|
||||
"""
|
||||
users = await sync_to_async(list)(
|
||||
User.objects.filter(user_hotels__hotel_id=hotel_id, user_hotels__role__in=["admin", "manager"]).distinct()
|
||||
)
|
||||
return users
|
||||
|
||||
|
||||
async def show_users(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Показать пользователей, зарегистрированных в отеле."""
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
# Если callback_data не содержит ID отеля, отображаем список отелей
|
||||
if not query.data.startswith("manage_users_hotel_"):
|
||||
user_id = query.from_user.id
|
||||
hotels = await get_hotels_for_user(user_id)
|
||||
|
||||
if not hotels:
|
||||
await query.edit_message_text("У вас нет доступных отелей.")
|
||||
return
|
||||
|
||||
keyboard = [
|
||||
[InlineKeyboardButton(hotel.name, callback_data=f"manage_users_hotel_{hotel.id}")]
|
||||
for hotel in hotels
|
||||
]
|
||||
keyboard.append([InlineKeyboardButton("🏠 Главная", callback_data="main_menu")])
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await query.edit_message_text("Выберите отель:", reply_markup=reply_markup)
|
||||
return
|
||||
|
||||
# Обработка пользователей отеля
|
||||
hotel_id = int(query.data.split("_")[-1])
|
||||
users = await sync_to_async(list)(
|
||||
User.objects.filter(user_hotel__hotel_id=hotel_id)
|
||||
)
|
||||
|
||||
if not users:
|
||||
await query.edit_message_text("В этом отеле нет пользователей.")
|
||||
return
|
||||
|
||||
keyboard = [
|
||||
[InlineKeyboardButton(f"{user.username}", callback_data=f"edit_user_{user.id}")]
|
||||
for user in users
|
||||
]
|
||||
keyboard.append([
|
||||
InlineKeyboardButton("🏠 Главная", callback_data="main_menu"),
|
||||
InlineKeyboardButton("🔙 Назад", callback_data="manage_users"),
|
||||
[InlineKeyboardButton("🏠 Главная", callback_data="main_menu")],
|
||||
[InlineKeyboardButton("🔙 Назад", callback_data="back")],
|
||||
])
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await query.edit_message_text("Выберите пользователя:", reply_markup=reply_markup)
|
||||
|
||||
|
||||
async def get_hotels_for_user(user):
|
||||
"""Получение отелей, связанных с пользователем."""
|
||||
return await sync_to_async(list)(
|
||||
Hotel.objects.filter(hotel_users__user=user).distinct()
|
||||
)
|
||||
|
||||
async def show_user_hotels(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Показ списка отелей пользователя."""
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
user_id = query.from_user.id
|
||||
user_hotels = await get_hotels_for_user(user_id)
|
||||
|
||||
if not user_hotels:
|
||||
await query.edit_message_text("У вас нет связанных отелей.")
|
||||
return
|
||||
|
||||
keyboard = [
|
||||
[InlineKeyboardButton(hotel.name, callback_data=f"users_hotel_{hotel.id}")]
|
||||
for hotel in user_hotels
|
||||
]
|
||||
keyboard.append([InlineKeyboardButton("🔙 Назад", callback_data="main_menu")])
|
||||
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await query.edit_message_text("Выберите отель:", reply_markup=reply_markup)
|
||||
|
||||
async def show_users_in_hotel(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Показ пользователей в выбранном отеле."""
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
hotel_id = int(query.data.split("_")[2])
|
||||
users = await get_users_for_hotel(hotel_id)
|
||||
|
||||
if not users:
|
||||
await query.edit_message_text("В этом отеле нет пользователей.")
|
||||
return
|
||||
|
||||
keyboard = [
|
||||
[InlineKeyboardButton(f"{user.first_name} {user.last_name}", callback_data=f"user_action_{user.id}")]
|
||||
for user in users
|
||||
]
|
||||
keyboard.append([
|
||||
InlineKeyboardButton("🏠 Главная", callback_data="main_menu"),
|
||||
InlineKeyboardButton("🔙 Назад", callback_data="manage_users"),
|
||||
])
|
||||
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await query.edit_message_text("Пользователи отеля:", reply_markup=reply_markup)
|
||||
|
||||
async def user_action_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Меню действий для пользователя."""
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
user_id = int(query.data.split("_")[2])
|
||||
user = await sync_to_async(User.objects.get)(id=user_id)
|
||||
|
||||
keyboard = [
|
||||
[InlineKeyboardButton("✏️ Изменить имя", callback_data=f"edit_user_{user_id}")],
|
||||
[InlineKeyboardButton("🗑️ Удалить", callback_data=f"delete_user_{user_id}")],
|
||||
[
|
||||
InlineKeyboardButton("🏠 Главная", callback_data="main_menu"),
|
||||
InlineKeyboardButton("🔙 Назад", callback_data="users_hotel"),
|
||||
],
|
||||
]
|
||||
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
await query.edit_message_text(
|
||||
f"Пользователь: {user.first_name} {user.last_name}\nВыберите действие:",
|
||||
reply_markup=reply_markup,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user