bnovo plugin
scheduller
This commit is contained in:
@@ -8,53 +8,34 @@ from django.shortcuts import render
|
||||
from django import forms
|
||||
from pms_integration.models import PMSConfiguration, PMSIntegrationLog
|
||||
|
||||
|
||||
class PMSConfigurationForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = PMSConfiguration
|
||||
fields = "__all__"
|
||||
fields = '__all__'
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
# Загружаем доступные плагины
|
||||
plugins = PluginLoader.load_plugins()
|
||||
self.fields['plugin_name'].choices = [(plugin, plugin) for plugin in plugins.keys()]
|
||||
plugin_choices = [(plugin_name, plugin_name) for plugin_name in plugins.keys()]
|
||||
self.fields['plugin_name'] = forms.ChoiceField(choices=plugin_choices, required=False)
|
||||
|
||||
@admin.register(PMSConfiguration)
|
||||
class PMSConfigurationAdmin(admin.ModelAdmin):
|
||||
form = PMSConfigurationForm
|
||||
list_display = ('name', 'plugin_name', 'created_at', 'check_plugins_button')
|
||||
search_fields = ('name', 'description')
|
||||
list_filter = ('created_at',)
|
||||
list_display = ('name', 'plugin_name', 'created_at')
|
||||
search_fields = ('name', 'plugin_name')
|
||||
ordering = ('-created_at',)
|
||||
|
||||
def get_urls(self):
|
||||
"""Добавляем URL для проверки плагинов."""
|
||||
urls = super().get_urls()
|
||||
custom_urls = [
|
||||
path("check-plugins/", self.check_plugins, name="check-plugins"),
|
||||
]
|
||||
return custom_urls + urls
|
||||
|
||||
def check_plugins(self, request):
|
||||
"""Проверка и отображение плагинов."""
|
||||
def save_model(self, request, obj, form, change):
|
||||
# Проверка на наличие плагина
|
||||
plugins = PluginLoader.load_plugins()
|
||||
plugin_details = [
|
||||
{"name": plugin_name, "doc": plugins[plugin_name].__doc__ or "Нет документации"}
|
||||
for plugin_name in plugins
|
||||
]
|
||||
context = {
|
||||
"title": "Проверка плагинов",
|
||||
"plugin_details": plugin_details,
|
||||
}
|
||||
return render(request, "admin/check_plugins.html", context)
|
||||
|
||||
def check_plugins_button(self, obj):
|
||||
"""Добавляем кнопку для проверки плагинов."""
|
||||
return format_html(
|
||||
'<a class="button" href="{}">Проверить плагины</a>',
|
||||
"/admin/pms_integration/pmsconfiguration/check-plugins/",
|
||||
)
|
||||
check_plugins_button.short_description = "Проверить плагины"
|
||||
|
||||
if obj.plugin_name and obj.plugin_name not in plugins.keys():
|
||||
raise ValueError(f"Выберите корректный плагин. '{obj.plugin_name}' нет среди допустимых значений.")
|
||||
super().save_model(request, obj, form, change)
|
||||
|
||||
|
||||
@admin.register(PMSIntegrationLog)
|
||||
class PMSIntegrationLogAdmin(admin.ModelAdmin):
|
||||
list_display = ('hotel', 'checked_at', 'status', 'message')
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
from django import forms
|
||||
from .models import PMSConfiguration
|
||||
from .manager import PluginLoader
|
||||
|
||||
class PMSConfigurationForm(forms.ModelForm):
|
||||
class Meta:
|
||||
model = PMSConfiguration
|
||||
fields = "__all__"
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
plugins = PluginLoader.load_plugins()
|
||||
self.fields['plugin_name'].choices = [(plugin, plugin) for plugin in plugins.keys()]
|
||||
@@ -7,27 +7,31 @@ from asgiref.sync import sync_to_async
|
||||
|
||||
class PluginLoader:
|
||||
PLUGIN_PATH = Path(__file__).parent / "plugins"
|
||||
print("Путь к папке плагинов:", PLUGIN_PATH.resolve())
|
||||
print("Содержимое папки:", list(PLUGIN_PATH.iterdir()))
|
||||
|
||||
@staticmethod
|
||||
def load_plugins():
|
||||
plugins = {}
|
||||
if not PluginLoader.PLUGIN_PATH.exists():
|
||||
print("Папка с плагинами не существует:", PluginLoader.PLUGIN_PATH)
|
||||
return plugins
|
||||
|
||||
print("Загрузка плагинов:")
|
||||
for file in os.listdir(PluginLoader.PLUGIN_PATH):
|
||||
if file.endswith("_pms.py") and not file.startswith("__"):
|
||||
print(f" Plugin {file}")
|
||||
module_name = f"pms_integration.plugins.{file[:-3]}"
|
||||
try:
|
||||
module = importlib.import_module(module_name)
|
||||
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
|
||||
print(f"Загружен плагин: {cls.__name__}")
|
||||
plugin_name = file[:-7] # Убираем `_pms` из имени файла
|
||||
print(f" Загружен плагин {plugin_name}: {cls.__name__}")
|
||||
plugins[plugin_name] = cls
|
||||
except Exception as e:
|
||||
print(f"Ошибка при загрузке модуля {module_name}: {e}")
|
||||
print(f"Итоговый список плагинов: {list(plugins.keys())}")
|
||||
print(f" Ошибка загрузки плагина {module_name}: {e}")
|
||||
return plugins
|
||||
|
||||
|
||||
class PMSIntegrationManager:
|
||||
def __init__(self, hotel_id):
|
||||
self.hotel_id = hotel_id
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.1.4 on 2024-12-10 02:52
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('pms_integration', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='pmsconfiguration',
|
||||
name='plugin_name',
|
||||
field=models.CharField(blank=True, choices=[], max_length=255, null=True),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.1.4 on 2024-12-10 02:58
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('pms_integration', '0002_alter_pmsconfiguration_plugin_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='pmsconfiguration',
|
||||
name='plugin_name',
|
||||
field=models.CharField(blank=True, choices=[], max_length=255, null=True, verbose_name='Плагин'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Generated by Django 5.1.4 on 2024-12-10 03:00
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('pms_integration', '0003_alter_pmsconfiguration_plugin_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='pmsconfiguration',
|
||||
name='plugin_name',
|
||||
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Плагин'),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,23 @@
|
||||
# Generated by Django 5.1.4 on 2024-12-10 03:03
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('pms_integration', '0004_alter_pmsconfiguration_plugin_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='pmsconfiguration',
|
||||
name='private_key',
|
||||
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Приватный ключ'),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='pmsconfiguration',
|
||||
name='public_key',
|
||||
field=models.CharField(blank=True, max_length=255, null=True, verbose_name='Публичный ключ'),
|
||||
),
|
||||
]
|
||||
@@ -8,10 +8,12 @@ class PMSConfiguration(models.Model):
|
||||
name = models.CharField(max_length=255, verbose_name="Название PMS")
|
||||
url = models.URLField(verbose_name="URL API")
|
||||
token = models.CharField(max_length=255, blank=True, null=True, verbose_name="Токен")
|
||||
public_key = models.CharField(max_length=255, blank=True, null=True, verbose_name="Публичный ключ")
|
||||
private_key = models.CharField(max_length=255, blank=True, null=True, verbose_name="Приватный ключ")
|
||||
username = models.CharField(max_length=255, blank=True, null=True, verbose_name="Логин")
|
||||
password = models.CharField(max_length=255, blank=True, null=True, verbose_name="Пароль")
|
||||
plugin_name = models.CharField(max_length=255, verbose_name="Название плагина")
|
||||
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Дата создания") # Добавлено поле
|
||||
plugin_name = models.CharField(max_length=255, blank=True, null=True, verbose_name="Плагин")
|
||||
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Дата создания")
|
||||
|
||||
|
||||
def __str__(self):
|
||||
|
||||
@@ -1,71 +1,136 @@
|
||||
import requests
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
from .base_plugin import BasePMSPlugin
|
||||
from asgiref.sync import sync_to_async
|
||||
from pms_integration.models import PMSConfiguration # Убедитесь, что модель существует
|
||||
|
||||
|
||||
class BnovoPMS(BasePMSPlugin):
|
||||
"""
|
||||
Плагин для интеграции с Bnovo.
|
||||
"""
|
||||
json_schema = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "integer"},
|
||||
"number": {"type": "integer"},
|
||||
"roomTypeName": {"type": "string"},
|
||||
"checkInStatus": {"type": "string"},
|
||||
"guests": {"type": "array"},
|
||||
},
|
||||
"required": ["id", "number", "roomTypeName", "checkInStatus", "guests"]
|
||||
}
|
||||
class BnovoPMSPlugin(BasePMSPlugin):
|
||||
"""Плагин для работы с PMS Bnovo."""
|
||||
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.api_url = config.url.rstrip("/") # Убираем лишний `/` в конце URL
|
||||
self.username = config.username
|
||||
self.password = config.password
|
||||
self.token = None # SID
|
||||
|
||||
if not self.api_url:
|
||||
raise ValueError("Не указан URL для работы плагина.")
|
||||
if not self.username or not self.password:
|
||||
raise ValueError("Не указаны логин или пароль для авторизации.")
|
||||
|
||||
def get_default_parser_settings(self):
|
||||
"""
|
||||
Возвращает настройки парсера по умолчанию.
|
||||
"""
|
||||
"""Возвращает настройки по умолчанию для обработки данных."""
|
||||
return {
|
||||
"field_mapping": {
|
||||
"room_name": "roomNumber",
|
||||
"check_in": "from",
|
||||
"check_out": "until",
|
||||
},
|
||||
"date_format": "%Y-%m-%dT%H:%M:%S"
|
||||
"date_format": "%Y-%m-%dT%H:%M:%S",
|
||||
"timezone": "UTC"
|
||||
}
|
||||
def fetch_data(self):
|
||||
response = requests.get(self.pms_config.url, headers={"Authorization": f"Bearer {self.pms_config.token}"})
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
|
||||
# Проверка структуры
|
||||
expected_fields = self.pms_config.parser_settings.get("fields_mapping", {})
|
||||
for field in expected_fields.values():
|
||||
if field not in data[0]: # Проверяем первую запись
|
||||
raise ValueError(f"Поле {field} отсутствует в ответе API.")
|
||||
async def _save_token_to_db(self, sid):
|
||||
"""Сохраняет токен (SID) в базу данных."""
|
||||
try:
|
||||
await sync_to_async(PMSConfiguration.objects.update_or_create)(
|
||||
plugin_name="bnovo",
|
||||
defaults={"token": sid}
|
||||
)
|
||||
print(f"[DEBUG] Токен сохранен в БД: {sid}")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Ошибка сохранения токена в БД: {e}")
|
||||
|
||||
return data
|
||||
|
||||
def fetch_and_parse(self):
|
||||
response = requests.get(
|
||||
self.pms_config.url,
|
||||
headers={"Authorization": f"Bearer {self.pms_config.token}"}
|
||||
)
|
||||
self.validate_response(response) # Проверка соответствия структуры
|
||||
if response.status_code != 200:
|
||||
raise ValueError(f"Ошибка запроса к PMS Bnovo: {response.text}")
|
||||
def _get_auth_headers(self):
|
||||
"""Создает заголовки авторизации."""
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
if self.token:
|
||||
headers["Cookie"] = f"SID={self.token}"
|
||||
return headers
|
||||
|
||||
data = response.json()
|
||||
parsed_data = self.parse_data(data)
|
||||
return parsed_data
|
||||
async def _fetch_session(self):
|
||||
"""Получает идентификатор сессии (SID) через запрос."""
|
||||
url = f"{self.api_url}/"
|
||||
payload = {
|
||||
"username": self.username,
|
||||
"password": self.password,
|
||||
}
|
||||
|
||||
def parse_data(self, data):
|
||||
# Пример разбора данных на основе JSON-маски
|
||||
reservations = []
|
||||
for item in data["reservations"]:
|
||||
reservation = {
|
||||
"id": item["id"],
|
||||
"room_number": item["roomNumber"],
|
||||
"check_in": item["checkIn"],
|
||||
"check_out": item["checkOut"],
|
||||
"status": item["status"],
|
||||
}
|
||||
reservations.append(reservation)
|
||||
return reservations
|
||||
|
||||
print(f"[DEBUG] URL авторизации: {url}")
|
||||
print(f"[DEBUG] Тело запроса: {json.dumps(payload, indent=2)}")
|
||||
headers = self._get_auth_headers()
|
||||
|
||||
session = requests.Session()
|
||||
response = session.post(url, json=payload, headers=headers, allow_redirects=False)
|
||||
|
||||
print(f"[DEBUG] Статус ответа: {response.status_code}")
|
||||
print(f"[DEBUG] Ответ заголовков: {response.headers}")
|
||||
print(f"[DEBUG] Cookies: {session.cookies}")
|
||||
|
||||
if response.status_code == 302 and "SID" in session.cookies:
|
||||
sid = session.cookies.get("SID")
|
||||
self.token = sid
|
||||
print(f"[DEBUG] Получен SID: {sid}")
|
||||
|
||||
# Правильное сохранение в БД через sync_to_async
|
||||
try:
|
||||
await self._save_token_to_db(sid)
|
||||
print(f"[DEBUG] Токен сохранен в БД")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] Ошибка сохранения токена в БД: {e}")
|
||||
else:
|
||||
raise ValueError(f"Не удалось получить SID из ответа: {response.text}")
|
||||
|
||||
async def _fetch_data(self):
|
||||
"""Получает данные о бронированиях с помощью эндпоинта `/dashboard`."""
|
||||
await self._fetch_session() # Авторизуемся перед каждым запросом
|
||||
|
||||
now = datetime.now()
|
||||
create_from = (now - timedelta(days=90)).strftime("%d.%m.%Y") # Диапазон: последние 90 дней
|
||||
create_to = now.strftime("%d.%m.%Y")
|
||||
|
||||
params = {
|
||||
"create_from": create_from,
|
||||
"create_to": create_to,
|
||||
"status_ids": "1",
|
||||
"advanced_search": 2, # Обязательный параметр
|
||||
"c": 100, # Количество элементов на странице (максимум 100)
|
||||
"page": 1, # Начальная страница
|
||||
"order_by": "create_date.asc", # Сортировка по возрастанию даты создания
|
||||
}
|
||||
|
||||
headers = self._get_auth_headers()
|
||||
|
||||
all_bookings = [] # Для сохранения всех бронирований
|
||||
while True:
|
||||
print(f"[DEBUG] Запрос к /dashboard с параметрами: {json.dumps(params, indent=2)}")
|
||||
response = requests.get(f"{self.api_url}/dashboard", headers=headers, params=params)
|
||||
|
||||
print(f"[DEBUG] Статус ответа: {response.status_code}")
|
||||
if response.status_code != 200:
|
||||
raise ValueError(f"Ошибка при получении данных: {response.status_code}, {response.text}")
|
||||
|
||||
data = response.json()
|
||||
print(json.dumps(data, indent=2))
|
||||
bookings = data.get("bookings", [])
|
||||
all_bookings.extend(bookings)
|
||||
|
||||
print(f"[DEBUG] Получено бронирований: {len(bookings)}")
|
||||
print(f"[DEBUG] Всего бронирований: {len(all_bookings)}")
|
||||
|
||||
# Проверка на наличие следующей страницы
|
||||
pages_info = data.get("pages", {})
|
||||
current_page = pages_info.get("current_page", 1)
|
||||
total_pages = pages_info.get("total_pages", 1)
|
||||
|
||||
if current_page >= total_pages:
|
||||
break # Все страницы загружены
|
||||
|
||||
params["page"] += 1 # Переход на следующую страницу
|
||||
|
||||
if not all_bookings:
|
||||
print("[DEBUG] Нет бронирований за указанный период.")
|
||||
else:
|
||||
print(f"[DEBUG] Полученные бронирования: {json.dumps(all_bookings, indent=2)}")
|
||||
return all_bookings
|
||||
@@ -1,78 +1,254 @@
|
||||
import hashlib
|
||||
import requests
|
||||
import json
|
||||
from datetime import datetime
|
||||
from hotels.models import Reservation
|
||||
# import requests
|
||||
# import hashlib
|
||||
# import json
|
||||
# from .base_plugin import BasePMSPlugin
|
||||
# from datetime import datetime, timedelta
|
||||
# from asgiref.sync import sync_to_async
|
||||
|
||||
from pms_integration.plugins.base_plugin import BasePMSPlugin
|
||||
|
||||
# class RealtyCalendarPlugin(BasePMSPlugin):
|
||||
# """Плагин для импорта данных из системы RealtyCalendar
|
||||
# """
|
||||
# def __init__(self, config):
|
||||
# super().__init__(config)
|
||||
# self.public_key = config.public_key
|
||||
# self.private_key = config.private_key
|
||||
# self.api_url = config.url.rstrip("/") # Убираем лишний `/` в конце URL
|
||||
|
||||
# if not self.public_key or not self.private_key:
|
||||
# raise ValueError("Публичный или приватный ключ отсутствует для RealtyCalendar")
|
||||
# def get_default_parser_settings(self):
|
||||
# """
|
||||
# Возвращает настройки по умолчанию для обработки данных.
|
||||
# """
|
||||
# return {
|
||||
# "date_format": "%Y-%m-%dT%H:%M:%S",
|
||||
# "timezone": "UTC"
|
||||
# }
|
||||
# def _get_sorted_keys(self, obj):
|
||||
# """
|
||||
# Возвращает отсортированный по имени список ключей.
|
||||
# """
|
||||
# return sorted(list(obj.keys()))
|
||||
|
||||
# def _generate_data_string(self, obj):
|
||||
# """
|
||||
# Формирует строку параметров для подписи.
|
||||
# """
|
||||
# sorted_keys = self._get_sorted_keys(obj)
|
||||
# string = "".join(f"{key}={obj[key]}" for key in sorted_keys)
|
||||
# return string + self.private_key
|
||||
|
||||
# def _generate_md5(self, string):
|
||||
# """
|
||||
# Генерирует MD5-хеш от строки.
|
||||
# """
|
||||
# return hashlib.md5(string.encode("utf-8")).hexdigest()
|
||||
|
||||
# def _generate_sign(self, data):
|
||||
# """
|
||||
# Генерирует подпись для данных запроса.
|
||||
# """
|
||||
# data_string = self._generate_data_string(data)
|
||||
# return self._generate_md5(data_string)
|
||||
|
||||
# def fetch_data(self):
|
||||
# """
|
||||
# Выполняет запрос к API RealtyCalendar для получения данных о бронированиях.
|
||||
# """
|
||||
# base_url = f"https://realtycalendar.ru/api/v1/bookings/{self.public_key}/"
|
||||
# headers = {
|
||||
# "Accept": "application/json",
|
||||
# "Content-Type": "application/json",
|
||||
# }
|
||||
|
||||
# # Определяем даты выборки
|
||||
# now = datetime.now()
|
||||
# data = {
|
||||
# "begin_date": (now - timedelta(days=7)).strftime("%Y-%m-%d"),
|
||||
# "end_date": now.strftime("%Y-%m-%d"),
|
||||
# }
|
||||
|
||||
# # Генерация подписи
|
||||
# data["sign"] = self._generate_sign(data)
|
||||
|
||||
# # Отправляем запрос
|
||||
# print(f"URL запроса: {base_url}")
|
||||
# print(f"Заголовки: {headers}")
|
||||
# print(f"Данные запроса: {data}")
|
||||
|
||||
# response = requests.post(url=base_url, headers=headers, json=data)
|
||||
|
||||
# # Логируем результат
|
||||
# print(f"Статус ответа: {response.status_code}")
|
||||
# print(f"Ответ: {response.text}")
|
||||
|
||||
# # Проверяем успешность запроса
|
||||
# if response.status_code == 200:
|
||||
# return response.json().get("bookings", [])
|
||||
# else:
|
||||
# raise ValueError(f"Ошибка API RealtyCalendar: {response.status_code}, {response.text}")
|
||||
|
||||
# async def _save_to_db(self, data, hotel_id):
|
||||
# """
|
||||
# Сохраняет данные о бронированиях в базу данных.
|
||||
# """
|
||||
# from hotels.models import Reservation, Hotel
|
||||
|
||||
# hotel = await sync_to_async(Hotel.objects.get)(id=hotel_id)
|
||||
# for item in data:
|
||||
# try:
|
||||
# reservation, created = await sync_to_async(Reservation.objects.update_or_create)(
|
||||
# reservation_id=item["id"],
|
||||
# hotel=hotel,
|
||||
# defaults={
|
||||
# "room_number": item.get("apartment_id", ""), # ID квартиры
|
||||
# "check_in": datetime.strptime(item["begin_date"], "%Y-%m-%d"), # Дата заезда
|
||||
# "check_out": datetime.strptime(item["end_date"], "%Y-%m-%d"), # Дата выезда
|
||||
# "status": item.get("status", ""), # Статус бронирования
|
||||
# "price": item.get("amount", 0), # Сумма оплаты
|
||||
# "client_name": item["client"].get("fio", ""), # Имя клиента
|
||||
# "client_email": item["client"].get("email", ""), # Email клиента
|
||||
# "client_phone": item["client"].get("phone", ""), # Телефон клиента
|
||||
# }
|
||||
# )
|
||||
# print(f"{'Создана' if created else 'Обновлена'} запись: {reservation}")
|
||||
# except Exception as e:
|
||||
# print(f"Ошибка при сохранении бронирования ID {item['id']}: {e}")
|
||||
|
||||
|
||||
import requests
|
||||
import hashlib
|
||||
import json
|
||||
from .base_plugin import BasePMSPlugin
|
||||
from datetime import datetime, timedelta
|
||||
from asgiref.sync import sync_to_async
|
||||
|
||||
|
||||
class RealtyCalendarPlugin(BasePMSPlugin):
|
||||
"""
|
||||
Плагин для взаимодействия с RealtyCalendar.
|
||||
"""Плагин для импорта данных из системы RealtyCalendar
|
||||
"""
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.public_key = config.token # Используем `token` как публичный ключ
|
||||
self.private_key = config.password # Используем `password` как приватный ключ
|
||||
self.base_url = config.url
|
||||
self.public_key = config.public_key
|
||||
self.private_key = config.private_key
|
||||
self.api_url = config.url.rstrip("/")
|
||||
|
||||
def generate_sign(self, params):
|
||||
"""
|
||||
Генерация подписи запроса.
|
||||
:param params: Параметры запроса.
|
||||
:return: Подпись.
|
||||
"""
|
||||
sorted_keys = sorted(params.keys())
|
||||
data_string = ''.join(f"{key}={params[key]}" for key in sorted_keys)
|
||||
sign_string = f"{data_string}{self.private_key}"
|
||||
return hashlib.md5(sign_string.encode('utf-8')).hexdigest()
|
||||
if not self.public_key or not self.private_key:
|
||||
raise ValueError("Публичный или приватный ключ отсутствует для RealtyCalendar")
|
||||
|
||||
def fetch_data(self, start_date=None, end_date=None):
|
||||
def get_default_parser_settings(self):
|
||||
"""
|
||||
Получение данных из RealtyCalendar.
|
||||
:param start_date: Начальная дата (формат YYYY-MM-DD).
|
||||
:param end_date: Конечная дата (формат YYYY-MM-DD).
|
||||
:return: Список данных бронирования.
|
||||
Возвращает настройки по умолчанию для обработки данных.
|
||||
"""
|
||||
if not start_date:
|
||||
start_date = datetime.now().strftime('%Y-%m-%d')
|
||||
if not end_date:
|
||||
end_date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
|
||||
|
||||
params = {
|
||||
'begin_date': start_date,
|
||||
'end_date': end_date,
|
||||
return {
|
||||
"date_format": "%Y-%m-%dT%H:%M:%S",
|
||||
"timezone": "UTC"
|
||||
}
|
||||
params['sign'] = self.generate_sign(params)
|
||||
|
||||
url = f"{self.base_url}/bookings/{self.public_key}/"
|
||||
def _get_sorted_keys(self, obj):
|
||||
"""
|
||||
Возвращает отсортированный по имени список ключей.
|
||||
"""
|
||||
sorted_keys = sorted(list(obj.keys()))
|
||||
print(f"[DEBUG] Отсортированные ключи: {sorted_keys}")
|
||||
return sorted_keys
|
||||
|
||||
def _generate_data_string(self, obj):
|
||||
"""
|
||||
Формирует строку параметров для подписи.
|
||||
"""
|
||||
sorted_keys = self._get_sorted_keys(obj)
|
||||
string = "".join(f"{key}={obj[key]}" for key in sorted_keys)
|
||||
print(f"[DEBUG] Сформированная строка данных: {string}")
|
||||
return string + self.private_key
|
||||
|
||||
def _generate_md5(self, string):
|
||||
"""
|
||||
Генерирует MD5-хеш от строки.
|
||||
"""
|
||||
md5_hash = hashlib.md5(string.encode("utf-8")).hexdigest()
|
||||
print(f"[DEBUG] Сформированный MD5-хеш: {md5_hash}")
|
||||
return md5_hash
|
||||
|
||||
def _generate_sign(self, data):
|
||||
"""
|
||||
Генерирует подпись для данных запроса.
|
||||
"""
|
||||
data_string = self._generate_data_string(data)
|
||||
print(f"[DEBUG] Строка для подписи: {data_string}")
|
||||
sign = self._generate_md5(data_string)
|
||||
print(f"[DEBUG] Подпись: {sign}")
|
||||
return sign
|
||||
|
||||
def _fetch_data(self):
|
||||
"""
|
||||
Выполняет запрос к API RealtyCalendar для получения данных о бронированиях.
|
||||
"""
|
||||
base_url = f"https://realtycalendar.ru/api/v1/bookings/{self.public_key}/"
|
||||
headers = {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
"Accept": "application/json",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
response = requests.post(url, json=params, headers=headers)
|
||||
response.raise_for_status()
|
||||
# Определяем даты выборки
|
||||
now = datetime.now()
|
||||
data = {
|
||||
"begin_date": (now - timedelta(days=7)).strftime("%Y-%m-%d"),
|
||||
"end_date": now.strftime("%Y-%m-%d"),
|
||||
}
|
||||
|
||||
data = response.json()
|
||||
return data.get('bookings', [])
|
||||
print(f"[DEBUG] Даты выборки: {data}")
|
||||
|
||||
@staticmethod
|
||||
def save_data(bookings):
|
||||
# Генерация подписи
|
||||
data["sign"] = self._generate_sign(data)
|
||||
|
||||
# Отправляем запрос
|
||||
print(f"[DEBUG] URL запроса: {base_url}")
|
||||
print(f"[DEBUG] Заголовки: {headers}")
|
||||
print(f"[DEBUG] Данные запроса: {data}")
|
||||
|
||||
response = requests.post(url=base_url, headers=headers, json=data)
|
||||
|
||||
# Логируем результат
|
||||
print(f"[DEBUG] Статус ответа: {response.status_code}")
|
||||
print(f"[DEBUG] Ответ: {response.text}")
|
||||
|
||||
# Проверяем успешность запроса
|
||||
if response.status_code == 200:
|
||||
bookings = response.json().get("bookings", [])
|
||||
print(f"[DEBUG] Полученные данные бронирований: {bookings}")
|
||||
return bookings
|
||||
else:
|
||||
raise ValueError(f"Ошибка API RealtyCalendar: {response.status_code}, {response.text}")
|
||||
|
||||
|
||||
async def _save_to_db(self, data, hotel_id):
|
||||
"""
|
||||
Сохранение данных бронирования в базу данных.
|
||||
:param bookings: Список бронирований.
|
||||
Сохраняет данные о бронированиях в базу данных.
|
||||
"""
|
||||
for booking in bookings:
|
||||
Reservation.objects.update_or_create(
|
||||
external_id=booking['id'],
|
||||
defaults={
|
||||
'check_in': booking['begin_date'],
|
||||
'check_out': booking['end_date'],
|
||||
'amount': booking['amount'],
|
||||
'notes': booking.get('notes', ''),
|
||||
'guest_name': booking['client']['fio'],
|
||||
'guest_phone': booking['client']['phone'],
|
||||
},
|
||||
)
|
||||
from hotels.models import Reservation, Hotel
|
||||
|
||||
hotel = await sync_to_async(Hotel.objects.get)(id=hotel_id)
|
||||
print(f"[DEBUG] Загружен отель: {hotel.name}")
|
||||
|
||||
for item in data:
|
||||
print(f"[DEBUG] Обработка бронирования: {item}")
|
||||
try:
|
||||
reservation, created = await sync_to_async(Reservation.objects.update_or_create)(
|
||||
reservation_id=item["id"],
|
||||
hotel=hotel,
|
||||
defaults={
|
||||
"room_number": item.get("apartment_id", ""), # ID квартиры
|
||||
"check_in": datetime.strptime(item["begin_date"], "%Y-%m-%d"), # Дата заезда
|
||||
"check_out": datetime.strptime(item["end_date"], "%Y-%m-%d"), # Дата выезда
|
||||
"status": item.get("status", ""), # Статус бронирования
|
||||
"price": item.get("amount", 0), # Сумма оплаты
|
||||
"client_name": item["client"].get("fio", ""), # Имя клиента
|
||||
"client_email": item["client"].get("email", ""), # Email клиента
|
||||
"client_phone": item["client"].get("phone", ""), # Телефон клиента
|
||||
}
|
||||
)
|
||||
print(f"[DEBUG] {'Создана' if created else 'Обновлена'} запись: {reservation}")
|
||||
except Exception as e:
|
||||
print(f"[DEBUG] Ошибка при сохранении бронирования ID {item['id']}: {e}")
|
||||
|
||||
@@ -8,6 +8,9 @@ from hotels.models import Hotel
|
||||
|
||||
|
||||
class Shelter(BasePMSPlugin):
|
||||
"""
|
||||
Плагин для PMS Shelter Coud.
|
||||
"""
|
||||
def __init__(self, config):
|
||||
super().__init__(config)
|
||||
self.token = config.token
|
||||
|
||||
73
pms_integration/test_requests.py
Normal file
73
pms_integration/test_requests.py
Normal file
@@ -0,0 +1,73 @@
|
||||
# import requests
|
||||
# import json
|
||||
|
||||
# # Функция авторизации
|
||||
# def authorize(username, password):
|
||||
# url = "https://online.bnovo.ru/"
|
||||
# headers = {
|
||||
# "accept": "application/json",
|
||||
# "Content-Type": "application/json"
|
||||
# }
|
||||
# payload = {
|
||||
# "username": username,
|
||||
# "password": password
|
||||
# }
|
||||
|
||||
# response = requests.post(url, headers=headers, json=payload, allow_redirects=False)
|
||||
# print(f"[DEBUG] Статус авторизации: {response.status_code}")
|
||||
# print(f"[DEBUG] Заголовки ответа: {response.headers}")
|
||||
|
||||
# if response.status_code == 302 and "SID" in response.cookies:
|
||||
# sid = response.cookies.get("SID")
|
||||
# print(f"[DEBUG] Получен SID: {sid}")
|
||||
# return sid
|
||||
# else:
|
||||
# raise ValueError(f"Ошибка авторизации: {response.text}")
|
||||
|
||||
# # Функция получения данных с /dashboard
|
||||
# def fetch_dashboard(sid, create_from, create_to, status_ids, page=1, count=10):
|
||||
# url = f"https://online.bnovo.ru/dashboard"
|
||||
# headers = {
|
||||
# "accept": "application/json",
|
||||
# "Cookie": f"SID={sid}"
|
||||
# }
|
||||
# params = {
|
||||
# "create_from": create_from,
|
||||
# "create_to": create_to,
|
||||
# "advanced_search": 2,
|
||||
# "status_ids": status_ids,
|
||||
# "c": count,
|
||||
# "page": page,
|
||||
# "order_by": "create_date.asc"
|
||||
# }
|
||||
|
||||
# response = requests.get(url, headers=headers, params=params)
|
||||
# print(f"[DEBUG] Статус запроса: {response.status_code}")
|
||||
# print(f"[DEBUG] Ответ: {json.dumps(response.json(), indent=2, ensure_ascii=False)}")
|
||||
|
||||
# if response.status_code == 200:
|
||||
# return response.json()
|
||||
# else:
|
||||
# raise ValueError(f"Ошибка при запросе данных: {response.text}")
|
||||
|
||||
# # Тестовый вызов
|
||||
# try:
|
||||
# username = "cto@hotelantifraud.ru"
|
||||
# password = "tD8wC1zP9tiT6mY1"
|
||||
|
||||
# # Авторизация
|
||||
# sid = authorize(username, password)
|
||||
|
||||
# # Получение бронирований
|
||||
# bookings = fetch_dashboard(
|
||||
# sid=sid,
|
||||
# create_from="25.09.2024",
|
||||
# create_to="05.10.2024",
|
||||
# status_ids="1",
|
||||
# page=1,
|
||||
# count=10
|
||||
# )
|
||||
# print(f"[INFO] Полученные бронирования: {json.dumps(bookings, indent=2, ensure_ascii=False)}")
|
||||
|
||||
# except Exception as e:
|
||||
# print(f"[ERROR] {e}")
|
||||
Reference in New Issue
Block a user