168 lines
6.2 KiB
Python
168 lines
6.2 KiB
Python
from django.contrib.auth.decorators import login_required
|
||
from django.http import JsonResponse
|
||
from django.shortcuts import render
|
||
from django.views.decorators.http import require_http_methods
|
||
from django.db import transaction
|
||
import json
|
||
|
||
from ..models import (
|
||
TechAnalyze,
|
||
Satellite,
|
||
Polarization,
|
||
Modulation,
|
||
Standard,
|
||
)
|
||
|
||
|
||
@login_required
|
||
def tech_analyze_entry(request):
|
||
"""
|
||
Представление для ввода данных технического анализа.
|
||
"""
|
||
satellites = Satellite.objects.all().order_by('name')
|
||
|
||
context = {
|
||
'satellites': satellites,
|
||
}
|
||
|
||
return render(request, 'mainapp/tech_analyze_entry.html', context)
|
||
|
||
|
||
@login_required
|
||
@require_http_methods(["POST"])
|
||
def tech_analyze_save(request):
|
||
"""
|
||
API endpoint для сохранения данных технического анализа.
|
||
"""
|
||
try:
|
||
data = json.loads(request.body)
|
||
satellite_id = data.get('satellite_id')
|
||
rows = data.get('rows', [])
|
||
|
||
if not satellite_id:
|
||
return JsonResponse({
|
||
'success': False,
|
||
'error': 'Не выбран спутник'
|
||
}, status=400)
|
||
|
||
if not rows:
|
||
return JsonResponse({
|
||
'success': False,
|
||
'error': 'Нет данных для сохранения'
|
||
}, status=400)
|
||
|
||
try:
|
||
satellite = Satellite.objects.get(id=satellite_id)
|
||
except Satellite.DoesNotExist:
|
||
return JsonResponse({
|
||
'success': False,
|
||
'error': 'Спутник не найден'
|
||
}, status=404)
|
||
|
||
created_count = 0
|
||
updated_count = 0
|
||
errors = []
|
||
|
||
with transaction.atomic():
|
||
for idx, row in enumerate(rows, start=1):
|
||
try:
|
||
name = row.get('name', '').strip()
|
||
if not name:
|
||
errors.append(f"Строка {idx}: отсутствует имя")
|
||
continue
|
||
|
||
# Обработка поляризации
|
||
polarization_name = row.get('polarization', '').strip() or '-'
|
||
polarization, _ = Polarization.objects.get_or_create(name=polarization_name)
|
||
|
||
# Обработка модуляции
|
||
modulation_name = row.get('modulation', '').strip() or '-'
|
||
modulation, _ = Modulation.objects.get_or_create(name=modulation_name)
|
||
|
||
# Обработка стандарта
|
||
standard_name = row.get('standard', '').strip()
|
||
if standard_name.lower() == 'unknown':
|
||
standard_name = '-'
|
||
if not standard_name:
|
||
standard_name = '-'
|
||
standard, _ = Standard.objects.get_or_create(name=standard_name)
|
||
|
||
# Обработка числовых полей
|
||
frequency = row.get('frequency')
|
||
if frequency:
|
||
try:
|
||
frequency = float(str(frequency).replace(',', '.'))
|
||
except (ValueError, TypeError):
|
||
frequency = 0
|
||
else:
|
||
frequency = 0
|
||
|
||
freq_range = row.get('freq_range')
|
||
if freq_range:
|
||
try:
|
||
freq_range = float(str(freq_range).replace(',', '.'))
|
||
except (ValueError, TypeError):
|
||
freq_range = 0
|
||
else:
|
||
freq_range = 0
|
||
|
||
bod_velocity = row.get('bod_velocity')
|
||
if bod_velocity:
|
||
try:
|
||
bod_velocity = float(str(bod_velocity).replace(',', '.'))
|
||
except (ValueError, TypeError):
|
||
bod_velocity = 0
|
||
else:
|
||
bod_velocity = 0
|
||
|
||
note = row.get('note', '').strip()
|
||
|
||
# Создание или обновление записи
|
||
tech_analyze, created = TechAnalyze.objects.update_or_create(
|
||
name=name,
|
||
defaults={
|
||
'satellite': satellite,
|
||
'polarization': polarization,
|
||
'frequency': frequency,
|
||
'freq_range': freq_range,
|
||
'bod_velocity': bod_velocity,
|
||
'modulation': modulation,
|
||
'standard': standard,
|
||
'note': note,
|
||
'updated_by': request.user.customuser if hasattr(request.user, 'customuser') else None,
|
||
}
|
||
)
|
||
|
||
if created:
|
||
tech_analyze.created_by = request.user.customuser if hasattr(request.user, 'customuser') else None
|
||
tech_analyze.save()
|
||
created_count += 1
|
||
else:
|
||
updated_count += 1
|
||
|
||
except Exception as e:
|
||
errors.append(f"Строка {idx}: {str(e)}")
|
||
|
||
response_data = {
|
||
'success': True,
|
||
'created': created_count,
|
||
'updated': updated_count,
|
||
'total': created_count + updated_count,
|
||
}
|
||
|
||
if errors:
|
||
response_data['errors'] = errors
|
||
|
||
return JsonResponse(response_data)
|
||
|
||
except json.JSONDecodeError:
|
||
return JsonResponse({
|
||
'success': False,
|
||
'error': 'Неверный формат данных'
|
||
}, status=400)
|
||
except Exception as e:
|
||
return JsonResponse({
|
||
'success': False,
|
||
'error': str(e)
|
||
}, status=500)
|