cleanings
This commit is contained in:
110
antifroud/views.py
Normal file
110
antifroud/views.py
Normal file
@@ -0,0 +1,110 @@
|
||||
import logging
|
||||
from django.http import JsonResponse
|
||||
from django.shortcuts import render
|
||||
from django.contrib.auth.decorators import login_required
|
||||
from .models import ImportedHotel
|
||||
from hotels.models import Hotel
|
||||
|
||||
from django.contrib.admin.views.decorators import staff_member_required
|
||||
from django.utils import timezone
|
||||
|
||||
# Создаем логгер
|
||||
logger = logging.getLogger('antifroud')
|
||||
|
||||
@staff_member_required
|
||||
def import_selected_hotels(request):
|
||||
if request.method != 'POST':
|
||||
logger.error("Invalid request method. Only POST is allowed.")
|
||||
return JsonResponse({'success': False, 'error': 'Invalid request method'})
|
||||
|
||||
selected_hotels = request.POST.getlist('hotels')
|
||||
if not selected_hotels:
|
||||
logger.warning("No hotels selected for import.")
|
||||
return JsonResponse({'success': False, 'error': 'No hotels selected'})
|
||||
|
||||
try:
|
||||
logger.info("Fetching selected hotels from ImportedHotel model.")
|
||||
|
||||
# Получаем отели, которые были выбраны для импорта
|
||||
imported_hotels = ImportedHotel.objects.filter(id__in=selected_hotels)
|
||||
logger.info(f"Found {imported_hotels.count()} selected hotels for import.")
|
||||
|
||||
# Список для хранения новых объектов отелей
|
||||
hotels_to_import = []
|
||||
|
||||
for imported_hotel in imported_hotels:
|
||||
logger.debug(f"Preparing hotel data for import: {imported_hotel.name}, {imported_hotel.city}")
|
||||
|
||||
# Получаем APIConfiguration (если имеется)
|
||||
api_configuration = None
|
||||
if imported_hotel.api:
|
||||
api_configuration = imported_hotel.api
|
||||
|
||||
# Получаем PMSConfiguration (если имеется)
|
||||
pms_configuration = None
|
||||
if imported_hotel.pms:
|
||||
pms_configuration = imported_hotel.pms
|
||||
|
||||
# Проверяем, импортирован ли отель из другого отеля (imported_from)
|
||||
imported_from = None
|
||||
if imported_hotel.imported_from:
|
||||
imported_from = imported_hotel.imported_from
|
||||
|
||||
# Подготовим данные для нового отеля
|
||||
hotel_data = {
|
||||
'name': imported_hotel.name,
|
||||
'api': api_configuration,
|
||||
'pms': pms_configuration,
|
||||
'imported_from': imported_from,
|
||||
'imported_at': timezone.now(), # Устанавливаем дату импорта
|
||||
'import_status': 'completed', # Устанавливаем статус импорта
|
||||
}
|
||||
|
||||
# Создаем новый объект Hotel
|
||||
hotel = Hotel(**hotel_data)
|
||||
hotels_to_import.append(hotel)
|
||||
|
||||
# Массово сохраняем новые отели в таблице Hotels
|
||||
logger.info(f"Importing {len(hotels_to_import)} hotels into Hotel model.")
|
||||
Hotel.objects.bulk_create(hotels_to_import)
|
||||
logger.info("Hotels imported successfully.")
|
||||
|
||||
# Обновляем статус импортированных отелей
|
||||
imported_hotels.update(imported=True)
|
||||
logger.info(f"Updated {imported_hotels.count()} imported hotels' status.")
|
||||
|
||||
return JsonResponse({'success': True})
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error during hotel import: {str(e)}", exc_info=True)
|
||||
return JsonResponse({'success': False, 'error': str(e)})
|
||||
|
||||
from django.http import JsonResponse
|
||||
from django.views.decorators.csrf import csrf_exempt
|
||||
from .models import Hotel
|
||||
from .forms import HotelImportForm
|
||||
@csrf_exempt # Или используйте @login_required, если нужно ограничить доступ
|
||||
def import_hotels(request):
|
||||
if request.method == 'POST':
|
||||
form = HotelImportForm(request.POST)
|
||||
if form.is_valid():
|
||||
# Получаем выбранные отели
|
||||
selected_hotels = form.cleaned_data['hotels']
|
||||
|
||||
# Логика импорта отелей (например, можно их обновить или импортировать в другую базу)
|
||||
# Для примера, просто устанавливаем флаг "imported" в True
|
||||
for hotel in selected_hotels:
|
||||
hotel.imported_to_main_db = True
|
||||
hotel.save()
|
||||
|
||||
# Возвращаем успешный ответ
|
||||
return JsonResponse({"message": "Отели успешно импортированы!"}, status=200)
|
||||
else:
|
||||
# Если форма невалидна
|
||||
return JsonResponse({"message": "Ошибка при импорте отелей."}, status=400)
|
||||
|
||||
else:
|
||||
# GET-запрос, просто показываем форму
|
||||
form = HotelImportForm()
|
||||
|
||||
return render(request, 'antifroud/admin/import_hotels.html', {'form': form})
|
||||
Reference in New Issue
Block a user