pms_integration in process

This commit is contained in:
2024-12-09 10:10:53 +09:00
parent 1398f444bd
commit 60eaef5527
15 changed files with 243 additions and 146 deletions

View File

@@ -1,53 +1,68 @@
# pms_integration/manager.py
import importlib
from hotels.models import Hotel, PMSIntegrationLog, Reservation
from asgiref.sync import sync_to_async
from django.core.exceptions import ObjectDoesNotExist
from hotels.models import Hotel
from .models import PMSIntegrationLog
import os
from pathlib import Path
from plugins.base_plugin import BasePMSPlugin
class PluginLoader:
"""
Класс для автоматической загрузки плагинов PMS.
"""
PLUGIN_PATH = Path(__file__).parent / "plugins"
@staticmethod
def load_plugins():
plugins = {}
for file in os.listdir(PluginLoader.PLUGIN_PATH):
if file.endswith("_pms.py") and not file.startswith("__"):
module_name = f"pms_integration.plugins.{file[:-3]}"
try:
module = importlib.import_module(module_name)
# Ищем класс, наследующийся от BasePMSPlugin
for attr in dir(module):
cls = getattr(module, attr)
if isinstance(cls, type) and issubclass(cls, BasePMSPlugin) and cls is not BasePMSPlugin:
plugins[cls.__name__] = cls
except Exception as e:
print(f"Ошибка загрузки плагина {module_name}: {e}")
return plugins
class PMSIntegrationManager:
"""Универсальный менеджер интеграции с PMS."""
def __init__(self, hotel_id):
self.hotel_id = hotel_id
self.hotel = None
self.pms_config = None
self.plugin = None
async def load_hotel_data(self):
"""Загружает данные отеля и инициализирует соответствующий плагин."""
self.hotel = await sync_to_async(Hotel.objects.get)(id=self.hotel_id)
pms_system = self.hotel.pms
def load_hotel(self):
from hotels.models import Hotel # Импорт здесь, чтобы избежать кругового импорта
self.hotel = Hotel.objects.get(id=self.hotel_id)
self.pms_config = self.hotel.pms
if not self.pms_config:
raise ValueError(f"Отель {self.hotel.name} не связан с PMS системой.")
if not pms_system:
raise ValueError("PMS система не настроена для отеля.")
def load_plugin(self):
plugins = PluginLoader.load_plugins()
if self.pms_config.name not in plugins:
raise ValueError(f"Плагин для PMS {self.pms_config.name} не найден.")
self.plugin = plugins[self.pms_config.name](self.pms_config)
plugin_module = f"pms_integration.plugins.{pms_system.name.lower()}_pms"
try:
plugin_class = getattr(importlib.import_module(plugin_module), f"{pms_system.name.capitalize()}PMSPlugin")
self.plugin = plugin_class(self.hotel.api)
except (ImportError, AttributeError) as e:
raise ValueError(f"Плагин для PMS '{pms_system.name}' не найден: {e}")
def fetch_data(self):
if not self.plugin:
raise ValueError("Плагин не загружен.")
return self.plugin.fetch_data()
async def fetch_and_save_data(self):
"""Получение данных от PMS и их сохранение."""
raw_data = self.plugin.fetch_data()
parsed_data = self.plugin.parse_data(raw_data)
# Сохраняем данные в БД
for res in parsed_data:
await sync_to_async(Reservation.objects.update_or_create)(
reservation_id=res["id"],
defaults={
"hotel": self.hotel,
"room_number": res["room_number"],
"room_type": res["room_type"],
"check_in": res["check_in"],
"check_out": res["check_out"],
"status": res["status"],
"price": res.get("price"),
},
)
# Логируем успех
await sync_to_async(PMSIntegrationLog.objects.create)(
hotel=self.hotel, status="success", message="Данные успешно обновлены."
)
def save_log(self, status, message):
from .models import PMSIntegrationLog # Избегаем кругового импорта
PMSIntegrationLog.objects.create(
hotel=self.hotel,
status=status,
message=message,
)