Files
Touchh/bot/operations/hotels.py
trevor 93994ed929 settings application
.env db params+global settings in admin model
ECVI plugin module
2024-12-14 20:50:11 +09:00

143 lines
6.1 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 telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from asgiref.sync import sync_to_async
from hotels.models import Hotel, UserHotel
from users.models import User
from pms_integration.manager import PMSIntegrationManager
from bot.utils.froud_check import detect_fraud
async def manage_hotels(update: Update, context):
"""Отображение списка отелей, связанных с пользователем."""
query = update.callback_query
await query.answer()
user_id = query.from_user.id
user = await sync_to_async(User.objects.filter(chat_id=user_id).first)()
if not user:
await query.edit_message_text("Вы не зарегистрированы в системе.")
return
user_hotels = await sync_to_async(list)(
UserHotel.objects.filter(user=user).select_related("hotel")
)
if not user_hotels:
await query.edit_message_text("У вас нет связанных отелей.")
return
keyboard = [
[InlineKeyboardButton(f"🏨 {hotel.hotel.name}", callback_data=f"hotel_{hotel.hotel.id}")]
for hotel in user_hotels
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text("Выберите отель:", reply_markup=reply_markup)
async def hotel_actions(update: Update, context):
"""Обработчик действий для выбранного отеля."""
query = update.callback_query
await query.answer()
hotel_id = int(query.data.split("_")[1])
print(f"Selected hotel id: {hotel_id}")
hotel = await sync_to_async(Hotel.objects.filter(id=hotel_id).first)()
if not hotel:
await query.edit_message_text("Отель не найден.")
return
keyboard = [
[InlineKeyboardButton("🗑️ Удалить отель", callback_data=f"delete_hotel_{hotel_id}")],
[InlineKeyboardButton("Проверить на FRAUD", callback_data=f"check_fraud_{hotel_id}")],
[InlineKeyboardButton("🔗 Проверить интеграцию с PMS", callback_data=f"check_pms_{hotel_id}")],
[InlineKeyboardButton("🛏️ Настроить номера", callback_data=f"setup_rooms_{hotel_id}")],
[InlineKeyboardButton("🏠 Главная", callback_data="main_menu")],
[InlineKeyboardButton("🔙 Назад", callback_data="back")],
]
reply_markup = InlineKeyboardMarkup(keyboard)
await query.edit_message_text(f"Управление отелем: {hotel.name}", reply_markup=reply_markup)
async def handle_fraud_check(update, context):
query = update.callback_query
hotel_id = int(query.data.split("_")[2])
await detect_fraud(hotel_id)
await query.edit_message_text("Проверка на FRAUD завершена. Администратор уведомлен.")
async def delete_hotel(update: Update, context):
"""Удаление отеля."""
query = update.callback_query
await query.answer()
hotel_id = int(query.data.split("_")[2])
hotel = await sync_to_async(Hotel.objects.filter(id=hotel_id).first)()
if hotel:
hotel_name = hotel.name
await sync_to_async(hotel.delete)()
await query.edit_message_text(f"Отель {hotel_name} успешно удалён.")
else:
await query.edit_message_text("Отель не найден.")
async def check_pms(update, context):
query = update.callback_query
try:
# Получение ID отеля из callback_data
hotel_id = query.data.split("_")[2]
# Получение конфигурации отеля и PMS
hotel = await sync_to_async(Hotel.objects.select_related('pms').get)(id=hotel_id)
pms_config = hotel.pms
if not pms_config:
await query.edit_message_text("PMS конфигурация не найдена.")
return
# Создаем экземпляр PMSIntegrationManager
pms_manager = PMSIntegrationManager(hotel_id=hotel_id)
await pms_manager.load_hotel()
await sync_to_async(pms_manager.load_plugin)()
# Проверяем, какой способ интеграции использовать
if hasattr(pms_manager.plugin, 'fetch_data') and callable(pms_manager.plugin.fetch_data):
# Плагин поддерживает метод fetch_data
report = await pms_manager.plugin._fetch_data()
else:
await query.edit_message_text("Подходящий способ интеграции с PMS не найден.")
return
# Формируем сообщение о результатах
result_message = (
f"Интеграция PMS завершена успешно.\n"
f"Обработано интервалов: {report['processed_intervals']}\n"
f"Обработано записей: {report['processed_items']}\n"
f"Ошибки: {len(report['errors'])}"
)
if report["errors"]:
result_message += "\n\nСписок ошибок:\n" + "\n".join(report["errors"])
await query.edit_message_text(result_message)
except Exception as e:
# Обрабатываем и логируем ошибки
await query.edit_message_text(f"❌ Ошибка: {str(e)}")
async def setup_rooms(update: Update, context):
"""Настроить номера отеля."""
query = update.callback_query
await query.answer()
hotel_id = int(query.data.split("_")[2])
hotel = await sync_to_async(Hotel.objects.filter(id=hotel_id).first)()
if not hotel:
await query.edit_message_text("Отель не найден.")
return
await query.edit_message_text(f"Настройка номеров для отеля: {hotel.name}")
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