Compare commits
2 Commits
8393734dc3
...
4949a03e68
| Author | SHA1 | Date | |
|---|---|---|---|
| 4949a03e68 | |||
| d889dc7b2a |
@@ -926,10 +926,10 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
Форма для создания и редактирования заявок на источники.
|
Форма для создания и редактирования заявок на источники.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Дополнительные поля для координат
|
# Дополнительные поля для координат ГСО
|
||||||
coords_lat = forms.FloatField(
|
coords_lat = forms.FloatField(
|
||||||
required=False,
|
required=False,
|
||||||
label='Широта',
|
label='Широта ГСО',
|
||||||
widget=forms.NumberInput(attrs={
|
widget=forms.NumberInput(attrs={
|
||||||
'class': 'form-control',
|
'class': 'form-control',
|
||||||
'step': '0.000001',
|
'step': '0.000001',
|
||||||
@@ -938,7 +938,27 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
)
|
)
|
||||||
coords_lon = forms.FloatField(
|
coords_lon = forms.FloatField(
|
||||||
required=False,
|
required=False,
|
||||||
label='Долгота',
|
label='Долгота ГСО',
|
||||||
|
widget=forms.NumberInput(attrs={
|
||||||
|
'class': 'form-control',
|
||||||
|
'step': '0.000001',
|
||||||
|
'placeholder': 'Например: 37.618423'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
# Дополнительные поля для координат источника
|
||||||
|
coords_source_lat = forms.FloatField(
|
||||||
|
required=False,
|
||||||
|
label='Широта источника',
|
||||||
|
widget=forms.NumberInput(attrs={
|
||||||
|
'class': 'form-control',
|
||||||
|
'step': '0.000001',
|
||||||
|
'placeholder': 'Например: 55.751244'
|
||||||
|
})
|
||||||
|
)
|
||||||
|
coords_source_lon = forms.FloatField(
|
||||||
|
required=False,
|
||||||
|
label='Долгота источника',
|
||||||
widget=forms.NumberInput(attrs={
|
widget=forms.NumberInput(attrs={
|
||||||
'class': 'form-control',
|
'class': 'form-control',
|
||||||
'step': '0.000001',
|
'step': '0.000001',
|
||||||
@@ -951,10 +971,16 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
model = SourceRequest
|
model = SourceRequest
|
||||||
fields = [
|
fields = [
|
||||||
'source',
|
'source',
|
||||||
|
'satellite',
|
||||||
'status',
|
'status',
|
||||||
'priority',
|
'priority',
|
||||||
'planned_at',
|
'planned_at',
|
||||||
'request_date',
|
'request_date',
|
||||||
|
'card_date',
|
||||||
|
'downlink',
|
||||||
|
'uplink',
|
||||||
|
'transfer',
|
||||||
|
'region',
|
||||||
'gso_success',
|
'gso_success',
|
||||||
'kubsat_success',
|
'kubsat_success',
|
||||||
'comment',
|
'comment',
|
||||||
@@ -962,7 +988,9 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
widgets = {
|
widgets = {
|
||||||
'source': forms.Select(attrs={
|
'source': forms.Select(attrs={
|
||||||
'class': 'form-select',
|
'class': 'form-select',
|
||||||
'required': True
|
}),
|
||||||
|
'satellite': forms.Select(attrs={
|
||||||
|
'class': 'form-select',
|
||||||
}),
|
}),
|
||||||
'status': forms.Select(attrs={
|
'status': forms.Select(attrs={
|
||||||
'class': 'form-select'
|
'class': 'form-select'
|
||||||
@@ -978,6 +1006,29 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
'class': 'form-control',
|
'class': 'form-control',
|
||||||
'type': 'date'
|
'type': 'date'
|
||||||
}),
|
}),
|
||||||
|
'card_date': forms.DateInput(attrs={
|
||||||
|
'class': 'form-control',
|
||||||
|
'type': 'date'
|
||||||
|
}),
|
||||||
|
'downlink': forms.NumberInput(attrs={
|
||||||
|
'class': 'form-control',
|
||||||
|
'step': '0.01',
|
||||||
|
'placeholder': 'Частота downlink в МГц'
|
||||||
|
}),
|
||||||
|
'uplink': forms.NumberInput(attrs={
|
||||||
|
'class': 'form-control',
|
||||||
|
'step': '0.01',
|
||||||
|
'placeholder': 'Частота uplink в МГц'
|
||||||
|
}),
|
||||||
|
'transfer': forms.NumberInput(attrs={
|
||||||
|
'class': 'form-control',
|
||||||
|
'step': '0.01',
|
||||||
|
'placeholder': 'Перенос в МГц'
|
||||||
|
}),
|
||||||
|
'region': forms.TextInput(attrs={
|
||||||
|
'class': 'form-control',
|
||||||
|
'placeholder': 'Район/местоположение'
|
||||||
|
}),
|
||||||
'gso_success': forms.Select(
|
'gso_success': forms.Select(
|
||||||
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
||||||
attrs={'class': 'form-select'}
|
attrs={'class': 'form-select'}
|
||||||
@@ -994,10 +1045,16 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
}
|
}
|
||||||
labels = {
|
labels = {
|
||||||
'source': 'Источник',
|
'source': 'Источник',
|
||||||
|
'satellite': 'Спутник',
|
||||||
'status': 'Статус',
|
'status': 'Статус',
|
||||||
'priority': 'Приоритет',
|
'priority': 'Приоритет',
|
||||||
'planned_at': 'Дата и время планирования',
|
'planned_at': 'Дата и время планирования',
|
||||||
'request_date': 'Дата заявки',
|
'request_date': 'Дата заявки',
|
||||||
|
'card_date': 'Дата формирования карточки',
|
||||||
|
'downlink': 'Частота Downlink (МГц)',
|
||||||
|
'uplink': 'Частота Uplink (МГц)',
|
||||||
|
'transfer': 'Перенос (МГц)',
|
||||||
|
'region': 'Район',
|
||||||
'gso_success': 'ГСО успешно?',
|
'gso_success': 'ГСО успешно?',
|
||||||
'kubsat_success': 'Кубсат успешно?',
|
'kubsat_success': 'Кубсат успешно?',
|
||||||
'comment': 'Комментарий',
|
'comment': 'Комментарий',
|
||||||
@@ -1008,8 +1065,10 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
source_id = kwargs.pop('source_id', None)
|
source_id = kwargs.pop('source_id', None)
|
||||||
super().__init__(*args, **kwargs)
|
super().__init__(*args, **kwargs)
|
||||||
|
|
||||||
# Загружаем queryset для источников
|
# Загружаем queryset для источников и спутников
|
||||||
self.fields['source'].queryset = Source.objects.all().order_by('-id')
|
self.fields['source'].queryset = Source.objects.all().order_by('-id')
|
||||||
|
self.fields['source'].required = False
|
||||||
|
self.fields['satellite'].queryset = Satellite.objects.all().order_by('name')
|
||||||
|
|
||||||
# Если передан source_id, устанавливаем его как начальное значение
|
# Если передан source_id, устанавливаем его как начальное значение
|
||||||
if source_id:
|
if source_id:
|
||||||
@@ -1017,6 +1076,13 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
# Можно сделать поле только для чтения
|
# Можно сделать поле только для чтения
|
||||||
self.fields['source'].widget.attrs['readonly'] = True
|
self.fields['source'].widget.attrs['readonly'] = True
|
||||||
|
|
||||||
|
# Пытаемся заполнить данные из источника
|
||||||
|
try:
|
||||||
|
source = Source.objects.get(pk=source_id)
|
||||||
|
self._fill_from_source(source)
|
||||||
|
except Source.DoesNotExist:
|
||||||
|
pass
|
||||||
|
|
||||||
# Настраиваем виджеты для булевых полей
|
# Настраиваем виджеты для булевых полей
|
||||||
self.fields['gso_success'].widget = forms.Select(
|
self.fields['gso_success'].widget = forms.Select(
|
||||||
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
choices=[(None, '-'), (True, 'Да'), (False, 'Нет')],
|
||||||
@@ -1028,16 +1094,44 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Заполняем координаты из существующего объекта
|
# Заполняем координаты из существующего объекта
|
||||||
if self.instance and self.instance.pk and self.instance.coords:
|
if self.instance and self.instance.pk:
|
||||||
self.fields['coords_lat'].initial = self.instance.coords.y
|
if self.instance.coords:
|
||||||
self.fields['coords_lon'].initial = self.instance.coords.x
|
self.fields['coords_lat'].initial = self.instance.coords.y
|
||||||
|
self.fields['coords_lon'].initial = self.instance.coords.x
|
||||||
|
if self.instance.coords_source:
|
||||||
|
self.fields['coords_source_lat'].initial = self.instance.coords_source.y
|
||||||
|
self.fields['coords_source_lon'].initial = self.instance.coords_source.x
|
||||||
|
|
||||||
|
def _fill_from_source(self, source):
|
||||||
|
"""Заполняет поля формы данными из источника и его связанных объектов."""
|
||||||
|
# Получаем первую точку источника с транспондером
|
||||||
|
objitem = source.source_objitems.select_related(
|
||||||
|
'transponder', 'transponder__sat_id', 'parameter_obj'
|
||||||
|
).filter(transponder__isnull=False).first()
|
||||||
|
|
||||||
|
if objitem and objitem.transponder:
|
||||||
|
transponder = objitem.transponder
|
||||||
|
# Заполняем данные из транспондера
|
||||||
|
if transponder.downlink:
|
||||||
|
self.fields['downlink'].initial = transponder.downlink
|
||||||
|
if transponder.uplink:
|
||||||
|
self.fields['uplink'].initial = transponder.uplink
|
||||||
|
if transponder.transfer:
|
||||||
|
self.fields['transfer'].initial = transponder.transfer
|
||||||
|
if transponder.sat_id:
|
||||||
|
self.fields['satellite'].initial = transponder.sat_id.pk
|
||||||
|
|
||||||
|
# Координаты из источника
|
||||||
|
if source.coords_average:
|
||||||
|
self.fields['coords_lat'].initial = source.coords_average.y
|
||||||
|
self.fields['coords_lon'].initial = source.coords_average.x
|
||||||
|
|
||||||
def save(self, commit=True):
|
def save(self, commit=True):
|
||||||
from django.contrib.gis.geos import Point
|
from django.contrib.gis.geos import Point
|
||||||
|
|
||||||
instance = super().save(commit=False)
|
instance = super().save(commit=False)
|
||||||
|
|
||||||
# Обрабатываем координаты
|
# Обрабатываем координаты ГСО
|
||||||
coords_lat = self.cleaned_data.get('coords_lat')
|
coords_lat = self.cleaned_data.get('coords_lat')
|
||||||
coords_lon = self.cleaned_data.get('coords_lon')
|
coords_lon = self.cleaned_data.get('coords_lon')
|
||||||
|
|
||||||
@@ -1046,6 +1140,15 @@ class SourceRequestForm(forms.ModelForm):
|
|||||||
elif coords_lat is None and coords_lon is None:
|
elif coords_lat is None and coords_lon is None:
|
||||||
instance.coords = None
|
instance.coords = None
|
||||||
|
|
||||||
|
# Обрабатываем координаты источника
|
||||||
|
coords_source_lat = self.cleaned_data.get('coords_source_lat')
|
||||||
|
coords_source_lon = self.cleaned_data.get('coords_source_lon')
|
||||||
|
|
||||||
|
if coords_source_lat is not None and coords_source_lon is not None:
|
||||||
|
instance.coords_source = Point(coords_source_lon, coords_source_lat, srid=4326)
|
||||||
|
elif coords_source_lat is None and coords_source_lon is None:
|
||||||
|
instance.coords_source = None
|
||||||
|
|
||||||
if commit:
|
if commit:
|
||||||
instance.save()
|
instance.save()
|
||||||
|
|
||||||
|
|||||||
60
dbapp/mainapp/migrations/0021_add_source_request_fields.py
Normal file
60
dbapp/mainapp/migrations/0021_add_source_request_fields.py
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
# Generated by Django 5.2.7 on 2025-12-09 12:39
|
||||||
|
|
||||||
|
import django.contrib.gis.db.models.fields
|
||||||
|
import django.db.models.deletion
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('mainapp', '0020_satellite_location_place'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='card_date',
|
||||||
|
field=models.DateField(blank=True, help_text='Дата формирования карточки', null=True, verbose_name='Дата формирования карточки'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='coords_source',
|
||||||
|
field=django.contrib.gis.db.models.fields.PointField(blank=True, help_text='Координаты источника (WGS84)', null=True, srid=4326, verbose_name='Координаты источника'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='downlink',
|
||||||
|
field=models.FloatField(blank=True, help_text='Частота downlink в МГц', null=True, verbose_name='Частота Downlink, МГц'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='region',
|
||||||
|
field=models.CharField(blank=True, help_text='Район/местоположение', max_length=255, null=True, verbose_name='Район'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='satellite',
|
||||||
|
field=models.ForeignKey(blank=True, help_text='Связанный спутник', null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='satellite_requests', to='mainapp.satellite', verbose_name='Спутник'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='transfer',
|
||||||
|
field=models.FloatField(blank=True, help_text='Перенос по частоте в МГц', null=True, verbose_name='Перенос, МГц'),
|
||||||
|
),
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='uplink',
|
||||||
|
field=models.FloatField(blank=True, help_text='Частота uplink в МГц', null=True, verbose_name='Частота Uplink, МГц'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='coords',
|
||||||
|
field=django.contrib.gis.db.models.fields.PointField(blank=True, help_text='Координаты ГСО (WGS84)', null=True, srid=4326, verbose_name='Координаты ГСО'),
|
||||||
|
),
|
||||||
|
migrations.AlterField(
|
||||||
|
model_name='sourcerequest',
|
||||||
|
name='source',
|
||||||
|
field=models.ForeignKey(blank=True, help_text='Связанный источник', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='source_requests', to='mainapp.source', verbose_name='Источник'),
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -1216,15 +1216,28 @@ class SourceRequest(models.Model):
|
|||||||
('high', 'Высокий'),
|
('high', 'Высокий'),
|
||||||
]
|
]
|
||||||
|
|
||||||
# Связь с источником
|
# Связь с источником (опционально для заявок без привязки)
|
||||||
source = models.ForeignKey(
|
source = models.ForeignKey(
|
||||||
Source,
|
Source,
|
||||||
on_delete=models.CASCADE,
|
on_delete=models.CASCADE,
|
||||||
related_name='source_requests',
|
related_name='source_requests',
|
||||||
verbose_name='Источник',
|
verbose_name='Источник',
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
help_text='Связанный источник',
|
help_text='Связанный источник',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Связь со спутником
|
||||||
|
satellite = models.ForeignKey(
|
||||||
|
Satellite,
|
||||||
|
on_delete=models.SET_NULL,
|
||||||
|
related_name='satellite_requests',
|
||||||
|
verbose_name='Спутник',
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
help_text='Связанный спутник',
|
||||||
|
)
|
||||||
|
|
||||||
# Основные поля
|
# Основные поля
|
||||||
status = models.CharField(
|
status = models.CharField(
|
||||||
max_length=20,
|
max_length=20,
|
||||||
@@ -1256,12 +1269,38 @@ class SourceRequest(models.Model):
|
|||||||
verbose_name='Дата заявки',
|
verbose_name='Дата заявки',
|
||||||
help_text='Дата подачи заявки',
|
help_text='Дата подачи заявки',
|
||||||
)
|
)
|
||||||
|
card_date = models.DateField(
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Дата формирования карточки',
|
||||||
|
help_text='Дата формирования карточки',
|
||||||
|
)
|
||||||
status_updated_at = models.DateTimeField(
|
status_updated_at = models.DateTimeField(
|
||||||
auto_now=True,
|
auto_now=True,
|
||||||
verbose_name='Дата обновления статуса',
|
verbose_name='Дата обновления статуса',
|
||||||
help_text='Дата и время последнего обновления статуса',
|
help_text='Дата и время последнего обновления статуса',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Частоты и перенос
|
||||||
|
downlink = models.FloatField(
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Частота Downlink, МГц',
|
||||||
|
help_text='Частота downlink в МГц',
|
||||||
|
)
|
||||||
|
uplink = models.FloatField(
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Частота Uplink, МГц',
|
||||||
|
help_text='Частота uplink в МГц',
|
||||||
|
)
|
||||||
|
transfer = models.FloatField(
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Перенос, МГц',
|
||||||
|
help_text='Перенос по частоте в МГц',
|
||||||
|
)
|
||||||
|
|
||||||
# Результаты
|
# Результаты
|
||||||
gso_success = models.BooleanField(
|
gso_success = models.BooleanField(
|
||||||
null=True,
|
null=True,
|
||||||
@@ -1276,6 +1315,15 @@ class SourceRequest(models.Model):
|
|||||||
help_text='Успешность Кубсат',
|
help_text='Успешность Кубсат',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Район
|
||||||
|
region = models.CharField(
|
||||||
|
max_length=255,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Район',
|
||||||
|
help_text='Район/местоположение',
|
||||||
|
)
|
||||||
|
|
||||||
# Комментарий
|
# Комментарий
|
||||||
comment = models.TextField(
|
comment = models.TextField(
|
||||||
null=True,
|
null=True,
|
||||||
@@ -1284,13 +1332,22 @@ class SourceRequest(models.Model):
|
|||||||
help_text='Дополнительные комментарии к заявке',
|
help_text='Дополнительные комментарии к заявке',
|
||||||
)
|
)
|
||||||
|
|
||||||
# Координаты (усреднённые по выбранным точкам)
|
# Координаты ГСО (усреднённые по выбранным точкам)
|
||||||
coords = gis.PointField(
|
coords = gis.PointField(
|
||||||
srid=4326,
|
srid=4326,
|
||||||
null=True,
|
null=True,
|
||||||
blank=True,
|
blank=True,
|
||||||
verbose_name='Координаты',
|
verbose_name='Координаты ГСО',
|
||||||
help_text='Усреднённые координаты по выбранным точкам (WGS84)',
|
help_text='Координаты ГСО (WGS84)',
|
||||||
|
)
|
||||||
|
|
||||||
|
# Координаты источника
|
||||||
|
coords_source = gis.PointField(
|
||||||
|
srid=4326,
|
||||||
|
null=True,
|
||||||
|
blank=True,
|
||||||
|
verbose_name='Координаты источника',
|
||||||
|
help_text='Координаты источника (WGS84)',
|
||||||
)
|
)
|
||||||
|
|
||||||
# Количество точек, использованных для расчёта координат
|
# Количество точек, использованных для расчёта координат
|
||||||
|
|||||||
@@ -1,10 +1,37 @@
|
|||||||
|
{% load static %}
|
||||||
<!-- Вкладка заявок на источники -->
|
<!-- Вкладка заявок на источники -->
|
||||||
|
<link href="{% static 'tabulator/css/tabulator_bootstrap5.min.css' %}" rel="stylesheet">
|
||||||
|
<style>
|
||||||
|
#requestsTable .tabulator-header .tabulator-col {
|
||||||
|
padding: 8px 6px !important;
|
||||||
|
font-size: 12px !important;
|
||||||
|
}
|
||||||
|
#requestsTable .tabulator-cell {
|
||||||
|
padding: 6px 8px !important;
|
||||||
|
font-size: 12px !important;
|
||||||
|
}
|
||||||
|
#requestsTable .tabulator-row {
|
||||||
|
min-height: 36px !important;
|
||||||
|
}
|
||||||
|
#requestsTable .tabulator-footer {
|
||||||
|
font-size: 12px !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
|
||||||
<div class="card mb-3">
|
<div class="card mb-3">
|
||||||
<div class="card-header d-flex justify-content-between align-items-center">
|
<div class="card-header d-flex justify-content-between align-items-center">
|
||||||
<h5 class="mb-0"><i class="bi bi-list-task"></i> Заявки на источники</h5>
|
<h5 class="mb-0"><i class="bi bi-list-task"></i> Заявки на источники</h5>
|
||||||
<button type="button" class="btn btn-success btn-sm" onclick="openCreateRequestModal()">
|
<div>
|
||||||
<i class="bi bi-plus-circle"></i> Создать заявку
|
<button type="button" class="btn btn-outline-danger btn-sm me-2" id="bulkDeleteBtn" onclick="bulkDeleteRequests()">
|
||||||
</button>
|
<i class="bi bi-trash"></i> Удалить
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-outline-success btn-sm me-2" onclick="exportRequests()">
|
||||||
|
<i class="bi bi-file-earmark-excel"></i> Экспорт
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-success btn-sm" onclick="openCreateRequestModal()">
|
||||||
|
<i class="bi bi-plus-circle"></i> Создать
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<!-- Фильтры заявок -->
|
<!-- Фильтры заявок -->
|
||||||
@@ -41,198 +68,288 @@
|
|||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<!-- Клиентский поиск по имени точки -->
|
<!-- Клиентский поиск -->
|
||||||
<div class="row mb-3">
|
<div class="row mb-3">
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<div class="input-group input-group-sm">
|
<div class="input-group input-group-sm">
|
||||||
<input type="text" id="searchRequestObjitemName" class="form-control"
|
<input type="text" id="searchRequestInput" class="form-control"
|
||||||
placeholder="Поиск по имени точки..."
|
placeholder="Поиск по спутнику, частоте...">
|
||||||
oninput="filterRequestsByName()">
|
|
||||||
<button type="button" class="btn btn-outline-secondary" onclick="clearRequestSearch()">
|
<button type="button" class="btn btn-outline-secondary" onclick="clearRequestSearch()">
|
||||||
<i class="bi bi-x-lg"></i>
|
<i class="bi bi-x-lg"></i>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-8">
|
|
||||||
<span class="text-muted small" id="requestsCounter">
|
|
||||||
Показано заявок: {{ requests|length }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Таблица заявок -->
|
<!-- Таблица заявок (Tabulator с встроенной пагинацией) -->
|
||||||
<div class="table-responsive" style="max-height: 60vh; overflow-y: auto;">
|
<div id="requestsTable"></div>
|
||||||
<table class="table table-striped table-hover table-sm table-bordered" style="font-size: 0.85rem;">
|
|
||||||
<thead class="table-dark sticky-top">
|
|
||||||
<tr>
|
|
||||||
<th style="min-width: 60px;">ID</th>
|
|
||||||
<th style="min-width: 80px;">Источник</th>
|
|
||||||
<th style="min-width: 120px;">Статус</th>
|
|
||||||
<th style="min-width: 80px;">Приоритет</th>
|
|
||||||
<th style="min-width: 150px;">Координаты</th>
|
|
||||||
<th style="min-width: 150px;">Имя точки</th>
|
|
||||||
<th style="min-width: 100px;">Модуляция</th>
|
|
||||||
<th style="min-width: 100px;">Симв. скор.</th>
|
|
||||||
<th style="min-width: 130px;">Дата планирования</th>
|
|
||||||
<th style="min-width: 80px;">ГСО</th>
|
|
||||||
<th style="min-width: 80px;">Кубсат</th>
|
|
||||||
<th style="min-width: 130px;">Обновлено</th>
|
|
||||||
<th style="min-width: 120px;">Действия</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
{% for req in requests %}
|
|
||||||
<tr data-objitem-name="{{ req.objitem_name|default:'' }}">
|
|
||||||
<td>{{ req.id }}</td>
|
|
||||||
<td>
|
|
||||||
<a href="{% url 'mainapp:source_update' req.source_id %}" target="_blank">
|
|
||||||
#{{ req.source_id }}
|
|
||||||
</a>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span class="badge
|
|
||||||
{% if req.status == 'successful' or req.status == 'result_received' %}bg-success
|
|
||||||
{% elif req.status == 'unsuccessful' or req.status == 'no_correlation' or req.status == 'no_signal' %}bg-danger
|
|
||||||
{% elif req.status == 'planned' %}bg-primary
|
|
||||||
{% elif req.status == 'downloading' or req.status == 'processing' %}bg-warning text-dark
|
|
||||||
{% else %}bg-secondary{% endif %}">
|
|
||||||
{{ req.get_status_display }}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<span class="badge
|
|
||||||
{% if req.priority == 'high' %}bg-danger
|
|
||||||
{% elif req.priority == 'medium' %}bg-warning text-dark
|
|
||||||
{% else %}bg-secondary{% endif %}">
|
|
||||||
{{ req.get_priority_display }}
|
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
{% if req.coords %}
|
|
||||||
<small>{{ req.coords.y|floatformat:6 }}, {{ req.coords.x|floatformat:6 }}</small>
|
|
||||||
{% else %}-{% endif %}
|
|
||||||
</td>
|
|
||||||
<td>{{ req.objitem_name|default:"-" }}</td>
|
|
||||||
<td>{{ req.modulation|default:"-" }}</td>
|
|
||||||
<td>{{ req.symbol_rate|default:"-" }}</td>
|
|
||||||
<td>{{ req.planned_at|date:"d.m.Y H:i"|default:"-" }}</td>
|
|
||||||
<td class="text-center">
|
|
||||||
{% if req.gso_success is True %}
|
|
||||||
<span class="badge bg-success">Да</span>
|
|
||||||
{% elif req.gso_success is False %}
|
|
||||||
<span class="badge bg-danger">Нет</span>
|
|
||||||
{% else %}-{% endif %}
|
|
||||||
</td>
|
|
||||||
<td class="text-center">
|
|
||||||
{% if req.kubsat_success is True %}
|
|
||||||
<span class="badge bg-success">Да</span>
|
|
||||||
{% elif req.kubsat_success is False %}
|
|
||||||
<span class="badge bg-danger">Нет</span>
|
|
||||||
{% else %}-{% endif %}
|
|
||||||
</td>
|
|
||||||
<td>{{ req.status_updated_at|date:"d.m.Y H:i"|default:"-" }}</td>
|
|
||||||
<td>
|
|
||||||
<div class="btn-group btn-group-sm" role="group">
|
|
||||||
<button type="button" class="btn btn-outline-info" onclick="showHistory({{ req.id }})" title="История">
|
|
||||||
<i class="bi bi-clock-history"></i>
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-outline-warning" onclick="openEditRequestModal({{ req.id }})" title="Редактировать">
|
|
||||||
<i class="bi bi-pencil"></i>
|
|
||||||
</button>
|
|
||||||
<button type="button" class="btn btn-outline-danger" onclick="deleteRequest({{ req.id }})" title="Удалить">
|
|
||||||
<i class="bi bi-trash"></i>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
{% empty %}
|
|
||||||
<tr>
|
|
||||||
<td colspan="13" class="text-center text-muted">Нет заявок</td>
|
|
||||||
</tr>
|
|
||||||
{% endfor %}
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Пагинация -->
|
|
||||||
{% if page_obj %}
|
|
||||||
<nav aria-label="Пагинация" class="mt-3">
|
|
||||||
<ul class="pagination pagination-sm justify-content-center">
|
|
||||||
{% if page_obj.has_previous %}
|
|
||||||
<li class="page-item">
|
|
||||||
<a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if current_priority %}&priority={{ current_priority }}{% endif %}">
|
|
||||||
«
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
{% endif %}
|
|
||||||
|
|
||||||
<li class="page-item disabled">
|
|
||||||
<span class="page-link">{{ page_obj.number }} из {{ page_obj.paginator.num_pages }}</span>
|
|
||||||
</li>
|
|
||||||
|
|
||||||
{% if page_obj.has_next %}
|
|
||||||
<li class="page-item">
|
|
||||||
<a class="page-link" href="?page={{ page_obj.next_page_number }}{% if current_status %}&status={{ current_status }}{% endif %}{% if current_priority %}&priority={{ current_priority }}{% endif %}">
|
|
||||||
»
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
{% endif %}
|
|
||||||
</ul>
|
|
||||||
</nav>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<script src="{% static 'tabulator/js/tabulator.min.js' %}"></script>
|
||||||
<script>
|
<script>
|
||||||
// Фильтрация таблицы заявок по имени точки
|
// Данные заявок из Django (через JSON)
|
||||||
function filterRequestsByName() {
|
const requestsData = JSON.parse('{{ requests_json|escapejs }}');
|
||||||
const searchValue = document.getElementById('searchRequestObjitemName').value.toLowerCase().trim();
|
|
||||||
const tbody = document.querySelector('.table tbody');
|
|
||||||
const rows = tbody.querySelectorAll('tr');
|
|
||||||
|
|
||||||
let visibleCount = 0;
|
// Форматтер для статуса
|
||||||
|
function statusFormatter(cell) {
|
||||||
|
const status = cell.getValue();
|
||||||
|
const display = cell.getData().status_display;
|
||||||
|
let badgeClass = 'bg-secondary';
|
||||||
|
|
||||||
rows.forEach(row => {
|
if (status === 'successful' || status === 'result_received') {
|
||||||
// Пропускаем строку "Нет заявок"
|
badgeClass = 'bg-success';
|
||||||
if (row.querySelector('td[colspan]')) {
|
} else if (status === 'unsuccessful' || status === 'no_correlation' || status === 'no_signal') {
|
||||||
return;
|
badgeClass = 'bg-danger';
|
||||||
}
|
} else if (status === 'planned') {
|
||||||
|
badgeClass = 'bg-primary';
|
||||||
|
} else if (status === 'downloading' || status === 'processing') {
|
||||||
|
badgeClass = 'bg-warning text-dark';
|
||||||
|
}
|
||||||
|
|
||||||
const objitemName = (row.dataset.objitemName || '').toLowerCase();
|
return `<span class="badge ${badgeClass}">${display}</span>`;
|
||||||
|
|
||||||
if (!searchValue || objitemName.includes(searchValue)) {
|
|
||||||
row.style.display = '';
|
|
||||||
visibleCount++;
|
|
||||||
} else {
|
|
||||||
row.style.display = 'none';
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
updateRequestsCounter(visibleCount);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Обновление счётчика заявок
|
// Форматтер для булевых значений (ГСО/Кубсат)
|
||||||
function updateRequestsCounter(count) {
|
function boolFormatter(cell) {
|
||||||
const counter = document.getElementById('requestsCounter');
|
const val = cell.getValue();
|
||||||
if (counter) {
|
if (val === true) {
|
||||||
counter.textContent = `Показано заявок: ${count}`;
|
return '<span class="badge bg-success">Да</span>';
|
||||||
|
} else if (val === false) {
|
||||||
|
return '<span class="badge bg-danger">Нет</span>';
|
||||||
}
|
}
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Форматтер для координат (4 знака после запятой)
|
||||||
|
function coordsFormatter(cell) {
|
||||||
|
const data = cell.getData();
|
||||||
|
const field = cell.getField();
|
||||||
|
let lat, lon;
|
||||||
|
|
||||||
|
if (field === 'coords_lat') {
|
||||||
|
lat = data.coords_lat;
|
||||||
|
lon = data.coords_lon;
|
||||||
|
} else {
|
||||||
|
lat = data.coords_source_lat;
|
||||||
|
lon = data.coords_source_lon;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lat !== null && lon !== null) {
|
||||||
|
return `${lat.toFixed(4)}, ${lon.toFixed(4)}`;
|
||||||
|
}
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Форматтер для числовых значений
|
||||||
|
function numberFormatter(cell, decimals) {
|
||||||
|
const val = cell.getValue();
|
||||||
|
if (val !== null && val !== undefined) {
|
||||||
|
return val.toFixed(decimals);
|
||||||
|
}
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Форматтер для источника
|
||||||
|
function sourceFormatter(cell) {
|
||||||
|
const sourceId = cell.getValue();
|
||||||
|
if (sourceId) {
|
||||||
|
return `<a href="/source/${sourceId}/edit/" target="_blank">#${sourceId}</a>`;
|
||||||
|
}
|
||||||
|
return '-';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Форматтер для приоритета
|
||||||
|
function priorityFormatter(cell) {
|
||||||
|
const priority = cell.getValue();
|
||||||
|
const display = cell.getData().priority_display;
|
||||||
|
let badgeClass = 'bg-secondary';
|
||||||
|
|
||||||
|
if (priority === 'high') {
|
||||||
|
badgeClass = 'bg-danger';
|
||||||
|
} else if (priority === 'medium') {
|
||||||
|
badgeClass = 'bg-warning text-dark';
|
||||||
|
} else if (priority === 'low') {
|
||||||
|
badgeClass = 'bg-info';
|
||||||
|
}
|
||||||
|
|
||||||
|
return `<span class="badge ${badgeClass}">${display}</span>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Форматтер для комментария
|
||||||
|
function commentFormatter(cell) {
|
||||||
|
const val = cell.getValue();
|
||||||
|
if (!val) return '-';
|
||||||
|
|
||||||
|
// Обрезаем длинный текст и добавляем tooltip
|
||||||
|
const maxLength = 50;
|
||||||
|
if (val.length > maxLength) {
|
||||||
|
const truncated = val.substring(0, maxLength) + '...';
|
||||||
|
return `<span title="${val.replace(/"/g, '"')}">${truncated}</span>`;
|
||||||
|
}
|
||||||
|
return val;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Форматтер для действий
|
||||||
|
function actionsFormatter(cell) {
|
||||||
|
const id = cell.getData().id;
|
||||||
|
return `
|
||||||
|
<div class="btn-group btn-group-sm" role="group">
|
||||||
|
<button type="button" class="btn btn-outline-info btn-sm" onclick="showHistory(${id})" title="История">
|
||||||
|
<i class="bi bi-clock-history"></i>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-outline-warning btn-sm" onclick="openEditRequestModal(${id})" title="Редактировать">
|
||||||
|
<i class="bi bi-pencil"></i>
|
||||||
|
</button>
|
||||||
|
<button type="button" class="btn btn-outline-danger btn-sm" onclick="deleteRequest(${id})" title="Удалить">
|
||||||
|
<i class="bi bi-trash"></i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Инициализация Tabulator
|
||||||
|
const requestsTable = new Tabulator("#requestsTable", {
|
||||||
|
data: requestsData,
|
||||||
|
layout: "fitColumns",
|
||||||
|
height: "65vh",
|
||||||
|
placeholder: "Нет заявок",
|
||||||
|
selectable: true,
|
||||||
|
selectableRangeMode: "click",
|
||||||
|
pagination: true,
|
||||||
|
paginationSize: 50,
|
||||||
|
paginationSizeSelector: [25, 50, 100, 200],
|
||||||
|
paginationCounter: "rows",
|
||||||
|
columns: [
|
||||||
|
{
|
||||||
|
formatter: "rowSelection",
|
||||||
|
titleFormatter: "rowSelection",
|
||||||
|
hozAlign: "center",
|
||||||
|
headerSort: false,
|
||||||
|
width: 50,
|
||||||
|
cellClick: function(e, cell) {
|
||||||
|
cell.getRow().toggleSelect();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{title: "ID", field: "id", width: 50, hozAlign: "center"},
|
||||||
|
{title: "Ист.", field: "source_id", width: 55, formatter: sourceFormatter},
|
||||||
|
{title: "Спутник", field: "satellite_name", width: 100},
|
||||||
|
{title: "Статус", field: "status", width: 105, formatter: statusFormatter},
|
||||||
|
{title: "Приоритет", field: "priority", width: 85, formatter: priorityFormatter},
|
||||||
|
{title: "Заявка", field: "request_date", width: 85},
|
||||||
|
{title: "Карточка", field: "card_date", width: 85},
|
||||||
|
{title: "Планирование", field: "planned_at", width: 120},
|
||||||
|
{title: "Down", field: "downlink", width: 65, hozAlign: "right", formatter: function(cell) { return numberFormatter(cell, 2); }},
|
||||||
|
{title: "Up", field: "uplink", width: 65, hozAlign: "right", formatter: function(cell) { return numberFormatter(cell, 2); }},
|
||||||
|
{title: "Пер.", field: "transfer", width: 50, hozAlign: "right", formatter: function(cell) { return numberFormatter(cell, 0); }},
|
||||||
|
{title: "Коорд. ГСО", field: "coords_lat", width: 110, formatter: coordsFormatter},
|
||||||
|
{title: "Район", field: "region", width: 80, formatter: function(cell) {
|
||||||
|
const val = cell.getValue();
|
||||||
|
return val ? val.substring(0, 12) + (val.length > 12 ? '...' : '') : '-';
|
||||||
|
}},
|
||||||
|
{title: "ГСО", field: "gso_success", width: 50, hozAlign: "center", formatter: boolFormatter},
|
||||||
|
{title: "Куб", field: "kubsat_success", width: 50, hozAlign: "center", formatter: boolFormatter},
|
||||||
|
{title: "Коорд. ист.", field: "coords_source_lat", width: 110, formatter: coordsFormatter},
|
||||||
|
{title: "Комментарий", field: "comment", width: 180, formatter: commentFormatter},
|
||||||
|
{title: "Действия", field: "id", width: 105, formatter: actionsFormatter, headerSort: false},
|
||||||
|
],
|
||||||
|
rowSelectionChanged: function(data, rows) {
|
||||||
|
updateSelectedCount();
|
||||||
|
},
|
||||||
|
dataFiltered: function(filters, rows) {
|
||||||
|
updateRequestsCounter();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Поиск по таблице
|
||||||
|
document.getElementById('searchRequestInput').addEventListener('input', function() {
|
||||||
|
const searchValue = this.value.toLowerCase().trim();
|
||||||
|
if (searchValue) {
|
||||||
|
requestsTable.setFilter(function(data) {
|
||||||
|
// Поиск по спутнику
|
||||||
|
const satelliteMatch = data.satellite_name && data.satellite_name.toLowerCase().includes(searchValue);
|
||||||
|
|
||||||
|
// Поиск по частотам (downlink, uplink, transfer)
|
||||||
|
const downlinkMatch = data.downlink && data.downlink.toString().includes(searchValue);
|
||||||
|
const uplinkMatch = data.uplink && data.uplink.toString().includes(searchValue);
|
||||||
|
const transferMatch = data.transfer && data.transfer.toString().includes(searchValue);
|
||||||
|
|
||||||
|
// Поиск по району
|
||||||
|
const regionMatch = data.region && data.region.toLowerCase().includes(searchValue);
|
||||||
|
|
||||||
|
return satelliteMatch || downlinkMatch || uplinkMatch || transferMatch || regionMatch;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
requestsTable.clearFilter();
|
||||||
|
}
|
||||||
|
updateRequestsCounter();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Обновление счётчика заявок (пустая функция для совместимости)
|
||||||
|
function updateRequestsCounter() {
|
||||||
|
// Функция оставлена для совместимости, но ничего не делает
|
||||||
}
|
}
|
||||||
|
|
||||||
// Очистка поиска
|
// Очистка поиска
|
||||||
function clearRequestSearch() {
|
function clearRequestSearch() {
|
||||||
document.getElementById('searchRequestObjitemName').value = '';
|
document.getElementById('searchRequestInput').value = '';
|
||||||
filterRequestsByName();
|
requestsTable.clearFilter();
|
||||||
|
updateRequestsCounter();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Обновление счётчика выбранных (пустая функция для совместимости)
|
||||||
|
function updateSelectedCount() {
|
||||||
|
// Функция оставлена для совместимости, но ничего не делает
|
||||||
|
}
|
||||||
|
|
||||||
|
// Массовое удаление заявок
|
||||||
|
async function bulkDeleteRequests() {
|
||||||
|
const selectedRows = requestsTable.getSelectedRows();
|
||||||
|
const ids = selectedRows.map(row => row.getData().id);
|
||||||
|
|
||||||
|
if (ids.length === 0) {
|
||||||
|
alert('Не выбраны заявки для удаления');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!confirm(`Вы уверены, что хотите удалить ${ids.length} заявок?`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('{% url "mainapp:source_request_bulk_delete" %}', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-CSRFToken': '{{ csrf_token }}',
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ ids: ids })
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
alert(data.message);
|
||||||
|
location.reload();
|
||||||
|
} else {
|
||||||
|
alert('Ошибка: ' + (data.error || 'Неизвестная ошибка'));
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
alert('Ошибка: ' + error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Экспорт заявок в Excel
|
||||||
|
function exportRequests() {
|
||||||
|
// Получаем текущие параметры фильтрации
|
||||||
|
const urlParams = new URLSearchParams(window.location.search);
|
||||||
|
const exportUrl = '{% url "mainapp:source_request_export" %}?' + urlParams.toString();
|
||||||
|
window.location.href = exportUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Инициализация счётчика при загрузке
|
// Инициализация счётчика при загрузке
|
||||||
document.addEventListener('DOMContentLoaded', function() {
|
document.addEventListener('DOMContentLoaded', function() {
|
||||||
const tbody = document.querySelector('.table tbody');
|
updateRequestsCounter();
|
||||||
if (tbody) {
|
|
||||||
const rows = tbody.querySelectorAll('tr:not([style*="display: none"])');
|
|
||||||
// Исключаем строку "Нет заявок"
|
|
||||||
const visibleRows = Array.from(rows).filter(row => !row.querySelector('td[colspan]'));
|
|
||||||
updateRequestsCounter(visibleRows.length);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -57,19 +57,28 @@
|
|||||||
|
|
||||||
<!-- Источник и статус -->
|
<!-- Источник и статус -->
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-md-4 mb-3">
|
<div class="col-md-3 mb-3">
|
||||||
<label for="requestSource" class="form-label">Источник (ID) *</label>
|
<label for="requestSource" class="form-label">Источник (ID)</label>
|
||||||
<div class="input-group">
|
<div class="input-group">
|
||||||
<span class="input-group-text">#</span>
|
<span class="input-group-text">#</span>
|
||||||
<input type="number" class="form-control" id="requestSourceId" name="source"
|
<input type="number" class="form-control" id="requestSourceId" name="source"
|
||||||
placeholder="Введите ID источника" required min="1" onchange="loadSourceData()">
|
placeholder="ID источника" min="1" onchange="loadSourceData()">
|
||||||
<button type="button" class="btn btn-outline-secondary" onclick="loadSourceData()">
|
<button type="button" class="btn btn-outline-secondary" onclick="loadSourceData()">
|
||||||
<i class="bi bi-search"></i>
|
<i class="bi bi-search"></i>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="sourceCheckResult" class="form-text"></div>
|
<div id="sourceCheckResult" class="form-text"></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4 mb-3">
|
<div class="col-md-3 mb-3">
|
||||||
|
<label for="requestSatellite" class="form-label">Спутник</label>
|
||||||
|
<select class="form-select" id="requestSatellite" name="satellite">
|
||||||
|
<option value="">-</option>
|
||||||
|
{% for sat in satellites %}
|
||||||
|
<option value="{{ sat.id }}">{{ sat.name }}</option>
|
||||||
|
{% endfor %}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3 mb-3">
|
||||||
<label for="requestStatus" class="form-label">Статус</label>
|
<label for="requestStatus" class="form-label">Статус</label>
|
||||||
<select class="form-select" id="requestStatus" name="status">
|
<select class="form-select" id="requestStatus" name="status">
|
||||||
<option value="planned">Запланировано</option>
|
<option value="planned">Запланировано</option>
|
||||||
@@ -83,7 +92,7 @@
|
|||||||
<option value="result_received">Результат получен</option>
|
<option value="result_received">Результат получен</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4 mb-3">
|
<div class="col-md-3 mb-3">
|
||||||
<label for="requestPriority" class="form-label">Приоритет</label>
|
<label for="requestPriority" class="form-label">Приоритет</label>
|
||||||
<select class="form-select" id="requestPriority" name="priority">
|
<select class="form-select" id="requestPriority" name="priority">
|
||||||
<option value="low">Низкий</option>
|
<option value="low">Низкий</option>
|
||||||
@@ -93,6 +102,30 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Частоты и перенос -->
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-3 mb-3">
|
||||||
|
<label for="requestDownlink" class="form-label">Downlink (МГц)</label>
|
||||||
|
<input type="number" step="0.01" class="form-control" id="requestDownlink" name="downlink"
|
||||||
|
placeholder="Частота downlink">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3 mb-3">
|
||||||
|
<label for="requestUplink" class="form-label">Uplink (МГц)</label>
|
||||||
|
<input type="number" step="0.01" class="form-control" id="requestUplink" name="uplink"
|
||||||
|
placeholder="Частота uplink">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3 mb-3">
|
||||||
|
<label for="requestTransfer" class="form-label">Перенос (МГц)</label>
|
||||||
|
<input type="number" step="0.01" class="form-control" id="requestTransfer" name="transfer"
|
||||||
|
placeholder="Перенос">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3 mb-3">
|
||||||
|
<label for="requestRegion" class="form-label">Район</label>
|
||||||
|
<input type="text" class="form-control" id="requestRegion" name="region"
|
||||||
|
placeholder="Район/местоположение">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<!-- Данные источника (только для чтения) -->
|
<!-- Данные источника (только для чтения) -->
|
||||||
<div class="card bg-light mb-3" id="sourceDataCard" style="display: none;">
|
<div class="card bg-light mb-3" id="sourceDataCard" style="display: none;">
|
||||||
<div class="card-header py-2">
|
<div class="card-header py-2">
|
||||||
@@ -116,34 +149,44 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Координаты -->
|
<!-- Координаты ГСО -->
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-md-4 mb-3">
|
<div class="col-md-3 mb-3">
|
||||||
<label for="requestCoordsLat" class="form-label">Широта</label>
|
<label for="requestCoordsLat" class="form-label">Широта ГСО</label>
|
||||||
<input type="number" step="0.000001" class="form-control" id="requestCoordsLat" name="coords_lat"
|
<input type="number" step="0.000001" class="form-control" id="requestCoordsLat" name="coords_lat"
|
||||||
placeholder="Например: 55.751244">
|
placeholder="Например: 55.751244">
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4 mb-3">
|
<div class="col-md-3 mb-3">
|
||||||
<label for="requestCoordsLon" class="form-label">Долгота</label>
|
<label for="requestCoordsLon" class="form-label">Долгота ГСО</label>
|
||||||
<input type="number" step="0.000001" class="form-control" id="requestCoordsLon" name="coords_lon"
|
<input type="number" step="0.000001" class="form-control" id="requestCoordsLon" name="coords_lon"
|
||||||
placeholder="Например: 37.618423">
|
placeholder="Например: 37.618423">
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4 mb-3">
|
<div class="col-md-3 mb-3">
|
||||||
<label class="form-label">Кол-во точек</label>
|
<label for="requestCoordsSourceLat" class="form-label">Широта источника</label>
|
||||||
<input type="text" class="form-control" id="requestPointsCount" readonly value="-">
|
<input type="number" step="0.000001" class="form-control" id="requestCoordsSourceLat" name="coords_source_lat"
|
||||||
|
placeholder="Например: 55.751244">
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3 mb-3">
|
||||||
|
<label for="requestCoordsSourceLon" class="form-label">Долгота источника</label>
|
||||||
|
<input type="number" step="0.000001" class="form-control" id="requestCoordsSourceLon" name="coords_source_lon"
|
||||||
|
placeholder="Например: 37.618423">
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Даты -->
|
<!-- Даты -->
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-md-6 mb-3">
|
<div class="col-md-4 mb-3">
|
||||||
<label for="requestPlannedAt" class="form-label">Дата и время планирования</label>
|
<label for="requestPlannedAt" class="form-label">Дата и время планирования</label>
|
||||||
<input type="datetime-local" class="form-control" id="requestPlannedAt" name="planned_at">
|
<input type="datetime-local" class="form-control" id="requestPlannedAt" name="planned_at">
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-6 mb-3">
|
<div class="col-md-4 mb-3">
|
||||||
<label for="requestDate" class="form-label">Дата заявки</label>
|
<label for="requestDate" class="form-label">Дата заявки</label>
|
||||||
<input type="date" class="form-control" id="requestDate" name="request_date">
|
<input type="date" class="form-control" id="requestDate" name="request_date">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="col-md-4 mb-3">
|
||||||
|
<label for="requestCardDate" class="form-label">Дата формирования карточки</label>
|
||||||
|
<input type="date" class="form-control" id="requestCardDate" name="card_date">
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Результаты -->
|
<!-- Результаты -->
|
||||||
@@ -233,9 +276,8 @@ function loadSourceData() {
|
|||||||
document.getElementById('requestObjitemName').value = data.objitem_name || '-';
|
document.getElementById('requestObjitemName').value = data.objitem_name || '-';
|
||||||
document.getElementById('requestModulation').value = data.modulation || '-';
|
document.getElementById('requestModulation').value = data.modulation || '-';
|
||||||
document.getElementById('requestSymbolRate').value = data.symbol_rate || '-';
|
document.getElementById('requestSymbolRate').value = data.symbol_rate || '-';
|
||||||
document.getElementById('requestPointsCount').value = data.points_count || '0';
|
|
||||||
|
|
||||||
// Заполняем координаты (редактируемые)
|
// Заполняем координаты ГСО (редактируемые)
|
||||||
if (data.coords_lat !== null) {
|
if (data.coords_lat !== null) {
|
||||||
document.getElementById('requestCoordsLat').value = data.coords_lat.toFixed(6);
|
document.getElementById('requestCoordsLat').value = data.coords_lat.toFixed(6);
|
||||||
}
|
}
|
||||||
@@ -243,6 +285,20 @@ function loadSourceData() {
|
|||||||
document.getElementById('requestCoordsLon').value = data.coords_lon.toFixed(6);
|
document.getElementById('requestCoordsLon').value = data.coords_lon.toFixed(6);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Заполняем данные из транспондера
|
||||||
|
if (data.downlink) {
|
||||||
|
document.getElementById('requestDownlink').value = data.downlink;
|
||||||
|
}
|
||||||
|
if (data.uplink) {
|
||||||
|
document.getElementById('requestUplink').value = data.uplink;
|
||||||
|
}
|
||||||
|
if (data.transfer) {
|
||||||
|
document.getElementById('requestTransfer').value = data.transfer;
|
||||||
|
}
|
||||||
|
if (data.satellite_id) {
|
||||||
|
document.getElementById('requestSatellite').value = data.satellite_id;
|
||||||
|
}
|
||||||
|
|
||||||
sourceDataCard.style.display = 'block';
|
sourceDataCard.style.display = 'block';
|
||||||
} else {
|
} else {
|
||||||
resultDiv.innerHTML = `<span class="text-danger"><i class="bi bi-x-circle"></i> Источник #${sourceId} не найден</span>`;
|
resultDiv.innerHTML = `<span class="text-danger"><i class="bi bi-x-circle"></i> Источник #${sourceId} не найден</span>`;
|
||||||
@@ -264,7 +320,14 @@ function clearSourceData() {
|
|||||||
document.getElementById('requestSymbolRate').value = '';
|
document.getElementById('requestSymbolRate').value = '';
|
||||||
document.getElementById('requestCoordsLat').value = '';
|
document.getElementById('requestCoordsLat').value = '';
|
||||||
document.getElementById('requestCoordsLon').value = '';
|
document.getElementById('requestCoordsLon').value = '';
|
||||||
document.getElementById('requestPointsCount').value = '-';
|
document.getElementById('requestCoordsSourceLat').value = '';
|
||||||
|
document.getElementById('requestCoordsSourceLon').value = '';
|
||||||
|
document.getElementById('requestDownlink').value = '';
|
||||||
|
document.getElementById('requestUplink').value = '';
|
||||||
|
document.getElementById('requestTransfer').value = '';
|
||||||
|
document.getElementById('requestRegion').value = '';
|
||||||
|
document.getElementById('requestSatellite').value = '';
|
||||||
|
document.getElementById('requestCardDate').value = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
// Открытие модального окна создания заявки
|
// Открытие модального окна создания заявки
|
||||||
@@ -294,11 +357,13 @@ function openEditRequestModal(requestId) {
|
|||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
document.getElementById('requestId').value = data.id;
|
document.getElementById('requestId').value = data.id;
|
||||||
document.getElementById('requestSourceId').value = data.source_id;
|
document.getElementById('requestSourceId').value = data.source_id || '';
|
||||||
|
document.getElementById('requestSatellite').value = data.satellite_id || '';
|
||||||
document.getElementById('requestStatus').value = data.status;
|
document.getElementById('requestStatus').value = data.status;
|
||||||
document.getElementById('requestPriority').value = data.priority;
|
document.getElementById('requestPriority').value = data.priority;
|
||||||
document.getElementById('requestPlannedAt').value = data.planned_at || '';
|
document.getElementById('requestPlannedAt').value = data.planned_at || '';
|
||||||
document.getElementById('requestDate').value = data.request_date || '';
|
document.getElementById('requestDate').value = data.request_date || '';
|
||||||
|
document.getElementById('requestCardDate').value = data.card_date || '';
|
||||||
document.getElementById('requestGsoSuccess').value = data.gso_success === null ? '' : data.gso_success.toString();
|
document.getElementById('requestGsoSuccess').value = data.gso_success === null ? '' : data.gso_success.toString();
|
||||||
document.getElementById('requestKubsatSuccess').value = data.kubsat_success === null ? '' : data.kubsat_success.toString();
|
document.getElementById('requestKubsatSuccess').value = data.kubsat_success === null ? '' : data.kubsat_success.toString();
|
||||||
document.getElementById('requestComment').value = data.comment || '';
|
document.getElementById('requestComment').value = data.comment || '';
|
||||||
@@ -307,9 +372,14 @@ function openEditRequestModal(requestId) {
|
|||||||
document.getElementById('requestObjitemName').value = data.objitem_name || '-';
|
document.getElementById('requestObjitemName').value = data.objitem_name || '-';
|
||||||
document.getElementById('requestModulation').value = data.modulation || '-';
|
document.getElementById('requestModulation').value = data.modulation || '-';
|
||||||
document.getElementById('requestSymbolRate').value = data.symbol_rate || '-';
|
document.getElementById('requestSymbolRate').value = data.symbol_rate || '-';
|
||||||
document.getElementById('requestPointsCount').value = data.points_count || '0';
|
|
||||||
|
|
||||||
// Заполняем координаты
|
// Заполняем частоты
|
||||||
|
document.getElementById('requestDownlink').value = data.downlink || '';
|
||||||
|
document.getElementById('requestUplink').value = data.uplink || '';
|
||||||
|
document.getElementById('requestTransfer').value = data.transfer || '';
|
||||||
|
document.getElementById('requestRegion').value = data.region || '';
|
||||||
|
|
||||||
|
// Заполняем координаты ГСО
|
||||||
if (data.coords_lat !== null) {
|
if (data.coords_lat !== null) {
|
||||||
document.getElementById('requestCoordsLat').value = data.coords_lat.toFixed(6);
|
document.getElementById('requestCoordsLat').value = data.coords_lat.toFixed(6);
|
||||||
} else {
|
} else {
|
||||||
@@ -321,7 +391,19 @@ function openEditRequestModal(requestId) {
|
|||||||
document.getElementById('requestCoordsLon').value = '';
|
document.getElementById('requestCoordsLon').value = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('sourceDataCard').style.display = 'block';
|
// Заполняем координаты источника
|
||||||
|
if (data.coords_source_lat !== null) {
|
||||||
|
document.getElementById('requestCoordsSourceLat').value = data.coords_source_lat.toFixed(6);
|
||||||
|
} else {
|
||||||
|
document.getElementById('requestCoordsSourceLat').value = '';
|
||||||
|
}
|
||||||
|
if (data.coords_source_lon !== null) {
|
||||||
|
document.getElementById('requestCoordsSourceLon').value = data.coords_source_lon.toFixed(6);
|
||||||
|
} else {
|
||||||
|
document.getElementById('requestCoordsSourceLon').value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('sourceDataCard').style.display = data.source_id ? 'block' : 'none';
|
||||||
|
|
||||||
const modal = new bootstrap.Modal(document.getElementById('requestModal'));
|
const modal = new bootstrap.Modal(document.getElementById('requestModal'));
|
||||||
modal.show();
|
modal.show();
|
||||||
|
|||||||
143
dbapp/mainapp/templates/mainapp/source_request_import.html
Normal file
143
dbapp/mainapp/templates/mainapp/source_request_import.html
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
{% extends 'mainapp/base.html' %}
|
||||||
|
{% load static %}
|
||||||
|
|
||||||
|
{% block title %}Импорт заявок из Excel{% endblock %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
<div class="container-fluid mt-3">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-8 offset-md-2">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">
|
||||||
|
<h5 class="mb-0"><i class="bi bi-file-earmark-excel"></i> Импорт заявок из Excel</h5>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<form id="importForm" enctype="multipart/form-data">
|
||||||
|
{% csrf_token %}
|
||||||
|
<div class="mb-3">
|
||||||
|
<label for="file" class="form-label">Выберите Excel файл (.xlsx)</label>
|
||||||
|
<input type="file" class="form-control" id="file" name="file" accept=".xlsx,.xls" required>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="alert alert-info">
|
||||||
|
<h6>Ожидаемые столбцы в файле:</h6>
|
||||||
|
<ul class="mb-0 small">
|
||||||
|
<li><strong>Дата постановки задачи</strong> → Дата заявки</li>
|
||||||
|
<li><strong>Спутник</strong> → Спутник (ищется по NORAD в скобках, например "NSS 12 (36032)")</li>
|
||||||
|
<li><strong>Дата формирования карточки</strong> → Дата формирования карточки</li>
|
||||||
|
<li><strong>Дата проведения</strong> → Дата и время планирования</li>
|
||||||
|
<li><strong>Частота Downlink</strong> → Частота Downlink</li>
|
||||||
|
<li><strong>Частота Uplink</strong> → Частота Uplink</li>
|
||||||
|
<li><strong>Перенос</strong> → Перенос</li>
|
||||||
|
<li><strong>Координаты ГСО</strong> → Координаты ГСО (формат: "широта. долгота")</li>
|
||||||
|
<li><strong>Район</strong> → Район</li>
|
||||||
|
<li><strong>Результат ГСО</strong> → Если "Успешно", то ГСО успешно = Да, иначе Нет + в комментарий</li>
|
||||||
|
<li><strong>Результат кубсата</strong> → <span class="text-danger">Красная ячейка</span> = Кубсат неуспешно, иначе успешно. Значение добавляется в комментарий</li>
|
||||||
|
<li><strong>Координаты источника</strong> → Координаты источника</li>
|
||||||
|
</ul>
|
||||||
|
<hr>
|
||||||
|
<h6>Логика определения статуса:</h6>
|
||||||
|
<ul class="mb-0 small">
|
||||||
|
<li>Если есть <strong>координаты источника</strong> → статус "Результат получен"</li>
|
||||||
|
<li>Если нет координат источника, но <strong>ГСО успешно</strong> → статус "Успешно"</li>
|
||||||
|
<li>Если нет координат источника и <strong>ГСО неуспешно</strong> → статус "Неуспешно"</li>
|
||||||
|
<li>Иначе → статус "Запланировано"</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="btn btn-primary" id="submitBtn">
|
||||||
|
<i class="bi bi-upload"></i> Загрузить
|
||||||
|
</button>
|
||||||
|
<a href="{% url 'mainapp:kubsat' %}" class="btn btn-secondary">
|
||||||
|
<i class="bi bi-arrow-left"></i> Назад
|
||||||
|
</a>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<!-- Результаты импорта -->
|
||||||
|
<div id="results" class="mt-4" style="display: none;">
|
||||||
|
<h6>Результаты импорта:</h6>
|
||||||
|
<div id="resultsContent"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
document.getElementById('importForm').addEventListener('submit', async function(e) {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
const submitBtn = document.getElementById('submitBtn');
|
||||||
|
const resultsDiv = document.getElementById('results');
|
||||||
|
const resultsContent = document.getElementById('resultsContent');
|
||||||
|
|
||||||
|
submitBtn.disabled = true;
|
||||||
|
submitBtn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Загрузка...';
|
||||||
|
resultsDiv.style.display = 'none';
|
||||||
|
|
||||||
|
const formData = new FormData(this);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('{% url "mainapp:source_request_import" %}', {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
headers: {
|
||||||
|
'X-Requested-With': 'XMLHttpRequest'
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
resultsDiv.style.display = 'block';
|
||||||
|
|
||||||
|
if (data.success) {
|
||||||
|
let html = `
|
||||||
|
<div class="alert alert-success">
|
||||||
|
<strong>Успешно!</strong> Создано заявок: ${data.created}
|
||||||
|
${data.skipped > 0 ? `, пропущено: ${data.skipped}` : ''}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
if (data.headers && data.headers.length > 0) {
|
||||||
|
html += `
|
||||||
|
<div class="alert alert-secondary">
|
||||||
|
<strong>Найденные заголовки:</strong> ${data.headers.join(', ')}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.errors && data.errors.length > 0) {
|
||||||
|
html += `
|
||||||
|
<div class="alert alert-warning">
|
||||||
|
<strong>Ошибки (${data.total_errors}):</strong>
|
||||||
|
<ul class="mb-0 small">
|
||||||
|
${data.errors.map(e => `<li>${e}</li>`).join('')}
|
||||||
|
</ul>
|
||||||
|
${data.total_errors > 20 ? '<p class="mb-0 mt-2"><em>Показаны первые 20 ошибок</em></p>' : ''}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
resultsContent.innerHTML = html;
|
||||||
|
} else {
|
||||||
|
resultsContent.innerHTML = `
|
||||||
|
<div class="alert alert-danger">
|
||||||
|
<strong>Ошибка:</strong> ${data.error}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
resultsDiv.style.display = 'block';
|
||||||
|
resultsContent.innerHTML = `
|
||||||
|
<div class="alert alert-danger">
|
||||||
|
<strong>Ошибка:</strong> ${error.message}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
} finally {
|
||||||
|
submitBtn.disabled = false;
|
||||||
|
submitBtn.innerHTML = '<i class="bi bi-upload"></i> Загрузить';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
{% endblock %}
|
||||||
@@ -138,7 +138,17 @@
|
|||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
<div class="alert alert-info">
|
<div class="alert alert-info">
|
||||||
<i class="bi bi-info-circle"></i>
|
<i class="bi bi-info-circle"></i>
|
||||||
Будут обновлены только точки с отсутствующими данными (модуляция "-", символьная скорость -1 или 0, стандарт "-").
|
<strong>Будут обновлены точки с отсутствующими данными:</strong>
|
||||||
|
<ul class="mb-0 mt-2">
|
||||||
|
<li>Модуляция (если "-")</li>
|
||||||
|
<li>Символьная скорость (если -1, 0 или пусто)</li>
|
||||||
|
<li>Стандарт (если "-")</li>
|
||||||
|
<li>Частота (если 0, -1 или пусто)</li>
|
||||||
|
<li>Полоса частот (если 0, -1 или пусто)</li>
|
||||||
|
<li>Поляризация (если "-")</li>
|
||||||
|
<li>Транспондер (если не привязан)</li>
|
||||||
|
<li>Источник LyngSat (если не привязан)</li>
|
||||||
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="mb-3">
|
<div class="mb-3">
|
||||||
|
|||||||
@@ -68,9 +68,12 @@ from .views.source_requests import (
|
|||||||
SourceRequestCreateView,
|
SourceRequestCreateView,
|
||||||
SourceRequestUpdateView,
|
SourceRequestUpdateView,
|
||||||
SourceRequestDeleteView,
|
SourceRequestDeleteView,
|
||||||
|
SourceRequestBulkDeleteView,
|
||||||
|
SourceRequestExportView,
|
||||||
SourceRequestAPIView,
|
SourceRequestAPIView,
|
||||||
SourceRequestDetailAPIView,
|
SourceRequestDetailAPIView,
|
||||||
SourceDataAPIView,
|
SourceDataAPIView,
|
||||||
|
SourceRequestImportView,
|
||||||
)
|
)
|
||||||
from .views.tech_analyze import (
|
from .views.tech_analyze import (
|
||||||
TechAnalyzeEntryView,
|
TechAnalyzeEntryView,
|
||||||
@@ -158,6 +161,9 @@ urlpatterns = [
|
|||||||
path('api/source/<int:source_id>/requests/', SourceRequestAPIView.as_view(), name='source_requests_api'),
|
path('api/source/<int:source_id>/requests/', SourceRequestAPIView.as_view(), name='source_requests_api'),
|
||||||
path('api/source-request/<int:pk>/', SourceRequestDetailAPIView.as_view(), name='source_request_detail_api'),
|
path('api/source-request/<int:pk>/', SourceRequestDetailAPIView.as_view(), name='source_request_detail_api'),
|
||||||
path('api/source/<int:source_id>/data/', SourceDataAPIView.as_view(), name='source_data_api'),
|
path('api/source/<int:source_id>/data/', SourceDataAPIView.as_view(), name='source_data_api'),
|
||||||
|
path('source-requests/import/', SourceRequestImportView.as_view(), name='source_request_import'),
|
||||||
|
path('source-requests/export/', SourceRequestExportView.as_view(), name='source_request_export'),
|
||||||
|
path('source-requests/bulk-delete/', SourceRequestBulkDeleteView.as_view(), name='source_request_bulk_delete'),
|
||||||
path('data-entry/', DataEntryView.as_view(), name='data_entry'),
|
path('data-entry/', DataEntryView.as_view(), name='data_entry'),
|
||||||
path('api/search-objitem/', SearchObjItemAPIView.as_view(), name='search_objitem_api'),
|
path('api/search-objitem/', SearchObjItemAPIView.as_view(), name='search_objitem_api'),
|
||||||
path('tech-analyze/', TechAnalyzeEntryView.as_view(), name='tech_analyze_entry'),
|
path('tech-analyze/', TechAnalyzeEntryView.as_view(), name='tech_analyze_entry'),
|
||||||
|
|||||||
@@ -27,9 +27,14 @@ class KubsatView(LoginRequiredMixin, FormView):
|
|||||||
context['full_width_page'] = True
|
context['full_width_page'] = True
|
||||||
|
|
||||||
# Добавляем данные для вкладки заявок
|
# Добавляем данные для вкладки заявок
|
||||||
from mainapp.models import SourceRequest
|
from mainapp.models import SourceRequest, Satellite
|
||||||
|
|
||||||
|
# Список спутников для формы создания заявки
|
||||||
|
context['satellites'] = Satellite.objects.all().order_by('name')
|
||||||
|
|
||||||
requests_qs = SourceRequest.objects.select_related(
|
requests_qs = SourceRequest.objects.select_related(
|
||||||
'source', 'source__info', 'source__ownership',
|
'source', 'source__info', 'source__ownership',
|
||||||
|
'satellite',
|
||||||
'created_by__user', 'updated_by__user'
|
'created_by__user', 'updated_by__user'
|
||||||
).prefetch_related(
|
).prefetch_related(
|
||||||
'source__source_objitems__parameter_obj__modulation'
|
'source__source_objitems__parameter_obj__modulation'
|
||||||
@@ -72,6 +77,36 @@ class KubsatView(LoginRequiredMixin, FormView):
|
|||||||
requests_list.append(req)
|
requests_list.append(req)
|
||||||
|
|
||||||
context['requests'] = requests_list
|
context['requests'] = requests_list
|
||||||
|
|
||||||
|
# Сериализуем заявки в JSON для Tabulator
|
||||||
|
import json
|
||||||
|
requests_json_data = []
|
||||||
|
for req in requests_list:
|
||||||
|
requests_json_data.append({
|
||||||
|
'id': req.id,
|
||||||
|
'source_id': req.source_id,
|
||||||
|
'satellite_name': req.satellite.name if req.satellite else '-',
|
||||||
|
'status': req.status,
|
||||||
|
'status_display': req.get_status_display(),
|
||||||
|
'priority': req.priority,
|
||||||
|
'priority_display': req.get_priority_display(),
|
||||||
|
'request_date': req.request_date.strftime('%d.%m.%Y') if req.request_date else '-',
|
||||||
|
'card_date': req.card_date.strftime('%d.%m.%Y') if req.card_date else '-',
|
||||||
|
'planned_at': req.planned_at.strftime('%d.%m.%Y %H:%M') if req.planned_at else '-',
|
||||||
|
'downlink': float(req.downlink) if req.downlink else None,
|
||||||
|
'uplink': float(req.uplink) if req.uplink else None,
|
||||||
|
'transfer': float(req.transfer) if req.transfer else None,
|
||||||
|
'coords_lat': float(req.coords.y) if req.coords else None,
|
||||||
|
'coords_lon': float(req.coords.x) if req.coords else None,
|
||||||
|
'region': req.region or '',
|
||||||
|
'gso_success': req.gso_success,
|
||||||
|
'kubsat_success': req.kubsat_success,
|
||||||
|
'coords_source_lat': float(req.coords_source.y) if req.coords_source else None,
|
||||||
|
'coords_source_lon': float(req.coords_source.x) if req.coords_source else None,
|
||||||
|
'comment': req.comment or '',
|
||||||
|
})
|
||||||
|
context['requests_json'] = json.dumps(requests_json_data, ensure_ascii=False)
|
||||||
|
|
||||||
context['status_choices'] = SourceRequest.STATUS_CHOICES
|
context['status_choices'] = SourceRequest.STATUS_CHOICES
|
||||||
context['priority_choices'] = SourceRequest.PRIORITY_CHOICES
|
context['priority_choices'] = SourceRequest.PRIORITY_CHOICES
|
||||||
context['current_status'] = status or ''
|
context['current_status'] = status or ''
|
||||||
|
|||||||
@@ -3,14 +3,20 @@
|
|||||||
"""
|
"""
|
||||||
from django.contrib.auth.mixins import LoginRequiredMixin
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
||||||
from django.http import JsonResponse
|
from django.http import JsonResponse
|
||||||
|
from django.shortcuts import render
|
||||||
from django.views import View
|
from django.views import View
|
||||||
from django.views.generic import ListView, CreateView, UpdateView
|
from django.views.generic import ListView, CreateView, UpdateView
|
||||||
from django.urls import reverse_lazy
|
from django.urls import reverse_lazy
|
||||||
from django.db.models import Q
|
from django.db.models import Q
|
||||||
|
|
||||||
from mainapp.models import SourceRequest, SourceRequestStatusHistory, Source
|
from mainapp.models import SourceRequest, SourceRequestStatusHistory, Source, Satellite
|
||||||
from mainapp.forms import SourceRequestForm
|
from mainapp.forms import SourceRequestForm
|
||||||
|
|
||||||
|
import re
|
||||||
|
import pandas as pd
|
||||||
|
from datetime import datetime
|
||||||
|
from django.contrib.gis.geos import Point
|
||||||
|
|
||||||
|
|
||||||
class SourceRequestListView(LoginRequiredMixin, ListView):
|
class SourceRequestListView(LoginRequiredMixin, ListView):
|
||||||
"""Список заявок на источники."""
|
"""Список заявок на источники."""
|
||||||
@@ -22,6 +28,7 @@ class SourceRequestListView(LoginRequiredMixin, ListView):
|
|||||||
def get_queryset(self):
|
def get_queryset(self):
|
||||||
queryset = SourceRequest.objects.select_related(
|
queryset = SourceRequest.objects.select_related(
|
||||||
'source', 'source__info', 'source__ownership',
|
'source', 'source__info', 'source__ownership',
|
||||||
|
'satellite',
|
||||||
'created_by__user', 'updated_by__user'
|
'created_by__user', 'updated_by__user'
|
||||||
).order_by('-created_at')
|
).order_by('-created_at')
|
||||||
|
|
||||||
@@ -174,6 +181,217 @@ class SourceRequestDeleteView(LoginRequiredMixin, View):
|
|||||||
}, status=404)
|
}, status=404)
|
||||||
|
|
||||||
|
|
||||||
|
class SourceRequestBulkDeleteView(LoginRequiredMixin, View):
|
||||||
|
"""Массовое удаление заявок."""
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
import json
|
||||||
|
try:
|
||||||
|
data = json.loads(request.body)
|
||||||
|
ids = data.get('ids', [])
|
||||||
|
|
||||||
|
if not ids:
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'Не выбраны заявки для удаления'
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
deleted_count, _ = SourceRequest.objects.filter(pk__in=ids).delete()
|
||||||
|
|
||||||
|
return JsonResponse({
|
||||||
|
'success': True,
|
||||||
|
'message': f'Удалено заявок: {deleted_count}',
|
||||||
|
'deleted_count': deleted_count
|
||||||
|
})
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return JsonResponse({
|
||||||
|
'success': False,
|
||||||
|
'error': 'Неверный формат данных'
|
||||||
|
}, status=400)
|
||||||
|
|
||||||
|
|
||||||
|
class SourceRequestExportView(LoginRequiredMixin, View):
|
||||||
|
"""Экспорт заявок в Excel."""
|
||||||
|
|
||||||
|
def get(self, request):
|
||||||
|
from django.http import HttpResponse
|
||||||
|
from openpyxl import Workbook
|
||||||
|
from openpyxl.styles import Font, Alignment, PatternFill
|
||||||
|
from io import BytesIO
|
||||||
|
|
||||||
|
# Получаем заявки с фильтрами
|
||||||
|
queryset = SourceRequest.objects.select_related(
|
||||||
|
'satellite'
|
||||||
|
).order_by('-created_at')
|
||||||
|
|
||||||
|
# Применяем фильтры
|
||||||
|
status = request.GET.get('status')
|
||||||
|
if status:
|
||||||
|
queryset = queryset.filter(status=status)
|
||||||
|
|
||||||
|
priority = request.GET.get('priority')
|
||||||
|
if priority:
|
||||||
|
queryset = queryset.filter(priority=priority)
|
||||||
|
|
||||||
|
gso_success = request.GET.get('gso_success')
|
||||||
|
if gso_success == 'true':
|
||||||
|
queryset = queryset.filter(gso_success=True)
|
||||||
|
elif gso_success == 'false':
|
||||||
|
queryset = queryset.filter(gso_success=False)
|
||||||
|
|
||||||
|
kubsat_success = request.GET.get('kubsat_success')
|
||||||
|
if kubsat_success == 'true':
|
||||||
|
queryset = queryset.filter(kubsat_success=True)
|
||||||
|
elif kubsat_success == 'false':
|
||||||
|
queryset = queryset.filter(kubsat_success=False)
|
||||||
|
|
||||||
|
# Создаём Excel файл
|
||||||
|
wb = Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = "Заявки"
|
||||||
|
|
||||||
|
# Заголовки (как в импорте, но без источника + приоритет + статус + комментарий)
|
||||||
|
headers = [
|
||||||
|
'Дата постановки задачи',
|
||||||
|
'Дата формирования карточки',
|
||||||
|
'Дата проведения',
|
||||||
|
'Спутник',
|
||||||
|
'Частота Downlink',
|
||||||
|
'Частота Uplink',
|
||||||
|
'Перенос',
|
||||||
|
'Координаты ГСО',
|
||||||
|
'Район',
|
||||||
|
'Приоритет',
|
||||||
|
'Статус',
|
||||||
|
'Результат ГСО',
|
||||||
|
'Результат кубсата',
|
||||||
|
'Координаты источника',
|
||||||
|
'Комментарий',
|
||||||
|
]
|
||||||
|
|
||||||
|
# Стили
|
||||||
|
header_font = Font(bold=True)
|
||||||
|
header_fill = PatternFill(start_color="DDDDDD", end_color="DDDDDD", fill_type="solid")
|
||||||
|
green_fill = PatternFill(start_color="90EE90", end_color="90EE90", fill_type="solid")
|
||||||
|
red_fill = PatternFill(start_color="FF6B6B", end_color="FF6B6B", fill_type="solid")
|
||||||
|
gray_fill = PatternFill(start_color="D3D3D3", end_color="D3D3D3", fill_type="solid")
|
||||||
|
|
||||||
|
# Записываем заголовки
|
||||||
|
for col_num, header in enumerate(headers, 1):
|
||||||
|
cell = ws.cell(row=1, column=col_num, value=header)
|
||||||
|
cell.font = header_font
|
||||||
|
cell.fill = header_fill
|
||||||
|
cell.alignment = Alignment(horizontal='center', vertical='center')
|
||||||
|
|
||||||
|
# Записываем данные
|
||||||
|
for row_num, req in enumerate(queryset, 2):
|
||||||
|
# Дата постановки задачи
|
||||||
|
ws.cell(row=row_num, column=1, value=req.request_date.strftime('%d.%m.%Y') if req.request_date else '')
|
||||||
|
|
||||||
|
# Дата формирования карточки
|
||||||
|
ws.cell(row=row_num, column=2, value=req.card_date.strftime('%d.%m.%Y') if req.card_date else '')
|
||||||
|
|
||||||
|
# Дата проведения
|
||||||
|
ws.cell(row=row_num, column=3, value=req.planned_at.strftime('%d.%m.%y %H:%M') if req.planned_at else '')
|
||||||
|
|
||||||
|
# Спутник
|
||||||
|
satellite_str = ''
|
||||||
|
if req.satellite:
|
||||||
|
satellite_str = req.satellite.name
|
||||||
|
if req.satellite.norad:
|
||||||
|
satellite_str += f' ({req.satellite.norad})'
|
||||||
|
ws.cell(row=row_num, column=4, value=satellite_str)
|
||||||
|
|
||||||
|
# Частота Downlink
|
||||||
|
ws.cell(row=row_num, column=5, value=req.downlink if req.downlink else '')
|
||||||
|
|
||||||
|
# Частота Uplink
|
||||||
|
ws.cell(row=row_num, column=6, value=req.uplink if req.uplink else '')
|
||||||
|
|
||||||
|
# Перенос
|
||||||
|
ws.cell(row=row_num, column=7, value=req.transfer if req.transfer else '')
|
||||||
|
|
||||||
|
# Координаты ГСО
|
||||||
|
coords_gso = ''
|
||||||
|
if req.coords:
|
||||||
|
coords_gso = f'{req.coords.y:.6f} {req.coords.x:.6f}'
|
||||||
|
ws.cell(row=row_num, column=8, value=coords_gso)
|
||||||
|
|
||||||
|
# Район
|
||||||
|
ws.cell(row=row_num, column=9, value=req.region or '')
|
||||||
|
|
||||||
|
# Приоритет
|
||||||
|
ws.cell(row=row_num, column=10, value=req.get_priority_display())
|
||||||
|
|
||||||
|
# Статус (с цветом)
|
||||||
|
status_cell = ws.cell(row=row_num, column=11, value=req.get_status_display())
|
||||||
|
if req.status in ['successful', 'result_received']:
|
||||||
|
status_cell.fill = green_fill
|
||||||
|
elif req.status == 'unsuccessful':
|
||||||
|
status_cell.fill = red_fill
|
||||||
|
else:
|
||||||
|
status_cell.fill = gray_fill
|
||||||
|
|
||||||
|
# Результат ГСО (с цветом)
|
||||||
|
gso_cell = ws.cell(row=row_num, column=12)
|
||||||
|
if req.gso_success is True:
|
||||||
|
gso_cell.value = 'Да'
|
||||||
|
gso_cell.fill = green_fill
|
||||||
|
elif req.gso_success is False:
|
||||||
|
gso_cell.value = 'Нет'
|
||||||
|
gso_cell.fill = red_fill
|
||||||
|
else:
|
||||||
|
gso_cell.value = ''
|
||||||
|
|
||||||
|
# Результат кубсата (с цветом)
|
||||||
|
kubsat_cell = ws.cell(row=row_num, column=13)
|
||||||
|
if req.kubsat_success is True:
|
||||||
|
kubsat_cell.value = 'Да'
|
||||||
|
kubsat_cell.fill = green_fill
|
||||||
|
elif req.kubsat_success is False:
|
||||||
|
kubsat_cell.value = 'Нет'
|
||||||
|
kubsat_cell.fill = red_fill
|
||||||
|
else:
|
||||||
|
kubsat_cell.value = ''
|
||||||
|
|
||||||
|
# Координаты источника
|
||||||
|
coords_source = ''
|
||||||
|
if req.coords_source:
|
||||||
|
coords_source = f'{req.coords_source.y:.6f} {req.coords_source.x:.6f}'
|
||||||
|
ws.cell(row=row_num, column=14, value=coords_source)
|
||||||
|
|
||||||
|
# Комментарий
|
||||||
|
ws.cell(row=row_num, column=15, value=req.comment or '')
|
||||||
|
|
||||||
|
# Автоширина колонок
|
||||||
|
for column in ws.columns:
|
||||||
|
max_length = 0
|
||||||
|
column_letter = column[0].column_letter
|
||||||
|
for cell in column:
|
||||||
|
try:
|
||||||
|
if len(str(cell.value)) > max_length:
|
||||||
|
max_length = len(str(cell.value))
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
adjusted_width = min(max_length + 2, 40)
|
||||||
|
ws.column_dimensions[column_letter].width = adjusted_width
|
||||||
|
|
||||||
|
# Сохраняем в BytesIO
|
||||||
|
output = BytesIO()
|
||||||
|
wb.save(output)
|
||||||
|
output.seek(0)
|
||||||
|
|
||||||
|
# Возвращаем файл
|
||||||
|
response = HttpResponse(
|
||||||
|
output.read(),
|
||||||
|
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||||
|
)
|
||||||
|
filename = f'source_requests_{datetime.now().strftime("%Y%m%d_%H%M")}.xlsx'
|
||||||
|
response['Content-Disposition'] = f'attachment; filename="{filename}"'
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
class SourceRequestAPIView(LoginRequiredMixin, View):
|
class SourceRequestAPIView(LoginRequiredMixin, View):
|
||||||
"""API для получения данных о заявках источника."""
|
"""API для получения данных о заявках источника."""
|
||||||
|
|
||||||
@@ -230,6 +448,7 @@ class SourceRequestDetailAPIView(LoginRequiredMixin, View):
|
|||||||
try:
|
try:
|
||||||
req = SourceRequest.objects.select_related(
|
req = SourceRequest.objects.select_related(
|
||||||
'source', 'source__info', 'source__ownership',
|
'source', 'source__info', 'source__ownership',
|
||||||
|
'satellite',
|
||||||
'created_by__user', 'updated_by__user'
|
'created_by__user', 'updated_by__user'
|
||||||
).prefetch_related(
|
).prefetch_related(
|
||||||
'status_history__changed_by__user',
|
'status_history__changed_by__user',
|
||||||
@@ -250,39 +469,59 @@ class SourceRequestDetailAPIView(LoginRequiredMixin, View):
|
|||||||
})
|
})
|
||||||
|
|
||||||
# Получаем данные из первой точки источника (имя, модуляция, символьная скорость)
|
# Получаем данные из первой точки источника (имя, модуляция, символьная скорость)
|
||||||
source_data = _get_source_extra_data(req.source)
|
source_data = _get_source_extra_data(req.source) if req.source else {
|
||||||
|
'objitem_name': '-', 'modulation': '-', 'symbol_rate': '-'
|
||||||
|
}
|
||||||
|
|
||||||
# Координаты из заявки или из источника
|
# Координаты ГСО из заявки или из источника
|
||||||
coords_lat = None
|
coords_lat = None
|
||||||
coords_lon = None
|
coords_lon = None
|
||||||
if req.coords:
|
if req.coords:
|
||||||
coords_lat = req.coords.y
|
coords_lat = req.coords.y
|
||||||
coords_lon = req.coords.x
|
coords_lon = req.coords.x
|
||||||
elif req.source.coords_average:
|
elif req.source and req.source.coords_average:
|
||||||
coords_lat = req.source.coords_average.y
|
coords_lat = req.source.coords_average.y
|
||||||
coords_lon = req.source.coords_average.x
|
coords_lon = req.source.coords_average.x
|
||||||
|
|
||||||
|
# Координаты источника
|
||||||
|
coords_source_lat = None
|
||||||
|
coords_source_lon = None
|
||||||
|
if req.coords_source:
|
||||||
|
coords_source_lat = req.coords_source.y
|
||||||
|
coords_source_lon = req.coords_source.x
|
||||||
|
|
||||||
data = {
|
data = {
|
||||||
'id': req.id,
|
'id': req.id,
|
||||||
'source_id': req.source_id,
|
'source_id': req.source_id,
|
||||||
|
'satellite_id': req.satellite_id,
|
||||||
|
'satellite_name': req.satellite.name if req.satellite else '-',
|
||||||
'status': req.status,
|
'status': req.status,
|
||||||
'status_display': req.get_status_display(),
|
'status_display': req.get_status_display(),
|
||||||
'priority': req.priority,
|
'priority': req.priority,
|
||||||
'priority_display': req.get_priority_display(),
|
'priority_display': req.get_priority_display(),
|
||||||
'planned_at': req.planned_at.isoformat() if req.planned_at else None,
|
'planned_at': req.planned_at.strftime('%Y-%m-%dT%H:%M') if req.planned_at else '',
|
||||||
'planned_at_display': req.planned_at.strftime('%d.%m.%Y %H:%M') if req.planned_at else '-',
|
'planned_at_display': req.planned_at.strftime('%d.%m.%Y %H:%M') if req.planned_at else '-',
|
||||||
'request_date': req.request_date.isoformat() if req.request_date else None,
|
'request_date': req.request_date.isoformat() if req.request_date else None,
|
||||||
'request_date_display': req.request_date.strftime('%d.%m.%Y') if req.request_date else '-',
|
'request_date_display': req.request_date.strftime('%d.%m.%Y') if req.request_date else '-',
|
||||||
|
'card_date': req.card_date.isoformat() if req.card_date else None,
|
||||||
|
'card_date_display': req.card_date.strftime('%d.%m.%Y') if req.card_date else '-',
|
||||||
'status_updated_at': req.status_updated_at.strftime('%d.%m.%Y %H:%M') if req.status_updated_at else '-',
|
'status_updated_at': req.status_updated_at.strftime('%d.%m.%Y %H:%M') if req.status_updated_at else '-',
|
||||||
|
'downlink': req.downlink,
|
||||||
|
'uplink': req.uplink,
|
||||||
|
'transfer': req.transfer,
|
||||||
|
'region': req.region or '',
|
||||||
'gso_success': req.gso_success,
|
'gso_success': req.gso_success,
|
||||||
'kubsat_success': req.kubsat_success,
|
'kubsat_success': req.kubsat_success,
|
||||||
'comment': req.comment or '',
|
'comment': req.comment or '',
|
||||||
'created_at': req.created_at.strftime('%d.%m.%Y %H:%M') if req.created_at else '-',
|
'created_at': req.created_at.strftime('%d.%m.%Y %H:%M') if req.created_at else '-',
|
||||||
'created_by': str(req.created_by) if req.created_by else '-',
|
'created_by': str(req.created_by) if req.created_by else '-',
|
||||||
'history': history,
|
'history': history,
|
||||||
# Дополнительные данные
|
# Координаты ГСО
|
||||||
'coords_lat': coords_lat,
|
'coords_lat': coords_lat,
|
||||||
'coords_lon': coords_lon,
|
'coords_lon': coords_lon,
|
||||||
|
# Координаты источника
|
||||||
|
'coords_source_lat': coords_source_lat,
|
||||||
|
'coords_source_lon': coords_source_lon,
|
||||||
'points_count': req.points_count,
|
'points_count': req.points_count,
|
||||||
'objitem_name': source_data['objitem_name'],
|
'objitem_name': source_data['objitem_name'],
|
||||||
'modulation': source_data['modulation'],
|
'modulation': source_data['modulation'],
|
||||||
@@ -321,15 +560,16 @@ def _get_source_extra_data(source):
|
|||||||
|
|
||||||
|
|
||||||
class SourceDataAPIView(LoginRequiredMixin, View):
|
class SourceDataAPIView(LoginRequiredMixin, View):
|
||||||
"""API для получения данных источника (координаты, имя точки, модуляция, символьная скорость)."""
|
"""API для получения данных источника (координаты, имя точки, модуляция, символьная скорость, транспондер)."""
|
||||||
|
|
||||||
def get(self, request, source_id):
|
def get(self, request, source_id):
|
||||||
from mainapp.utils import calculate_mean_coords
|
from mainapp.utils import calculate_mean_coords
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
source = Source.objects.select_related('info', 'ownership').prefetch_related(
|
source = Source.objects.select_related('info', 'ownership').prefetch_related(
|
||||||
'source_objitems__parameter_obj__modulation',
|
'source_objitems__parameter_obj__modulation',
|
||||||
|
'source_objitems__parameter_obj__id_satellite',
|
||||||
|
'source_objitems__transponder__sat_id',
|
||||||
'source_objitems__geo_obj'
|
'source_objitems__geo_obj'
|
||||||
).get(pk=source_id)
|
).get(pk=source_id)
|
||||||
except Source.DoesNotExist:
|
except Source.DoesNotExist:
|
||||||
@@ -339,10 +579,18 @@ class SourceDataAPIView(LoginRequiredMixin, View):
|
|||||||
source_data = _get_source_extra_data(source)
|
source_data = _get_source_extra_data(source)
|
||||||
|
|
||||||
# Рассчитываем усреднённые координаты из всех точек (сортируем по дате ГЛ)
|
# Рассчитываем усреднённые координаты из всех точек (сортируем по дате ГЛ)
|
||||||
objitems = source.source_objitems.select_related('geo_obj').order_by('geo_obj__timestamp')
|
objitems = source.source_objitems.select_related('geo_obj', 'transponder', 'transponder__sat_id').order_by('geo_obj__timestamp')
|
||||||
|
|
||||||
avg_coords = None
|
avg_coords = None
|
||||||
points_count = 0
|
points_count = 0
|
||||||
|
|
||||||
|
# Данные из транспондера
|
||||||
|
downlink = None
|
||||||
|
uplink = None
|
||||||
|
transfer = None
|
||||||
|
satellite_id = None
|
||||||
|
satellite_name = None
|
||||||
|
|
||||||
for objitem in objitems:
|
for objitem in objitems:
|
||||||
if hasattr(objitem, 'geo_obj') and objitem.geo_obj and objitem.geo_obj.coords:
|
if hasattr(objitem, 'geo_obj') and objitem.geo_obj and objitem.geo_obj.coords:
|
||||||
coord = (float(objitem.geo_obj.coords.x), float(objitem.geo_obj.coords.y))
|
coord = (float(objitem.geo_obj.coords.x), float(objitem.geo_obj.coords.y))
|
||||||
@@ -352,6 +600,24 @@ class SourceDataAPIView(LoginRequiredMixin, View):
|
|||||||
else:
|
else:
|
||||||
avg_coords, _ = calculate_mean_coords(avg_coords, coord)
|
avg_coords, _ = calculate_mean_coords(avg_coords, coord)
|
||||||
|
|
||||||
|
# Берём данные из первого транспондера
|
||||||
|
if downlink is None and objitem.transponder:
|
||||||
|
transponder = objitem.transponder
|
||||||
|
downlink = transponder.downlink
|
||||||
|
uplink = transponder.uplink
|
||||||
|
transfer = transponder.transfer
|
||||||
|
if transponder.sat_id:
|
||||||
|
satellite_id = transponder.sat_id.pk
|
||||||
|
satellite_name = transponder.sat_id.name
|
||||||
|
|
||||||
|
# Если нет данных из транспондера, пробуем из параметров
|
||||||
|
if satellite_id is None:
|
||||||
|
for objitem in objitems:
|
||||||
|
if objitem.parameter_obj and objitem.parameter_obj.id_satellite:
|
||||||
|
satellite_id = objitem.parameter_obj.id_satellite.pk
|
||||||
|
satellite_name = objitem.parameter_obj.id_satellite.name
|
||||||
|
break
|
||||||
|
|
||||||
# Если нет координат из точек, берём из источника
|
# Если нет координат из точек, берём из источника
|
||||||
coords_lat = None
|
coords_lat = None
|
||||||
coords_lon = None
|
coords_lon = None
|
||||||
@@ -373,6 +639,359 @@ class SourceDataAPIView(LoginRequiredMixin, View):
|
|||||||
'symbol_rate': source_data['symbol_rate'],
|
'symbol_rate': source_data['symbol_rate'],
|
||||||
'info': source.info.name if source.info else '-',
|
'info': source.info.name if source.info else '-',
|
||||||
'ownership': source.ownership.name if source.ownership else '-',
|
'ownership': source.ownership.name if source.ownership else '-',
|
||||||
|
# Данные из транспондера
|
||||||
|
'downlink': downlink,
|
||||||
|
'uplink': uplink,
|
||||||
|
'transfer': transfer,
|
||||||
|
'satellite_id': satellite_id,
|
||||||
|
'satellite_name': satellite_name,
|
||||||
}
|
}
|
||||||
|
|
||||||
return JsonResponse(data)
|
return JsonResponse(data)
|
||||||
|
|
||||||
|
|
||||||
|
class SourceRequestImportView(LoginRequiredMixin, View):
|
||||||
|
"""Импорт заявок из Excel файла."""
|
||||||
|
|
||||||
|
def get(self, request):
|
||||||
|
"""Отображает форму загрузки файла."""
|
||||||
|
return render(request, 'mainapp/source_request_import.html')
|
||||||
|
|
||||||
|
def post(self, request):
|
||||||
|
"""Обрабатывает загруженный Excel файл."""
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
from openpyxl.styles import PatternFill
|
||||||
|
|
||||||
|
if 'file' not in request.FILES:
|
||||||
|
return JsonResponse({'success': False, 'error': 'Файл не загружен'}, status=400)
|
||||||
|
|
||||||
|
file = request.FILES['file']
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Читаем Excel файл с openpyxl для доступа к цветам
|
||||||
|
wb = load_workbook(file, data_only=True)
|
||||||
|
ws = wb.worksheets[0]
|
||||||
|
|
||||||
|
# Получаем заголовки (очищаем от пробелов)
|
||||||
|
headers = []
|
||||||
|
for cell in ws[1]:
|
||||||
|
val = cell.value
|
||||||
|
if val:
|
||||||
|
headers.append(str(val).strip())
|
||||||
|
else:
|
||||||
|
headers.append(None)
|
||||||
|
|
||||||
|
# Находим индекс столбца "Результат кубсата"
|
||||||
|
kubsat_col_idx = None
|
||||||
|
for i, h in enumerate(headers):
|
||||||
|
if h and 'кубсат' in h.lower():
|
||||||
|
kubsat_col_idx = i
|
||||||
|
break
|
||||||
|
|
||||||
|
results = {
|
||||||
|
'created': 0,
|
||||||
|
'errors': [],
|
||||||
|
'skipped': 0,
|
||||||
|
'headers': [h for h in headers if h], # Для отладки
|
||||||
|
}
|
||||||
|
|
||||||
|
custom_user = getattr(request.user, 'customuser', None)
|
||||||
|
|
||||||
|
# Обрабатываем строки начиная со второй (первая - заголовки)
|
||||||
|
for row_idx, row in enumerate(ws.iter_rows(min_row=2, values_only=False), start=2):
|
||||||
|
try:
|
||||||
|
# Получаем значения
|
||||||
|
row_values = {headers[i]: cell.value for i, cell in enumerate(row) if i < len(headers)}
|
||||||
|
|
||||||
|
# Получаем цвет ячейки "Результат кубсата"
|
||||||
|
kubsat_is_red = False
|
||||||
|
kubsat_value = None
|
||||||
|
if kubsat_col_idx is not None and kubsat_col_idx < len(row):
|
||||||
|
kubsat_cell = row[kubsat_col_idx]
|
||||||
|
kubsat_value = kubsat_cell.value
|
||||||
|
# Проверяем цвет заливки
|
||||||
|
if kubsat_cell.fill and kubsat_cell.fill.fgColor:
|
||||||
|
color = kubsat_cell.fill.fgColor
|
||||||
|
if color.type == 'rgb' and color.rgb:
|
||||||
|
# Красный цвет: FF0000 или близкие оттенки
|
||||||
|
rgb = color.rgb
|
||||||
|
if isinstance(rgb, str) and len(rgb) >= 6:
|
||||||
|
# Убираем альфа-канал если есть
|
||||||
|
rgb = rgb[-6:]
|
||||||
|
r = int(rgb[0:2], 16)
|
||||||
|
g = int(rgb[2:4], 16)
|
||||||
|
b = int(rgb[4:6], 16)
|
||||||
|
# Считаем красным если R > 200 и G < 100 и B < 100
|
||||||
|
if r > 180 and g < 120 and b < 120:
|
||||||
|
kubsat_is_red = True
|
||||||
|
|
||||||
|
self._process_row(row_values, row_idx, results, custom_user, kubsat_is_red, kubsat_value)
|
||||||
|
except Exception as e:
|
||||||
|
results['errors'].append(f"Строка {row_idx}: {str(e)}")
|
||||||
|
|
||||||
|
return JsonResponse({
|
||||||
|
'success': True,
|
||||||
|
'created': results['created'],
|
||||||
|
'skipped': results['skipped'],
|
||||||
|
'errors': results['errors'][:20],
|
||||||
|
'total_errors': len(results['errors']),
|
||||||
|
'headers': results.get('headers', [])[:15], # Для отладки
|
||||||
|
})
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
return JsonResponse({'success': False, 'error': f'Ошибка чтения файла: {str(e)}'}, status=400)
|
||||||
|
|
||||||
|
def _process_row(self, row, row_idx, results, custom_user, kubsat_is_red=False, kubsat_value=None):
|
||||||
|
"""Обрабатывает одну строку из Excel."""
|
||||||
|
# Пропускаем полностью пустые строки (все значения None или пустые)
|
||||||
|
has_any_data = any(v for v in row.values() if v is not None and str(v).strip())
|
||||||
|
if not has_any_data:
|
||||||
|
results['skipped'] += 1
|
||||||
|
return
|
||||||
|
|
||||||
|
# Парсим дату заявки (Дата постановки задачи)
|
||||||
|
request_date = self._parse_date(row.get('Дата постановки задачи'))
|
||||||
|
|
||||||
|
# Парсим дату формирования карточки
|
||||||
|
card_date = self._parse_date(row.get('Дата формирования карточки'))
|
||||||
|
|
||||||
|
# Парсим дату и время планирования (Дата проведения)
|
||||||
|
planned_at = self._parse_datetime(row.get('Дата проведения'))
|
||||||
|
|
||||||
|
# Ищем спутник по NORAD
|
||||||
|
satellite = self._find_satellite(row.get('Спутник'))
|
||||||
|
|
||||||
|
# Парсим частоты
|
||||||
|
downlink = self._parse_float(row.get('Частота Downlink'))
|
||||||
|
uplink = self._parse_float(row.get('Частота Uplink'))
|
||||||
|
transfer = self._parse_float(row.get('Перенос'))
|
||||||
|
|
||||||
|
# Парсим координаты ГСО
|
||||||
|
coords = self._parse_coords(row.get('Координаты ГСО'))
|
||||||
|
|
||||||
|
# Район
|
||||||
|
region = str(row.get('Район', '')).strip() if row.get('Район') else None
|
||||||
|
|
||||||
|
# Результат ГСО
|
||||||
|
gso_result = row.get('Результат ГСО')
|
||||||
|
gso_success = None
|
||||||
|
comment_parts = []
|
||||||
|
|
||||||
|
if gso_result:
|
||||||
|
gso_str = str(gso_result).strip().lower()
|
||||||
|
if gso_str in ('успешно', 'да', 'true', '1'):
|
||||||
|
gso_success = True
|
||||||
|
else:
|
||||||
|
gso_success = False
|
||||||
|
comment_parts.append(f"Результат ГСО: {str(gso_result).strip()}")
|
||||||
|
|
||||||
|
# Результат кубсата - по цвету ячейки
|
||||||
|
kubsat_success = None
|
||||||
|
if kubsat_is_red:
|
||||||
|
kubsat_success = False
|
||||||
|
elif kubsat_value:
|
||||||
|
kubsat_success = True
|
||||||
|
|
||||||
|
# Добавляем значение кубсата в комментарий
|
||||||
|
if kubsat_value:
|
||||||
|
comment_parts.append(f"Результат кубсата: {str(kubsat_value).strip()}")
|
||||||
|
|
||||||
|
# Координаты источника
|
||||||
|
coords_source = self._parse_coords(row.get('Координаты источника'))
|
||||||
|
|
||||||
|
# Определяем статус по логике:
|
||||||
|
# - если есть координата источника -> result_received
|
||||||
|
# - если нет координаты источника, но ГСО успешно -> successful
|
||||||
|
# - если нет координаты источника и ГСО не успешно -> unsuccessful
|
||||||
|
status = 'planned'
|
||||||
|
if coords_source:
|
||||||
|
status = 'result_received'
|
||||||
|
elif gso_success is True:
|
||||||
|
status = 'successful'
|
||||||
|
elif gso_success is False:
|
||||||
|
status = 'unsuccessful'
|
||||||
|
|
||||||
|
# Собираем комментарий
|
||||||
|
comment = '; '.join(comment_parts) if comment_parts else None
|
||||||
|
|
||||||
|
# Создаём заявку
|
||||||
|
source_request = SourceRequest(
|
||||||
|
source=None,
|
||||||
|
satellite=satellite,
|
||||||
|
status=status,
|
||||||
|
priority='medium',
|
||||||
|
request_date=request_date,
|
||||||
|
card_date=card_date,
|
||||||
|
planned_at=planned_at,
|
||||||
|
downlink=downlink,
|
||||||
|
uplink=uplink,
|
||||||
|
transfer=transfer,
|
||||||
|
region=region,
|
||||||
|
gso_success=gso_success,
|
||||||
|
kubsat_success=kubsat_success,
|
||||||
|
comment=comment,
|
||||||
|
created_by=custom_user,
|
||||||
|
updated_by=custom_user,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Устанавливаем координаты
|
||||||
|
if coords:
|
||||||
|
source_request.coords = Point(coords[1], coords[0], srid=4326)
|
||||||
|
|
||||||
|
if coords_source:
|
||||||
|
source_request.coords_source = Point(coords_source[1], coords_source[0], srid=4326)
|
||||||
|
|
||||||
|
source_request.save()
|
||||||
|
|
||||||
|
# Создаём начальную запись в истории
|
||||||
|
SourceRequestStatusHistory.objects.create(
|
||||||
|
source_request=source_request,
|
||||||
|
old_status='',
|
||||||
|
new_status=source_request.status,
|
||||||
|
changed_by=custom_user,
|
||||||
|
)
|
||||||
|
|
||||||
|
results['created'] += 1
|
||||||
|
|
||||||
|
def _parse_date(self, value):
|
||||||
|
"""Парсит дату из различных форматов."""
|
||||||
|
if pd.isna(value):
|
||||||
|
return None
|
||||||
|
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.date()
|
||||||
|
|
||||||
|
value_str = str(value).strip()
|
||||||
|
|
||||||
|
# Пробуем разные форматы
|
||||||
|
formats = ['%d.%m.%Y', '%d.%m.%y', '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y']
|
||||||
|
for fmt in formats:
|
||||||
|
try:
|
||||||
|
return datetime.strptime(value_str, fmt).date()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _parse_datetime(self, value):
|
||||||
|
"""Парсит дату и время из различных форматов."""
|
||||||
|
if pd.isna(value):
|
||||||
|
return None
|
||||||
|
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value
|
||||||
|
|
||||||
|
value_str = str(value).strip()
|
||||||
|
|
||||||
|
# Пробуем разные форматы
|
||||||
|
formats = [
|
||||||
|
'%d.%m.%y %H:%M', '%d.%m.%Y %H:%M', '%d.%m.%y %H:%M:%S', '%d.%m.%Y %H:%M:%S',
|
||||||
|
'%Y-%m-%d %H:%M', '%Y-%m-%d %H:%M:%S', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M'
|
||||||
|
]
|
||||||
|
for fmt in formats:
|
||||||
|
try:
|
||||||
|
return datetime.strptime(value_str, fmt)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _find_satellite(self, value):
|
||||||
|
"""Ищет спутник по названию с NORAD в скобках."""
|
||||||
|
if pd.isna(value):
|
||||||
|
return None
|
||||||
|
|
||||||
|
value_str = str(value).strip()
|
||||||
|
|
||||||
|
# Ищем NORAD в скобках: "NSS 12 (36032)"
|
||||||
|
match = re.search(r'\((\d+)\)', value_str)
|
||||||
|
if match:
|
||||||
|
norad = int(match.group(1))
|
||||||
|
try:
|
||||||
|
return Satellite.objects.get(norad=norad)
|
||||||
|
except Satellite.DoesNotExist:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Пробуем найти по имени
|
||||||
|
name = re.sub(r'\s*\(\d+\)\s*', '', value_str).strip()
|
||||||
|
if name:
|
||||||
|
satellite = Satellite.objects.filter(name__icontains=name).first()
|
||||||
|
if satellite:
|
||||||
|
return satellite
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _parse_float(self, value):
|
||||||
|
"""Парсит число с плавающей точкой."""
|
||||||
|
if pd.isna(value):
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Заменяем запятую на точку
|
||||||
|
value_str = str(value).replace(',', '.').strip()
|
||||||
|
return float(value_str)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _parse_coords(self, value):
|
||||||
|
"""Парсит координаты из строки. Возвращает (lat, lon) или None.
|
||||||
|
|
||||||
|
Поддерживаемые форматы:
|
||||||
|
- "24.920695 46.733201" (точка как десятичный разделитель, пробел между координатами)
|
||||||
|
- "24,920695 46,733201" (запятая как десятичный разделитель, пробел между координатами)
|
||||||
|
- "24.920695, 46.733201" (точка как десятичный разделитель, запятая+пробел между координатами)
|
||||||
|
- "21.763585. 39.158290" (точка с пробелом между координатами)
|
||||||
|
"""
|
||||||
|
if pd.isna(value):
|
||||||
|
return None
|
||||||
|
|
||||||
|
value_str = str(value).strip()
|
||||||
|
if not value_str:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Формат "21.763585. 39.158290" - точка с пробелом как разделитель координат
|
||||||
|
if re.search(r'\.\s+', value_str):
|
||||||
|
parts = re.split(r'\.\s+', value_str)
|
||||||
|
if len(parts) >= 2:
|
||||||
|
try:
|
||||||
|
lat = float(parts[0].replace(',', '.'))
|
||||||
|
lon = float(parts[1].replace(',', '.'))
|
||||||
|
return (lat, lon)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Формат "24.920695, 46.733201" - запятая с пробелом как разделитель координат
|
||||||
|
if ', ' in value_str:
|
||||||
|
parts = value_str.split(', ')
|
||||||
|
if len(parts) >= 2:
|
||||||
|
try:
|
||||||
|
lat = float(parts[0].replace(',', '.'))
|
||||||
|
lon = float(parts[1].replace(',', '.'))
|
||||||
|
return (lat, lon)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Формат "24,920695 46,733201" или "24.920695 46.733201" - пробел как разделитель координат
|
||||||
|
# Сначала разбиваем по пробелам
|
||||||
|
parts = value_str.split()
|
||||||
|
if len(parts) >= 2:
|
||||||
|
try:
|
||||||
|
# Заменяем запятую на точку в каждой части отдельно
|
||||||
|
lat = float(parts[0].replace(',', '.'))
|
||||||
|
lon = float(parts[1].replace(',', '.'))
|
||||||
|
return (lat, lon)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Формат "24.920695;46.733201" - точка с запятой как разделитель
|
||||||
|
if ';' in value_str:
|
||||||
|
parts = value_str.split(';')
|
||||||
|
if len(parts) >= 2:
|
||||||
|
try:
|
||||||
|
lat = float(parts[0].strip().replace(',', '.'))
|
||||||
|
lon = float(parts[1].strip().replace(',', '.'))
|
||||||
|
return (lat, lon)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
return None
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ from ..models import (
|
|||||||
Parameter,
|
Parameter,
|
||||||
)
|
)
|
||||||
from ..mixins import RoleRequiredMixin
|
from ..mixins import RoleRequiredMixin
|
||||||
from ..utils import parse_pagination_params
|
from ..utils import parse_pagination_params, find_matching_transponder, find_matching_lyngsat
|
||||||
|
|
||||||
|
|
||||||
class TechAnalyzeEntryView(LoginRequiredMixin, View):
|
class TechAnalyzeEntryView(LoginRequiredMixin, View):
|
||||||
@@ -190,6 +190,9 @@ class LinkExistingPointsView(LoginRequiredMixin, View):
|
|||||||
* Обновить модуляцию (если "-")
|
* Обновить модуляцию (если "-")
|
||||||
* Обновить символьную скорость (если -1.0 или None)
|
* Обновить символьную скорость (если -1.0 или None)
|
||||||
* Обновить стандарт (если "-")
|
* Обновить стандарт (если "-")
|
||||||
|
* Обновить частоту (если 0 или None)
|
||||||
|
* Обновить полосу частот (если 0 или None)
|
||||||
|
* Подобрать подходящий транспондер
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def post(self, request):
|
def post(self, request):
|
||||||
@@ -214,7 +217,7 @@ class LinkExistingPointsView(LoginRequiredMixin, View):
|
|||||||
# Получаем все ObjItem для данного спутника
|
# Получаем все ObjItem для данного спутника
|
||||||
objitems = ObjItem.objects.filter(
|
objitems = ObjItem.objects.filter(
|
||||||
parameter_obj__id_satellite=satellite
|
parameter_obj__id_satellite=satellite
|
||||||
).select_related('parameter_obj', 'parameter_obj__modulation', 'parameter_obj__standard')
|
).select_related('parameter_obj', 'parameter_obj__modulation', 'parameter_obj__standard', 'parameter_obj__polarization')
|
||||||
|
|
||||||
updated_count = 0
|
updated_count = 0
|
||||||
skipped_count = 0
|
skipped_count = 0
|
||||||
@@ -236,7 +239,14 @@ class LinkExistingPointsView(LoginRequiredMixin, View):
|
|||||||
parameter.bod_velocity is None or
|
parameter.bod_velocity is None or
|
||||||
parameter.bod_velocity == -1.0 or
|
parameter.bod_velocity == -1.0 or
|
||||||
parameter.bod_velocity == 0 or
|
parameter.bod_velocity == 0 or
|
||||||
(parameter.standard and parameter.standard.name == "-")
|
(parameter.standard and parameter.standard.name == "-") or
|
||||||
|
parameter.frequency is None or
|
||||||
|
parameter.frequency == 0 or
|
||||||
|
parameter.frequency == -1.0 or
|
||||||
|
parameter.freq_range is None or
|
||||||
|
parameter.freq_range == 0 or
|
||||||
|
parameter.freq_range == -1.0 or
|
||||||
|
objitem.transponder is None
|
||||||
)
|
)
|
||||||
|
|
||||||
if not needs_update:
|
if not needs_update:
|
||||||
@@ -247,7 +257,7 @@ class LinkExistingPointsView(LoginRequiredMixin, View):
|
|||||||
tech_analyze = TechAnalyze.objects.filter(
|
tech_analyze = TechAnalyze.objects.filter(
|
||||||
name=source_name,
|
name=source_name,
|
||||||
satellite=satellite
|
satellite=satellite
|
||||||
).select_related('modulation', 'standard').first()
|
).select_related('modulation', 'standard', 'polarization').first()
|
||||||
|
|
||||||
if not tech_analyze:
|
if not tech_analyze:
|
||||||
skipped_count += 1
|
skipped_count += 1
|
||||||
@@ -272,8 +282,55 @@ class LinkExistingPointsView(LoginRequiredMixin, View):
|
|||||||
parameter.standard = tech_analyze.standard
|
parameter.standard = tech_analyze.standard
|
||||||
updated = True
|
updated = True
|
||||||
|
|
||||||
|
# Обновляем частоту
|
||||||
|
if (parameter.frequency is None or parameter.frequency == 0 or parameter.frequency == -1.0) and \
|
||||||
|
tech_analyze.frequency and tech_analyze.frequency > 0:
|
||||||
|
parameter.frequency = tech_analyze.frequency
|
||||||
|
updated = True
|
||||||
|
|
||||||
|
# Обновляем полосу частот
|
||||||
|
if (parameter.freq_range is None or parameter.freq_range == 0 or parameter.freq_range == -1.0) and \
|
||||||
|
tech_analyze.freq_range and tech_analyze.freq_range > 0:
|
||||||
|
parameter.freq_range = tech_analyze.freq_range
|
||||||
|
updated = True
|
||||||
|
|
||||||
|
# Обновляем поляризацию если нужно
|
||||||
|
if parameter.polarization and parameter.polarization.name == "-" and tech_analyze.polarization:
|
||||||
|
parameter.polarization = tech_analyze.polarization
|
||||||
|
updated = True
|
||||||
|
|
||||||
|
# Сохраняем parameter перед поиском транспондера (чтобы использовать обновленные данные)
|
||||||
if updated:
|
if updated:
|
||||||
parameter.save()
|
parameter.save()
|
||||||
|
|
||||||
|
# Подбираем транспондер если его нет (используем функцию из utils)
|
||||||
|
if objitem.transponder is None and parameter.frequency and parameter.frequency > 0:
|
||||||
|
transponder = find_matching_transponder(
|
||||||
|
satellite,
|
||||||
|
parameter.frequency,
|
||||||
|
parameter.polarization
|
||||||
|
)
|
||||||
|
if transponder:
|
||||||
|
objitem.transponder = transponder
|
||||||
|
updated = True
|
||||||
|
|
||||||
|
# Подбираем источник LyngSat если его нет (используем функцию из utils)
|
||||||
|
if objitem.lyngsat_source is None and parameter.frequency and parameter.frequency > 0:
|
||||||
|
lyngsat_source = find_matching_lyngsat(
|
||||||
|
satellite,
|
||||||
|
parameter.frequency,
|
||||||
|
parameter.polarization,
|
||||||
|
tolerance_mhz=0.1
|
||||||
|
)
|
||||||
|
if lyngsat_source:
|
||||||
|
objitem.lyngsat_source = lyngsat_source
|
||||||
|
updated = True
|
||||||
|
|
||||||
|
# Сохраняем objitem если были изменения транспондера или lyngsat
|
||||||
|
if objitem.transponder or objitem.lyngsat_source:
|
||||||
|
objitem.save()
|
||||||
|
|
||||||
|
if updated:
|
||||||
updated_count += 1
|
updated_count += 1
|
||||||
else:
|
else:
|
||||||
skipped_count += 1
|
skipped_count += 1
|
||||||
@@ -305,7 +362,6 @@ class LinkExistingPointsView(LoginRequiredMixin, View):
|
|||||||
}, status=500)
|
}, status=500)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class TechAnalyzeListView(LoginRequiredMixin, View):
|
class TechAnalyzeListView(LoginRequiredMixin, View):
|
||||||
"""
|
"""
|
||||||
Представление для отображения списка данных технического анализа.
|
Представление для отображения списка данных технического анализа.
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ services:
|
|||||||
- ./logs:/app/logs
|
- ./logs:/app/logs
|
||||||
expose:
|
expose:
|
||||||
- 8000
|
- 8000
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
worker:
|
worker:
|
||||||
# build:
|
# build:
|
||||||
@@ -29,12 +31,16 @@ services:
|
|||||||
volumes:
|
volumes:
|
||||||
- ./logs:/app/logs
|
- ./logs:/app/logs
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:7-alpine
|
image: redis:7-alpine
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
ports:
|
ports:
|
||||||
- 6379:6379
|
- 6379:6379
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
db:
|
db:
|
||||||
image: postgis/postgis:18-3.6
|
image: postgis/postgis:18-3.6
|
||||||
@@ -46,18 +52,21 @@ services:
|
|||||||
- 5432:5432
|
- 5432:5432
|
||||||
volumes:
|
volumes:
|
||||||
- pgdata:/var/lib/postgresql
|
- pgdata:/var/lib/postgresql
|
||||||
# networks:
|
networks:
|
||||||
# - app-network
|
- app-network
|
||||||
|
|
||||||
nginx:
|
nginx:
|
||||||
image: nginx:alpine
|
image: nginx:alpine
|
||||||
depends_on:
|
depends_on:
|
||||||
- web
|
- web
|
||||||
|
- tileserver
|
||||||
ports:
|
ports:
|
||||||
- 8080:80
|
- 8080:80
|
||||||
volumes:
|
volumes:
|
||||||
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||||
- static_volume:/usr/share/nginx/html/static
|
- static_volume:/usr/share/nginx/html/static
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
flaresolverr:
|
flaresolverr:
|
||||||
image: ghcr.io/flaresolverr/flaresolverr:latest
|
image: ghcr.io/flaresolverr/flaresolverr:latest
|
||||||
@@ -69,6 +78,8 @@ services:
|
|||||||
- LOG_LEVEL=info
|
- LOG_LEVEL=info
|
||||||
- LOG_HTML=false
|
- LOG_HTML=false
|
||||||
- CAPTCHA_SOLVER=none
|
- CAPTCHA_SOLVER=none
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
tileserver:
|
tileserver:
|
||||||
image: maptiler/tileserver-gl:latest
|
image: maptiler/tileserver-gl:latest
|
||||||
@@ -77,13 +88,20 @@ services:
|
|||||||
ports:
|
ports:
|
||||||
- "8090:8080"
|
- "8090:8080"
|
||||||
volumes:
|
volumes:
|
||||||
- ./tileserver_data:/data
|
# - ./tileserver_data:/data
|
||||||
|
- /mnt/c/Users/I/Documents/TileServer:/data
|
||||||
- tileserver_config:/config
|
- tileserver_config:/config
|
||||||
environment:
|
environment:
|
||||||
- VERBOSE=true
|
- VERBOSE=true
|
||||||
- CORS_ENABLED=true
|
- CORS_ENABLED=true
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
pgdata:
|
pgdata:
|
||||||
static_volume:
|
static_volume:
|
||||||
tileserver_config
|
tileserver_config:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
app-network:
|
||||||
|
driver: bridge
|
||||||
Reference in New Issue
Block a user