synclog finshed

RealtyCalendar import finished (bugfixing remains)
This commit is contained in:
2024-12-24 21:34:56 +09:00
parent 12e99ca5c2
commit 4a82b39146
4 changed files with 124 additions and 183 deletions

View File

@@ -112,7 +112,7 @@ class ExternalDBSettingsAdmin(admin.ModelAdmin):
@admin.register(UserActivityLog) @admin.register(UserActivityLog)
class UserActivityLogAdmin(admin.ModelAdmin): class UserActivityLogAdmin(admin.ModelAdmin):
list_display = ("id", 'get_location',"formatted_timestamp", "date_time", "page_id", "url_parameters", "page_url" ,"created", "page_title", "type", "hits") list_display = ("id", 'get_location',"formatted_timestamp", "date_time", "page_id", "url_parameters", "page_url" ,"created", "page_title", "type", "hits")
search_fields = ("page_title", "url_parameters") search_fields = ("page_title", "url_parameters", "page_title")
list_filter = ("page_title", "created") list_filter = ("page_title", "created")
readonly_fields = ("created", "timestamp") readonly_fields = ("created", "timestamp")
@@ -204,16 +204,30 @@ class UserActivityLogAdmin(admin.ModelAdmin):
@admin.register(SyncLog) @admin.register(SyncLog)
class SyncLogAdmin(admin.ModelAdmin): class SyncLogAdmin(admin.ModelAdmin):
change_list_template = "antifroud/admin/sync_log.html" change_list_template = "antifroud/admin/sync_log.html" # Путь к вашему кастомному шаблону
list_display =['id', 'hotel', 'created', 'recieved_records', 'processed_records'] list_display = ['id', 'hotel', 'created', 'recieved_records', 'processed_records']
search_fields = ['id', 'hotel', 'created', 'recieved_records', 'processed_records'] search_fields = ['id', 'hotel__name', 'recieved_records', 'processed_records']
list_filter = ['id', 'hotel', 'created', 'recieved_records', 'processed_records'] list_filter = ['hotel', 'created']
class Meta: def changelist_view(self, request, extra_context=None):
model = SyncLog """
fields = ['hotel', 'recieved_records', 'processed_records'] Добавляет фильтрацию по отелям в шаблон.
"""
extra_context = extra_context or {}
# Получаем выбранный фильтр отеля из GET-параметров
hotel_id = request.GET.get('hotel')
hotels = Hotel.objects.all()
sync_logs = SyncLog.objects.all()
if hotel_id:
sync_logs = sync_logs.filter(hotel_id=hotel_id)
extra_context['sync_logs'] = sync_logs
extra_context['hotels'] = hotels
extra_context['selected_hotel'] = hotel_id # Чтобы отобразить выбранный отель
return super().changelist_view(request, extra_context=extra_context)
@admin.register(ViolationLog) @admin.register(ViolationLog)
class ViolationLogAdmin(admin.ModelAdmin): class ViolationLogAdmin(admin.ModelAdmin):
list_display = ['id', 'hotel', 'room_number' , 'hits', 'created_at', 'violation_type', 'violation_details', 'detected_at'] list_display = ['id', 'hotel', 'room_number' , 'hits', 'created_at', 'violation_type', 'violation_details', 'detected_at']

View File

