synclog finshed
RealtyCalendar import finished (bugfixing remains)
This commit is contained in:
@@ -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']
|
||||||
|
|||||||
@@ -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">
|
|
||||||
<div class="col-md-2 col-xl-2 align-self-center font-md text-dark-blue">
|
|
||||||
<label class="col-form-label p-0" for="hotel-id"><strong>Отель:</strong></label>
|
|
||||||
</div>
|
|
||||||
<div class="col-md-4 col-xl-3">
|
|
||||||
<div class="form-group mb-0">
|
|
||||||
<select class="custom-select custom-select-sm font-sm" name="hotel" id="hotel-id">
|
|
||||||
<option value="">--Выберите Отель --</option>
|
|
||||||
{% for hotel in hotels %}
|
{% for hotel in hotels %}
|
||||||
<option value="{{ hotel.id }}">{{ hotel.name }}</option>
|
<option value="{{ hotel.id }}" {% if hotel.id|stringformat:"s" == selected_hotel %}selected{% endif %}>
|
||||||
|
{{ hotel.name }}
|
||||||
|
</option>
|
||||||
{% endfor %}
|
{% endfor %}
|
||||||
</select>
|
</select>
|
||||||
</div>
|
<button type="submit" class="btn btn-primary">Применить</button>
|
||||||
</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>
|
||||||
|
|||||||
@@ -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:
|
||||||
|
self.logger.error(f"Ошибка API: {response.status_code}, {response.text}")
|
||||||
|
raise ValueError(f"Ошибка API RealtyCalendar: {response.status_code}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response_data = response.json()
|
response_data = response.json()
|
||||||
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", [])
|
bookings = response_data.get("bookings", [])
|
||||||
# self.logger.debug(f"Полученные данные бронирований: {bookings}")
|
if not isinstance(bookings, list):
|
||||||
except json.JSONDecodeError as e:
|
raise ValueError(f"Ожидался список, но получен {type(bookings)}")
|
||||||
self.logger.error(f"Ошибка декодирования JSON: {e}")
|
except Exception as e:
|
||||||
raise ValueError("Ошибка декодирования JSON ответа.")
|
self.logger.error(f"Ошибка обработки ответа API: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
# Получаем глобальные настройки отеля
|
||||||
|
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
|
||||||
|
hotel_tz = hotel.timezone
|
||||||
|
try:
|
||||||
|
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 = [
|
filtered_data = [
|
||||||
{
|
{
|
||||||
"id": item.get("id"),
|
'reservation_id': item.get('id'),
|
||||||
"begin_date": item.get("begin_date"),
|
'checkin': timezone.make_aware(
|
||||||
"end_date": item.get("end_date"),
|
datetime.strptime(
|
||||||
"amount": item.get("amount"),
|
f"{item.get('begin_date')} {check_in_time}",
|
||||||
"status": item.get("status"),
|
"%Y-%m-%d %H:%M:%S"
|
||||||
"is_delete": item.get("is_delete"),
|
)
|
||||||
"apartment_id": item.get("apartment_id"),
|
),
|
||||||
"prepayment": item.get("prepayment"),
|
'checkout': timezone.make_aware(
|
||||||
"deposit": item.get("deposit"),
|
datetime.strptime(
|
||||||
"source": item.get("source"),
|
f"{item.get('end_date')} {check_out_time}",
|
||||||
"notes": item.get("notes"),
|
"%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
|
for item in bookings
|
||||||
if isinstance(item, dict) and item.get("status") in ["booked", "request"]
|
if isinstance(item, dict) and item.get("status") in ["booked", "request"]
|
||||||
]
|
]
|
||||||
self.logger.debug(f"Отфильтрованные данные: {type(filtered_data)}")
|
|
||||||
|
|
||||||
for item in filtered_data:
|
await self._save_to_db(filtered_data)
|
||||||
self.logger.debug(f"Данные бронирования: {item}")
|
|
||||||
await self._save_to_db(item)
|
|
||||||
|
|
||||||
from django.utils import timezone
|
|
||||||
|
|
||||||
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):
|
if not isinstance(data, list):
|
||||||
self.logger.error(f"Ожидался список записей, но получен {type(data).__name__}")
|
self.logger.error(f"Ожидался список записей, но получен {type(data).__name__}")
|
||||||
return
|
return
|
||||||
|
|
||||||
total_records = len(data)
|
|
||||||
self.logger.info(f"Общее количество записей для обработки: {total_records}")
|
|
||||||
|
|
||||||
for index, item in enumerate(data, start=1):
|
for index, item in enumerate(data, start=1):
|
||||||
try:
|
try:
|
||||||
self.logger.info(f"Обработка записи {index}/{total_records}")
|
|
||||||
|
|
||||||
# Проверка типа данных
|
|
||||||
if not isinstance(item, dict):
|
|
||||||
self.logger.error(f"Пропущена запись {index}/{total_records}: ожидался dict, но получен {type(item).__name__}")
|
|
||||||
continue
|
|
||||||
|
|
||||||
# Получаем отель по настройкам PMS
|
|
||||||
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
|
hotel = await sync_to_async(Hotel.objects.get)(pms=self.pms_config)
|
||||||
self.logger.debug(f"Отель найден: {hotel.name}")
|
reservation_id = item.get('reservation_id')
|
||||||
|
|
||||||
# Проверяем, существует ли уже резервация с таким внешним ID
|
|
||||||
reservation_id = item.get('id')
|
|
||||||
if not reservation_id:
|
if not reservation_id:
|
||||||
self.logger.error(f"Пропущена запись {index}/{total_records}: отсутствует 'id' в данных.")
|
self.logger.error(f"Пропущена запись {index}: отсутствует 'id'")
|
||||||
continue
|
|
||||||
|
|
||||||
# Преобразуем даты в "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
|
continue
|
||||||
|
|
||||||
existing_reservation = await sync_to_async(Reservation.objects.filter)(reservation_id=reservation_id)
|
existing_reservation = await sync_to_async(Reservation.objects.filter)(reservation_id=reservation_id)
|
||||||
|
|
||||||
# Теперь вызываем .first() после асинхронного вызова
|
|
||||||
existing_reservation = await sync_to_async(existing_reservation.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 = {
|
defaults = {
|
||||||
'room_number': item.get('apartment_id'),
|
'room_number': item['room_number'],
|
||||||
'room_type': 'Описание отсутствует',
|
'room_type': item['room_type'],
|
||||||
'check_in': check_in,
|
'check_in': item['checkin'],
|
||||||
'check_out': check_out,
|
'check_out': item['checkout'],
|
||||||
'status': item.get('status'),
|
'status': item['status'],
|
||||||
'hotel': hotel
|
'hotel': hotel
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if existing_reservation:
|
||||||
|
await sync_to_async(Reservation.objects.update_or_create)(
|
||||||
|
reservation_id=reservation_id, defaults=defaults
|
||||||
)
|
)
|
||||||
self.logger.debug(f"Резервация обновлена.")
|
self.logger.debug(f"Резервация {reservation_id} обновлена.")
|
||||||
else:
|
else:
|
||||||
self.logger.debug(f"Резервация не найдена, создаем новую...")
|
await sync_to_async(Reservation.objects.create)(
|
||||||
reservation = await sync_to_async(Reservation.objects.create)(
|
reservation_id=reservation_id, **defaults
|
||||||
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}")
|
self.logger.debug(f"Создана новая резервация {reservation_id}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
self.logger.error(f"Ошибка при обработке записи {index}/{total_records}: {e}")
|
self.logger.error(f"Ошибка при обработке записи {index}: {e}")
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
self.logger.error(f"Ошибка обработки данных в _save_to_db: {e}")
|
|
||||||
|
|
||||||
|
|
||||||
def validate_plugin(self):
|
def validate_plugin(self):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -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
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user