shelter plugin completed
This commit is contained in:
@@ -121,6 +121,52 @@ async def delete_hotel(update: Update, context):
|
|||||||
# await pms_manager.save_log("error", str(e))
|
# await pms_manager.save_log("error", str(e))
|
||||||
# await query.edit_message_text(f"❌ Ошибка: {e}")
|
# await query.edit_message_text(f"❌ Ошибка: {e}")
|
||||||
|
|
||||||
|
# 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
|
||||||
|
# data = await pms_manager.plugin.fetch_data()
|
||||||
|
# elif pms_config.api_url and pms_config.token:
|
||||||
|
# # Используем прямой запрос к API
|
||||||
|
# from pms_integration.api_client import APIClient
|
||||||
|
# api_client = APIClient(base_url=pms_config.api_url, access_token=pms_config.token)
|
||||||
|
# data = api_client.fetch_reservations()
|
||||||
|
# else:
|
||||||
|
# # Если подходящий способ не найден
|
||||||
|
# await query.edit_message_text("Подходящий способ интеграции с PMS не найден.")
|
||||||
|
# return
|
||||||
|
|
||||||
|
# # Сохраняем данные в базу
|
||||||
|
# from bot.utils.database import save_reservations
|
||||||
|
# await sync_to_async(save_reservations)(data)
|
||||||
|
|
||||||
|
# # Уведомляем об успешной интеграции
|
||||||
|
# await query.edit_message_text(f"Интеграция PMS {pms_config.name} завершена успешно.")
|
||||||
|
# except Exception as e:
|
||||||
|
# # Обрабатываем и логируем ошибки
|
||||||
|
# await query.edit_message_text(f"❌ Ошибка: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def check_pms(update, context):
|
async def check_pms(update, context):
|
||||||
query = update.callback_query
|
query = update.callback_query
|
||||||
|
|
||||||
@@ -144,28 +190,28 @@ async def check_pms(update, context):
|
|||||||
# Проверяем, какой способ интеграции использовать
|
# Проверяем, какой способ интеграции использовать
|
||||||
if hasattr(pms_manager.plugin, 'fetch_data') and callable(pms_manager.plugin.fetch_data):
|
if hasattr(pms_manager.plugin, 'fetch_data') and callable(pms_manager.plugin.fetch_data):
|
||||||
# Плагин поддерживает метод fetch_data
|
# Плагин поддерживает метод fetch_data
|
||||||
data = await pms_manager.plugin.fetch_data()
|
report = await pms_manager.plugin._fetch_data()
|
||||||
elif pms_config.api_url and pms_config.token:
|
|
||||||
# Используем прямой запрос к API
|
|
||||||
from pms_integration.api_client import APIClient
|
|
||||||
api_client = APIClient(base_url=pms_config.api_url, access_token=pms_config.token)
|
|
||||||
data = api_client.fetch_reservations()
|
|
||||||
else:
|
else:
|
||||||
# Если подходящий способ не найден
|
|
||||||
await query.edit_message_text("Подходящий способ интеграции с PMS не найден.")
|
await query.edit_message_text("Подходящий способ интеграции с PMS не найден.")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Сохраняем данные в базу
|
# Формируем сообщение о результатах
|
||||||
from bot.utils.database import save_reservations
|
result_message = (
|
||||||
await sync_to_async(save_reservations)(data)
|
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)
|
||||||
await query.edit_message_text(f"Интеграция PMS {pms_config.name} завершена успешно.")
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Обрабатываем и логируем ошибки
|
# Обрабатываем и логируем ошибки
|
||||||
await query.edit_message_text(f"❌ Ошибка: {str(e)}")
|
await query.edit_message_text(f"❌ Ошибка: {str(e)}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
async def setup_rooms(update: Update, context):
|
async def setup_rooms(update: Update, context):
|
||||||
"""Настроить номера отеля."""
|
"""Настроить номера отеля."""
|
||||||
query = update.callback_query
|
query = update.callback_query
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
from .base_plugin import BasePMSPlugin
|
from .base_plugin import BasePMSPlugin
|
||||||
|
import requests
|
||||||
|
|
||||||
class EcviPMS(BasePMSPlugin):
|
class EcviPMS(BasePMSPlugin):
|
||||||
"""
|
"""
|
||||||
Плагин для PMS Shelter.
|
Плагин для PMS ECVI.
|
||||||
"""
|
"""
|
||||||
def fetch_data(self):
|
def _fetch_data(self):
|
||||||
print("Fetching data from Ecvi PMS...")
|
print("Fetching data from Ecvi PMS...")
|
||||||
# Реализация метода получения данных из PMS Shelter
|
# Реализация метода получения данных из PMS Shelter
|
||||||
response = requests.get(self.pms_config.url, headers={"Authorization": f"Bearer {self.pms_config.token}"})
|
response = requests.get(self.pms_config.url, headers={"Authorization": f"Bearer {self.pms_config.token}"})
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ class Shelter(BasePMSPlugin):
|
|||||||
self.api_url = pms_config.url
|
self.api_url = pms_config.url
|
||||||
self.token = pms_config.token
|
self.token = pms_config.token
|
||||||
self.pagination_count = 50
|
self.pagination_count = 50
|
||||||
|
|
||||||
def get_default_parser_settings(self):
|
def get_default_parser_settings(self):
|
||||||
"""
|
"""
|
||||||
Возвращает настройки по умолчанию для разбора данных PMS Shelter.
|
Возвращает настройки по умолчанию для разбора данных PMS Shelter.
|
||||||
@@ -35,10 +34,9 @@ class Shelter(BasePMSPlugin):
|
|||||||
"room_type_name": "roomTypeName",
|
"room_type_name": "roomTypeName",
|
||||||
"check_in_status": "checkInStatus",
|
"check_in_status": "checkInStatus",
|
||||||
"is_annul": "isAnnul",
|
"is_annul": "isAnnul",
|
||||||
"tariff_id": "tariffId",
|
|
||||||
"reservation_price": "reservationPrice",
|
"reservation_price": "reservationPrice",
|
||||||
"discount": "discount",
|
"discount": "discount",
|
||||||
"guests": "guests",
|
|
||||||
},
|
},
|
||||||
"date_format": "%Y-%m-%dT%H:%M:%S",
|
"date_format": "%Y-%m-%dT%H:%M:%S",
|
||||||
"timezone": "UTC",
|
"timezone": "UTC",
|
||||||
@@ -56,17 +54,15 @@ class Shelter(BasePMSPlugin):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ERROR] Ошибка получения последнего сохраненного бронирования: {e}")
|
print(f"[ERROR] Ошибка получения последнего сохраненного бронирования: {e}")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
async def _fetch_data(self):
|
async def _fetch_data(self):
|
||||||
"""
|
"""
|
||||||
Получает данные о бронированиях из PMS Shelter.
|
Получает данные о бронированиях из PMS.
|
||||||
|
Данные обрабатываются по временным промежуткам и сразу записываются в БД.
|
||||||
|
Возвращает отчёт о проделанной работе.
|
||||||
"""
|
"""
|
||||||
try:
|
now = datetime.utcnow().replace(tzinfo=timezone.utc)
|
||||||
now = datetime.utcnow()
|
start_date = await self._get_last_saved_date() or (now - timedelta(days=90))
|
||||||
start_date = await self._get_last_saved_date() or (now - timedelta(days=60))
|
end_date = now + timedelta(days=30)
|
||||||
end_date = now + timedelta(days=60)
|
|
||||||
total_count = None
|
|
||||||
from_index = 0
|
|
||||||
|
|
||||||
headers = {
|
headers = {
|
||||||
'accept': 'text/plain',
|
'accept': 'text/plain',
|
||||||
@@ -74,91 +70,111 @@ class Shelter(BasePMSPlugin):
|
|||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
}
|
}
|
||||||
|
|
||||||
print(f"[DEBUG] Start date: {start_date}, End date: {end_date}")
|
print(f"[DEBUG] Fetching data from {start_date} to {end_date}")
|
||||||
|
|
||||||
while total_count is None or from_index < total_count:
|
# Результаты выполнения
|
||||||
payload = {
|
report = {
|
||||||
"from": start_date.strftime('%Y-%m-%dT%H:%M:%SZ'),
|
"processed_intervals": 0,
|
||||||
"until": end_date.strftime('%Y-%m-%dT%H:%M:%SZ'),
|
"processed_items": 0,
|
||||||
"pagination": {
|
"errors": [],
|
||||||
"from": from_index,
|
|
||||||
"count": self.pagination_count,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
print(f"[DEBUG] Payload: {json.dumps(payload)}")
|
|
||||||
|
# Разделение на временные интервалы
|
||||||
|
interval_days = 5 # Например, каждые 5 дней
|
||||||
|
current_start_date = start_date
|
||||||
|
|
||||||
|
while current_start_date < end_date:
|
||||||
|
current_end_date = min(current_start_date + timedelta(days=interval_days), end_date)
|
||||||
|
|
||||||
|
# Формирование payload
|
||||||
|
payload = {
|
||||||
|
"from": current_start_date.strftime('%Y-%m-%dT%H:%M:%SZ'),
|
||||||
|
"until": current_end_date.strftime('%Y-%m-%dT%H:%M:%SZ'),
|
||||||
|
}
|
||||||
|
print(f"[DEBUG] Sending payload: {json.dumps(payload)}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = await sync_to_async(requests.post)(self.api_url, headers=headers, data=json.dumps(payload))
|
response = await sync_to_async(requests.post)(self.api_url, headers=headers, data=json.dumps(payload))
|
||||||
except requests.RequestException as e:
|
response.raise_for_status()
|
||||||
print(f"[ERROR] Ошибка HTTP-запроса: {e}")
|
except requests.exceptions.RequestException as e:
|
||||||
raise ValueError(f"Ошибка HTTP-запроса: {e}")
|
error_message = f"[ERROR] Request error between {current_start_date} and {current_end_date}: {e}"
|
||||||
|
print(error_message)
|
||||||
print(f"[DEBUG] Response status: {response.status_code}")
|
report["errors"].append(error_message)
|
||||||
|
current_start_date = current_end_date
|
||||||
if response.status_code != 200:
|
|
||||||
print(f"[ERROR] Request error: {response.status_code}, {response.text}")
|
|
||||||
raise ValueError(f"Ошибка запроса: {response.status_code}, {response.text}")
|
|
||||||
|
|
||||||
try:
|
|
||||||
data = response.json()
|
|
||||||
except json.JSONDecodeError as e:
|
|
||||||
print(f"[ERROR] Ошибка декодирования JSON: {e}")
|
|
||||||
raise ValueError(f"Ошибка декодирования JSON: {e}")
|
|
||||||
|
|
||||||
# Проверяем, что ответ содержит ключи "count" и "items"
|
|
||||||
if not isinstance(data, dict) or "count" not in data or "items" not in data:
|
|
||||||
print(f"[ERROR] Неверный формат данных: {data}")
|
|
||||||
raise ValueError(f"Неверный формат данных: {data}")
|
|
||||||
|
|
||||||
total_count = data.get("count", 0)
|
|
||||||
items = data.get("items", [])
|
|
||||||
|
|
||||||
print(f"[DEBUG] Total count: {total_count}, Items retrieved: {len(items)}")
|
|
||||||
|
|
||||||
if not isinstance(items, list):
|
|
||||||
print(f"[ERROR] Неверный тип items: {type(items)}. Ожидался list.")
|
|
||||||
raise ValueError(f"Неверный тип items: {type(items)}. Ожидался list.")
|
|
||||||
|
|
||||||
for item in items:
|
|
||||||
if not isinstance(item, dict):
|
|
||||||
print(f"[ERROR] Неверный формат элемента items: {item}")
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = response.json()
|
||||||
|
print(f"[DEBUG] Received response: {data}")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
error_message = f"[ERROR] Ошибка декодирования JSON между {current_start_date} и {current_end_date}: {e}"
|
||||||
|
print(error_message)
|
||||||
|
report["errors"].append(error_message)
|
||||||
|
current_start_date = current_end_date
|
||||||
|
continue
|
||||||
|
|
||||||
|
total_count = data.get("count", 0)
|
||||||
|
items = data.get("items", [])
|
||||||
|
print(f"[DEBUG] Retrieved {len(items)} items (Total: {total_count}).")
|
||||||
|
|
||||||
|
# Если данных нет, пропускаем текущий интервал
|
||||||
|
if not items:
|
||||||
|
print(f"[WARNING] No items found between {current_start_date} and {current_end_date}.")
|
||||||
|
else:
|
||||||
|
for idx, item in enumerate(items, start=1):
|
||||||
|
print(f"[DEBUG] Processing item #{idx}/{len(items)}: {item}")
|
||||||
try:
|
try:
|
||||||
await self._save_to_db(item)
|
await self._save_to_db(item)
|
||||||
|
report["processed_items"] += 1
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ERROR] Ошибка сохранения бронирования {item.get('id')}: {e}")
|
error_message = f"[ERROR] Error processing item {item.get('id', 'Unknown')}: {e}"
|
||||||
|
print(error_message)
|
||||||
|
report["errors"].append(error_message)
|
||||||
|
|
||||||
from_index += len(items)
|
# Отмечаем обработанный интервал
|
||||||
print(f"[DEBUG] Updated from_index: {from_index}")
|
report["processed_intervals"] += 1
|
||||||
|
|
||||||
except Exception as e:
|
# Обновляем начало интервала
|
||||||
print(f"[ERROR] Общая ошибка в методе _fetch_data: {e}")
|
current_start_date = current_end_date
|
||||||
|
|
||||||
|
print(f"[DEBUG] Data fetching completed from {start_date} to {end_date}.")
|
||||||
|
return report
|
||||||
|
|
||||||
|
|
||||||
async def _save_to_db(self, item):
|
async def _save_to_db(self, item):
|
||||||
"""
|
"""
|
||||||
Сохраняет данные о бронировании в БД.
|
Сохраняет данные о бронировании в БД.
|
||||||
|
Проверяет, существует ли уже бронирование с таким ID.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
print(f"[DEBUG] Fetching hotel for PMS: {self.pms_config}")
|
print(f"[DEBUG] Starting to save reservation {item['id']} to the database.")
|
||||||
|
|
||||||
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
|
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
|
||||||
print(f"[DEBUG] Hotel found: {hotel.name}")
|
print(f"[DEBUG] Hotel found: {hotel.name}")
|
||||||
|
|
||||||
# Учитываем формат даты без 'Z'
|
|
||||||
date_format = '%Y-%m-%dT%H:%M:%S'
|
date_format = '%Y-%m-%dT%H:%M:%S'
|
||||||
print(f"[DEBUG] Parsing check-in and check-out dates for reservation {item['id']}")
|
print(f"[DEBUG] Parsing check-in and check-out dates for reservation {item['id']}")
|
||||||
|
|
||||||
|
try:
|
||||||
check_in = datetime.strptime(item["from"], date_format).replace(tzinfo=timezone.utc)
|
check_in = datetime.strptime(item["from"], date_format).replace(tzinfo=timezone.utc)
|
||||||
check_out = datetime.strptime(item["until"], date_format).replace(tzinfo=timezone.utc)
|
check_out = datetime.strptime(item["until"], date_format).replace(tzinfo=timezone.utc)
|
||||||
|
print(f"[DEBUG] Parsed check-in: {check_in}, check-out: {check_out}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[ERROR] Ошибка парсинга дат для бронирования {item['id']}: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
# Проверяем room_number и устанавливаем значение по умолчанию, если оно отсутствует
|
|
||||||
room_number = item.get("roomNumber", "") or "Unknown"
|
room_number = item.get("roomNumber", "") or "Unknown"
|
||||||
print(f"[DEBUG] Room number determined: {room_number}")
|
print(f"[DEBUG] Room number determined: {room_number}")
|
||||||
|
|
||||||
# Сохраняем бронирование
|
print(f"[DEBUG] Checking if reservation with ID {item['id']} already exists.")
|
||||||
print(f"[DEBUG] Saving reservation {item['id']} to database")
|
existing_reservation = await sync_to_async(
|
||||||
reservation, created = await sync_to_async(Reservation.objects.update_or_create)(
|
Reservation.objects.filter(reservation_id=item["id"]).first
|
||||||
|
)()
|
||||||
|
|
||||||
|
if existing_reservation:
|
||||||
|
print(f"[DEBUG] Reservation with ID {item['id']} already exists. Updating it...")
|
||||||
|
print(f"[DEBUG] Updating existing reservation {item['id']}.")
|
||||||
|
await sync_to_async(Reservation.objects.update_or_create)(
|
||||||
reservation_id=item["id"],
|
reservation_id=item["id"],
|
||||||
hotel=hotel,
|
hotel=hotel,
|
||||||
defaults={
|
defaults={
|
||||||
@@ -171,12 +187,26 @@ class Shelter(BasePMSPlugin):
|
|||||||
"discount": item.get("discount", 0),
|
"discount": item.get("discount", 0),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
print(f"[DEBUG] Updated existing reservation {item['id']}.")
|
||||||
|
else:
|
||||||
|
print(f"[DEBUG] No existing reservation found for ID {item['id']}. Creating a new one...")
|
||||||
|
print(f"[DEBUG] Creating a new reservation {item['id']}.")
|
||||||
|
await sync_to_async(Reservation.objects.create)(
|
||||||
|
reservation_id=item["id"],
|
||||||
|
hotel=hotel,
|
||||||
|
room_number=room_number,
|
||||||
|
room_type=item.get("roomTypeName", ""),
|
||||||
|
check_in=check_in,
|
||||||
|
check_out=check_out,
|
||||||
|
status=item.get("checkInStatus", ""),
|
||||||
|
price=item.get("reservationPrice", 0),
|
||||||
|
discount=item.get("discount", 0),
|
||||||
|
)
|
||||||
|
print(f"[DEBUG] Created a new reservation {item['id']}.")
|
||||||
|
|
||||||
print(f"[DEBUG] {'Created' if created else 'Updated'} reservation {item['id']}")
|
print(f"[DEBUG] {'Created' if not existing_reservation else 'Updated'} reservation {item['id']} / {hotel.name}.")
|
||||||
|
|
||||||
except KeyError as ke:
|
|
||||||
print(f"[ERROR] Ошибка обработки ключей в элементе {item}: {ke}")
|
|
||||||
except ValueError as ve:
|
except ValueError as ve:
|
||||||
print(f"[ERROR] Ошибка обработки данных для бронирования {item['id']}: {ve}")
|
print(f"[ERROR] Ошибка обработки даты для бронирования {item['id']}: {ve}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ERROR] Общая ошибка сохранения бронирования {item.get('id', 'Unknown')}: {e}")
|
print(f"[ERROR] Ошибка сохранения бронирования {item['id']}: {e}")
|
||||||
|
|||||||
Binary file not shown.
1252
tmp_data/wpts_user_activity_log.json
Normal file
1252
tmp_data/wpts_user_activity_log.json
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user