@@ -1,7 +1,6 @@
{% extends "admin/change_list.html" %} {% extends "admin/change_list.html" %}
{% block content %} {% block content %}
<div class="container-fluid"> <div class="container-fluid">
<div class="row mt-4"> <div class="row mt-4">
<div class="col"> <div class="col">
<div class="card shadow-sm mb-2 db-graph"> <div class="card shadow-sm mb-2 db-graph">
@@ -9,53 +8,22 @@
<h6 class="text-white m-0 font-md">Журнал синхронизации</h6> <h6 class="text-white m-0 font-md">Журнал синхронизации</h6>
</div> </div>
<div class="card-body"> <div class="card-body">
<form method="post" action="{% url 'antifroud:sync_log_create' %}"> <!-- Форма фильтрации по отелям -->
{% csrf_token %} <form method="get" class="form-inline mb-3">
<div class="form-row"> <label for="hotel-filter" class="mr-2">Фильтр по отелям:</label>
<div class="col-md-9 col-xl-9"> <select name="hotel" id="hotel-filter" class="form-control mr-2">
<div class="box-bg"> <option value="">-- Все отели --</option>
<div class="form-row"> {% for hotel in hotels %}
<div class="col-md-2 col-xl-2 align-self-center font-md text-dark-blue"> <option value="{{ hotel.id }}" {% if hotel.id|stringformat:"s" == selected_hotel %}selected{% endif %}>
<label class="col-form-label p-0" for="hotel-id"><strong>Отель:</strong></label> {{ hotel.name }}
</div> </option>
<div class="col-md-4 col-xl-3"> {% endfor %}
<div class="form-group mb-0"> </select>
<select class="custom-select custom-select-sm font-sm" name="hotel" id="hotel-id"> <button type="submit" class="btn btn-primary">Применить</button>
<option value="">--Выберите Отель --</option>
{% for hotel in hotels %}
<option value="{{ hotel.id }}">{{ hotel.name }}</option>
{% endfor %}
</select>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-3 col-xl-3">
<div class="box-bg">
<div class="text-dark form-row">
<div class="col-xl-5 offset-xl-0 align-self-center">
<h6 class="mb-0 font-sm">Полученные записи:</h6>
</div>
<div class="col-xl-7 offset-xl-0 text-right align-self-center">
<div class="form-group mb-1">
<input class="form-control form-control-sm form-control font-sm" type="number" name="received_records" required />
</div>
</div>
<div class="col-xl-5 offset-xl-0 align-self-center">
<h6 class="mb-0 font-sm">Обработанные записи:</h6>
</div>
<div class="col-xl-7 offset-xl-0 text-right align-self-center">
<div class="form-group mb-1">
<input class="form-control form-control-sm form-control font-sm" type="number" name="processed_records" required />
</div>
</div>
</div>
</div>
</div>
</div>
</form> </form>
<!-- Список существующих журналов синхронизации --> <!-- Список существующих журналов синхронизации -->
<div class="table-responsive tbl-wfx mt-1 kot-table"> <div class="table-responsive tbl-wfx mt-1 kot-table">
<table class="table table-sm"> <table class="table table-sm">
@@ -63,10 +31,8 @@
<tr class="text-dark-blue"> <tr class="text-dark-blue">
<th>#</th> <th>#</th>
<th>Отель</th> <th>Отель</th>
<th>ID бронирования</th> <th> Дата синхронизации</th>
<th>Обработанные записи</th> <th>Обработанные записи</th>
<th>Полученные записи</th>
<th>Создан</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -74,14 +40,12 @@
<tr> <tr>
<td>{{ log.id }}</td> <td>{{ log.id }}</td>
<td>{{ log.hotel.name }}</td> <td>{{ log.hotel.name }}</td>
<td>{{ log.reservation_id }}</td>
<td>{{ log.processed_records }}</td>
<td>{{ log.recieved_records }}</td>
<td>{{ log.created }}</td> <td>{{ log.created }}</td>
<td>{{ log.processed_records }}</td>
</tr> </tr>
{% empty %} {% empty %}
<tr> <tr>
<td colspan="6" class="text-center">Нет журналов.</td> <td colspan="5" class="text-center">Нет записей.</td>
</tr> </tr>
{% endfor %} {% endfor %}
</tbody> </tbody>
@@ -93,4 +57,4 @@
</div> </div>
</div> </div>
{% endblock %} {% endblock %}

View File

