Files
Touchh/bot/operations/hotels.py
2024-12-25 12:01:19 +09:00

205 lines
9.2 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
from touchh.utils.log import CustomLogger
logger = CustomLogger(name="BOT-hotels Manager", log_level="DEBUG").get_logger()
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]
# logger.debug(f"Hotel ID: {hotel_id}")
# logger.debug(f"Hotel ID type : {type(hotel_id)}")
# # Получение конфигурации отеля и 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'])}"
# )
# logger.info(f'Result_Message: {result_message}\n Result_meaage_type: {type(result_message)}')
# 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 check_pms(update, context):
query = update.callback_query
try:
# Получение ID отеля из callback_data
hotel_id = query.data.split("_")[2]
logger.debug(f"Hotel ID: {hotel_id}")
logger.debug(f"Hotel ID type : {type(hotel_id)}")
# Получение конфигурации отеля и 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()
logger.debug(f"REPORT: {report}, TYPE: {type(report)}")
else:
await query.edit_message_text("Подходящий способ интеграции с PMS не найден.")
return
# Проверяем результат выполнения fetch_data
if not report or not isinstance(report, dict):
logger.error(f"Некорректный отчет от fetch_data: {report}")
await query.edit_message_text("Ошибка: Отчет fetch_data отсутствует или имеет некорректный формат.")
return
# Формируем сообщение о результатах
result_message = (
f"Интеграция PMS завершена успешно.\n"
f"Обработано интервалов: {report.get('processed_intervals', 0)}\n"
f"Обработано записей: {report.get('processed_items', 0)}\n"
f"Ошибки: {len(report.get('errors', []))}"
)
if report.get("errors"):
result_message += "\n\nСписок ошибок:\n" + "\n".join(report["errors"])
logger.info(f"Result_Message: {result_message}")
await query.edit_message_text(result_message)
except Exception as e:
# Обрабатываем и логируем ошибки
logger.error(f"Ошибка в методе check_pms: {str(e)}", exc_info=True)
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