Shelter PMS fully functional
This commit is contained in:
@@ -4,7 +4,11 @@ from bot.operations.hotels import manage_hotels, hotel_actions, delete_hotel, ch
|
||||
from bot.operations.statistics import statistics, stats_select_period, generate_statistics
|
||||
from bot.operations.settings import settings_menu, toggle_telegram, toggle_email, set_notification_time, show_current_settings
|
||||
from bot.operations.users import show_users
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
from pms_integration.api_client import APIClient
|
||||
|
||||
from users.models import User, NotificationSettings
|
||||
from hotels.models import Hotel
|
||||
|
||||
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Обработчик команды /start."""
|
||||
@@ -93,3 +97,27 @@ async def navigate_back(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
await hotel_actions(update, context)
|
||||
else:
|
||||
await update.callback_query.edit_message_text("Команда не распознана.")
|
||||
|
||||
|
||||
async def sync_hotel_data(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Синхронизация данных отеля через API."""
|
||||
user_id = update.effective_user.id
|
||||
|
||||
try:
|
||||
user = User.objects.get(chat_id=user_id)
|
||||
hotels = Hotel.objects.filter(hotel_users__user=user)
|
||||
except ObjectDoesNotExist:
|
||||
await update.message.reply_text("Вы не зарегистрированы.")
|
||||
return
|
||||
|
||||
if not hotels:
|
||||
await update.message.reply_text("У вас нет доступных отелей для синхронизации.")
|
||||
return
|
||||
|
||||
for hotel in hotels:
|
||||
try:
|
||||
client = APIClient(hotel.pms)
|
||||
client.run(hotel)
|
||||
await update.message.reply_text(f"Данные отеля {hotel.name} успешно синхронизированы.")
|
||||
except Exception as e:
|
||||
await update.message.reply_text(f"Ошибка синхронизации для {hotel.name}: {str(e)}")
|
||||
@@ -2,6 +2,7 @@ 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
|
||||
|
||||
async def manage_hotels(update: Update, context):
|
||||
"""Отображение списка отелей, связанных с пользователем."""
|
||||
@@ -36,6 +37,7 @@ async def hotel_actions(update: Update, context):
|
||||
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("Отель не найден.")
|
||||
@@ -67,22 +69,81 @@ async def delete_hotel(update: Update, context):
|
||||
await query.edit_message_text("Отель не найден.")
|
||||
|
||||
|
||||
async def check_pms(update: Update, context):
|
||||
"""Проверить интеграцию с PMS."""
|
||||
from pms_integration.manager import PMSIntegrationManager
|
||||
from asgiref.sync import sync_to_async
|
||||
from hotels.models import Hotel
|
||||
|
||||
# async def check_pms(update, context):
|
||||
# query = update.callback_query
|
||||
|
||||
# try:
|
||||
# # Логирование callback_data
|
||||
# hotel_id = query.data.split("_")[2]
|
||||
# print(f"Selected hotel id: {hotel_id}")
|
||||
# context.user_data["selected_hotel"] = hotel_id
|
||||
|
||||
# # Инициализация менеджера PMS
|
||||
# pms_manager = PMSIntegrationManager(hotel_id=hotel_id)
|
||||
# print(f"Loaded hotel: {pms_manager.hotel}")
|
||||
# await pms_manager.load_hotel() # Асинхронная загрузка отеля
|
||||
# pms_manager.load_plugin() # Загрузка плагина
|
||||
|
||||
# # Получение данных
|
||||
# data = pms_manager.fetch_data()
|
||||
# print(f'PMS_managerПолучено записей: {len(data)}\n\n\n___')
|
||||
# print(f'Данные {data}\n\n\n')
|
||||
# # Логирование
|
||||
# await pms_manager.save_log("success", f"Успешная интеграция с PMS {pms_manager.pms_config.name}.")
|
||||
# await query.edit_message_text(f"Интеграция успешна! Получено {len(data)} записей.")
|
||||
|
||||
# except Exception as e:
|
||||
# # Логирование ошибок
|
||||
# if 'pms_manager' in locals() and pms_manager.hotel:
|
||||
# await pms_manager.save_log("error", str(e))
|
||||
# await query.edit_message_text(f"❌ Ошибка: {e}")
|
||||
|
||||
async def check_pms(update, context):
|
||||
query = update.callback_query
|
||||
await query.answer()
|
||||
|
||||
hotel_id = int(query.data.split("_")[2])
|
||||
hotel = await sync_to_async(Hotel.objects.select_related('api', 'pms').get)(id=hotel_id)
|
||||
if not hotel:
|
||||
await query.edit_message_text("Отель не найден.")
|
||||
return
|
||||
try:
|
||||
# Получение hotel_id из callback_data
|
||||
hotel_id = query.data.split("_")[2]
|
||||
print(f"Selected hotel id: {hotel_id}")
|
||||
context.user_data["selected_hotel"] = hotel_id
|
||||
|
||||
api_name = hotel.api.name if hotel.api else "Не настроен"
|
||||
pms_name = hotel.pms.name if hotel.pms else "Не указана"
|
||||
# Инициализация менеджера PMS
|
||||
pms_manager = PMSIntegrationManager(hotel_id=hotel_id)
|
||||
print(f"Инициализация PMS менеджера для отеля ID: {hotel_id}")
|
||||
|
||||
status_message = f"Отель: {hotel.name}\nPMS система: {pms_name}\nAPI: {api_name}"
|
||||
await query.edit_message_text(status_message)
|
||||
# Загрузка данных отеля
|
||||
await pms_manager.load_hotel()
|
||||
print(f"Данные отеля загружены: {pms_manager.hotel}")
|
||||
|
||||
# Загрузка плагина
|
||||
pms_manager.load_plugin()
|
||||
print(f"Плагин загружен: {pms_manager.plugin}")
|
||||
|
||||
# Получение данных из PMS
|
||||
data = pms_manager.fetch_data()
|
||||
print(f"Данные получены из PMS: {len(data)} записей")
|
||||
# print(f"Полные данные: {data}\n\n\n")
|
||||
|
||||
# Сохранение лога успешной интеграции
|
||||
await pms_manager.save_log("success", f"Успешная интеграция с PMS {pms_manager.pms_config.name}.")
|
||||
|
||||
# Ответ пользователю
|
||||
await query.edit_message_text(f"Интеграция успешна! Получено {len(data)} записей.")
|
||||
|
||||
# Обработка данных и запись в БД
|
||||
await pms_manager.plugin._save_to_db(data, hotel_id=int(hotel_id))
|
||||
print(f"Данные успешно сохранены в базу данных.")
|
||||
|
||||
except Exception as e:
|
||||
# Логирование ошибки
|
||||
print(f"Ошибка при выполнении check_pms: {e}")
|
||||
if 'pms_manager' in locals() and pms_manager.hotel:
|
||||
await pms_manager.save_log("error", str(e))
|
||||
await query.edit_message_text(f"❌ Ошибка: {e}")
|
||||
|
||||
|
||||
async def setup_rooms(update: Update, context):
|
||||
|
||||
Reference in New Issue
Block a user