@@ -6,8 +6,9 @@ from datetime import datetime, timedelta
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
from touchh.utils.log import CustomLogger from touchh.utils.log import CustomLogger
from hotels.models import Hotel, Reservation from hotels.models import Hotel, Reservation
from app_settings.models import GlobalHotelSettings
from django.utils import timezone
class RealtyCalendarPlugin(BasePMSPlugin): class RealtyCalendarPlugin(BasePMSPlugin):
"""Плагин для импорта данных из системы RealtyCalendar."""
def __init__(self, config): def __init__(self, config):
super().__init__(config) super().__init__(config)
self.public_key = config.public_key self.public_key = config.public_key
@@ -72,145 +73,107 @@ class RealtyCalendarPlugin(BasePMSPlugin):
"Content-Type": "application/json", "Content-Type": "application/json",
} }
# Определяем даты выборки
now = datetime.now() now = datetime.now()
data = { data = {
"begin_date": (now - timedelta(days=7)).strftime("%Y-%m-%d"), "begin_date": (now - timedelta(days=7)).strftime("%Y-%m-%d"),
"end_date": now.strftime("%Y-%m-%d"), "end_date": now.strftime("%Y-%m-%d"),
} }
self.logger.debug(f"Даты выборки: {data}")
# Генерация подписи
data["sign"] = self._generate_sign(data) data["sign"] = self._generate_sign(data)
# Отправляем запрос
self.logger.debug(f"URL запроса: {base_url}")
self.logger.debug(f"Заголовки: {headers}")
self.logger.debug(f"Данные запроса: {data}")
response = requests.post(url=base_url, headers=headers, json=data) response = requests.post(url=base_url, headers=headers, json=data)
self.logger.debug(f"Запрос: {response}")
self.logger.debug(f"Статус ответа: {response.status_code}") self.logger.debug(f"Статус ответа: {response.status_code}")
# self.logger.debug(f"Ответ: {response.text}")
if response.status_code == 200: if response.status_code != 200:
try: self.logger.error(f"Ошибка API: {response.status_code}, {response.text}")
response_data = response.json() raise ValueError(f"Ошибка API RealtyCalendar: {response.status_code}")
self.logger.debug(f"Тип данных ответа: {type(response_data)}")
if not isinstance(response_data, dict) or "bookings" not in response_data:
raise ValueError(f"Неожиданная структура ответа: {response_data}")
bookings = response_data.get("bookings", [])
# self.logger.debug(f"Полученные данные бронирований: {bookings}")
except json.JSONDecodeError as e:
self.logger.error(f"Ошибка декодирования JSON: {e}")
raise ValueError("Ошибка декодирования JSON ответа.")
# Фильтрация данных try:
filtered_data = [ response_data = response.json()
{ bookings = response_data.get("bookings", [])
"id": item.get("id"), if not isinstance(bookings, list):
"begin_date": item.get("begin_date"), raise ValueError(f"Ожидался список, но получен {type(bookings)}")
"end_date": item.get("end_date"), except Exception as e:
"amount": item.get("amount"), self.logger.error(f"Ошибка обработки ответа API: {e}")
"status": item.get("status"), raise
"is_delete": item.get("is_delete"),
"apartment_id": item.get("apartment_id"),
"prepayment": item.get("prepayment"),
"deposit": item.get("deposit"),
"source": item.get("source"),
"notes": item.get("notes"),
}
for item in bookings
if isinstance(item, dict) and item.get("status") in ["booked", "request"]
]
self.logger.debug(f"Отфильтрованные данные: {type(filtered_data)}")
for item in filtered_data: # Получаем глобальные настройки отеля
self.logger.debug(f"Данные бронирования: {item}") hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
await self._save_to_db(item) hotel_tz = hotel.timezone
try:
from django.utils import timezone hotel_settings = await sync_to_async(GlobalHotelSettings.objects.first)()
check_in_time = hotel_settings.check_in_time.strftime("%H:%M:%S")
check_out_time = hotel_settings.check_out_time.strftime("%H:%M:%S")
except AttributeError:
# Используем значения по умолчанию, если настроек нет
check_in_time = "14:00:00"
check_out_time = "12:00:00"
filtered_data = [
{
'reservation_id': item.get('id'),
'checkin': timezone.make_aware(
datetime.strptime(
f"{item.get('begin_date')} {check_in_time}",
"%Y-%m-%d %H:%M:%S"
)
),
'checkout': timezone.make_aware(
datetime.strptime(
f"{item.get('end_date')} {check_out_time}",
"%Y-%m-%d %H:%M:%S"
)
),
'room_number': item.get('apartment_id'),
'room_type': item.get('notes', 'Описание отсутствует'),
'status': item.get('status')
}
for item in bookings
if isinstance(item, dict) and item.get("status") in ["booked", "request"]
]
await self._save_to_db(filtered_data)
async def _save_to_db(self, data): async def _save_to_db(self, data):
from django.utils import timezone
""" """
Сохраняет данные в БД (например, информацию о номере). Сохраняет данные в БД (например, информацию о номере).
""" """
try: if not isinstance(data, list):
# Проверяем общее количество записей для обработки self.logger.error(f"Ожидался список записей, но получен {type(data).__name__}")
if not isinstance(data, list): return
self.logger.error(f"Ожидался список записей, но получен {type(data).__name__}")
return
total_records = len(data) for index, item in enumerate(data, start=1):
self.logger.info(f"Общее количество записей для обработки: {total_records}") try:
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
reservation_id = item.get('reservation_id')
if not reservation_id:
self.logger.error(f"Пропущена запись {index}: отсутствует 'id'")
continue
for index, item in enumerate(data, start=1): existing_reservation = await sync_to_async(Reservation.objects.filter)(reservation_id=reservation_id)
try: existing_reservation = await sync_to_async(existing_reservation.first)()
self.logger.info(f"Обработка записи {index}/{total_records}")
# Проверка типа данных defaults = {
if not isinstance(item, dict): 'room_number': item['room_number'],
self.logger.error(f"Пропущена запись {index}/{total_records}: ожидался dict, но получен {type(item).__name__}") 'room_type': item['room_type'],
continue 'check_in': item['checkin'],
'check_out': item['checkout'],
'status': item['status'],
'hotel': hotel
}
# Получаем отель по настройкам PMS if existing_reservation:
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config) await sync_to_async(Reservation.objects.update_or_create)(
self.logger.debug(f"Отель найден: {hotel.name}") reservation_id=reservation_id, defaults=defaults
)
# Проверяем, существует ли уже резервация с таким внешним ID self.logger.debug(f"Резервация {reservation_id} обновлена.")
reservation_id = item.get('id') else:
if not reservation_id: await sync_to_async(Reservation.objects.create)(
self.logger.error(f"Пропущена запись {index}/{total_records}: отсутствует 'id' в данных.") reservation_id=reservation_id, **defaults
continue )
self.logger.debug(f"Создана новая резервация {reservation_id}")
# Преобразуем даты в "aware" объекты
try:
check_in = timezone.make_aware(datetime.strptime(item.get('begin_date'), "%Y-%m-%d"))
check_out = timezone.make_aware(datetime.strptime(item.get('end_date'), "%Y-%m-%d"))
except Exception as e:
self.logger.error(f"Ошибка преобразования дат для записи {index}/{total_records}: {e}")
continue
existing_reservation = await sync_to_async(Reservation.objects.filter)(reservation_id=reservation_id)
# Теперь вызываем .first() после асинхронного вызова
existing_reservation = await sync_to_async(existing_reservation.first)()
if existing_reservation:
self.logger.debug(f"Резервация {reservation_id} уже существует. Обновляем...")
await sync_to_async(Reservation.objects.update_or_create)(
reservation_id=reservation_id,
defaults={
'room_number': item.get('apartment_id'),
'room_type': 'Описание отсутствует',
'check_in': check_in,
'check_out': check_out,
'status': item.get('status'),
'hotel': hotel
}
)
self.logger.debug(f"Резервация обновлена.")
else:
self.logger.debug(f"Резервация не найдена, создаем новую...")
reservation = await sync_to_async(Reservation.objects.create)(
reservation_id=reservation_id,
room_number=item.get('apartment_id'),
room_type='Описание отсутствует',
check_in=check_in,
check_out=check_out,
status=item.get('status'),
hotel=hotel
)
self.logger.debug(f"Новая резервация создана с ID: {reservation.reservation_id}")
except Exception as e:
self.logger.error(f"Ошибка при обработке записи {index}/{total_records}: {e}")
except Exception as e:
self.logger.error(f"Ошибка обработки данных в _save_to_db: {e}")
except Exception as e:
self.logger.error(f"Ошибка при обработке записи {index}: {e}")
def validate_plugin(self): def validate_plugin(self):
""" """

View File

@@ -34,10 +34,10 @@ SECRET_KEY = 'django-insecure-l_8uu8#p*^zf)9zry80)6u+!+2g1a4tg!wx7@^!uw(+^axyh&h
# SECURITY WARNING: don't run with debug turned on in production! # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True DEBUG = True
ALLOWED_HOSTS = ['0.0.0.0', '192.168.219.140', '127.0.0.1', 'localhost', '192.168.219.114', '588a-182-226-158-253.ngrok-free.app', '*.ngrok-free.app'] ALLOWED_HOSTS = ['0.0.0.0', '192.168.219.140', '127.0.0.1', 'localhost', '192.168.219.114', '8f6e-182-226-158-253.ngrok-free.app', '*.ngrok-free.app']
CSRF_TRUSTED_ORIGINS = [ CSRF_TRUSTED_ORIGINS = [
'http://588a-182-226-158-253.ngrok-free.app', 'https://8f6e-182-226-158-253.ngrok-free.app',
'https://*.ngrok-free.app', # Это подойдет для любых URL, связанных с ngrok 'https://*.ngrok-free.app', # Это подойдет для любых URL, связанных с ngrok
] ]